Godot Engine – Multi-platform 2D and 3D game engine
Updated to Jolt Physics 5.6.0
Jorrit Rouweb3db140c6cf2
diff --git a/modules/jolt_physics/jolt_globals.cpp b/modules/jolt_physics/jolt_globals.cppindex 76dcf17ba5c..fb9b4d780a0 100644--- a/modules/jolt_physics/jolt_globals.cpp+++ b/modules/jolt_physics/jolt_globals.cpp@@ -43,6 +43,7 @@#include <Jolt/Jolt.h>+#include <Jolt/Core/Factory.h>#include <Jolt/RegisterTypes.h>#include <cstdarg>diff --git a/modules/jolt_physics/spaces/jolt_contact_listener_3d.cpp b/modules/jolt_physics/spaces/jolt_contact_listener_3d.cppindex 68377a0031d..b594e348f51 100644--- a/modules/jolt_physics/spaces/jolt_contact_listener_3d.cpp+++ b/modules/jolt_physics/spaces/jolt_contact_listener_3d.cpp@@ -211,6 +211,9 @@ bool JoltContactListener3D::_try_add_contacts(const JPH::Body &p_jolt_body1, conJPH::CollisionEstimationResult collision;JPH::EstimateCollisionResponse(p_jolt_body1, p_jolt_body2, p_manifold, collision, p_settings.mCombinedFriction, p_settings.mCombinedRestitution, JoltProjectSettings::bounce_velocity_threshold, 5);+ const JPH::Vec3 friction_impulse1 = contact_count > 0 ? (collision.mTangent1 * collision.mFrictionImpulse1) / contact_count : JPH::Vec3::sZero();+ const JPH::Vec3 friction_impulse2 = contact_count > 0 ? (collision.mTangent2 * collision.mFrictionImpulse2) / contact_count : JPH::Vec3::sZero();+for (JPH::uint i = 0; i < contact_count; ++i) {const JPH::RVec3 relative_point1 = JPH::RVec3(p_manifold.mRelativeContactPointsOn1[i]);const JPH::RVec3 relative_point2 = JPH::RVec3(p_manifold.mRelativeContactPointsOn2[i]);@@ -221,11 +224,7 @@ bool JoltContactListener3D::_try_add_contacts(const JPH::Body &p_jolt_body1, conconst JPH::Vec3 velocity1 = p_jolt_body1.GetPointVelocity(world_point1);const JPH::Vec3 velocity2 = p_jolt_body2.GetPointVelocity(world_point2);- const JPH::CollisionEstimationResult::Impulse &impulse = collision.mImpulses[i];-- const JPH::Vec3 contact_impulse = p_manifold.mWorldSpaceNormal * impulse.mContactImpulse;- const JPH::Vec3 friction_impulse1 = collision.mTangent1 * impulse.mFrictionImpulse1;- const JPH::Vec3 friction_impulse2 = collision.mTangent2 * impulse.mFrictionImpulse2;+ const JPH::Vec3 contact_impulse = p_manifold.mWorldSpaceNormal * collision.mContactImpulse[i];const JPH::Vec3 combined_impulse = contact_impulse + friction_impulse1 + friction_impulse2;Contact contact1;diff --git a/thirdparty/README.md b/thirdparty/README.mdindex 9cd7adf08e6..954db2061f2 100644--- a/thirdparty/README.md+++ b/thirdparty/README.md@@ -511,23 +511,14 @@ Files generated from upstream source:## jolt_physics- Upstream: https://github.com/jrouwe/JoltPhysics-- Version: 5.5.0 (23dadd0e603f1b321142d4c74df07fce85064989, 2025)+- Version: 5.6.0 (e77f175595e64cb44218cc9d9d56fc365ad0e36a, 2026)- License: MITFiles extracted from upstream source:-- All files in `Jolt/`, except `Jolt/Jolt.cmake` and any files dependent on `ENABLE_OBJECT_STREAM`, as seen in `Jolt/Jolt.cmake`+- All files in `Jolt/`, except `Jolt/Jolt.cmake`, any files dependent on `ENABLE_OBJECT_STREAM` as seen in `Jolt/Jolt.cmake` and the `Jolt/Physics/Hair/`, `Jolt/Compute/` and `Jolt/Shaders/` folders.- `LICENSE`-Patches:--- `0001-backport-upstream-commit-ee3725250.patch` (GH-115089)-- `0002-backport-upstream-commit-bc7f1fb8c.patch` (GH-115305)-- `0003-backport-upstream-commit-365a15367.patch` (GH-115305)-- `0004-backport-upstream-commit-e0a6a9a16.patch` (GH-115327)-- `0005-backport-upstream-commit-449b645.patch` (GH-117194)-- `0006-backport-upstream-commit-63765d1.patch` (GH-118393)-## libbacktracediff --git a/thirdparty/jolt_physics/Jolt/ConfigurationString.h b/thirdparty/jolt_physics/Jolt/ConfigurationString.hindex 566f13a32e1..d2a87db1eab 100644--- a/thirdparty/jolt_physics/Jolt/ConfigurationString.h+++ b/thirdparty/jolt_physics/Jolt/ConfigurationString.h@@ -38,6 +38,9 @@ inline const char *GetConfigurationString()"32-bit "#endif"with instructions: "+#ifdef JPH_USE_RVV+ "RVV "+#endif#ifdef JPH_USE_NEON"NEON "#endif@@ -105,6 +108,9 @@ inline const char *GetConfigurationString()#endif#if defined(__cpp_exceptions) && __cpp_exceptions"(C++ Exceptions) "+#endif+#ifdef JPH_SHARED_LIBRARY+ "(Shared Library) "#endif;}diff --git a/thirdparty/jolt_physics/Jolt/Core/ARMNeon.h b/thirdparty/jolt_physics/Jolt/Core/ARMNeon.hindex 6273945dc06..9396b4aee88 100644--- a/thirdparty/jolt_physics/Jolt/Core/ARMNeon.h+++ b/thirdparty/jolt_physics/Jolt/Core/ARMNeon.h@@ -27,25 +27,32 @@template <unsigned I1, unsigned I2, unsigned I3, unsigned I4>JPH_INLINE float32x4_t NeonShuffleFloat32x4(float32x4_t inV1, float32x4_t inV2){- float32x4_t ret;- ret = vmovq_n_f32(vgetq_lane_f32(I1 >= 4? inV2 : inV1, I1 & 0b11));- ret = vsetq_lane_f32(vgetq_lane_f32(I2 >= 4? inV2 : inV1, I2 & 0b11), ret, 1);- ret = vsetq_lane_f32(vgetq_lane_f32(I3 >= 4? inV2 : inV1, I3 & 0b11), ret, 2);- ret = vsetq_lane_f32(vgetq_lane_f32(I4 >= 4? inV2 : inV1, I4 & 0b11), ret, 3);- return ret;+ float32x2_t lo = vcopy_laneq_f32(vdup_n_f32(0), 0, I1 >= 4? inV2 : inV1, I1 & 0b11);+ lo = vcopy_laneq_f32(lo, 1, I2 >= 4? inV2 : inV1, I2 & 0b11);++ float32x2_t hi = vcopy_laneq_f32(vdup_n_f32(0), 0, I3 >= 4? inV2 : inV1, I3 & 0b11);+ hi = vcopy_laneq_f32(hi, 1, I4 >= 4? inV2 : inV1, I4 & 0b11);++ return vcombine_f32(lo, hi);}// Specializationstemplate <>- JPH_INLINE float32x4_t NeonShuffleFloat32x4<0, 1, 2, 2>(float32x4_t inV1, float32x4_t inV2)+ JPH_INLINE float32x4_t NeonShuffleFloat32x4<0, 0, 0, 0>(float32x4_t inV1, float32x4_t inV2){- return vcombine_f32(vget_low_f32(inV1), vdup_lane_f32(vget_high_f32(inV1), 0));+ return vdupq_laneq_f32(inV1, 0);}template <>- JPH_INLINE float32x4_t NeonShuffleFloat32x4<0, 1, 3, 3>(float32x4_t inV1, float32x4_t inV2)+ JPH_INLINE float32x4_t NeonShuffleFloat32x4<0, 1, 0, 0>(float32x4_t inV1, float32x4_t inV2){- return vcombine_f32(vget_low_f32(inV1), vdup_lane_f32(vget_high_f32(inV1), 1));+ return vcombine_f32(vget_low_f32(inV1), vdup_lane_f32(vget_low_f32(inV1), 0));+ }++ template <>+ JPH_INLINE float32x4_t NeonShuffleFloat32x4<0, 1, 2, 2>(float32x4_t inV1, float32x4_t inV2)+ {+ return vcopyq_laneq_f32(inV1, 3, inV1, 2);}template <>@@ -54,16 +61,207 @@return inV1;}+ template <>+ JPH_INLINE float32x4_t NeonShuffleFloat32x4<0, 1, 3, 2>(float32x4_t inV1, float32x4_t inV2)+ {+ return vcombine_f32(vget_low_f32(inV1), vrev64_f32(vget_high_f32(inV1)));+ }++ template <>+ JPH_INLINE float32x4_t NeonShuffleFloat32x4<0, 1, 3, 3>(float32x4_t inV1, float32x4_t inV2)+ {+ return vcopyq_laneq_f32(inV1, 2, inV1, 3);+ }++ template <>+ JPH_INLINE float32x4_t NeonShuffleFloat32x4<0, 1, 4, 5>(float32x4_t inV1, float32x4_t inV2)+ {+ return vreinterpretq_f32_f64(vzip1q_f64(vreinterpretq_f64_f32(inV1), vreinterpretq_f64_f32(inV2)));+ }++ template <>+ JPH_INLINE float32x4_t NeonShuffleFloat32x4<0, 2, 1, 1>(float32x4_t inV1, float32x4_t inV2)+ {+ return vuzp1q_f32(inV1, vdupq_laneq_f32(inV1, 1));+ }++ template <>+ JPH_INLINE float32x4_t NeonShuffleFloat32x4<0, 2, 1, 3>(float32x4_t inV1, float32x4_t inV2)+ {+ return vuzp1q_f32(inV1, vrev64q_f32(inV1));+ }++ template <>+ JPH_INLINE float32x4_t NeonShuffleFloat32x4<0, 2, 2, 2>(float32x4_t inV1, float32x4_t inV2)+ {+ return vuzp1q_f32(inV1, vdupq_laneq_f32(inV1, 2));+ }++ template <>+ JPH_INLINE float32x4_t NeonShuffleFloat32x4<0, 2, 2, 3>(float32x4_t inV1, float32x4_t inV2)+ {+ return vcopyq_laneq_f32(inV1, 1, inV1, 2);+ }++ template <>+ JPH_INLINE float32x4_t NeonShuffleFloat32x4<0, 2, 3, 2>(float32x4_t inV1, float32x4_t inV2)+ {+ return vcopyq_laneq_f32(vuzp1q_f32(inV1, inV1), 2, inV1, 3);+ }++ template <>+ JPH_INLINE float32x4_t NeonShuffleFloat32x4<0, 2, 3, 3>(float32x4_t inV1, float32x4_t inV2)+ {+ return vuzp1q_f32(inV1, vdupq_laneq_f32(inV1, 3));+ }++ template <>+ JPH_INLINE float32x4_t NeonShuffleFloat32x4<0, 2, 4, 6>(float32x4_t inV1, float32x4_t inV2)+ {+ return vuzp1q_f32(inV1, inV2);+ }++ template <>+ JPH_INLINE float32x4_t NeonShuffleFloat32x4<0, 3, 1, 2>(float32x4_t inV1, float32x4_t inV2)+ {+ return vzip1q_f32(inV1, vextq_f32(inV1, vdupq_laneq_f32(inV1, 2), 3));+ }++ template <>+ JPH_INLINE float32x4_t NeonShuffleFloat32x4<1, 0, 0, 0>(float32x4_t inV1, float32x4_t inV2)+ {+ return vcombine_f32(vrev64_f32(vget_low_f32(inV1)), vdup_lane_f32(vget_low_f32(inV1), 0));+ }++ template <>+ JPH_INLINE float32x4_t NeonShuffleFloat32x4<1, 0, 0, 2>(float32x4_t inV1, float32x4_t inV2)+ {+ return vcombine_f32(vrev64_f32(vget_low_f32(inV1)), vzip1_f32(vget_low_f32(inV1), vget_high_f32(inV1)));+ }+template <>JPH_INLINE float32x4_t NeonShuffleFloat32x4<1, 0, 3, 2>(float32x4_t inV1, float32x4_t inV2){- return vcombine_f32(vrev64_f32(vget_low_f32(inV1)), vrev64_f32(vget_high_f32(inV1)));+ return vrev64q_f32(inV1);+ }++ template <>+ JPH_INLINE float32x4_t NeonShuffleFloat32x4<1, 1, 1, 1>(float32x4_t inV1, float32x4_t inV2)+ {+ return vdupq_laneq_f32(inV1, 1);+ }++ template <>+ JPH_INLINE float32x4_t NeonShuffleFloat32x4<1, 1, 2, 2>(float32x4_t inV1, float32x4_t inV2)+ {+ float32x4_t t = vextq_f32(inV1, inV1, 1);+ return vzip1q_f32(t, t);+ }++ template <>+ JPH_INLINE float32x4_t NeonShuffleFloat32x4<1, 1, 3, 3>(float32x4_t inV1, float32x4_t inV2)+ {+ return vtrn2q_f32(inV1, inV1);+ }++ // Used extensively by cross product+ template <>+ JPH_INLINE float32x4_t NeonShuffleFloat32x4<1, 2, 0, 0>(float32x4_t inV1, float32x4_t inV2)+ {+ return vcopyq_laneq_f32(vextq_f32(inV1, inV1, 1), 2, inV1, 0);+ }++ template <>+ JPH_INLINE float32x4_t NeonShuffleFloat32x4<1, 2, 0, 1>(float32x4_t inV1, float32x4_t inV2)+ {+ return vextq_f32(vextq_f32(inV1, inV1, 3), inV1, 2);+ }++ template <>+ JPH_INLINE float32x4_t NeonShuffleFloat32x4<1, 2, 0, 2>(float32x4_t inV1, float32x4_t inV2)+ {+ return vcopyq_laneq_f32(vuzp1q_f32(inV1, inV1), 0, inV1, 1);+ }++ template <>+ JPH_INLINE float32x4_t NeonShuffleFloat32x4<1, 2, 2, 2>(float32x4_t inV1, float32x4_t inV2)+ {+ return vcombine_f32(vext_f32(vget_low_f32(inV1), vget_high_f32(inV1), 1), vdup_lane_f32(vget_high_f32(inV1), 0));+ }++ template <>+ JPH_INLINE float32x4_t NeonShuffleFloat32x4<1, 2, 3, 2>(float32x4_t inV1, float32x4_t inV2)+ {+ return vextq_f32(inV1, vdupq_laneq_f32(inV1, 2), 1);+ }++ template <>+ JPH_INLINE float32x4_t NeonShuffleFloat32x4<1, 2, 3, 3>(float32x4_t inV1, float32x4_t inV2)+ {+ return vextq_f32(inV1, vdupq_laneq_f32(inV1, 3), 1);+ }++ template <>+ JPH_INLINE float32x4_t NeonShuffleFloat32x4<1, 3, 0, 2>(float32x4_t inV1, float32x4_t inV2)+ {+ return vuzp2q_f32(inV1, vrev64q_f32(inV1));+ }++ template <>+ JPH_INLINE float32x4_t NeonShuffleFloat32x4<1, 3, 5, 7>(float32x4_t inV1, float32x4_t inV2)+ {+ return vuzp2q_f32(inV1, inV2);+ }++ template <>+ JPH_INLINE float32x4_t NeonShuffleFloat32x4<2, 0, 1, 1>(float32x4_t inV1, float32x4_t inV2)+ {+ return vcopyq_laneq_f32(vzip1q_f32(inV1, inV1), 0, inV1, 2);+ }++ template <>+ JPH_INLINE float32x4_t NeonShuffleFloat32x4<2, 0, 1, 2>(float32x4_t inV1, float32x4_t inV2)+ {+ return vextq_f32(vuzp1q_f32(inV1, inV1), inV1, 3);+ }++ template <>+ JPH_INLINE float32x4_t NeonShuffleFloat32x4<2, 1, 0, 0>(float32x4_t inV1, float32x4_t inV2)+ {+ float32x4_t t = vextq_f32(vuzp1q_f32(inV1, inV1), inV1, 3);+ return vuzp1q_f32(t, vuzp1q_f32(inV1, inV1));+ }++ template <>+ JPH_INLINE float32x4_t NeonShuffleFloat32x4<2, 1, 0, 3>(float32x4_t inV1, float32x4_t inV2)+ {+ float32x4_t t = vrev64q_f32(inV1);+ return vextq_f32(t, t, 3);}template <>JPH_INLINE float32x4_t NeonShuffleFloat32x4<2, 2, 1, 0>(float32x4_t inV1, float32x4_t inV2){- return vcombine_f32(vdup_lane_f32(vget_high_f32(inV1), 0), vrev64_f32(vget_low_f32(inV1)));+ return vextq_f32(vtrn1q_f32(inV1, inV1), vrev64q_f32(inV1), 2);+ }++ template <>+ JPH_INLINE float32x4_t NeonShuffleFloat32x4<2, 2, 1, 1>(float32x4_t inV1, float32x4_t inV2)+ {+ float32x4_t t = vcopyq_laneq_f32(inV1, 3, inV1, 1);+ return vzip2q_f32(t, t);+ }++ template <>+ JPH_INLINE float32x4_t NeonShuffleFloat32x4<2, 2, 1, 2>(float32x4_t inV1, float32x4_t inV2)+ {+ return vcopyq_laneq_f32(vdupq_laneq_f32(inV1, 2), 2, inV1, 1);+ }++ template <>+ JPH_INLINE float32x4_t NeonShuffleFloat32x4<2, 2, 2, 2>(float32x4_t inV1, float32x4_t inV2)+ {+ return vdupq_laneq_f32(inV1, 2);}template <>@@ -72,12 +270,60 @@return vcombine_f32(vget_high_f32(inV1), vget_low_f32(inV1));}- // Used extensively by cross producttemplate <>- JPH_INLINE float32x4_t NeonShuffleFloat32x4<1, 2, 0, 0>(float32x4_t inV1, float32x4_t inV2)+ JPH_INLINE float32x4_t NeonShuffleFloat32x4<2, 3, 1, 2>(float32x4_t inV1, float32x4_t inV2)+ {+ return vextq_f32(inV1, vextq_f32(inV1, inV1, 1), 2);+ }++ template <>+ JPH_INLINE float32x4_t NeonShuffleFloat32x4<2, 3, 2, 2>(float32x4_t inV1, float32x4_t inV2)+ {+ return vextq_f32(inV1, vdupq_laneq_f32(inV1, 2), 2);+ }++ template <>+ JPH_INLINE float32x4_t NeonShuffleFloat32x4<2, 3, 2, 3>(float32x4_t inV1, float32x4_t inV2)+ {+ return vreinterpretq_f32_f64(vdupq_laneq_f64(vreinterpretq_f64_f32(inV1), 1));+ }++ template <>+ JPH_INLINE float32x4_t NeonShuffleFloat32x4<2, 3, 6, 7>(float32x4_t inV1, float32x4_t inV2)+ {+ return vreinterpretq_f32_f64(vzip2q_f64(vreinterpretq_f64_f32(inV1), vreinterpretq_f64_f32(inV2)));+ }++ template <>+ JPH_INLINE float32x4_t NeonShuffleFloat32x4<3, 0, 1, 2>(float32x4_t inV1, float32x4_t inV2)+ {+ return vextq_f32(inV1, inV1, 3);+ }++ template <>+ JPH_INLINE float32x4_t NeonShuffleFloat32x4<3, 0, 3, 2>(float32x4_t inV1, float32x4_t inV2)+ {+ return vtrn1q_f32(vdupq_laneq_f32(inV1, 3), inV1);+ }++ template <>+ JPH_INLINE float32x4_t NeonShuffleFloat32x4<3, 2, 1, 0>(float32x4_t inV1, float32x4_t inV2)+ {+ float32x4_t t = vrev64q_f32(inV1);+ return vextq_f32(t, t, 2);+ }++ template <>+ JPH_INLINE float32x4_t NeonShuffleFloat32x4<3, 2, 3, 2>(float32x4_t inV1, float32x4_t inV2)+ {+ float32x2_t zy = vrev64_f32(vget_high_f32(inV1));+ return vcombine_f32(zy, zy);+ }++ template <>+ JPH_INLINE float32x4_t NeonShuffleFloat32x4<3, 3, 3, 3>(float32x4_t inV1, float32x4_t inV2){- static uint8x16_t table = JPH_NEON_UINT8x16(0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x02, 0x03);- return vreinterpretq_f32_u8(vqtbl1q_u8(vreinterpretq_u8_f32(inV1), table));+ return vdupq_laneq_f32(inV1, 3);}// Shuffle a vectordiff --git a/thirdparty/jolt_physics/Jolt/Core/Color.h b/thirdparty/jolt_physics/Jolt/Core/Color.hindex 4995701bc24..03f9fe1f4ab 100644--- a/thirdparty/jolt_physics/Jolt/Core/Color.h+++ b/thirdparty/jolt_physics/Jolt/Core/Color.h@@ -93,6 +93,6 @@ public:};};-static_assert(std::is_trivial<Color>(), "Is supposed to be a trivial type!");+static_assert(std::is_trivially_default_constructible<Color>() && std::is_trivially_copyable<Color>(), "Is supposed to be a trivial type!");JPH_NAMESPACE_ENDdiff --git a/thirdparty/jolt_physics/Jolt/Core/Core.h b/thirdparty/jolt_physics/Jolt/Core/Core.hindex 687c1fd95cb..30377deeffb 100644--- a/thirdparty/jolt_physics/Jolt/Core/Core.h+++ b/thirdparty/jolt_physics/Jolt/Core/Core.h@@ -6,7 +6,7 @@// Jolt library version#define JPH_VERSION_MAJOR 5-#define JPH_VERSION_MINOR 5+#define JPH_VERSION_MINOR 6#define JPH_VERSION_PATCH 0// Determine which features the library was compiled with@@ -117,7 +117,25 @@#endif// Detect CPU architecture-#if defined(__x86_64__) || defined(_M_X64) || defined(__i386__) || defined(_M_IX86)+#if defined(__aarch64__) || defined(_M_ARM64) || defined(__arm__) || defined(_M_ARM) || defined(_M_ARM64EC)+ // ARM CPU architecture+ #define JPH_CPU_ARM+ #if defined(__aarch64__) || defined(_M_ARM64) || defined(_M_ARM64EC)+ #define JPH_CPU_ARCH_BITS 64+ #define JPH_USE_NEON+ #define JPH_VECTOR_ALIGNMENT 16+ #define JPH_DVECTOR_ALIGNMENT 32+ #else+ #define JPH_CPU_ARCH_BITS 32+ #define JPH_VECTOR_ALIGNMENT 8 // 32-bit ARM does not support aligning on the stack on 16 byte boundaries+ #define JPH_DVECTOR_ALIGNMENT 8+ #endif+ #ifndef JPH_CROSS_PLATFORM_DETERMINISTIC // FMA is not compatible with cross platform determinism+ #if defined(__ARM_FEATURE_FMA) && !defined(JPH_USE_FMADD)+ #define JPH_USE_FMADD+ #endif+ #endif+#elif defined(__x86_64__) || defined(_M_X64) || defined(__i386__) || defined(_M_IX86)// X86 CPU architecture#define JPH_CPU_X86#if defined(__x86_64__) || defined(_M_X64)@@ -167,19 +185,6 @@#error Undefined compiler#endif#endif-#elif defined(__aarch64__) || defined(_M_ARM64) || defined(__arm__) || defined(_M_ARM)- // ARM CPU architecture- #define JPH_CPU_ARM- #if defined(__aarch64__) || defined(_M_ARM64)- #define JPH_CPU_ARCH_BITS 64- #define JPH_USE_NEON- #define JPH_VECTOR_ALIGNMENT 16- #define JPH_DVECTOR_ALIGNMENT 32- #else- #define JPH_CPU_ARCH_BITS 32- #define JPH_VECTOR_ALIGNMENT 8 // 32-bit ARM does not support aligning on the stack on 16 byte boundaries- #define JPH_DVECTOR_ALIGNMENT 8- #endif#elif defined(__riscv)// RISC-V CPU architecture#define JPH_CPU_RISCV@@ -192,6 +197,9 @@#define JPH_VECTOR_ALIGNMENT 16#define JPH_DVECTOR_ALIGNMENT 8#endif+ #if defined(__riscv_vector)+ #define JPH_USE_RVV+ #endif#elif defined(JPH_PLATFORM_WASM)// WebAssembly CPU architecture#define JPH_CPU_WASM@@ -270,9 +278,15 @@#endif#endif#endif++ #define JPH_IF_SHARED_LIBRARY(x) x+ #define JPH_IF_NOT_SHARED_LIBRARY(x)#else// If the define is not set, we use static linking and symbols don't need to be imported or exported#define JPH_EXPORT++ #define JPH_IF_SHARED_LIBRARY(x)+ #define JPH_IF_NOT_SHARED_LIBRARY(x) x#endif#ifndef JPH_EXPORT_GCC_BUG_WORKAROUND@@ -284,52 +298,78 @@// Pragmas to store / restore the warning state and to disable individual warnings#ifdef JPH_COMPILER_CLANG-#define JPH_PRAGMA(x) _Pragma(#x)-#define JPH_SUPPRESS_WARNING_PUSH JPH_PRAGMA(clang diagnostic push)-#define JPH_SUPPRESS_WARNING_POP JPH_PRAGMA(clang diagnostic pop)-#define JPH_CLANG_SUPPRESS_WARNING(w) JPH_PRAGMA(clang diagnostic ignored w)-#if __clang_major__ >= 13- #define JPH_CLANG_13_PLUS_SUPPRESS_WARNING(w) JPH_CLANG_SUPPRESS_WARNING(w)+ #define JPH_PRAGMA(x) _Pragma(#x)+ #define JPH_SUPPRESS_WARNING_PUSH JPH_PRAGMA(clang diagnostic push)+ #define JPH_SUPPRESS_WARNING_POP JPH_PRAGMA(clang diagnostic pop)+ #define JPH_CLANG_SUPPRESS_WARNING(w) JPH_PRAGMA(clang diagnostic ignored w)+ #if __has_warning("-Wdeprecated-copy")+ #define JPH_CLANG_SUPPRESS_DEPRECATED_COPY_WARNING JPH_CLANG_SUPPRESS_WARNING("-Wdeprecated-copy")+ #endif+ #if __has_warning("-Wdeprecated-copy-with-dtor")+ #define JPH_CLANG_SUPPRESS_DEPRECATED_COPY_WITH_DTOR_WARNING JPH_CLANG_SUPPRESS_WARNING("-Wdeprecated-copy-with-dtor")+ #endif+ #if __has_warning("-Wunsafe-buffer-usage")+ #define JPH_CLANG_SUPPRESS_UNSAFE_BUFFER_USAGE_WARNING JPH_CLANG_SUPPRESS_WARNING("-Wunsafe-buffer-usage")+ #endif+ #if __has_warning("-Wimplicit-int-float-conversion")+ #define JPH_CLANG_SUPPRESS_IMPLICIT_INT_FLOAT_CONVERSION_WARNING JPH_CLANG_SUPPRESS_WARNING("-Wimplicit-int-float-conversion")+ #endif+ #if __has_warning("-Wunique-object-duplication")+ #define JPH_CLANG_SUPPRESS_UNIQUE_OBJECT_DUPLICATION_WARNING JPH_CLANG_SUPPRESS_WARNING("-Wunique-object-duplication")+ #endif+ #if __has_warning("-Wnrvo")+ #define JPH_CLANG_SUPPRESS_NRVO_WARNING JPH_CLANG_SUPPRESS_WARNING("-Wnrvo")+ #endif#else- #define JPH_CLANG_13_PLUS_SUPPRESS_WARNING(w)+ #define JPH_CLANG_SUPPRESS_WARNING(w)#endif-#if __clang_major__ >= 16- #define JPH_CLANG_16_PLUS_SUPPRESS_WARNING(w) JPH_CLANG_SUPPRESS_WARNING(w)-#else- #define JPH_CLANG_16_PLUS_SUPPRESS_WARNING(w)+#ifndef JPH_CLANG_SUPPRESS_DEPRECATED_COPY_WARNING+ #define JPH_CLANG_SUPPRESS_DEPRECATED_COPY_WARNING#endif-#else-#define JPH_CLANG_SUPPRESS_WARNING(w)-#define JPH_CLANG_13_PLUS_SUPPRESS_WARNING(w)-#define JPH_CLANG_16_PLUS_SUPPRESS_WARNING(w)+#ifndef JPH_CLANG_SUPPRESS_DEPRECATED_COPY_WITH_DTOR_WARNING+ #define JPH_CLANG_SUPPRESS_DEPRECATED_COPY_WITH_DTOR_WARNING+#endif+#ifndef JPH_CLANG_SUPPRESS_UNSAFE_BUFFER_USAGE_WARNING+ #define JPH_CLANG_SUPPRESS_UNSAFE_BUFFER_USAGE_WARNING+#endif+#ifndef JPH_CLANG_SUPPRESS_IMPLICIT_INT_FLOAT_CONVERSION_WARNING+ #define JPH_CLANG_SUPPRESS_IMPLICIT_INT_FLOAT_CONVERSION_WARNING#endif+#ifndef JPH_CLANG_SUPPRESS_UNIQUE_OBJECT_DUPLICATION_WARNING+ #define JPH_CLANG_SUPPRESS_UNIQUE_OBJECT_DUPLICATION_WARNING+#endif+#ifndef JPH_CLANG_SUPPRESS_NRVO_WARNING+ #define JPH_CLANG_SUPPRESS_NRVO_WARNING+#endif+#ifdef JPH_COMPILER_GCC-#define JPH_PRAGMA(x) _Pragma(#x)-#define JPH_SUPPRESS_WARNING_PUSH JPH_PRAGMA(GCC diagnostic push)-#define JPH_SUPPRESS_WARNING_POP JPH_PRAGMA(GCC diagnostic pop)-#define JPH_GCC_SUPPRESS_WARNING(w) JPH_PRAGMA(GCC diagnostic ignored w)+ #define JPH_PRAGMA(x) _Pragma(#x)+ #define JPH_SUPPRESS_WARNING_PUSH JPH_PRAGMA(GCC diagnostic push)+ #define JPH_SUPPRESS_WARNING_POP JPH_PRAGMA(GCC diagnostic pop)+ #define JPH_GCC_SUPPRESS_WARNING(w) JPH_PRAGMA(GCC diagnostic ignored w)#else-#define JPH_GCC_SUPPRESS_WARNING(w)+ #define JPH_GCC_SUPPRESS_WARNING(w)#endif+#ifdef JPH_COMPILER_MSVC-#define JPH_PRAGMA(x) __pragma(x)-#define JPH_SUPPRESS_WARNING_PUSH JPH_PRAGMA(warning (push))-#define JPH_SUPPRESS_WARNING_POP JPH_PRAGMA(warning (pop))-#define JPH_MSVC_SUPPRESS_WARNING(w) JPH_PRAGMA(warning (disable : w))-#if _MSC_VER >= 1920 && _MSC_VER < 1930- #define JPH_MSVC2019_SUPPRESS_WARNING(w) JPH_MSVC_SUPPRESS_WARNING(w)+ #define JPH_PRAGMA(x) __pragma(x)+ #define JPH_SUPPRESS_WARNING_PUSH JPH_PRAGMA(warning (push))+ #define JPH_SUPPRESS_WARNING_POP JPH_PRAGMA(warning (pop))+ #define JPH_MSVC_SUPPRESS_WARNING(w) JPH_PRAGMA(warning (disable : w))+ #if _MSC_VER >= 1920 && _MSC_VER < 1930+ #define JPH_MSVC2019_SUPPRESS_WARNING(w) JPH_MSVC_SUPPRESS_WARNING(w)+ #else+ #define JPH_MSVC2019_SUPPRESS_WARNING(w)+ #endif+ #if _MSC_VER >= 1950+ #define JPH_MSVC2026_PLUS_SUPPRESS_WARNING(w) JPH_MSVC_SUPPRESS_WARNING(w)+ #else+ #define JPH_MSVC2026_PLUS_SUPPRESS_WARNING(w)+ #endif#else+ #define JPH_MSVC_SUPPRESS_WARNING(w)#define JPH_MSVC2019_SUPPRESS_WARNING(w)-#endif-#if _MSC_VER >= 1950-#define JPH_MSVC2026_PLUS_SUPPRESS_WARNING(w) JPH_MSVC_SUPPRESS_WARNING(w)-#else-#define JPH_MSVC2026_PLUS_SUPPRESS_WARNING(w)-#endif-#else-#define JPH_MSVC_SUPPRESS_WARNING(w)-#define JPH_MSVC2019_SUPPRESS_WARNING(w)-#define JPH_MSVC2026_PLUS_SUPPRESS_WARNING(w)+ #define JPH_MSVC2026_PLUS_SUPPRESS_WARNING(w)#endif// Disable common warnings triggered by Jolt when compiling with -Wall@@ -354,10 +394,13 @@JPH_CLANG_SUPPRESS_WARNING("-Wdocumentation-unknown-command") \JPH_CLANG_SUPPRESS_WARNING("-Wctad-maybe-unsupported") \JPH_CLANG_SUPPRESS_WARNING("-Wswitch-default") \- JPH_CLANG_13_PLUS_SUPPRESS_WARNING("-Wdeprecated-copy") \- JPH_CLANG_13_PLUS_SUPPRESS_WARNING("-Wdeprecated-copy-with-dtor") \- JPH_CLANG_16_PLUS_SUPPRESS_WARNING("-Wunsafe-buffer-usage") \- JPH_IF_NOT_ANDROID(JPH_CLANG_SUPPRESS_WARNING("-Wimplicit-int-float-conversion")) \+ JPH_CLANG_SUPPRESS_DEPRECATED_COPY_WARNING \+ JPH_CLANG_SUPPRESS_DEPRECATED_COPY_WITH_DTOR_WARNING \+ JPH_CLANG_SUPPRESS_UNSAFE_BUFFER_USAGE_WARNING \+ JPH_CLANG_SUPPRESS_IMPLICIT_INT_FLOAT_CONVERSION_WARNING \+ JPH_CLANG_SUPPRESS_WARNING("-Wpadded") \+ JPH_IF_NOT_SHARED_LIBRARY(JPH_CLANG_SUPPRESS_UNIQUE_OBJECT_DUPLICATION_WARNING) \+ JPH_CLANG_SUPPRESS_NRVO_WARNING \\JPH_GCC_SUPPRESS_WARNING("-Wcomment") \JPH_GCC_SUPPRESS_WARNING("-Winvalid-offsetof") \@@ -390,7 +433,8 @@JPH_MSVC_SUPPRESS_WARNING(5264) /* 'X': 'const' variable is not used */ \JPH_MSVC_SUPPRESS_WARNING(4251) /* class 'X' needs to have DLL-interface to be used by clients of class 'Y' */ \JPH_MSVC_SUPPRESS_WARNING(4738) /* storing 32-bit float result in memory, possible loss of performance */ \- JPH_MSVC2019_SUPPRESS_WARNING(5246) /* the initialization of a subobject should be wrapped in braces */+ JPH_MSVC2019_SUPPRESS_WARNING(5246) /* the initialization of a subobject should be wrapped in braces */ \+ JPH_MSVC2026_PLUS_SUPPRESS_WARNING(5291) /* 'X': deriving from the base class 'Y' can cause potential runtime issues due to an ABI bug. Recommend adding a 4-byte data member to the base class for the padding at the end of it to work around this bug. */// OS-specific includes#if defined(JPH_PLATFORM_WINDOWS)@@ -429,6 +473,7 @@// Suppress warnings generated by the standard template library#define JPH_SUPPRESS_WARNINGS_STD_BEGIN \JPH_SUPPRESS_WARNING_PUSH \+ JPH_CLANG_SUPPRESS_WARNING("-Wpadded") \JPH_MSVC_SUPPRESS_WARNING(4365) \JPH_MSVC_SUPPRESS_WARNING(4619) \JPH_MSVC_SUPPRESS_WARNING(4710) \@@ -473,6 +518,8 @@ JPH_SUPPRESS_WARNINGS_STD_BEGIN#else#include <arm_neon.h>#endif+#elif defined(JPH_USE_RVV)+ #include <riscv_vector.h>#endifJPH_SUPPRESS_WARNINGS_STD_END@@ -482,7 +529,6 @@ JPH_NAMESPACE_BEGINusing std::min;using std::max;using std::abs;-using std::sqrt;using std::ceil;using std::floor;using std::trunc;@@ -501,7 +547,9 @@ using uint = unsigned int;using uint8 = std::uint8_t;using uint16 = std::uint16_t;using uint32 = std::uint32_t;+using int32 = std::int32_t;using uint64 = std::uint64_t;+using int64 = std::int64_t;// Assert sizes of typesstatic_assert(sizeof(uint) >= 4, "Invalid size of uint");@@ -596,39 +644,26 @@ static_assert(sizeof(uint64) == 8, "Invalid size of uint64");// Macro to indicate that a parameter / variable is unused#define JPH_UNUSED(x) (void)x-// Macro to enable floating point precise mode and to disable fused multiply add instructions-#if defined(JPH_COMPILER_GCC) || defined(JPH_CROSS_PLATFORM_DETERMINISTIC)- // We compile without -ffast-math and -ffp-contract=fast, so we don't need to disable anything- #define JPH_PRECISE_MATH_ON- #define JPH_PRECISE_MATH_OFF-#elif defined(JPH_COMPILER_CLANG)- // We compile without -ffast-math because pragma float_control(precise, on) doesn't seem to actually negate all of the -ffast-math effects and causes the unit tests to fail (even if the pragma is added to all files)- // On clang 14 and later we can turn off float contraction through a pragma (before it was buggy), so if FMA is on we can disable it through this macro- #if (defined(JPH_CPU_ARM) && !defined(JPH_PLATFORM_ANDROID) && __clang_major__ >= 16) || (defined(JPH_CPU_X86) && __clang_major__ >= 14)- #define JPH_PRECISE_MATH_ON \- _Pragma("float_control(precise, on, push)") \- _Pragma("clang fp contract(off)")- #define JPH_PRECISE_MATH_OFF \- _Pragma("float_control(pop)")- #elif __clang_major__ >= 14 && (defined(JPH_USE_FMADD) || defined(FP_FAST_FMA))- #define JPH_PRECISE_MATH_ON \- _Pragma("clang fp contract(off)")- #define JPH_PRECISE_MATH_OFF \- _Pragma("clang fp contract(on)")- #else- #define JPH_PRECISE_MATH_ON- #define JPH_PRECISE_MATH_OFF- #endif+// Macro to enable floating point precise mode+#if defined(JPH_COMPILER_CLANG)+ #define JPH_PRECISE_MATH_ON \+ _Pragma("clang diagnostic push") \+ _Pragma("clang diagnostic ignored \"-Wignored-pragmas\"") \+ _Pragma("float_control(precise, on, push)") \+ _Pragma("clang diagnostic pop")+ #define JPH_PRECISE_MATH_OFF \+ _Pragma("clang diagnostic push") \+ _Pragma("clang diagnostic ignored \"-Wignored-pragmas\"") \+ _Pragma("float_control(pop)") \+ _Pragma("clang diagnostic pop")#elif defined(JPH_COMPILER_MSVC)- // Unfortunately there is no way to push the state of fp_contract, so we have to assume it was turned on before JPH_PRECISE_MATH_ON- #define JPH_PRECISE_MATH_ON \- __pragma(float_control(precise, on, push)) \- __pragma(fp_contract(off))- #define JPH_PRECISE_MATH_OFF \- __pragma(fp_contract(on)) \+ #define JPH_PRECISE_MATH_ON \+ __pragma(float_control(precise, on, push))+ #define JPH_PRECISE_MATH_OFF \__pragma(float_control(pop))#else- #error Undefined+ #define JPH_PRECISE_MATH_ON+ #define JPH_PRECISE_MATH_OFF#endif// Check if Thread Sanitizer is enabled@@ -649,4 +684,25 @@ static_assert(sizeof(uint64) == 8, "Invalid size of uint64");#define JPH_TSAN_NO_SANITIZE#endif+// Check if Address Sanitizer is enabled+#ifdef __has_feature+ #if __has_feature(address_sanitizer)+ #define JPH_ASAN_ENABLED+ #endif+#else+ #ifdef __SANITIZE_ADDRESS__+ #define JPH_ASAN_ENABLED+ #endif+#endif++// DirectX 12 is only supported on Windows+#if defined(JPH_USE_DX12) && !defined(JPH_PLATFORM_WINDOWS)+ #undef JPH_USE_DX12+#endif // JPH_PLATFORM_WINDOWS++// Metal is only supported on Apple platforms+#if defined(JPH_USE_MTL) && !defined(JPH_PLATFORM_MACOS) && !defined(JPH_PLATFORM_IOS)+ #undef JPH_USE_MTL+#endif // !JPH_PLATFORM_MACOS && !JPH_PLATFORM_IOS+JPH_NAMESPACE_ENDdiff --git a/thirdparty/jolt_physics/Jolt/Core/IncludeWindows.h b/thirdparty/jolt_physics/Jolt/Core/IncludeWindows.hnew file mode 100644index 00000000000..fe1eb18879e--- /dev/null+++ b/thirdparty/jolt_physics/Jolt/Core/IncludeWindows.h@@ -0,0 +1,36 @@+// Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)+// SPDX-FileCopyrightText: 2025 Jorrit Rouwe+// SPDX-License-Identifier: MIT++#ifdef JPH_PLATFORM_WINDOWS++JPH_SUPPRESS_WARNING_PUSH+JPH_MSVC_SUPPRESS_WARNING(5039) // winbase.h(13179): warning C5039: 'TpSetCallbackCleanupGroup': pointer or reference to potentially throwing function passed to 'extern "C"' function under -EHc. Undefined behavior may occur if this function throws an exception.+JPH_MSVC2026_PLUS_SUPPRESS_WARNING(4865) // wingdi.h(2806,1): '<unnamed-enum-DISPLAYCONFIG_OUTPUT_TECHNOLOGY_OTHER>': the underlying type will change from 'int' to '__int64' when '/Zc:enumTypes' is specified on the command line+JPH_CLANG_SUPPRESS_WARNING("-Wreserved-macro-identifier") // Complains about _WIN32_WINNT being reserved++#ifndef WINVER+ #define WINVER 0x0A00 // Targeting Windows 10 and above+#endif++#ifndef _WIN32_WINNT+ #define _WIN32_WINNT 0x0A00+#endif++#ifndef WIN32_LEAN_AND_MEAN+ #define WIN32_LEAN_AND_MEAN+#endif++#ifndef NOMINMAX+ #define NOMINMAX+#endif++#ifndef JPH_COMPILER_MINGW+ #include <Windows.h>+#else+ #include <windows.h>+#endif++JPH_SUPPRESS_WARNING_POP++#endifdiff --git a/thirdparty/jolt_physics/Jolt/Core/JobSystemThreadPool.cpp b/thirdparty/jolt_physics/Jolt/Core/JobSystemThreadPool.cppindex bf5c87e6ccc..b2f7a24112d 100644--- a/thirdparty/jolt_physics/Jolt/Core/JobSystemThreadPool.cpp+++ b/thirdparty/jolt_physics/Jolt/Core/JobSystemThreadPool.cpp@@ -7,21 +7,8 @@#include <Jolt/Core/JobSystemThreadPool.h>#include <Jolt/Core/Profiler.h>#include <Jolt/Core/FPException.h>+#include <Jolt/Core/IncludeWindows.h>-#ifdef JPH_PLATFORM_WINDOWS- JPH_SUPPRESS_WARNING_PUSH- JPH_MSVC_SUPPRESS_WARNING(5039) // winbase.h(13179): warning C5039: 'TpSetCallbackCleanupGroup': pointer or reference to potentially throwing function passed to 'extern "C"' function under -EHc. Undefined behavior may occur if this function throws an exception.- JPH_MSVC2026_PLUS_SUPPRESS_WARNING(4865) // wingdi.h(2806,1): '<unnamed-enum-DISPLAYCONFIG_OUTPUT_TECHNOLOGY_OTHER>': the underlying type will change from 'int' to '__int64' when '/Zc:enumTypes' is specified on the command line- #ifndef WIN32_LEAN_AND_MEAN- #define WIN32_LEAN_AND_MEAN- #endif-#ifndef JPH_COMPILER_MINGW- #include <Windows.h>-#else- #include <windows.h>-#endif- JPH_SUPPRESS_WARNING_POP-#endif#ifdef JPH_PLATFORM_LINUX#include <sys/prctl.h>#endif@@ -314,7 +301,7 @@ void JobSystemThreadPool::ThreadMain(int inThreadIndex)#if defined(JPH_PLATFORM_WINDOWS) || defined(JPH_PLATFORM_LINUX)SetThreadName(name);-#endif // JPH_PLATFORM_WINDOWS && !JPH_COMPILER_MINGW+#endif // JPH_PLATFORM_WINDOWS || JPH_PLATFORM_LINUX// Enable floating point exceptionsFPExceptionsEnable enable_exceptions;diff --git a/thirdparty/jolt_physics/Jolt/Core/LSANSuppressions.h b/thirdparty/jolt_physics/Jolt/Core/LSANSuppressions.hnew file mode 100644index 00000000000..c05a8bcca21--- /dev/null+++ b/thirdparty/jolt_physics/Jolt/Core/LSANSuppressions.h@@ -0,0 +1,21 @@+// Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)+// SPDX-FileCopyrightText: 2026 Jorrit Rouwe+// SPDX-License-Identifier: MIT++#pragma once++#if defined(JPH_USE_VK) && defined(JPH_ASAN_ENABLED)++JPH_SUPPRESS_WARNING_PUSH+JPH_CLANG_SUPPRESS_WARNING("-Wreserved-identifier")++// Suppress ASAN leak detection for the Vulkan driver+extern "C" const char *__lsan_default_suppressions();+extern "C" const char *__lsan_default_suppressions()+{+ return "leak:libvulkan";+}++JPH_SUPPRESS_WARNING_POP++#endifdiff --git a/thirdparty/jolt_physics/Jolt/Core/LockFreeHashMap.h b/thirdparty/jolt_physics/Jolt/Core/LockFreeHashMap.hindex ac1557b39a4..575280a5f61 100644--- a/thirdparty/jolt_physics/Jolt/Core/LockFreeHashMap.h+++ b/thirdparty/jolt_physics/Jolt/Core/LockFreeHashMap.h@@ -128,6 +128,9 @@ public:/// Convert uint32 handle back to key and valueinline const KeyValue * FromHandle(uint32 inHandle) const;+ /// Convert uint32 handle back to key and value (note that it is illegal to change the key this way)+ inline KeyValue * FromHandle(uint32 inHandle);+#ifdef JPH_ENABLE_ASSERTS/// Get the number of key value pairs that this map currently contains./// Available only when asserts are enabled because adding elements creates contention on this atomic and negatively affects performance.diff --git a/thirdparty/jolt_physics/Jolt/Core/LockFreeHashMap.inl b/thirdparty/jolt_physics/Jolt/Core/LockFreeHashMap.inlindex aa4b875e9c7..dd6d00efe65 100644--- a/thirdparty/jolt_physics/Jolt/Core/LockFreeHashMap.inl+++ b/thirdparty/jolt_physics/Jolt/Core/LockFreeHashMap.inl@@ -12,7 +12,11 @@ JPH_NAMESPACE_BEGINinline LFHMAllocator::~LFHMAllocator(){+#if JPH_DEFAULT_ALLOCATE_ALIGNMENT < 16AlignedFree(mObjectStore);+#else+ Free(mObjectStore);+#endif}inline void LFHMAllocator::Init(uint inObjectStoreSizeBytes)@@ -20,7 +24,11 @@ inline void LFHMAllocator::Init(uint inObjectStoreSizeBytes)JPH_ASSERT(mObjectStore == nullptr);mObjectStoreSizeBytes = inObjectStoreSizeBytes;+#if JPH_DEFAULT_ALLOCATE_ALIGNMENT < 16mObjectStore = reinterpret_cast<uint8 *>(JPH::AlignedAllocate(inObjectStoreSizeBytes, 16));+#else+ mObjectStore = reinterpret_cast<uint8 *>(JPH::Allocate(inObjectStoreSizeBytes));+#endif}inline void LFHMAllocator::Clear()@@ -124,7 +132,11 @@ void LockFreeHashMap<Key, Value>::Init(uint32 inMaxBuckets)mNumBuckets = inMaxBuckets;mMaxBuckets = inMaxBuckets;+#if JPH_DEFAULT_ALLOCATE_ALIGNMENT < 16mBuckets = reinterpret_cast<atomic<uint32> *>(AlignedAllocate(inMaxBuckets * sizeof(atomic<uint32>), 16));+#else+ mBuckets = reinterpret_cast<atomic<uint32> *>(Allocate(inMaxBuckets * sizeof(atomic<uint32>)));+#endifClear();}@@ -132,7 +144,11 @@ void LockFreeHashMap<Key, Value>::Init(uint32 inMaxBuckets)template <class Key, class Value>LockFreeHashMap<Key, Value>::~LockFreeHashMap(){+#if JPH_DEFAULT_ALLOCATE_ALIGNMENT < 16AlignedFree(mBuckets);+#else+ Free(mBuckets);+#endif}template <class Key, class Value>@@ -240,6 +256,12 @@ inline const typename LockFreeHashMap<Key, Value>::KeyValue *LockFreeHashMap<Keyreturn mAllocator.template FromOffset<const KeyValue>(inHandle);}+template <class Key, class Value>+inline typename LockFreeHashMap<Key, Value>::KeyValue *LockFreeHashMap<Key, Value>::FromHandle(uint32 inHandle)+{+ return mAllocator.template FromOffset<KeyValue>(inHandle);+}+template <class Key, class Value>inline void LockFreeHashMap<Key, Value>::GetAllKeyValues(Array<const KeyValue *> &outAll) const{diff --git a/thirdparty/jolt_physics/Jolt/Core/ObjectToIDMap.h b/thirdparty/jolt_physics/Jolt/Core/ObjectToIDMap.hnew file mode 100644index 00000000000..0e7a30c921b--- /dev/null+++ b/thirdparty/jolt_physics/Jolt/Core/ObjectToIDMap.h@@ -0,0 +1,21 @@+// Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)+// SPDX-FileCopyrightText: 2026 Jorrit Rouwe+// SPDX-License-Identifier: MIT++#pragma once++#include <Jolt/Core/UnorderedMapFwd.h>++JPH_NAMESPACE_BEGIN++namespace StreamUtils {++template <class Type>+using ObjectToIDMap = UnorderedMap<const Type *, uint32>;++template <class Type>+using IDToObjectMap = Array<Ref<Type>>;++} // StreamUtils++JPH_NAMESPACE_ENDdiff --git a/thirdparty/jolt_physics/Jolt/Core/Prefetch.h b/thirdparty/jolt_physics/Jolt/Core/Prefetch.hnew file mode 100644index 00000000000..98f99e3aee9--- /dev/null+++ b/thirdparty/jolt_physics/Jolt/Core/Prefetch.h@@ -0,0 +1,20 @@+// Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)+// SPDX-FileCopyrightText: 2026 Jorrit Rouwe+// SPDX-License-Identifier: MIT++#pragma once++JPH_NAMESPACE_BEGIN++/// Prefetch the given address to L1 cache. Can be used to avoid cache misses, but should be used with care as it can also cause cache pollution if used incorrectly.+template <typename T>+inline void PrefetchL1(const T *inAddress)+{+#ifdef JPH_USE_SSE+ _mm_prefetch(reinterpret_cast<const char *>(inAddress), _MM_HINT_T0);+#elif defined(JPH_COMPILER_GCC) || defined(JPH_COMPILER_CLANG)+ __builtin_prefetch(inAddress, 0, 3);+#endif+}++JPH_NAMESPACE_ENDdiff --git a/thirdparty/jolt_physics/Jolt/Core/Profiler.cpp b/thirdparty/jolt_physics/Jolt/Core/Profiler.cppindex 6536607d5af..6aa752e0c05 100644--- a/thirdparty/jolt_physics/Jolt/Core/Profiler.cpp+++ b/thirdparty/jolt_physics/Jolt/Core/Profiler.cpp@@ -8,9 +8,11 @@#include <Jolt/Core/Color.h>#include <Jolt/Core/StringTools.h>#include <Jolt/Core/QuickSort.h>+#include <Jolt/Core/UnorderedMap.h>JPH_SUPPRESS_WARNINGS_STD_BEGIN#include <fstream>+#include <chrono>JPH_SUPPRESS_WARNINGS_STD_ENDJPH_NAMESPACE_BEGIN@@ -49,15 +51,15 @@ bool ProfileMeasurement::sOutOfSamplesReported = false;void Profiler::UpdateReferenceTime(){mReferenceTick = GetProcessorTickCount();- mReferenceTime = std::chrono::high_resolution_clock::now();+ mReferenceTime = std::chrono::duration_cast<std::chrono::microseconds>(std::chrono::high_resolution_clock::now().time_since_epoch()).count();}uint64 Profiler::GetProcessorTicksPerSecond() const{uint64 ticks = GetProcessorTickCount();- std::chrono::high_resolution_clock::time_point time = std::chrono::high_resolution_clock::now();+ uint64 micros = std::chrono::duration_cast<std::chrono::microseconds>(std::chrono::high_resolution_clock::now().time_since_epoch()).count();- return (ticks - mReferenceTick) * 1000000000ULL / std::chrono::duration_cast<std::chrono::nanoseconds>(time - mReferenceTime).count();+ return (ticks - mReferenceTick) * 1000000ULL / (micros - mReferenceTime);}// This function assumes that none of the threads are active while we're dumping the profile,diff --git a/thirdparty/jolt_physics/Jolt/Core/Profiler.h b/thirdparty/jolt_physics/Jolt/Core/Profiler.hindex 8926485560d..93cacf50756 100644--- a/thirdparty/jolt_physics/Jolt/Core/Profiler.h+++ b/thirdparty/jolt_physics/Jolt/Core/Profiler.h@@ -6,12 +6,11 @@JPH_SUPPRESS_WARNINGS_STD_BEGIN#include <mutex>-#include <chrono>JPH_SUPPRESS_WARNINGS_STD_END#include <Jolt/Core/NonCopyable.h>#include <Jolt/Core/TickCounter.h>-#include <Jolt/Core/UnorderedMap.h>+#include <Jolt/Core/UnorderedMapFwd.h>#if defined(JPH_EXTERNAL_PROFILE)@@ -176,7 +175,7 @@ private:std::mutex mLock; ///< Lock that protects mThreadsuint64 mReferenceTick; ///< Tick count at the start of the frame- std::chrono::high_resolution_clock::time_point mReferenceTime; ///< Time at the start of the frame+ uint64 mReferenceTime; ///< Time at the start of the frame in microsecondsArray<ProfileThread *> mThreads; ///< List of all active threadsbool mDump = false; ///< When true, the samples are dumped next frameString mDumpTag; ///< When not empty, this overrides the auto incrementing number of the dump filenamediff --git a/thirdparty/jolt_physics/Jolt/Core/RISCVVector.h b/thirdparty/jolt_physics/Jolt/Core/RISCVVector.hnew file mode 100644index 00000000000..405dfee895a--- /dev/null+++ b/thirdparty/jolt_physics/Jolt/Core/RISCVVector.h@@ -0,0 +1,111 @@+// Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)+// SPDX-FileCopyrightText: 2026 Jorrit Rouwe+// SPDX-License-Identifier: MIT++#pragma once++JPH_NAMESPACE_BEGIN++#ifdef JPH_USE_RVV++template <unsigned IndexX, unsigned IndexY, unsigned IndexZ, unsigned IndexW>+JPH_INLINE vfloat32m1_t RVVShuffleFloat32x4(vfloat32m1_t inV0, vfloat32m1_t inV1)+{+ vfloat32m2_t combined = __riscv_vlmul_ext_v_f32m1_f32m2(inV0);+ combined = __riscv_vslideup_vx_f32m2(combined, __riscv_vlmul_ext_v_f32m1_f32m2(inV1), 4, 8);++ const uint32 indices_raw[4] = { IndexX, IndexY, IndexZ, IndexW };+ const vuint32m1_t v_indices_m1 = __riscv_vle32_v_u32m1(indices_raw, 4);+ const vuint32m2_t v_indices_m2 = __riscv_vlmul_ext_v_u32m1_u32m2(v_indices_m1);++ const vfloat32m2_t gathered_m2 = __riscv_vrgather_vv_f32m2(combined, v_indices_m2, 4);+ return __riscv_vlmul_trunc_v_f32m2_f32m1(gathered_m2);+}++template <>+JPH_INLINE vfloat32m1_t RVVShuffleFloat32x4<0, 1, 2, 3>(vfloat32m1_t inV0, vfloat32m1_t inV1)+{+ return inV0;+}++template <>+JPH_INLINE vfloat32m1_t RVVShuffleFloat32x4<0, 1, 4, 5>(vfloat32m1_t inV0, vfloat32m1_t inV1)+{+ vfloat32m1_t result = inV0;+ return __riscv_vslideup_vx_f32m1(result, inV1, 2, 4);+}++template <>+JPH_INLINE vfloat32m1_t RVVShuffleFloat32x4<1, 0, 3, 2>(vfloat32m1_t inV0, vfloat32m1_t inV1)+{+ // Avoids m2 extension overhead that the default implementation of RVVShuffleFloat32x4 has+ const uint32 indices_raw[4] = { 1, 0, 3, 2 };+ const vuint32m1_t indices = __riscv_vle32_v_u32m1(indices_raw, 4);+ return __riscv_vrgather_vv_f32m1(inV0, indices, 4);+}++template <>+JPH_INLINE vfloat32m1_t RVVShuffleFloat32x4<2, 3, 0, 1>(vfloat32m1_t inV0, vfloat32m1_t inV1)+{+ vfloat32m1_t upper = __riscv_vslidedown_vx_f32m1(inV0, 2, 4);+ return __riscv_vslideup_vx_f32m1(upper, inV0, 2, 4);+}++template <>+JPH_INLINE vfloat32m1_t RVVShuffleFloat32x4<2, 3, 6, 7>(vfloat32m1_t inV0, vfloat32m1_t inV1)+{+ return __riscv_vslidedown_vx_f32m1_tu(inV1, inV0, 2, 2);+}++template <>+JPH_INLINE vfloat32m1_t RVVShuffleFloat32x4<4, 5, 6, 7>(vfloat32m1_t inV0, vfloat32m1_t inV1)+{+ return inV1;+}++template <>+JPH_INLINE vfloat32m1_t RVVShuffleFloat32x4<0, 2, 4, 6>(vfloat32m1_t inV0, vfloat32m1_t inV1)+{+ vfloat32m2_t combined = __riscv_vlmul_ext_v_f32m1_f32m2(inV0);+ combined = __riscv_vslideup_vx_f32m2(combined, __riscv_vlmul_ext_v_f32m1_f32m2(inV1), 4, 8);++ vuint64m2_t combined_u64 = __riscv_vreinterpret_v_u32m2_u64m2(__riscv_vreinterpret_v_f32m2_u32m2(combined));++ // vnsrl extracts lower 32 bits from all 4 u64 elements -> [0, 2, 4, 6]+ vuint32m1_t result = __riscv_vnsrl_wx_u32m1(combined_u64, 0, 4);++ return __riscv_vreinterpret_v_u32m1_f32m1(result);+}++template <>+JPH_INLINE vfloat32m1_t RVVShuffleFloat32x4<1, 3, 5, 7>(vfloat32m1_t inV0, vfloat32m1_t inV1)+{+ vfloat32m2_t combined = __riscv_vlmul_ext_v_f32m1_f32m2(inV0);+ combined = __riscv_vslideup_vx_f32m2(combined, __riscv_vlmul_ext_v_f32m1_f32m2(inV1), 4, 8);++ vuint64m2_t combined_u64 = __riscv_vreinterpret_v_u32m2_u64m2(__riscv_vreinterpret_v_f32m2_u32m2(combined));++ // vnsrl with shift=32 extracts upper 32 bits from all 4 u64 elements -> [1, 3, 5, 7]+ vuint32m1_t result = __riscv_vnsrl_wx_u32m1(combined_u64, 32, 4);++ return __riscv_vreinterpret_v_u32m1_f32m1(result);+}++/// Given inV = (a, b, c, d), calculates (a + b) + (c + d) when cross platform determinism is on, otherwise calculates a + b + c + d (order undefined)+JPH_INLINE vfloat32m1_t RVVSumElementsFloat32x4(vfloat32m1_t inV)+{+#ifdef JPH_CROSS_PLATFORM_DETERMINISTIC+ const vfloat32m1_t shift1 = __riscv_vslidedown_vx_f32m1(inV, 1, 4);+ const vfloat32m1_t sum_pairs = __riscv_vfadd_vv_f32m1(inV, shift1, 4);+ const vfloat32m1_t shift2 = __riscv_vslidedown_vx_f32m1(sum_pairs, 2, 4);+ const vfloat32m1_t sum = __riscv_vfadd_vv_f32m1(sum_pairs, shift2, 4);+#else+ const vfloat32m1_t zeros = __riscv_vfmv_v_f_f32m1(0.0f, 4);+ const vfloat32m1_t sum = __riscv_vfredusum_vs_f32m1_f32m1(inV, zeros, 4);+#endif+ return sum;+}++#endif // JPH_USE_RVV++JPH_NAMESPACE_ENDdiff --git a/thirdparty/jolt_physics/Jolt/Core/RTTI.h b/thirdparty/jolt_physics/Jolt/Core/RTTI.hindex 90f358cbd58..3957747d638 100644--- a/thirdparty/jolt_physics/Jolt/Core/RTTI.h+++ b/thirdparty/jolt_physics/Jolt/Core/RTTI.h@@ -195,18 +195,18 @@ protected:#define JPH_DECLARE_RTTI_NON_VIRTUAL(linkage, class_name) \public: \JPH_OVERRIDE_NEW_DELETE \- friend linkage RTTI * GetRTTIOfType(class_name *); \- friend inline const RTTI * GetRTTI([[maybe_unused]] const class_name *inObject) { return GetRTTIOfType(static_cast<class_name *>(nullptr)); }\- static void sCreateRTTI(RTTI &inRTTI); \+ friend linkage JPH::RTTI * GetRTTIOfType(class_name *); \+ friend inline const JPH::RTTI *GetRTTI([[maybe_unused]] const class_name *inObject) { return GetRTTIOfType(static_cast<class_name *>(nullptr)); } \+ static void sCreateRTTI(JPH::RTTI &inRTTI); \// JPH_IMPLEMENT_RTTI_NON_VIRTUAL#define JPH_IMPLEMENT_RTTI_NON_VIRTUAL(class_name) \- RTTI * GetRTTIOfType(class_name *) \+ JPH::RTTI * GetRTTIOfType(class_name *) \{ \- static RTTI rtti(#class_name, sizeof(class_name), []() -> void * { return new class_name; }, [](void *inObject) { delete (class_name *)inObject; }, &class_name::sCreateRTTI); \+ static JPH::RTTI rtti(#class_name, sizeof(class_name), []() -> void * { return new class_name; }, [](void *inObject) { delete (class_name *)inObject; }, &class_name::sCreateRTTI); \return &rtti; \} \- void class_name::sCreateRTTI(RTTI &inRTTI) \+ void class_name::sCreateRTTI(JPH::RTTI &inRTTI) \//////////////////////////////////////////////////////////////////////////////////////////// Same as above, but when you cannot insert the declaration in the class@@ -215,18 +215,18 @@ public: \// JPH_DECLARE_RTTI_OUTSIDE_CLASS#define JPH_DECLARE_RTTI_OUTSIDE_CLASS(linkage, class_name) \- linkage RTTI * GetRTTIOfType(class_name *); \- inline const RTTI * GetRTTI(const class_name *inObject) { return GetRTTIOfType((class_name *)nullptr); }\- void CreateRTTI##class_name(RTTI &inRTTI); \+ linkage JPH::RTTI * GetRTTIOfType(class_name *); \+ inline const JPH::RTTI * GetRTTI(const class_name *inObject) { return GetRTTIOfType((class_name *)nullptr); }\+ void CreateRTTI##class_name(JPH::RTTI &inRTTI); \// JPH_IMPLEMENT_RTTI_OUTSIDE_CLASS#define JPH_IMPLEMENT_RTTI_OUTSIDE_CLASS(class_name) \- RTTI * GetRTTIOfType(class_name *) \+ JPH::RTTI * GetRTTIOfType(class_name *) \{ \- static RTTI rtti((const char *)#class_name, sizeof(class_name), []() -> void * { return new class_name; }, [](void *inObject) { delete (class_name *)inObject; }, &CreateRTTI##class_name); \+ static JPH::RTTI rtti((const char *)#class_name, sizeof(class_name), []() -> void * { return new class_name; }, [](void *inObject) { delete (class_name *)inObject; }, &CreateRTTI##class_name); \return &rtti; \} \- void CreateRTTI##class_name(RTTI &inRTTI)+ void CreateRTTI##class_name(JPH::RTTI &inRTTI)//////////////////////////////////////////////////////////////////////////////////////////// Same as above, but for classes that have virtual functions@@ -235,11 +235,11 @@ public: \#define JPH_DECLARE_RTTI_HELPER(linkage, class_name, modifier) \public: \JPH_OVERRIDE_NEW_DELETE \- friend linkage RTTI * GetRTTIOfType(class_name *); \- friend inline const RTTI * GetRTTI(const class_name *inObject) { return inObject->GetRTTI(); } \- virtual const RTTI * GetRTTI() const modifier; \- virtual const void * CastTo(const RTTI *inRTTI) const modifier; \- static void sCreateRTTI(RTTI &inRTTI); \+ friend linkage JPH::RTTI * GetRTTIOfType(class_name *); \+ friend inline const JPH::RTTI *GetRTTI(const class_name *inObject) { return inObject->GetRTTI(); } \+ virtual const JPH::RTTI * GetRTTI() const modifier; \+ virtual const void * CastTo(const JPH::RTTI *inRTTI) const modifier; \+ static void sCreateRTTI(JPH::RTTI &inRTTI); \// JPH_DECLARE_RTTI_VIRTUAL - for derived classes with RTTI#define JPH_DECLARE_RTTI_VIRTUAL(linkage, class_name) \@@ -247,20 +247,20 @@ public: \// JPH_IMPLEMENT_RTTI_VIRTUAL#define JPH_IMPLEMENT_RTTI_VIRTUAL(class_name) \- RTTI * GetRTTIOfType(class_name *) \+ JPH::RTTI * GetRTTIOfType(class_name *) \{ \- static RTTI rtti(#class_name, sizeof(class_name), []() -> void * { return new class_name; }, [](void *inObject) { delete (class_name *)inObject; }, &class_name::sCreateRTTI); \+ static JPH::RTTI rtti(#class_name, sizeof(class_name), []() -> void * { return new class_name; }, [](void *inObject) { delete (class_name *)inObject; }, &class_name::sCreateRTTI); \return &rtti; \} \- const RTTI * class_name::GetRTTI() const \+ const JPH::RTTI * class_name::GetRTTI() const \{ \return JPH_RTTI(class_name); \} \- const void * class_name::CastTo(const RTTI *inRTTI) const \+ const void * class_name::CastTo(const JPH::RTTI *inRTTI) const \{ \return JPH_RTTI(class_name)->CastTo((const void *)this, inRTTI); \} \- void class_name::sCreateRTTI(RTTI &inRTTI) \+ void class_name::sCreateRTTI(JPH::RTTI &inRTTI) \// JPH_DECLARE_RTTI_VIRTUAL_BASE - for concrete base class that has RTTI#define JPH_DECLARE_RTTI_VIRTUAL_BASE(linkage, class_name) \@@ -276,20 +276,20 @@ public: \// JPH_IMPLEMENT_RTTI_ABSTRACT#define JPH_IMPLEMENT_RTTI_ABSTRACT(class_name) \- RTTI * GetRTTIOfType(class_name *) \+ JPH::RTTI * GetRTTIOfType(class_name *) \{ \- static RTTI rtti(#class_name, sizeof(class_name), nullptr, [](void *inObject) { delete (class_name *)inObject; }, &class_name::sCreateRTTI); \+ static JPH::RTTI rtti(#class_name, sizeof(class_name), nullptr, [](void *inObject) { delete (class_name *)inObject; }, &class_name::sCreateRTTI); \return &rtti; \} \- const RTTI * class_name::GetRTTI() const \+ const JPH::RTTI * class_name::GetRTTI() const \{ \return JPH_RTTI(class_name); \} \- const void * class_name::CastTo(const RTTI *inRTTI) const \+ const void * class_name::CastTo(const JPH::RTTI *inRTTI) const \{ \return JPH_RTTI(class_name)->CastTo((const void *)this, inRTTI); \} \- void class_name::sCreateRTTI(RTTI &inRTTI) \+ void class_name::sCreateRTTI(JPH::RTTI &inRTTI) \// JPH_DECLARE_RTTI_ABSTRACT_BASE - for abstract base class that has RTTI#define JPH_DECLARE_RTTI_ABSTRACT_BASE(linkage, class_name) \@@ -304,12 +304,12 @@ public: \//////////////////////////////////////////////////////////////////////////////////////////#define JPH_DECLARE_RTTI_FOR_FACTORY(linkage, class_name) \- linkage RTTI * GetRTTIOfType(class class_name *);+ linkage JPH::RTTI * GetRTTIOfType(class class_name *);#define JPH_DECLARE_RTTI_WITH_NAMESPACE_FOR_FACTORY(linkage, name_space, class_name) \namespace name_space { \class class_name; \- linkage RTTI * GetRTTIOfType(class class_name *); \+ linkage JPH::RTTI * GetRTTIOfType(class class_name *); \}//////////////////////////////////////////////////////////////////////////////////////////@@ -335,7 +335,7 @@ public: \///////////////////////////////////////////////////////////////////////////////////////////// Define very dirty macro to get the offset of a baseclass into a class-#define JPH_BASE_CLASS_OFFSET(inClass, inBaseClass) ((int(uint64((inBaseClass *)((inClass *)0x10000))))-0x10000)+#define JPH_BASE_CLASS_OFFSET(inClass, inBaseClass) ((int(JPH::uint64((inBaseClass *)((inClass *)0x10000))))-0x10000)// JPH_ADD_BASE_CLASS#define JPH_ADD_BASE_CLASS(class_name, base_class_name) \diff --git a/thirdparty/jolt_physics/Jolt/Core/Reference.h b/thirdparty/jolt_physics/Jolt/Core/Reference.hindex 8a2de696865..03137fa04dd 100644--- a/thirdparty/jolt_physics/Jolt/Core/Reference.h+++ b/thirdparty/jolt_physics/Jolt/Core/Reference.h@@ -61,7 +61,8 @@ public:{#ifndef JPH_TSAN_ENABLED// Releasing a reference must use release semantics...- if (mRefCount.fetch_sub(1, memory_order_release) == 1)+ uint32 old_value = mRefCount.fetch_sub(1, memory_order_release);+ if (old_value == 1){// ... so that we can use acquire to ensure that we see any updates from other threads that released a ref before deleting the objectatomic_thread_fence(memory_order_acquire);@@ -69,9 +70,11 @@ public:}#else// But under TSAN, we cannot use atomic_thread_fence, so we use an acq_rel operation unconditionally instead- if (mRefCount.fetch_sub(1, memory_order_acq_rel) == 1)+ uint32 old_value = mRefCount.fetch_sub(1, memory_order_acq_rel);+ if (old_value == 1)delete static_cast<const T *>(this);#endif+ JPH_ASSERT(old_value != 0 && old_value != cEmbedded, "Too many calls to Release");}/// INTERNAL HELPER FUNCTION USED BY SERIALIZATIONdiff --git a/thirdparty/jolt_physics/Jolt/Core/Result.h b/thirdparty/jolt_physics/Jolt/Core/Result.hindex 282b35adbb0..22124998379 100644--- a/thirdparty/jolt_physics/Jolt/Core/Result.h+++ b/thirdparty/jolt_physics/Jolt/Core/Result.h@@ -8,7 +8,7 @@ JPH_NAMESPACE_BEGIN/// Helper class that either contains a valid result or an errortemplate <class Type>-class Result+class [[nodiscard]] Result{public:/// Default constructordiff --git a/thirdparty/jolt_physics/Jolt/Core/Semaphore.cpp b/thirdparty/jolt_physics/Jolt/Core/Semaphore.cppindex ee7c31a9058..233257a8210 100644--- a/thirdparty/jolt_physics/Jolt/Core/Semaphore.cpp+++ b/thirdparty/jolt_physics/Jolt/Core/Semaphore.cpp@@ -5,21 +5,7 @@#include <Jolt/Jolt.h>#include <Jolt/Core/Semaphore.h>--#ifdef JPH_PLATFORM_WINDOWS- JPH_SUPPRESS_WARNING_PUSH- JPH_MSVC_SUPPRESS_WARNING(5039) // winbase.h(13179): warning C5039: 'TpSetCallbackCleanupGroup': pointer or reference to potentially throwing function passed to 'extern "C"' function under -EHc. Undefined behavior may occur if this function throws an exception.- JPH_MSVC2026_PLUS_SUPPRESS_WARNING(4865) // wingdi.h(2806,1): '<unnamed-enum-DISPLAYCONFIG_OUTPUT_TECHNOLOGY_OTHER>': the underlying type will change from 'int' to '__int64' when '/Zc:enumTypes' is specified on the command line-#ifndef WIN32_LEAN_AND_MEAN- #define WIN32_LEAN_AND_MEAN- #endif-#ifndef JPH_COMPILER_MINGW- #include <Windows.h>-#else- #include <windows.h>-#endif- JPH_SUPPRESS_WARNING_POP-#endif+#include <Jolt/Core/IncludeWindows.h>JPH_NAMESPACE_BEGINdiff --git a/thirdparty/jolt_physics/Jolt/Core/StaticArray.h b/thirdparty/jolt_physics/Jolt/Core/StaticArray.hindex 421bf680f59..254c7f09a9f 100644--- a/thirdparty/jolt_physics/Jolt/Core/StaticArray.h+++ b/thirdparty/jolt_physics/Jolt/Core/StaticArray.h@@ -20,7 +20,7 @@ public:static constexpr uint Capacity = N;/// Default constructor- StaticArray() = default;+ StaticArray() { /* We specifically don't want to initialize the union */ }/// Constructor from initializer listexplicit StaticArray(std::initializer_list<T> inList)@@ -296,16 +296,12 @@ public:}protected:- struct alignas(T) Storage+ size_type mSize = 0;+ union // Prevent constructors from being called for mElements{- uint8 mData[sizeof(T)];+ T mElements[N];+ uint8 mDummy;};-- static_assert(sizeof(T) == sizeof(Storage), "Mismatch in size");- static_assert(alignof(T) == alignof(Storage), "Mismatch in alignment");-- size_type mSize = 0;- Storage mElements[N];};JPH_NAMESPACE_ENDdiff --git a/thirdparty/jolt_physics/Jolt/Core/StreamUtils.h b/thirdparty/jolt_physics/Jolt/Core/StreamUtils.hindex 1feb232f350..5717e5224c1 100644--- a/thirdparty/jolt_physics/Jolt/Core/StreamUtils.h+++ b/thirdparty/jolt_physics/Jolt/Core/StreamUtils.h@@ -7,6 +7,7 @@#include <Jolt/Core/Result.h>#include <Jolt/Core/StreamIn.h>#include <Jolt/Core/StreamOut.h>+#include <Jolt/Core/ObjectToIDMap.h>#include <Jolt/Core/UnorderedMap.h>#include <Jolt/Core/Factory.h>@@ -14,12 +15,6 @@ JPH_NAMESPACE_BEGINnamespace StreamUtils {-template <class Type>-using ObjectToIDMap = UnorderedMap<const Type *, uint32>;--template <class Type>-using IDToObjectMap = Array<Ref<Type>>;-// Restore a single object by reading the hash of the type, constructing it and then calling the restore functiontemplate <class Type>Result<Ref<Type>> RestoreObject(StreamIn &inStream, void (Type::*inRestoreBinaryStateFunction)(StreamIn &))diff --git a/thirdparty/jolt_physics/Jolt/Core/StridedPtr.h b/thirdparty/jolt_physics/Jolt/Core/StridedPtr.hindex 1cf97fa6783..43858cb57e2 100644--- a/thirdparty/jolt_physics/Jolt/Core/StridedPtr.h+++ b/thirdparty/jolt_physics/Jolt/Core/StridedPtr.h@@ -10,7 +10,7 @@ JPH_NAMESPACE_BEGIN/// elements that the pointer points to can be part of a larger structure./// The stride gives the number of bytes from one element to the next.template <class T>-class JPH_EXPORT StridedPtr+class StridedPtr{public:using value_type = T;diff --git a/thirdparty/jolt_physics/Jolt/Core/TickCounter.cpp b/thirdparty/jolt_physics/Jolt/Core/TickCounter.cppindex 133e1cc3e3e..cb4b1d8cf90 100644--- a/thirdparty/jolt_physics/Jolt/Core/TickCounter.cpp+++ b/thirdparty/jolt_physics/Jolt/Core/TickCounter.cpp@@ -5,21 +5,7 @@#include <Jolt/Jolt.h>#include <Jolt/Core/TickCounter.h>--#if defined(JPH_PLATFORM_WINDOWS)- JPH_SUPPRESS_WARNING_PUSH- JPH_MSVC_SUPPRESS_WARNING(5039) // winbase.h(13179): warning C5039: 'TpSetCallbackCleanupGroup': pointer or reference to potentially throwing function passed to 'extern "C"' function under -EHc. Undefined behavior may occur if this function throws an exception.- JPH_MSVC2026_PLUS_SUPPRESS_WARNING(4865) // wingdi.h(2806,1): '<unnamed-enum-DISPLAYCONFIG_OUTPUT_TECHNOLOGY_OTHER>': the underlying type will change from 'int' to '__int64' when '/Zc:enumTypes' is specified on the command line-#ifndef WIN32_LEAN_AND_MEAN- #define WIN32_LEAN_AND_MEAN- #endif-#ifndef JPH_COMPILER_MINGW- #include <Windows.h>-#else- #include <windows.h>-#endif- JPH_SUPPRESS_WARNING_POP-#endif+#include <Jolt/Core/IncludeWindows.h>JPH_NAMESPACE_BEGINdiff --git a/thirdparty/jolt_physics/Jolt/Core/UnorderedMap.h b/thirdparty/jolt_physics/Jolt/Core/UnorderedMap.hindex 236eaaa69f2..fa50454344c 100644--- a/thirdparty/jolt_physics/Jolt/Core/UnorderedMap.h+++ b/thirdparty/jolt_physics/Jolt/Core/UnorderedMap.h@@ -5,6 +5,7 @@#pragma once#include <Jolt/Core/HashTable.h>+#include <Jolt/Core/UnorderedMapFwd.h>JPH_NAMESPACE_BEGIN@@ -25,7 +26,7 @@ public:/// @tparam Value Value type/// @tparam Hash Hash function (note should be 64-bits)/// @tparam KeyEqual Equality comparison function-template <class Key, class Value, class Hash = JPH::Hash<Key>, class KeyEqual = std::equal_to<Key>>+template <class Key, class Value, class Hash, class KeyEqual>class UnorderedMap : public HashTable<Key, std::pair<Key, Value>, UnorderedMapDetail<Key, Value>, Hash, KeyEqual>{using Base = HashTable<Key, std::pair<Key, Value>, UnorderedMapDetail<Key, Value>, Hash, KeyEqual>;diff --git a/thirdparty/jolt_physics/Jolt/Core/UnorderedMapFwd.h b/thirdparty/jolt_physics/Jolt/Core/UnorderedMapFwd.hnew file mode 100644index 00000000000..50222604c42--- /dev/null+++ b/thirdparty/jolt_physics/Jolt/Core/UnorderedMapFwd.h@@ -0,0 +1,14 @@+// Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)+// SPDX-FileCopyrightText: 2026 Jorrit Rouwe+// SPDX-License-Identifier: MIT++#pragma once++JPH_NAMESPACE_BEGIN++// Forward declaration of UnorderedMap (defined in UnorderedMap.h).+// This is provided because compiling UnorderedMap.h can be expensive due to its use of templates.+template <class Key, class Value, class Hash = JPH::Hash<Key>, class KeyEqual = std::equal_to<Key>>+class UnorderedMap;++JPH_NAMESPACE_ENDdiff --git a/thirdparty/jolt_physics/Jolt/Core/UnorderedSet.h b/thirdparty/jolt_physics/Jolt/Core/UnorderedSet.hindex a3202554435..0a18873939b 100644--- a/thirdparty/jolt_physics/Jolt/Core/UnorderedSet.h+++ b/thirdparty/jolt_physics/Jolt/Core/UnorderedSet.h@@ -5,6 +5,7 @@#pragma once#include <Jolt/Core/HashTable.h>+#include <Jolt/Core/UnorderedSetFwd.h>JPH_NAMESPACE_BEGIN@@ -24,7 +25,7 @@ public:/// @tparam Key Key type/// @tparam Hash Hash function (note should be 64-bits)/// @tparam KeyEqual Equality comparison function-template <class Key, class Hash = JPH::Hash<Key>, class KeyEqual = std::equal_to<Key>>+template <class Key, class Hash, class KeyEqual>class UnorderedSet : public HashTable<Key, Key, UnorderedSetDetail<Key>, Hash, KeyEqual>{};diff --git a/thirdparty/jolt_physics/Jolt/Core/UnorderedSetFwd.h b/thirdparty/jolt_physics/Jolt/Core/UnorderedSetFwd.hnew file mode 100644index 00000000000..f3161cc3b14--- /dev/null+++ b/thirdparty/jolt_physics/Jolt/Core/UnorderedSetFwd.h@@ -0,0 +1,14 @@+// Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)+// SPDX-FileCopyrightText: 2026 Jorrit Rouwe+// SPDX-License-Identifier: MIT++#pragma once++JPH_NAMESPACE_BEGIN++// Forward declaration of UnorderedSet (defined in UnorderedSet.h).+// This is provided because compiling UnorderedSet.h can be expensive due to its use of templates.+template <class Key, class Hash = JPH::Hash<Key>, class KeyEqual = std::equal_to<Key>>+class UnorderedSet;++JPH_NAMESPACE_ENDdiff --git a/thirdparty/jolt_physics/Jolt/Geometry/ClosestPoint.h b/thirdparty/jolt_physics/Jolt/Geometry/ClosestPoint.hindex a437763f574..12d4ca0318b 100644--- a/thirdparty/jolt_physics/Jolt/Geometry/ClosestPoint.h+++ b/thirdparty/jolt_physics/Jolt/Geometry/ClosestPoint.h@@ -6,9 +6,6 @@JPH_NAMESPACE_BEGIN-// Turn off fused multiply add instruction because it makes the equations of the form a * b - c * d inaccurate below-JPH_PRECISE_MATH_ON-/// Helper utils to find the closest point to a line segment, triangle or tetrahedronnamespace ClosestPoint{@@ -69,7 +66,7 @@ namespace ClosestPoint// Denominator must be positive:// |v0|^2 * |v1|^2 - (v0 . v1)^2 = |v0|^2 * |v1|^2 * (1 - cos(angle)^2) >= 0- float denominator = d00 * d11 - d01 * d01;+ float denominator = DifferenceOfProducts(d00, d11, d01, d01);if (denominator < 1.0e-12f){// Degenerate triangle, return coordinates along longest edge@@ -89,8 +86,8 @@ namespace ClosestPoint{float a0 = inA.Dot(v0);float a1 = inA.Dot(v1);- outV = (d01 * a1 - d11 * a0) / denominator;- outW = (d01 * a0 - d00 * a1) / denominator;+ outV = DifferenceOfProducts(d01, a1, d11, a0) / denominator;+ outW = DifferenceOfProducts(d01, a0, d00, a1) / denominator;outU = 1.0f - outV - outW;}}@@ -99,7 +96,7 @@ namespace ClosestPoint// Use v1 and v2 to calculate barycentric coordinatesfloat d12 = v1.Dot(v2);- float denominator = d11 * d22 - d12 * d12;+ float denominator = DifferenceOfProducts(d11, d22, d12, d12);if (denominator < 1.0e-12f){// Degenerate triangle, return coordinates along longest edge@@ -119,8 +116,8 @@ namespace ClosestPoint{float c1 = inC.Dot(v1);float c2 = inC.Dot(v2);- outU = (d22 * c1 - d12 * c2) / denominator;- outV = (d11 * c2 - d12 * c1) / denominator;+ outU = DifferenceOfProducts(d22, c1, d12, c2) / denominator;+ outV = DifferenceOfProducts(d11, c2, d12, c1) / denominator;outW = 1.0f - outU - outV;}}@@ -166,12 +163,12 @@ namespace ClosestPoint// See: https://box2d.org/posts/2014/01/troublesome-triangle/// The difference in normals is most pronounced when one edge is much smaller than the others (in which case the other 2 must have roughly the same length).// Therefore we can suffice by just picking the shortest from 2 edges and use that with the 3rd edge to calculate the normal.- // We first check which of the edges is shorter and if bc is shorter than ac then we swap a with c to a is always on the shortest edge+ // In this case we ensure that ab is shorter than bc by swapping a and c if it is not.UVec4 swap_ac;{- Vec3 ac = inC - inA;+ Vec3 ba = inA - inB;Vec3 bc = inC - inB;- swap_ac = Vec4::sLess(bc.DotV4(bc), ac.DotV4(ac));+ swap_ac = Vec4::sLess(bc.DotV4(bc), ba.DotV4(ba));}Vec3 a = Vec3::sSelect(inA, inC, swap_ac);Vec3 c = Vec3::sSelect(inC, inA, swap_ac);@@ -179,7 +176,7 @@ namespace ClosestPoint// Calculate normalVec3 ab = inB - a;Vec3 ac = c - a;- Vec3 n = ab.Cross(ac);+ Vec3 n = ab.CrossPrecise(ac);float n_len_sq = n.LengthSq();// Check degenerate@@ -343,7 +340,7 @@ namespace ClosestPoint// With p = 0// Test if point p and d lie on opposite sides of plane through abc- Vec3 n = (inB - inA).Cross(inC - inA);+ Vec3 n = (inB - inA).CrossPrecise(inC - inA);float signp = inA.Dot(n); // [AP AB AC]float signd = (inD - inA).Dot(n); // [AD AB AC]@@ -367,10 +364,10 @@ namespace ClosestPointVec3 bd = inD - inB;Vec3 bc = inC - inB;- Vec3 ab_cross_ac = ab.Cross(ac);- Vec3 ac_cross_ad = ac.Cross(ad);- Vec3 ad_cross_ab = ad.Cross(ab);- Vec3 bd_cross_bc = bd.Cross(bc);+ Vec3 ab_cross_ac = ab.CrossPrecise(ac);+ Vec3 ac_cross_ad = ac.CrossPrecise(ad);+ Vec3 ad_cross_ab = ad.CrossPrecise(ab);+ Vec3 bd_cross_bc = bd.CrossPrecise(bc);// For each plane get the side on which the origin isfloat signp0 = inA.Dot(ab_cross_ac); // ABC@@ -493,6 +490,4 @@ namespace ClosestPoint}};-JPH_PRECISE_MATH_OFF-JPH_NAMESPACE_ENDdiff --git a/thirdparty/jolt_physics/Jolt/Geometry/ConvexHullBuilder.cpp b/thirdparty/jolt_physics/Jolt/Geometry/ConvexHullBuilder.cppindex e15c0912ffd..1d1cb6f63d8 100644--- a/thirdparty/jolt_physics/Jolt/Geometry/ConvexHullBuilder.cpp+++ b/thirdparty/jolt_physics/Jolt/Geometry/ConvexHullBuilder.cpp@@ -402,7 +402,7 @@ ConvexHullBuilder::EResult ConvexHullBuilder::Initialize(int inMaxVertices, floa}// Check if the hull is coplanar- if (Square(max_dist) <= 25.0f * coplanar_tolerance_sq)+ if (Square(max_dist) <= Square(cCoplanarSlopFactor) * coplanar_tolerance_sq){// First project all points in 2D spaceVec3 base1 = initial_plane_normal.GetNormalizedPerpendicular();@@ -1330,7 +1330,7 @@ void ConvexHullBuilder::DetermineMaxError(Face *&outFaceWithMaxError, float &outfloat normal_len = f->mNormal.Length();JPH_ASSERT(normal_len > 0.0f);float plane_dist = f->mNormal.Dot(v - f->mCentroid) / normal_len;- if (plane_dist > -outCoplanarDistance)+ if (plane_dist > -cCoplanarSlopFactor * outCoplanarDistance){// Check distance to the edges of this facefloat edge_dist_sq = GetDistanceToEdgeSq(v, f);@@ -1351,7 +1351,7 @@ void ConvexHullBuilder::DetermineMaxError(Face *&outFaceWithMaxError, float &out}// If the minimum distance to an edge is further than our current max error, we use that as max error- float min_edge_dist = sqrt(min_edge_dist_sq);+ float min_edge_dist = Sqrt(min_edge_dist_sq);if (min_edge_dist_face != nullptr && min_edge_dist > max_error){max_error = min_edge_dist;diff --git a/thirdparty/jolt_physics/Jolt/Geometry/ConvexHullBuilder.h b/thirdparty/jolt_physics/Jolt/Geometry/ConvexHullBuilder.hindex db1ef358d16..bd6ff1aa155 100644--- a/thirdparty/jolt_physics/Jolt/Geometry/ConvexHullBuilder.h+++ b/thirdparty/jolt_physics/Jolt/Geometry/ConvexHullBuilder.h@@ -133,6 +133,9 @@ private:/// Minimal square area of a triangle (used for merging and checking if a triangle is degenerate)static constexpr float cMinTriangleAreaSq = 1.0e-12f;+ /// Extra slop used to determine if the hull is coplanar / a point is on a face.+ static constexpr float cCoplanarSlopFactor = 6.0f;+#ifdef JPH_CONVEX_BUILDER_DEBUG/// Factor to scale convex hull when debug drawing the construction processstatic constexpr Real cDrawScale = 10;diff --git a/thirdparty/jolt_physics/Jolt/Geometry/EPAConvexHullBuilder.h b/thirdparty/jolt_physics/Jolt/Geometry/EPAConvexHullBuilder.hindex 15d61b068bd..4df8d7ee77e 100644--- a/thirdparty/jolt_physics/Jolt/Geometry/EPAConvexHullBuilder.h+++ b/thirdparty/jolt_physics/Jolt/Geometry/EPAConvexHullBuilder.h@@ -707,8 +707,6 @@ private:#endif};-// The determinant that is calculated in the Triangle constructor is really sensitive-// to numerical round off, disable the fmadd instructions to maintain precision.JPH_PRECISE_MATH_ONEPAConvexHullBuilder::Triangle::Triangle(int inIdx0, int inIdx1, int inIdx2, const Vec3 *inPositions)@@ -747,7 +745,7 @@ EPAConvexHullBuilder::Triangle::Triangle(int inIdx0, int inIdx1, int inIdx2, conif (y20_dot_y20 < y21_dot_y21){// We select the edges y10 and y20- mNormal = y10.Cross(y20);+ mNormal = y10.CrossPrecise(y20);// Check if triangle is degeneratefloat normal_len_sq = mNormal.LengthSq();@@ -775,13 +773,13 @@ EPAConvexHullBuilder::Triangle::Triangle(int inIdx0, int inIdx1, int inIdx2, con// Cramers rule to invert matrix:float y10_dot_y10 = y10.LengthSq();float y10_dot_y20 = y10.Dot(y20);- float determinant = y10_dot_y10 * y20_dot_y20 - y10_dot_y20 * y10_dot_y20;+ float determinant = DifferenceOfProducts(y10_dot_y10, y20_dot_y20, y10_dot_y20, y10_dot_y20);if (determinant > 0.0f) // If determinant == 0 then the system is linearly dependent and the triangle is degenerate, since y10.10 * y20.y20 > y10.y20^2 it should also be > 0{float y0_dot_y10 = y0.Dot(y10);float y0_dot_y20 = y0.Dot(y20);- float l0 = (y10_dot_y20 * y0_dot_y20 - y20_dot_y20 * y0_dot_y10) / determinant;- float l1 = (y10_dot_y20 * y0_dot_y10 - y10_dot_y10 * y0_dot_y20) / determinant;+ float l0 = DifferenceOfProducts(y10_dot_y20, y0_dot_y20, y20_dot_y20, y0_dot_y10) / determinant;+ float l1 = DifferenceOfProducts(y10_dot_y20, y0_dot_y10, y10_dot_y10, y0_dot_y20) / determinant;mLambda[0] = l0;mLambda[1] = l1;mLambdaRelativeTo0 = true;@@ -797,7 +795,7 @@ EPAConvexHullBuilder::Triangle::Triangle(int inIdx0, int inIdx1, int inIdx2, conelse{// We select the edges y10 and y21- mNormal = y10.Cross(y21);+ mNormal = y10.CrossPrecise(y21);// Check if triangle is degeneratefloat normal_len_sq = mNormal.LengthSq();@@ -821,13 +819,13 @@ EPAConvexHullBuilder::Triangle::Triangle(int inIdx0, int inIdx1, int inIdx2, con// Cramers rule to invert matrix:float y10_dot_y10 = y10.LengthSq();float y10_dot_y21 = y10.Dot(y21);- float determinant = y10_dot_y10 * y21_dot_y21 - y10_dot_y21 * y10_dot_y21;+ float determinant = DifferenceOfProducts(y10_dot_y10, y21_dot_y21, y10_dot_y21, y10_dot_y21);if (determinant > 0.0f){float y1_dot_y10 = y1.Dot(y10);float y1_dot_y21 = y1.Dot(y21);- float l0 = (y21_dot_y21 * y1_dot_y10 - y10_dot_y21 * y1_dot_y21) / determinant;- float l1 = (y10_dot_y21 * y1_dot_y10 - y10_dot_y10 * y1_dot_y21) / determinant;+ float l0 = DifferenceOfProducts(y21_dot_y21, y1_dot_y10, y10_dot_y21, y1_dot_y21) / determinant;+ float l1 = DifferenceOfProducts(y10_dot_y21, y1_dot_y10, y10_dot_y10, y1_dot_y21) / determinant;mLambda[0] = l0;mLambda[1] = l1;mLambdaRelativeTo0 = false;diff --git a/thirdparty/jolt_physics/Jolt/Geometry/EPAPenetrationDepth.h b/thirdparty/jolt_physics/Jolt/Geometry/EPAPenetrationDepth.hindex 87696bb968e..086fcc7d422 100644--- a/thirdparty/jolt_physics/Jolt/Geometry/EPAPenetrationDepth.h+++ b/thirdparty/jolt_physics/Jolt/Geometry/EPAPenetrationDepth.h@@ -124,7 +124,7 @@ public:if (closest_points_dist_sq > 0.0f){// Collision within convex radius, adjust points for convex radius- float v_len = sqrt(closest_points_dist_sq); // GetClosestPoints function returns |ioV|^2 when return value < FLT_MAX+ float v_len = Sqrt(closest_points_dist_sq); // GetClosestPoints function returns |ioV|^2 when return value < FLT_MAXoutPointA += ioV * (inConvexRadiusA / v_len);outPointB -= ioV * (inConvexRadiusB / v_len);return EStatus::Colliding;diff --git a/thirdparty/jolt_physics/Jolt/Geometry/RayTriangle.h b/thirdparty/jolt_physics/Jolt/Geometry/RayTriangle.hindex 42dc921d760..a081cf187bd 100644--- a/thirdparty/jolt_physics/Jolt/Geometry/RayTriangle.h+++ b/thirdparty/jolt_physics/Jolt/Geometry/RayTriangle.h@@ -22,7 +22,7 @@ JPH_INLINE float RayTriangle(Vec3Arg inOrigin, Vec3Arg inDirection, Vec3Arg inV0Vec3 e2 = inV2 - inV0;// Begin calculating determinant - also used to calculate u parameter- Vec3 p = inDirection.Cross(e2);+ Vec3 p = inDirection.CrossPrecise(e2);// if determinant is near zero, ray lies in plane of triangleVec3 det = Vec3::sReplicate(e1.Dot(p));@@ -40,7 +40,7 @@ JPH_INLINE float RayTriangle(Vec3Arg inOrigin, Vec3Arg inDirection, Vec3Arg inV0Vec3 u = Vec3::sReplicate(s.Dot(p)) / det;// Prepare to test v parameter- Vec3 q = s.Cross(e1);+ Vec3 q = s.CrossPrecise(e1);// Calculate v parameterVec3 v = Vec3::sReplicate(inDirection.Dot(q)) / det;@@ -95,9 +95,9 @@ JPH_INLINE Vec4 RayTriangle4(Vec3Arg inOrigin, Vec3Arg inDirection, Vec4Arg inV0Vec4 dz = inDirection.SplatZ();// Begin calculating determinant - also used to calculate u parameter- Vec4 px = dy * e2z - dz * e2y;- Vec4 py = dz * e2x - dx * e2z;- Vec4 pz = dx * e2y - dy * e2x;+ Vec4 px = Vec4::sDifferenceOfProducts(dy, e2z, dz, e2y);+ Vec4 py = Vec4::sDifferenceOfProducts(dz, e2x, dx, e2z);+ Vec4 pz = Vec4::sDifferenceOfProducts(dx, e2y, dy, e2x);// if determinant is near zero, ray lies in plane of triangleVec4 det = e1x * px + e1y * py + e1z * pz;@@ -121,9 +121,9 @@ JPH_INLINE Vec4 RayTriangle4(Vec3Arg inOrigin, Vec3Arg inDirection, Vec4Arg inV0Vec4 u = Vec4::sXor(sx * px + sy * py + sz * pz, det_sign);// Prepare to test v parameter- Vec4 qx = sy * e1z - sz * e1y;- Vec4 qy = sz * e1x - sx * e1z;- Vec4 qz = sx * e1y - sy * e1x;+ Vec4 qx = Vec4::sDifferenceOfProducts(sy, e1z, sz, e1y);+ Vec4 qy = Vec4::sDifferenceOfProducts(sz, e1x, sx, e1z);+ Vec4 qz = Vec4::sDifferenceOfProducts(sx, e1y, sy, e1x);// Calculate v parameter and flip sign if determinant was negativeVec4 v = Vec4::sXor(dx * qx + dy * qy + dz * qz, det_sign);diff --git a/thirdparty/jolt_physics/Jolt/Geometry/Sphere.h b/thirdparty/jolt_physics/Jolt/Geometry/Sphere.hindex 05f7dd14f37..3f7b9b98963 100644--- a/thirdparty/jolt_physics/Jolt/Geometry/Sphere.h+++ b/thirdparty/jolt_physics/Jolt/Geometry/Sphere.h@@ -52,7 +52,7 @@ public:{// It is further away than radius, we need to widen the sphere// The diameter of the new sphere is radius + d, so the new radius is half of that- float d = sqrt(d_sq);+ float d = Sqrt(d_sq);float radius = 0.5f * (mRadius + d);// The center needs to shift by new radius - old radius in the direction of ddiff --git a/thirdparty/jolt_physics/Jolt/Jolt.h b/thirdparty/jolt_physics/Jolt/Jolt.hindex acc400ce9e3..7c9359358ad 100644--- a/thirdparty/jolt_physics/Jolt/Jolt.h+++ b/thirdparty/jolt_physics/Jolt/Jolt.h@@ -7,6 +7,7 @@// Project includes#include <Jolt/Core/Core.h>#include <Jolt/Core/ARMNeon.h>+#include <Jolt/Core/RISCVVector.h>#include <Jolt/Core/Memory.h>#include <Jolt/Core/IssueReporting.h>#include <Jolt/Core/Array.h>diff --git a/thirdparty/jolt_physics/Jolt/Jolt.natvis b/thirdparty/jolt_physics/Jolt/Jolt.natvisindex d183d95b5a5..b6093032acf 100644--- a/thirdparty/jolt_physics/Jolt/Jolt.natvis+++ b/thirdparty/jolt_physics/Jolt/Jolt.natvis@@ -68,7 +68,7 @@<DisplayString>min=({mMin}), max=({mMax})</DisplayString></Type><Type Name="JPH::BodyID">- <DisplayString>idx={mID & 0x007fffff}, seq={(mID >> 23) & 0xff}, in_bp={mID >> 24,d}</DisplayString>+ <DisplayString>idx={mID & 0x007fffff}, seq={(mID >> 23) & 0xff}, bp={mID >> 31,d}</DisplayString></Type><Type Name="JPH::Body"><DisplayString>{mDebugName}: p=({mPosition.mF32[0],g}, {mPosition.mF32[1],g}, {mPosition.mF32[2],g}), r=({mRotation.mValue.mF32[0],g}, {mRotation.mValue.mF32[1],g}, {mRotation.mValue.mF32[2],g}, {mRotation.mValue.mF32[3],g}), v=({mLinearVelocity.mF32[0],g}, {mLinearVelocity.mF32[1],g}, {mLinearVelocity.mF32[2],g}), w=({mAngularVelocity.mF32[0],g}, {mAngularVelocity.mF32[1],g}, {mAngularVelocity.mF32[2],g})</DisplayString>@@ -82,7 +82,7 @@<Item Name="[size]" ExcludeView="simple">mSize</Item><ArrayItems><Size>mSize</Size>- <ValuePointer>(value_type *)mElements</ValuePointer>+ <ValuePointer>mElements</ValuePointer></ArrayItems></Expand></Type>diff --git a/thirdparty/jolt_physics/Jolt/Math/BVec16.h b/thirdparty/jolt_physics/Jolt/Math/BVec16.hindex a4ac12bf79d..4c87bbab8e4 100644--- a/thirdparty/jolt_physics/Jolt/Math/BVec16.h+++ b/thirdparty/jolt_physics/Jolt/Math/BVec16.h@@ -92,7 +92,7 @@ public:};};-static_assert(std::is_trivial<BVec16>(), "Is supposed to be a trivial type!");+static_assert(std::is_trivially_default_constructible<BVec16>() && std::is_trivially_copyable<BVec16>(), "Is supposed to be a trivial type!");JPH_NAMESPACE_ENDdiff --git a/thirdparty/jolt_physics/Jolt/Math/DMat44.h b/thirdparty/jolt_physics/Jolt/Math/DMat44.hindex cf585c8f3bd..220f121ac9d 100644--- a/thirdparty/jolt_physics/Jolt/Math/DMat44.h+++ b/thirdparty/jolt_physics/Jolt/Math/DMat44.h@@ -151,7 +151,7 @@ private:DVec3 mCol3; ///< Translation column, 4th element is assumed to be 1};-static_assert(std::is_trivial<DMat44>(), "Is supposed to be a trivial type!");+static_assert(std::is_trivially_default_constructible<DMat44>() && std::is_trivially_copyable<DMat44>(), "Is supposed to be a trivial type!");JPH_NAMESPACE_ENDdiff --git a/thirdparty/jolt_physics/Jolt/Math/DMat44.inl b/thirdparty/jolt_physics/Jolt/Math/DMat44.inlindex 462cf79114c..208555fddbb 100644--- a/thirdparty/jolt_physics/Jolt/Math/DMat44.inl+++ b/thirdparty/jolt_physics/Jolt/Math/DMat44.inl@@ -87,6 +87,26 @@ DVec3 DMat44::operator * (Vec3Arg inV) constfloat64x2_t low = vaddq_f64(mCol3.mValue.val[0], vcvt_f64_f32(vget_low_f32(t)));float64x2_t high = vaddq_f64(mCol3.mValue.val[1], vcvt_high_f64_f32(t));return DVec3::sFixW({ low, high });+#elif defined(JPH_USE_RVV)+ const vfloat32m1_t v0 = __riscv_vfmv_v_f_f32m1(inV.mF32[0], 4);+ const vfloat32m1_t v1 = __riscv_vfmv_v_f_f32m1(inV.mF32[1], 4);+ const vfloat32m1_t v2 = __riscv_vfmv_v_f_f32m1(inV.mF32[2], 4);++ const vfloat32m1_t col0 = __riscv_vle32_v_f32m1(mCol[0].mF32, 4);+ const vfloat32m1_t col1 = __riscv_vle32_v_f32m1(mCol[1].mF32, 4);+ const vfloat32m1_t col2 = __riscv_vle32_v_f32m1(mCol[2].mF32, 4);+ const vfloat64m2_t col3 = __riscv_vle64_v_f64m2(mCol3.mF64, 4);++ vfloat32m1_t t = __riscv_vfmul_vv_f32m1(col0, v0, 4);+ t = __riscv_vfmacc_vv_f32m1(t, col1, v1, 4);+ t = __riscv_vfmacc_vv_f32m1(t, col2, v2, 4);++ vfloat64m2_t t_f64 = __riscv_vfwcvt_f_f_v_f64m2(t, 4);+ t_f64 = __riscv_vfadd_vv_f64m2(t_f64, col3, 4);++ DVec3 v;+ __riscv_vse64_v_f64m2(v.mF64, t_f64, 4);+ return DVec3::sFixW(v.mValue);#elsereturn DVec3(mCol3.mF64[0] + double(mCol[0].mF32[0] * inV.mF32[0] + mCol[1].mF32[0] * inV.mF32[1] + mCol[2].mF32[0] * inV.mF32[2]),@@ -130,6 +150,29 @@ DVec3 DMat44::operator * (DVec3Arg inV) constt_high = vaddq_f64(t_high, vmulq_f64(vcvt_high_f64_f32(col1), yyyy));t_high = vaddq_f64(t_high, vmulq_f64(vcvt_high_f64_f32(col2), zzzz));return DVec3::sFixW({ t_low, t_high });+#elif defined(JPH_USE_RVV)+ const vfloat64m2_t xxxx = __riscv_vfmv_v_f_f64m2(inV.mF64[0], 4);+ const vfloat64m2_t yyyy = __riscv_vfmv_v_f_f64m2(inV.mF64[1], 4);+ const vfloat64m2_t zzzz = __riscv_vfmv_v_f_f64m2(inV.mF64[2], 4);++ const vfloat32m1_t col0_f32 = __riscv_vle32_v_f32m1(mCol[0].mF32, 4);+ const vfloat32m1_t col1_f32 = __riscv_vle32_v_f32m1(mCol[1].mF32, 4);+ const vfloat32m1_t col2_f32 = __riscv_vle32_v_f32m1(mCol[2].mF32, 4);++ const vfloat64m2_t col0 = __riscv_vfwcvt_f_f_v_f64m2(col0_f32, 4);+ const vfloat64m2_t col1 = __riscv_vfwcvt_f_f_v_f64m2(col1_f32, 4);+ const vfloat64m2_t col2 = __riscv_vfwcvt_f_f_v_f64m2(col2_f32, 4);++ const vfloat64m2_t col3 = __riscv_vle64_v_f64m2(mCol3.mF64, 4);++ vfloat64m2_t t = __riscv_vfmul_vv_f64m2(col0, xxxx, 4);+ t = __riscv_vfmacc_vv_f64m2(t, col1, yyyy, 4);+ t = __riscv_vfmacc_vv_f64m2(t, col2, zzzz, 4);+ t = __riscv_vfadd_vv_f64m2(t, col3, 4);++ DVec3 v;+ __riscv_vse64_v_f64m2(v.mF64, t, 4);+ return DVec3::sFixW(v.mValue);#elsereturn DVec3(mCol3.mF64[0] + double(mCol[0].mF32[0]) * inV.mF64[0] + double(mCol[1].mF32[0]) * inV.mF64[1] + double(mCol[2].mF32[0]) * inV.mF64[2],@@ -173,6 +216,26 @@ DVec3 DMat44::Multiply3x3(DVec3Arg inV) constt_high = vaddq_f64(t_high, vmulq_f64(vcvt_high_f64_f32(col1), yyyy));t_high = vaddq_f64(t_high, vmulq_f64(vcvt_high_f64_f32(col2), zzzz));return DVec3::sFixW({ t_low, t_high });+#elif defined(JPH_USE_RVV)+ const vfloat64m2_t xxxx = __riscv_vfmv_v_f_f64m2(inV.mF64[0], 4);+ const vfloat64m2_t yyyy = __riscv_vfmv_v_f_f64m2(inV.mF64[1], 4);+ const vfloat64m2_t zzzz = __riscv_vfmv_v_f_f64m2(inV.mF64[2], 4);++ const vfloat32m1_t col0 = __riscv_vle32_v_f32m1(mCol[0].mF32, 4);+ const vfloat32m1_t col1 = __riscv_vle32_v_f32m1(mCol[1].mF32, 4);+ const vfloat32m1_t col2 = __riscv_vle32_v_f32m1(mCol[2].mF32, 4);++ const vfloat64m2_t col0_f64 = __riscv_vfwcvt_f_f_v_f64m2(col0, 4);+ const vfloat64m2_t col1_f64 = __riscv_vfwcvt_f_f_v_f64m2(col1, 4);+ const vfloat64m2_t col2_f64 = __riscv_vfwcvt_f_f_v_f64m2(col2, 4);++ vfloat64m2_t t = __riscv_vfmul_vv_f64m2(col0_f64, xxxx, 4);+ t = __riscv_vfmacc_vv_f64m2(t, col1_f64, yyyy, 4);+ t = __riscv_vfmacc_vv_f64m2(t, col2_f64, zzzz, 4);++ DVec3::Type v;+ __riscv_vse64_v_f64m2(v.mData, t, 4);+ return DVec3::sFixW(v);#elsereturn DVec3(double(mCol[0].mF32[0]) * inV.mF64[0] + double(mCol[1].mF32[0]) * inV.mF64[1] + double(mCol[2].mF32[0]) * inV.mF64[2],@@ -204,6 +267,23 @@ DMat44 DMat44::operator * (Mat44Arg inM) constt = vmlaq_f32(t, mCol[2].mValue, vdupq_laneq_f32(c, 2));result.mCol[i].mValue = t;}+#elif defined(JPH_USE_RVV)+ const vfloat32m1_t col0 = __riscv_vle32_v_f32m1(mCol[0].mF32, 4);+ const vfloat32m1_t col1 = __riscv_vle32_v_f32m1(mCol[1].mF32, 4);+ const vfloat32m1_t col2 = __riscv_vle32_v_f32m1(mCol[2].mF32, 4);++ for (int i = 0; i < 3; ++i)+ {+ const Vec4 v = inM.GetColumn4(i);+ const vfloat32m1_t v0 = __riscv_vfmv_v_f_f32m1(v.mF32[0], 4);+ const vfloat32m1_t v1 = __riscv_vfmv_v_f_f32m1(v.mF32[1], 4);+ const vfloat32m1_t v2 = __riscv_vfmv_v_f_f32m1(v.mF32[2], 4);++ vfloat32m1_t t = __riscv_vfmul_vv_f32m1(v0, col0, 4);+ t = __riscv_vfmacc_vv_f32m1(t, col1, v1, 4);+ t = __riscv_vfmacc_vv_f32m1(t, col2, v2, 4);+ __riscv_vse32_v_f32m1(result.mCol[i].mF32, t, 4);+ }#elsefor (int i = 0; i < 3; ++i){@@ -241,6 +321,23 @@ DMat44 DMat44::operator * (DMat44Arg inM) constt = vmlaq_f32(t, mCol[2].mValue, vdupq_laneq_f32(c, 2));result.mCol[i].mValue = t;}+#elif defined(JPH_USE_RVV)+ const vfloat32m1_t col0 = __riscv_vle32_v_f32m1(mCol[0].mF32, 4);+ const vfloat32m1_t col1 = __riscv_vle32_v_f32m1(mCol[1].mF32, 4);+ const vfloat32m1_t col2 = __riscv_vle32_v_f32m1(mCol[2].mF32, 4);++ for (int i = 0; i < 3; ++i)+ {+ const float *col_i = inM.mCol[i].mF32;+ const vfloat32m1_t v0 = __riscv_vfmv_v_f_f32m1(col_i[0], 4);+ const vfloat32m1_t v1 = __riscv_vfmv_v_f_f32m1(col_i[1], 4);+ const vfloat32m1_t v2 = __riscv_vfmv_v_f_f32m1(col_i[2], 4);++ vfloat32m1_t t = __riscv_vfmul_vv_f32m1(v0, col0, 4);+ t = __riscv_vfmacc_vv_f32m1(t, col1, v1, 4);+ t = __riscv_vfmacc_vv_f32m1(t, col2, v2, 4);+ __riscv_vse32_v_f32m1(result.mCol[i].mF32, t, 4);+ }#elsefor (int i = 0; i < 3; ++i){@@ -270,7 +367,7 @@ DMat44 DMat44::PreScaled(Vec3Arg inScale) constDMat44 DMat44::PostScaled(Vec3Arg inScale) const{Vec4 scale(inScale, 1);- return DMat44(scale * mCol[0], scale * mCol[1], scale * mCol[2], DVec3(scale) * mCol3);+ return DMat44(scale * mCol[0], scale * mCol[1], scale * mCol[2], DVec3(inScale) * mCol3);}DMat44 DMat44::PreTranslated(Vec3Arg inTranslation) constdiff --git a/thirdparty/jolt_physics/Jolt/Math/DVec3.h b/thirdparty/jolt_physics/Jolt/Math/DVec3.hindex b2f9019911c..9c9395f402d 100644--- a/thirdparty/jolt_physics/Jolt/Math/DVec3.h+++ b/thirdparty/jolt_physics/Jolt/Math/DVec3.h@@ -274,8 +274,8 @@ public:static JPH_INLINE Type sFixW(TypeArg inValue);/// Representations of true and false for boolean operations- inline static const double cTrue = BitCast<double>(~uint64(0));- inline static const double cFalse = 0.0;+ inline static constexpr double cTrue = BitCast<double>(~uint64(0));+ inline static constexpr double cFalse = 0.0;union{@@ -284,7 +284,7 @@ public:};};-static_assert(std::is_trivial<DVec3>(), "Is supposed to be a trivial type!");+static_assert(std::is_trivially_default_constructible<DVec3>() && std::is_trivially_copyable<DVec3>(), "Is supposed to be a trivial type!");JPH_NAMESPACE_ENDdiff --git a/thirdparty/jolt_physics/Jolt/Math/DVec3.inl b/thirdparty/jolt_physics/Jolt/Math/DVec3.inlindex fd18db40951..a9efa90ff26 100644--- a/thirdparty/jolt_physics/Jolt/Math/DVec3.inl+++ b/thirdparty/jolt_physics/Jolt/Math/DVec3.inl@@ -21,6 +21,10 @@ DVec3::DVec3(Vec3Arg inRHS)#elif defined(JPH_USE_NEON)mValue.val[0] = vcvt_f64_f32(vget_low_f32(inRHS.mValue));mValue.val[1] = vcvt_high_f64_f32(inRHS.mValue);+#elif defined(JPH_USE_RVV)+ const vfloat32m1_t src = __riscv_vle32_v_f32m1(inRHS.mF32, 3);+ const vfloat64m2_t widened = __riscv_vfwcvt_f_f_v_f64m2(src, 3);+ __riscv_vse64_v_f64m2(mF64, widened, 3);#elsemF64[0] = (double)inRHS.GetX();mF64[1] = (double)inRHS.GetY();@@ -46,6 +50,11 @@ DVec3::DVec3(double inX, double inY, double inZ)#elif defined(JPH_USE_NEON)mValue.val[0] = vcombine_f64(vcreate_f64(BitCast<uint64>(inX)), vcreate_f64(BitCast<uint64>(inY)));mValue.val[1] = vdupq_n_f64(inZ);+#elif defined(JPH_USE_RVV)+ vfloat64m2_t v = __riscv_vfmv_v_f_f64m2(inZ, 4);+ v = __riscv_vfslide1up_vf_f64m2(v, inY, 4);+ v = __riscv_vfslide1up_vf_f64m2(v, inX, 4);+ __riscv_vse64_v_f64m2(mF64, v, 4);#elsemF64[0] = inX;mF64[1] = inY;@@ -70,6 +79,9 @@ DVec3::DVec3(const Double3 &inV)#elif defined(JPH_USE_NEON)mValue.val[0] = vld1q_f64(&inV.x);mValue.val[1] = vdupq_n_f64(inV.z);+#elif defined(JPH_USE_RVV)+ vfloat64m2_t v = __riscv_vle64_v_f64m2(&inV.x, 3);+ __riscv_vse64_v_f64m2(mF64, v, 3);#elsemF64[0] = inV.x;mF64[1] = inV.y;@@ -104,6 +116,12 @@ DVec3::Type DVec3::sFixW(TypeArg inValue)value.val[0] = inValue.val[0];value.val[1] = vdupq_laneq_f64(inValue.val[1], 0);return value;+ #elif defined(JPH_USE_RVV)+ Type value;+ const vfloat64m2_t buffer = __riscv_vle64_v_f64m2(inValue.mData, 3);+ __riscv_vse64_v_f64m2(value.mData, buffer, 3);+ value.mData[3] = value.mData[2];+ return value;#elseType value;value.mData[0] = inValue.mData[0];@@ -127,6 +145,11 @@ DVec3 DVec3::sZero()#elif defined(JPH_USE_NEON)float64x2_t zero = vdupq_n_f64(0.0);return DVec3({ zero, zero });+#elif defined(JPH_USE_RVV)+ DVec3 vec;+ const vfloat64m2_t v = __riscv_vfmv_v_f_f64m2(0.0, 3);+ __riscv_vse64_v_f64m2(vec.mF64, v, 3);+ return vec;#elsereturn DVec3(0, 0, 0);#endif@@ -142,6 +165,11 @@ DVec3 DVec3::sReplicate(double inV)#elif defined(JPH_USE_NEON)float64x2_t value = vdupq_n_f64(inV);return DVec3({ value, value });+#elif defined(JPH_USE_RVV)+ DVec3 vec;+ const vfloat64m2_t v = __riscv_vfmv_v_f_f64m2(inV, 3);+ __riscv_vse64_v_f64m2(vec.mF64, v, 3);+ return vec;#elsereturn DVec3(inV, inV, inV);#endif@@ -167,6 +195,10 @@ DVec3 DVec3::sLoadDouble3Unsafe(const Double3 &inV)v.mHigh = _mm_set1_pd(inV.z);#elif defined(JPH_USE_NEON)Type v = vld1q_f64_x2(&inV.x);+#elif defined(JPH_USE_RVV)+ Type v;+ const vfloat64m2_t vec = __riscv_vle64_v_f64m2(&inV.x, 3);+ __riscv_vse64_v_f64m2(v.mData, vec, 3);#elseType v = { inV.x, inV.y, inV.z };#endif@@ -175,9 +207,23 @@ DVec3 DVec3::sLoadDouble3Unsafe(const Double3 &inV)void DVec3::StoreDouble3(Double3 *outV) const{+#if defined(JPH_USE_AVX)+ _mm_storeu_pd(&outV->x, _mm256_castpd256_pd128(mValue));+ outV->z = mF64[2];+#elif defined(JPH_USE_SSE)+ _mm_storeu_pd(&outV->x, mValue.mLow);+ outV->z = mF64[2];+#elif defined(JPH_USE_NEON)+ vst1q_f64(&outV->x, mValue.val[0]);+ outV->z = mF64[2];+#elif defined(JPH_USE_RVV)+ const vfloat64m2_t v = __riscv_vle64_v_f64m2(mF64, 3);+ __riscv_vse64_v_f64m2(&outV->x, v, 3);+#elseoutV->x = mF64[0];outV->y = mF64[1];outV->z = mF64[2];+#endif}DVec3::operator Vec3() const@@ -188,8 +234,14 @@ DVec3::operator Vec3() const__m128 low = _mm_cvtpd_ps(mValue.mLow);__m128 high = _mm_cvtpd_ps(mValue.mHigh);return _mm_shuffle_ps(low, high, _MM_SHUFFLE(1, 0, 1, 0));-#elif defined(JPH_USE_NEON)- return vcvt_high_f32_f64(vcvtx_f32_f64(mValue.val[0]), mValue.val[1]);+#elif defined(JPH_USE_NEON) && !defined(JPH_COMPILER_MSVC) // Disabled on MSVC because of internal compiler error: https://developercommunity.visualstudio.com/t/ARM64-NEON-vcvt_f32_f64-with-fp:fast-tr/11088003+ return vcvt_high_f32_f64(vcvt_f32_f64(mValue.val[0]), mValue.val[1]);+#elif defined(JPH_USE_RVV)+ Vec3 v;+ const vfloat64m2_t src = __riscv_vle64_v_f64m2(mF64, 3);+ const vfloat32m1_t narrowed = __riscv_vfncvt_f_f_w_f32m1(src, 3);+ __riscv_vse32_v_f32m1(v.mF32, narrowed, 3);+ return v;#elsereturn Vec3((float)GetX(), (float)GetY(), (float)GetZ());#endif@@ -203,6 +255,13 @@ DVec3 DVec3::sMin(DVec3Arg inV1, DVec3Arg inV2)return DVec3({ _mm_min_pd(inV1.mValue.mLow, inV2.mValue.mLow), _mm_min_pd(inV1.mValue.mHigh, inV2.mValue.mHigh) });#elif defined(JPH_USE_NEON)return DVec3({ vminq_f64(inV1.mValue.val[0], inV2.mValue.val[0]), vminq_f64(inV1.mValue.val[1], inV2.mValue.val[1]) });+#elif defined(JPH_USE_RVV)+ DVec3 res;+ const vfloat64m2_t v1 = __riscv_vle64_v_f64m2(inV1.mF64, 3);+ const vfloat64m2_t v2 = __riscv_vle64_v_f64m2(inV2.mF64, 3);+ const vfloat64m2_t min = __riscv_vfmin_vv_f64m2(v1, v2, 3);+ __riscv_vse64_v_f64m2(res.mF64, min, 3);+ return res;#elsereturn DVec3(min(inV1.mF64[0], inV2.mF64[0]),min(inV1.mF64[1], inV2.mF64[1]),@@ -218,6 +277,13 @@ DVec3 DVec3::sMax(DVec3Arg inV1, DVec3Arg inV2)return DVec3({ _mm_max_pd(inV1.mValue.mLow, inV2.mValue.mLow), _mm_max_pd(inV1.mValue.mHigh, inV2.mValue.mHigh) });#elif defined(JPH_USE_NEON)return DVec3({ vmaxq_f64(inV1.mValue.val[0], inV2.mValue.val[0]), vmaxq_f64(inV1.mValue.val[1], inV2.mValue.val[1]) });+#elif defined(JPH_USE_RVV)+ DVec3 res;+ const vfloat64m2_t v1 = __riscv_vle64_v_f64m2(inV1.mF64, 3);+ const vfloat64m2_t v2 = __riscv_vle64_v_f64m2(inV2.mF64, 3);+ const vfloat64m2_t max = __riscv_vfmax_vv_f64m2(v1, v2, 3);+ __riscv_vse64_v_f64m2(res.mF64, max, 3);+ return res;#elsereturn DVec3(max(inV1.mF64[0], inV2.mF64[0]),max(inV1.mF64[1], inV2.mF64[1]),@@ -238,6 +304,15 @@ DVec3 DVec3::sEquals(DVec3Arg inV1, DVec3Arg inV2)return DVec3({ _mm_cmpeq_pd(inV1.mValue.mLow, inV2.mValue.mLow), _mm_cmpeq_pd(inV1.mValue.mHigh, inV2.mValue.mHigh) });#elif defined(JPH_USE_NEON)return DVec3({ vreinterpretq_f64_u64(vceqq_f64(inV1.mValue.val[0], inV2.mValue.val[0])), vreinterpretq_f64_u64(vceqq_f64(inV1.mValue.val[1], inV2.mValue.val[1])) });+#elif defined(JPH_USE_RVV)+ DVec3 res;+ const vfloat64m2_t v1 = __riscv_vle64_v_f64m2(inV1.mF64, 3);+ const vfloat64m2_t v2 = __riscv_vle64_v_f64m2(inV2.mF64, 3);+ const vbool32_t mask = __riscv_vmfeq_vv_f64m2_b32(v1, v2, 3);+ const vfloat64m2_t zeros = __riscv_vfmv_v_f_f64m2(cFalse, 3);+ const vfloat64m2_t merged = __riscv_vfmerge_vfm_f64m2(zeros, cTrue, mask, 3);+ __riscv_vse64_v_f64m2(res.mF64, merged, 3);+ return res;#elsereturn DVec3(inV1.mF64[0] == inV2.mF64[0]? cTrue : cFalse,inV1.mF64[1] == inV2.mF64[1]? cTrue : cFalse,@@ -253,6 +328,15 @@ DVec3 DVec3::sLess(DVec3Arg inV1, DVec3Arg inV2)return DVec3({ _mm_cmplt_pd(inV1.mValue.mLow, inV2.mValue.mLow), _mm_cmplt_pd(inV1.mValue.mHigh, inV2.mValue.mHigh) });#elif defined(JPH_USE_NEON)return DVec3({ vreinterpretq_f64_u64(vcltq_f64(inV1.mValue.val[0], inV2.mValue.val[0])), vreinterpretq_f64_u64(vcltq_f64(inV1.mValue.val[1], inV2.mValue.val[1])) });+#elif defined(JPH_USE_RVV)+ DVec3 res;+ const vfloat64m2_t v1 = __riscv_vle64_v_f64m2(inV1.mF64, 3);+ const vfloat64m2_t v2 = __riscv_vle64_v_f64m2(inV2.mF64, 3);+ const vbool32_t mask = __riscv_vmflt_vv_f64m2_b32(v1, v2, 3);+ const vfloat64m2_t zeros = __riscv_vfmv_v_f_f64m2(cFalse, 3);+ const vfloat64m2_t merged = __riscv_vfmerge_vfm_f64m2(zeros, cTrue, mask, 3);+ __riscv_vse64_v_f64m2(res.mF64, merged, 3);+ return res;#elsereturn DVec3(inV1.mF64[0] < inV2.mF64[0]? cTrue : cFalse,inV1.mF64[1] < inV2.mF64[1]? cTrue : cFalse,@@ -268,6 +352,15 @@ DVec3 DVec3::sLessOrEqual(DVec3Arg inV1, DVec3Arg inV2)return DVec3({ _mm_cmple_pd(inV1.mValue.mLow, inV2.mValue.mLow), _mm_cmple_pd(inV1.mValue.mHigh, inV2.mValue.mHigh) });#elif defined(JPH_USE_NEON)return DVec3({ vreinterpretq_f64_u64(vcleq_f64(inV1.mValue.val[0], inV2.mValue.val[0])), vreinterpretq_f64_u64(vcleq_f64(inV1.mValue.val[1], inV2.mValue.val[1])) });+#elif defined(JPH_USE_RVV)+ DVec3 res;+ const vfloat64m2_t v1 = __riscv_vle64_v_f64m2(inV1.mF64, 3);+ const vfloat64m2_t v2 = __riscv_vle64_v_f64m2(inV2.mF64, 3);+ const vbool32_t mask = __riscv_vmfle_vv_f64m2_b32(v1, v2, 3);+ const vfloat64m2_t zeros = __riscv_vfmv_v_f_f64m2(cFalse, 3);+ const vfloat64m2_t merged = __riscv_vfmerge_vfm_f64m2(zeros, cTrue, mask, 3);+ __riscv_vse64_v_f64m2(res.mF64, merged, 3);+ return res;#elsereturn DVec3(inV1.mF64[0] <= inV2.mF64[0]? cTrue : cFalse,inV1.mF64[1] <= inV2.mF64[1]? cTrue : cFalse,@@ -283,6 +376,15 @@ DVec3 DVec3::sGreater(DVec3Arg inV1, DVec3Arg inV2)return DVec3({ _mm_cmpgt_pd(inV1.mValue.mLow, inV2.mValue.mLow), _mm_cmpgt_pd(inV1.mValue.mHigh, inV2.mValue.mHigh) });#elif defined(JPH_USE_NEON)return DVec3({ vreinterpretq_f64_u64(vcgtq_f64(inV1.mValue.val[0], inV2.mValue.val[0])), vreinterpretq_f64_u64(vcgtq_f64(inV1.mValue.val[1], inV2.mValue.val[1])) });+#elif defined(JPH_USE_RVV)+ DVec3 res;+ const vfloat64m2_t v1 = __riscv_vle64_v_f64m2(inV1.mF64, 3);+ const vfloat64m2_t v2 = __riscv_vle64_v_f64m2(inV2.mF64, 3);+ const vbool32_t mask = __riscv_vmfgt_vv_f64m2_b32(v1, v2, 3);+ const vfloat64m2_t zeros = __riscv_vfmv_v_f_f64m2(cFalse, 3);+ const vfloat64m2_t merged = __riscv_vfmerge_vfm_f64m2(zeros, cTrue, mask, 3);+ __riscv_vse64_v_f64m2(res.mF64, merged, 3);+ return res;#elsereturn DVec3(inV1.mF64[0] > inV2.mF64[0]? cTrue : cFalse,inV1.mF64[1] > inV2.mF64[1]? cTrue : cFalse,@@ -298,6 +400,15 @@ DVec3 DVec3::sGreaterOrEqual(DVec3Arg inV1, DVec3Arg inV2)return DVec3({ _mm_cmpge_pd(inV1.mValue.mLow, inV2.mValue.mLow), _mm_cmpge_pd(inV1.mValue.mHigh, inV2.mValue.mHigh) });#elif defined(JPH_USE_NEON)return DVec3({ vreinterpretq_f64_u64(vcgeq_f64(inV1.mValue.val[0], inV2.mValue.val[0])), vreinterpretq_f64_u64(vcgeq_f64(inV1.mValue.val[1], inV2.mValue.val[1])) });+#elif defined(JPH_USE_RVV)+ DVec3 res;+ const vfloat64m2_t v1 = __riscv_vle64_v_f64m2(inV1.mF64, 3);+ const vfloat64m2_t v2 = __riscv_vle64_v_f64m2(inV2.mF64, 3);+ const vbool32_t mask = __riscv_vmfge_vv_f64m2_b32(v1, v2, 3);+ const vfloat64m2_t zeros = __riscv_vfmv_v_f_f64m2(cFalse, 3);+ const vfloat64m2_t merged = __riscv_vfmerge_vfm_f64m2(zeros, cTrue, mask, 3);+ __riscv_vse64_v_f64m2(res.mF64, merged, 3);+ return res;#elsereturn DVec3(inV1.mF64[0] >= inV2.mF64[0]? cTrue : cFalse,inV1.mF64[1] >= inV2.mF64[1]? cTrue : cFalse,@@ -307,14 +418,22 @@ DVec3 DVec3::sGreaterOrEqual(DVec3Arg inV1, DVec3Arg inV2)DVec3 DVec3::sFusedMultiplyAdd(DVec3Arg inMul1, DVec3Arg inMul2, DVec3Arg inAdd){-#if defined(JPH_USE_AVX)- #ifdef JPH_USE_FMADD+#ifdef JPH_USE_FMADD+ #ifdef JPH_USE_AVXreturn _mm256_fmadd_pd(inMul1.mValue, inMul2.mValue, inAdd.mValue);+ #elif defined(JPH_USE_NEON)+ return DVec3({ vmlaq_f64(inAdd.mValue.val[0], inMul1.mValue.val[0], inMul2.mValue.val[0]), vmlaq_f64(inAdd.mValue.val[1], inMul1.mValue.val[1], inMul2.mValue.val[1]) });+ #elif defined(JPH_USE_RVV)+ DVec3 res;+ const vfloat64m2_t v1 = __riscv_vle64_v_f64m2(inMul1.mF64, 3);+ const vfloat64m2_t v2 = __riscv_vle64_v_f64m2(inMul2.mF64, 3);+ const vfloat64m2_t rvv_add = __riscv_vle64_v_f64m2(inAdd.mF64, 3);+ const vfloat64m2_t fmadd = __riscv_vfmacc_vv_f64m2(rvv_add, v1, v2, 3);+ __riscv_vse64_v_f64m2(res.mF64, fmadd, 3);+ return res;#else- return _mm256_add_pd(_mm256_mul_pd(inMul1.mValue, inMul2.mValue), inAdd.mValue);+ return inMul1 * inMul2 + inAdd;#endif-#elif defined(JPH_USE_NEON)- return DVec3({ vmlaq_f64(inAdd.mValue.val[0], inMul1.mValue.val[0], inMul2.mValue.val[0]), vmlaq_f64(inAdd.mValue.val[1], inMul1.mValue.val[1], inMul2.mValue.val[1]) });#elsereturn inMul1 * inMul2 + inAdd;#endif@@ -331,6 +450,20 @@ DVec3 DVec3::sSelect(DVec3Arg inNotSet, DVec3Arg inSet, DVec3Arg inControl)Type v = { vbslq_f64(vreinterpretq_u64_s64(vshrq_n_s64(vreinterpretq_s64_f64(inControl.mValue.val[0]), 63)), inSet.mValue.val[0], inNotSet.mValue.val[0]),vbslq_f64(vreinterpretq_u64_s64(vshrq_n_s64(vreinterpretq_s64_f64(inControl.mValue.val[1]), 63)), inSet.mValue.val[1], inNotSet.mValue.val[1]) };return sFixW(v);+#elif defined(JPH_USE_RVV)+ DVec3 masked;+ const vfloat64m2_t control_double = __riscv_vle64_v_f64m2(inControl.mF64, 3);+ const vfloat64m2_t not_set = __riscv_vle64_v_f64m2(inNotSet.mF64, 3);+ const vfloat64m2_t set = __riscv_vle64_v_f64m2(inSet.mF64, 3);+ const vuint64m2_t control = __riscv_vreinterpret_v_f64m2_u64m2(control_double);++ // Generate RVV bool mask from UVec4+ const uint64 sign_bit_mask = 0x8000000000000000u;+ const vuint64m2_t r = __riscv_vand_vx_u64m2(control, sign_bit_mask, 3);+ const vbool32_t rvv_mask = __riscv_vmsne_vx_u64m2_b32(r, 0x0, 3);+ const vfloat64m2_t merged = __riscv_vmerge_vvm_f64m2(not_set, set, rvv_mask, 3);+ __riscv_vse64_v_f64m2(masked.mF64, merged, 3);+ return masked;#elseDVec3 result;for (int i = 0; i < 3; i++)@@ -351,6 +484,13 @@ DVec3 DVec3::sOr(DVec3Arg inV1, DVec3Arg inV2)#elif defined(JPH_USE_NEON)return DVec3({ vreinterpretq_f64_u64(vorrq_u64(vreinterpretq_u64_f64(inV1.mValue.val[0]), vreinterpretq_u64_f64(inV2.mValue.val[0]))),vreinterpretq_f64_u64(vorrq_u64(vreinterpretq_u64_f64(inV1.mValue.val[1]), vreinterpretq_u64_f64(inV2.mValue.val[1]))) });+#elif defined(JPH_USE_RVV)+ DVec3 or_result;+ const vuint64m2_t v1 = __riscv_vle64_v_u64m2(reinterpret_cast<const uint64 *>(inV1.mF64), 3);+ const vuint64m2_t v2 = __riscv_vle64_v_u64m2(reinterpret_cast<const uint64 *>(inV2.mF64), 3);+ const vuint64m2_t res = __riscv_vor_vv_u64m2(v1, v2, 3);+ __riscv_vse64_v_u64m2(reinterpret_cast<uint64 *>(or_result.mF64), res, 3);+ return or_result;#elsereturn DVec3(BitCast<double>(BitCast<uint64>(inV1.mF64[0]) | BitCast<uint64>(inV2.mF64[0])),BitCast<double>(BitCast<uint64>(inV1.mF64[1]) | BitCast<uint64>(inV2.mF64[1])),@@ -367,6 +507,13 @@ DVec3 DVec3::sXor(DVec3Arg inV1, DVec3Arg inV2)#elif defined(JPH_USE_NEON)return DVec3({ vreinterpretq_f64_u64(veorq_u64(vreinterpretq_u64_f64(inV1.mValue.val[0]), vreinterpretq_u64_f64(inV2.mValue.val[0]))),vreinterpretq_f64_u64(veorq_u64(vreinterpretq_u64_f64(inV1.mValue.val[1]), vreinterpretq_u64_f64(inV2.mValue.val[1]))) });+#elif defined(JPH_USE_RVV)+ DVec3 xor_result;+ const vuint64m2_t v1 = __riscv_vle64_v_u64m2(reinterpret_cast<const uint64 *>(inV1.mF64), 3);+ const vuint64m2_t v2 = __riscv_vle64_v_u64m2(reinterpret_cast<const uint64 *>(inV2.mF64), 3);+ const vuint64m2_t res = __riscv_vxor_vv_u64m2(v1, v2, 3);+ __riscv_vse64_v_u64m2(reinterpret_cast<uint64 *>(xor_result.mF64), res, 3);+ return xor_result;#elsereturn DVec3(BitCast<double>(BitCast<uint64>(inV1.mF64[0]) ^ BitCast<uint64>(inV2.mF64[0])),BitCast<double>(BitCast<uint64>(inV1.mF64[1]) ^ BitCast<uint64>(inV2.mF64[1])),@@ -383,6 +530,13 @@ DVec3 DVec3::sAnd(DVec3Arg inV1, DVec3Arg inV2)#elif defined(JPH_USE_NEON)return DVec3({ vreinterpretq_f64_u64(vandq_u64(vreinterpretq_u64_f64(inV1.mValue.val[0]), vreinterpretq_u64_f64(inV2.mValue.val[0]))),vreinterpretq_f64_u64(vandq_u64(vreinterpretq_u64_f64(inV1.mValue.val[1]), vreinterpretq_u64_f64(inV2.mValue.val[1]))) });+#elif defined(JPH_USE_RVV)+ DVec3 and_result;+ const vuint64m2_t v1 = __riscv_vle64_v_u64m2(reinterpret_cast<const uint64 *>(inV1.mF64), 3);+ const vuint64m2_t v2 = __riscv_vle64_v_u64m2(reinterpret_cast<const uint64 *>(inV2.mF64), 3);+ const vuint64m2_t res = __riscv_vand_vv_u64m2(v1, v2, 3);+ __riscv_vse64_v_u64m2(reinterpret_cast<uint64 *>(and_result.mF64), res, 3);+ return and_result;#elsereturn DVec3(BitCast<double>(BitCast<uint64>(inV1.mF64[0]) & BitCast<uint64>(inV2.mF64[0])),BitCast<double>(BitCast<uint64>(inV1.mF64[1]) & BitCast<uint64>(inV2.mF64[1])),@@ -434,6 +588,13 @@ DVec3 DVec3::operator * (DVec3Arg inV2) constreturn DVec3({ _mm_mul_pd(mValue.mLow, inV2.mValue.mLow), _mm_mul_pd(mValue.mHigh, inV2.mValue.mHigh) });#elif defined(JPH_USE_NEON)return DVec3({ vmulq_f64(mValue.val[0], inV2.mValue.val[0]), vmulq_f64(mValue.val[1], inV2.mValue.val[1]) });+#elif defined(JPH_USE_RVV)+ DVec3 res;+ const vfloat64m2_t v1 = __riscv_vle64_v_f64m2(mF64, 3);+ const vfloat64m2_t v2 = __riscv_vle64_v_f64m2(inV2.mF64, 3);+ const vfloat64m2_t mul = __riscv_vfmul_vv_f64m2(v1, v2, 3);+ __riscv_vse64_v_f64m2(res.mF64, mul, 3);+ return res;#elsereturn DVec3(mF64[0] * inV2.mF64[0], mF64[1] * inV2.mF64[1], mF64[2] * inV2.mF64[2]);#endif@@ -448,6 +609,12 @@ DVec3 DVec3::operator * (double inV2) constreturn DVec3({ _mm_mul_pd(mValue.mLow, v), _mm_mul_pd(mValue.mHigh, v) });#elif defined(JPH_USE_NEON)return DVec3({ vmulq_n_f64(mValue.val[0], inV2), vmulq_n_f64(mValue.val[1], inV2) });+#elif defined(JPH_USE_RVV)+ DVec3 res;+ const vfloat64m2_t src = __riscv_vle64_v_f64m2(mF64, 3);+ const vfloat64m2_t mul = __riscv_vfmul_vf_f64m2(src, inV2, 3);+ __riscv_vse64_v_f64m2(res.mF64, mul, 3);+ return res;#elsereturn DVec3(mF64[0] * inV2, mF64[1] * inV2, mF64[2] * inV2);#endif@@ -462,6 +629,12 @@ DVec3 operator * (double inV1, DVec3Arg inV2)return DVec3({ _mm_mul_pd(v, inV2.mValue.mLow), _mm_mul_pd(v, inV2.mValue.mHigh) });#elif defined(JPH_USE_NEON)return DVec3({ vmulq_n_f64(inV2.mValue.val[0], inV1), vmulq_n_f64(inV2.mValue.val[1], inV1) });+#elif defined(JPH_USE_RVV)+ DVec3 res;+ const vfloat64m2_t v1 = __riscv_vle64_v_f64m2(inV2.mF64, 3);+ const vfloat64m2_t mul = __riscv_vfmul_vf_f64m2(v1, inV1, 3);+ __riscv_vse64_v_f64m2(res.mF64, mul, 3);+ return res;#elsereturn DVec3(inV1 * inV2.mF64[0], inV1 * inV2.mF64[1], inV1 * inV2.mF64[2]);#endif@@ -477,6 +650,12 @@ DVec3 DVec3::operator / (double inV2) const#elif defined(JPH_USE_NEON)float64x2_t v = vdupq_n_f64(inV2);return DVec3({ vdivq_f64(mValue.val[0], v), vdivq_f64(mValue.val[1], v) });+#elif defined(JPH_USE_RVV)+ DVec3 res;+ const vfloat64m2_t src = __riscv_vle64_v_f64m2(mF64, 3);+ const vfloat64m2_t div = __riscv_vfdiv_vf_f64m2(src, inV2, 3);+ __riscv_vse64_v_f64m2(res.mF64, div, 3);+ return res;#elsereturn DVec3(mF64[0] / inV2, mF64[1] / inV2, mF64[2] / inV2);#endif@@ -493,6 +672,10 @@ DVec3 &DVec3::operator *= (double inV2)#elif defined(JPH_USE_NEON)mValue.val[0] = vmulq_n_f64(mValue.val[0], inV2);mValue.val[1] = vmulq_n_f64(mValue.val[1], inV2);+#elif defined(JPH_USE_RVV)+ const vfloat64m2_t v1 = __riscv_vle64_v_f64m2(mF64, 3);+ const vfloat64m2_t res = __riscv_vfmul_vf_f64m2(v1, inV2, 3);+ __riscv_vse64_v_f64m2(mF64, res, 3);#elsefor (int i = 0; i < 3; ++i)mF64[i] *= inV2;@@ -513,6 +696,11 @@ DVec3 &DVec3::operator *= (DVec3Arg inV2)#elif defined(JPH_USE_NEON)mValue.val[0] = vmulq_f64(mValue.val[0], inV2.mValue.val[0]);mValue.val[1] = vmulq_f64(mValue.val[1], inV2.mValue.val[1]);+#elif defined(JPH_USE_RVV)+ const vfloat64m2_t v1 = __riscv_vle64_v_f64m2(mF64, 3);+ const vfloat64m2_t v2 = __riscv_vle64_v_f64m2(inV2.mF64, 3);+ const vfloat64m2_t rvv_res = __riscv_vfmul_vv_f64m2(v1, v2, 3);+ __riscv_vse64_v_f64m2(mF64, rvv_res, 3);#elsefor (int i = 0; i < 3; ++i)mF64[i] *= inV2.mF64[i];@@ -535,6 +723,10 @@ DVec3 &DVec3::operator /= (double inV2)float64x2_t v = vdupq_n_f64(inV2);mValue.val[0] = vdivq_f64(mValue.val[0], v);mValue.val[1] = vdivq_f64(mValue.val[1], v);+#elif defined(JPH_USE_RVV)+ const vfloat64m2_t v = __riscv_vle64_v_f64m2(mF64, 3);+ const vfloat64m2_t res = __riscv_vfdiv_vf_f64m2(v, inV2, 3);+ __riscv_vse64_v_f64m2(mF64, res, 3);#elsefor (int i = 0; i < 3; ++i)mF64[i] /= inV2;@@ -553,6 +745,14 @@ DVec3 DVec3::operator + (Vec3Arg inV2) constreturn DVec3({ _mm_add_pd(mValue.mLow, _mm_cvtps_pd(inV2.mValue)), _mm_add_pd(mValue.mHigh, _mm_cvtps_pd(_mm_shuffle_ps(inV2.mValue, inV2.mValue, _MM_SHUFFLE(2, 2, 2, 2)))) });#elif defined(JPH_USE_NEON)return DVec3({ vaddq_f64(mValue.val[0], vcvt_f64_f32(vget_low_f32(inV2.mValue))), vaddq_f64(mValue.val[1], vcvt_high_f64_f32(inV2.mValue)) });+#elif defined(JPH_USE_RVV)+ DVec3 res;+ const vfloat64m2_t v1 = __riscv_vle64_v_f64m2(mF64, 3);+ const vfloat32m1_t v2_f32 = __riscv_vle32_v_f32m1(inV2.mF32, 3);+ const vfloat64m2_t v2 = __riscv_vfwcvt_f_f_v_f64m2(v2_f32, 3);+ const vfloat64m2_t rvv_add = __riscv_vfadd_vv_f64m2(v1, v2, 3);+ __riscv_vse64_v_f64m2(res.mF64, rvv_add, 3);+ return res;#elsereturn DVec3(mF64[0] + inV2.mF32[0], mF64[1] + inV2.mF32[1], mF64[2] + inV2.mF32[2]);#endif@@ -566,6 +766,13 @@ DVec3 DVec3::operator + (DVec3Arg inV2) constreturn DVec3({ _mm_add_pd(mValue.mLow, inV2.mValue.mLow), _mm_add_pd(mValue.mHigh, inV2.mValue.mHigh) });#elif defined(JPH_USE_NEON)return DVec3({ vaddq_f64(mValue.val[0], inV2.mValue.val[0]), vaddq_f64(mValue.val[1], inV2.mValue.val[1]) });+#elif defined(JPH_USE_RVV)+ DVec3 res;+ const vfloat64m2_t v1 = __riscv_vle64_v_f64m2(mF64, 3);+ const vfloat64m2_t v2 = __riscv_vle64_v_f64m2(inV2.mF64, 3);+ const vfloat64m2_t rvv_add = __riscv_vfadd_vv_f64m2(v1, v2, 3);+ __riscv_vse64_v_f64m2(res.mF64, rvv_add, 3);+ return res;#elsereturn DVec3(mF64[0] + inV2.mF64[0], mF64[1] + inV2.mF64[1], mF64[2] + inV2.mF64[2]);#endif@@ -581,6 +788,12 @@ DVec3 &DVec3::operator += (Vec3Arg inV2)#elif defined(JPH_USE_NEON)mValue.val[0] = vaddq_f64(mValue.val[0], vcvt_f64_f32(vget_low_f32(inV2.mValue)));mValue.val[1] = vaddq_f64(mValue.val[1], vcvt_high_f64_f32(inV2.mValue));+#elif defined(JPH_USE_RVV)+ const vfloat64m2_t v1 = __riscv_vle64_v_f64m2(mF64, 3);+ const vfloat32m1_t v2_f32 = __riscv_vle32_v_f32m1(inV2.mF32, 3);+ const vfloat64m2_t v2 = __riscv_vfwcvt_f_f_v_f64m2(v2_f32, 3);+ const vfloat64m2_t rvv_add = __riscv_vfadd_vv_f64m2(v1, v2, 3);+ __riscv_vse64_v_f64m2(mF64, rvv_add, 3);#elsefor (int i = 0; i < 3; ++i)mF64[i] += inV2.mF32[i];@@ -601,6 +814,11 @@ DVec3 &DVec3::operator += (DVec3Arg inV2)#elif defined(JPH_USE_NEON)mValue.val[0] = vaddq_f64(mValue.val[0], inV2.mValue.val[0]);mValue.val[1] = vaddq_f64(mValue.val[1], inV2.mValue.val[1]);+#elif defined(JPH_USE_RVV)+ const vfloat64m2_t v1 = __riscv_vle64_v_f64m2(mF64, 3);+ const vfloat64m2_t v2 = __riscv_vle64_v_f64m2(inV2.mF64, 3);+ const vfloat64m2_t rvv_add = __riscv_vfadd_vv_f64m2(v1, v2, 3);+ __riscv_vse64_v_f64m2(mF64, rvv_add, 3);#elsefor (int i = 0; i < 3; ++i)mF64[i] += inV2.mF64[i];@@ -625,6 +843,21 @@ DVec3 DVec3::operator - () const#elsereturn DVec3({ vnegq_f64(mValue.val[0]), vnegq_f64(mValue.val[1]) });#endif+#elif defined(JPH_USE_RVV)+ #ifdef JPH_CROSS_PLATFORM_DETERMINISTIC+ DVec3 res;+ const vfloat64m2_t rvv_zero = __riscv_vfmv_v_f_f64m2(0.0, 3);+ const vfloat64m2_t v = __riscv_vle64_v_f64m2(mF64, 3);+ const vfloat64m2_t rvv_neg = __riscv_vfsub_vv_f64m2(rvv_zero, v, 3);+ __riscv_vse64_v_f64m2(res.mF64, rvv_neg, 3);+ return res;+ #else+ DVec3 res;+ const vfloat64m2_t v = __riscv_vle64_v_f64m2(mF64, 3);+ const vfloat64m2_t rvv_neg = __riscv_vfsgnjn_vv_f64m2(v, v, 3);+ __riscv_vse64_v_f64m2(res.mF64, rvv_neg, 3);+ return res;+ #endif#else#ifdef JPH_CROSS_PLATFORM_DETERMINISTICreturn DVec3(0.0 - mF64[0], 0.0 - mF64[1], 0.0 - mF64[2]);@@ -642,6 +875,14 @@ DVec3 DVec3::operator - (Vec3Arg inV2) constreturn DVec3({ _mm_sub_pd(mValue.mLow, _mm_cvtps_pd(inV2.mValue)), _mm_sub_pd(mValue.mHigh, _mm_cvtps_pd(_mm_shuffle_ps(inV2.mValue, inV2.mValue, _MM_SHUFFLE(2, 2, 2, 2)))) });#elif defined(JPH_USE_NEON)return DVec3({ vsubq_f64(mValue.val[0], vcvt_f64_f32(vget_low_f32(inV2.mValue))), vsubq_f64(mValue.val[1], vcvt_high_f64_f32(inV2.mValue)) });+#elif defined(JPH_USE_RVV)+ DVec3 res;+ const vfloat64m2_t v1 = __riscv_vle64_v_f64m2(mF64, 3);+ const vfloat32m1_t v2_f32 = __riscv_vle32_v_f32m1(inV2.mF32, 3);+ const vfloat64m2_t v2 = __riscv_vfwcvt_f_f_v_f64m2(v2_f32, 3);+ const vfloat64m2_t rvv_sub = __riscv_vfsub_vv_f64m2(v1, v2, 3);+ __riscv_vse64_v_f64m2(res.mF64, rvv_sub, 3);+ return res;#elsereturn DVec3(mF64[0] - inV2.mF32[0], mF64[1] - inV2.mF32[1], mF64[2] - inV2.mF32[2]);#endif@@ -655,6 +896,13 @@ DVec3 DVec3::operator - (DVec3Arg inV2) constreturn DVec3({ _mm_sub_pd(mValue.mLow, inV2.mValue.mLow), _mm_sub_pd(mValue.mHigh, inV2.mValue.mHigh) });#elif defined(JPH_USE_NEON)return DVec3({ vsubq_f64(mValue.val[0], inV2.mValue.val[0]), vsubq_f64(mValue.val[1], inV2.mValue.val[1]) });+#elif defined(JPH_USE_RVV)+ DVec3 res;+ const vfloat64m2_t v1 = __riscv_vle64_v_f64m2(mF64, 3);+ const vfloat64m2_t v2 = __riscv_vle64_v_f64m2(inV2.mF64, 3);+ const vfloat64m2_t rvv_sub = __riscv_vfsub_vv_f64m2(v1, v2, 3);+ __riscv_vse64_v_f64m2(res.mF64, rvv_sub, 3);+ return res;#elsereturn DVec3(mF64[0] - inV2.mF64[0], mF64[1] - inV2.mF64[1], mF64[2] - inV2.mF64[2]);#endif@@ -670,6 +918,12 @@ DVec3 &DVec3::operator -= (Vec3Arg inV2)#elif defined(JPH_USE_NEON)mValue.val[0] = vsubq_f64(mValue.val[0], vcvt_f64_f32(vget_low_f32(inV2.mValue)));mValue.val[1] = vsubq_f64(mValue.val[1], vcvt_high_f64_f32(inV2.mValue));+#elif defined(JPH_USE_RVV)+ const vfloat64m2_t v1 = __riscv_vle64_v_f64m2(mF64, 3);+ const vfloat32m1_t v2_f32 = __riscv_vle32_v_f32m1(inV2.mF32, 3);+ const vfloat64m2_t v2 = __riscv_vfwcvt_f_f_v_f64m2(v2_f32, 3);+ const vfloat64m2_t rvv_sub = __riscv_vfsub_vv_f64m2(v1, v2, 3);+ __riscv_vse64_v_f64m2(mF64, rvv_sub, 3);#elsefor (int i = 0; i < 3; ++i)mF64[i] -= inV2.mF32[i];@@ -690,6 +944,11 @@ DVec3 &DVec3::operator -= (DVec3Arg inV2)#elif defined(JPH_USE_NEON)mValue.val[0] = vsubq_f64(mValue.val[0], inV2.mValue.val[0]);mValue.val[1] = vsubq_f64(mValue.val[1], inV2.mValue.val[1]);+#elif defined(JPH_USE_RVV)+ const vfloat64m2_t v1 = __riscv_vle64_v_f64m2(mF64, 3);+ const vfloat64m2_t v2 = __riscv_vle64_v_f64m2(inV2.mF64, 3);+ const vfloat64m2_t rvv_sub = __riscv_vfsub_vv_f64m2(v1, v2, 3);+ __riscv_vse64_v_f64m2(mF64, rvv_sub, 3);#elsefor (int i = 0; i < 3; ++i)mF64[i] -= inV2.mF64[i];@@ -709,6 +968,13 @@ DVec3 DVec3::operator / (DVec3Arg inV2) constreturn DVec3({ _mm_div_pd(mValue.mLow, inV2.mValue.mLow), _mm_div_pd(mValue.mHigh, inV2.mValue.mHigh) });#elif defined(JPH_USE_NEON)return DVec3({ vdivq_f64(mValue.val[0], inV2.mValue.val[0]), vdivq_f64(mValue.val[1], inV2.mValue.val[1]) });+#elif defined(JPH_USE_RVV)+ DVec3 res;+ const vfloat64m2_t v1 = __riscv_vle64_v_f64m2(mF64, 3);+ const vfloat64m2_t v2 = __riscv_vle64_v_f64m2(inV2.mF64, 3);+ const vfloat64m2_t rvv_div = __riscv_vfdiv_vv_f64m2(v1, v2, 3);+ __riscv_vse64_v_f64m2(res.mF64, rvv_div, 3);+ return res;#elsereturn DVec3(mF64[0] / inV2.mF64[0], mF64[1] / inV2.mF64[1], mF64[2] / inV2.mF64[2]);#endif@@ -725,6 +991,12 @@ DVec3 DVec3::Abs() constreturn DVec3({ _mm_max_pd(_mm_sub_pd(zero, mValue.mLow), mValue.mLow), _mm_max_pd(_mm_sub_pd(zero, mValue.mHigh), mValue.mHigh) });#elif defined(JPH_USE_NEON)return DVec3({ vabsq_f64(mValue.val[0]), vabsq_f64(mValue.val[1]) });+#elif defined(JPH_USE_RVV)+ DVec3 res;+ const vfloat64m2_t v = __riscv_vle64_v_f64m2(mF64, 3);+ const vfloat64m2_t rvv_abs = __riscv_vfsgnj_vf_f64m2(v, 1.0, 3);+ __riscv_vse64_v_f64m2(res.mF64, rvv_abs, 3);+ return res;#elsereturn DVec3(abs(mF64[0]), abs(mF64[1]), abs(mF64[2]));#endif@@ -744,6 +1016,21 @@ DVec3 DVec3::Cross(DVec3Arg inV2) constt2 = _mm256_mul_pd(t2, inV2.mValue);__m256d t3 = _mm256_sub_pd(t1, t2);return _mm256_permute4x64_pd(t3, _MM_SHUFFLE(0, 0, 2, 1)); // Assure Z and W are the same+#elif defined(JPH_USE_RVV)+ const uint64 indices[3] = { 1, 2, 0 };+ const vuint64m2_t gather_indices = __riscv_vle64_v_u64m2(indices, 3);+ const vfloat64m2_t v0 = __riscv_vle64_v_f64m2(mF64, 3);+ const vfloat64m2_t v1 = __riscv_vle64_v_f64m2(inV2.mF64, 3);+ vfloat64m2_t t0 = __riscv_vrgather_vv_f64m2(v1, gather_indices, 3);+ t0 = __riscv_vfmul_vv_f64m2(t0, v0, 3);+ vfloat64m2_t t1 = __riscv_vrgather_vv_f64m2(v0, gather_indices, 3);+ t1 = __riscv_vfmul_vv_f64m2(t1, v1, 3);+ const vfloat64m2_t sub = __riscv_vfsub_vv_f64m2(t0, t1, 3);+ const vfloat64m2_t cross = __riscv_vrgather_vv_f64m2(sub, gather_indices, 3);++ DVec3 cross_result;+ __riscv_vse64_v_f64m2(cross_result.mF64, cross, 3);+ return cross_result;#elsereturn DVec3(mF64[1] * inV2.mF64[2] - mF64[2] * inV2.mF64[1],mF64[2] * inV2.mF64[0] - mF64[0] * inV2.mF64[2],@@ -772,6 +1059,13 @@ double DVec3::Dot(DVec3Arg inV2) constfloat64x2_t mul_low = vmulq_f64(mValue.val[0], inV2.mValue.val[0]);float64x2_t mul_high = vmulq_f64(mValue.val[1], inV2.mValue.val[1]);return vaddvq_f64(mul_low) + vgetq_lane_f64(mul_high, 0);+#elif defined(JPH_USE_RVV)+ const vfloat64m1_t zeros = __riscv_vfmv_v_f_f64m1(0.0, 3);+ const vfloat64m2_t v1 = __riscv_vle64_v_f64m2(mF64, 3);+ const vfloat64m2_t v2 = __riscv_vle64_v_f64m2(inV2.mF64, 3);+ const vfloat64m2_t mul = __riscv_vfmul_vv_f64m2(v1, v2, 3);+ const vfloat64m1_t sum = __riscv_vfredosum_vs_f64m2_f64m1(mul, zeros, 3);+ return __riscv_vfmv_f_s_f64m1_f64(sum);#elsedouble dot = 0.0;for (int i = 0; i < 3; i++)@@ -793,14 +1087,20 @@ DVec3 DVec3::Sqrt() constreturn DVec3({ _mm_sqrt_pd(mValue.mLow), _mm_sqrt_pd(mValue.mHigh) });#elif defined(JPH_USE_NEON)return DVec3({ vsqrtq_f64(mValue.val[0]), vsqrtq_f64(mValue.val[1]) });+#elif defined(JPH_USE_RVV)+ DVec3 res;+ const vfloat64m2_t v = __riscv_vle64_v_f64m2(mF64, 3);+ const vfloat64m2_t rvv_sqrt = __riscv_vfsqrt_v_f64m2(v, 3);+ __riscv_vse64_v_f64m2(res.mF64, rvv_sqrt, 3);+ return res;#else- return DVec3(sqrt(mF64[0]), sqrt(mF64[1]), sqrt(mF64[2]));+ return DVec3(JPH::Sqrt(mF64[0]), JPH::Sqrt(mF64[1]), JPH::Sqrt(mF64[2]));#endif}double DVec3::Length() const{- return sqrt(Dot(*this));+ return JPH::Sqrt(Dot(*this));}DVec3 DVec3::Normalized() const@@ -821,6 +1121,11 @@ bool DVec3::IsNaN() constreturn (_mm256_movemask_pd(_mm256_cmp_pd(mValue, mValue, _CMP_UNORD_Q)) & 0x7) != 0;#elif defined(JPH_USE_SSE)return ((_mm_movemask_pd(_mm_cmpunord_pd(mValue.mLow, mValue.mLow)) + (_mm_movemask_pd(_mm_cmpunord_pd(mValue.mHigh, mValue.mHigh)) << 2)) & 0x7) != 0;+#elif defined(JPH_USE_RVV)+ const vfloat64m2_t v = __riscv_vle64_v_f64m2(mF64, 3);+ const vbool32_t mask = __riscv_vmfeq_vv_f64m2_b32(v, v, 3);+ const uint32 eq = __riscv_vcpop_m_b32(mask, 3);+ return eq != 3;#elsereturn isnan(mF64[0]) || isnan(mF64[1]) || isnan(mF64[2]);#endif@@ -829,7 +1134,8 @@ bool DVec3::IsNaN() constDVec3 DVec3::GetSign() const{#if defined(JPH_USE_AVX512)- return _mm256_fixupimm_pd(mValue, mValue, _mm256_set1_epi32(0xA9A90A00), 0);+ __m256d one = _mm256_set1_pd(1.0);+ return _mm256_or_pd(_mm256_fixupimm_pd(mValue, mValue, _mm256_set1_epi32(0xA9A90100), 0), one);#elif defined(JPH_USE_AVX)__m256d minus_one = _mm256_set1_pd(-1.0);__m256d one = _mm256_set1_pd(1.0);@@ -843,6 +1149,13 @@ DVec3 DVec3::GetSign() constuint64x2_t one = vreinterpretq_u64_f64(vdupq_n_f64(1.0f));return DVec3({ vreinterpretq_f64_u64(vorrq_u64(vandq_u64(vreinterpretq_u64_f64(mValue.val[0]), minus_one), one)),vreinterpretq_f64_u64(vorrq_u64(vandq_u64(vreinterpretq_u64_f64(mValue.val[1]), minus_one), one)) });+#elif defined(JPH_USE_RVV)+ DVec3 res;+ const vfloat64m2_t rvv_in = __riscv_vle64_v_f64m2(mF64, 3);+ const vfloat64m2_t rvv_one = __riscv_vfmv_v_f_f64m2(1.0, 3);+ const vfloat64m2_t rvv_signs = __riscv_vfsgnj_vv_f64m2(rvv_one, rvv_in, 3);+ __riscv_vse64_v_f64m2(res.mF64, rvv_signs, 3);+ return res;#elsereturn DVec3(std::signbit(mF64[0])? -1.0 : 1.0,std::signbit(mF64[1])? -1.0 : 1.0,@@ -864,6 +1177,15 @@ DVec3 DVec3::PrepareRoundToZero() constuint64x2_t mask = vdupq_n_u64(~cDoubleToFloatMantissaLoss);return DVec3({ vreinterpretq_f64_u64(vandq_u64(vreinterpretq_u64_f64(mValue.val[0]), mask)),vreinterpretq_f64_u64(vandq_u64(vreinterpretq_u64_f64(mValue.val[1]), mask)) });+#elif defined(JPH_USE_RVV)+ const vfloat64m2_t dvec = __riscv_vle64_v_f64m2(mF64, 3);+ const vuint64m2_t dvec_u64 = __riscv_vreinterpret_v_f64m2_u64m2(dvec);+ const vuint64m2_t chopped = __riscv_vand_vx_u64m2(dvec_u64, ~cDoubleToFloatMantissaLoss, 3);+ const vfloat64m2_t chopped_f64 = __riscv_vreinterpret_v_u64m2_f64m2(chopped);++ DVec3 res;+ __riscv_vse64_v_f64m2(res.mF64, chopped_f64, 3);+ return res;#elsedouble x = BitCast<double>(BitCast<uint64>(mF64[0]) & ~cDoubleToFloatMantissaLoss);double y = BitCast<double>(BitCast<uint64>(mF64[1]) & ~cDoubleToFloatMantissaLoss);@@ -911,6 +1233,18 @@ DVec3 DVec3::PrepareRoundToInf() constfloat64x2_t value_or_mantissa_loss_high = vreinterpretq_f64_u64(vorrq_u64(vreinterpretq_u64_f64(mValue.val[1]), mantissa_loss));float64x2_t value_high = vbslq_f64(is_zero_high, mValue.val[1], value_or_mantissa_loss_high);return DVec3({ value_low, value_high });+#elif defined(JPH_USE_RVV)+ const vfloat64m2_t dvec = __riscv_vle64_v_f64m2(mF64, 3);+ const vuint64m2_t dvec_u64 = __riscv_vreinterpret_v_f64m2_u64m2(dvec);+ const vuint64m2_t and_loss = __riscv_vand_vx_u64m2(dvec_u64, cDoubleToFloatMantissaLoss, 3);+ const vuint64m2_t or_loss = __riscv_vor_vx_u64m2(dvec_u64, cDoubleToFloatMantissaLoss, 3);+ const vbool32_t is_zero = __riscv_vmseq_vx_u64m2_b32(and_loss, 0x0, 3);+ const vuint64m2_t select = __riscv_vmerge_vvm_u64m2(or_loss, dvec_u64, is_zero, 3);+ const vfloat64m2_t select_f64 = __riscv_vreinterpret_v_u64m2_f64m2(select);++ DVec3 res;+ __riscv_vse64_v_f64m2(res.mF64, select_f64, 3);+ return res;#elseuint64 ux = BitCast<uint64>(mF64[0]);uint64 uy = BitCast<uint64>(mF64[1]);diff --git a/thirdparty/jolt_physics/Jolt/Math/Double3.h b/thirdparty/jolt_physics/Jolt/Math/Double3.hindex 9b738ff8f8f..9cd4d054bb4 100644--- a/thirdparty/jolt_physics/Jolt/Math/Double3.h+++ b/thirdparty/jolt_physics/Jolt/Math/Double3.h@@ -40,7 +40,7 @@ public:double z;};-static_assert(std::is_trivial<Double3>(), "Is supposed to be a trivial type!");+static_assert(std::is_trivially_default_constructible<Double3>() && std::is_trivially_copyable<Double3>(), "Is supposed to be a trivial type!");JPH_NAMESPACE_ENDdiff --git a/thirdparty/jolt_physics/Jolt/Math/EigenValueSymmetric.h b/thirdparty/jolt_physics/Jolt/Math/EigenValueSymmetric.hindex ce4a3087cc1..37da339c875 100644--- a/thirdparty/jolt_physics/Jolt/Math/EigenValueSymmetric.h+++ b/thirdparty/jolt_physics/Jolt/Math/EigenValueSymmetric.h@@ -127,11 +127,11 @@ bool EigenValueSymmetric(const Matrix &inMatrix, Matrix &outEigVec, Vector &outEelse{float theta = 0.5f * h / a_pq; // Warning: Can become infinite if a(ip, iq) is very small which may trigger an invalid float exception- t = 1.0f / (abs(theta) + sqrt(1.0f + theta * theta)); // If theta becomes inf, t will be 0 so the infinite is not a problem for the algorithm+ t = 1.0f / (abs(theta) + Sqrt(1.0f + theta * theta)); // If theta becomes inf, t will be 0 so the infinite is not a problem for the algorithmif (theta < 0.0f) t = -t;}- float c = 1.0f / sqrt(1.0f + t * t);+ float c = 1.0f / Sqrt(1.0f + t * t);float s = t * c;float tau = s / (1.0f + c);h = t * a_pq;diff --git a/thirdparty/jolt_physics/Jolt/Math/FindRoot.h b/thirdparty/jolt_physics/Jolt/Math/FindRoot.hindex 21fef9f61f0..34399262c59 100644--- a/thirdparty/jolt_physics/Jolt/Math/FindRoot.h+++ b/thirdparty/jolt_physics/Jolt/Math/FindRoot.h@@ -17,7 +17,15 @@ inline int FindRoot(const T inA, const T inB, const T inC, T &outX1, T &outX2){// Check if this is a constant equationif (inB == T(0))+ {+ if (inC == T(0))+ {+ outX1 = outX2 = 0.0f;+ return 1; // Actually infinitely many solutions+ }+return 0;+ }// Linear equation with 1 solutionoutX1 = outX2 = -inC / inB;@@ -25,10 +33,10 @@ inline int FindRoot(const T inA, const T inB, const T inC, T &outX1, T &outX2)}// See Numerical Recipes in C, Chapter 5.6 Quadratic and Cubic Equations- T det = Square(inB) - T(4) * inA * inC;+ T det = DifferenceOfProducts(inB, inB, T(4) * inA, inC);if (det < T(0))return 0;- T q = (inB + Sign(inB) * sqrt(det)) / T(-2);+ T q = (inB + Sign(inB) * Sqrt(det)) / T(-2);outX1 = q / inA;if (q == T(0)){diff --git a/thirdparty/jolt_physics/Jolt/Math/Float2.h b/thirdparty/jolt_physics/Jolt/Math/Float2.hindex 3e16e8c6c04..2ff150ddc74 100644--- a/thirdparty/jolt_physics/Jolt/Math/Float2.h+++ b/thirdparty/jolt_physics/Jolt/Math/Float2.h@@ -31,6 +31,6 @@ public:float y;};-static_assert(std::is_trivial<Float2>(), "Is supposed to be a trivial type!");+static_assert(std::is_trivially_default_constructible<Float2>() && std::is_trivially_copyable<Float2>(), "Is supposed to be a trivial type!");JPH_NAMESPACE_ENDdiff --git a/thirdparty/jolt_physics/Jolt/Math/Float3.h b/thirdparty/jolt_physics/Jolt/Math/Float3.hindex 1355e9ca0f8..ce05a198dce 100644--- a/thirdparty/jolt_physics/Jolt/Math/Float3.h+++ b/thirdparty/jolt_physics/Jolt/Math/Float3.h@@ -42,7 +42,7 @@ public:using VertexList = Array<Float3>;-static_assert(std::is_trivial<Float3>(), "Is supposed to be a trivial type!");+static_assert(std::is_trivially_default_constructible<Float3>() && std::is_trivially_copyable<Float3>(), "Is supposed to be a trivial type!");JPH_NAMESPACE_ENDdiff --git a/thirdparty/jolt_physics/Jolt/Math/Float4.h b/thirdparty/jolt_physics/Jolt/Math/Float4.hindex 454c9c27936..4372ef66ead 100644--- a/thirdparty/jolt_physics/Jolt/Math/Float4.h+++ b/thirdparty/jolt_physics/Jolt/Math/Float4.h@@ -39,6 +39,6 @@ public:float w;};-static_assert(std::is_trivial<Float4>(), "Is supposed to be a trivial type!");+static_assert(std::is_trivially_default_constructible<Float4>() && std::is_trivially_copyable<Float4>(), "Is supposed to be a trivial type!");JPH_NAMESPACE_ENDdiff --git a/thirdparty/jolt_physics/Jolt/Math/Mat44.h b/thirdparty/jolt_physics/Jolt/Math/Mat44.hindex 4774935efcc..52c5fc59554 100644--- a/thirdparty/jolt_physics/Jolt/Math/Mat44.h+++ b/thirdparty/jolt_physics/Jolt/Math/Mat44.h@@ -236,7 +236,7 @@ private:Vec4 mCol[4]; ///< Column};-static_assert(std::is_trivial<Mat44>(), "Is supposed to be a trivial type!");+static_assert(std::is_trivially_default_constructible<Mat44>() && std::is_trivially_copyable<Mat44>(), "Is supposed to be a trivial type!");JPH_NAMESPACE_ENDdiff --git a/thirdparty/jolt_physics/Jolt/Math/Mat44.inl b/thirdparty/jolt_physics/Jolt/Math/Mat44.inlindex f04533f27f6..0324bef4546 100644--- a/thirdparty/jolt_physics/Jolt/Math/Mat44.inl+++ b/thirdparty/jolt_physics/Jolt/Math/Mat44.inl@@ -261,6 +261,30 @@ Mat44 Mat44::operator * (Mat44Arg inM) constt = vmlaq_f32(t, mCol[3].mValue, vdupq_laneq_f32(c, 3));result.mCol[i].mValue = t;}+#elif defined(JPH_USE_RVV)+ const vfloat32m1_t col0 = __riscv_vle32_v_f32m1(mCol[0].mF32, 4);+ const vfloat32m1_t col1 = __riscv_vle32_v_f32m1(mCol[1].mF32, 4);+ const vfloat32m1_t col2 = __riscv_vle32_v_f32m1(mCol[2].mF32, 4);+ const vfloat32m1_t col3 = __riscv_vle32_v_f32m1(mCol[3].mF32, 4);++ for (int i = 0; i < 4; ++i)+ {+ const float *c = inM.mCol[i].mF32;+ const vfloat32m1_t rep_0 = __riscv_vfmv_v_f_f32m1(c[0], 4);+ const vfloat32m1_t rep_1 = __riscv_vfmv_v_f_f32m1(c[1], 4);+ const vfloat32m1_t rep_2 = __riscv_vfmv_v_f_f32m1(c[2], 4);+ const vfloat32m1_t rep_3 = __riscv_vfmv_v_f_f32m1(c[3], 4);++ const vfloat32m1_t mul1 = __riscv_vfmul_vv_f32m1(col1, rep_1, 4);+ const vfloat32m1_t mul2 = __riscv_vfmul_vv_f32m1(col2, rep_2, 4);+ const vfloat32m1_t mul3 = __riscv_vfmul_vv_f32m1(col3, rep_3, 4);++ vfloat32m1_t t = __riscv_vfmul_vv_f32m1(col0, rep_0, 4);+ t = __riscv_vfadd_vv_f32m1(t, mul1, 4);+ t = __riscv_vfadd_vv_f32m1(t, mul2, 4);+ t = __riscv_vfadd_vv_f32m1(t, mul3, 4);+ __riscv_vse32_v_f32m1(result.mCol[i].mF32, t, 4);+ }#elsefor (int i = 0; i < 4; ++i)result.mCol[i] = mCol[0] * inM.mCol[i].mF32[0] + mCol[1] * inM.mCol[i].mF32[1] + mCol[2] * inM.mCol[i].mF32[2] + mCol[3] * inM.mCol[i].mF32[3];@@ -282,6 +306,27 @@ Vec3 Mat44::operator * (Vec3Arg inV) constt = vmlaq_f32(t, mCol[2].mValue, vdupq_laneq_f32(inV.mValue, 2));t = vaddq_f32(t, mCol[3].mValue); // Don't combine this with the first mul into a fused multiply add, causes precision issuesreturn Vec3::sFixW(t);+#elif defined(JPH_USE_RVV)+ const vfloat32m1_t v0 = __riscv_vfmv_v_f_f32m1(inV.mF32[0], 4);+ const vfloat32m1_t v1 = __riscv_vfmv_v_f_f32m1(inV.mF32[1], 4);+ const vfloat32m1_t v2 = __riscv_vfmv_v_f_f32m1(inV.mF32[2], 4);++ const vfloat32m1_t col0 = __riscv_vle32_v_f32m1(mCol[0].mF32, 4);+ const vfloat32m1_t col1 = __riscv_vle32_v_f32m1(mCol[1].mF32, 4);+ const vfloat32m1_t col2 = __riscv_vle32_v_f32m1(mCol[2].mF32, 4);+ const vfloat32m1_t col3 = __riscv_vle32_v_f32m1(mCol[3].mF32, 4);++ const vfloat32m1_t mul1 = __riscv_vfmul_vv_f32m1(col1, v1, 4);+ const vfloat32m1_t mul2 = __riscv_vfmul_vv_f32m1(col2, v2, 4);++ vfloat32m1_t t = __riscv_vfmul_vv_f32m1(col0, v0, 4);+ t = __riscv_vfadd_vv_f32m1(t, mul1, 4);+ t = __riscv_vfadd_vv_f32m1(t, mul2, 4);+ t = __riscv_vfadd_vv_f32m1(t, col3, 4);++ Type v;+ __riscv_vse32_v_f32m1(v.mData, t, 4);+ return Vec3::sFixW(v);#elsereturn Vec3(mCol[0].mF32[0] * inV.mF32[0] + mCol[1].mF32[0] * inV.mF32[1] + mCol[2].mF32[0] * inV.mF32[2] + mCol[3].mF32[0],@@ -304,6 +349,29 @@ Vec4 Mat44::operator * (Vec4Arg inV) constt = vmlaq_f32(t, mCol[2].mValue, vdupq_laneq_f32(inV.mValue, 2));t = vmlaq_f32(t, mCol[3].mValue, vdupq_laneq_f32(inV.mValue, 3));return t;+#elif defined(JPH_USE_RVV)+ const vfloat32m1_t v0 = __riscv_vfmv_v_f_f32m1(inV.mF32[0], 4);+ const vfloat32m1_t v1 = __riscv_vfmv_v_f_f32m1(inV.mF32[1], 4);+ const vfloat32m1_t v2 = __riscv_vfmv_v_f_f32m1(inV.mF32[2], 4);+ const vfloat32m1_t v3 = __riscv_vfmv_v_f_f32m1(inV.mF32[3], 4);++ const vfloat32m1_t col0 = __riscv_vle32_v_f32m1(mCol[0].mF32, 4);+ const vfloat32m1_t col1 = __riscv_vle32_v_f32m1(mCol[1].mF32, 4);+ const vfloat32m1_t col2 = __riscv_vle32_v_f32m1(mCol[2].mF32, 4);+ const vfloat32m1_t col3 = __riscv_vle32_v_f32m1(mCol[3].mF32, 4);++ const vfloat32m1_t mul1 = __riscv_vfmul_vv_f32m1(col1, v1, 4);+ const vfloat32m1_t mul2 = __riscv_vfmul_vv_f32m1(col2, v2, 4);+ const vfloat32m1_t mul3 = __riscv_vfmul_vv_f32m1(col3, v3, 4);++ vfloat32m1_t t = __riscv_vfmul_vv_f32m1(col0, v0, 4);+ t = __riscv_vfadd_vv_f32m1(t, mul1, 4);+ t = __riscv_vfadd_vv_f32m1(t, mul2, 4);+ t = __riscv_vfadd_vv_f32m1(t, mul3, 4);++ Vec4 v;+ __riscv_vse32_v_f32m1(v.mF32, t, 4);+ return v;#elsereturn Vec4(mCol[0].mF32[0] * inV.mF32[0] + mCol[1].mF32[0] * inV.mF32[1] + mCol[2].mF32[0] * inV.mF32[2] + mCol[3].mF32[0] * inV.mF32[3],@@ -325,6 +393,25 @@ Vec3 Mat44::Multiply3x3(Vec3Arg inV) constt = vmlaq_f32(t, mCol[1].mValue, vdupq_laneq_f32(inV.mValue, 1));t = vmlaq_f32(t, mCol[2].mValue, vdupq_laneq_f32(inV.mValue, 2));return Vec3::sFixW(t);+#elif defined(JPH_USE_RVV)+ const vfloat32m1_t v0 = __riscv_vfmv_v_f_f32m1(inV.mF32[0], 4);+ const vfloat32m1_t v1 = __riscv_vfmv_v_f_f32m1(inV.mF32[1], 4);+ const vfloat32m1_t v2 = __riscv_vfmv_v_f_f32m1(inV.mF32[2], 4);++ const vfloat32m1_t col0 = __riscv_vle32_v_f32m1(mCol[0].mF32, 4);+ const vfloat32m1_t col1 = __riscv_vle32_v_f32m1(mCol[1].mF32, 4);+ const vfloat32m1_t col2 = __riscv_vle32_v_f32m1(mCol[2].mF32, 4);++ const vfloat32m1_t mul1 = __riscv_vfmul_vv_f32m1(v1, col1, 4);+ const vfloat32m1_t mul2 = __riscv_vfmul_vv_f32m1(v2, col2, 4);++ vfloat32m1_t t = __riscv_vfmul_vv_f32m1(v0, col0, 4);+ t = __riscv_vfadd_vv_f32m1(t, mul1, 4);+ t = __riscv_vfadd_vv_f32m1(t, mul2, 4);++ Type v;+ __riscv_vse32_v_f32m1(v.mData, t, 4);+ return Vec3::sFixW(v);#elsereturn Vec3(mCol[0].mF32[0] * inV.mF32[0] + mCol[1].mF32[0] * inV.mF32[1] + mCol[2].mF32[0] * inV.mF32[2],@@ -335,16 +422,7 @@ Vec3 Mat44::Multiply3x3(Vec3Arg inV) constVec3 Mat44::Multiply3x3Transposed(Vec3Arg inV) const{-#if defined(JPH_USE_SSE4_1)- __m128 x = _mm_dp_ps(mCol[0].mValue, inV.mValue, 0x7f);- __m128 y = _mm_dp_ps(mCol[1].mValue, inV.mValue, 0x7f);- __m128 xy = _mm_blend_ps(x, y, 0b0010);- __m128 z = _mm_dp_ps(mCol[2].mValue, inV.mValue, 0x7f);- __m128 xyzz = _mm_blend_ps(xy, z, 0b1100);- return xyzz;-#elsereturn Transposed3x3().Multiply3x3(inV);-#endif}Mat44 Mat44::Multiply3x3(Mat44Arg inM) const@@ -372,6 +450,26 @@ Mat44 Mat44::Multiply3x3(Mat44Arg inM) constt = vmlaq_f32(t, mCol[2].mValue, vdupq_laneq_f32(c, 2));result.mCol[i].mValue = t;}+#elif defined(JPH_USE_RVV)+ const vfloat32m1_t col0 = __riscv_vle32_v_f32m1(mCol[0].mF32, 4);+ const vfloat32m1_t col1 = __riscv_vle32_v_f32m1(mCol[1].mF32, 4);+ const vfloat32m1_t col2 = __riscv_vle32_v_f32m1(mCol[2].mF32, 4);++ for (int i = 0; i < 3; ++i)+ {+ const float* col_i = inM.mCol[i].mF32;+ const vfloat32m1_t v0 = __riscv_vfmv_v_f_f32m1(col_i[0], 4);+ const vfloat32m1_t v1 = __riscv_vfmv_v_f_f32m1(col_i[1], 4);+ const vfloat32m1_t v2 = __riscv_vfmv_v_f_f32m1(col_i[2], 4);++ const vfloat32m1_t mul1 = __riscv_vfmul_vv_f32m1(v1, col1, 4);+ const vfloat32m1_t mul2 = __riscv_vfmul_vv_f32m1(v2, col2, 4);++ vfloat32m1_t t = __riscv_vfmul_vv_f32m1(v0, col0, 4);+ t = __riscv_vfadd_vv_f32m1(t, mul1, 4);+ t = __riscv_vfadd_vv_f32m1(t, mul2, 4);+ __riscv_vse32_v_f32m1(result.mCol[i].mF32, t, 4);+ }#elsefor (int i = 0; i < 3; ++i)result.mCol[i] = mCol[0] * inM.mCol[i].mF32[0] + mCol[1] * inM.mCol[i].mF32[1] + mCol[2] * inM.mCol[i].mF32[2];@@ -490,6 +588,18 @@ Mat44 Mat44::Transposed() constresult.mCol[2].mValue = tmp4.val[0];result.mCol[3].mValue = tmp4.val[1];return result;+#elif defined(JPH_USE_RVV)+ const vfloat32m1_t row0 = __riscv_vlse32_v_f32m1(&mCol[0].mF32[0], sizeof(Vec4), 4);+ const vfloat32m1_t row1 = __riscv_vlse32_v_f32m1(&mCol[0].mF32[1], sizeof(Vec4), 4);+ const vfloat32m1_t row2 = __riscv_vlse32_v_f32m1(&mCol[0].mF32[2], sizeof(Vec4), 4);+ const vfloat32m1_t row3 = __riscv_vlse32_v_f32m1(&mCol[0].mF32[3], sizeof(Vec4), 4);++ Mat44 result;+ __riscv_vse32_v_f32m1(result.mCol[0].mF32, row0, 4);+ __riscv_vse32_v_f32m1(result.mCol[1].mF32, row1, 4);+ __riscv_vse32_v_f32m1(result.mCol[2].mF32, row2, 4);+ __riscv_vse32_v_f32m1(result.mCol[3].mF32, row3, 4);+ return result;#elseMat44 result;for (int c = 0; c < 4; ++c)@@ -522,6 +632,22 @@ Mat44 Mat44::Transposed3x3() constresult.mCol[0].mValue = tmp3.val[0];result.mCol[1].mValue = tmp3.val[1];result.mCol[2].mValue = tmp4.val[0];+#elif defined(JPH_USE_RVV)+ const float end_col[4] = { 0, 0, 0, 1 };+ const vfloat32m1_t rvv_end_col = __riscv_vle32_v_f32m1(end_col, 4);+ const vfloat32m1_t rvv_end_row = __riscv_vfmv_v_f_f32m1(0.0f, 3);++ const vfloat32m1_t row0 = __riscv_vlse32_v_f32m1(&mCol[0].mF32[0], sizeof(Vec4), 3);+ const vfloat32m1_t row1 = __riscv_vlse32_v_f32m1(&mCol[0].mF32[1], sizeof(Vec4), 3);+ const vfloat32m1_t row2 = __riscv_vlse32_v_f32m1(&mCol[0].mF32[2], sizeof(Vec4), 3);++ Mat44 result;+ __riscv_vse32_v_f32m1(result.mCol[0].mF32, row0, 3);+ __riscv_vse32_v_f32m1(result.mCol[1].mF32, row1, 3);+ __riscv_vse32_v_f32m1(result.mCol[2].mF32, row2, 3);+ __riscv_vse32_v_f32m1(result.mCol[3].mF32, rvv_end_col, 4);+ __riscv_vsse32_v_f32m1(&result.mCol[0].mF32[3], sizeof(Vec4), rvv_end_row, 3);+ return result;#elseMat44 result;for (int c = 0; c < 3; ++c)@@ -690,6 +816,95 @@ Mat44 Mat44::Inversed() constresult.mCol[2].mValue = vmulq_f32(det, minor2);result.mCol[3].mValue = vmulq_f32(det, minor3);return result;+#elif defined(JPH_USE_RVV)+ // Implementation mirrored from SSE and NEON implementations+ const vfloat32m1_t c0 = __riscv_vle32_v_f32m1(mCol[0].mF32, 4);+ const vfloat32m1_t c1 = __riscv_vle32_v_f32m1(mCol[1].mF32, 4);+ const vfloat32m1_t c2 = __riscv_vle32_v_f32m1(mCol[2].mF32, 4);+ const vfloat32m1_t c3 = __riscv_vle32_v_f32m1(mCol[3].mF32, 4);++ vfloat32m1_t minor0, minor1, minor2, minor3;+ vfloat32m1_t tmp1;+ vfloat32m1_t row0, row1, row2, row3;++ tmp1 = RVVShuffleFloat32x4<0, 1, 4, 5>(c0, c1);+ row1 = RVVShuffleFloat32x4<0, 1, 4, 5>(c2, c3);+ row0 = RVVShuffleFloat32x4<0, 2, 4, 6>(tmp1, row1);+ row1 = RVVShuffleFloat32x4<1, 3, 5, 7>(row1, tmp1);+ tmp1 = RVVShuffleFloat32x4<2, 3, 6, 7>(c0, c1);+ row3 = RVVShuffleFloat32x4<2, 3, 6, 7>(c2, c3);+ row2 = RVVShuffleFloat32x4<0, 2, 4, 6>(tmp1, row3);+ row3 = RVVShuffleFloat32x4<1, 3, 5, 7>(row3, tmp1);++ tmp1 = __riscv_vfmul_vv_f32m1(row2, row3, 4);+ tmp1 = RVVShuffleFloat32x4<1, 0, 3, 2>(tmp1, tmp1);+ minor0 = __riscv_vfmul_vv_f32m1(row1, tmp1, 4);+ minor1 = __riscv_vfmul_vv_f32m1(row0, tmp1, 4);+ tmp1 = RVVShuffleFloat32x4<2, 3, 0, 1>(tmp1, tmp1);+ minor0 = __riscv_vfsub_vv_f32m1(__riscv_vfmul_vv_f32m1(row1, tmp1, 4), minor0, 4);+ minor1 = __riscv_vfsub_vv_f32m1(__riscv_vfmul_vv_f32m1(row0, tmp1, 4), minor1, 4);+ minor1 = RVVShuffleFloat32x4<2, 3, 0, 1>(minor1, minor1);++ tmp1 = __riscv_vfmul_vv_f32m1(row1, row2, 4);+ tmp1 = RVVShuffleFloat32x4<1, 0, 3, 2>(tmp1, tmp1);+ minor0 = __riscv_vfadd_vv_f32m1(__riscv_vfmul_vv_f32m1(row3, tmp1, 4), minor0, 4);+ minor3 = __riscv_vfmul_vv_f32m1(row0, tmp1, 4);+ tmp1 = RVVShuffleFloat32x4<2, 3, 0, 1>(tmp1, tmp1);+ minor0 = __riscv_vfsub_vv_f32m1(minor0, __riscv_vfmul_vv_f32m1(row3, tmp1, 4), 4);+ minor3 = __riscv_vfsub_vv_f32m1(__riscv_vfmul_vv_f32m1(row0, tmp1, 4), minor3, 4);+ minor3 = RVVShuffleFloat32x4<2, 3, 0, 1>(minor3, minor3);++ tmp1 = RVVShuffleFloat32x4<2, 3, 0, 1>(row1, row1);+ tmp1 = __riscv_vfmul_vv_f32m1(tmp1, row3, 4);+ tmp1 = RVVShuffleFloat32x4<1, 0, 3, 2>(tmp1, tmp1);+ row2 = RVVShuffleFloat32x4<2, 3, 0, 1>(row2, row2);+ minor0 = __riscv_vfadd_vv_f32m1(__riscv_vfmul_vv_f32m1(row2, tmp1, 4), minor0, 4);+ minor2 = __riscv_vfmul_vv_f32m1(row0, tmp1, 4);+ tmp1 = RVVShuffleFloat32x4<2, 3, 0, 1>(tmp1, tmp1);+ minor0 = __riscv_vfsub_vv_f32m1(minor0, __riscv_vfmul_vv_f32m1(row2, tmp1, 4), 4);+ minor2 = __riscv_vfsub_vv_f32m1(__riscv_vfmul_vv_f32m1(row0, tmp1, 4), minor2, 4);+ minor2 = RVVShuffleFloat32x4<2, 3, 0, 1>(minor2, minor2);++ tmp1 = __riscv_vfmul_vv_f32m1(row0, row1, 4);+ tmp1 = RVVShuffleFloat32x4<1, 0, 3, 2>(tmp1, tmp1);+ minor2 = __riscv_vfadd_vv_f32m1(__riscv_vfmul_vv_f32m1(row3, tmp1, 4), minor2, 4);+ minor3 = __riscv_vfsub_vv_f32m1(__riscv_vfmul_vv_f32m1(row2, tmp1, 4), minor3, 4);+ tmp1 = RVVShuffleFloat32x4<2, 3, 0, 1>(tmp1, tmp1);+ minor2 = __riscv_vfsub_vv_f32m1(__riscv_vfmul_vv_f32m1(row3, tmp1, 4), minor2, 4);+ minor3 = __riscv_vfsub_vv_f32m1(minor3, __riscv_vfmul_vv_f32m1(row2, tmp1, 4), 4);++ tmp1 = __riscv_vfmul_vv_f32m1(row0, row3, 4);+ tmp1 = RVVShuffleFloat32x4<1, 0, 3, 2>(tmp1, tmp1);+ minor1 = __riscv_vfsub_vv_f32m1(minor1, __riscv_vfmul_vv_f32m1(row2, tmp1, 4), 4);+ minor2 = __riscv_vfadd_vv_f32m1(__riscv_vfmul_vv_f32m1(row1, tmp1, 4), minor2, 4);+ tmp1 = RVVShuffleFloat32x4<2, 3, 0, 1>(tmp1, tmp1);+ minor1 = __riscv_vfadd_vv_f32m1(__riscv_vfmul_vv_f32m1(row2, tmp1, 4), minor1, 4);+ minor2 = __riscv_vfsub_vv_f32m1(minor2, __riscv_vfmul_vv_f32m1(row1, tmp1, 4), 4);++ tmp1 = __riscv_vfmul_vv_f32m1(row0, row2, 4);+ tmp1 = RVVShuffleFloat32x4<1, 0, 3, 2>(tmp1, tmp1);+ minor1 = __riscv_vfadd_vv_f32m1(__riscv_vfmul_vv_f32m1(row3, tmp1, 4), minor1, 4);+ minor3 = __riscv_vfsub_vv_f32m1(minor3, __riscv_vfmul_vv_f32m1(row1, tmp1, 4), 4);+ tmp1 = RVVShuffleFloat32x4<2, 3, 0, 1>(tmp1, tmp1);+ minor1 = __riscv_vfsub_vv_f32m1(minor1, __riscv_vfmul_vv_f32m1(row3, tmp1, 4), 4);+ minor3 = __riscv_vfadd_vv_f32m1(__riscv_vfmul_vv_f32m1(row1, tmp1, 4), minor3, 4);++ const vfloat32m1_t v_det = __riscv_vfmul_vv_f32m1(row0, minor0, 4);+ const vfloat32m1_t s_det = RVVSumElementsFloat32x4(v_det);+ const vfloat32m1_t det_splat = __riscv_vrgather_vx_f32m1(s_det, 0, 4);+ const vfloat32m1_t det_inv = __riscv_vfrdiv_vf_f32m1(det_splat, 1.0f, 4);++ minor0 = __riscv_vfmul_vv_f32m1(det_inv, minor0, 4);+ minor1 = __riscv_vfmul_vv_f32m1(det_inv, minor1, 4);+ minor2 = __riscv_vfmul_vv_f32m1(det_inv, minor2, 4);+ minor3 = __riscv_vfmul_vv_f32m1(det_inv, minor3, 4);++ Mat44 result;+ __riscv_vse32_v_f32m1(result.mCol[0].mF32, minor0, 4);+ __riscv_vse32_v_f32m1(result.mCol[1].mF32, minor1, 4);+ __riscv_vse32_v_f32m1(result.mCol[2].mF32, minor2, 4);+ __riscv_vse32_v_f32m1(result.mCol[3].mF32, minor3, 4);+ return result;#elsefloat m00 = JPH_EL(0, 0), m10 = JPH_EL(1, 0), m20 = JPH_EL(2, 0), m30 = JPH_EL(3, 0);float m01 = JPH_EL(0, 1), m11 = JPH_EL(1, 1), m21 = JPH_EL(2, 1), m31 = JPH_EL(3, 1);@@ -735,7 +950,7 @@ Mat44 Mat44::InversedRotationTranslation() constfloat Mat44::GetDeterminant3x3() const{- return GetAxisX().Dot(GetAxisY().Cross(GetAxisZ()));+ return GetAxisX().Dot(GetAxisY().CrossPrecise(GetAxisZ()));}Mat44 Mat44::Adjointed3x3() const@@ -786,7 +1001,7 @@ Quat Mat44::GetQuaternion() constif (tr >= 0.0f){- float s = sqrt(tr + 1.0f);+ float s = Sqrt(tr + 1.0f);float is = 0.5f / s;return Quat((mCol[1].mF32[2] - mCol[2].mF32[1]) * is,@@ -802,7 +1017,7 @@ Quat Mat44::GetQuaternion() constif (i == 0){- float s = sqrt(mCol[0].mF32[0] - (mCol[1].mF32[1] + mCol[2].mF32[2]) + 1);+ float s = Sqrt(mCol[0].mF32[0] - (mCol[1].mF32[1] + mCol[2].mF32[2]) + 1);float is = 0.5f / s;return Quat(0.5f * s,@@ -812,7 +1027,7 @@ Quat Mat44::GetQuaternion() const}else if (i == 1){- float s = sqrt(mCol[1].mF32[1] - (mCol[2].mF32[2] + mCol[0].mF32[0]) + 1);+ float s = Sqrt(mCol[1].mF32[1] - (mCol[2].mF32[2] + mCol[0].mF32[0]) + 1);float is = 0.5f / s;return Quat((mCol[1].mF32[0] + mCol[0].mF32[1]) * is,@@ -824,7 +1039,7 @@ Quat Mat44::GetQuaternion() const{JPH_ASSERT(i == 2);- float s = sqrt(mCol[2].mF32[2] - (mCol[0].mF32[0] + mCol[1].mF32[1]) + 1);+ float s = Sqrt(mCol[2].mF32[2] - (mCol[0].mF32[0] + mCol[1].mF32[1]) + 1);float is = 0.5f / s;return Quat((mCol[0].mF32[2] + mCol[2].mF32[0]) * is,@@ -880,6 +1095,15 @@ Mat44 Mat44::GetRotationSafe() constvsetq_lane_f32(0, mCol[1].mValue, 3),vsetq_lane_f32(0, mCol[2].mValue, 3),Vec4(0, 0, 0, 1));+#elif defined(JPH_USE_RVV)+ const float end_col[4] = { 0, 0, 0, 1 };+ const vfloat32m1_t rvv_end_col = __riscv_vle32_v_f32m1(end_col, 4);+ const vfloat32m1_t rvv_end_row = __riscv_vfmv_v_f_f32m1(0.0f, 3);++ Mat44 result(*this);+ __riscv_vse32_v_f32m1(result.mCol[3].mF32, rvv_end_col, 4);+ __riscv_vsse32_v_f32m1(&result.mCol[0].mF32[3], sizeof(Vec4), rvv_end_row, 3);+ return result;#elsereturn Mat44(Vec4(mCol[0].mF32[0], mCol[0].mF32[1], mCol[0].mF32[2], 0),Vec4(mCol[1].mF32[0], mCol[1].mF32[1], mCol[1].mF32[2], 0),diff --git a/thirdparty/jolt_physics/Jolt/Math/Math.h b/thirdparty/jolt_physics/Jolt/Math/Math.hindex 02083684e43..0ecacaed0ca 100644--- a/thirdparty/jolt_physics/Jolt/Math/Math.h+++ b/thirdparty/jolt_physics/Jolt/Math/Math.h@@ -43,6 +43,21 @@ inline float CenterAngleAroundZero(float inV)return inV;}+/// Calculates inA * inB - inC * inD with higher accuracy when fused multiply add instructions are available.+/// If inA * inB and inC * inD are large, the subtraction can cause a large loss of precision when the result is small.+/// See: https://pharr.org/matt/blog/2019/11/03/difference-of-floats (or search for Kahan's algorithm)+JPH_INLINE float DifferenceOfProducts(float inA, float inB, float inC, float inD)+{+#ifdef JPH_USE_FMADD+ float cd = inC * inD;+ float err = std::fma(-inC, inD, cd);+ float dop = std::fma(inA, inB, -cd);+ return dop + err;+#else+ return inA * inB - inC * inD;+#endif+}+/// Clamp a value between two valuestemplate <typename T>JPH_INLINE constexpr T Clamp(T inV, T inMin, T inMax)@@ -57,6 +72,38 @@ JPH_INLINE constexpr T Square(T inV)return inV * inV;}+/// Take the square root of a float value+JPH_INLINE float Sqrt(float inV)+{+#ifdef JPH_USE_SSE+ return _mm_cvtss_f32(_mm_sqrt_ss(_mm_set_ss(inV)));+#elif defined(JPH_USE_NEON)+ return vget_lane_f32(vsqrt_f32(vdup_n_f32(inV)), 0);+#elif defined(JPH_CPU_RISCV)+ float res;+ asm("fsqrt.s %0, %1" : "=f"(res) : "f"(inV));+ return res;+#else+ return std::sqrt(inV);+#endif+}++/// Take the square root of a double value+JPH_INLINE double Sqrt(double inV)+{+#ifdef JPH_USE_SSE+ return _mm_cvtsd_f64(_mm_sqrt_sd(_mm_undefined_pd(), _mm_set_sd(inV)));+#elif defined(JPH_USE_NEON)+ return vget_lane_f64(vsqrt_f64(vdup_n_f64(inV)), 0);+#elif defined(JPH_CPU_RISCV)+ double res;+ asm("fsqrt.d %0, %1" : "=f"(res) : "f"(inV));+ return res;+#else+ return std::sqrt(inV);+#endif+}+/// Returns \f$inV^3\f$.template <typename T>JPH_INLINE constexpr T Cubed(T inV)@@ -187,22 +234,13 @@ inline uint32 GetNextPowerOf2(uint32 inValue)return inValue <= 1? uint32(1) : uint32(1) << (32 - CountLeadingZeros(inValue - 1));}-// Simple implementation of C++20 std::bit_cast (unfortunately not constexpr)+/// Simple implementation of C++20 std::bit_casttemplate <class To, class From>-JPH_INLINE To BitCast(const From &inValue)+JPH_INLINE constexpr To BitCast(const From &inValue){static_assert(std::is_trivially_constructible_v<To>);static_assert(sizeof(From) == sizeof(To));-- union FromTo- {- To mTo;- From mFrom;- };-- FromTo convert;- convert.mFrom = inValue;- return convert.mTo;+ return __builtin_bit_cast(To, inValue);}JPH_NAMESPACE_ENDdiff --git a/thirdparty/jolt_physics/Jolt/Math/Matrix.h b/thirdparty/jolt_physics/Jolt/Math/Matrix.hindex 031665bbe71..7fba8bfc07d 100644--- a/thirdparty/jolt_physics/Jolt/Math/Matrix.h+++ b/thirdparty/jolt_physics/Jolt/Math/Matrix.h@@ -242,7 +242,7 @@ inline bool Matrix<2, 2>::SetInversed(const Matrix<2, 2> &inM)float d = inM.mCol[1].mF32[1];// Calculate determinant- float det = a * d - b * c;+ float det = DifferenceOfProducts(a, d, b, c);if (det == 0.0f)return false;diff --git a/thirdparty/jolt_physics/Jolt/Math/Quat.h b/thirdparty/jolt_physics/Jolt/Math/Quat.hindex 1971e2ddf11..c788e8220c0 100644--- a/thirdparty/jolt_physics/Jolt/Math/Quat.h+++ b/thirdparty/jolt_physics/Jolt/Math/Quat.h@@ -264,7 +264,7 @@ public:Vec4 mValue;};-static_assert(std::is_trivial<Quat>(), "Is supposed to be a trivial type!");+static_assert(std::is_trivially_default_constructible<Quat>() && std::is_trivially_copyable<Quat>(), "Is supposed to be a trivial type!");JPH_NAMESPACE_ENDdiff --git a/thirdparty/jolt_physics/Jolt/Math/Quat.inl b/thirdparty/jolt_physics/Jolt/Math/Quat.inlindex 7c160a5f230..09e54347ae9 100644--- a/thirdparty/jolt_physics/Jolt/Math/Quat.inl+++ b/thirdparty/jolt_physics/Jolt/Math/Quat.inl@@ -6,122 +6,154 @@ JPH_NAMESPACE_BEGINQuat Quat::operator * (QuatArg inRHS) const{-#if defined(JPH_USE_SSE4_1)- // Taken from: http://momchil-velikov.blogspot.nl/2013/10/fast-sse-quternion-multiplication.html+#ifdef JPH_USE_SSE__m128 abcd = mValue.mValue;__m128 xyzw = inRHS.mValue.mValue;- __m128 t0 = _mm_shuffle_ps(abcd, abcd, _MM_SHUFFLE(3, 3, 3, 3));- __m128 t1 = _mm_shuffle_ps(xyzw, xyzw, _MM_SHUFFLE(2, 3, 0, 1));+ // Names based on logical order, opposite of shuffle order.+ __m128 abca = _mm_shuffle_ps(abcd, abcd, _MM_SHUFFLE(0, 2, 1, 0));+ __m128 bcab = _mm_shuffle_ps(abcd, abcd, _MM_SHUFFLE(1, 0, 2, 1));+ __m128 cabc = _mm_shuffle_ps(abcd, abcd, _MM_SHUFFLE(2, 1, 0, 2));+ __m128 dddd = _mm_shuffle_ps(abcd, abcd, _MM_SHUFFLE(3, 3, 3, 3));- __m128 t3 = _mm_shuffle_ps(abcd, abcd, _MM_SHUFFLE(0, 0, 0, 0));- __m128 t4 = _mm_shuffle_ps(xyzw, xyzw, _MM_SHUFFLE(1, 0, 3, 2));+ __m128 wwwx = _mm_shuffle_ps(xyzw, xyzw, _MM_SHUFFLE(0, 3, 3, 3));+ __m128 zxyy = _mm_shuffle_ps(xyzw, xyzw, _MM_SHUFFLE(1, 1, 0, 2));+ __m128 yzxz = _mm_shuffle_ps(xyzw, xyzw, _MM_SHUFFLE(2, 0, 2, 1));- __m128 t5 = _mm_shuffle_ps(abcd, abcd, _MM_SHUFFLE(1, 1, 1, 1));- __m128 t6 = _mm_shuffle_ps(xyzw, xyzw, _MM_SHUFFLE(2, 0, 3, 1));-- // [d,d,d,d] * [z,w,x,y] = [dz,dw,dx,dy]- __m128 m0 = _mm_mul_ps(t0, t1);+ __m128 m2 = _mm_mul_ps(bcab, zxyy);+#ifdef JPH_USE_FMADD+ __m128 m3 = _mm_fmadd_ps(abca, wwwx, m2);+#else+ __m128 m1 = _mm_mul_ps(abca, wwwx);+ __m128 m3 = _mm_add_ps(m1, m2);+#endif- // [a,a,a,a] * [y,x,w,z] = [ay,ax,aw,az]- __m128 m1 = _mm_mul_ps(t3, t4);+ // Negate last (logical) component.+ m3 = _mm_xor_ps(_mm_set_ps(-0.0f, 0.0f, 0.0f, 0.0f), m3);- // [b,b,b,b] * [z,x,w,y] = [bz,bx,bw,by]- __m128 m2 = _mm_mul_ps(t5, t6);+#ifdef JPH_USE_FMADD+ __m128 m5 = _mm_fnmadd_ps(cabc, yzxz, m3);+ __m128 m7 = _mm_fmadd_ps(dddd, xyzw, m5);+#else+ __m128 m4 = _mm_mul_ps(dddd, xyzw);+ __m128 m5 = _mm_mul_ps(cabc, yzxz);+ __m128 m6 = _mm_sub_ps(m4, m5);+ __m128 m7 = _mm_add_ps(m3, m6);+#endif- // [c,c,c,c] * [w,z,x,y] = [cw,cz,cx,cy]- __m128 t7 = _mm_shuffle_ps(abcd, abcd, _MM_SHUFFLE(2, 2, 2, 2));- __m128 t8 = _mm_shuffle_ps(xyzw, xyzw, _MM_SHUFFLE(3, 2, 0, 1));- __m128 m3 = _mm_mul_ps(t7, t8);+ // [(aw+bz)+(dx-cy),(bw+cx)+(dy-az),(cw+ay)+(dz-bx),-(ax+by)+(dw-cz)]+ return Quat(Vec4(m7));+#elif defined(JPH_USE_NEON)+ float32x4_t abcd = mValue.mValue;+ float32x4_t xyzw = inRHS.mValue.mValue;- // [dz,dw,dx,dy] + -[ay,ax,aw,az] = [dz+ay,dw-ax,dx+aw,dy-az]- __m128 e = _mm_addsub_ps(m0, m1);+ float32x4_t abca = vcopyq_laneq_f32(abcd, 3, abcd, 0);+ float32x4_t bcab = JPH_NEON_SHUFFLE_F32x4(abcd, abcd, 1, 2, 0, 1);+ float32x4_t cabc = JPH_NEON_SHUFFLE_F32x4(abcd, abcd, 2, 0, 1, 2);+ float32x4_t dddd = vdupq_laneq_f32(abcd, 3);- // [dx+aw,dz+ay,dy-az,dw-ax]- e = _mm_shuffle_ps(e, e, _MM_SHUFFLE(1, 3, 0, 2));+ float32x4_t wwwx = vcopyq_laneq_f32(vdupq_laneq_f32(xyzw, 3), 3, xyzw, 0);+ float32x4_t zxyy = JPH_NEON_SHUFFLE_F32x4(xyzw, xyzw, 2, 0, 1, 1);+ float32x4_t yzxz = JPH_NEON_SHUFFLE_F32x4(xyzw, xyzw, 1, 2, 0, 2);- // [dx+aw,dz+ay,dy-az,dw-ax] + -[bz,bx,bw,by] = [dx+aw+bz,dz+ay-bx,dy-az+bw,dw-ax-by]- e = _mm_addsub_ps(e, m2);+ float32x4_t m1 = vmulq_f32(abca, wwwx);+ float32x4_t m2 = vmulq_f32(bcab, zxyy);+ float32x4_t m3 = vaddq_f32(m1, m2);- // [dz+ay-bx,dw-ax-by,dy-az+bw,dx+aw+bz]- e = _mm_shuffle_ps(e, e, _MM_SHUFFLE(2, 0, 1, 3));+ uint32x4_t w_neg_mask = JPH_NEON_UINT32x4(0, 0, 0, 0x80000000u);+ m3 = vreinterpretq_f32_u32(veorq_u32(vreinterpretq_u32_f32(m3), w_neg_mask));- // [dz+ay-bx,dw-ax-by,dy-az+bw,dx+aw+bz] + -[cw,cz,cx,cy] = [dz+ay-bx+cw,dw-ax-by-cz,dy-az+bw+cx,dx+aw+bz-cy]- e = _mm_addsub_ps(e, m3);+ float32x4_t m4 = vmulq_f32(dddd, xyzw);+ float32x4_t m5 = vmulq_f32(cabc, yzxz);+ float32x4_t m6 = vsubq_f32(m4, m5);+ float32x4_t m7 = vaddq_f32(m3, m6);- // [dw-ax-by-cz,dz+ay-bx+cw,dy-az+bw+cx,dx+aw+bz-cy]- return Quat(Vec4(_mm_shuffle_ps(e, e, _MM_SHUFFLE(2, 3, 1, 0))));+ return Quat(Vec4(m7));#else- float lx = mValue.GetX();- float ly = mValue.GetY();- float lz = mValue.GetZ();- float lw = mValue.GetW();-- float rx = inRHS.mValue.GetX();- float ry = inRHS.mValue.GetY();- float rz = inRHS.mValue.GetZ();- float rw = inRHS.mValue.GetW();-- float x = lw * rx + lx * rw + ly * rz - lz * ry;- float y = lw * ry - lx * rz + ly * rw + lz * rx;- float z = lw * rz + lx * ry - ly * rx + lz * rw;- float w = lw * rw - lx * rx - ly * ry - lz * rz;-- return Quat(x, y, z, w);+ float a = mValue.GetX();+ float b = mValue.GetY();+ float c = mValue.GetZ();+ float d = mValue.GetW();++ float x = inRHS.mValue.GetX();+ float y = inRHS.mValue.GetY();+ float z = inRHS.mValue.GetZ();+ float w = inRHS.mValue.GetW();++ return Quat((a * w + b * z) + (d * x - c * y),+ (b * w + c * x) + (d * y - a * z),+ (c * w + a * y) + (d * z - b * x),+ -(a * x + b * y) + (d * w - c * z));#endif}Quat Quat::sMultiplyImaginary(Vec3Arg inLHS, QuatArg inRHS){-#if defined(JPH_USE_SSE4_1)+#ifdef JPH_USE_SSE__m128 abc0 = inLHS.mValue;__m128 xyzw = inRHS.mValue.mValue;- // [a,a,a,a] * [w,y,z,x] = [aw,ay,az,ax]- __m128 aaaa = _mm_shuffle_ps(abc0, abc0, _MM_SHUFFLE(0, 0, 0, 0));- __m128 xzyw = _mm_shuffle_ps(xyzw, xyzw, _MM_SHUFFLE(3, 1, 2, 0));- __m128 axazayaw = _mm_mul_ps(aaaa, xzyw);+ // Names based on logical order, opposite of shuffle order.+ __m128 abca = _mm_shuffle_ps(abc0, abc0, _MM_SHUFFLE(0, 2, 1, 0));+ __m128 bcab = _mm_shuffle_ps(abc0, abc0, _MM_SHUFFLE(1, 0, 2, 1));+ __m128 cabc = _mm_shuffle_ps(abc0, abc0, _MM_SHUFFLE(2, 1, 0, 2));- // [b,b,b,b] * [z,x,w,y] = [bz,bx,bw,by]- __m128 bbbb = _mm_shuffle_ps(abc0, abc0, _MM_SHUFFLE(1, 1, 1, 1));- __m128 ywxz = _mm_shuffle_ps(xyzw, xyzw, _MM_SHUFFLE(2, 0, 3, 1));- __m128 bybwbxbz = _mm_mul_ps(bbbb, ywxz);+ __m128 wwwx = _mm_shuffle_ps(xyzw, xyzw, _MM_SHUFFLE(0, 3, 3, 3));+ __m128 zxyy = _mm_shuffle_ps(xyzw, xyzw, _MM_SHUFFLE(1, 1, 0, 2));+ __m128 yzxz = _mm_shuffle_ps(xyzw, xyzw, _MM_SHUFFLE(2, 0, 2, 1));- // [c,c,c,c] * [w,z,x,y] = [cw,cz,cx,cy]- __m128 cccc = _mm_shuffle_ps(abc0, abc0, _MM_SHUFFLE(2, 2, 2, 2));- __m128 yxzw = _mm_shuffle_ps(xyzw, xyzw, _MM_SHUFFLE(3, 2, 0, 1));- __m128 cycxczcw = _mm_mul_ps(cccc, yxzw);+ __m128 m2 = _mm_mul_ps(bcab, zxyy);+#ifdef JPH_USE_FMADD+ __m128 m3 = _mm_fmadd_ps(abca, wwwx, m2);+#else+ __m128 m1 = _mm_mul_ps(abca, wwwx);+ __m128 m3 = _mm_add_ps(m1, m2);+#endif- // [+aw,+ay,-az,-ax]- __m128 e = _mm_xor_ps(axazayaw, _mm_set_ps(0.0f, 0.0f, -0.0f, -0.0f));+ // Negate last (logical) component.+ m3 = _mm_xor_ps(_mm_set_ps(-0.0f, 0.0f, 0.0f, 0.0f), m3);- // [+aw,+ay,-az,-ax] + -[bz,bx,bw,by] = [+aw+bz,+ay-bx,-az+bw,-ax-by]- e = _mm_addsub_ps(e, bybwbxbz);+ __m128 m4 = _mm_mul_ps(cabc, yzxz);- // [+ay-bx,-ax-by,-az+bw,+aw+bz]- e = _mm_shuffle_ps(e, e, _MM_SHUFFLE(2, 0, 1, 3));+ // [(aw+bz)-cy,(bw+cx)-az,(cw+ay)-bx,-(ax+by)-cz]+ return Quat(Vec4(_mm_sub_ps(m3, m4)));+#elif defined(JPH_USE_NEON)+ float32x4_t abc0 = inLHS.mValue;+ float32x4_t xyzw = inRHS.mValue.mValue;- // [+ay-bx,-ax-by,-az+bw,+aw+bz] + -[cw,cz,cx,cy] = [+ay-bx+cw,-ax-by-cz,-az+bw+cx,+aw+bz-cy]- e = _mm_addsub_ps(e, cycxczcw);+ float32x4_t abca = vcopyq_laneq_f32(abc0, 3, abc0, 0);+ float32x4_t bcab = JPH_NEON_SHUFFLE_F32x4(abc0, abc0, 1, 2, 0, 1);+ float32x4_t cabc = JPH_NEON_SHUFFLE_F32x4(abc0, abc0, 2, 0, 1, 2);- // [-ax-by-cz,+ay-bx+cw,-az+bw+cx,+aw+bz-cy]- return Quat(Vec4(_mm_shuffle_ps(e, e, _MM_SHUFFLE(2, 3, 1, 0))));-#else- float lx = inLHS.GetX();- float ly = inLHS.GetY();- float lz = inLHS.GetZ();+ float32x4_t wwwx = vcopyq_laneq_f32(vdupq_laneq_f32(xyzw, 3), 3, xyzw, 0);+ float32x4_t zxyy = JPH_NEON_SHUFFLE_F32x4(xyzw, xyzw, 2, 0, 1, 1);+ float32x4_t yzxz = JPH_NEON_SHUFFLE_F32x4(xyzw, xyzw, 1, 2, 0, 2);++ float32x4_t m1 = vmulq_f32(abca, wwwx);+ float32x4_t m2 = vmulq_f32(bcab, zxyy);+ float32x4_t m3 = vaddq_f32(m1, m2);- float rx = inRHS.mValue.GetX();- float ry = inRHS.mValue.GetY();- float rz = inRHS.mValue.GetZ();- float rw = inRHS.mValue.GetW();+ uint32x4_t w_neg_mask = JPH_NEON_UINT32x4(0, 0, 0, 0x80000000u);+ m3 = vreinterpretq_f32_u32(veorq_u32(vreinterpretq_u32_f32(m3), w_neg_mask));- float x = (lx * rw) + ly * rz - lz * ry;- float y = -(lx * rz) + ly * rw + lz * rx;- float z = (lx * ry) - ly * rx + lz * rw;- float w = -(lx * rx) - ly * ry - lz * rz;+ float32x4_t m4 = vmulq_f32(cabc, yzxz);+ float32x4_t m7 = vsubq_f32(m3, m4);- return Quat(x, y, z, w);+ return Quat(Vec4(m7));+#else+ float a = inLHS.GetX();+ float b = inLHS.GetY();+ float c = inLHS.GetZ();++ float x = inRHS.mValue.GetX();+ float y = inRHS.mValue.GetY();+ float z = inRHS.mValue.GetZ();+ float w = inRHS.mValue.GetW();++ return Quat((a * w + b * z) - c * y,+ (b * w + c * x) - a * z,+ (c * w + a * y) - b * x,+ -(a * x + b * y) - c * z);#endif}@@ -168,7 +200,7 @@ Vec3 Quat::GetAngularVelocity(float inDeltaTime) const// Otherwise calculate the angle from w = cos(angle / 2) and determine the axis by normalizing the imaginary part// Note that it is also possible to calculate the angle through angle = 2 * atan2(|xyz|, w). This is more accurate but also 2x as expensive.float angle = 2.0f * ACos(w_pos.GetW());- return (xyz / (sqrt(xyz_len_sq) * inDeltaTime)) * angle;+ return (xyz / (Sqrt(xyz_len_sq) * inDeltaTime)) * angle;}Quat Quat::sFromTo(Vec3Arg inFrom, Vec3Arg inTo)@@ -203,7 +235,7 @@ Quat Quat::sFromTo(Vec3Arg inFrom, Vec3Arg inTo)which then needs to be normalized because the whole equation was multiplied by 2 cos(angle / 2)*/- float len_v1_v2 = sqrt(inFrom.LengthSq() * inTo.LengthSq());+ float len_v1_v2 = Sqrt(inFrom.LengthSq() * inTo.LengthSq());float w = len_v1_v2 + inFrom.Dot(inTo);if (w == 0.0f)@@ -227,12 +259,13 @@ Quat Quat::sFromTo(Vec3Arg inFrom, Vec3Arg inTo)template <class Random>Quat Quat::sRandom(Random &inRandom){- std::uniform_real_distribution<float> zero_to_one(0.0f, 1.0f);- float x0 = zero_to_one(inRandom);- float r1 = sqrt(1.0f - x0), r2 = sqrt(x0);- std::uniform_real_distribution<float> zero_to_two_pi(0.0f, 2.0f * JPH_PI);+ // Using Uniform Random Rotations - Graphics Gems III - Ken Shoemake+ float x0 = float(inRandom() - inRandom.min()) / float(inRandom.max() - inRandom.min());+ float r1 = Sqrt(1.0f - x0), r2 = Sqrt(x0);+ float theta1 = 2.0f * JPH_PI * float(inRandom() - inRandom.min()) / float(inRandom.max() - inRandom.min());+ float theta2 = 2.0f * JPH_PI * float(inRandom() - inRandom.min()) / float(inRandom.max() - inRandom.min());Vec4 s, c;- Vec4(zero_to_two_pi(inRandom), zero_to_two_pi(inRandom), 0, 0).SinCos(s, c);+ Vec4(theta1, theta2, 0, 0).SinCos(s, c);return Quat(s.GetX() * r1, c.GetX() * r1, s.GetY() * r2, c.GetY() * r2);}@@ -258,20 +291,21 @@ Quat Quat::sEulerAngles(Vec3Arg inAngles)Vec3 Quat::GetEulerAngles() const{- float y_sq = GetY() * GetY();+ float x = GetX(), y = GetY(), z = GetZ(), w = GetW();+ float y_sq = y * y;// X- float t0 = 2.0f * (GetW() * GetX() + GetY() * GetZ());- float t1 = 1.0f - 2.0f * (GetX() * GetX() + y_sq);+ float t0 = 2.0f * (w * x + y * z);+ float t1 = 1.0f - 2.0f * (x * x + y_sq);// Y- float t2 = 2.0f * (GetW() * GetY() - GetZ() * GetX());+ float t2 = 2.0f * (w * y - z * x);t2 = t2 > 1.0f? 1.0f : t2;t2 = t2 < -1.0f? -1.0f : t2;// Z- float t3 = 2.0f * (GetW() * GetZ() + GetX() * GetY());- float t4 = 1.0f - 2.0f * (y_sq + GetZ() * GetZ());+ float t3 = 2.0f * (w * z + x * y);+ float t4 = 1.0f - 2.0f * (y_sq + z * z);return Vec3(ATan2(t0, t1), ASin(t2), ATan2(t3, t4));}@@ -281,7 +315,7 @@ Quat Quat::GetTwist(Vec3Arg inAxis) constQuat twist(Vec4(GetXYZ().Dot(inAxis) * inAxis, GetW()));float twist_len = twist.LengthSq();if (twist_len != 0.0f)- return twist / sqrt(twist_len);+ return twist / Sqrt(twist_len);elsereturn Quat::sIdentity();}@@ -289,7 +323,7 @@ Quat Quat::GetTwist(Vec3Arg inAxis) constvoid Quat::GetSwingTwist(Quat &outSwing, Quat &outTwist) const{float x = GetX(), y = GetY(), z = GetZ(), w = GetW();- float s = sqrt(Square(w) + Square(x));+ float s = Sqrt(Square(w) + Square(x));if (s != 0.0f){outTwist = Quat(x / s, 0, 0, w / s);@@ -306,7 +340,7 @@ void Quat::GetSwingTwist(Quat &outSwing, Quat &outTwist) constQuat Quat::LERP(QuatArg inDestination, float inFraction) const{float scale0 = 1.0f - inFraction;- return Quat(Vec4::sReplicate(scale0) * mValue + Vec4::sReplicate(inFraction) * inDestination.mValue);+ return Quat(scale0 * mValue + inFraction * inDestination.mValue);}Quat Quat::SLERP(QuatArg inDestination, float inFraction) const@@ -343,7 +377,7 @@ Quat Quat::SLERP(QuatArg inDestination, float inFraction) const}// Interpolate between the two quaternions- return Quat(Vec4::sReplicate(scale0) * mValue + Vec4::sReplicate(scale1) * inDestination.mValue).Normalized();+ return Quat(scale0 * mValue + scale1 * inDestination.mValue).Normalized();}Vec3 Quat::operator * (Vec3Arg inValue) const@@ -419,7 +453,7 @@ void Quat::StoreFloat4(Float4 *outV) constQuat Quat::sLoadFloat3Unsafe(const Float3 &inV){Vec3 v = Vec3::sLoadFloat3Unsafe(inV);- float w = sqrt(max(1.0f - v.LengthSq(), 0.0f)); // It is possible that the length of v is a fraction above 1, and we don't want to introduce NaN's in that case so we clamp to 0+ float w = Sqrt(max(1.0f - v.LengthSq(), 0.0f)); // It is possible that the length of v is a fraction above 1, and we don't want to introduce NaN's in that case so we clamp to 0return Quat(Vec4(v, w));}diff --git a/thirdparty/jolt_physics/Jolt/Math/Trigonometry.h b/thirdparty/jolt_physics/Jolt/Math/Trigonometry.hindex 3503dd17bd4..0e8dce73c2b 100644--- a/thirdparty/jolt_physics/Jolt/Math/Trigonometry.h+++ b/thirdparty/jolt_physics/Jolt/Math/Trigonometry.h@@ -58,7 +58,7 @@ JPH_INLINE float ACosApproximate(float inX)// So we observe that the form of the Taylor expansion is f(x) = sqrt(1 - x) * (a + b x) and we fit the function so that f(0) = pi / 2// this gives us a = pi / 2. f(1) = 0 regardless of b. We search for a constant b that minimizes the error in the range [0, 1].float abs_x = min(abs(inX), 1.0f); // Ensure that we don't get a value larger than 1- float val = sqrt(1.0f - abs_x) * (JPH_PI / 2 - 0.175394f * abs_x);+ float val = Sqrt(1.0f - abs_x) * (JPH_PI / 2 - 0.175394f * abs_x);// Our approximation is valid in the range [0, 1], extend it to the range [-1, 1]return inX < 0? JPH_PI - val : val;diff --git a/thirdparty/jolt_physics/Jolt/Math/UVec4.h b/thirdparty/jolt_physics/Jolt/Math/UVec4.hindex 0c30f1f2a01..ba3a4c2c933 100644--- a/thirdparty/jolt_physics/Jolt/Math/UVec4.h+++ b/thirdparty/jolt_physics/Jolt/Math/UVec4.h@@ -225,7 +225,7 @@ public:};};-static_assert(std::is_trivial<UVec4>(), "Is supposed to be a trivial type!");+static_assert(std::is_trivially_default_constructible<UVec4>() && std::is_trivially_copyable<UVec4>(), "Is supposed to be a trivial type!");JPH_NAMESPACE_ENDdiff --git a/thirdparty/jolt_physics/Jolt/Math/UVec4.inl b/thirdparty/jolt_physics/Jolt/Math/UVec4.inlindex 6a0be910b37..ebdc9108448 100644--- a/thirdparty/jolt_physics/Jolt/Math/UVec4.inl+++ b/thirdparty/jolt_physics/Jolt/Math/UVec4.inl@@ -12,6 +12,12 @@ UVec4::UVec4(uint32 inX, uint32 inY, uint32 inZ, uint32 inW)uint32x2_t xy = vcreate_u32(static_cast<uint64>(inX) | (static_cast<uint64>(inY) << 32));uint32x2_t zw = vcreate_u32(static_cast<uint64>(inZ) | (static_cast<uint64>(inW) << 32));mValue = vcombine_u32(xy, zw);+#elif defined(JPH_USE_RVV)+ vuint32m1_t v = __riscv_vmv_v_x_u32m1(inW, 4);+ v = __riscv_vslide1up_vx_u32m1(v, inZ, 4);+ v = __riscv_vslide1up_vx_u32m1(v, inY, 4);+ v = __riscv_vslide1up_vx_u32m1(v, inX, 4);+ __riscv_vse32_v_u32m1(mU32, v, 4);#elsemU32[0] = inX;mU32[1] = inY;@@ -37,6 +43,14 @@ UVec4 UVec4::Swizzle() constreturn _mm_shuffle_epi32(mValue, _MM_SHUFFLE(SwizzleW, SwizzleZ, SwizzleY, SwizzleX));#elif defined(JPH_USE_NEON)return JPH_NEON_SHUFFLE_U32x4(mValue, mValue, SwizzleX, SwizzleY, SwizzleZ, SwizzleW);+#elif defined(JPH_USE_RVV)+ UVec4 v;+ const vuint32m1_t data = __riscv_vle32_v_u32m1(mU32, 4);+ const uint32 stored_indices[4] = { SwizzleX, SwizzleY, SwizzleZ, SwizzleW };+ const vuint32m1_t index = __riscv_vle32_v_u32m1(stored_indices, 4);+ const vuint32m1_t swizzled = __riscv_vrgather_vv_u32m1(data, index, 4);+ __riscv_vse32_v_u32m1(v.mU32, swizzled, 4);+ return v;#elsereturn UVec4(mU32[SwizzleX], mU32[SwizzleY], mU32[SwizzleZ], mU32[SwizzleW]);#endif@@ -48,6 +62,11 @@ UVec4 UVec4::sZero()return _mm_setzero_si128();#elif defined(JPH_USE_NEON)return vdupq_n_u32(0);+#elif defined(JPH_USE_RVV)+ UVec4 v;+ const vuint32m1_t zero_vec = __riscv_vmv_v_x_u32m1(0, 4);+ __riscv_vse32_v_u32m1(v.mU32, zero_vec, 4);+ return v;#elsereturn UVec4(0, 0, 0, 0);#endif@@ -59,6 +78,11 @@ UVec4 UVec4::sReplicate(uint32 inV)return _mm_set1_epi32(int(inV));#elif defined(JPH_USE_NEON)return vdupq_n_u32(inV);+#elif defined(JPH_USE_RVV)+ UVec4 vec;+ const vuint32m1_t v = __riscv_vmv_v_x_u32m1(inV, 4);+ __riscv_vse32_v_u32m1(vec.mU32, v, 4);+ return vec;#elsereturn UVec4(inV, inV, inV, inV);#endif@@ -81,6 +105,11 @@ UVec4 UVec4::sLoadInt4(const uint32 *inV)return _mm_loadu_si128(reinterpret_cast<const __m128i *>(inV));#elif defined(JPH_USE_NEON)return vld1q_u32(inV);+#elif defined(JPH_USE_RVV)+ UVec4 vector;+ const vuint32m1_t v = __riscv_vle32_v_u32m1(inV, 4);+ __riscv_vse32_v_u32m1(vector.mU32, v, 4);+ return vector;#elsereturn UVec4(inV[0], inV[1], inV[2], inV[3]);#endif@@ -92,6 +121,11 @@ UVec4 UVec4::sLoadInt4Aligned(const uint32 *inV)return _mm_load_si128(reinterpret_cast<const __m128i *>(inV));#elif defined(JPH_USE_NEON)return vld1q_u32(inV); // ARM doesn't make distinction between aligned or not+#elif defined(JPH_USE_RVV)+ UVec4 vector;+ const vuint32m1_t v = __riscv_vle32_v_u32m1(inV, 4);+ __riscv_vse32_v_u32m1(vector.mU32, v, 4);+ return vector;#elsereturn UVec4(inV[0], inV[1], inV[2], inV[3]);#endif@@ -102,6 +136,13 @@ UVec4 UVec4::sGatherInt4(const uint32 *inBase, UVec4Arg inOffsets){#ifdef JPH_USE_AVX2return _mm_i32gather_epi32(reinterpret_cast<const int *>(inBase), inOffsets.mValue, Scale);+#elif defined(JPH_USE_RVV)+ UVec4 v;+ const vuint32m1_t offsets = __riscv_vle32_v_u32m1(inOffsets.mU32, 4);+ const vuint32m1_t scaled_offsets = __riscv_vmul_vx_u32m1(offsets, Scale, 4);+ const vuint32m1_t gathered = __riscv_vluxei32_v_u32m1(inBase, scaled_offsets, 4);+ __riscv_vse32_v_u32m1(v.mU32, gathered, 4);+ return v;#elseconst uint8 *base = reinterpret_cast<const uint8 *>(inBase);uint32 x = *reinterpret_cast<const uint32 *>(base + inOffsets.GetX() * Scale);@@ -118,6 +159,13 @@ UVec4 UVec4::sMin(UVec4Arg inV1, UVec4Arg inV2)return _mm_min_epu32(inV1.mValue, inV2.mValue);#elif defined(JPH_USE_NEON)return vminq_u32(inV1.mValue, inV2.mValue);+#elif defined(JPH_USE_RVV)+ UVec4 res;+ const vuint32m1_t v1 = __riscv_vle32_v_u32m1(inV1.mU32, 4);+ const vuint32m1_t v2 = __riscv_vle32_v_u32m1(inV2.mU32, 4);+ const vuint32m1_t min = __riscv_vminu_vv_u32m1(v1, v2, 4);+ __riscv_vse32_v_u32m1(res.mU32, min, 4);+ return res;#elseUVec4 result;for (int i = 0; i < 4; i++)@@ -132,6 +180,13 @@ UVec4 UVec4::sMax(UVec4Arg inV1, UVec4Arg inV2)return _mm_max_epu32(inV1.mValue, inV2.mValue);#elif defined(JPH_USE_NEON)return vmaxq_u32(inV1.mValue, inV2.mValue);+#elif defined(JPH_USE_RVV)+ UVec4 res;+ const vuint32m1_t v1 = __riscv_vle32_v_u32m1(inV1.mU32, 4);+ const vuint32m1_t v2 = __riscv_vle32_v_u32m1(inV2.mU32, 4);+ const vuint32m1_t max = __riscv_vmaxu_vv_u32m1(v1, v2, 4);+ __riscv_vse32_v_u32m1(res.mU32, max, 4);+ return res;#elseUVec4 result;for (int i = 0; i < 4; i++)@@ -146,6 +201,15 @@ UVec4 UVec4::sEquals(UVec4Arg inV1, UVec4Arg inV2)return _mm_cmpeq_epi32(inV1.mValue, inV2.mValue);#elif defined(JPH_USE_NEON)return vceqq_u32(inV1.mValue, inV2.mValue);+#elif defined(JPH_USE_RVV)+ UVec4 res;+ const vuint32m1_t v1 = __riscv_vle32_v_u32m1(inV1.mU32, 4);+ const vuint32m1_t v2 = __riscv_vle32_v_u32m1(inV2.mU32, 4);+ const vbool32_t mask = __riscv_vmseq_vv_u32m1_b32(v1, v2, 4);+ const vuint32m1_t zeros = __riscv_vmv_v_x_u32m1(0x0, 4);+ const vuint32m1_t merged = __riscv_vmerge_vxm_u32m1(zeros, 0xFFFFFFFF, mask, 4);+ __riscv_vse32_v_u32m1(res.mU32, merged, 4);+ return res;#elsereturn UVec4(inV1.mU32[0] == inV2.mU32[0]? 0xffffffffu : 0,inV1.mU32[1] == inV2.mU32[1]? 0xffffffffu : 0,@@ -163,6 +227,18 @@ UVec4 UVec4::sSelect(UVec4Arg inNotSet, UVec4Arg inSet, UVec4Arg inControl)return _mm_castps_si128(_mm_or_ps(_mm_and_ps(is_set, _mm_castsi128_ps(inSet.mValue)), _mm_andnot_ps(is_set, _mm_castsi128_ps(inNotSet.mValue))));#elif defined(JPH_USE_NEON)return vbslq_u32(vreinterpretq_u32_s32(vshrq_n_s32(vreinterpretq_s32_u32(inControl.mValue), 31)), inSet.mValue, inNotSet.mValue);+#elif defined(JPH_USE_RVV)+ UVec4 masked;+ const vuint32m1_t control = __riscv_vle32_v_u32m1(inControl.mU32, 4);+ const vuint32m1_t not_set = __riscv_vle32_v_u32m1(inNotSet.mU32, 4);+ const vuint32m1_t set = __riscv_vle32_v_u32m1(inSet.mU32, 4);++ // Generate RVV bool mask from UVec4+ const vuint32m1_t r = __riscv_vand_vx_u32m1(control, 0x80000000u, 4);+ const vbool32_t rvv_mask = __riscv_vmsne_vx_u32m1_b32(r, 0x0, 4);+ const vuint32m1_t merged = __riscv_vmerge_vvm_u32m1(not_set, set, rvv_mask, 4);+ __riscv_vse32_v_u32m1(masked.mU32, merged, 4);+ return masked;#elseUVec4 result;for (int i = 0; i < 4; i++)@@ -177,6 +253,13 @@ UVec4 UVec4::sOr(UVec4Arg inV1, UVec4Arg inV2)return _mm_or_si128(inV1.mValue, inV2.mValue);#elif defined(JPH_USE_NEON)return vorrq_u32(inV1.mValue, inV2.mValue);+#elif defined(JPH_USE_RVV)+ UVec4 or_result;+ const vuint32m1_t v1 = __riscv_vle32_v_u32m1(inV1.mU32, 4);+ const vuint32m1_t v2 = __riscv_vle32_v_u32m1(inV2.mU32, 4);+ const vuint32m1_t res = __riscv_vor_vv_u32m1(v1, v2, 4);+ __riscv_vse32_v_u32m1(or_result.mU32, res, 4);+ return or_result;#elsereturn UVec4(inV1.mU32[0] | inV2.mU32[0],inV1.mU32[1] | inV2.mU32[1],@@ -191,6 +274,13 @@ UVec4 UVec4::sXor(UVec4Arg inV1, UVec4Arg inV2)return _mm_xor_si128(inV1.mValue, inV2.mValue);#elif defined(JPH_USE_NEON)return veorq_u32(inV1.mValue, inV2.mValue);+#elif defined(JPH_USE_RVV)+ UVec4 xor_result;+ const vuint32m1_t v1 = __riscv_vle32_v_u32m1(inV1.mU32, 4);+ const vuint32m1_t v2 = __riscv_vle32_v_u32m1(inV2.mU32, 4);+ const vuint32m1_t res = __riscv_vxor_vv_u32m1(v1, v2, 4);+ __riscv_vse32_v_u32m1(xor_result.mU32, res, 4);+ return xor_result;#elsereturn UVec4(inV1.mU32[0] ^ inV2.mU32[0],inV1.mU32[1] ^ inV2.mU32[1],@@ -205,6 +295,13 @@ UVec4 UVec4::sAnd(UVec4Arg inV1, UVec4Arg inV2)return _mm_and_si128(inV1.mValue, inV2.mValue);#elif defined(JPH_USE_NEON)return vandq_u32(inV1.mValue, inV2.mValue);+#elif defined(JPH_USE_RVV)+ UVec4 and_result;+ const vuint32m1_t v1 = __riscv_vle32_v_u32m1(inV1.mU32, 4);+ const vuint32m1_t v2 = __riscv_vle32_v_u32m1(inV2.mU32, 4);+ const vuint32m1_t res = __riscv_vand_vv_u32m1(v1, v2, 4);+ __riscv_vse32_v_u32m1(and_result.mU32, res, 4);+ return and_result;#elsereturn UVec4(inV1.mU32[0] & inV2.mU32[0],inV1.mU32[1] & inV2.mU32[1],@@ -222,6 +319,12 @@ UVec4 UVec4::sNot(UVec4Arg inV1)return sXor(inV1, sReplicate(0xffffffff));#elif defined(JPH_USE_NEON)return vmvnq_u32(inV1.mValue);+#elif defined(JPH_USE_RVV)+ UVec4 v;+ const vuint32m1_t src = __riscv_vle32_v_u32m1(inV1.mU32, 4);+ const vuint32m1_t rvv_not = __riscv_vxor_vx_u32m1(src, -1, 4);+ __riscv_vse32_v_u32m1(v.mU32, rvv_not, 4);+ return v;#elsereturn UVec4(~inV1.mU32[0], ~inV1.mU32[1], ~inV1.mU32[2], ~inV1.mU32[3]);#endif@@ -247,6 +350,13 @@ UVec4 UVec4::operator * (UVec4Arg inV2) constreturn _mm_mullo_epi32(mValue, inV2.mValue);#elif defined(JPH_USE_NEON)return vmulq_u32(mValue, inV2.mValue);+#elif defined(JPH_USE_RVV)+ UVec4 res;+ const vuint32m1_t v1 = __riscv_vle32_v_u32m1(mU32, 4);+ const vuint32m1_t v2 = __riscv_vle32_v_u32m1(inV2.mU32, 4);+ const vuint32m1_t mul = __riscv_vmul_vv_u32m1(v1, v2, 4);+ __riscv_vse32_v_u32m1(res.mU32, mul, 4);+ return res;#elseUVec4 result;for (int i = 0; i < 4; i++)@@ -261,6 +371,13 @@ UVec4 UVec4::operator + (UVec4Arg inV2) constreturn _mm_add_epi32(mValue, inV2.mValue);#elif defined(JPH_USE_NEON)return vaddq_u32(mValue, inV2.mValue);+#elif defined(JPH_USE_RVV)+ UVec4 res;+ const vuint32m1_t v1 = __riscv_vle32_v_u32m1(mU32, 4);+ const vuint32m1_t v2 = __riscv_vle32_v_u32m1(inV2.mU32, 4);+ const vuint32m1_t rvv_add = __riscv_vadd_vv_u32m1(v1, v2, 4);+ __riscv_vse32_v_u32m1(res.mU32, rvv_add, 4);+ return res;#elsereturn UVec4(mU32[0] + inV2.mU32[0],mU32[1] + inV2.mU32[1],@@ -275,6 +392,11 @@ UVec4 &UVec4::operator += (UVec4Arg inV2)mValue = _mm_add_epi32(mValue, inV2.mValue);#elif defined(JPH_USE_NEON)mValue = vaddq_u32(mValue, inV2.mValue);+#elif defined(JPH_USE_RVV)+ const vuint32m1_t v1 = __riscv_vle32_v_u32m1(mU32, 4);+ const vuint32m1_t v2 = __riscv_vle32_v_u32m1(inV2.mU32, 4);+ const vuint32m1_t rvv_add = __riscv_vadd_vv_u32m1(v1, v2, 4);+ __riscv_vse32_v_u32m1(mU32, rvv_add, 4);#elsefor (int i = 0; i < 4; ++i)mU32[i] += inV2.mU32[i];@@ -288,6 +410,13 @@ UVec4 UVec4::operator - (UVec4Arg inV2) constreturn _mm_sub_epi32(mValue, inV2.mValue);#elif defined(JPH_USE_NEON)return vsubq_u32(mValue, inV2.mValue);+#elif defined(JPH_USE_RVV)+ UVec4 res;+ const vuint32m1_t v1 = __riscv_vle32_v_u32m1(mU32, 4);+ const vuint32m1_t v2 = __riscv_vle32_v_u32m1(inV2.mU32, 4);+ const vuint32m1_t rvv_add = __riscv_vsub_vv_u32m1(v1, v2, 4);+ __riscv_vse32_v_u32m1(res.mU32, rvv_add, 4);+ return res;#elsereturn UVec4(mU32[0] - inV2.mU32[0],mU32[1] - inV2.mU32[1],@@ -302,6 +431,11 @@ UVec4 &UVec4::operator -= (UVec4Arg inV2)mValue = _mm_sub_epi32(mValue, inV2.mValue);#elif defined(JPH_USE_NEON)mValue = vsubq_u32(mValue, inV2.mValue);+#elif defined(JPH_USE_RVV)+ const vuint32m1_t v1 = __riscv_vle32_v_u32m1(mU32, 4);+ const vuint32m1_t v2 = __riscv_vle32_v_u32m1(inV2.mU32, 4);+ const vuint32m1_t rvv_sub = __riscv_vsub_vv_u32m1(v1, v2, 4);+ __riscv_vse32_v_u32m1(mU32, rvv_sub, 4);#elsefor (int i = 0; i < 4; ++i)mU32[i] -= inV2.mU32[i];@@ -315,6 +449,11 @@ UVec4 UVec4::SplatX() constreturn _mm_shuffle_epi32(mValue, _MM_SHUFFLE(0, 0, 0, 0));#elif defined(JPH_USE_NEON)return vdupq_laneq_u32(mValue, 0);+#elif defined(JPH_USE_RVV)+ UVec4 vec;+ const vuint32m1_t splat = __riscv_vmv_v_x_u32m1(mU32[0], 4);+ __riscv_vse32_v_u32m1(vec.mU32, splat, 4);+ return vec;#elsereturn UVec4(mU32[0], mU32[0], mU32[0], mU32[0]);#endif@@ -326,6 +465,11 @@ UVec4 UVec4::SplatY() constreturn _mm_shuffle_epi32(mValue, _MM_SHUFFLE(1, 1, 1, 1));#elif defined(JPH_USE_NEON)return vdupq_laneq_u32(mValue, 1);+#elif defined(JPH_USE_RVV)+ UVec4 vec;+ const vuint32m1_t splat = __riscv_vmv_v_x_u32m1(mU32[1], 4);+ __riscv_vse32_v_u32m1(vec.mU32, splat, 4);+ return vec;#elsereturn UVec4(mU32[1], mU32[1], mU32[1], mU32[1]);#endif@@ -337,6 +481,11 @@ UVec4 UVec4::SplatZ() constreturn _mm_shuffle_epi32(mValue, _MM_SHUFFLE(2, 2, 2, 2));#elif defined(JPH_USE_NEON)return vdupq_laneq_u32(mValue, 2);+#elif defined(JPH_USE_RVV)+ UVec4 vec;+ const vuint32m1_t splat = __riscv_vmv_v_x_u32m1(mU32[2], 4);+ __riscv_vse32_v_u32m1(vec.mU32, splat, 4);+ return vec;#elsereturn UVec4(mU32[2], mU32[2], mU32[2], mU32[2]);#endif@@ -348,6 +497,11 @@ UVec4 UVec4::SplatW() constreturn _mm_shuffle_epi32(mValue, _MM_SHUFFLE(3, 3, 3, 3));#elif defined(JPH_USE_NEON)return vdupq_laneq_u32(mValue, 3);+#elif defined(JPH_USE_RVV)+ UVec4 vec;+ const vuint32m1_t splat = __riscv_vmv_v_x_u32m1(mU32[3], 4);+ __riscv_vse32_v_u32m1(vec.mU32, splat, 4);+ return vec;#elsereturn UVec4(mU32[3], mU32[3], mU32[3], mU32[3]);#endif@@ -359,6 +513,12 @@ Vec4 UVec4::ToFloat() constreturn _mm_cvtepi32_ps(mValue);#elif defined(JPH_USE_NEON)return vcvtq_f32_u32(mValue);+#elif defined(JPH_USE_RVV)+ Vec4 res;+ const vuint32m1_t v = __riscv_vle32_v_u32m1(mU32, 4);+ const vfloat32m1_t v_float = __riscv_vfcvt_f_xu_v_f32m1(v, 4);+ __riscv_vse32_v_f32m1(res.mF32, v_float, 4);+ return res;#elsereturn Vec4((float)mU32[0], (float)mU32[1], (float)mU32[2], (float)mU32[3]);#endif@@ -379,11 +539,22 @@ UVec4 UVec4::DotV(UVec4Arg inV2) const{#if defined(JPH_USE_SSE4_1)__m128i mul = _mm_mullo_epi32(mValue, inV2.mValue);- __m128i sum = _mm_add_epi32(mul, _mm_shuffle_epi32(mul, _MM_SHUFFLE(2, 3, 0, 1)));- return _mm_add_epi32(sum, _mm_shuffle_epi32(sum, _MM_SHUFFLE(1, 0, 3, 2)));+ __m128i sum = _mm_add_epi32(mul, _mm_shuffle_epi32(mul, _MM_SHUFFLE(2, 3, 0, 1)));+ return _mm_add_epi32(sum, _mm_shuffle_epi32(sum, _MM_SHUFFLE(1, 0, 3, 2)));#elif defined(JPH_USE_NEON)uint32x4_t mul = vmulq_u32(mValue, inV2.mValue);return vdupq_n_u32(vaddvq_u32(mul));+#elif defined(JPH_USE_RVV)+ UVec4 res;+ const vuint32m1_t zeros = __riscv_vmv_v_x_u32m1(0, 4);+ const vuint32m1_t v1 = __riscv_vle32_v_u32m1(mU32, 4);+ const vuint32m1_t v2 = __riscv_vle32_v_u32m1(inV2.mU32, 4);+ const vuint32m1_t mul = __riscv_vmul_vv_u32m1(v1, v2, 4);+ const vuint32m1_t sum = __riscv_vredsum_vs_u32m1_u32m1(mul, zeros, 4);+ const vuint32m1_t splat = __riscv_vrgather_vx_u32m1(sum, 0, 4);+ __riscv_vse32_v_u32m1(res.mU32, splat, 4);+ return res;+#elsereturn UVec4::sReplicate(mU32[0] * inV2.mU32[0] + mU32[1] * inV2.mU32[1] + mU32[2] * inV2.mU32[2] + mU32[3] * inV2.mU32[3]);#endif@@ -393,11 +564,18 @@ uint32 UVec4::Dot(UVec4Arg inV2) const{#if defined(JPH_USE_SSE4_1)__m128i mul = _mm_mullo_epi32(mValue, inV2.mValue);- __m128i sum = _mm_add_epi32(mul, _mm_shuffle_epi32(mul, _MM_SHUFFLE(2, 3, 0, 1)));- return _mm_cvtsi128_si32(_mm_add_epi32(sum, _mm_shuffle_epi32(sum, _MM_SHUFFLE(1, 0, 3, 2))));+ __m128i sum = _mm_add_epi32(mul, _mm_shuffle_epi32(mul, _MM_SHUFFLE(2, 3, 0, 1)));+ return _mm_cvtsi128_si32(_mm_add_epi32(sum, _mm_shuffle_epi32(sum, _MM_SHUFFLE(1, 0, 3, 2))));#elif defined(JPH_USE_NEON)uint32x4_t mul = vmulq_u32(mValue, inV2.mValue);return vaddvq_u32(mul);+#elif defined(JPH_USE_RVV)+ const vuint32m1_t zeros = __riscv_vmv_v_x_u32m1(0, 4);+ const vuint32m1_t v1 = __riscv_vle32_v_u32m1(mU32, 4);+ const vuint32m1_t v2 = __riscv_vle32_v_u32m1(inV2.mU32, 4);+ const vuint32m1_t mul = __riscv_vmul_vv_u32m1(v1, v2, 4);+ const vuint32m1_t sum = __riscv_vredsum_vs_u32m1_u32m1(mul, zeros, 4);+ return __riscv_vmv_x_s_u32m1_u32(sum);#elsereturn mU32[0] * inV2.mU32[0] + mU32[1] * inV2.mU32[1] + mU32[2] * inV2.mU32[2] + mU32[3] * inV2.mU32[3];#endif@@ -409,6 +587,9 @@ void UVec4::StoreInt4(uint32 *outV) const_mm_storeu_si128(reinterpret_cast<__m128i *>(outV), mValue);#elif defined(JPH_USE_NEON)vst1q_u32(outV, mValue);+#elif defined(JPH_USE_RVV)+ const vuint32m1_t v = __riscv_vle32_v_u32m1(mU32, 4);+ __riscv_vse32_v_u32m1(outV, v, 4);#elsefor (int i = 0; i < 4; ++i)outV[i] = mU32[i];@@ -421,6 +602,9 @@ void UVec4::StoreInt4Aligned(uint32 *outV) const_mm_store_si128(reinterpret_cast<__m128i *>(outV), mValue);#elif defined(JPH_USE_NEON)vst1q_u32(outV, mValue); // ARM doesn't make distinction between aligned or not+#elif defined(JPH_USE_RVV)+ const vuint32m1_t v = __riscv_vle32_v_u32m1(mU32, 4);+ __riscv_vse32_v_u32m1(outV, v, 4);#elsefor (int i = 0; i < 4; ++i)outV[i] = mU32[i];@@ -433,6 +617,11 @@ int UVec4::CountTrues() constreturn CountBits(_mm_movemask_ps(_mm_castsi128_ps(mValue)));#elif defined(JPH_USE_NEON)return vaddvq_u32(vshrq_n_u32(mValue, 31));+#elif defined(JPH_USE_RVV)+ const vuint32m1_t src = __riscv_vle32_v_u32m1(mU32, 4);+ const vuint32m1_t filter = __riscv_vand_vx_u32m1(src, 0x80000000, 4);+ const vbool32_t mask = __riscv_vmsne_vx_u32m1_b32(filter, 0, 4);+ return __riscv_vcpop_m_b32(mask, 4);#elsereturn (mU32[0] >> 31) + (mU32[1] >> 31) + (mU32[2] >> 31) + (mU32[3] >> 31);#endif@@ -445,6 +634,12 @@ int UVec4::GetTrues() const#elif defined(JPH_USE_NEON)int32x4_t shift = JPH_NEON_INT32x4(0, 1, 2, 3);return vaddvq_u32(vshlq_u32(vshrq_n_u32(mValue, 31), shift));+#elif defined(JPH_USE_RVV)+ const vuint32m1_t src = __riscv_vle32_v_u32m1(mU32, 4);+ const vbool32_t mask = __riscv_vmsgeu_vx_u32m1_b32(src, 0x80000000, 4);+ const vuint32m1_t as_int = __riscv_vreinterpret_v_b32_u32m1(mask);+ const uint32 result = __riscv_vmv_x_s_u32m1_u32(as_int) & 0xF;+ return result;#elsereturn (mU32[0] >> 31) | ((mU32[1] >> 31) << 1) | ((mU32[2] >> 31) << 2) | ((mU32[3] >> 31) << 3);#endif@@ -479,6 +674,13 @@ UVec4 UVec4::LogicalShiftLeft() constreturn _mm_slli_epi32(mValue, Count);#elif defined(JPH_USE_NEON)return vshlq_n_u32(mValue, Count);+#elif defined(JPH_USE_RVV)+ const vuint32m1_t v = __riscv_vle32_v_u32m1(mU32, 4);+ const vuint32m1_t shifted = __riscv_vsll_vx_u32m1(v, Count, 4);++ UVec4 vec;+ __riscv_vse32_v_u32m1(vec.mU32, shifted, 4);+ return vec;#elsereturn UVec4(mU32[0] << Count, mU32[1] << Count, mU32[2] << Count, mU32[3] << Count);#endif@@ -493,6 +695,13 @@ UVec4 UVec4::LogicalShiftRight() constreturn _mm_srli_epi32(mValue, Count);#elif defined(JPH_USE_NEON)return vshrq_n_u32(mValue, Count);+#elif defined(JPH_USE_RVV)+ const vuint32m1_t v = __riscv_vle32_v_u32m1(mU32, 4);+ const vuint32m1_t shifted = __riscv_vsrl_vx_u32m1(v, Count, 4);++ UVec4 vec;+ __riscv_vse32_v_u32m1(vec.mU32, shifted, 4);+ return vec;#elsereturn UVec4(mU32[0] >> Count, mU32[1] >> Count, mU32[2] >> Count, mU32[3] >> Count);#endif@@ -507,11 +716,18 @@ UVec4 UVec4::ArithmeticShiftRight() constreturn _mm_srai_epi32(mValue, Count);#elif defined(JPH_USE_NEON)return vreinterpretq_u32_s32(vshrq_n_s32(vreinterpretq_s32_u32(mValue), Count));+#elif defined(JPH_USE_RVV)+ const vint32m1_t v = __riscv_vle32_v_i32m1(reinterpret_cast<const int32 *>(mU32), 4);+ const vint32m1_t shifted = __riscv_vsra_vx_i32m1(v, Count, 4);++ UVec4 vec;+ __riscv_vse32_v_i32m1(reinterpret_cast<int32 *>(vec.mU32), shifted, 4);+ return vec;#else- return UVec4(uint32(int32_t(mU32[0]) >> Count),- uint32(int32_t(mU32[1]) >> Count),- uint32(int32_t(mU32[2]) >> Count),- uint32(int32_t(mU32[3]) >> Count));+ return UVec4(uint32(int32(mU32[0]) >> Count),+ uint32(int32(mU32[1]) >> Count),+ uint32(int32(mU32[2]) >> Count),+ uint32(int32(mU32[3]) >> Count));#endif}@@ -523,6 +739,13 @@ UVec4 UVec4::Expand4Uint16Lo() constuint16x4_t value = vget_low_u16(vreinterpretq_u16_u32(mValue));uint16x4_t zero = vdup_n_u16(0);return vreinterpretq_u32_u16(vcombine_u16(vzip1_u16(value, zero), vzip2_u16(value, zero)));+#elif defined(JPH_USE_RVV)+ const vuint16mf2_t v = __riscv_vle16_v_u16mf2(reinterpret_cast<const uint16 *>(mU32), 4);+ const vuint32m1_t zext = __riscv_vzext_vf2_u32m1(v, 4);++ UVec4 res;+ __riscv_vse32_v_u32m1(res.mU32, zext, 4);+ return res;#elsereturn UVec4(mU32[0] & 0xffff,(mU32[0] >> 16) & 0xffff,@@ -539,6 +762,13 @@ UVec4 UVec4::Expand4Uint16Hi() constuint16x4_t value = vget_high_u16(vreinterpretq_u16_u32(mValue));uint16x4_t zero = vdup_n_u16(0);return vreinterpretq_u32_u16(vcombine_u16(vzip1_u16(value, zero), vzip2_u16(value, zero)));+#elif defined(JPH_USE_RVV)+ const vuint16mf2_t v = __riscv_vle16_v_u16mf2(reinterpret_cast<const uint16 *>(&mU32[2]), 4);+ const vuint32m1_t zext = __riscv_vzext_vf2_u32m1(v, 4);++ UVec4 res;+ __riscv_vse32_v_u32m1(res.mU32, zext, 4);+ return res;#elsereturn UVec4(mU32[2] & 0xffff,(mU32[2] >> 16) & 0xffff,@@ -554,6 +784,13 @@ UVec4 UVec4::Expand4Byte0() const#elif defined(JPH_USE_NEON)uint8x16_t idx = JPH_NEON_UINT8x16(0x00, 0x7f, 0x7f, 0x7f, 0x01, 0x7f, 0x7f, 0x7f, 0x02, 0x7f, 0x7f, 0x7f, 0x03, 0x7f, 0x7f, 0x7f);return vreinterpretq_u32_s8(vqtbl1q_s8(vreinterpretq_s8_u32(mValue), idx));+#elif defined(JPH_USE_RVV)+ const vuint8mf4_t v = __riscv_vle8_v_u8mf4(reinterpret_cast<const uint8 *>(mU32), 4);+ const vuint32m1_t zext = __riscv_vzext_vf4_u32m1(v, 4);++ UVec4 res;+ __riscv_vse32_v_u32m1(res.mU32, zext, 4);+ return res;#elseUVec4 result;for (int i = 0; i < 4; i++)@@ -569,6 +806,13 @@ UVec4 UVec4::Expand4Byte4() const#elif defined(JPH_USE_NEON)uint8x16_t idx = JPH_NEON_UINT8x16(0x04, 0x7f, 0x7f, 0x7f, 0x05, 0x7f, 0x7f, 0x7f, 0x06, 0x7f, 0x7f, 0x7f, 0x07, 0x7f, 0x7f, 0x7f);return vreinterpretq_u32_s8(vqtbl1q_s8(vreinterpretq_s8_u32(mValue), idx));+#elif defined(JPH_USE_RVV)+ const vuint8mf4_t v = __riscv_vle8_v_u8mf4(reinterpret_cast<const uint8 *>(&mU32[1]), 4);+ const vuint32m1_t zext = __riscv_vzext_vf4_u32m1(v, 4);++ UVec4 res;+ __riscv_vse32_v_u32m1(res.mU32, zext, 4);+ return res;#elseUVec4 result;for (int i = 0; i < 4; i++)@@ -584,6 +828,13 @@ UVec4 UVec4::Expand4Byte8() const#elif defined(JPH_USE_NEON)uint8x16_t idx = JPH_NEON_UINT8x16(0x08, 0x7f, 0x7f, 0x7f, 0x09, 0x7f, 0x7f, 0x7f, 0x0a, 0x7f, 0x7f, 0x7f, 0x0b, 0x7f, 0x7f, 0x7f);return vreinterpretq_u32_s8(vqtbl1q_s8(vreinterpretq_s8_u32(mValue), idx));+#elif defined(JPH_USE_RVV)+ const vuint8mf4_t v = __riscv_vle8_v_u8mf4(reinterpret_cast<const uint8 *>(&mU32[2]), 4);+ const vuint32m1_t zext = __riscv_vzext_vf4_u32m1(v, 4);++ UVec4 res;+ __riscv_vse32_v_u32m1(res.mU32, zext, 4);+ return res;#elseUVec4 result;for (int i = 0; i < 4; i++)@@ -599,6 +850,13 @@ UVec4 UVec4::Expand4Byte12() const#elif defined(JPH_USE_NEON)uint8x16_t idx = JPH_NEON_UINT8x16(0x0c, 0x7f, 0x7f, 0x7f, 0x0d, 0x7f, 0x7f, 0x7f, 0x0e, 0x7f, 0x7f, 0x7f, 0x0f, 0x7f, 0x7f, 0x7f);return vreinterpretq_u32_s8(vqtbl1q_s8(vreinterpretq_s8_u32(mValue), idx));+#elif defined(JPH_USE_RVV)+ const vuint8mf4_t v = __riscv_vle8_v_u8mf4(reinterpret_cast<const uint8 *>(&mU32[3]), 4);+ const vuint32m1_t zext = __riscv_vzext_vf4_u32m1(v, 4);++ UVec4 res;+ __riscv_vse32_v_u32m1(res.mU32, zext, 4);+ return res;#elseUVec4 result;for (int i = 0; i < 4; i++)@@ -625,6 +883,13 @@ UVec4 UVec4::ShiftComponents4Minus(int inCount) const#elif defined(JPH_USE_NEON)uint8x16_t idx = vreinterpretq_u8_u32(*reinterpret_cast<const UVec4::Type *>(sFourMinusXShuffle[inCount]));return vreinterpretq_u32_s8(vqtbl1q_s8(vreinterpretq_s8_u32(mValue), idx));+#elif defined(JPH_USE_RVV)+ const uint32 *start_ptr = mU32 + (4 - inCount);+ const vuint32m1_t v = __riscv_vle32_v_u32m1(start_ptr, inCount);++ UVec4 res = sZero();+ __riscv_vse32_v_u32m1(res.mU32, v, inCount);+ return res;#elseUVec4 result = UVec4::sZero();for (int i = 0; i < inCount; i++)diff --git a/thirdparty/jolt_physics/Jolt/Math/Vec3.h b/thirdparty/jolt_physics/Jolt/Math/Vec3.hindex 60df89d8143..bb9d7ec7d41 100644--- a/thirdparty/jolt_physics/Jolt/Math/Vec3.h+++ b/thirdparty/jolt_physics/Jolt/Math/Vec3.h@@ -223,9 +223,15 @@ public:/// Reciprocal vector (1 / value) for each of the componentsJPH_INLINE Vec3 Reciprocal() const;+ /// Calculates inA * inB - inC * inD with more precision when FMA instructions are available. See DifferenceOfProducts.+ JPH_INLINE static Vec3 sDifferenceOfProducts(Vec3Arg inA, Vec3Arg inB, Vec3Arg inC, Vec3Arg inD);+/// Cross productJPH_INLINE Vec3 Cross(Vec3Arg inV2) const;+ /// Cross product (more precise version when FMA is available)+ JPH_INLINE Vec3 CrossPrecise(Vec3Arg inV2) const;+/// Dot product, returns the dot product in X, Y and Z componentsJPH_INLINE Vec3 DotV(Vec3Arg inV2) const;@@ -262,6 +268,9 @@ public:/// Get the maximum of X, Y and ZJPH_INLINE float ReduceMax() const;+ /// Get the sum of X, Y and Z+ JPH_INLINE float ReduceSum() const;+/// Component wise square rootJPH_INLINE Vec3 Sqrt() const;@@ -301,7 +310,7 @@ public:};};-static_assert(std::is_trivial<Vec3>(), "Is supposed to be a trivial type!");+static_assert(std::is_trivially_default_constructible<Vec3>() && std::is_trivially_copyable<Vec3>(), "Is supposed to be a trivial type!");JPH_NAMESPACE_ENDdiff --git a/thirdparty/jolt_physics/Jolt/Math/Vec3.inl b/thirdparty/jolt_physics/Jolt/Math/Vec3.inlindex ddbfd342ea2..62bd5426770 100644--- a/thirdparty/jolt_physics/Jolt/Math/Vec3.inl+++ b/thirdparty/jolt_physics/Jolt/Math/Vec3.inl@@ -30,6 +30,12 @@ JPH_INLINE Vec3::Type Vec3::sFixW(Type inValue)return _mm_shuffle_ps(inValue, inValue, _MM_SHUFFLE(2, 2, 1, 0));#elif defined(JPH_USE_NEON)return JPH_NEON_SHUFFLE_F32x4(inValue, inValue, 0, 1, 2, 2);+ #elif defined(JPH_USE_RVV)+ Type value;+ const vfloat32m1_t v = __riscv_vle32_v_f32m1(inValue.mData, 3);+ __riscv_vse32_v_f32m1(value.mData, v, 3);+ value.mData[3] = value.mData[2];+ return value;#elseType value;value.mData[0] = inValue.mData[0];@@ -60,11 +66,15 @@ Vec3::Vec3(const Float3 &inV)float32x2_t xy = vld1_f32(&inV.x);float32x2_t zz = vdup_n_f32(inV.z); // Assure Z and W are the samemValue = vcombine_f32(xy, zz);+#elif defined(JPH_USE_RVV)+ const vfloat32m1_t v = __riscv_vle32_v_f32m1(&inV.x, 3);+ __riscv_vse32_v_f32m1(mF32, v, 3);+ mF32[3] = inV.z;#else- mF32[0] = inV[0];- mF32[1] = inV[1];- mF32[2] = inV[2];- mF32[3] = inV[2]; // Not strictly needed when JPH_FLOATING_POINT_EXCEPTIONS_ENABLED is off but prevents warnings about uninitialized variables+ mF32[0] = inV.x;+ mF32[1] = inV.y;+ mF32[2] = inV.z;+ mF32[3] = inV.z; // Not strictly needed when JPH_FLOATING_POINT_EXCEPTIONS_ENABLED is off but prevents warnings about uninitialized variables#endif}@@ -76,6 +86,10 @@ Vec3::Vec3(float inX, float inY, float inZ)uint32x2_t xy = vcreate_u32(static_cast<uint64>(BitCast<uint32>(inX)) | (static_cast<uint64>(BitCast<uint32>(inY)) << 32));uint32x2_t zz = vreinterpret_u32_f32(vdup_n_f32(inZ));mValue = vreinterpretq_f32_u32(vcombine_u32(xy, zz));+#elif defined(JPH_USE_RVV)+ const float aggregated[4] = { inX, inY, inZ, inZ };+ const vfloat32m1_t v = __riscv_vle32_v_f32m1(aggregated, 4);+ __riscv_vse32_v_f32m1(mF32, v, 4);#elsemF32[0] = inX;mF32[1] = inY;@@ -95,6 +109,14 @@ Vec3 Vec3::Swizzle() constreturn _mm_shuffle_ps(mValue, mValue, _MM_SHUFFLE(SwizzleZ, SwizzleZ, SwizzleY, SwizzleX)); // Assure Z and W are the same#elif defined(JPH_USE_NEON)return JPH_NEON_SHUFFLE_F32x4(mValue, mValue, SwizzleX, SwizzleY, SwizzleZ, SwizzleZ);+#elif defined(JPH_USE_RVV)+ Vec3 v;+ const vfloat32m1_t data = __riscv_vle32_v_f32m1(mF32, 4);+ const uint32 stored_indices[4] = { SwizzleX, SwizzleY, SwizzleZ, SwizzleZ };+ const vuint32m1_t index = __riscv_vle32_v_u32m1(stored_indices, 4);+ const vfloat32m1_t swizzled = __riscv_vrgather_vv_f32m1(data, index, 4);+ __riscv_vse32_v_f32m1(v.mF32, swizzled, 4);+ return v;#elsereturn Vec3(mF32[SwizzleX], mF32[SwizzleY], mF32[SwizzleZ]);#endif@@ -106,6 +128,11 @@ Vec3 Vec3::sZero()return _mm_setzero_ps();#elif defined(JPH_USE_NEON)return vdupq_n_f32(0);+#elif defined(JPH_USE_RVV)+ Vec3 v;+ const vfloat32m1_t zero_vec = __riscv_vfmv_v_f_f32m1(0.0f, 3);+ __riscv_vse32_v_f32m1(v.mF32, zero_vec, 3);+ return v;#elsereturn Vec3(0, 0, 0);#endif@@ -117,6 +144,11 @@ Vec3 Vec3::sReplicate(float inV)return _mm_set1_ps(inV);#elif defined(JPH_USE_NEON)return vdupq_n_f32(inV);+#elif defined(JPH_USE_RVV)+ Vec3 vec;+ const vfloat32m1_t v = __riscv_vfmv_v_f_f32m1(inV, 3);+ __riscv_vse32_v_f32m1(vec.mF32, v, 3);+ return vec;#elsereturn Vec3(inV, inV, inV);#endif@@ -138,6 +170,10 @@ Vec3 Vec3::sLoadFloat3Unsafe(const Float3 &inV)Type v = _mm_loadu_ps(&inV.x);#elif defined(JPH_USE_NEON)Type v = vld1q_f32(&inV.x);+#elif defined(JPH_USE_RVV)+ Type v;+ const vfloat32m1_t rvv = __riscv_vle32_v_f32m1(&inV.x, 3);+ __riscv_vse32_v_f32m1(v.mData, rvv, 3);#elseType v = { inV.x, inV.y, inV.z };#endif@@ -150,6 +186,13 @@ Vec3 Vec3::sMin(Vec3Arg inV1, Vec3Arg inV2)return _mm_min_ps(inV1.mValue, inV2.mValue);#elif defined(JPH_USE_NEON)return vminq_f32(inV1.mValue, inV2.mValue);+#elif defined(JPH_USE_RVV)+ Vec3 res;+ const vfloat32m1_t v1 = __riscv_vle32_v_f32m1(inV1.mF32, 3);+ const vfloat32m1_t v2 = __riscv_vle32_v_f32m1(inV2.mF32, 3);+ const vfloat32m1_t min = __riscv_vfmin_vv_f32m1(v1, v2, 3);+ __riscv_vse32_v_f32m1(res.mF32, min, 3);+ return res;#elsereturn Vec3(min(inV1.mF32[0], inV2.mF32[0]),min(inV1.mF32[1], inV2.mF32[1]),@@ -163,6 +206,13 @@ Vec3 Vec3::sMax(Vec3Arg inV1, Vec3Arg inV2)return _mm_max_ps(inV1.mValue, inV2.mValue);#elif defined(JPH_USE_NEON)return vmaxq_f32(inV1.mValue, inV2.mValue);+#elif defined(JPH_USE_RVV)+ Vec3 res;+ const vfloat32m1_t v1 = __riscv_vle32_v_f32m1(inV1.mF32, 3);+ const vfloat32m1_t v2 = __riscv_vle32_v_f32m1(inV2.mF32, 3);+ const vfloat32m1_t max = __riscv_vfmax_vv_f32m1(v1, v2, 3);+ __riscv_vse32_v_f32m1(res.mF32, max, 3);+ return res;#elsereturn Vec3(max(inV1.mF32[0], inV2.mF32[0]),max(inV1.mF32[1], inV2.mF32[1]),@@ -181,6 +231,16 @@ UVec4 Vec3::sEquals(Vec3Arg inV1, Vec3Arg inV2)return _mm_castps_si128(_mm_cmpeq_ps(inV1.mValue, inV2.mValue));#elif defined(JPH_USE_NEON)return vceqq_f32(inV1.mValue, inV2.mValue);+#elif defined(JPH_USE_RVV)+ UVec4 res;+ const vfloat32m1_t v1 = __riscv_vle32_v_f32m1(inV1.mF32, 3);+ const vfloat32m1_t v2 = __riscv_vle32_v_f32m1(inV2.mF32, 3);+ const vbool32_t mask = __riscv_vmfeq_vv_f32m1_b32(v1, v2, 3);+ const vuint32m1_t zeros = __riscv_vmv_v_x_u32m1(0x0, 3);+ const vuint32m1_t merged = __riscv_vmerge_vxm_u32m1(zeros, 0xFFFFFFFF, mask, 3);+ __riscv_vse32_v_u32m1(res.mU32, merged, 3);+ res.mU32[3] = res.mU32[2];+ return res;#elseuint32 z = inV1.mF32[2] == inV2.mF32[2]? 0xffffffffu : 0;return UVec4(inV1.mF32[0] == inV2.mF32[0]? 0xffffffffu : 0,@@ -196,6 +256,16 @@ UVec4 Vec3::sLess(Vec3Arg inV1, Vec3Arg inV2)return _mm_castps_si128(_mm_cmplt_ps(inV1.mValue, inV2.mValue));#elif defined(JPH_USE_NEON)return vcltq_f32(inV1.mValue, inV2.mValue);+#elif defined(JPH_USE_RVV)+ UVec4 res;+ const vfloat32m1_t v1 = __riscv_vle32_v_f32m1(inV1.mF32, 3);+ const vfloat32m1_t v2 = __riscv_vle32_v_f32m1(inV2.mF32, 3);+ const vbool32_t mask = __riscv_vmflt_vv_f32m1_b32(v1, v2, 3);+ const vuint32m1_t zeros = __riscv_vmv_v_x_u32m1(0x0, 3);+ const vuint32m1_t merged = __riscv_vmerge_vxm_u32m1(zeros, 0xFFFFFFFF, mask, 3);+ __riscv_vse32_v_u32m1(res.mU32, merged, 3);+ res.mU32[3] = res.mU32[2];+ return res;#elseuint32 z = inV1.mF32[2] < inV2.mF32[2]? 0xffffffffu : 0;return UVec4(inV1.mF32[0] < inV2.mF32[0]? 0xffffffffu : 0,@@ -211,6 +281,16 @@ UVec4 Vec3::sLessOrEqual(Vec3Arg inV1, Vec3Arg inV2)return _mm_castps_si128(_mm_cmple_ps(inV1.mValue, inV2.mValue));#elif defined(JPH_USE_NEON)return vcleq_f32(inV1.mValue, inV2.mValue);+#elif defined(JPH_USE_RVV)+ UVec4 res;+ const vfloat32m1_t v1 = __riscv_vle32_v_f32m1(inV1.mF32, 3);+ const vfloat32m1_t v2 = __riscv_vle32_v_f32m1(inV2.mF32, 3);+ const vbool32_t mask = __riscv_vmfle_vv_f32m1_b32(v1, v2, 3);+ const vuint32m1_t zeros = __riscv_vmv_v_x_u32m1(0x0, 3);+ const vuint32m1_t merged = __riscv_vmerge_vxm_u32m1(zeros, 0xFFFFFFFF, mask, 3);+ __riscv_vse32_v_u32m1(res.mU32, merged, 3);+ res.mU32[3] = res.mU32[2];+ return res;#elseuint32 z = inV1.mF32[2] <= inV2.mF32[2]? 0xffffffffu : 0;return UVec4(inV1.mF32[0] <= inV2.mF32[0]? 0xffffffffu : 0,@@ -226,6 +306,16 @@ UVec4 Vec3::sGreater(Vec3Arg inV1, Vec3Arg inV2)return _mm_castps_si128(_mm_cmpgt_ps(inV1.mValue, inV2.mValue));#elif defined(JPH_USE_NEON)return vcgtq_f32(inV1.mValue, inV2.mValue);+#elif defined(JPH_USE_RVV)+ UVec4 res;+ const vfloat32m1_t v1 = __riscv_vle32_v_f32m1(inV1.mF32, 3);+ const vfloat32m1_t v2 = __riscv_vle32_v_f32m1(inV2.mF32, 3);+ const vbool32_t mask = __riscv_vmfgt_vv_f32m1_b32(v1, v2, 3);+ const vuint32m1_t zeros = __riscv_vmv_v_x_u32m1(0x0, 3);+ const vuint32m1_t merged = __riscv_vmerge_vxm_u32m1(zeros, 0xFFFFFFFF, mask, 3);+ __riscv_vse32_v_u32m1(res.mU32, merged, 3);+ res.mU32[3] = res.mU32[2];+ return res;#elseuint32 z = inV1.mF32[2] > inV2.mF32[2]? 0xffffffffu : 0;return UVec4(inV1.mF32[0] > inV2.mF32[0]? 0xffffffffu : 0,@@ -241,6 +331,16 @@ UVec4 Vec3::sGreaterOrEqual(Vec3Arg inV1, Vec3Arg inV2)return _mm_castps_si128(_mm_cmpge_ps(inV1.mValue, inV2.mValue));#elif defined(JPH_USE_NEON)return vcgeq_f32(inV1.mValue, inV2.mValue);+#elif defined(JPH_USE_RVV)+ UVec4 res;+ const vfloat32m1_t v1 = __riscv_vle32_v_f32m1(inV1.mF32, 3);+ const vfloat32m1_t v2 = __riscv_vle32_v_f32m1(inV2.mF32, 3);+ const vbool32_t mask = __riscv_vmfge_vv_f32m1_b32(v1, v2, 3);+ const vuint32m1_t zeros = __riscv_vmv_v_x_u32m1(0x0, 3);+ const vuint32m1_t merged = __riscv_vmerge_vxm_u32m1(zeros, 0xFFFFFFFF, mask, 3);+ __riscv_vse32_v_u32m1(res.mU32, merged, 3);+ res.mU32[3] = res.mU32[2];+ return res;#elseuint32 z = inV1.mF32[2] >= inV2.mF32[2]? 0xffffffffu : 0;return UVec4(inV1.mF32[0] >= inV2.mF32[0]? 0xffffffffu : 0,@@ -252,18 +352,24 @@ UVec4 Vec3::sGreaterOrEqual(Vec3Arg inV1, Vec3Arg inV2)Vec3 Vec3::sFusedMultiplyAdd(Vec3Arg inMul1, Vec3Arg inMul2, Vec3Arg inAdd){-#if defined(JPH_USE_SSE)- #ifdef JPH_USE_FMADD+#ifdef JPH_USE_FMADD+ #ifdef JPH_USE_SSEreturn _mm_fmadd_ps(inMul1.mValue, inMul2.mValue, inAdd.mValue);+ #elif defined(JPH_USE_NEON)+ return vmlaq_f32(inAdd.mValue, inMul1.mValue, inMul2.mValue);+ #elif defined(JPH_USE_RVV)+ Vec3 res;+ const vfloat32m1_t v1 = __riscv_vle32_v_f32m1(inMul1.mF32, 3);+ const vfloat32m1_t v2 = __riscv_vle32_v_f32m1(inMul2.mF32, 3);+ const vfloat32m1_t rvv_add = __riscv_vle32_v_f32m1(inAdd.mF32, 3);+ const vfloat32m1_t fmadd = __riscv_vfmacc_vv_f32m1(rvv_add, v1, v2, 3);+ __riscv_vse32_v_f32m1(res.mF32, fmadd, 3);+ return res;#else- return _mm_add_ps(_mm_mul_ps(inMul1.mValue, inMul2.mValue), inAdd.mValue);+ return inMul1 * inMul2 + inAdd;#endif-#elif defined(JPH_USE_NEON)- return vmlaq_f32(inAdd.mValue, inMul1.mValue, inMul2.mValue);#else- return Vec3(inMul1.mF32[0] * inMul2.mF32[0] + inAdd.mF32[0],- inMul1.mF32[1] * inMul2.mF32[1] + inAdd.mF32[1],- inMul1.mF32[2] * inMul2.mF32[2] + inAdd.mF32[2]);+ return inMul1 * inMul2 + inAdd;#endif}@@ -279,6 +385,18 @@ Vec3 Vec3::sSelect(Vec3Arg inNotSet, Vec3Arg inSet, UVec4Arg inControl)#elif defined(JPH_USE_NEON)Type v = vbslq_f32(vreinterpretq_u32_s32(vshrq_n_s32(vreinterpretq_s32_u32(inControl.mValue), 31)), inSet.mValue, inNotSet.mValue);return sFixW(v);+#elif defined(JPH_USE_RVV)+ Vec3 masked;+ const vuint32m1_t control = __riscv_vle32_v_u32m1(inControl.mU32, 3);+ const vfloat32m1_t not_set = __riscv_vle32_v_f32m1(inNotSet.mF32, 3);+ const vfloat32m1_t set = __riscv_vle32_v_f32m1(inSet.mF32, 3);++ // Generate RVV bool mask from UVec4+ const vuint32m1_t r = __riscv_vand_vx_u32m1(control, 0x80000000u, 3);+ const vbool32_t rvv_mask = __riscv_vmsne_vx_u32m1_b32(r, 0x0, 3);+ const vfloat32m1_t merged = __riscv_vmerge_vvm_f32m1(not_set, set, rvv_mask, 3);+ __riscv_vse32_v_f32m1(masked.mF32, merged, 3);+ return masked;#elseVec3 result;for (int i = 0; i < 3; i++)@@ -296,6 +414,13 @@ Vec3 Vec3::sOr(Vec3Arg inV1, Vec3Arg inV2)return _mm_or_ps(inV1.mValue, inV2.mValue);#elif defined(JPH_USE_NEON)return vreinterpretq_f32_u32(vorrq_u32(vreinterpretq_u32_f32(inV1.mValue), vreinterpretq_u32_f32(inV2.mValue)));+#elif defined(JPH_USE_RVV)+ Vec3 or_result;+ const vuint32m1_t v1 = __riscv_vle32_v_u32m1(reinterpret_cast<const uint32 *>(inV1.mF32), 3);+ const vuint32m1_t v2 = __riscv_vle32_v_u32m1(reinterpret_cast<const uint32 *>(inV2.mF32), 3);+ const vuint32m1_t res = __riscv_vor_vv_u32m1(v1, v2, 3);+ __riscv_vse32_v_u32m1(reinterpret_cast<uint32 *>(or_result.mF32), res, 3);+ return or_result;#elsereturn Vec3(UVec4::sOr(inV1.ReinterpretAsInt(), inV2.ReinterpretAsInt()).ReinterpretAsFloat());#endif@@ -307,6 +432,13 @@ Vec3 Vec3::sXor(Vec3Arg inV1, Vec3Arg inV2)return _mm_xor_ps(inV1.mValue, inV2.mValue);#elif defined(JPH_USE_NEON)return vreinterpretq_f32_u32(veorq_u32(vreinterpretq_u32_f32(inV1.mValue), vreinterpretq_u32_f32(inV2.mValue)));+#elif defined(JPH_USE_RVV)+ Vec3 xor_result;+ const vuint32m1_t v1 = __riscv_vle32_v_u32m1(reinterpret_cast<const uint32 *>(inV1.mF32), 3);+ const vuint32m1_t v2 = __riscv_vle32_v_u32m1(reinterpret_cast<const uint32 *>(inV2.mF32), 3);+ const vuint32m1_t res = __riscv_vxor_vv_u32m1(v1, v2, 3);+ __riscv_vse32_v_u32m1(reinterpret_cast<uint32 *>(xor_result.mF32), res, 3);+ return xor_result;#elsereturn Vec3(UVec4::sXor(inV1.ReinterpretAsInt(), inV2.ReinterpretAsInt()).ReinterpretAsFloat());#endif@@ -318,6 +450,13 @@ Vec3 Vec3::sAnd(Vec3Arg inV1, Vec3Arg inV2)return _mm_and_ps(inV1.mValue, inV2.mValue);#elif defined(JPH_USE_NEON)return vreinterpretq_f32_u32(vandq_u32(vreinterpretq_u32_f32(inV1.mValue), vreinterpretq_u32_f32(inV2.mValue)));+#elif defined(JPH_USE_RVV)+ Vec3 and_result;+ const vuint32m1_t v1 = __riscv_vle32_v_u32m1(reinterpret_cast<const uint32 *>(inV1.mF32), 3);+ const vuint32m1_t v2 = __riscv_vle32_v_u32m1(reinterpret_cast<const uint32 *>(inV2.mF32), 3);+ const vuint32m1_t res = __riscv_vand_vv_u32m1(v1, v2, 3);+ __riscv_vse32_v_u32m1(reinterpret_cast<uint32 *>(and_result.mF32), res, 3);+ return and_result;#elsereturn Vec3(UVec4::sAnd(inV1.ReinterpretAsInt(), inV2.ReinterpretAsInt()).ReinterpretAsFloat());#endif@@ -333,10 +472,14 @@ Vec3 Vec3::sUnitSpherical(float inTheta, float inPhi)template <class Random>Vec3 Vec3::sRandom(Random &inRandom){- std::uniform_real_distribution<float> zero_to_one(0.0f, 1.0f);- float theta = JPH_PI * zero_to_one(inRandom);- float phi = 2.0f * JPH_PI * zero_to_one(inRandom);- return sUnitSpherical(theta, phi);+ // Generating uniform unit random vectors in Rn - Andersen Ang+ // See: https://angms.science/doc/RM/randUnitVec.pdf+ float z = -1.0f + 2.0f * float(inRandom() - inRandom.min()) / float(inRandom.max() - inRandom.min());+ float r = JPH::Sqrt(1.0f - Square(z));+ float theta = 2.0f * JPH_PI * float(inRandom() - inRandom.min()) / float(inRandom.max() - inRandom.min());+ Vec4 s, c;+ Vec4::sReplicate(theta).SinCos(s, c);+ return Vec3(r * s.GetX(), r * c.GetX(), z);}bool Vec3::operator == (Vec3Arg inV2) const@@ -360,6 +503,13 @@ Vec3 Vec3::operator * (Vec3Arg inV2) constreturn _mm_mul_ps(mValue, inV2.mValue);#elif defined(JPH_USE_NEON)return vmulq_f32(mValue, inV2.mValue);+#elif defined(JPH_USE_RVV)+ Vec3 res;+ const vfloat32m1_t v1 = __riscv_vle32_v_f32m1(mF32, 3);+ const vfloat32m1_t v2 = __riscv_vle32_v_f32m1(inV2.mF32, 3);+ const vfloat32m1_t mul = __riscv_vfmul_vv_f32m1(v1, v2, 3);+ __riscv_vse32_v_f32m1(res.mF32, mul, 3);+ return res;#elsereturn Vec3(mF32[0] * inV2.mF32[0], mF32[1] * inV2.mF32[1], mF32[2] * inV2.mF32[2]);#endif@@ -371,6 +521,12 @@ Vec3 Vec3::operator * (float inV2) constreturn _mm_mul_ps(mValue, _mm_set1_ps(inV2));#elif defined(JPH_USE_NEON)return vmulq_n_f32(mValue, inV2);+#elif defined(JPH_USE_RVV)+ Vec3 res;+ const vfloat32m1_t src = __riscv_vle32_v_f32m1(mF32, 3);+ const vfloat32m1_t mul = __riscv_vfmul_vf_f32m1(src, inV2, 3);+ __riscv_vse32_v_f32m1(res.mF32, mul, 3);+ return res;#elsereturn Vec3(mF32[0] * inV2, mF32[1] * inV2, mF32[2] * inV2);#endif@@ -382,6 +538,12 @@ Vec3 operator * (float inV1, Vec3Arg inV2)return _mm_mul_ps(_mm_set1_ps(inV1), inV2.mValue);#elif defined(JPH_USE_NEON)return vmulq_n_f32(inV2.mValue, inV1);+#elif defined(JPH_USE_RVV)+ Vec3 res;+ const vfloat32m1_t v1 = __riscv_vle32_v_f32m1(inV2.mF32, 3);+ const vfloat32m1_t mul = __riscv_vfmul_vf_f32m1(v1, inV1, 3);+ __riscv_vse32_v_f32m1(res.mF32, mul, 3);+ return res;#elsereturn Vec3(inV1 * inV2.mF32[0], inV1 * inV2.mF32[1], inV1 * inV2.mF32[2]);#endif@@ -393,6 +555,12 @@ Vec3 Vec3::operator / (float inV2) constreturn _mm_div_ps(mValue, _mm_set1_ps(inV2));#elif defined(JPH_USE_NEON)return vdivq_f32(mValue, vdupq_n_f32(inV2));+#elif defined(JPH_USE_RVV)+ Vec3 res;+ const vfloat32m1_t v1 = __riscv_vle32_v_f32m1(mF32, 3);+ const vfloat32m1_t div = __riscv_vfdiv_vf_f32m1(v1, inV2, 3);+ __riscv_vse32_v_f32m1(res.mF32, div, 3);+ return res;#elsereturn Vec3(mF32[0] / inV2, mF32[1] / inV2, mF32[2] / inV2);#endif@@ -404,6 +572,10 @@ Vec3 &Vec3::operator *= (float inV2)mValue = _mm_mul_ps(mValue, _mm_set1_ps(inV2));#elif defined(JPH_USE_NEON)mValue = vmulq_n_f32(mValue, inV2);+#elif defined(JPH_USE_RVV)+ const vfloat32m1_t v1 = __riscv_vle32_v_f32m1(mF32, 3);+ const vfloat32m1_t res = __riscv_vfmul_vf_f32m1(v1, inV2, 3);+ __riscv_vse32_v_f32m1(mF32, res, 3);#elsefor (int i = 0; i < 3; ++i)mF32[i] *= inV2;@@ -420,6 +592,11 @@ Vec3 &Vec3::operator *= (Vec3Arg inV2)mValue = _mm_mul_ps(mValue, inV2.mValue);#elif defined(JPH_USE_NEON)mValue = vmulq_f32(mValue, inV2.mValue);+#elif defined(JPH_USE_RVV)+ const vfloat32m1_t v1 = __riscv_vle32_v_f32m1(mF32, 3);+ const vfloat32m1_t v2 = __riscv_vle32_v_f32m1(inV2.mF32, 3);+ const vfloat32m1_t rvv_res = __riscv_vfmul_vv_f32m1(v1, v2, 3);+ __riscv_vse32_v_f32m1(mF32, rvv_res, 3);#elsefor (int i = 0; i < 3; ++i)mF32[i] *= inV2.mF32[i];@@ -436,6 +613,10 @@ Vec3 &Vec3::operator /= (float inV2)mValue = _mm_div_ps(mValue, _mm_set1_ps(inV2));#elif defined(JPH_USE_NEON)mValue = vdivq_f32(mValue, vdupq_n_f32(inV2));+#elif defined(JPH_USE_RVV)+ const vfloat32m1_t v = __riscv_vle32_v_f32m1(mF32, 3);+ const vfloat32m1_t res = __riscv_vfdiv_vf_f32m1(v, inV2, 3);+ __riscv_vse32_v_f32m1(mF32, res, 3);#elsefor (int i = 0; i < 3; ++i)mF32[i] /= inV2;@@ -452,6 +633,13 @@ Vec3 Vec3::operator + (Vec3Arg inV2) constreturn _mm_add_ps(mValue, inV2.mValue);#elif defined(JPH_USE_NEON)return vaddq_f32(mValue, inV2.mValue);+#elif defined(JPH_USE_RVV)+ Vec3 res;+ const vfloat32m1_t v1 = __riscv_vle32_v_f32m1(mF32, 3);+ const vfloat32m1_t v2 = __riscv_vle32_v_f32m1(inV2.mF32, 3);+ const vfloat32m1_t rvv_add = __riscv_vfadd_vv_f32m1(v1, v2, 3);+ __riscv_vse32_v_f32m1(res.mF32, rvv_add, 3);+ return res;#elsereturn Vec3(mF32[0] + inV2.mF32[0], mF32[1] + inV2.mF32[1], mF32[2] + inV2.mF32[2]);#endif@@ -463,6 +651,11 @@ Vec3 &Vec3::operator += (Vec3Arg inV2)mValue = _mm_add_ps(mValue, inV2.mValue);#elif defined(JPH_USE_NEON)mValue = vaddq_f32(mValue, inV2.mValue);+#elif defined(JPH_USE_RVV)+ const vfloat32m1_t v1 = __riscv_vle32_v_f32m1(mF32, 3);+ const vfloat32m1_t v2 = __riscv_vle32_v_f32m1(inV2.mF32, 3);+ const vfloat32m1_t rvv_add = __riscv_vfadd_vv_f32m1(v1, v2, 3);+ __riscv_vse32_v_f32m1(mF32, rvv_add, 3);#elsefor (int i = 0; i < 3; ++i)mF32[i] += inV2.mF32[i];@@ -483,6 +676,21 @@ Vec3 Vec3::operator - () const#elsereturn vnegq_f32(mValue);#endif+#elif defined(JPH_USE_RVV)+ #ifdef JPH_CROSS_PLATFORM_DETERMINISTIC+ Vec3 res;+ const vfloat32m1_t rvv_zero = __riscv_vfmv_v_f_f32m1(0.0f, 3);+ const vfloat32m1_t v = __riscv_vle32_v_f32m1(mF32, 3);+ const vfloat32m1_t rvv_neg = __riscv_vfsub_vv_f32m1(rvv_zero, v, 3);+ __riscv_vse32_v_f32m1(res.mF32, rvv_neg, 3);+ return res;+ #else+ Vec3 res;+ const vfloat32m1_t v = __riscv_vle32_v_f32m1(mF32, 3);+ const vfloat32m1_t rvv_neg = __riscv_vfsgnjn_vv_f32m1(v, v, 3);+ __riscv_vse32_v_f32m1(res.mF32, rvv_neg, 3);+ return res;+ #endif#else#ifdef JPH_CROSS_PLATFORM_DETERMINISTICreturn Vec3(0.0f - mF32[0], 0.0f - mF32[1], 0.0f - mF32[2]);@@ -498,6 +706,13 @@ Vec3 Vec3::operator - (Vec3Arg inV2) constreturn _mm_sub_ps(mValue, inV2.mValue);#elif defined(JPH_USE_NEON)return vsubq_f32(mValue, inV2.mValue);+#elif defined(JPH_USE_RVV)+ Vec3 res;+ const vfloat32m1_t v1 = __riscv_vle32_v_f32m1(mF32, 3);+ const vfloat32m1_t v2 = __riscv_vle32_v_f32m1(inV2.mF32, 3);+ const vfloat32m1_t rvv_sub = __riscv_vfsub_vv_f32m1(v1, v2, 3);+ __riscv_vse32_v_f32m1(res.mF32, rvv_sub, 3);+ return res;#elsereturn Vec3(mF32[0] - inV2.mF32[0], mF32[1] - inV2.mF32[1], mF32[2] - inV2.mF32[2]);#endif@@ -509,6 +724,11 @@ Vec3 &Vec3::operator -= (Vec3Arg inV2)mValue = _mm_sub_ps(mValue, inV2.mValue);#elif defined(JPH_USE_NEON)mValue = vsubq_f32(mValue, inV2.mValue);+#elif defined(JPH_USE_RVV)+ const vfloat32m1_t v1 = __riscv_vle32_v_f32m1(mF32, 3);+ const vfloat32m1_t v2 = __riscv_vle32_v_f32m1(inV2.mF32, 3);+ const vfloat32m1_t rvv_sub = __riscv_vfsub_vv_f32m1(v1, v2, 3);+ __riscv_vse32_v_f32m1(mF32, rvv_sub, 3);#elsefor (int i = 0; i < 3; ++i)mF32[i] -= inV2.mF32[i];@@ -526,6 +746,13 @@ Vec3 Vec3::operator / (Vec3Arg inV2) constreturn _mm_div_ps(mValue, inV2.mValue);#elif defined(JPH_USE_NEON)return vdivq_f32(mValue, inV2.mValue);+#elif defined(JPH_USE_RVV)+ Vec3 res;+ const vfloat32m1_t v1 = __riscv_vle32_v_f32m1(mF32, 3);+ const vfloat32m1_t v2 = __riscv_vle32_v_f32m1(inV2.mF32, 3);+ const vfloat32m1_t rvv_div = __riscv_vfdiv_vv_f32m1(v1, v2, 3);+ __riscv_vse32_v_f32m1(res.mF32, rvv_div, 3);+ return res;#elsereturn Vec3(mF32[0] / inV2.mF32[0], mF32[1] / inV2.mF32[1], mF32[2] / inV2.mF32[2]);#endif@@ -537,6 +764,11 @@ Vec4 Vec3::SplatX() constreturn _mm_shuffle_ps(mValue, mValue, _MM_SHUFFLE(0, 0, 0, 0));#elif defined(JPH_USE_NEON)return vdupq_laneq_f32(mValue, 0);+#elif defined(JPH_USE_RVV)+ Vec4 vec;+ const vfloat32m1_t splat = __riscv_vfmv_v_f_f32m1(mF32[0], 4);+ __riscv_vse32_v_f32m1(vec.mF32, splat, 4);+ return vec;#elsereturn Vec4(mF32[0], mF32[0], mF32[0], mF32[0]);#endif@@ -548,6 +780,11 @@ Vec4 Vec3::SplatY() constreturn _mm_shuffle_ps(mValue, mValue, _MM_SHUFFLE(1, 1, 1, 1));#elif defined(JPH_USE_NEON)return vdupq_laneq_f32(mValue, 1);+#elif defined(JPH_USE_RVV)+ Vec4 vec;+ const vfloat32m1_t splat = __riscv_vfmv_v_f_f32m1(mF32[1], 4);+ __riscv_vse32_v_f32m1(vec.mF32, splat, 4);+ return vec;#elsereturn Vec4(mF32[1], mF32[1], mF32[1], mF32[1]);#endif@@ -559,6 +796,11 @@ Vec4 Vec3::SplatZ() constreturn _mm_shuffle_ps(mValue, mValue, _MM_SHUFFLE(2, 2, 2, 2));#elif defined(JPH_USE_NEON)return vdupq_laneq_f32(mValue, 2);+#elif defined(JPH_USE_RVV)+ Vec4 vec;+ const vfloat32m1_t splat = __riscv_vfmv_v_f_f32m1(mF32[2], 4);+ __riscv_vse32_v_f32m1(vec.mF32, splat, 4);+ return vec;#elsereturn Vec4(mF32[2], mF32[2], mF32[2], mF32[2]);#endif@@ -582,6 +824,12 @@ Vec3 Vec3::Abs() constreturn _mm_max_ps(_mm_sub_ps(_mm_setzero_ps(), mValue), mValue);#elif defined(JPH_USE_NEON)return vabsq_f32(mValue);+#elif defined(JPH_USE_RVV)+ Vec3 res;+ const vfloat32m1_t v = __riscv_vle32_v_f32m1(mF32, 3);+ const vfloat32m1_t rvv_abs = __riscv_vfsgnj_vf_f32m1(v, 1.0, 3);+ __riscv_vse32_v_f32m1(res.mF32, rvv_abs, 3);+ return res;#elsereturn Vec3(abs(mF32[0]), abs(mF32[1]), abs(mF32[2]));#endif@@ -592,6 +840,18 @@ Vec3 Vec3::Reciprocal() constreturn sOne() / mValue;}+Vec3 Vec3::sDifferenceOfProducts(Vec3Arg inA, Vec3Arg inB, Vec3Arg inC, Vec3Arg inD)+{+#ifdef JPH_USE_FMADD+ Vec3 cd = inC * inD;+ Vec3 err = Vec3::sFusedMultiplyAdd(-inC, inD, cd);+ Vec3 dop = Vec3::sFusedMultiplyAdd(inA, inB, -cd);+ return dop + err;+#else+ return inA * inB - inC * inD;+#endif+}+Vec3 Vec3::Cross(Vec3Arg inV2) const{#if defined(JPH_USE_SSE)@@ -608,6 +868,21 @@ Vec3 Vec3::Cross(Vec3Arg inV2) constt2 = vmulq_f32(t2, inV2.mValue);Type t3 = vsubq_f32(t1, t2);return JPH_NEON_SHUFFLE_F32x4(t3, t3, 1, 2, 0, 0); // Assure Z and W are the same+#elif defined(JPH_USE_RVV)+ const uint32 indices[3] = { 1, 2, 0 };+ const vuint32m1_t gather_indices = __riscv_vle32_v_u32m1(indices, 3);+ const vfloat32m1_t v0 = __riscv_vle32_v_f32m1(mF32, 3);+ const vfloat32m1_t v1 = __riscv_vle32_v_f32m1(inV2.mF32, 3);+ vfloat32m1_t t0 = __riscv_vrgather_vv_f32m1(v1, gather_indices, 3);+ t0 = __riscv_vfmul_vv_f32m1(t0, v0, 3);+ vfloat32m1_t t1 = __riscv_vrgather_vv_f32m1(v0, gather_indices, 3);+ t1 = __riscv_vfmul_vv_f32m1(t1, v1, 3);+ const vfloat32m1_t sub = __riscv_vfsub_vv_f32m1(t0, t1, 3);+ const vfloat32m1_t cross = __riscv_vrgather_vv_f32m1(sub, gather_indices, 3);++ Vec3 cross_result;+ __riscv_vse32_v_f32m1(cross_result.mF32, cross, 3);+ return cross_result;#elsereturn Vec3(mF32[1] * inV2.mF32[2] - mF32[2] * inV2.mF32[1],mF32[2] * inV2.mF32[0] - mF32[0] * inV2.mF32[2],@@ -615,82 +890,67 @@ Vec3 Vec3::Cross(Vec3Arg inV2) const#endif}-Vec3 Vec3::DotV(Vec3Arg inV2) const+Vec3 Vec3::CrossPrecise(Vec3Arg inV2) const{-#if defined(JPH_USE_SSE4_1)- return _mm_dp_ps(mValue, inV2.mValue, 0x7f);-#elif defined(JPH_USE_NEON)- float32x4_t mul = vmulq_f32(mValue, inV2.mValue);- mul = vsetq_lane_f32(0, mul, 3);- return vdupq_n_f32(vaddvq_f32(mul));-#else- float dot = 0.0f;- for (int i = 0; i < 3; i++)- dot += mF32[i] * inV2.mF32[i];- return Vec3::sReplicate(dot);-#endif+ return sDifferenceOfProducts(*this, inV2.Swizzle<SWIZZLE_Y, SWIZZLE_Z, SWIZZLE_X>(), Swizzle<SWIZZLE_Y, SWIZZLE_Z, SWIZZLE_X>(), inV2).Swizzle<SWIZZLE_Y, SWIZZLE_Z, SWIZZLE_X>();}-Vec4 Vec3::DotV4(Vec3Arg inV2) const+float Vec3::ReduceSum() const{+ // Ensure that we handle -0.0f correctly when cross platform deterministic behavior is required.#if defined(JPH_USE_SSE4_1)- return _mm_dp_ps(mValue, inV2.mValue, 0x7f);+ #ifdef JPH_CROSS_PLATFORM_DETERMINISTIC+ Type val = _mm_blend_ps(mValue, _mm_setzero_ps(), 0x8); // [x, y, z, 0]+ Type shuf = _mm_movehdup_ps(val); // [y, y, 0, 0]+ Type sums = _mm_add_ps(val, shuf); // [x + y, y + y, z + 0, 0]+ shuf = _mm_movehl_ps(shuf, sums); // [z + 0, 0, 0, 0]+ #else+ Type shuf = _mm_movehdup_ps(mValue); // [y, y, w, w]+ Type sums = _mm_add_ps(mValue, shuf); // [x + y, y + y, z + w, w + w]+ shuf = _mm_movehl_ps(mValue, mValue); // [z, w, z, w]+ #endif+ sums = _mm_add_ps(sums, shuf); // Deterministic: [(x + y) + (z + 0), ...], non-deterministic: [(x + y) + z, ...]+ return _mm_cvtss_f32(sums);#elif defined(JPH_USE_NEON)- float32x4_t mul = vmulq_f32(mValue, inV2.mValue);- mul = vsetq_lane_f32(0, mul, 3);- return vdupq_n_f32(vaddvq_f32(mul));+ Type v = vsetq_lane_f32(0, mValue, 3);+ return vaddvq_f32(v);+#elif defined(JPH_USE_RVV)+ const vfloat32m1_t zeros = __riscv_vfmv_v_f_f32m1(0.0f, 3);+ const vfloat32m1_t v = __riscv_vle32_v_f32m1(mF32, 3);+ const vfloat32m1_t sum = __riscv_vfredosum_vs_f32m1_f32m1(v, zeros, 3);+ return __riscv_vfmv_f_s_f32m1_f32(sum);#else- float dot = 0.0f;- for (int i = 0; i < 3; i++)- dot += mF32[i] * inV2.mF32[i];- return Vec4::sReplicate(dot);+ #ifdef JPH_CROSS_PLATFORM_DETERMINISTIC+ return (mF32[0] + mF32[1]) + (mF32[2] + 0.0f);+ #else+ return mF32[0] + mF32[1] + mF32[2];+ #endif#endif}float Vec3::Dot(Vec3Arg inV2) const{-#if defined(JPH_USE_SSE4_1)- return _mm_cvtss_f32(_mm_dp_ps(mValue, inV2.mValue, 0x7f));-#elif defined(JPH_USE_NEON)- float32x4_t mul = vmulq_f32(mValue, inV2.mValue);- mul = vsetq_lane_f32(0, mul, 3);- return vaddvq_f32(mul);-#else- float dot = 0.0f;- for (int i = 0; i < 3; i++)- dot += mF32[i] * inV2.mF32[i];- return dot;-#endif+ return (*this * inV2).ReduceSum();+}++Vec3 Vec3::DotV(Vec3Arg inV2) const+{+ return Vec3::sReplicate(Dot(inV2));+}++Vec4 Vec3::DotV4(Vec3Arg inV2) const+{+ return Vec4::sReplicate(Dot(inV2));}float Vec3::LengthSq() const{-#if defined(JPH_USE_SSE4_1)- return _mm_cvtss_f32(_mm_dp_ps(mValue, mValue, 0x7f));-#elif defined(JPH_USE_NEON)- float32x4_t mul = vmulq_f32(mValue, mValue);- mul = vsetq_lane_f32(0, mul, 3);- return vaddvq_f32(mul);-#else- float len_sq = 0.0f;- for (int i = 0; i < 3; i++)- len_sq += mF32[i] * mF32[i];- return len_sq;-#endif+ return Dot(*this);}float Vec3::Length() const{-#if defined(JPH_USE_SSE4_1)- return _mm_cvtss_f32(_mm_sqrt_ss(_mm_dp_ps(mValue, mValue, 0x7f)));-#elif defined(JPH_USE_NEON)- float32x4_t mul = vmulq_f32(mValue, mValue);- mul = vsetq_lane_f32(0, mul, 3);- float32x2_t sum = vdup_n_f32(vaddvq_f32(mul));- return vget_lane_f32(vsqrt_f32(sum), 0);-#else- return sqrt(LengthSq());-#endif+ return JPH::Sqrt(LengthSq());}Vec3 Vec3::Sqrt() const@@ -699,29 +959,31 @@ Vec3 Vec3::Sqrt() constreturn _mm_sqrt_ps(mValue);#elif defined(JPH_USE_NEON)return vsqrtq_f32(mValue);+#elif defined(JPH_USE_RVV)+ Vec3 res;+ const vfloat32m1_t v = __riscv_vle32_v_f32m1(mF32, 3);+ const vfloat32m1_t rvv_sqrt = __riscv_vfsqrt_v_f32m1(v, 3);+ __riscv_vse32_v_f32m1(res.mF32, rvv_sqrt, 3);+ return res;#else- return Vec3(sqrt(mF32[0]), sqrt(mF32[1]), sqrt(mF32[2]));+ return Vec3(JPH::Sqrt(mF32[0]), JPH::Sqrt(mF32[1]), JPH::Sqrt(mF32[2]));#endif}Vec3 Vec3::Normalized() const{-#if defined(JPH_USE_SSE4_1)- return _mm_div_ps(mValue, _mm_sqrt_ps(_mm_dp_ps(mValue, mValue, 0x7f)));-#elif defined(JPH_USE_NEON)- float32x4_t mul = vmulq_f32(mValue, mValue);- mul = vsetq_lane_f32(0, mul, 3);- float32x4_t sum = vdupq_n_f32(vaddvq_f32(mul));- return vdivq_f32(mValue, vsqrtq_f32(sum));-#elsereturn *this / Length();-#endif}Vec3 Vec3::NormalizedOr(Vec3Arg inZeroValue) const{#if defined(JPH_USE_SSE4_1) && !defined(JPH_PLATFORM_WASM) // _mm_blendv_ps has problems on FireFox- Type len_sq = _mm_dp_ps(mValue, mValue, 0x7f);+ Type mul = _mm_mul_ps(mValue, mValue);+ Type shuf = _mm_movehdup_ps(mul);+ Type sums = _mm_add_ps(mul, shuf);+ shuf = _mm_movehl_ps(mul, mul);+ sums = _mm_add_ps(sums, shuf);+ Type len_sq = _mm_shuffle_ps(sums, sums, _MM_SHUFFLE(0, 0, 0, 0));// clang with '-ffast-math' (which you should not use!) can generate _mm_rsqrt_ps// instructions which produce INFs/NaNs when they get a denormal float as input.// We therefore treat denormals as zero here.@@ -740,12 +1002,28 @@ Vec3 Vec3::NormalizedOr(Vec3Arg inZeroValue) constfloat32x4_t len_sq = vdupq_n_f32(vaddvq_f32(mul));uint32x4_t is_zero = vcleq_f32(len_sq, vdupq_n_f32(FLT_MIN));return vbslq_f32(is_zero, inZeroValue.mValue, vdivq_f32(mValue, vsqrtq_f32(len_sq)));+#elif defined(JPH_USE_RVV)+ const vfloat32m1_t src = __riscv_vle32_v_f32m1(mF32, 3);+ const vfloat32m1_t zeros = __riscv_vfmv_v_f_f32m1(0.0f, 3);+ const vfloat32m1_t mul = __riscv_vfmul_vv_f32m1(src, src, 3);+ const vfloat32m1_t sum = __riscv_vfredosum_vs_f32m1_f32m1(mul, zeros, 3);+ const float dot = __riscv_vfmv_f_s_f32m1_f32(sum);+ if (dot <= FLT_MIN)+ return inZeroValue;++ const vfloat32m1_t splat = __riscv_vrgather_vx_f32m1(sum, 0, 3);+ const vfloat32m1_t length = __riscv_vfsqrt_v_f32m1(splat, 3);++ Vec3 v;+ const vfloat32m1_t norm = __riscv_vfdiv_vv_f32m1(src, length, 3);+ __riscv_vse32_v_f32m1(v.mF32, norm, 3);+ return v;#elsefloat len_sq = LengthSq();if (len_sq <= FLT_MIN)return inZeroValue;else- return *this / sqrt(len_sq);+ return *this / JPH::Sqrt(len_sq);#endif}@@ -764,6 +1042,11 @@ bool Vec3::IsNaN() constuint32x4_t mask = JPH_NEON_UINT32x4(1, 1, 1, 0);uint32x4_t is_equal = vceqq_f32(mValue, mValue); // If a number is not equal to itself it's a NaNreturn vaddvq_u32(vandq_u32(is_equal, mask)) != 3;+#elif defined(JPH_USE_RVV)+ const vfloat32m1_t v = __riscv_vle32_v_f32m1(mF32, 3);+ const vbool32_t mask = __riscv_vmfeq_vv_f32m1_b32(v, v, 3);+ const uint32 eq = __riscv_vcpop_m_b32(mask, 3);+ return eq != 3;#elsereturn isnan(mF32[0]) || isnan(mF32[1]) || isnan(mF32[2]);#endif@@ -781,6 +1064,9 @@ void Vec3::StoreFloat3(Float3 *outV) constfloat32x2_t xy = vget_low_f32(mValue);vst1_f32(&outV->x, xy);vst1q_lane_f32(&outV->z, mValue, 2);+#elif defined(JPH_USE_RVV)+ const vfloat32m1_t v = __riscv_vle32_v_f32m1(mF32, 3);+ __riscv_vse32_v_f32m1(&outV->x, v, 3);#elseoutV->x = mF32[0];outV->y = mF32[1];@@ -794,6 +1080,12 @@ UVec4 Vec3::ToInt() constreturn _mm_cvttps_epi32(mValue);#elif defined(JPH_USE_NEON)return vcvtq_u32_f32(mValue);+#elif defined(JPH_USE_RVV)+ UVec4 res;+ const vfloat32m1_t v = __riscv_vle32_v_f32m1(mF32, 4);+ const vuint32m1_t cast = __riscv_vfcvt_rtz_xu_f_v_u32m1(v, 4);+ __riscv_vse32_v_u32m1(res.mU32, cast, 4);+ return res;#elsereturn UVec4(uint32(mF32[0]), uint32(mF32[1]), uint32(mF32[2]), uint32(mF32[3]));#endif@@ -826,22 +1118,51 @@ float Vec3::ReduceMax() constVec3 Vec3::GetNormalizedPerpendicular() const{- if (abs(mF32[0]) > abs(mF32[1]))- {- float len = sqrt(mF32[0] * mF32[0] + mF32[2] * mF32[2]);- return Vec3(mF32[2], 0.0f, -mF32[0]) / len;- }- else- {- float len = sqrt(mF32[1] * mF32[1] + mF32[2] * mF32[2]);- return Vec3(0.0f, mF32[2], -mF32[1]) / len;- }+#if defined(JPH_USE_SSE)+ // Build both perpendicular candidates without explicit masking:+ // perp_x = [z, 0, -x, 0] (used when |x| > |y|)+ // perp_y = [0, z, -y, 0] (used when |x| <= |y|)+ __m128 zero = _mm_setzero_ps();+ __m128 neg = _mm_sub_ps(zero, mValue);+ __m128 perp_x = _mm_shuffle_ps(_mm_unpackhi_ps(mValue, zero), neg, _MM_SHUFFLE(0, 0, 1, 0));+ __m128 perp_y = _mm_shuffle_ps(_mm_unpackhi_ps(zero, mValue), neg, _MM_SHUFFLE(1, 1, 1, 0));++ // Compare squared components instead of absolute values (saves the abs computation).+ __m128 sq = _mm_mul_ps(mValue, mValue);+ __m128 xx = _mm_shuffle_ps(sq, sq, _MM_SHUFFLE(0, 0, 0, 0));+ __m128 yy = _mm_shuffle_ps(sq, sq, _MM_SHUFFLE(1, 1, 1, 1));+ __m128 zz = _mm_shuffle_ps(sq, sq, _MM_SHUFFLE(2, 2, 2, 2));+ __m128 x_gt_y = _mm_cmpgt_ps(xx, yy);++ // Select perpendicular based on |x| > |y|.+#if defined(JPH_USE_SSE4_1) && !defined(JPH_PLATFORM_WASM) // _mm_blendv_ps has problems on FireFox+ __m128 result = _mm_blendv_ps(perp_y, perp_x, x_gt_y);+#else+ __m128 result = _mm_or_ps(_mm_and_ps(x_gt_y, perp_x), _mm_andnot_ps(x_gt_y, perp_y));+#endif++ // Normalize. Since the result has only two nonzero components; one of x^2 / y^2 plus z^2; the squared length is max(xx, yy) + zz. All lanes of the sqrt input are identical.+ __m128 len = _mm_sqrt_ps(_mm_add_ps(_mm_max_ps(xx, yy), zz));+ return _mm_div_ps(result, len);+#else+ float x = mF32[0], y = mF32[1], z = mF32[2];+ float xx = x * x, yy = y * y, zz = z * z;+#ifdef JPH_CROSS_PLATFORM_DETERMINISTIC+ Vec3 perp_x(z, 0.0f, 0.0f - x);+ Vec3 perp_y(0.0f, z, 0.0f - y);+#else+ Vec3 perp_x(z, 0.0f, -x);+ Vec3 perp_y(0.0f, z, -y);+#endif // JPH_CROSS_PLATFORM_DETERMINISTIC+ return (xx > yy ? perp_x : perp_y) / JPH::Sqrt(max(xx, yy) + zz);+#endif // JPH_USE_SSE}Vec3 Vec3::GetSign() const{#if defined(JPH_USE_AVX512)- return _mm_fixupimm_ps(mValue, mValue, _mm_set1_epi32(0xA9A90A00), 0);+ Type one = _mm_set1_ps(1.0f);+ return _mm_or_ps(_mm_fixupimm_ps(mValue, mValue, _mm_set1_epi32(0xA9A90100), 0), one);#elif defined(JPH_USE_SSE)Type minus_one = _mm_set1_ps(-1.0f);Type one = _mm_set1_ps(1.0f);@@ -850,6 +1171,13 @@ Vec3 Vec3::GetSign() constType minus_one = vdupq_n_f32(-1.0f);Type one = vdupq_n_f32(1.0f);return vreinterpretq_f32_u32(vorrq_u32(vandq_u32(vreinterpretq_u32_f32(mValue), vreinterpretq_u32_f32(minus_one)), vreinterpretq_u32_f32(one)));+#elif defined(JPH_USE_RVV)+ Vec3 res;+ const vfloat32m1_t rvv_in = __riscv_vle32_v_f32m1(mF32, 3);+ const vfloat32m1_t rvv_one = __riscv_vfmv_v_f_f32m1(1.0, 3);+ const vfloat32m1_t rvv_signs = __riscv_vfsgnj_vv_f32m1(rvv_one, rvv_in, 3);+ __riscv_vse32_v_f32m1(res.mF32, rvv_signs, 3);+ return res;#elsereturn Vec3(std::signbit(mF32[0])? -1.0f : 1.0f,std::signbit(mF32[1])? -1.0f : 1.0f,@@ -911,14 +1239,15 @@ Vec3 Vec3::sDecompressUnitVector(uint32 inValue)constexpr uint cNumBits = 14;constexpr uint cMask = (1u << cNumBits) - 1;constexpr uint cMaxValue = cMask - 1; // Need odd number of buckets to quantize to or else we can't encode 0+ constexpr int cHalfMaxValue = int(cMaxValue >> 1);constexpr float cScale = 2.0f * cOneOverSqrt2 / float(cMaxValue);// Restore two components- Vec3 v = Vec3(UVec4(inValue & cMask, (inValue >> cNumBits) & cMask, 0, 0).ToFloat()) * cScale - Vec3(cOneOverSqrt2, cOneOverSqrt2, 0.0f);+ Vec3 v = Vec3(float(int(inValue & cMask) - cHalfMaxValue), float(int((inValue >> cNumBits) & cMask) - cHalfMaxValue), 0) * cScale;JPH_ASSERT(v.GetZ() == 0.0f);// Restore the highest component- v.SetZ(sqrt(max(1.0f - v.LengthSq(), 0.0f)));+ v.SetZ(JPH::Sqrt(max(1.0f - v.LengthSq(), 0.0f)));// Extract signif ((inValue & 0x80000000u) != 0)diff --git a/thirdparty/jolt_physics/Jolt/Math/Vec4.h b/thirdparty/jolt_physics/Jolt/Math/Vec4.hindex 53595644668..c2ca83352ce 100644--- a/thirdparty/jolt_physics/Jolt/Math/Vec4.h+++ b/thirdparty/jolt_physics/Jolt/Math/Vec4.h@@ -230,6 +230,9 @@ public:/// Reciprocal vector (1 / value) for each of the componentsJPH_INLINE Vec4 Reciprocal() const;+ /// Calculates inA * inB - inC * inD with more precision when FMA instructions are available. See DifferenceOfProducts.+ JPH_INLINE static Vec4 sDifferenceOfProducts(Vec4Arg inA, Vec4Arg inB, Vec4Arg inC, Vec4Arg inD);+/// Dot product, returns the dot product in X, Y, Z and W componentsJPH_INLINE Vec4 DotV(Vec4Arg inV2) const;@@ -263,6 +266,9 @@ public:/// Get the maximum of X, Y, Z and WJPH_INLINE float ReduceMax() const;+ /// Sum X, Y, Z and W+ JPH_INLINE float ReduceSum() const;+/// Component wise square rootJPH_INLINE Vec4 Sqrt() const;@@ -313,7 +319,7 @@ public:};};-static_assert(std::is_trivial<Vec4>(), "Is supposed to be a trivial type!");+static_assert(std::is_trivially_default_constructible<Vec4>() && std::is_trivially_copyable<Vec4>(), "Is supposed to be a trivial type!");JPH_NAMESPACE_ENDdiff --git a/thirdparty/jolt_physics/Jolt/Math/Vec4.inl b/thirdparty/jolt_physics/Jolt/Math/Vec4.inlindex 0954fd04c7c..1528b77e2a3 100644--- a/thirdparty/jolt_physics/Jolt/Math/Vec4.inl+++ b/thirdparty/jolt_physics/Jolt/Math/Vec4.inl@@ -20,6 +20,10 @@ Vec4::Vec4(Vec3Arg inRHS, float inW)mValue = _mm_blend_ps(inRHS.mValue, _mm_set1_ps(inW), 8);#elif defined(JPH_USE_NEON)mValue = vsetq_lane_f32(inW, inRHS.mValue, 3);+#elif defined(JPH_USE_RVV)+ const vfloat32m1_t v = __riscv_vle32_v_f32m1(inRHS.mF32, 4);+ __riscv_vse32_v_f32m1(mF32, v, 4);+ mF32[3] = inW;#elsefor (int i = 0; i < 3; i++)mF32[i] = inRHS.mF32[i];@@ -35,6 +39,12 @@ Vec4::Vec4(float inX, float inY, float inZ, float inW)uint32x2_t xy = vcreate_u32(static_cast<uint64>(BitCast<uint32>(inX)) | (static_cast<uint64>(BitCast<uint32>(inY)) << 32));uint32x2_t zw = vcreate_u32(static_cast<uint64>(BitCast<uint32>(inZ)) | (static_cast<uint64>(BitCast<uint32>(inW)) << 32));mValue = vreinterpretq_f32_u32(vcombine_u32(xy, zw));+#elif defined(JPH_USE_RVV)+ vfloat32m1_t v = __riscv_vfmv_v_f_f32m1(inW, 4);+ v = __riscv_vfslide1up_vf_f32m1(v, inZ, 4);+ v = __riscv_vfslide1up_vf_f32m1(v, inY, 4);+ v = __riscv_vfslide1up_vf_f32m1(v, inX, 4);+ __riscv_vse32_v_f32m1(mF32, v, 4);#elsemF32[0] = inX;mF32[1] = inY;@@ -55,6 +65,14 @@ Vec4 Vec4::Swizzle() constreturn _mm_shuffle_ps(mValue, mValue, _MM_SHUFFLE(SwizzleW, SwizzleZ, SwizzleY, SwizzleX));#elif defined(JPH_USE_NEON)return JPH_NEON_SHUFFLE_F32x4(mValue, mValue, SwizzleX, SwizzleY, SwizzleZ, SwizzleW);+#elif defined(JPH_USE_RVV)+ Vec4 v;+ const vfloat32m1_t data = __riscv_vle32_v_f32m1(mF32, 4);+ const uint32 stored_indices[4] = { SwizzleX, SwizzleY, SwizzleZ, SwizzleW };+ const vuint32m1_t index = __riscv_vle32_v_u32m1(stored_indices, 4);+ const vfloat32m1_t swizzled = __riscv_vrgather_vv_f32m1(data, index, 4);+ __riscv_vse32_v_f32m1(v.mF32, swizzled, 4);+ return v;#elsereturn Vec4(mF32[SwizzleX], mF32[SwizzleY], mF32[SwizzleZ], mF32[SwizzleW]);#endif@@ -66,6 +84,11 @@ Vec4 Vec4::sZero()return _mm_setzero_ps();#elif defined(JPH_USE_NEON)return vdupq_n_f32(0);+#elif defined(JPH_USE_RVV)+ Vec4 v;+ const vfloat32m1_t zero_vec = __riscv_vfmv_v_f_f32m1(0.0f, 4);+ __riscv_vse32_v_f32m1(v.mF32, zero_vec, 4);+ return v;#elsereturn Vec4(0, 0, 0, 0);#endif@@ -77,6 +100,11 @@ Vec4 Vec4::sReplicate(float inV)return _mm_set1_ps(inV);#elif defined(JPH_USE_NEON)return vdupq_n_f32(inV);+#elif defined(JPH_USE_RVV)+ Vec4 vec;+ const vfloat32m1_t v = __riscv_vfmv_v_f_f32m1(inV, 4);+ __riscv_vse32_v_f32m1(vec.mF32, v, 4);+ return vec;#elsereturn Vec4(inV, inV, inV, inV);#endif@@ -98,6 +126,11 @@ Vec4 Vec4::sLoadFloat4(const Float4 *inV)return _mm_loadu_ps(&inV->x);#elif defined(JPH_USE_NEON)return vld1q_f32(&inV->x);+#elif defined(JPH_USE_RVV)+ Vec4 vector;+ const vfloat32m1_t v = __riscv_vle32_v_f32m1(&inV->x, 4);+ __riscv_vse32_v_f32m1(vector.mF32, v, 4);+ return vector;#elsereturn Vec4(inV->x, inV->y, inV->z, inV->w);#endif@@ -109,6 +142,11 @@ Vec4 Vec4::sLoadFloat4Aligned(const Float4 *inV)return _mm_load_ps(&inV->x);#elif defined(JPH_USE_NEON)return vld1q_f32(&inV->x);+#elif defined(JPH_USE_RVV)+ Vec4 vector;+ vfloat32m1_t v = __riscv_vle32_v_f32m1(&inV->x, 4);+ __riscv_vse32_v_f32m1(vector.mF32, v, 4);+ return vector;#elsereturn Vec4(inV->x, inV->y, inV->z, inV->w);#endif@@ -130,6 +168,13 @@ Vec4 Vec4::sGatherFloat4(const float *inBase, UVec4Arg inOffsets)Type zw = _mm_unpacklo_ps(z, w);return _mm_movelh_ps(xy, zw);#endif+#elif defined(JPH_USE_RVV)+ Vec4 v;+ const vuint32m1_t offsets = __riscv_vle32_v_u32m1(inOffsets.mU32, 4);+ const vuint32m1_t scaled_offsets = __riscv_vmul_vx_u32m1(offsets, Scale, 4);+ const vfloat32m1_t gathered = __riscv_vluxei32_v_f32m1(inBase, scaled_offsets, 4);+ __riscv_vse32_v_f32m1(v.mF32, gathered, 4);+ return v;#elseconst uint8 *base = reinterpret_cast<const uint8 *>(inBase);float x = *reinterpret_cast<const float *>(base + inOffsets.GetX() * Scale);@@ -146,6 +191,13 @@ Vec4 Vec4::sMin(Vec4Arg inV1, Vec4Arg inV2)return _mm_min_ps(inV1.mValue, inV2.mValue);#elif defined(JPH_USE_NEON)return vminq_f32(inV1.mValue, inV2.mValue);+#elif defined(JPH_USE_RVV)+ Vec4 res;+ const vfloat32m1_t v1 = __riscv_vle32_v_f32m1(inV1.mF32, 4);+ const vfloat32m1_t v2 = __riscv_vle32_v_f32m1(inV2.mF32, 4);+ const vfloat32m1_t min = __riscv_vfmin_vv_f32m1(v1, v2, 4);+ __riscv_vse32_v_f32m1(res.mF32, min, 4);+ return res;#elsereturn Vec4(min(inV1.mF32[0], inV2.mF32[0]),min(inV1.mF32[1], inV2.mF32[1]),@@ -160,6 +212,13 @@ Vec4 Vec4::sMax(Vec4Arg inV1, Vec4Arg inV2)return _mm_max_ps(inV1.mValue, inV2.mValue);#elif defined(JPH_USE_NEON)return vmaxq_f32(inV1.mValue, inV2.mValue);+#elif defined(JPH_USE_RVV)+ Vec4 res;+ const vfloat32m1_t v1 = __riscv_vle32_v_f32m1(inV1.mF32, 4);+ const vfloat32m1_t v2 = __riscv_vle32_v_f32m1(inV2.mF32, 4);+ const vfloat32m1_t max = __riscv_vfmax_vv_f32m1(v1, v2, 4);+ __riscv_vse32_v_f32m1(res.mF32, max, 4);+ return res;#elsereturn Vec4(max(inV1.mF32[0], inV2.mF32[0]),max(inV1.mF32[1], inV2.mF32[1]),@@ -179,6 +238,15 @@ UVec4 Vec4::sEquals(Vec4Arg inV1, Vec4Arg inV2)return _mm_castps_si128(_mm_cmpeq_ps(inV1.mValue, inV2.mValue));#elif defined(JPH_USE_NEON)return vceqq_f32(inV1.mValue, inV2.mValue);+#elif defined(JPH_USE_RVV)+ UVec4 res;+ const vfloat32m1_t v1 = __riscv_vle32_v_f32m1(inV1.mF32, 4);+ const vfloat32m1_t v2 = __riscv_vle32_v_f32m1(inV2.mF32, 4);+ const vbool32_t mask = __riscv_vmfeq_vv_f32m1_b32(v1, v2, 4);+ const vuint32m1_t zeros = __riscv_vmv_v_x_u32m1(0x0, 4);+ const vuint32m1_t merged = __riscv_vmerge_vxm_u32m1(zeros, 0xFFFFFFFF, mask, 4);+ __riscv_vse32_v_u32m1(res.mU32, merged, 4);+ return res;#elsereturn UVec4(inV1.mF32[0] == inV2.mF32[0]? 0xffffffffu : 0,inV1.mF32[1] == inV2.mF32[1]? 0xffffffffu : 0,@@ -193,6 +261,15 @@ UVec4 Vec4::sLess(Vec4Arg inV1, Vec4Arg inV2)return _mm_castps_si128(_mm_cmplt_ps(inV1.mValue, inV2.mValue));#elif defined(JPH_USE_NEON)return vcltq_f32(inV1.mValue, inV2.mValue);+#elif defined(JPH_USE_RVV)+ UVec4 res;+ const vfloat32m1_t v1 = __riscv_vle32_v_f32m1(inV1.mF32, 4);+ const vfloat32m1_t v2 = __riscv_vle32_v_f32m1(inV2.mF32, 4);+ const vbool32_t mask = __riscv_vmflt_vv_f32m1_b32(v1, v2, 4);+ const vuint32m1_t zeros = __riscv_vmv_v_x_u32m1(0x0, 4);+ const vuint32m1_t merged = __riscv_vmerge_vxm_u32m1(zeros, 0xFFFFFFFF, mask, 4);+ __riscv_vse32_v_u32m1(res.mU32, merged, 4);+ return res;#elsereturn UVec4(inV1.mF32[0] < inV2.mF32[0]? 0xffffffffu : 0,inV1.mF32[1] < inV2.mF32[1]? 0xffffffffu : 0,@@ -207,6 +284,15 @@ UVec4 Vec4::sLessOrEqual(Vec4Arg inV1, Vec4Arg inV2)return _mm_castps_si128(_mm_cmple_ps(inV1.mValue, inV2.mValue));#elif defined(JPH_USE_NEON)return vcleq_f32(inV1.mValue, inV2.mValue);+#elif defined(JPH_USE_RVV)+ UVec4 res;+ const vfloat32m1_t v1 = __riscv_vle32_v_f32m1(inV1.mF32, 4);+ const vfloat32m1_t v2 = __riscv_vle32_v_f32m1(inV2.mF32, 4);+ const vbool32_t mask = __riscv_vmfle_vv_f32m1_b32(v1, v2, 4);+ const vuint32m1_t zeros = __riscv_vmv_v_x_u32m1(0x0, 4);+ const vuint32m1_t merged = __riscv_vmerge_vxm_u32m1(zeros, 0xFFFFFFFF, mask, 4);+ __riscv_vse32_v_u32m1(res.mU32, merged, 4);+ return res;#elsereturn UVec4(inV1.mF32[0] <= inV2.mF32[0]? 0xffffffffu : 0,inV1.mF32[1] <= inV2.mF32[1]? 0xffffffffu : 0,@@ -221,6 +307,15 @@ UVec4 Vec4::sGreater(Vec4Arg inV1, Vec4Arg inV2)return _mm_castps_si128(_mm_cmpgt_ps(inV1.mValue, inV2.mValue));#elif defined(JPH_USE_NEON)return vcgtq_f32(inV1.mValue, inV2.mValue);+#elif defined(JPH_USE_RVV)+ UVec4 res;+ const vfloat32m1_t v1 = __riscv_vle32_v_f32m1(inV1.mF32, 4);+ const vfloat32m1_t v2 = __riscv_vle32_v_f32m1(inV2.mF32, 4);+ const vbool32_t mask = __riscv_vmfgt_vv_f32m1_b32(v1, v2, 4);+ const vuint32m1_t zeros = __riscv_vmv_v_x_u32m1(0x0, 4);+ const vuint32m1_t merged = __riscv_vmerge_vxm_u32m1(zeros, 0xFFFFFFFF, mask, 4);+ __riscv_vse32_v_u32m1(res.mU32, merged, 4);+ return res;#elsereturn UVec4(inV1.mF32[0] > inV2.mF32[0]? 0xffffffffu : 0,inV1.mF32[1] > inV2.mF32[1]? 0xffffffffu : 0,@@ -235,6 +330,15 @@ UVec4 Vec4::sGreaterOrEqual(Vec4Arg inV1, Vec4Arg inV2)return _mm_castps_si128(_mm_cmpge_ps(inV1.mValue, inV2.mValue));#elif defined(JPH_USE_NEON)return vcgeq_f32(inV1.mValue, inV2.mValue);+#elif defined(JPH_USE_RVV)+ UVec4 res;+ const vfloat32m1_t v1 = __riscv_vle32_v_f32m1(inV1.mF32, 4);+ const vfloat32m1_t v2 = __riscv_vle32_v_f32m1(inV2.mF32, 4);+ const vbool32_t mask = __riscv_vmfge_vv_f32m1_b32(v1, v2, 4);+ const vuint32m1_t zeros = __riscv_vmv_v_x_u32m1(0x0, 4);+ const vuint32m1_t merged = __riscv_vmerge_vxm_u32m1(zeros, 0xFFFFFFFF, mask, 4);+ __riscv_vse32_v_u32m1(res.mU32, merged, 4);+ return res;#elsereturn UVec4(inV1.mF32[0] >= inV2.mF32[0]? 0xffffffffu : 0,inV1.mF32[1] >= inV2.mF32[1]? 0xffffffffu : 0,@@ -245,19 +349,24 @@ UVec4 Vec4::sGreaterOrEqual(Vec4Arg inV1, Vec4Arg inV2)Vec4 Vec4::sFusedMultiplyAdd(Vec4Arg inMul1, Vec4Arg inMul2, Vec4Arg inAdd){-#if defined(JPH_USE_SSE)- #ifdef JPH_USE_FMADD+#ifdef JPH_USE_FMADD+ #ifdef JPH_USE_SSEreturn _mm_fmadd_ps(inMul1.mValue, inMul2.mValue, inAdd.mValue);+ #elif defined(JPH_USE_NEON)+ return vmlaq_f32(inAdd.mValue, inMul1.mValue, inMul2.mValue);+ #elif defined(JPH_USE_RVV)+ Vec4 res;+ const vfloat32m1_t v1 = __riscv_vle32_v_f32m1(inMul1.mF32, 4);+ const vfloat32m1_t v2 = __riscv_vle32_v_f32m1(inMul2.mF32, 4);+ const vfloat32m1_t rvv_add = __riscv_vle32_v_f32m1(inAdd.mF32, 4);+ const vfloat32m1_t fmadd = __riscv_vfmacc_vv_f32m1(rvv_add, v1, v2, 4);+ __riscv_vse32_v_f32m1(res.mF32, fmadd, 4);+ return res;#else- return _mm_add_ps(_mm_mul_ps(inMul1.mValue, inMul2.mValue), inAdd.mValue);+ return inMul1 * inMul2 + inAdd;#endif-#elif defined(JPH_USE_NEON)- return vmlaq_f32(inAdd.mValue, inMul1.mValue, inMul2.mValue);#else- return Vec4(inMul1.mF32[0] * inMul2.mF32[0] + inAdd.mF32[0],- inMul1.mF32[1] * inMul2.mF32[1] + inAdd.mF32[1],- inMul1.mF32[2] * inMul2.mF32[2] + inAdd.mF32[2],- inMul1.mF32[3] * inMul2.mF32[3] + inAdd.mF32[3]);+ return inMul1 * inMul2 + inAdd;#endif}@@ -270,6 +379,18 @@ Vec4 Vec4::sSelect(Vec4Arg inNotSet, Vec4Arg inSet, UVec4Arg inControl)return _mm_or_ps(_mm_and_ps(is_set, inSet.mValue), _mm_andnot_ps(is_set, inNotSet.mValue));#elif defined(JPH_USE_NEON)return vbslq_f32(vreinterpretq_u32_s32(vshrq_n_s32(vreinterpretq_s32_u32(inControl.mValue), 31)), inSet.mValue, inNotSet.mValue);+#elif defined(JPH_USE_RVV)+ Vec4 masked;+ const vuint32m1_t control = __riscv_vle32_v_u32m1(inControl.mU32, 4);+ const vfloat32m1_t not_set = __riscv_vle32_v_f32m1(inNotSet.mF32, 4);+ const vfloat32m1_t set = __riscv_vle32_v_f32m1(inSet.mF32, 4);++ // Generate RVV bool mask from UVec4+ const vuint32m1_t r = __riscv_vand_vx_u32m1(control, 0x80000000u, 4);+ const vbool32_t rvv_mask = __riscv_vmsne_vx_u32m1_b32(r, 0x0, 4);+ const vfloat32m1_t merged = __riscv_vmerge_vvm_f32m1(not_set, set, rvv_mask, 4);+ __riscv_vse32_v_f32m1(masked.mF32, merged, 4);+ return masked;#elseVec4 result;for (int i = 0; i < 4; i++)@@ -284,6 +405,13 @@ Vec4 Vec4::sOr(Vec4Arg inV1, Vec4Arg inV2)return _mm_or_ps(inV1.mValue, inV2.mValue);#elif defined(JPH_USE_NEON)return vreinterpretq_f32_u32(vorrq_u32(vreinterpretq_u32_f32(inV1.mValue), vreinterpretq_u32_f32(inV2.mValue)));+#elif defined(JPH_USE_RVV)+ Vec4 or_result;+ const vuint32m1_t v1 = __riscv_vle32_v_u32m1(reinterpret_cast<const uint32 *>(inV1.mF32), 4);+ const vuint32m1_t v2 = __riscv_vle32_v_u32m1(reinterpret_cast<const uint32 *>(inV2.mF32), 4);+ const vuint32m1_t res = __riscv_vor_vv_u32m1(v1, v2, 4);+ __riscv_vse32_v_u32m1(reinterpret_cast<uint32 *>(or_result.mF32), res, 4);+ return or_result;#elsereturn UVec4::sOr(inV1.ReinterpretAsInt(), inV2.ReinterpretAsInt()).ReinterpretAsFloat();#endif@@ -295,6 +423,13 @@ Vec4 Vec4::sXor(Vec4Arg inV1, Vec4Arg inV2)return _mm_xor_ps(inV1.mValue, inV2.mValue);#elif defined(JPH_USE_NEON)return vreinterpretq_f32_u32(veorq_u32(vreinterpretq_u32_f32(inV1.mValue), vreinterpretq_u32_f32(inV2.mValue)));+#elif defined(JPH_USE_RVV)+ Vec4 xor_result;+ const vuint32m1_t v1 = __riscv_vle32_v_u32m1(reinterpret_cast<const uint32 *>(inV1.mF32), 4);+ const vuint32m1_t v2 = __riscv_vle32_v_u32m1(reinterpret_cast<const uint32 *>(inV2.mF32), 4);+ const vuint32m1_t res = __riscv_vxor_vv_u32m1(v1, v2, 4);+ __riscv_vse32_v_u32m1(reinterpret_cast<uint32 *>(xor_result.mF32), res, 4);+ return xor_result;#elsereturn UVec4::sXor(inV1.ReinterpretAsInt(), inV2.ReinterpretAsInt()).ReinterpretAsFloat();#endif@@ -306,6 +441,13 @@ Vec4 Vec4::sAnd(Vec4Arg inV1, Vec4Arg inV2)return _mm_and_ps(inV1.mValue, inV2.mValue);#elif defined(JPH_USE_NEON)return vreinterpretq_f32_u32(vandq_u32(vreinterpretq_u32_f32(inV1.mValue), vreinterpretq_u32_f32(inV2.mValue)));+#elif defined(JPH_USE_RVV)+ Vec4 and_result;+ const vuint32m1_t v1 = __riscv_vle32_v_u32m1(reinterpret_cast<const uint32 *>(inV1.mF32), 4);+ const vuint32m1_t v2 = __riscv_vle32_v_u32m1(reinterpret_cast<const uint32 *>(inV2.mF32), 4);+ const vuint32m1_t res = __riscv_vand_vv_u32m1(v1, v2, 4);+ __riscv_vse32_v_u32m1(reinterpret_cast<uint32 *>(and_result.mF32), res, 4);+ return and_result;#elsereturn UVec4::sAnd(inV1.ReinterpretAsInt(), inV2.ReinterpretAsInt()).ReinterpretAsFloat();#endif@@ -388,6 +530,11 @@ bool Vec4::IsNaN() const#elif defined(JPH_USE_NEON)uint32x4_t is_equal = vceqq_f32(mValue, mValue); // If a number is not equal to itself it's a NaNreturn vaddvq_u32(vshrq_n_u32(is_equal, 31)) != 4;+#elif defined(JPH_USE_RVV)+ const vfloat32m1_t v = __riscv_vle32_v_f32m1(mF32, 4);+ const vbool32_t mask = __riscv_vmfeq_vv_f32m1_b32(v, v, 4);+ const uint32 eq = __riscv_vcpop_m_b32(mask, 4);+ return eq != 4;#elsereturn isnan(mF32[0]) || isnan(mF32[1]) || isnan(mF32[2]) || isnan(mF32[3]);#endif@@ -399,6 +546,13 @@ Vec4 Vec4::operator * (Vec4Arg inV2) constreturn _mm_mul_ps(mValue, inV2.mValue);#elif defined(JPH_USE_NEON)return vmulq_f32(mValue, inV2.mValue);+#elif defined(JPH_USE_RVV)+ Vec4 res;+ const vfloat32m1_t v1 = __riscv_vle32_v_f32m1(mF32, 4);+ const vfloat32m1_t v2 = __riscv_vle32_v_f32m1(inV2.mF32, 4);+ const vfloat32m1_t mul = __riscv_vfmul_vv_f32m1(v1, v2, 4);+ __riscv_vse32_v_f32m1(res.mF32, mul, 4);+ return res;#elsereturn Vec4(mF32[0] * inV2.mF32[0],mF32[1] * inV2.mF32[1],@@ -413,6 +567,12 @@ Vec4 Vec4::operator * (float inV2) constreturn _mm_mul_ps(mValue, _mm_set1_ps(inV2));#elif defined(JPH_USE_NEON)return vmulq_n_f32(mValue, inV2);+#elif defined(JPH_USE_RVV)+ Vec4 res;+ const vfloat32m1_t src = __riscv_vle32_v_f32m1(mF32, 4);+ const vfloat32m1_t mul = __riscv_vfmul_vf_f32m1(src, inV2, 4);+ __riscv_vse32_v_f32m1(res.mF32, mul, 4);+ return res;#elsereturn Vec4(mF32[0] * inV2, mF32[1] * inV2, mF32[2] * inV2, mF32[3] * inV2);#endif@@ -425,6 +585,12 @@ Vec4 operator * (float inV1, Vec4Arg inV2)return _mm_mul_ps(_mm_set1_ps(inV1), inV2.mValue);#elif defined(JPH_USE_NEON)return vmulq_n_f32(inV2.mValue, inV1);+#elif defined(JPH_USE_RVV)+ Vec4 res;+ const vfloat32m1_t v1 = __riscv_vle32_v_f32m1(inV2.mF32, 4);+ const vfloat32m1_t mul = __riscv_vfmul_vf_f32m1(v1, inV1, 4);+ __riscv_vse32_v_f32m1(res.mF32, mul, 4);+ return res;#elsereturn Vec4(inV1 * inV2.mF32[0],inV1 * inV2.mF32[1],@@ -439,6 +605,12 @@ Vec4 Vec4::operator / (float inV2) constreturn _mm_div_ps(mValue, _mm_set1_ps(inV2));#elif defined(JPH_USE_NEON)return vdivq_f32(mValue, vdupq_n_f32(inV2));+#elif defined(JPH_USE_RVV)+ Vec4 res;+ const vfloat32m1_t v1 = __riscv_vle32_v_f32m1(mF32, 4);+ const vfloat32m1_t div = __riscv_vfdiv_vf_f32m1(v1, inV2, 4);+ __riscv_vse32_v_f32m1(res.mF32, div, 4);+ return res;#elsereturn Vec4(mF32[0] / inV2, mF32[1] / inV2, mF32[2] / inV2, mF32[3] / inV2);#endif@@ -450,6 +622,10 @@ Vec4 &Vec4::operator *= (float inV2)mValue = _mm_mul_ps(mValue, _mm_set1_ps(inV2));#elif defined(JPH_USE_NEON)mValue = vmulq_n_f32(mValue, inV2);+#elif defined(JPH_USE_RVV)+ const vfloat32m1_t v1 = __riscv_vle32_v_f32m1(mF32, 4);+ const vfloat32m1_t res = __riscv_vfmul_vf_f32m1(v1, inV2, 4);+ __riscv_vse32_v_f32m1(mF32, res, 4);#elsefor (int i = 0; i < 4; ++i)mF32[i] *= inV2;@@ -463,6 +639,11 @@ Vec4 &Vec4::operator *= (Vec4Arg inV2)mValue = _mm_mul_ps(mValue, inV2.mValue);#elif defined(JPH_USE_NEON)mValue = vmulq_f32(mValue, inV2.mValue);+#elif defined(JPH_USE_RVV)+ const vfloat32m1_t v1 = __riscv_vle32_v_f32m1(mF32, 4);+ const vfloat32m1_t v2 = __riscv_vle32_v_f32m1(inV2.mF32, 4);+ const vfloat32m1_t rvv_res = __riscv_vfmul_vv_f32m1(v1, v2, 4);+ __riscv_vse32_v_f32m1(mF32, rvv_res, 4);#elsefor (int i = 0; i < 4; ++i)mF32[i] *= inV2.mF32[i];@@ -476,6 +657,10 @@ Vec4 &Vec4::operator /= (float inV2)mValue = _mm_div_ps(mValue, _mm_set1_ps(inV2));#elif defined(JPH_USE_NEON)mValue = vdivq_f32(mValue, vdupq_n_f32(inV2));+#elif defined(JPH_USE_RVV)+ const vfloat32m1_t v = __riscv_vle32_v_f32m1(mF32, 4);+ const vfloat32m1_t res = __riscv_vfdiv_vf_f32m1(v, inV2, 4);+ __riscv_vse32_v_f32m1(mF32, res, 4);#elsefor (int i = 0; i < 4; ++i)mF32[i] /= inV2;@@ -489,6 +674,13 @@ Vec4 Vec4::operator + (Vec4Arg inV2) constreturn _mm_add_ps(mValue, inV2.mValue);#elif defined(JPH_USE_NEON)return vaddq_f32(mValue, inV2.mValue);+#elif defined(JPH_USE_RVV)+ Vec4 res;+ const vfloat32m1_t v1 = __riscv_vle32_v_f32m1(mF32, 4);+ const vfloat32m1_t v2 = __riscv_vle32_v_f32m1(inV2.mF32, 4);+ const vfloat32m1_t rvv_add = __riscv_vfadd_vv_f32m1(v1, v2, 4);+ __riscv_vse32_v_f32m1(res.mF32, rvv_add, 4);+ return res;#elsereturn Vec4(mF32[0] + inV2.mF32[0],mF32[1] + inV2.mF32[1],@@ -503,6 +695,11 @@ Vec4 &Vec4::operator += (Vec4Arg inV2)mValue = _mm_add_ps(mValue, inV2.mValue);#elif defined(JPH_USE_NEON)mValue = vaddq_f32(mValue, inV2.mValue);+#elif defined(JPH_USE_RVV)+ const vfloat32m1_t v1 = __riscv_vle32_v_f32m1(mF32, 4);+ const vfloat32m1_t v2 = __riscv_vle32_v_f32m1(inV2.mF32, 4);+ const vfloat32m1_t rvv_add = __riscv_vfadd_vv_f32m1(v1, v2, 4);+ __riscv_vse32_v_f32m1(mF32, rvv_add, 4);#elsefor (int i = 0; i < 4; ++i)mF32[i] += inV2.mF32[i];@@ -520,6 +717,21 @@ Vec4 Vec4::operator - () const#elsereturn vnegq_f32(mValue);#endif+#elif defined(JPH_USE_RVV)+ #ifdef JPH_CROSS_PLATFORM_DETERMINISTIC+ Vec4 res;+ const vfloat32m1_t rvv_zero = __riscv_vfmv_v_f_f32m1(0.0f, 4);+ const vfloat32m1_t v = __riscv_vle32_v_f32m1(mF32, 4);+ const vfloat32m1_t rvv_neg = __riscv_vfsub_vv_f32m1(rvv_zero, v, 4);+ __riscv_vse32_v_f32m1(res.mF32, rvv_neg, 4);+ return res;+ #else+ Vec4 res;+ const vfloat32m1_t v = __riscv_vle32_v_f32m1(mF32, 4);+ const vfloat32m1_t rvv_neg = __riscv_vfsgnjn_vv_f32m1(v, v, 4);+ __riscv_vse32_v_f32m1(res.mF32, rvv_neg, 4);+ return res;+ #endif#else#ifdef JPH_CROSS_PLATFORM_DETERMINISTICreturn Vec4(0.0f - mF32[0], 0.0f - mF32[1], 0.0f - mF32[2], 0.0f - mF32[3]);@@ -535,6 +747,13 @@ Vec4 Vec4::operator - (Vec4Arg inV2) constreturn _mm_sub_ps(mValue, inV2.mValue);#elif defined(JPH_USE_NEON)return vsubq_f32(mValue, inV2.mValue);+#elif defined(JPH_USE_RVV)+ Vec4 res;+ const vfloat32m1_t v1 = __riscv_vle32_v_f32m1(mF32, 4);+ const vfloat32m1_t v2 = __riscv_vle32_v_f32m1(inV2.mF32, 4);+ const vfloat32m1_t rvv_sub = __riscv_vfsub_vv_f32m1(v1, v2, 4);+ __riscv_vse32_v_f32m1(res.mF32, rvv_sub, 4);+ return res;#elsereturn Vec4(mF32[0] - inV2.mF32[0],mF32[1] - inV2.mF32[1],@@ -549,6 +768,11 @@ Vec4 &Vec4::operator -= (Vec4Arg inV2)mValue = _mm_sub_ps(mValue, inV2.mValue);#elif defined(JPH_USE_NEON)mValue = vsubq_f32(mValue, inV2.mValue);+#elif defined(JPH_USE_RVV)+ const vfloat32m1_t v1 = __riscv_vle32_v_f32m1(mF32, 4);+ const vfloat32m1_t v2 = __riscv_vle32_v_f32m1(inV2.mF32, 4);+ const vfloat32m1_t rvv_sub = __riscv_vfsub_vv_f32m1(v1, v2, 4);+ __riscv_vse32_v_f32m1(mF32, rvv_sub, 4);#elsefor (int i = 0; i < 4; ++i)mF32[i] -= inV2.mF32[i];@@ -562,6 +786,13 @@ Vec4 Vec4::operator / (Vec4Arg inV2) constreturn _mm_div_ps(mValue, inV2.mValue);#elif defined(JPH_USE_NEON)return vdivq_f32(mValue, inV2.mValue);+#elif defined(JPH_USE_RVV)+ Vec4 res;+ const vfloat32m1_t v1 = __riscv_vle32_v_f32m1(mF32, 4);+ const vfloat32m1_t v2 = __riscv_vle32_v_f32m1(inV2.mF32, 4);+ const vfloat32m1_t rvv_div = __riscv_vfdiv_vv_f32m1(v1, v2, 4);+ __riscv_vse32_v_f32m1(res.mF32, rvv_div, 4);+ return res;#elsereturn Vec4(mF32[0] / inV2.mF32[0],mF32[1] / inV2.mF32[1],@@ -576,6 +807,11 @@ Vec4 Vec4::SplatX() constreturn _mm_shuffle_ps(mValue, mValue, _MM_SHUFFLE(0, 0, 0, 0));#elif defined(JPH_USE_NEON)return vdupq_laneq_f32(mValue, 0);+#elif defined(JPH_USE_RVV)+ Vec4 vec;+ const vfloat32m1_t splat = __riscv_vfmv_v_f_f32m1(mF32[0], 4);+ __riscv_vse32_v_f32m1(vec.mF32, splat, 4);+ return vec;#elsereturn Vec4(mF32[0], mF32[0], mF32[0], mF32[0]);#endif@@ -587,6 +823,11 @@ Vec4 Vec4::SplatY() constreturn _mm_shuffle_ps(mValue, mValue, _MM_SHUFFLE(1, 1, 1, 1));#elif defined(JPH_USE_NEON)return vdupq_laneq_f32(mValue, 1);+#elif defined(JPH_USE_RVV)+ Vec4 vec;+ const vfloat32m1_t splat = __riscv_vfmv_v_f_f32m1(mF32[1], 4);+ __riscv_vse32_v_f32m1(vec.mF32, splat, 4);+ return vec;#elsereturn Vec4(mF32[1], mF32[1], mF32[1], mF32[1]);#endif@@ -598,6 +839,11 @@ Vec4 Vec4::SplatZ() constreturn _mm_shuffle_ps(mValue, mValue, _MM_SHUFFLE(2, 2, 2, 2));#elif defined(JPH_USE_NEON)return vdupq_laneq_f32(mValue, 2);+#elif defined(JPH_USE_RVV)+ Vec4 vec;+ const vfloat32m1_t splat = __riscv_vfmv_v_f_f32m1(mF32[2], 4);+ __riscv_vse32_v_f32m1(vec.mF32, splat, 4);+ return vec;#elsereturn Vec4(mF32[2], mF32[2], mF32[2], mF32[2]);#endif@@ -609,6 +855,11 @@ Vec4 Vec4::SplatW() constreturn _mm_shuffle_ps(mValue, mValue, _MM_SHUFFLE(3, 3, 3, 3));#elif defined(JPH_USE_NEON)return vdupq_laneq_f32(mValue, 3);+#elif defined(JPH_USE_RVV)+ Vec4 vec;+ const vfloat32m1_t splat = __riscv_vfmv_v_f_f32m1(mF32[3], 4);+ __riscv_vse32_v_f32m1(vec.mF32, splat, 4);+ return vec;#elsereturn Vec4(mF32[3], mF32[3], mF32[3], mF32[3]);#endif@@ -620,6 +871,11 @@ Vec3 Vec4::SplatX3() constreturn _mm_shuffle_ps(mValue, mValue, _MM_SHUFFLE(0, 0, 0, 0));#elif defined(JPH_USE_NEON)return vdupq_laneq_f32(mValue, 0);+#elif defined(JPH_USE_RVV)+ Vec3 vec;+ const vfloat32m1_t splat = __riscv_vfmv_v_f_f32m1(mF32[0], 3);+ __riscv_vse32_v_f32m1(vec.mF32, splat, 3);+ return vec;#elsereturn Vec3(mF32[0], mF32[0], mF32[0]);#endif@@ -631,6 +887,11 @@ Vec3 Vec4::SplatY3() constreturn _mm_shuffle_ps(mValue, mValue, _MM_SHUFFLE(1, 1, 1, 1));#elif defined(JPH_USE_NEON)return vdupq_laneq_f32(mValue, 1);+#elif defined(JPH_USE_RVV)+ Vec3 vec;+ const vfloat32m1_t splat = __riscv_vfmv_v_f_f32m1(mF32[1], 3);+ __riscv_vse32_v_f32m1(vec.mF32, splat, 3);+ return vec;#elsereturn Vec3(mF32[1], mF32[1], mF32[1]);#endif@@ -642,6 +903,11 @@ Vec3 Vec4::SplatZ3() constreturn _mm_shuffle_ps(mValue, mValue, _MM_SHUFFLE(2, 2, 2, 2));#elif defined(JPH_USE_NEON)return vdupq_laneq_f32(mValue, 2);+#elif defined(JPH_USE_RVV)+ Vec3 vec;+ const vfloat32m1_t splat = __riscv_vfmv_v_f_f32m1(mF32[2], 3);+ __riscv_vse32_v_f32m1(vec.mF32, splat, 3);+ return vec;#elsereturn Vec3(mF32[2], mF32[2], mF32[2]);#endif@@ -653,6 +919,11 @@ Vec3 Vec4::SplatW3() constreturn _mm_shuffle_ps(mValue, mValue, _MM_SHUFFLE(3, 3, 3, 3));#elif defined(JPH_USE_NEON)return vdupq_laneq_f32(mValue, 3);+#elif defined(JPH_USE_RVV)+ Vec3 vec;+ const vfloat32m1_t splat = __riscv_vfmv_v_f_f32m1(mF32[3], 3);+ __riscv_vse32_v_f32m1(vec.mF32, splat, 3);+ return vec;#elsereturn Vec3(mF32[3], mF32[3], mF32[3]);#endif@@ -686,6 +957,12 @@ Vec4 Vec4::Abs() constreturn _mm_max_ps(_mm_sub_ps(_mm_setzero_ps(), mValue), mValue);#elif defined(JPH_USE_NEON)return vabsq_f32(mValue);+#elif defined(JPH_USE_RVV)+ Vec4 res;+ const vfloat32m1_t v = __riscv_vle32_v_f32m1(mF32, 4);+ const vfloat32m1_t rvv_abs = __riscv_vfsgnj_vf_f32m1(v, 1.0, 4);+ __riscv_vse32_v_f32m1(res.mF32, rvv_abs, 4);+ return res;#elsereturn Vec4(abs(mF32[0]), abs(mF32[1]), abs(mF32[2]), abs(mF32[3]));#endif@@ -696,57 +973,60 @@ Vec4 Vec4::Reciprocal() constreturn sOne() / mValue;}-Vec4 Vec4::DotV(Vec4Arg inV2) const+Vec4 Vec4::sDifferenceOfProducts(Vec4Arg inA, Vec4Arg inB, Vec4Arg inC, Vec4Arg inD){-#if defined(JPH_USE_SSE4_1)- return _mm_dp_ps(mValue, inV2.mValue, 0xff);-#elif defined(JPH_USE_NEON)- float32x4_t mul = vmulq_f32(mValue, inV2.mValue);- return vdupq_n_f32(vaddvq_f32(mul));+#ifdef JPH_USE_FMADD+ Vec4 cd = inC * inD;+ Vec4 err = Vec4::sFusedMultiplyAdd(-inC, inD, cd);+ Vec4 dop = Vec4::sFusedMultiplyAdd(inA, inB, -cd);+ return dop + err;#else- // Brackets placed so that the order is consistent with the vectorized version- return Vec4::sReplicate((mF32[0] * inV2.mF32[0] + mF32[1] * inV2.mF32[1]) + (mF32[2] * inV2.mF32[2] + mF32[3] * inV2.mF32[3]));+ return inA * inB - inC * inD;#endif}-float Vec4::Dot(Vec4Arg inV2) const+float Vec4::ReduceSum() const{#if defined(JPH_USE_SSE4_1)- return _mm_cvtss_f32(_mm_dp_ps(mValue, inV2.mValue, 0xff));+ Type shuf = _mm_movehdup_ps(mValue); // [y, y, w, w]+ Type sums = _mm_add_ps(mValue, shuf); // [x + y, y + y, z + w, w + w]+ shuf = _mm_movehl_ps(sums, sums); // [z + w, w + w, z + w, w + w]+ sums = _mm_add_ps(sums, shuf); // [(x + y) + (z + w), ...]+ return _mm_cvtss_f32(sums);#elif defined(JPH_USE_NEON)- float32x4_t mul = vmulq_f32(mValue, inV2.mValue);- return vaddvq_f32(mul);+ return vaddvq_f32(mValue);+#elif defined(JPH_USE_RVV)+ const vfloat32m1_t v = __riscv_vle32_v_f32m1(mF32, 4);+ return __riscv_vfmv_f_s_f32m1_f32(RVVSumElementsFloat32x4(v));#else// Brackets placed so that the order is consistent with the vectorized version- return (mF32[0] * inV2.mF32[0] + mF32[1] * inV2.mF32[1]) + (mF32[2] * inV2.mF32[2] + mF32[3] * inV2.mF32[3]);+ return (mF32[0] + mF32[1]) + (mF32[2] + mF32[3]);#endif}+float Vec4::Dot(Vec4Arg inV2) const+{+ return (*this * inV2).ReduceSum();+}++Vec4 Vec4::DotV(Vec4Arg inV2) const+{+ return Vec4::sReplicate(Dot(inV2));+}+float Vec4::LengthSq() const{-#if defined(JPH_USE_SSE4_1)- return _mm_cvtss_f32(_mm_dp_ps(mValue, mValue, 0xff));-#elif defined(JPH_USE_NEON)- float32x4_t mul = vmulq_f32(mValue, mValue);- return vaddvq_f32(mul);-#else- // Brackets placed so that the order is consistent with the vectorized version- return (mF32[0] * mF32[0] + mF32[1] * mF32[1]) + (mF32[2] * mF32[2] + mF32[3] * mF32[3]);-#endif+ return Dot(*this);}float Vec4::Length() const{-#if defined(JPH_USE_SSE4_1)- return _mm_cvtss_f32(_mm_sqrt_ss(_mm_dp_ps(mValue, mValue, 0xff)));-#elif defined(JPH_USE_NEON)- float32x4_t mul = vmulq_f32(mValue, mValue);- float32x2_t sum = vdup_n_f32(vaddvq_f32(mul));- return vget_lane_f32(vsqrt_f32(sum), 0);-#else- // Brackets placed so that the order is consistent with the vectorized version- return sqrt((mF32[0] * mF32[0] + mF32[1] * mF32[1]) + (mF32[2] * mF32[2] + mF32[3] * mF32[3]));-#endif+ return JPH::Sqrt(LengthSq());+}++Vec4 Vec4::Normalized() const+{+ return *this / Length();}Vec4 Vec4::Sqrt() const@@ -755,16 +1035,22 @@ Vec4 Vec4::Sqrt() constreturn _mm_sqrt_ps(mValue);#elif defined(JPH_USE_NEON)return vsqrtq_f32(mValue);+#elif defined(JPH_USE_RVV)+ Vec4 res;+ const vfloat32m1_t rvv_v = __riscv_vle32_v_f32m1(mF32, 4);+ const vfloat32m1_t rvv_sqrt = __riscv_vfsqrt_v_f32m1(rvv_v, 4);+ __riscv_vse32_v_f32m1(res.mF32, rvv_sqrt, 4);+ return res;#else- return Vec4(sqrt(mF32[0]), sqrt(mF32[1]), sqrt(mF32[2]), sqrt(mF32[3]));+ return Vec4(JPH::Sqrt(mF32[0]), JPH::Sqrt(mF32[1]), JPH::Sqrt(mF32[2]), JPH::Sqrt(mF32[3]));#endif}-Vec4 Vec4::GetSign() const{#if defined(JPH_USE_AVX512)- return _mm_fixupimm_ps(mValue, mValue, _mm_set1_epi32(0xA9A90A00), 0);+ Type one = _mm_set1_ps(1.0f);+ return _mm_or_ps(_mm_fixupimm_ps(mValue, mValue, _mm_set1_epi32(0xA9A90100), 0), one);#elif defined(JPH_USE_SSE)Type minus_one = _mm_set1_ps(-1.0f);Type one = _mm_set1_ps(1.0f);@@ -773,6 +1059,13 @@ Vec4 Vec4::GetSign() constType minus_one = vdupq_n_f32(-1.0f);Type one = vdupq_n_f32(1.0f);return vreinterpretq_f32_u32(vorrq_u32(vandq_u32(vreinterpretq_u32_f32(mValue), vreinterpretq_u32_f32(minus_one)), vreinterpretq_u32_f32(one)));+#elif defined(JPH_USE_RVV)+ Vec4 res;+ const vfloat32m1_t rvv_in = __riscv_vle32_v_f32m1(mF32, 4);+ const vfloat32m1_t rvv_one = __riscv_vfmv_v_f_f32m1(1.0, 4);+ const vfloat32m1_t rvv_signs = __riscv_vfsgnj_vv_f32m1(rvv_one, rvv_in, 4);+ __riscv_vse32_v_f32m1(res.mF32, rvv_signs, 4);+ return res;#elsereturn Vec4(std::signbit(mF32[0])? -1.0f : 1.0f,std::signbit(mF32[1])? -1.0f : 1.0f,@@ -791,25 +1084,15 @@ JPH_INLINE Vec4 Vec4::FlipSign() constreturn Vec4::sXor(*this, Vec4(X > 0? 0.0f : -0.0f, Y > 0? 0.0f : -0.0f, Z > 0? 0.0f : -0.0f, W > 0? 0.0f : -0.0f));}-Vec4 Vec4::Normalized() const-{-#if defined(JPH_USE_SSE4_1)- return _mm_div_ps(mValue, _mm_sqrt_ps(_mm_dp_ps(mValue, mValue, 0xff)));-#elif defined(JPH_USE_NEON)- float32x4_t mul = vmulq_f32(mValue, mValue);- float32x4_t sum = vdupq_n_f32(vaddvq_f32(mul));- return vdivq_f32(mValue, vsqrtq_f32(sum));-#else- return *this / Length();-#endif-}-void Vec4::StoreFloat4(Float4 *outV) const{#if defined(JPH_USE_SSE)_mm_storeu_ps(&outV->x, mValue);#elif defined(JPH_USE_NEON)vst1q_f32(&outV->x, mValue);+#elif defined(JPH_USE_RVV)+ const vfloat32m1_t v = __riscv_vle32_v_f32m1(mF32, 4);+ __riscv_vse32_v_f32m1(&outV->x, v, 4);#elsefor (int i = 0; i < 4; ++i)(&outV->x)[i] = mF32[i];@@ -822,6 +1105,12 @@ UVec4 Vec4::ToInt() constreturn _mm_cvttps_epi32(mValue);#elif defined(JPH_USE_NEON)return vcvtq_u32_f32(mValue);+#elif defined(JPH_USE_RVV)+ UVec4 res;+ const vfloat32m1_t v = __riscv_vle32_v_f32m1(mF32, 4);+ const vuint32m1_t cast = __riscv_vfcvt_rtz_xu_f_v_u32m1(v, 4);+ __riscv_vse32_v_u32m1(res.mU32, cast, 4);+ return res;#elsereturn UVec4(uint32(mF32[0]), uint32(mF32[1]), uint32(mF32[2]), uint32(mF32[3]));#endif@@ -845,6 +1134,13 @@ int Vec4::GetSignBits() const#elif defined(JPH_USE_NEON)int32x4_t shift = JPH_NEON_INT32x4(0, 1, 2, 3);return vaddvq_u32(vshlq_u32(vshrq_n_u32(vreinterpretq_u32_f32(mValue), 31), shift));+#elif defined(JPH_USE_RVV)+ const vuint32m1_t v = __riscv_vle32_v_u32m1(reinterpret_cast<const uint32 *>(mF32), 4);+ const vuint32m1_t shifted = __riscv_vsrl_vx_u32m1(v, 31, 4);+ const vbool32_t mask = __riscv_vmsne_vx_u32m1_b32(shifted, 0x0, 4);+ const vuint32m1_t as_int = __riscv_vreinterpret_v_b32_u32m1(mask);+ const uint32 result = __riscv_vmv_x_s_u32m1_u32(as_int) & 0xF;+ return result;#elsereturn (std::signbit(mF32[0])? 1 : 0) | (std::signbit(mF32[1])? 2 : 0) | (std::signbit(mF32[2])? 4 : 0) | (std::signbit(mF32[3])? 8 : 0);#endif@@ -852,16 +1148,24 @@ int Vec4::GetSignBits() constfloat Vec4::ReduceMin() const{+#ifdef JPH_USE_NEON+ return vminvq_f32(mValue);+#elseVec4 v = sMin(mValue, Swizzle<SWIZZLE_Y, SWIZZLE_UNUSED, SWIZZLE_W, SWIZZLE_UNUSED>());v = sMin(v, v.Swizzle<SWIZZLE_Z, SWIZZLE_UNUSED, SWIZZLE_UNUSED, SWIZZLE_UNUSED>());return v.GetX();+#endif}float Vec4::ReduceMax() const{+#ifdef JPH_USE_NEON+ return vmaxvq_f32(mValue);+#elseVec4 v = sMax(mValue, Swizzle<SWIZZLE_Y, SWIZZLE_UNUSED, SWIZZLE_W, SWIZZLE_UNUSED>());v = sMax(v, v.Swizzle<SWIZZLE_Z, SWIZZLE_UNUSED, SWIZZLE_UNUSED, SWIZZLE_UNUSED>());return v.GetX();+#endif}void Vec4::SinCos(Vec4 &outSin, Vec4 &outCos) const@@ -1117,14 +1421,15 @@ Vec4 Vec4::sDecompressUnitVector(uint32 inValue)constexpr uint cNumBits = 9;constexpr uint cMask = (1u << cNumBits) - 1;constexpr uint cMaxValue = cMask - 1; // Need odd number of buckets to quantize to or else we can't encode 0+ constexpr int cHalfMaxValue = int(cMaxValue >> 1);constexpr float cScale = 2.0f * cOneOverSqrt2 / float(cMaxValue);// Restore three components- Vec4 v = Vec4(UVec4(inValue & cMask, (inValue >> cNumBits) & cMask, (inValue >> (2 * cNumBits)) & cMask, 0).ToFloat()) * cScale - Vec4(cOneOverSqrt2, cOneOverSqrt2, cOneOverSqrt2, 0.0f);+ Vec4 v = Vec4(float(int(inValue & cMask) - cHalfMaxValue), float(int((inValue >> cNumBits) & cMask) - cHalfMaxValue), float(int(inValue >> (2 * cNumBits)) & cMask) - cHalfMaxValue, 0) * cScale;JPH_ASSERT(v.GetW() == 0.0f);// Restore the highest component- v.SetW(sqrt(max(1.0f - v.LengthSq(), 0.0f)));+ v.SetW(JPH::Sqrt(max(1.0f - v.LengthSq(), 0.0f)));// Extract signif ((inValue & 0x80000000u) != 0)diff --git a/thirdparty/jolt_physics/Jolt/Math/Vector.h b/thirdparty/jolt_physics/Jolt/Math/Vector.hindex b51a93c07b0..600433ed103 100644--- a/thirdparty/jolt_physics/Jolt/Math/Vector.h+++ b/thirdparty/jolt_physics/Jolt/Math/Vector.h@@ -74,6 +74,12 @@ public:return true;}+ /// Test if vector is near zero+ inline bool IsNearZero(float inMaxDistSq = 1.0e-12f) const+ {+ return LengthSq() <= inMaxDistSq;+ }+/// Test if two vectors are close to each otherinline bool IsClose(const Vector &inV2, float inMaxDistSq = 1.0e-12f) const{@@ -180,7 +186,7 @@ public:/// Length of vectorinline float Length() const{- return sqrt(LengthSq());+ return Sqrt(LengthSq());}/// Check if vector is normalizeddiff --git a/thirdparty/jolt_physics/Jolt/ObjectStream/SerializableAttributeEnum.h b/thirdparty/jolt_physics/Jolt/ObjectStream/SerializableAttributeEnum.hindex c6f241ea41c..286a324c178 100644--- a/thirdparty/jolt_physics/Jolt/ObjectStream/SerializableAttributeEnum.h+++ b/thirdparty/jolt_physics/Jolt/ObjectStream/SerializableAttributeEnum.h@@ -51,7 +51,7 @@ inline void AddSerializableAttributeEnum(RTTI &inRTTI, uint inOffset, const char// JPH_ADD_ENUM_ATTRIBUTE_WITH_ALIAS#define JPH_ADD_ENUM_ATTRIBUTE_WITH_ALIAS(class_name, member_name, alias_name) \- AddSerializableAttributeEnum<decltype(class_name::member_name)>(inRTTI, offsetof(class_name, member_name), alias_name);+ JPH::AddSerializableAttributeEnum<decltype(class_name::member_name)>(inRTTI, offsetof(class_name, member_name), alias_name);// JPH_ADD_ENUM_ATTRIBUTE#define JPH_ADD_ENUM_ATTRIBUTE(class_name, member_name) \diff --git a/thirdparty/jolt_physics/Jolt/ObjectStream/SerializableAttributeTyped.h b/thirdparty/jolt_physics/Jolt/ObjectStream/SerializableAttributeTyped.hindex ce18325c46c..5c9d3ae5500 100644--- a/thirdparty/jolt_physics/Jolt/ObjectStream/SerializableAttributeTyped.h+++ b/thirdparty/jolt_physics/Jolt/ObjectStream/SerializableAttributeTyped.h@@ -44,7 +44,7 @@ inline void AddSerializableAttributeTyped(RTTI &inRTTI, uint inOffset, const cha// JPH_ADD_ATTRIBUTE#define JPH_ADD_ATTRIBUTE_WITH_ALIAS(class_name, member_name, alias_name) \- AddSerializableAttributeTyped<decltype(class_name::member_name)>(inRTTI, offsetof(class_name, member_name), alias_name);+ JPH::AddSerializableAttributeTyped<decltype(class_name::member_name)>(inRTTI, offsetof(class_name, member_name), alias_name);// JPH_ADD_ATTRIBUTE#define JPH_ADD_ATTRIBUTE(class_name, member_name) \diff --git a/thirdparty/jolt_physics/Jolt/ObjectStream/SerializableObject.h b/thirdparty/jolt_physics/Jolt/ObjectStream/SerializableObject.hindex 280d8d14c06..a50b58f03d5 100644--- a/thirdparty/jolt_physics/Jolt/ObjectStream/SerializableObject.h+++ b/thirdparty/jolt_physics/Jolt/ObjectStream/SerializableObject.h@@ -16,52 +16,52 @@ JPH_NAMESPACE_BEGIN// JPH_DECLARE_SERIALIZATION_FUNCTIONS#define JPH_DECLARE_SERIALIZATION_FUNCTIONS(linkage, prefix, class_name) \- linkage prefix bool OSReadData(IObjectStreamIn &ioStream, class_name &inInstance); \- linkage prefix bool OSReadData(IObjectStreamIn &ioStream, class_name *&inPointer); \- linkage prefix bool OSIsType(class_name *, int inArrayDepth, EOSDataType inDataType, const char *inClassName); \- linkage prefix bool OSIsType(class_name **, int inArrayDepth, EOSDataType inDataType, const char *inClassName); \- linkage prefix void OSWriteData(IObjectStreamOut &ioStream, const class_name &inInstance); \- linkage prefix void OSWriteData(IObjectStreamOut &ioStream, class_name *const &inPointer); \- linkage prefix void OSWriteDataType(IObjectStreamOut &ioStream, class_name *); \- linkage prefix void OSWriteDataType(IObjectStreamOut &ioStream, class_name **);+ linkage prefix bool OSReadData(JPH::IObjectStreamIn &ioStream, class_name &inInstance); \+ linkage prefix bool OSReadData(JPH::IObjectStreamIn &ioStream, class_name *&inPointer); \+ linkage prefix bool OSIsType(class_name *, int inArrayDepth, JPH::EOSDataType inDataType, const char *inClassName); \+ linkage prefix bool OSIsType(class_name **, int inArrayDepth, JPH::EOSDataType inDataType, const char *inClassName); \+ linkage prefix void OSWriteData(JPH::IObjectStreamOut &ioStream, const class_name &inInstance); \+ linkage prefix void OSWriteData(JPH::IObjectStreamOut &ioStream, class_name *const &inPointer); \+ linkage prefix void OSWriteDataType(JPH::IObjectStreamOut &ioStream, class_name *); \+ linkage prefix void OSWriteDataType(JPH::IObjectStreamOut &ioStream, class_name **);// JPH_IMPLEMENT_SERIALIZATION_FUNCTIONS#define JPH_IMPLEMENT_SERIALIZATION_FUNCTIONS(class_name) \- bool OSReadData(IObjectStreamIn &ioStream, class_name &inInstance) \+ bool OSReadData(JPH::IObjectStreamIn &ioStream, class_name &inInstance) \{ \return ioStream.ReadClassData(#class_name, (void *)&inInstance); \} \- bool OSReadData(IObjectStreamIn &ioStream, class_name *&inPointer) \+ bool OSReadData(JPH::IObjectStreamIn &ioStream, class_name *&inPointer) \{ \return ioStream.ReadPointerData(JPH_RTTI(class_name), (void **)&inPointer); \} \- bool OSIsType(class_name *, int inArrayDepth, EOSDataType inDataType, const char *inClassName) \+ bool OSIsType(class_name *, int inArrayDepth, JPH::EOSDataType inDataType, const char *inClassName) \{ \- return inArrayDepth == 0 && inDataType == EOSDataType::Instance && strcmp(inClassName, #class_name) == 0; \+ return inArrayDepth == 0 && inDataType == JPH::EOSDataType::Instance && strcmp(inClassName, #class_name) == 0; \} \- bool OSIsType(class_name **, int inArrayDepth, EOSDataType inDataType, const char *inClassName) \+ bool OSIsType(class_name **, int inArrayDepth, JPH::EOSDataType inDataType, const char *inClassName) \{ \- return inArrayDepth == 0 && inDataType == EOSDataType::Pointer && strcmp(inClassName, #class_name) == 0; \+ return inArrayDepth == 0 && inDataType == JPH::EOSDataType::Pointer && strcmp(inClassName, #class_name) == 0; \} \- void OSWriteData(IObjectStreamOut &ioStream, const class_name &inInstance) \+ void OSWriteData(JPH::IObjectStreamOut &ioStream, const class_name &inInstance) \{ \ioStream.WriteClassData(JPH_RTTI(class_name), (void *)&inInstance); \} \- void OSWriteData(IObjectStreamOut &ioStream, class_name *const &inPointer) \+ void OSWriteData(JPH::IObjectStreamOut &ioStream, class_name *const &inPointer) \{ \if (inPointer) \ioStream.WritePointerData(GetRTTI(inPointer), (void *)inPointer); \else \ioStream.WritePointerData(nullptr, nullptr); \} \- void OSWriteDataType(IObjectStreamOut &ioStream, class_name *) \+ void OSWriteDataType(JPH::IObjectStreamOut &ioStream, class_name *) \{ \- ioStream.WriteDataType(EOSDataType::Instance); \+ ioStream.WriteDataType(JPH::EOSDataType::Instance); \ioStream.WriteName(#class_name); \} \- void OSWriteDataType(IObjectStreamOut &ioStream, class_name **) \+ void OSWriteDataType(JPH::IObjectStreamOut &ioStream, class_name **) \{ \- ioStream.WriteDataType(EOSDataType::Pointer); \+ ioStream.WriteDataType(JPH::EOSDataType::Pointer); \ioStream.WriteName(#class_name); \}diff --git a/thirdparty/jolt_physics/Jolt/Physics/Body/Body.cpp b/thirdparty/jolt_physics/Jolt/Physics/Body/Body.cppindex 034f3452863..3cd11a3682f 100644--- a/thirdparty/jolt_physics/Jolt/Physics/Body/Body.cpp+++ b/thirdparty/jolt_physics/Jolt/Physics/Body/Body.cpp@@ -243,7 +243,7 @@ bool Body::ApplyBuoyancyImpulse(float inTotalVolume, float inSubmergedVolume, Veif (relative_center_of_buoyancy_velocity_len_sq > 1.0e-12f){Vec3 local_relative_center_of_buoyancy_velocity = GetRotation().InverseRotate(relative_center_of_buoyancy_velocity);- area = local_relative_center_of_buoyancy_velocity.Abs().Dot(size.Swizzle<SWIZZLE_Y, SWIZZLE_Z, SWIZZLE_X>() * size.Swizzle<SWIZZLE_Z, SWIZZLE_X, SWIZZLE_Y>()) / sqrt(relative_center_of_buoyancy_velocity_len_sq);+ area = local_relative_center_of_buoyancy_velocity.Abs().Dot(size.Swizzle<SWIZZLE_Y, SWIZZLE_Z, SWIZZLE_X>() * size.Swizzle<SWIZZLE_Z, SWIZZLE_X, SWIZZLE_Y>()) / Sqrt(relative_center_of_buoyancy_velocity_len_sq);}// Calculate the impulse@@ -253,7 +253,7 @@ bool Body::ApplyBuoyancyImpulse(float inTotalVolume, float inSubmergedVolume, Vefloat linear_velocity_len_sq = linear_velocity.LengthSq();float drag_delta_linear_velocity_len_sq = (drag_impulse * inverse_mass).LengthSq();if (drag_delta_linear_velocity_len_sq > linear_velocity_len_sq)- drag_impulse *= sqrt(linear_velocity_len_sq / drag_delta_linear_velocity_len_sq);+ drag_impulse *= Sqrt(linear_velocity_len_sq / drag_delta_linear_velocity_len_sq);// Calculate the resulting delta linear velocity due to buoyancy and dragVec3 delta_linear_velocity = (drag_impulse + buoyancy_impulse) * inverse_mass;@@ -271,7 +271,7 @@ bool Body::ApplyBuoyancyImpulse(float inTotalVolume, float inSubmergedVolume, Vefloat angular_velocity_len_sq = angular_velocity.LengthSq();float drag_delta_angular_velocity_len_sq = drag_delta_angular_velocity.LengthSq();if (drag_delta_angular_velocity_len_sq > angular_velocity_len_sq)- drag_delta_angular_velocity *= sqrt(angular_velocity_len_sq / drag_delta_angular_velocity_len_sq);+ drag_delta_angular_velocity *= Sqrt(angular_velocity_len_sq / drag_delta_angular_velocity_len_sq);// Calculate total delta angular velocity due to drag and buoyancyVec3 delta_angular_velocity = drag_delta_angular_velocity + inv_inertia * inRelativeCenterOfBuoyancy.Cross(buoyancy_impulse + drag_impulse);@@ -395,6 +395,46 @@ BodyCreationSettings Body::GetBodyCreationSettings() constreturn result;}+void Body::ApplyBodyCreationSettings(const BodyCreationSettings &inBodyCreationSettings, const BroadPhaseLayerInterface &inBPLInterface)+{+ JPH_ASSERT(IsRigidBody() && !IsInBroadPhase());++ mShape = inBodyCreationSettings.GetShape();+ mUserData = inBodyCreationSettings.mUserData;+ SetFriction(inBodyCreationSettings.mFriction);+ SetRestitution(inBodyCreationSettings.mRestitution);+ mMotionType = inBodyCreationSettings.mMotionType;+ SetIsSensor(inBodyCreationSettings.mIsSensor);+ SetCollideKinematicVsNonDynamic(inBodyCreationSettings.mCollideKinematicVsNonDynamic);+ SetUseManifoldReduction(inBodyCreationSettings.mUseManifoldReduction);+ SetApplyGyroscopicForce(inBodyCreationSettings.mApplyGyroscopicForce);+ SetEnhancedInternalEdgeRemoval(inBodyCreationSettings.mEnhancedInternalEdgeRemoval);+ SetObjectLayerInternal(inBodyCreationSettings.mObjectLayer, inBPLInterface);+ mCollisionGroup = inBodyCreationSettings.mCollisionGroup;++ if (inBodyCreationSettings.HasMassProperties())+ {+ MotionProperties *mp = mMotionProperties;+ JPH_ASSERT(mp != nullptr, "Body was created without MotionProperties, ApplyBodyCreationSettings can't create one!");+ mp->SetLinearDamping(inBodyCreationSettings.mLinearDamping);+ mp->SetAngularDamping(inBodyCreationSettings.mAngularDamping);+ mp->SetMaxLinearVelocity(inBodyCreationSettings.mMaxLinearVelocity);+ mp->SetMaxAngularVelocity(inBodyCreationSettings.mMaxAngularVelocity);+ mp->SetMassProperties(inBodyCreationSettings.mAllowedDOFs, inBodyCreationSettings.GetMassProperties());+ mp->SetLinearVelocity(inBodyCreationSettings.mLinearVelocity); // Needs to happen after setting the max linear/angular velocity and setting allowed DOFs+ mp->SetAngularVelocity(inBodyCreationSettings.mAngularVelocity);+ mp->SetGravityFactor(inBodyCreationSettings.mGravityFactor);+ mp->SetNumVelocityStepsOverride(inBodyCreationSettings.mNumVelocityStepsOverride);+ mp->SetNumPositionStepsOverride(inBodyCreationSettings.mNumPositionStepsOverride);+ mp->mMotionQuality = inBodyCreationSettings.mMotionQuality;+ mp->mAllowSleeping = inBodyCreationSettings.mAllowSleeping;+ JPH_IF_ENABLE_ASSERTS(mp->mCachedBodyType = mBodyType;)+ JPH_IF_ENABLE_ASSERTS(mp->mCachedMotionType = mMotionType;)+ }++ SetPositionAndRotationInternal(inBodyCreationSettings.mPosition, inBodyCreationSettings.mRotation);+}+SoftBodyCreationSettings Body::GetSoftBodyCreationSettings() const{JPH_ASSERT(IsSoftBody());@@ -423,4 +463,32 @@ SoftBodyCreationSettings Body::GetSoftBodyCreationSettings() constreturn result;}+void Body::ApplySoftBodyCreationSettings(const SoftBodyCreationSettings &inSoftBodyCreationSettings, const BroadPhaseLayerInterface &inBPLInterface)+{+ JPH_ASSERT(IsSoftBody() && !IsInBroadPhase());++ mUserData = inSoftBodyCreationSettings.mUserData;+ SetFriction(inSoftBodyCreationSettings.mFriction);+ SetRestitution(inSoftBodyCreationSettings.mRestitution);+ mMotionType = EMotionType::Dynamic;+ SetObjectLayerInternal(inSoftBodyCreationSettings.mObjectLayer, inBPLInterface);+ mCollisionGroup = inSoftBodyCreationSettings.mCollisionGroup;++ SoftBodyMotionProperties *mp = static_cast<SoftBodyMotionProperties *>(mMotionProperties);+ mp->SetLinearDamping(inSoftBodyCreationSettings.mLinearDamping);+ mp->SetAngularDamping(0);+ mp->SetMaxLinearVelocity(inSoftBodyCreationSettings.mMaxLinearVelocity);+ mp->SetMaxAngularVelocity(FLT_MAX);+ mp->SetLinearVelocity(Vec3::sZero());+ mp->SetAngularVelocity(Vec3::sZero());+ mp->SetGravityFactor(inSoftBodyCreationSettings.mGravityFactor);+ mp->mMotionQuality = EMotionQuality::Discrete;+ mp->mAllowSleeping = inSoftBodyCreationSettings.mAllowSleeping;+ JPH_IF_ENABLE_ASSERTS(mp->mCachedBodyType = mBodyType;)+ JPH_IF_ENABLE_ASSERTS(mp->mCachedMotionType = mMotionType;)+ mp->Initialize(inSoftBodyCreationSettings);++ SetPositionAndRotationInternal(inSoftBodyCreationSettings.mPosition, inSoftBodyCreationSettings.mMakeRotationIdentity? Quat::sIdentity() : inSoftBodyCreationSettings.mRotation);+}+JPH_NAMESPACE_ENDdiff --git a/thirdparty/jolt_physics/Jolt/Physics/Body/Body.h b/thirdparty/jolt_physics/Jolt/Physics/Body/Body.hindex fe5249c3b08..3b17513ab48 100644--- a/thirdparty/jolt_physics/Jolt/Physics/Body/Body.h+++ b/thirdparty/jolt_physics/Jolt/Physics/Body/Body.h@@ -150,10 +150,12 @@ public:inline Vec3 GetLinearVelocity() const { return !IsStatic()? mMotionProperties->GetLinearVelocity() : Vec3::sZero(); }/// Set world space linear velocity of the center of mass (unit: m/s).+ /// Note that it is illegal to set a non-zero linear velocity on a sleeping body without waking it up afterwards./// If you want the body to wake up when it is sleeping, use BodyInterface::SetLinearVelocity instead.void SetLinearVelocity(Vec3Arg inLinearVelocity) { JPH_ASSERT(!IsStatic()); mMotionProperties->SetLinearVelocity(inLinearVelocity); }/// Set world space linear velocity of the center of mass, will make sure the value is clamped against the maximum linear velocity.+ /// Note that it is illegal to set a non-zero linear velocity on a sleeping body without waking it up afterwards./// If you want the body to wake up when it is sleeping, use BodyInterface::SetLinearVelocity instead.void SetLinearVelocityClamped(Vec3Arg inLinearVelocity) { JPH_ASSERT(!IsStatic()); mMotionProperties->SetLinearVelocityClamped(inLinearVelocity); }@@ -161,10 +163,12 @@ public:inline Vec3 GetAngularVelocity() const { return !IsStatic()? mMotionProperties->GetAngularVelocity() : Vec3::sZero(); }/// Set world space angular velocity of the center of mass (unit: rad/s).+ /// Note that it is illegal to set a non-zero angular velocity on a sleeping body without waking it up afterwards./// If you want the body to wake up when it is sleeping, use BodyInterface::SetAngularVelocity instead.void SetAngularVelocity(Vec3Arg inAngularVelocity) { JPH_ASSERT(!IsStatic()); mMotionProperties->SetAngularVelocity(inAngularVelocity); }/// Set world space angular velocity of the center of mass, will make sure the value is clamped against the maximum angular velocity.+ /// Note that it is illegal to set a non-zero angular velocity on a sleeping body without waking it up afterwards./// If you want the body to wake up when it is sleeping, use BodyInterface::SetAngularVelocity instead.void SetAngularVelocityClamped(Vec3Arg inAngularVelocity) { JPH_ASSERT(!IsStatic()); mMotionProperties->SetAngularVelocityClamped(inAngularVelocity); }@@ -216,7 +220,8 @@ public:/// If you want the body to wake up when it is sleeping, use BodyInterface::AddAngularImpulse instead.inline void AddAngularImpulse(Vec3Arg inAngularImpulse);- /// Set velocity of body such that it will be positioned at inTargetPosition/Rotation in inDeltaTime seconds.+ /// Set velocity of body such that it will be positioned at inTargetPosition/inTargetRotation in inDeltaTime seconds.+ /// Note that it is illegal to provide a new position/orientation on a sleeping body without waking it up afterwards./// If you want the body to wake up when it is sleeping, use BodyInterface::MoveKinematic instead.void MoveKinematic(RVec3Arg inTargetPosition, QuatArg inTargetRotation, float inDeltaTime);@@ -302,6 +307,18 @@ public:AABox actual_body_bounds = mShape->GetWorldSpaceBounds(GetCenterOfMassTransform(), Vec3::sOne());JPH_ASSERT(actual_body_bounds == mBounds, "Mismatch between cached bounding box and actual bounding box");}++ /// Validates that a body that is sleeping has zero velocity.+ inline void ValidateMotion() const+ {+ if (!IsStatic() && !IsActive())+ {+ // If this fails then you have set a velocity on a body without waking it up.+ // Use BodyInterface::SetLinearVelocity or BodyInterface::SetAngularVelocity to set the velocity and wake up the body at the same time.+ JPH_ASSERT(mMotionProperties->GetLinearVelocity().IsNearZero(), "Sleeping body has non-zero linear velocity!");+ JPH_ASSERT(mMotionProperties->GetAngularVelocity().IsNearZero(), "Sleeping body has non-zero angular velocity!");+ }+ }#endif // JPH_ENABLE_ASSERTS/// Access to the motion properties@@ -322,12 +339,18 @@ public:/// Get the transformed shape of this body, which can be used to do collision detection outside of a body lockinline TransformedShape GetTransformedShape() const { JPH_ASSERT(BodyAccess::sCheckRights(BodyAccess::sPositionAccess(), BodyAccess::EAccess::Read)); return TransformedShape(mPosition, mRotation, mShape, mID); }- /// Debug function to convert a body back to a body creation settings object to be able to save/recreate the body later+ /// Function to convert a body back to a body creation settings object to be able to save/recreate the body later. Can e.g. be used to move a body from one PhysicsSystem to another.BodyCreationSettings GetBodyCreationSettings() const;- /// Debug function to convert a soft body back to a soft body creation settings object to be able to save/recreate the body later+ /// Function to overwrite current body state with inBodyCreationSettings. Can only be done when the body is not in the physics system and cannot add MotionProperties if the body was created without one.+ void ApplyBodyCreationSettings(const BodyCreationSettings &inBodyCreationSettings, const BroadPhaseLayerInterface &inBPLInterface);++ /// Function to convert a soft body back to a body creation settings object to be able to save/recreate the body later. Can e.g. be used to move a body from one PhysicsSystem to another.SoftBodyCreationSettings GetSoftBodyCreationSettings() const;+ /// Function to overwrite current body state with inSoftBodyCreationSettings. Can only be done when the body is not in the physics system and cannot add MotionProperties if the body was created without one.+ void ApplySoftBodyCreationSettings(const SoftBodyCreationSettings &inSoftBodyCreationSettings, const BroadPhaseLayerInterface &inBPLInterface);+/// A dummy body that can be used by constraints to attach a constraint to the world instead of another bodystatic Body sFixedToWorld;@@ -346,6 +369,9 @@ public:inline void AddRotationStep(Vec3Arg inAngularVelocityTimesDeltaTime);inline void SubRotationStep(Vec3Arg inAngularVelocityTimesDeltaTime);+ /// Function to update body's layer (should only be called internally since it also requires updating the broadphase)+ inline void SetObjectLayerInternal(ObjectLayer inLayer, const BroadPhaseLayerInterface &inBPLInterface) { mObjectLayer = inLayer; mBroadPhaseLayer = inBPLInterface.GetBroadPhaseLayer(inLayer); }+/// Flag if body is in the broadphase (should only be called by the BroadPhase)inline void SetInBroadPhaseInternal(bool inInBroadPhase) { if (inInBroadPhase) mFlags.fetch_or(uint8(EFlags::IsInBroadPhase), memory_order_relaxed); else mFlags.fetch_and(uint8(~uint8(EFlags::IsInBroadPhase)), memory_order_relaxed); }diff --git a/thirdparty/jolt_physics/Jolt/Physics/Body/BodyCreationSettings.cpp b/thirdparty/jolt_physics/Jolt/Physics/Body/BodyCreationSettings.cppindex 9b6d3f92c41..ca69445e424 100644--- a/thirdparty/jolt_physics/Jolt/Physics/Body/BodyCreationSettings.cpp+++ b/thirdparty/jolt_physics/Jolt/Physics/Body/BodyCreationSettings.cpp@@ -8,6 +8,7 @@#include <Jolt/ObjectStream/TypeDeclarations.h>#include <Jolt/Core/StreamIn.h>#include <Jolt/Core/StreamOut.h>+#include <Jolt/Core/StreamUtils.h>JPH_NAMESPACE_BEGIN@@ -109,6 +110,41 @@ void BodyCreationSettings::RestoreBinaryState(StreamIn &inStream)mMassPropertiesOverride.RestoreBinaryState(inStream);}+bool BodyCreationSettings::operator == (const BodyCreationSettings &inRHS) const+{+ return mPosition == inRHS.mPosition+ && mRotation == inRHS.mRotation+ && mLinearVelocity == inRHS.mLinearVelocity+ && mAngularVelocity == inRHS.mAngularVelocity+ && mUserData == inRHS.mUserData+ && mObjectLayer == inRHS.mObjectLayer+ && mCollisionGroup == inRHS.mCollisionGroup+ && mMotionType == inRHS.mMotionType+ && mAllowedDOFs == inRHS.mAllowedDOFs+ && mAllowDynamicOrKinematic == inRHS.mAllowDynamicOrKinematic+ && mIsSensor == inRHS.mIsSensor+ && mCollideKinematicVsNonDynamic == inRHS.mCollideKinematicVsNonDynamic+ && mUseManifoldReduction == inRHS.mUseManifoldReduction+ && mApplyGyroscopicForce == inRHS.mApplyGyroscopicForce+ && mMotionQuality == inRHS.mMotionQuality+ && mEnhancedInternalEdgeRemoval == inRHS.mEnhancedInternalEdgeRemoval+ && mAllowSleeping == inRHS.mAllowSleeping+ && mFriction == inRHS.mFriction+ && mRestitution == inRHS.mRestitution+ && mLinearDamping == inRHS.mLinearDamping+ && mAngularDamping == inRHS.mAngularDamping+ && mMaxLinearVelocity == inRHS.mMaxLinearVelocity+ && mMaxAngularVelocity == inRHS.mMaxAngularVelocity+ && mGravityFactor == inRHS.mGravityFactor+ && mNumVelocityStepsOverride == inRHS.mNumVelocityStepsOverride+ && mNumPositionStepsOverride == inRHS.mNumPositionStepsOverride+ && mOverrideMassProperties == inRHS.mOverrideMassProperties+ && mInertiaMultiplier == inRHS.mInertiaMultiplier+ && mMassPropertiesOverride == inRHS.mMassPropertiesOverride+ && mShape == inRHS.mShape+ && mShapePtr == inRHS.mShapePtr;+}+Shape::ShapeResult BodyCreationSettings::ConvertShapeSettings(){// If we already have a shape, return itdiff --git a/thirdparty/jolt_physics/Jolt/Physics/Body/BodyCreationSettings.h b/thirdparty/jolt_physics/Jolt/Physics/Body/BodyCreationSettings.hindex 898b8e40e75..c4f2ad78e44 100644--- a/thirdparty/jolt_physics/Jolt/Physics/Body/BodyCreationSettings.h+++ b/thirdparty/jolt_physics/Jolt/Physics/Body/BodyCreationSettings.h@@ -11,7 +11,7 @@#include <Jolt/Physics/Body/MotionQuality.h>#include <Jolt/Physics/Body/AllowedDOFs.h>#include <Jolt/ObjectStream/SerializableObject.h>-#include <Jolt/Core/StreamUtils.h>+#include <Jolt/Core/ObjectToIDMap.h>JPH_NAMESPACE_BEGIN@@ -37,6 +37,10 @@ public:BodyCreationSettings(const ShapeSettings *inShape, RVec3Arg inPosition, QuatArg inRotation, EMotionType inMotionType, ObjectLayer inObjectLayer) : mPosition(inPosition), mRotation(inRotation), mObjectLayer(inObjectLayer), mMotionType(inMotionType), mShape(inShape) { }BodyCreationSettings(const Shape *inShape, RVec3Arg inPosition, QuatArg inRotation, EMotionType inMotionType, ObjectLayer inObjectLayer) : mPosition(inPosition), mRotation(inRotation), mObjectLayer(inObjectLayer), mMotionType(inMotionType), mShapePtr(inShape) { }+ /// Test if two BodyCreationSettings are equal+ bool operator == (const BodyCreationSettings &inRHS) const;+ bool operator != (const BodyCreationSettings &inRHS) const { return !(*this == inRHS); }+/// Access to the shape settings object. This contains serializable (non-runtime optimized) information about the Shape.const ShapeSettings * GetShapeSettings() const { return mShape; }void SetShapeSettings(const ShapeSettings *inShape) { mShape = inShape; mShapePtr = nullptr; }diff --git a/thirdparty/jolt_physics/Jolt/Physics/Body/BodyInterface.cpp b/thirdparty/jolt_physics/Jolt/Physics/Body/BodyInterface.cppindex d30bfe57975..4633d640a2c 100644--- a/thirdparty/jolt_physics/Jolt/Physics/Body/BodyInterface.cpp+++ b/thirdparty/jolt_physics/Jolt/Physics/Body/BodyInterface.cpp@@ -274,8 +274,8 @@ TwoBodyConstraint *BodyInterface::CreateConstraint(const TwoBodyConstraintSettinBody *body1 = lock.GetBody(0);Body *body2 = lock.GetBody(1);- JPH_ASSERT(body1 != body2);JPH_ASSERT(body1 != nullptr || body2 != nullptr);+ JPH_ASSERT(body1 != body2);return inSettings->Create(body1 != nullptr? *body1 : Body::sFixedToWorld, body2 != nullptr? *body2 : Body::sFixedToWorld);}@@ -365,7 +365,7 @@ void BodyInterface::SetObjectLayer(const BodyID &inBodyID, ObjectLayer inLayer)if (body.GetObjectLayer() != inLayer){// Update the layer on the body- mBodyManager->SetBodyObjectLayerInternal(body, inLayer);+ body.SetObjectLayerInternal(inLayer, mBodyManager->GetBroadPhaseLayerInterface());// Notify broadphase of changeif (body.IsInBroadPhase())@@ -967,34 +967,34 @@ float BodyInterface::GetGravityFactor(const BodyID &inBodyID) constvoid BodyInterface::SetMaxLinearVelocity(const BodyID &inBodyID, float inLinearVelocity){- BodyLockWrite lock(*mBodyLockInterface, inBodyID);- if (lock.Succeeded() && lock.GetBody().GetMotionPropertiesUnchecked() != nullptr)- lock.GetBody().GetMotionPropertiesUnchecked()->SetMaxLinearVelocity(inLinearVelocity);+ BodyLockWrite lock(*mBodyLockInterface, inBodyID);+ if (lock.Succeeded() && lock.GetBody().GetMotionPropertiesUnchecked() != nullptr)+ lock.GetBody().GetMotionPropertiesUnchecked()->SetMaxLinearVelocity(inLinearVelocity);}float BodyInterface::GetMaxLinearVelocity(const BodyID &inBodyID) const{- BodyLockRead lock(*mBodyLockInterface, inBodyID);- if (lock.Succeeded() && lock.GetBody().GetMotionPropertiesUnchecked() != nullptr)- return lock.GetBody().GetMotionPropertiesUnchecked()->GetMaxLinearVelocity();- else- return 500.0f;+ BodyLockRead lock(*mBodyLockInterface, inBodyID);+ if (lock.Succeeded() && lock.GetBody().GetMotionPropertiesUnchecked() != nullptr)+ return lock.GetBody().GetMotionPropertiesUnchecked()->GetMaxLinearVelocity();+ else+ return 500.0f;}void BodyInterface::SetMaxAngularVelocity(const BodyID &inBodyID, float inAngularVelocity){- BodyLockWrite lock(*mBodyLockInterface, inBodyID);- if (lock.Succeeded() && lock.GetBody().GetMotionPropertiesUnchecked() != nullptr)- lock.GetBody().GetMotionPropertiesUnchecked()->SetMaxAngularVelocity(inAngularVelocity);+ BodyLockWrite lock(*mBodyLockInterface, inBodyID);+ if (lock.Succeeded() && lock.GetBody().GetMotionPropertiesUnchecked() != nullptr)+ lock.GetBody().GetMotionPropertiesUnchecked()->SetMaxAngularVelocity(inAngularVelocity);}float BodyInterface::GetMaxAngularVelocity(const BodyID &inBodyID) const{- BodyLockRead lock(*mBodyLockInterface, inBodyID);- if (lock.Succeeded() && lock.GetBody().GetMotionPropertiesUnchecked() != nullptr)- return lock.GetBody().GetMotionPropertiesUnchecked()->GetMaxAngularVelocity();- else- return 0.25f * JPH_PI * 60.0f;+ BodyLockRead lock(*mBodyLockInterface, inBodyID);+ if (lock.Succeeded() && lock.GetBody().GetMotionPropertiesUnchecked() != nullptr)+ return lock.GetBody().GetMotionPropertiesUnchecked()->GetMaxAngularVelocity();+ else+ return 0.25f * JPH_PI * 60.0f;}void BodyInterface::SetUseManifoldReduction(const BodyID &inBodyID, bool inUseReduction)diff --git a/thirdparty/jolt_physics/Jolt/Physics/Body/BodyInterface.h b/thirdparty/jolt_physics/Jolt/Physics/Body/BodyInterface.hindex f7c3032c83e..3883deab1ae 100644--- a/thirdparty/jolt_physics/Jolt/Physics/Body/BodyInterface.h+++ b/thirdparty/jolt_physics/Jolt/Physics/Body/BodyInterface.h@@ -269,17 +269,17 @@ public:float GetGravityFactor(const BodyID &inBodyID) const; ///< @see MotionProperties::GetGravityFactor///@}- ///@name Max linear velocity- ///@{- void SetMaxLinearVelocity(const BodyID &inBodyID, float inLinearVelocity); ///< @see MotionProperties::SetMaxLinearVelocity- float GetMaxLinearVelocity(const BodyID &inBodyID) const; ///< @see MotionProperties::GetMaxLinearVelocity- ///@}-- ///@name Max angular velocity- ///@{- void SetMaxAngularVelocity(const BodyID &inBodyID, float inAngularVelocity); ///< @see MotionProperties::SetMaxAngularVelocity- float GetMaxAngularVelocity(const BodyID &inBodyID) const; ///< @see MotionProperties::GetMaxAngularVelocity- ///@}+ ///@name Max linear velocity+ ///@{+ void SetMaxLinearVelocity(const BodyID &inBodyID, float inLinearVelocity); ///< @see MotionProperties::SetMaxLinearVelocity+ float GetMaxLinearVelocity(const BodyID &inBodyID) const; ///< @see MotionProperties::GetMaxLinearVelocity+ ///@}++ ///@name Max angular velocity+ ///@{+ void SetMaxAngularVelocity(const BodyID &inBodyID, float inAngularVelocity); ///< @see MotionProperties::SetMaxAngularVelocity+ float GetMaxAngularVelocity(const BodyID &inBodyID) const; ///< @see MotionProperties::GetMaxAngularVelocity+ ///@}///@name Manifold reduction///@{diff --git a/thirdparty/jolt_physics/Jolt/Physics/Body/BodyManager.cpp b/thirdparty/jolt_physics/Jolt/Physics/Body/BodyManager.cppindex f6c0584e199..eee9d687553 100644--- a/thirdparty/jolt_physics/Jolt/Physics/Body/BodyManager.cpp+++ b/thirdparty/jolt_physics/Jolt/Physics/Body/BodyManager.cpp@@ -198,46 +198,7 @@ Body *BodyManager::AllocateBody(const BodyCreationSettings &inBodyCreationSettinbody = new Body;}body->mBodyType = EBodyType::RigidBody;- body->mShape = inBodyCreationSettings.GetShape();- body->mUserData = inBodyCreationSettings.mUserData;- body->SetFriction(inBodyCreationSettings.mFriction);- body->SetRestitution(inBodyCreationSettings.mRestitution);- body->mMotionType = inBodyCreationSettings.mMotionType;- if (inBodyCreationSettings.mIsSensor)- body->SetIsSensor(true);- if (inBodyCreationSettings.mCollideKinematicVsNonDynamic)- body->SetCollideKinematicVsNonDynamic(true);- if (inBodyCreationSettings.mUseManifoldReduction)- body->SetUseManifoldReduction(true);- if (inBodyCreationSettings.mApplyGyroscopicForce)- body->SetApplyGyroscopicForce(true);- if (inBodyCreationSettings.mEnhancedInternalEdgeRemoval)- body->SetEnhancedInternalEdgeRemoval(true);- SetBodyObjectLayerInternal(*body, inBodyCreationSettings.mObjectLayer);- body->mObjectLayer = inBodyCreationSettings.mObjectLayer;- body->mCollisionGroup = inBodyCreationSettings.mCollisionGroup;-- if (inBodyCreationSettings.HasMassProperties())- {- MotionProperties *mp = body->mMotionProperties;- mp->SetLinearDamping(inBodyCreationSettings.mLinearDamping);- mp->SetAngularDamping(inBodyCreationSettings.mAngularDamping);- mp->SetMaxLinearVelocity(inBodyCreationSettings.mMaxLinearVelocity);- mp->SetMaxAngularVelocity(inBodyCreationSettings.mMaxAngularVelocity);- mp->SetMassProperties(inBodyCreationSettings.mAllowedDOFs, inBodyCreationSettings.GetMassProperties());- mp->SetLinearVelocity(inBodyCreationSettings.mLinearVelocity); // Needs to happen after setting the max linear/angular velocity and setting allowed DOFs- mp->SetAngularVelocity(inBodyCreationSettings.mAngularVelocity);- mp->SetGravityFactor(inBodyCreationSettings.mGravityFactor);- mp->SetNumVelocityStepsOverride(inBodyCreationSettings.mNumVelocityStepsOverride);- mp->SetNumPositionStepsOverride(inBodyCreationSettings.mNumPositionStepsOverride);- mp->mMotionQuality = inBodyCreationSettings.mMotionQuality;- mp->mAllowSleeping = inBodyCreationSettings.mAllowSleeping;- JPH_IF_ENABLE_ASSERTS(mp->mCachedBodyType = body->mBodyType;)- JPH_IF_ENABLE_ASSERTS(mp->mCachedMotionType = body->mMotionType;)- }-- // Position body- body->SetPositionAndRotationInternal(inBodyCreationSettings.mPosition, inBodyCreationSettings.mRotation);+ body->ApplyBodyCreationSettings(inBodyCreationSettings, *mBroadPhaseLayerInterface);return body;}@@ -254,27 +215,7 @@ Body *BodyManager::AllocateSoftBody(const SoftBodyCreationSettings &inSoftBodyCrbody->mBodyType = EBodyType::SoftBody;body->mMotionProperties = mp;body->mShape = shape;- body->mUserData = inSoftBodyCreationSettings.mUserData;- body->SetFriction(inSoftBodyCreationSettings.mFriction);- body->SetRestitution(inSoftBodyCreationSettings.mRestitution);- body->mMotionType = EMotionType::Dynamic;- SetBodyObjectLayerInternal(*body, inSoftBodyCreationSettings.mObjectLayer);- body->mObjectLayer = inSoftBodyCreationSettings.mObjectLayer;- body->mCollisionGroup = inSoftBodyCreationSettings.mCollisionGroup;- mp->SetLinearDamping(inSoftBodyCreationSettings.mLinearDamping);- mp->SetAngularDamping(0);- mp->SetMaxLinearVelocity(inSoftBodyCreationSettings.mMaxLinearVelocity);- mp->SetMaxAngularVelocity(FLT_MAX);- mp->SetLinearVelocity(Vec3::sZero());- mp->SetAngularVelocity(Vec3::sZero());- mp->SetGravityFactor(inSoftBodyCreationSettings.mGravityFactor);- mp->mMotionQuality = EMotionQuality::Discrete;- mp->mAllowSleeping = inSoftBodyCreationSettings.mAllowSleeping;- JPH_IF_ENABLE_ASSERTS(mp->mCachedBodyType = body->mBodyType;)- JPH_IF_ENABLE_ASSERTS(mp->mCachedMotionType = body->mMotionType;)- mp->Initialize(inSoftBodyCreationSettings);-- body->SetPositionAndRotationInternal(inSoftBodyCreationSettings.mPosition, inSoftBodyCreationSettings.mMakeRotationIdentity? Quat::sIdentity() : inSoftBodyCreationSettings.mRotation);+ body->ApplySoftBodyCreationSettings(inSoftBodyCreationSettings, *mBroadPhaseLayerInterface);return body;}@@ -1189,7 +1130,7 @@ void BodyManager::ReportSimulationStats(){UniqueLock lock(mActiveBodiesMutex JPH_IF_ENABLE_ASSERTS(, this, EPhysicsLockTypes::ActiveBodiesList));- Trace("BodyID, IslandIndex, LargeIsland, BroadPhase (us), NarrowPhase (us), VelocityConstraint (us), PositionConstraint (us), UpdateBounds (us), CCD (us), NumContactConstraints, NumVelocitySteps, NumPositionSteps");+ Trace("BodyID, IslandIndex, LargeIsland, BroadPhase (us), NarrowPhase (us), VelocityConstraint (us), PositionConstraint (us), UpdateBounds (us), CCD (us), NumContactConstraints, NumCollisionSteps, NumVelocitySteps, NumPositionSteps");double us_per_tick = 1000000.0 / Profiler::sInstance->GetProcessorTicksPerSecond();@@ -1199,7 +1140,7 @@ void BodyManager::ReportSimulationStats()const Body *body = mBodies[id->GetIndex()];const MotionProperties *mp = body->mMotionProperties;const MotionProperties::SimulationStats &stats = mp->GetSimulationStats();- Trace("%u, %u, %s, %.2f, %.2f, %.2f, %.2f, %.2f, %.2f, %u, %u, %u",+ Trace("%u, %u, %s, %.2f, %.2f, %.2f, %.2f, %.2f, %.2f, %u, %u, %u, %u",body->GetID().GetIndex(),mp->GetIslandIndexInternal(),stats.mIsLargeIsland? "True" : "False",@@ -1210,6 +1151,7 @@ void BodyManager::ReportSimulationStats()double(stats.mUpdateBoundsTicks) * us_per_tick,double(stats.mCCDTicks) * us_per_tick,stats.mNumContactConstraints.load(memory_order_relaxed),+ stats.mNumCollisionSteps,stats.mNumVelocitySteps,stats.mNumPositionSteps);}diff --git a/thirdparty/jolt_physics/Jolt/Physics/Body/BodyManager.h b/thirdparty/jolt_physics/Jolt/Physics/Body/BodyManager.hindex 9b1899843ae..61599d658f8 100644--- a/thirdparty/jolt_physics/Jolt/Physics/Body/BodyManager.h+++ b/thirdparty/jolt_physics/Jolt/Physics/Body/BodyManager.h@@ -197,15 +197,15 @@ public:/// Unlock all bodies. This should only be done during PhysicsSystem::Update().void UnlockAllBodies() const;- /// Function to update body's layer (should only be called by the BodyInterface since it also requires updating the broadphase)- inline void SetBodyObjectLayerInternal(Body &ioBody, ObjectLayer inLayer) const { ioBody.mObjectLayer = inLayer; ioBody.mBroadPhaseLayer = mBroadPhaseLayerInterface->GetBroadPhaseLayer(inLayer); }-/// Set the Body::EFlags::InvalidateContactCache flag for the specified body. This means that the collision cache is invalid for any body pair involving that body until the next physics step.void InvalidateContactCacheForBody(Body &ioBody);/// Reset the Body::EFlags::InvalidateContactCache flag for all bodies. All contact pairs in the contact cache will now by valid again.void ValidateContactCacheForAllBodies();+ /// Return the BroadPhaseLayerInterface that this class has been initialized with+ const BroadPhaseLayerInterface &GetBroadPhaseLayerInterface() const { return *mBroadPhaseLayerInterface; }+/// Saving state for replayvoid SaveState(StateRecorder &inStream, const StateRecorderFilter *inFilter) const;diff --git a/thirdparty/jolt_physics/Jolt/Physics/Body/MassProperties.cpp b/thirdparty/jolt_physics/Jolt/Physics/Body/MassProperties.cppindex 91df6b0df3a..30455bf2f77 100644--- a/thirdparty/jolt_physics/Jolt/Physics/Body/MassProperties.cpp+++ b/thirdparty/jolt_physics/Jolt/Physics/Body/MassProperties.cpp@@ -97,7 +97,7 @@ Vec3 MassProperties::sGetEquivalentSolidBoxSize(float inMass, Vec3Arg inInertiaD// mass / 12 * [size_y^2 + size_z^2, size_x^2 + size_z^2, size_x^2 + size_y^2]// Solving for size_x, size_y and size_y (diagonal and mass are known):Vec3 diagonal = inInertiaDiagonal * (12.0f / inMass);- return Vec3(sqrt(0.5f * (-diagonal[0] + diagonal[1] + diagonal[2])), sqrt(0.5f * (diagonal[0] - diagonal[1] + diagonal[2])), sqrt(0.5f * (diagonal[0] + diagonal[1] - diagonal[2])));+ return Vec3(Sqrt(0.5f * (-diagonal[0] + diagonal[1] + diagonal[2])), Sqrt(0.5f * (diagonal[0] - diagonal[1] + diagonal[2])), Sqrt(0.5f * (diagonal[0] + diagonal[1] - diagonal[2])));}void MassProperties::Scale(Vec3Arg inScale)diff --git a/thirdparty/jolt_physics/Jolt/Physics/Body/MassProperties.h b/thirdparty/jolt_physics/Jolt/Physics/Body/MassProperties.hindex c2bfbffb2e1..ad18455ee25 100644--- a/thirdparty/jolt_physics/Jolt/Physics/Body/MassProperties.h+++ b/thirdparty/jolt_physics/Jolt/Physics/Body/MassProperties.h@@ -17,6 +17,17 @@ class JPH_EXPORT MassPropertiesJPH_DECLARE_SERIALIZABLE_NON_VIRTUAL(JPH_EXPORT, MassProperties)public:+ /// Test if two MassProperties are equal+ bool operator == (const MassProperties &inRHS) const+ {+ return mMass == inRHS.mMass && mInertia == inRHS.mInertia;+ }++ bool operator != (const MassProperties &inRHS) const+ {+ return !(*this == inRHS);+ }+/// Using eigendecomposition, decompose the inertia tensor into a diagonal matrix D and a right-handed rotation matrix R so that the inertia tensor is \f$R \: D \: R^{-1}\f$./// @see https://en.wikipedia.org/wiki/Moment_of_inertia section 'Principal axes'/// @param outRotation The rotation matrix Rdiff --git a/thirdparty/jolt_physics/Jolt/Physics/Body/MotionProperties.h b/thirdparty/jolt_physics/Jolt/Physics/Body/MotionProperties.hindex 15d19f0008e..55280a440ca 100644--- a/thirdparty/jolt_physics/Jolt/Physics/Body/MotionProperties.h+++ b/thirdparty/jolt_physics/Jolt/Physics/Body/MotionProperties.h@@ -42,22 +42,32 @@ public:/// Get world space linear velocity of the center of massinline Vec3 GetLinearVelocity() const { JPH_ASSERT(BodyAccess::sCheckRights(BodyAccess::sVelocityAccess(), BodyAccess::EAccess::Read)); return mLinearVelocity; }- /// Set world space linear velocity of the center of mass+ /// Set world space linear velocity of the center of mass.+ /// Note that it is illegal to set a non-zero linear velocity on a sleeping body without waking it up afterwards.+ /// If you want the body to wake up when it is sleeping, use BodyInterface::SetLinearVelocity instead.void SetLinearVelocity(Vec3Arg inLinearVelocity) { JPH_ASSERT(BodyAccess::sCheckRights(BodyAccess::sVelocityAccess(), BodyAccess::EAccess::ReadWrite)); JPH_ASSERT(inLinearVelocity.Length() <= mMaxLinearVelocity); mLinearVelocity = LockTranslation(inLinearVelocity); }- /// Set world space linear velocity of the center of mass, will make sure the value is clamped against the maximum linear velocity+ /// Set world space linear velocity of the center of mass, will make sure the value is clamped against the maximum linear velocity.+ /// Note that it is illegal to set a non-zero linear velocity on a sleeping body without waking it up afterwards.+ /// If you want the body to wake up when it is sleeping, use BodyInterface::SetLinearVelocity instead.void SetLinearVelocityClamped(Vec3Arg inLinearVelocity) { mLinearVelocity = LockTranslation(inLinearVelocity); ClampLinearVelocity(); }/// Get world space angular velocity of the center of massinline Vec3 GetAngularVelocity() const { JPH_ASSERT(BodyAccess::sCheckRights(BodyAccess::sVelocityAccess(), BodyAccess::EAccess::Read)); return mAngularVelocity; }- /// Set world space angular velocity of the center of mass+ /// Set world space angular velocity of the center of mass.+ /// Note that it is illegal to set a non-zero angular velocity on a sleeping body without waking it up afterwards.+ /// If you want the body to wake up when it is sleeping, use BodyInterface::SetAngularVelocity instead.void SetAngularVelocity(Vec3Arg inAngularVelocity) { JPH_ASSERT(BodyAccess::sCheckRights(BodyAccess::sVelocityAccess(), BodyAccess::EAccess::ReadWrite)); JPH_ASSERT(inAngularVelocity.Length() <= mMaxAngularVelocity); mAngularVelocity = LockAngular(inAngularVelocity); }- /// Set world space angular velocity of the center of mass, will make sure the value is clamped against the maximum angular velocity+ /// Set world space angular velocity of the center of mass, will make sure the value is clamped against the maximum angular velocity.+ /// Note that it is illegal to set a non-zero angular velocity on a sleeping body without waking it up afterwards.+ /// If you want the body to wake up when it is sleeping, use BodyInterface::SetAngularVelocity instead.void SetAngularVelocityClamped(Vec3Arg inAngularVelocity) { mAngularVelocity = LockAngular(inAngularVelocity); ClampAngularVelocity(); }/// Set velocity of body such that it will be rotate/translate by inDeltaPosition/Rotation in inDeltaTime seconds.+ /// Note that it is illegal to provide non-zero delta position/rotation on a sleeping body without waking it up afterwards.+ /// If you want the body to wake up when it is sleeping, use BodyInterface::MoveKinematic instead.inline void MoveKinematic(Vec3Arg inDeltaPosition, QuatArg inDeltaRotation, float inDeltaTime);///@name Velocity limits@@ -190,7 +200,7 @@ public:/// Stats for this body. These are average for the simulation island the body was part of.struct SimulationStats{- void Reset() { mBroadPhaseTicks = 0; mNarrowPhaseTicks.store(0, memory_order_relaxed); mVelocityConstraintTicks = 0; mPositionConstraintTicks = 0; mUpdateBoundsTicks = 0; mCCDTicks.store(0, memory_order_relaxed); mNumContactConstraints.store(0, memory_order_relaxed); mNumVelocitySteps = 0; mNumPositionSteps = 0; mIsLargeIsland = false; }+ void Reset() { mBroadPhaseTicks = 0; mNarrowPhaseTicks.store(0, memory_order_relaxed); mVelocityConstraintTicks = 0; mPositionConstraintTicks = 0; mUpdateBoundsTicks = 0; mCCDTicks.store(0, memory_order_relaxed); mNumContactConstraints.store(0, memory_order_relaxed); mNumCollisionSteps = 0; mNumVelocitySteps = 0; mNumPositionSteps = 0; mIsLargeIsland = false; }uint64 mBroadPhaseTicks = 0; ///< Number of processor ticks spent doing broad phase collision detectionatomic<uint64> mNarrowPhaseTicks = 0; ///< Number of ticks spent doing narrow phase collision detection@@ -199,6 +209,7 @@ public:uint64 mUpdateBoundsTicks = 0; ///< Number of ticks spent updating the broadphase and checking if the body should go to sleepatomic<uint64> mCCDTicks = 0; ///< Number of ticks spent doing CCDatomic<uint32> mNumContactConstraints = 0; ///< Number of contact constraints created for this body+ uint8 mNumCollisionSteps = 0; ///< Number of collision steps this body was active (see PhysicsSystem::Update(..., inCollisionSteps, ...)). All other properties are aggregated over multiple steps, so if you want e.g. the number of contact constraints per step you need to divide by this number.uint8 mNumVelocitySteps = 0; ///< Number of velocity iterations performeduint8 mNumPositionSteps = 0; ///< Number of position iterations performedbool mIsLargeIsland = false; ///< If this body was part of a large island@@ -214,10 +225,27 @@ public:///@name Update linear and angular velocity (used during constraint solving)///@{- inline void AddLinearVelocityStep(Vec3Arg inLinearVelocityChange) { JPH_DET_LOG("AddLinearVelocityStep: " << inLinearVelocityChange); JPH_ASSERT(BodyAccess::sCheckRights(BodyAccess::sVelocityAccess(), BodyAccess::EAccess::ReadWrite)); mLinearVelocity = LockTranslation(mLinearVelocity + inLinearVelocityChange); JPH_ASSERT(!mLinearVelocity.IsNaN()); }- inline void SubLinearVelocityStep(Vec3Arg inLinearVelocityChange) { JPH_DET_LOG("SubLinearVelocityStep: " << inLinearVelocityChange); JPH_ASSERT(BodyAccess::sCheckRights(BodyAccess::sVelocityAccess(), BodyAccess::EAccess::ReadWrite)); mLinearVelocity = LockTranslation(mLinearVelocity - inLinearVelocityChange); JPH_ASSERT(!mLinearVelocity.IsNaN()); }- inline void AddAngularVelocityStep(Vec3Arg inAngularVelocityChange) { JPH_DET_LOG("AddAngularVelocityStep: " << inAngularVelocityChange); JPH_ASSERT(BodyAccess::sCheckRights(BodyAccess::sVelocityAccess(), BodyAccess::EAccess::ReadWrite)); mAngularVelocity += inAngularVelocityChange; JPH_ASSERT(!mAngularVelocity.IsNaN()); }- inline void SubAngularVelocityStep(Vec3Arg inAngularVelocityChange) { JPH_DET_LOG("SubAngularVelocityStep: " << inAngularVelocityChange); JPH_ASSERT(BodyAccess::sCheckRights(BodyAccess::sVelocityAccess(), BodyAccess::EAccess::ReadWrite)); mAngularVelocity -= inAngularVelocityChange; JPH_ASSERT(!mAngularVelocity.IsNaN()); }+ inline void ApplyLinearVelocityStep(Vec3Arg inLinearVelocity)+ {+ JPH_DET_LOG("ApplyLinearVelocityStep: " << inLinearVelocity);+ JPH_ASSERT(BodyAccess::sCheckRights(BodyAccess::sVelocityAccess(), BodyAccess::EAccess::ReadWrite));+ JPH_ASSERT(mCachedMotionType == EMotionType::Dynamic);+ JPH_ASSERT(!inLinearVelocity.IsNaN());+ mLinearVelocity = LockTranslation(inLinearVelocity);+ }+ inline void AddLinearVelocityStep(Vec3Arg inLinearVelocityChange) { ApplyLinearVelocityStep(mLinearVelocity + inLinearVelocityChange); }+ inline void SubLinearVelocityStep(Vec3Arg inLinearVelocityChange) { ApplyLinearVelocityStep(mLinearVelocity - inLinearVelocityChange); }++ inline void ApplyAngularVelocityStep(Vec3Arg inAngularVelocity)+ {+ JPH_DET_LOG("ApplyAngularVelocityStep: " << inAngularVelocity);+ JPH_ASSERT(BodyAccess::sCheckRights(BodyAccess::sVelocityAccess(), BodyAccess::EAccess::ReadWrite));+ JPH_ASSERT(mCachedMotionType == EMotionType::Dynamic);+ JPH_ASSERT(!inAngularVelocity.IsNaN());+ mAngularVelocity = inAngularVelocity;+ }+ inline void AddAngularVelocityStep(Vec3Arg inAngularVelocityChange) { ApplyAngularVelocityStep(mAngularVelocity + inAngularVelocityChange); }+ inline void SubAngularVelocityStep(Vec3Arg inAngularVelocityChange) { ApplyAngularVelocityStep(mAngularVelocity - inAngularVelocityChange); }///@}/// Apply the gyroscopic force (aka Dzhanibekov effect, see https://en.wikipedia.org/wiki/Tennis_racket_theorem)diff --git a/thirdparty/jolt_physics/Jolt/Physics/Body/MotionProperties.inl b/thirdparty/jolt_physics/Jolt/Physics/Body/MotionProperties.inlindex e6caae61f51..5b6abc3f3a7 100644--- a/thirdparty/jolt_physics/Jolt/Physics/Body/MotionProperties.inl+++ b/thirdparty/jolt_physics/Jolt/Physics/Body/MotionProperties.inl@@ -27,7 +27,7 @@ void MotionProperties::ClampLinearVelocity()float len_sq = mLinearVelocity.LengthSq();JPH_ASSERT(isfinite(len_sq));if (len_sq > Square(mMaxLinearVelocity))- mLinearVelocity *= mMaxLinearVelocity / sqrt(len_sq);+ mLinearVelocity *= mMaxLinearVelocity / Sqrt(len_sq);}void MotionProperties::ClampAngularVelocity()@@ -37,7 +37,7 @@ void MotionProperties::ClampAngularVelocity()float len_sq = mAngularVelocity.LengthSq();JPH_ASSERT(isfinite(len_sq));if (len_sq > Square(mMaxAngularVelocity))- mAngularVelocity *= mMaxAngularVelocity / sqrt(len_sq);+ mAngularVelocity *= mMaxAngularVelocity / Sqrt(len_sq);}inline Mat44 MotionProperties::GetLocalSpaceInverseInertiaUnchecked() const@@ -118,7 +118,7 @@ void MotionProperties::ApplyGyroscopicForceInternal(QuatArg inBodyRotation, floa// to avoid introducing energy into the system due to the Euler stepVec3 new_local_momentum = local_momentum - inDeltaTime * local_angular_velocity.Cross(local_momentum);float new_local_momentum_len_sq = new_local_momentum.LengthSq();- new_local_momentum = new_local_momentum_len_sq > 0.0f? new_local_momentum * sqrt(local_momentum.LengthSq() / new_local_momentum_len_sq) : Vec3::sZero();+ new_local_momentum = new_local_momentum_len_sq > 0.0f? new_local_momentum * Sqrt(local_momentum.LengthSq() / new_local_momentum_len_sq) : Vec3::sZero();// Convert back to world space angular velocitymAngularVelocity = inertia_space_to_world_space * (mInvInertiaDiagonal * new_local_momentum);diff --git a/thirdparty/jolt_physics/Jolt/Physics/Character/CharacterBase.h b/thirdparty/jolt_physics/Jolt/Physics/Character/CharacterBase.hindex ce938eb6d4d..d258a86f6fa 100644--- a/thirdparty/jolt_physics/Jolt/Physics/Character/CharacterBase.h+++ b/thirdparty/jolt_physics/Jolt/Physics/Character/CharacterBase.h@@ -69,6 +69,10 @@ public:void SetUp(Vec3Arg inUp) { mUp = inUp; }Vec3 GetUp() const { return mUp; }+ // Every contact behind this plane can support the character+ const Plane & GetSupportingVolume() const { return mSupportingVolume; }+ void SetSupportingVolume(const Plane &inPlane) { mSupportingVolume = inPlane; }+/// Check if the normal of the ground surface is too steep to walk onbool IsSlopeTooSteep(Vec3Arg inNormal) const{diff --git a/thirdparty/jolt_physics/Jolt/Physics/Character/CharacterVirtual.cpp b/thirdparty/jolt_physics/Jolt/Physics/Character/CharacterVirtual.cppindex b7029d2d905..8b7644e44c0 100644--- a/thirdparty/jolt_physics/Jolt/Physics/Character/CharacterVirtual.cpp+++ b/thirdparty/jolt_physics/Jolt/Physics/Character/CharacterVirtual.cpp@@ -80,7 +80,10 @@ void CharacterVsCharacterCollisionSimple::CastCharacter(const CharacterVirtual *// Get world space bounds of the character in the form of center and extentVec3 origin = shape_cast.mShapeWorldBounds.GetCenter();- Vec3 extents = shape_cast.mShapeWorldBounds.GetExtent();+ Vec3 extents = shape_cast.mShapeWorldBounds.GetExtent() + Vec3::sReplicate(inShapeCastSettings.mExtraConvexRadius);++ // Create a copy of the settings so we can modify it for each character we test against+ ShapeCastSettings cast_settings = inShapeCastSettings;// Iterate over all charactersfor (const CharacterVirtual *c : mCharacters)@@ -90,18 +93,21 @@ void CharacterVsCharacterCollisionSimple::CastCharacter(const CharacterVirtual *// Make shape 2 relative to inBaseOffsetMat44 transform2 = c->GetCenterOfMassTransform().PostTranslated(-inBaseOffset).ToMat44();+ // We need to add the padding of character 2 so that we will detect collision with its outer shell+ cast_settings.mExtraConvexRadius = inShapeCastSettings.mExtraConvexRadius + c->GetCharacterPadding();+// Sweep bounding box of the character against the bounding box of the other character to see if they can collideconst Shape *shape2 = c->GetShape();AABox bounds2 = shape2->GetWorldSpaceBounds(transform2, Vec3::sOne());- bounds2.ExpandBy(extents);+ bounds2.ExpandBy(extents + Vec3::sReplicate(c->GetCharacterPadding()));if (!RayAABoxHits(origin, inDirection, bounds2.mMin, bounds2.mMax))continue;// Collector needs to know which character we're colliding withioCollector.SetUserData(reinterpret_cast<uint64>(c));- // Note that this collides against the character's shape without padding, this will be corrected for in CharacterVirtual::GetFirstContactForSweep- CollisionDispatch::sCastShapeVsShapeWorldSpace(shape_cast, inShapeCastSettings, shape2, Vec3::sOne(), { }, transform2, SubShapeIDCreator(), SubShapeIDCreator(), ioCollector);+ // Note that this collides against the character's shape without padding, this will be corrected for in CharacterVirtual::ValidateMovement+ CollisionDispatch::sCastShapeVsShapeWorldSpace(shape_cast, cast_settings, shape2, Vec3::sOne(), { }, transform2, SubShapeIDCreator(), SubShapeIDCreator(), ioCollector);}// Reset the user data@@ -194,7 +200,7 @@ Vec3 CharacterVirtual::CalculateCharacterGroundVelocity(RVec3Arg inCenterOfMass,float angular_velocity_len_sq = inAngularVelocity.LengthSq();if (angular_velocity_len_sq < 1.0e-12f)return inLinearVelocity;- float angular_velocity_len = sqrt(angular_velocity_len_sq);+ float angular_velocity_len = Sqrt(angular_velocity_len_sq);// Calculate the rotation that the object will make in the time stepQuat rotation = Quat::sRotation(inAngularVelocity / angular_velocity_len, angular_velocity_len * inDeltaTime);@@ -207,7 +213,7 @@ Vec3 CharacterVirtual::CalculateCharacterGroundVelocity(RVec3Arg inCenterOfMass,}template <class taCollector>-void CharacterVirtual::sFillContactProperties(const CharacterVirtual *inCharacter, Contact &outContact, const Body &inBody, Vec3Arg inUp, RVec3Arg inBaseOffset, const taCollector &inCollector, const CollideShapeResult &inResult)+void CharacterVirtual::sFillContactProperties(const CharacterVirtual *inCharacter, CharacterContact &outContact, const Body &inBody, Vec3Arg inUp, RVec3Arg inBaseOffset, const taCollector &inCollector, const CollideShapeResult &inResult){// Get adjusted body velocityVec3 linear_velocity, angular_velocity;@@ -217,7 +223,8 @@ void CharacterVirtual::sFillContactProperties(const CharacterVirtual *inCharacteoutContact.mLinearVelocity = linear_velocity + angular_velocity.Cross(Vec3(outContact.mPosition - inBody.GetCenterOfMassPosition())); // Calculate point velocityoutContact.mContactNormal = -inResult.mPenetrationAxis.NormalizedOr(Vec3::sZero());outContact.mSurfaceNormal = inCollector.GetContext()->GetWorldSpaceSurfaceNormal(inResult.mSubShapeID2, outContact.mPosition);- if (outContact.mContactNormal.Dot(outContact.mSurfaceNormal) < 0.0f)+ outContact.mIsBackFacingContact = outContact.mContactNormal.Dot(outContact.mSurfaceNormal) < -0.0174524f; // Allow a 1 degree slop, perpendicular is not backfacing+ if (outContact.mIsBackFacingContact)outContact.mSurfaceNormal = -outContact.mSurfaceNormal; // Flip surface normal if we're hitting a back faceif (outContact.mContactNormal.Dot(inUp) > outContact.mSurfaceNormal.Dot(inUp))outContact.mSurfaceNormal = outContact.mContactNormal; // Replace surface normal with contact normal if the contact normal is pointing more upwards@@ -230,7 +237,7 @@ void CharacterVirtual::sFillContactProperties(const CharacterVirtual *inCharacteoutContact.mMaterial = inCollector.GetContext()->GetMaterial(inResult.mSubShapeID2);}-void CharacterVirtual::sFillCharacterContactProperties(Contact &outContact, const CharacterVirtual *inOtherCharacter, RVec3Arg inBaseOffset, const CollideShapeResult &inResult)+void CharacterVirtual::sFillCharacterContactProperties(CharacterContact &outContact, const CharacterVirtual *inOtherCharacter, RVec3Arg inBaseOffset, const CollideShapeResult &inResult){outContact.mPosition = inBaseOffset + inResult.mContactPointOn2;outContact.mLinearVelocity = inOtherCharacter->GetLinearVelocity();@@ -259,10 +266,10 @@ void CharacterVirtual::ContactCollector::AddHit(const CollideShapeResult &inResu// Loop all contacts and find similar contactsfor (int i = (int)mContacts.size() - 1; i >= 0; --i){- Contact &contact_i = mContacts[i];+ CharacterContact &contact_i = mContacts[i];for (int j = i - 1; j >= 0; --j){- Contact &contact_j = mContacts[j];+ CharacterContact &contact_j = mContacts[j];if (contact_i.IsSameBody(contact_j)&& contact_i.mContactNormal.Dot(contact_j.mContactNormal) > mHitReductionCosMaxAngle) // Very similar contact normals{@@ -308,7 +315,7 @@ void CharacterVirtual::ContactCollector::AddHit(const CollideShapeResult &inResu// Create contact with other charactermContacts.emplace_back();- Contact &contact = mContacts.back();+ CharacterContact &contact = mContacts.back();sFillCharacterContactProperties(contact, mOtherCharacter, mBaseOffset, inResult);contact.mFraction = 0.0f;}@@ -319,25 +326,26 @@ void CharacterVirtual::ContactCollector::AddHit(const CollideShapeResult &inResuif (lock.SucceededAndIsInBroadPhase()){mContacts.emplace_back();- Contact &contact = mContacts.back();+ CharacterContact &contact = mContacts.back();sFillContactProperties(mCharacter, contact, lock.GetBody(), mUp, mBaseOffset, *this, inResult);contact.mFraction = 0.0f;}}}-void CharacterVirtual::ContactCastCollector::AddHit(const ShapeCastResult &inResult)+template <bool IgnoreInitialOverlap>+void CharacterVirtual::ContactCastCollector<IgnoreInitialOverlap>::AddHit(const ShapeCastResult &inResult){if (inResult.mFraction < mContact.mFraction // Since we're doing checks against the world and against characters, we may get a hit with a higher fraction than the previous hit- && inResult.mFraction > 0.0f // Ignore collisions at fraction = 0+ && (!IgnoreInitialOverlap || inResult.mFraction > 0.0f) // Ignore collisions at fraction = 0&& inResult.mPenetrationAxis.Dot(mDisplacement) > 0.0f) // Ignore penetrations that we're moving away from{// Test if this contact should be ignored- for (const ContactKey &c : mIgnoredContacts)+ for (const CharacterContactKey &c : mIgnoredContacts)if (c.mBodyB == inResult.mBodyID2 && c.mSubShapeIDB == inResult.mSubShapeID2)return;- Contact contact;+ CharacterContact contact;if (inResult.mBodyID2.IsInvalid()){@@ -425,7 +433,7 @@ void CharacterVirtual::GetContactsAtPosition(RVec3Arg inPosition, Vec3Arg inMove// Reduce distance to contact by padding to ensure we stay away from the object by a little margin// (this will make collision detection cheaper - especially for sweep tests as they won't hit the surface if we're properly sliding)- for (Contact &c : outContacts)+ for (CharacterContact &c : outContacts){c.mDistance -= mCharacterPadding;@@ -443,11 +451,11 @@ void CharacterVirtual::RemoveConflictingContacts(TempContactList &ioContacts, Ig// Discard conflicting penetrating contactsfor (size_t c1 = 0; c1 < ioContacts.size(); c1++){- Contact &contact1 = ioContacts[c1];+ CharacterContact &contact1 = ioContacts[c1];if (contact1.mDistance <= -cMinRequiredPenetration) // Only for penetrationsfor (size_t c2 = c1 + 1; c2 < ioContacts.size(); c2++){- Contact &contact2 = ioContacts[c2];+ CharacterContact &contact2 = ioContacts[c2];if (contact1.IsSameBody(contact2)&& contact2.mDistance <= -cMinRequiredPenetration // Only for penetrations&& contact1.mContactNormal.Dot(contact2.mContactNormal) < 0.0f) // Only opposing normals@@ -473,18 +481,18 @@ void CharacterVirtual::RemoveConflictingContacts(TempContactList &ioContacts, Ig}}-bool CharacterVirtual::ValidateContact(const Contact &inContact) const+bool CharacterVirtual::ValidateContact(const CharacterContact &inContact) const{if (mListener == nullptr)return true;if (inContact.mCharacterB != nullptr)- return mListener->OnCharacterContactValidate(this, inContact.mCharacterB, inContact.mSubShapeIDB);+ return mListener->OnCharacterContactValidate(this, inContact);else- return mListener->OnContactValidate(this, inContact.mBodyB, inContact.mSubShapeIDB);+ return mListener->OnContactValidate(this, inContact);}-void CharacterVirtual::ContactAdded(const Contact &inContact, CharacterContactSettings &ioSettings)+void CharacterVirtual::ContactAdded(const CharacterContact &inContact, CharacterContactSettings &ioSettings){if (mListener != nullptr){@@ -496,9 +504,9 @@ void CharacterVirtual::ContactAdded(const Contact &inContact, CharacterContactSeif (++it->second.mCount == 1){if (inContact.mCharacterB != nullptr)- mListener->OnCharacterContactPersisted(this, inContact.mCharacterB, inContact.mSubShapeIDB, inContact.mPosition, -inContact.mContactNormal, ioSettings);+ mListener->OnCharacterContactPersisted(this, inContact, ioSettings);else- mListener->OnContactPersisted(this, inContact.mBodyB, inContact.mSubShapeIDB, inContact.mPosition, -inContact.mContactNormal, ioSettings);+ mListener->OnContactPersisted(this, inContact, ioSettings);it->second.mSettings = ioSettings;}else@@ -511,9 +519,9 @@ void CharacterVirtual::ContactAdded(const Contact &inContact, CharacterContactSe{// New contactif (inContact.mCharacterB != nullptr)- mListener->OnCharacterContactAdded(this, inContact.mCharacterB, inContact.mSubShapeIDB, inContact.mPosition, -inContact.mContactNormal, ioSettings);+ mListener->OnCharacterContactAdded(this, inContact, ioSettings);else- mListener->OnContactAdded(this, inContact.mBodyB, inContact.mSubShapeIDB, inContact.mPosition, -inContact.mContactNormal, ioSettings);+ mListener->OnContactAdded(this, inContact, ioSettings);mListenerContacts.insert(ListenerContacts::value_type(inContact, ioSettings));}}@@ -558,7 +566,7 @@ inline static bool sCorrectFractionForCharacterPadding(const Shape *inShape, Mat}}-bool CharacterVirtual::GetFirstContactForSweep(RVec3Arg inPosition, Vec3Arg inDisplacement, Contact &outContact, const IgnoredContactList &inIgnoredContacts, const BroadPhaseLayerFilter &inBroadPhaseLayerFilter, const ObjectLayerFilter &inObjectLayerFilter, const BodyFilter &inBodyFilter, const ShapeFilter &inShapeFilter) const+bool CharacterVirtual::ValidateMovement(RVec3Arg inPosition, Vec3Arg inDisplacement, CharacterContact &outContact, const IgnoredContactList &inIgnoredContacts, const BroadPhaseLayerFilter &inBroadPhaseLayerFilter, const ObjectLayerFilter &inObjectLayerFilter, const BodyFilter &inBodyFilter, const ShapeFilter &inShapeFilter) const{// Too small distance -> skip checkingfloat displacement_len_sq = inDisplacement.LengthSq();@@ -577,16 +585,16 @@ bool CharacterVirtual::GetFirstContactForSweep(RVec3Arg inPosition, Vec3Arg inDisettings.mReturnDeepestPoint = false;// Calculate how much extra fraction we need to add to the cast to account for the character padding- float character_padding_fraction = mCharacterPadding / sqrt(displacement_len_sq);+ float character_padding_fraction = mCharacterPadding / Sqrt(displacement_len_sq);// Body filterIgnoreSingleBodyFilterChained body_filter(mInnerBodyID, inBodyFilter);// Cast shape- Contact contact;+ CharacterContact contact;contact.mFraction = 1.0f + character_padding_fraction;RVec3 base_offset = start.GetTranslation();- ContactCastCollector collector(mSystem, this, inDisplacement, mUp, inIgnoredContacts, base_offset, contact);+ ContactCastCollector<true> collector(mSystem, this, inDisplacement, mUp, inIgnoredContacts, base_offset, contact);collector.ResetEarlyOutFraction(contact.mFraction);RShapeCast shape_cast(mShape, Vec3::sOne(), start, inDisplacement);mSystem->GetNarrowPhaseQuery().CastShape(shape_cast, settings, base_offset, collector, inBroadPhaseLayerFilter, inObjectLayerFilter, body_filter, inShapeFilter);@@ -621,19 +629,22 @@ bool CharacterVirtual::GetFirstContactForSweep(RVec3Arg inPosition, Vec3Arg inDits = mSystem->GetBodyInterface().GetTransformedShape(outContact.mBodyB);}- // Fetch the face we're colliding with- Shape::SupportingFace face;- ts.GetSupportingFace(outContact.mSubShapeIDB, -outContact.mContactNormal, base_offset, face);-bool corrected = false;- if (face.size() >= 2)+ if (ts.mShape != nullptr) // If body B has been removed between CastShape and GetTransformedShape, TransformedShape will be empty{- // Inflate the colliding face by the character padding- PolygonConvexSupport polygon(face);- AddConvexRadius add_cvx(polygon, character_padding);+ // Fetch the face we're colliding with+ Shape::SupportingFace face;+ ts.GetSupportingFace(outContact.mSubShapeIDB, -outContact.mContactNormal, base_offset, face);- // Correct fraction to hit this inflated face instead of the inner shape- corrected = sCorrectFractionForCharacterPadding(mShape, start.GetRotation(), inDisplacement, Vec3::sOne(), add_cvx, outContact.mFraction);+ if (face.size() >= 2)+ {+ // Inflate the colliding face by the character padding+ PolygonConvexSupport polygon(face);+ AddConvexRadius add_cvx(polygon, character_padding);++ // Correct fraction to hit this inflated face instead of the inner shape+ corrected = sCorrectFractionForCharacterPadding(mShape, start.GetRotation(), inDisplacement, Vec3::sOne(), add_cvx, outContact.mFraction);+ }}if (!corrected){@@ -648,9 +659,49 @@ bool CharacterVirtual::GetFirstContactForSweep(RVec3Arg inPosition, Vec3Arg inDireturn true;}+bool CharacterVirtual::GetFirstContactForSweep(RVec3Arg inPosition, Vec3Arg inDisplacement, CharacterContact &outContact, const IgnoredContactList &inIgnoredContacts, const BroadPhaseLayerFilter &inBroadPhaseLayerFilter, const ObjectLayerFilter &inObjectLayerFilter, const BodyFilter &inBodyFilter, const ShapeFilter &inShapeFilter) const+{+ // Calculate start transform+ RMat44 start = GetCenterOfMassTransform(inPosition, mRotation, mShape);++ // Settings for the cast+ ShapeCastSettings settings;+ settings.mExtraConvexRadius = mCharacterPadding;+ settings.mBackFaceModeTriangles = mBackFaceMode;+ settings.mBackFaceModeConvex = EBackFaceMode::IgnoreBackFaces;+ settings.mActiveEdgeMode = EActiveEdgeMode::CollideOnlyWithActive;+ settings.mUseShrunkenShapeAndConvexRadius = true;+ settings.mReturnDeepestPoint = false;++ // Body filter+ IgnoreSingleBodyFilterChained body_filter(mInnerBodyID, inBodyFilter);++ // Cast shape+ CharacterContact contact;+ contact.mFraction = 1.0f + FLT_MIN;+ RVec3 base_offset = start.GetTranslation();+ ContactCastCollector<false> collector(mSystem, this, inDisplacement, mUp, inIgnoredContacts, base_offset, contact);+ RShapeCast shape_cast(mShape, Vec3::sOne(), start, inDisplacement);+ mSystem->GetNarrowPhaseQuery().CastShape(shape_cast, settings, base_offset, collector, inBroadPhaseLayerFilter, inObjectLayerFilter, body_filter, inShapeFilter);++ // Also collide with other characters+ if (mCharacterVsCharacterCollision != nullptr)+ {+ collector.SetContext(nullptr); // We're no longer colliding with a transformed shape, reset+ mCharacterVsCharacterCollision->CastCharacter(this, start, inDisplacement, settings, base_offset, collector);+ }++ if (contact.mBodyB.IsInvalid() && contact.mCharacterIDB.IsInvalid())+ return false;++ // Store contact+ outContact = contact;+ return true;+}+void CharacterVirtual::DetermineConstraints(TempContactList &inContacts, float inDeltaTime, ConstraintList &outConstraints) const{- for (Contact &c : inContacts)+ for (CharacterContact &c : inContacts){Vec3 contact_velocity = c.mLinearVelocity;@@ -683,7 +734,7 @@ void CharacterVirtual::DetermineConstraints(TempContactList &inContacts, float ioutConstraints.emplace_back();Constraint &vertical_constraint = outConstraints.back();vertical_constraint.mContact = &c;- vertical_constraint.mLinearVelocity = contact_velocity.Dot(normal) * normal; // Project the contact velocity on the new normal so that both planes push at an equal rate+ vertical_constraint.mLinearVelocity = c.mLinearVelocity.Dot(normal) * normal; // Project the contact velocity on the new normal so that both planes push at an equal rate. We ignore velocity added to push characters out of collision as that can get characters stuck if they are surrounded on all sides by steep slopes.vertical_constraint.mPlane = Plane(normal, c.mDistance / normal.Dot(c.mContactNormal)); // Calculate the distance we have to travel horizontally to hit the contact plane}}@@ -692,7 +743,7 @@ void CharacterVirtual::DetermineConstraints(TempContactList &inContacts, float ibool CharacterVirtual::HandleContact(Vec3Arg inVelocity, Constraint &ioConstraint, float inDeltaTime){- Contact &contact = *ioConstraint.mContact;+ CharacterContact &contact = *ioConstraint.mContact;// Validate the contact pointif (!ValidateContact(contact))@@ -865,7 +916,7 @@ void CharacterVirtual::SolveConstraints(Vec3Arg inVelocity, float inDeltaTime, f// Constraint should be ignored, remove it from the listc->mContact->mWasDiscarded = true;- // Mark it as ignored for GetFirstContactForSweep+ // Mark it as ignored for ValidateMovementioIgnoredContacts.emplace_back(*c->mContact);continue;}@@ -925,7 +976,7 @@ void CharacterVirtual::SolveConstraints(Vec3Arg inVelocity, float inDeltaTime, f// Find the normal of the previous contact that we will violate the most if we move in this new directionfloat highest_penetration = 0.0f;- Constraint *other_constraint = nullptr;+ const Constraint *other_constraint = nullptr;for (Constraint **c = previous_contacts.data(); c < previous_contacts.data() + num_previous_contacts; ++c)if (*c != constraint){@@ -942,6 +993,12 @@ void CharacterVirtual::SolveConstraints(Vec3Arg inVelocity, float inDeltaTime, fother_constraint = *c;}}++ // Cancel the constraint velocity in the other constraint plane's direction so that we won't try to apply it again and keep ping ponging between planes+ constraint->mLinearVelocity -= min(0.0f, constraint->mLinearVelocity.Dot(other_normal)) * other_normal;++ // Cancel the other constraints velocity in this constraint plane's direction so that we won't try to apply it again and keep ping ponging between planes+ (*c)->mLinearVelocity -= min(0.0f, (*c)->mLinearVelocity.Dot(plane_normal)) * plane_normal;}// Check if we found a 2nd constraint@@ -952,12 +1009,6 @@ void CharacterVirtual::SolveConstraints(Vec3Arg inVelocity, float inDeltaTime, fVec3 slide_dir = plane_normal.Cross(other_normal).Normalized();Vec3 velocity_in_slide_dir = new_velocity.Dot(slide_dir) * slide_dir;- // Cancel the constraint velocity in the other constraint plane's direction so that we won't try to apply it again and keep ping ponging between planes- constraint->mLinearVelocity -= min(0.0f, constraint->mLinearVelocity.Dot(other_normal)) * other_normal;-- // Cancel the other constraints velocity in this constraint plane's direction so that we won't try to apply it again and keep ping ponging between planes- other_constraint->mLinearVelocity -= min(0.0f, other_constraint->mLinearVelocity.Dot(plane_normal)) * plane_normal;-// Calculate the velocity of this constraint perpendicular to the slide directionVec3 perpendicular_velocity = constraint->mLinearVelocity - constraint->mLinearVelocity.Dot(slide_dir) * slide_dir;@@ -1022,7 +1073,7 @@ void CharacterVirtual::UpdateSupportingContact(bool inSkipContactVelocityCheck,{// Flag contacts as having a collision if they're close enough but ignore contacts we're moving away from.// Note that if we did MoveShape before we want to preserve any contacts that it marked as colliding- for (Contact &c : mActiveContacts)+ for (CharacterContact &c : mActiveContacts)if (!c.mWasDiscarded&& !c.mHadCollision&& c.mDistance < mCollisionTolerance@@ -1047,11 +1098,11 @@ void CharacterVirtual::UpdateSupportingContact(bool inSkipContactVelocityCheck,int num_avg_normal = 0;Vec3 avg_normal = Vec3::sZero();Vec3 avg_velocity = Vec3::sZero();- const Contact *supporting_contact = nullptr;+ const CharacterContact *supporting_contact = nullptr;float max_cos_angle = -FLT_MAX;- const Contact *deepest_contact = nullptr;+ const CharacterContact *deepest_contact = nullptr;float smallest_distance = FLT_MAX;- for (const Contact &c : mActiveContacts)+ for (const CharacterContact &c : mActiveContacts)if (c.mHadCollision && !c.mWasDiscarded){// Calculate the angle between the plane normal and the up direction@@ -1116,7 +1167,7 @@ void CharacterVirtual::UpdateSupportingContact(bool inSkipContactVelocityCheck,}// Take either the most supporting contact or the deepest contact- const Contact *best_contact = supporting_contact != nullptr? supporting_contact : deepest_contact;+ const CharacterContact *best_contact = supporting_contact != nullptr? supporting_contact : deepest_contact;// Calculate average normal and velocityif (num_avg_normal >= 1)@@ -1230,7 +1281,7 @@ void CharacterVirtual::MoveShape(RVec3 &ioPosition, Vec3Arg inVelocity, float inGetContactsAtPosition(ioPosition, movement_direction, mShape, contacts, inBroadPhaseLayerFilter, inObjectLayerFilter, inBodyFilter, inShapeFilter);#ifdef JPH_ENABLE_DETERMINISM_LOG- for (const Contact &c : contacts)+ for (const CharacterContact &c : contacts)JPH_DET_LOG("contact: " << c.mPosition << " vel: " << c.mLinearVelocity << " cnormal: " << c.mContactNormal << " snormal: " << c.mSurfaceNormal << " dist: " << c.mDistance << " fraction: " << c.mFraction << " body: " << c.mBodyB << " subshape: " << c.mSubShapeIDB);#endif // JPH_ENABLE_DETERMINISM_LOG@@ -1278,8 +1329,8 @@ void CharacterVirtual::MoveShape(RVec3 &ioPosition, Vec3Arg inVelocity, float inoutActiveContacts->assign(contacts.begin(), contacts.end());// Do a sweep to test if the path is really unobstructed- Contact cast_contact;- if (GetFirstContactForSweep(ioPosition, displacement, cast_contact, ignored_contacts, inBroadPhaseLayerFilter, inObjectLayerFilter, inBodyFilter, inShapeFilter))+ CharacterContact cast_contact;+ if (ValidateMovement(ioPosition, displacement, cast_contact, ignored_contacts, inBroadPhaseLayerFilter, inObjectLayerFilter, inBodyFilter, inShapeFilter)){displacement *= cast_contact.mFraction;time_simulated *= cast_contact.mFraction;@@ -1312,7 +1363,7 @@ Vec3 CharacterVirtual::CancelVelocityTowardsSteepSlopes(Vec3Arg inDesiredVelocitreturn inDesiredVelocity;Vec3 desired_velocity = inDesiredVelocity;- for (const Contact &c : mActiveContacts)+ for (const CharacterContact &c : mActiveContacts)if (c.mHadCollision&& !c.mWasDiscarded&& IsSlopeTooSteep(c.mSurfaceNormal))@@ -1344,7 +1395,7 @@ void CharacterVirtual::StartTrackingContactChanges()// Mark all current contacts as not seenmListenerContacts.reserve(ListenerContacts::size_type(mActiveContacts.size()));- for (const Contact &c : mActiveContacts)+ for (const CharacterContact &c : mActiveContacts)if (c.mHadCollision)mListenerContacts.insert(ListenerContacts::value_type(c, ListenerContactValue()));}@@ -1367,7 +1418,7 @@ void CharacterVirtual::FinishTrackingContactChanges()// to ensure that these lists are in sync.for (ListenerContacts::value_type &c : mListenerContacts)c.second.mCount = 0;- for (const Contact &c : mActiveContacts)+ for (const CharacterContact &c : mActiveContacts)if (c.mHadCollision){ListenerContacts::iterator it = mListenerContacts.find(c);@@ -1379,7 +1430,7 @@ void CharacterVirtual::FinishTrackingContactChanges()for (ListenerContacts::iterator it = mListenerContacts.begin(); it != mListenerContacts.end(); ++it)if (it->second.mCount == 0){- const ContactKey &c = it->first;+ const CharacterContactKey &c = it->first;if (!c.mCharacterIDB.IsInvalid())mListener->OnCharacterContactRemoved(this, c.mCharacterIDB, c.mSubShapeIDB);else@@ -1394,6 +1445,12 @@ void CharacterVirtual::Update(float inDeltaTime, Vec3Arg inGravity, const BroadPif (inDeltaTime <= 0.0f)return;+#ifdef JPH_DEBUG_RENDERER+ // Draw supporting volume pre movement+ if (sDrawSupportingVolume)+ DebugRenderer::sInstance->DrawPlane(mPosition - mSupportingVolume.GetConstant() * mSupportingVolume.GetNormal(), mSupportingVolume.GetNormal(), Color::sBlue, 1.0f);+#endif // JPH_DEBUG_RENDERER+StartTrackingContactChanges();JPH_SCOPE_EXIT([this]() { FinishTrackingContactChanges(); });@@ -1452,7 +1509,7 @@ void CharacterVirtual::UpdateGroundVelocity()}}-void CharacterVirtual::MoveToContact(RVec3Arg inPosition, const Contact &inContact, const BroadPhaseLayerFilter &inBroadPhaseLayerFilter, const ObjectLayerFilter &inObjectLayerFilter, const BodyFilter &inBodyFilter, const ShapeFilter &inShapeFilter, TempAllocator &inAllocator)+void CharacterVirtual::MoveToContact(RVec3Arg inPosition, const CharacterContact &inContact, const BroadPhaseLayerFilter &inBroadPhaseLayerFilter, const ObjectLayerFilter &inObjectLayerFilter, const BodyFilter &inBodyFilter, const ShapeFilter &inShapeFilter, TempAllocator &inAllocator){// Set the new positionSetPosition(inPosition);@@ -1468,7 +1525,7 @@ void CharacterVirtual::MoveToContact(RVec3Arg inPosition, const Contact &inConta// Ensure that we mark inContact as collidingbool found_contact = false;- for (Contact &c : contacts)+ for (CharacterContact &c : contacts)if (c.mBodyB == inContact.mBodyB&& c.mSubShapeIDB == inContact.mSubShapeIDB){@@ -1479,7 +1536,7 @@ void CharacterVirtual::MoveToContact(RVec3Arg inPosition, const Contact &inConta{contacts.push_back(inContact);- Contact © = contacts.back();+ CharacterContact © = contacts.back();copy.mHadCollision = true;}@@ -1509,7 +1566,7 @@ bool CharacterVirtual::SetShape(const Shape *inShape, float inMaxPenetrationDeptGetContactsAtPosition(mPosition, mLinearVelocity.NormalizedOr(Vec3::sZero()), inShape, contacts, inBroadPhaseLayerFilter, inObjectLayerFilter, inBodyFilter, inShapeFilter);// Test if this results in penetration, if so cancel the transition- for (const Contact &c : contacts)+ for (const CharacterContact &c : contacts)if (c.mDistance < -inMaxPenetrationDepth&& !c.mIsSensorB)return false;@@ -1541,7 +1598,7 @@ bool CharacterVirtual::CanWalkStairs(Vec3Arg inLinearVelocity) constreturn false;// Check contacts for steep slopes- for (const Contact &c : mActiveContacts)+ for (const CharacterContact &c : mActiveContacts)if (c.mHadCollision&& !c.mWasDiscarded&& c.mSurfaceNormal.Dot(horizontal_velocity - c.mLinearVelocity) < 0.0f // Pushing into the contact@@ -1556,11 +1613,11 @@ bool CharacterVirtual::WalkStairs(float inDeltaTime, Vec3Arg inStepUp, Vec3Arg iStartTrackingContactChanges();JPH_SCOPE_EXIT([this]() { FinishTrackingContactChanges(); });- // Move up+ // Move up. Note that we used ValidateMovement here so that we ignore initial collisions and character padding on the sides while moving up. This makes moving up a bit easier.Vec3 up = inStepUp;- Contact contact;+ CharacterContact contact;IgnoredContactList dummy_ignored_contacts(inAllocator);- if (GetFirstContactForSweep(mPosition, up, contact, dummy_ignored_contacts, inBroadPhaseLayerFilter, inObjectLayerFilter, inBodyFilter, inShapeFilter))+ if (ValidateMovement(mPosition, up, contact, dummy_ignored_contacts, inBroadPhaseLayerFilter, inObjectLayerFilter, inBodyFilter, inShapeFilter)){if (contact.mFraction < 1.0e-6f)return false; // No movement, cancel@@ -1579,13 +1636,12 @@ bool CharacterVirtual::WalkStairs(float inDeltaTime, Vec3Arg inStepUp, Vec3Arg i// Collect normals of steep slopes that we would like to walk stairs on.// We need to do this before calling MoveShape because it will update mActiveContacts.Vec3 character_velocity = inStepForward / inDeltaTime;- Vec3 horizontal_velocity = character_velocity - character_velocity.Dot(mUp) * mUp;Array<Vec3, STLTempAllocator<Vec3>> steep_slope_normals(inAllocator);steep_slope_normals.reserve(mActiveContacts.size());- for (const Contact &c : mActiveContacts)+ for (const CharacterContact &c : mActiveContacts)if (c.mHadCollision&& !c.mWasDiscarded- && c.mSurfaceNormal.Dot(horizontal_velocity - c.mLinearVelocity) < 0.0f // Pushing into the contact+ && c.mSurfaceNormal.Dot(character_velocity - c.mLinearVelocity) < 0.0f // Pushing into the contact&& IsSlopeTooSteep(c.mSurfaceNormal)) // Slope too steepsteep_slope_normals.push_back(c.mSurfaceNormal);if (steep_slope_normals.empty())@@ -1603,14 +1659,23 @@ bool CharacterVirtual::WalkStairs(float inDeltaTime, Vec3Arg inStepUp, Vec3Arg i// so we need to cancel the stair walk or else we will move faster than we should as we've done// normal movement first and then stair walk.bool made_progress = false;- float max_dot = -0.05f * inStepForward.Length();+ float step_forward_length = inStepForward.Length();+ Vec3 step_forward_normalized = inStepForward / step_forward_length;for (const Vec3 &normal : steep_slope_normals)- if (normal.Dot(horizontal_movement) < max_dot)+ {+ Vec3 direction = normal.Dot(mUp) * mUp - normal;+ float direction_len = direction.Length();+ if (direction_len > 1.0e-6f){- // We moved more than 5% of the forward step against a steep slope, accept this as progress- made_progress = true;- break;+ direction /= direction_len;+ if (direction.Dot(step_forward_normalized) > 0.707107f // If angle between forward and movement is more than 45 degrees we were mostly sliding+ && direction.Dot(horizontal_movement) > 0.05f * step_forward_length) // If we did not achieve 5% of movement cancel too+ {+ made_progress = true;+ break;+ }}+ }if (!made_progress)return false;@@ -1625,20 +1690,24 @@ bool CharacterVirtual::WalkStairs(float inDeltaTime, Vec3Arg inStepUp, Vec3Arg iVec3 down = -up + inStepDownExtra;if (!GetFirstContactForSweep(new_position, down, contact, dummy_ignored_contacts, inBroadPhaseLayerFilter, inObjectLayerFilter, inBodyFilter, inShapeFilter))return false; // No floor found, we're in mid air, cancel stair walk+ RVec3 final_position = new_position + contact.mFraction * down;++ Vec3 surface_normal = contact.mSurfaceNormal;+ bool too_steep = IsSlopeTooSteep(surface_normal);#ifdef JPH_DEBUG_RENDERER// Draw sweep downif (sDrawWalkStairs){- RVec3 debug_pos = new_position + contact.mFraction * down;- DebugRenderer::sInstance->DrawArrow(new_position, debug_pos, Color::sWhite, 0.01f);- DebugRenderer::sInstance->DrawArrow(contact.mPosition, contact.mPosition + contact.mSurfaceNormal, Color::sWhite, 0.01f);- mShape->Draw(DebugRenderer::sInstance, GetCenterOfMassTransform(debug_pos, mRotation, mShape), Vec3::sOne(), Color::sWhite, false, true);+ Color color = too_steep? Color::sRed : Color::sWhite;+ DebugRenderer::sInstance->DrawArrow(new_position, final_position, color, 0.01f);+ DebugRenderer::sInstance->DrawArrow(contact.mPosition, contact.mPosition + contact.mSurfaceNormal, color, 0.01f);+ mShape->Draw(DebugRenderer::sInstance, GetCenterOfMassTransform(final_position, mRotation, mShape), Vec3::sOne(), color, false, true);}#endif // JPH_DEBUG_RENDERER// Test for floor that will support the character- if (IsSlopeTooSteep(contact.mSurfaceNormal))+ if (too_steep){// If no test position was provided, we cancel the stair walkif (inStepForwardTest.IsNearZero())@@ -1660,31 +1729,35 @@ bool CharacterVirtual::WalkStairs(float inDeltaTime, Vec3Arg inStepUp, Vec3Arg i#endif // JPH_DEBUG_RENDERER// Then sweep down- Contact test_contact;+ CharacterContact test_contact;if (!GetFirstContactForSweep(test_position, down, test_contact, dummy_ignored_contacts, inBroadPhaseLayerFilter, inObjectLayerFilter, inBodyFilter, inShapeFilter))return false;+ surface_normal = test_contact.mSurfaceNormal;+ too_steep = IsSlopeTooSteep(surface_normal);+#ifdef JPH_DEBUG_RENDERER// Draw 2nd sweep downif (sDrawWalkStairs){RVec3 debug_pos = test_position + test_contact.mFraction * down;- DebugRenderer::sInstance->DrawArrow(test_position, debug_pos, Color::sCyan, 0.01f);- DebugRenderer::sInstance->DrawArrow(test_contact.mPosition, test_contact.mPosition + test_contact.mSurfaceNormal, Color::sCyan, 0.01f);- mShape->Draw(DebugRenderer::sInstance, GetCenterOfMassTransform(debug_pos, mRotation, mShape), Vec3::sOne(), Color::sCyan, false, true);+ Color color = too_steep? Color::sRed : Color::sCyan;+ DebugRenderer::sInstance->DrawArrow(test_position, debug_pos, color, 0.01f);+ DebugRenderer::sInstance->DrawArrow(test_contact.mPosition, test_contact.mPosition + test_contact.mSurfaceNormal, color, 0.01f);+ mShape->Draw(DebugRenderer::sInstance, GetCenterOfMassTransform(debug_pos, mRotation, mShape), Vec3::sOne(), color, false, true);}#endif // JPH_DEBUG_RENDERER- if (IsSlopeTooSteep(test_contact.mSurfaceNormal))+ if (too_steep)return false;}- // Calculate new down position- down *= contact.mFraction;- new_position += down;+ // If we don't gain any height compared to our contact then the stair walk is pointless+ if (Vec3(final_position - mPosition).Dot(surface_normal) < 1.0e-4f)+ return false;// Move the character to the new location- MoveToContact(new_position, contact, inBroadPhaseLayerFilter, inObjectLayerFilter, inBodyFilter, inShapeFilter, inAllocator);+ MoveToContact(final_position, contact, inBroadPhaseLayerFilter, inObjectLayerFilter, inBodyFilter, inShapeFilter, inAllocator);// Override ground state to 'on ground', it is possible that the contact normal is too steep, but in this case the inStepForwardTest has found a contact normal that is not too steepmGroundState = EGroundState::OnGround;@@ -1698,7 +1771,7 @@ bool CharacterVirtual::StickToFloor(Vec3Arg inStepDown, const BroadPhaseLayerFilJPH_SCOPE_EXIT([this]() { FinishTrackingContactChanges(); });// Try to find the floor- Contact contact;+ CharacterContact contact;IgnoredContactList dummy_ignored_contacts(inAllocator);if (!GetFirstContactForSweep(mPosition, inStepDown, contact, dummy_ignored_contacts, inBroadPhaseLayerFilter, inObjectLayerFilter, inBodyFilter, inShapeFilter))return false; // If no floor found, don't update our position@@ -1774,26 +1847,37 @@ void CharacterVirtual::ExtendedUpdate(float inDeltaTime, Vec3Arg inGravity, consif (achieved_horizontal_step_len + 1.0e-4f < desired_horizontal_step_len&& CanWalkStairs(desired_velocity)){+ // Find the contact that is most opposing our movement. Our extra walk stairs test is going to go in that direction instead+ // of the movement direction. This allows us to step up stairs if we're moving at a big angle along the stairs.+ Vec3 walk_stairs_direction = step_forward_normalized;+ float max_dot = inSettings.mWalkStairsCosAngleForwardContact; // Discard contacts that have an angle that is too big+ for (const CharacterContact &c : mActiveContacts)+ if (c.mHadCollision+ && !c.mWasDiscarded+ && c.mSurfaceNormal.Dot(desired_velocity - c.mLinearVelocity) < 0.0f // Pushing into the contact+ && IsSlopeTooSteep(c.mSurfaceNormal)) // Slope too steep+ {+ // Remove vertical component of the surface normal and negate it so that it points in the direction of movement+ Vec3 test = c.mSurfaceNormal.Dot(mUp) * mUp - c.mSurfaceNormal;+ float test_len = test.Length();+ if (test_len > 1.0e-6f)+ {+ test /= test_len;+ float dot = test.Dot(step_forward_normalized);+ if (dot > max_dot)+ {+ walk_stairs_direction = test;+ max_dot = dot;+ }+ }+ }+// Calculate how much we should step forward// Note that we clamp the step forward to a minimum distance. This is done because at very high frame rates the delta time// may be very small, causing a very small step forward. If the step becomes small enough, we may not move far enough// horizontally to actually end up at the top of the step.- Vec3 step_forward = step_forward_normalized * max(inSettings.mWalkStairsMinStepForward, desired_horizontal_step_len - achieved_horizontal_step_len);-- // Calculate how far to scan ahead for a floor. This is only used in case the floor normal at step_forward is too steep.- // In that case an additional check will be performed at this distance to check if that normal is not too steep.- // Start with the ground normal in the horizontal plane and normalizing it- Vec3 step_forward_test = -mGroundNormal;- step_forward_test -= step_forward_test.Dot(mUp) * mUp;- step_forward_test = step_forward_test.NormalizedOr(step_forward_normalized);-- // If this normalized vector and the character forward vector is bigger than a preset angle, we use the character forward vector instead of the ground normal- // to do our forward test- if (step_forward_test.Dot(step_forward_normalized) < inSettings.mWalkStairsCosAngleForwardContact)- step_forward_test = step_forward_normalized;-- // Calculate the correct magnitude for the test vector- step_forward_test *= inSettings.mWalkStairsStepForwardTest;+ Vec3 step_forward = walk_stairs_direction * max(inSettings.mWalkStairsMinStepForward, desired_horizontal_step_len - achieved_horizontal_step_len);+ Vec3 step_forward_test = walk_stairs_direction * inSettings.mWalkStairsStepForwardTest;WalkStairs(inDeltaTime, inSettings.mWalkStairsStepUp, step_forward, step_forward_test, inSettings.mWalkStairsStepDownExtra, inBroadPhaseLayerFilter, inObjectLayerFilter, inBodyFilter, inShapeFilter, inAllocator);}@@ -1801,23 +1885,23 @@ void CharacterVirtual::ExtendedUpdate(float inDeltaTime, Vec3Arg inGravity, cons}}-void CharacterVirtual::ContactKey::SaveState(StateRecorder &inStream) const+void CharacterContactKey::SaveState(StateRecorder &inStream) const{inStream.Write(mBodyB);inStream.Write(mCharacterIDB);inStream.Write(mSubShapeIDB);}-void CharacterVirtual::ContactKey::RestoreState(StateRecorder &inStream)+void CharacterContactKey::RestoreState(StateRecorder &inStream){inStream.Read(mBodyB);inStream.Read(mCharacterIDB);inStream.Read(mSubShapeIDB);}-void CharacterVirtual::Contact::SaveState(StateRecorder &inStream) const+void CharacterContact::SaveState(StateRecorder &inStream) const{- ContactKey::SaveState(inStream);+ CharacterContactKey::SaveState(inStream);inStream.Write(mPosition);inStream.Write(mLinearVelocity);@@ -1833,9 +1917,9 @@ void CharacterVirtual::Contact::SaveState(StateRecorder &inStream) const// Cannot store pointers to character B, user data and material}-void CharacterVirtual::Contact::RestoreState(StateRecorder &inStream)+void CharacterContact::RestoreState(StateRecorder &inStream){- ContactKey::RestoreState(inStream);+ CharacterContactKey::RestoreState(inStream);inStream.Read(mPosition);inStream.Read(mLinearVelocity);@@ -1865,11 +1949,11 @@ void CharacterVirtual::SaveState(StateRecorder &inStream) const// Store contacts that had collision, we're using it at the beginning of the step in CancelVelocityTowardsSteepSlopesuint32 num_contacts = 0;- for (const Contact &c : mActiveContacts)+ for (const CharacterContact &c : mActiveContacts)if (c.mHadCollision)++num_contacts;inStream.Write(num_contacts);- for (const Contact &c : mActiveContacts)+ for (const CharacterContact &c : mActiveContacts)if (c.mHadCollision)c.SaveState(inStream);}@@ -1893,7 +1977,7 @@ void CharacterVirtual::RestoreState(StateRecorder &inStream)uint32 num_contacts = (uint32)mActiveContacts.size();inStream.Read(num_contacts);mActiveContacts.resize(num_contacts);- for (Contact &c : mActiveContacts)+ for (CharacterContact &c : mActiveContacts)c.RestoreState(inStream);}diff --git a/thirdparty/jolt_physics/Jolt/Physics/Character/CharacterVirtual.h b/thirdparty/jolt_physics/Jolt/Physics/Character/CharacterVirtual.hindex ef70671c690..64a22ed87b4 100644--- a/thirdparty/jolt_physics/Jolt/Physics/Character/CharacterVirtual.h+++ b/thirdparty/jolt_physics/Jolt/Physics/Character/CharacterVirtual.h@@ -12,6 +12,7 @@#include <Jolt/Physics/Collision/ObjectLayer.h>#include <Jolt/Physics/Collision/TransformedShape.h>#include <Jolt/Core/STLTempAllocator.h>+#include <Jolt/Core/UnorderedMap.h>JPH_NAMESPACE_BEGIN@@ -68,7 +69,7 @@ public:};/// This class contains settings that allow you to override the behavior of a character's collision response-class CharacterContactSettings+class JPH_EXPORT CharacterContactSettings{public:/// True when the object can push the virtual character.@@ -80,6 +81,75 @@ public:bool mCanReceiveImpulses = true;};+/// Uniquely identifies a contact between a character and another body or character+class JPH_EXPORT CharacterContactKey+{+public:+ /// Constructor+ CharacterContactKey() = default;+ CharacterContactKey(const CharacterContactKey &inContact) = default;+ CharacterContactKey(const BodyID &inBodyB, const SubShapeID &inSubShapeID) : mBodyB(inBodyB), mSubShapeIDB(inSubShapeID) { }+ CharacterContactKey(const CharacterID &inCharacterIDB, const SubShapeID &inSubShapeID) : mCharacterIDB(inCharacterIDB), mSubShapeIDB(inSubShapeID) { }+ CharacterContactKey & operator = (const CharacterContactKey &inContact) = default;++ /// Checks if two contacts refer to the same body (or virtual character)+ inline bool IsSameBody(const CharacterContactKey &inOther) const+ {+ return mBodyB == inOther.mBodyB && mCharacterIDB == inOther.mCharacterIDB;+ }++ /// Equality operator+ inline bool operator == (const CharacterContactKey &inRHS) const+ {+ return mBodyB == inRHS.mBodyB && mCharacterIDB == inRHS.mCharacterIDB && mSubShapeIDB == inRHS.mSubShapeIDB;+ }++ inline bool operator != (const CharacterContactKey &inRHS) const+ {+ return !(*this == inRHS);+ }++ /// Hash of this structure+ inline uint64 GetHash() const+ {+ static_assert(sizeof(BodyID) + sizeof(CharacterID) + sizeof(SubShapeID) == sizeof(CharacterContactKey), "No padding expected");+ return HashBytes(this, sizeof(CharacterContactKey));+ }++ // Saving / restoring state for replay+ void SaveState(StateRecorder &inStream) const;+ void RestoreState(StateRecorder &inStream);++ BodyID mBodyB; ///< ID of body we're colliding with (if not invalid)+ CharacterID mCharacterIDB; ///< Character we're colliding with (if not invalid)+ SubShapeID mSubShapeIDB; ///< Sub shape ID of body or character we're colliding with+};++/// Encapsulates a collision contact between a character and another rigid body / character+class JPH_EXPORT CharacterContact : public CharacterContactKey+{+public:+ // Saving / restoring state for replay+ void SaveState(StateRecorder &inStream) const;+ void RestoreState(StateRecorder &inStream);++ RVec3 mPosition; ///< Position where the character makes contact+ Vec3 mLinearVelocity; ///< Velocity of the contact point+ Vec3 mContactNormal; ///< Contact normal, pointing towards the character+ Vec3 mSurfaceNormal; ///< Surface normal of the contact. Has been flipped if the contact is back facing (mIsBackFacingContact) and is equal to the contact normal if the contact normal is pointing up more.+ float mDistance; ///< Distance to the contact <= 0 means that it is an actual contact, > 0 means predictive+ float mFraction; ///< Fraction along the path where this contact takes place+ EMotionType mMotionTypeB; ///< Motion type of B, used to determine the priority of the contact+ bool mIsSensorB; ///< If B is a sensor+ const CharacterVirtual * mCharacterB = nullptr; ///< Character we're colliding with (if not nullptr). Note that this may be a dangling pointer when accessed through GetActiveContacts(), use mCharacterIDB instead.+ uint64 mUserData; ///< User data of B+ const PhysicsMaterial * mMaterial; ///< Material of B+ bool mHadCollision = false; ///< If the character actually collided with the contact (can be false if a predictive contact never becomes a real one)+ bool mWasDiscarded = false; ///< If the contact validate callback chose to discard this contact or when the body is a sensor+ bool mCanPushCharacter = true; ///< When true, the velocity of the contact point can push the character+ bool mIsBackFacingContact = false; ///< If this contact came from a back facing triangle / collision shape+};+/// This class receives callbacks when a virtual character hits something./// Once created, register it on a CharacterVirtual by using the character's SetListener method.class JPH_EXPORT CharacterContactListener@@ -93,28 +163,19 @@ public:virtual void OnAdjustBodyVelocity(const CharacterVirtual *inCharacter, const Body &inBody2, Vec3 &ioLinearVelocity, Vec3 &ioAngularVelocity) { /* Do nothing, the linear and angular velocity are already filled in */ }/// Checks if a character can collide with specified body. Return true if the contact is valid.- virtual bool OnContactValidate(const CharacterVirtual *inCharacter, const BodyID &inBodyID2, const SubShapeID &inSubShapeID2) { return true; }-- /// Same as OnContactValidate but when colliding with a CharacterVirtual- virtual bool OnCharacterContactValidate(const CharacterVirtual *inCharacter, const CharacterVirtual *inOtherCharacter, const SubShapeID &inSubShapeID2) { return true; }+ virtual bool OnContactValidate(const CharacterVirtual *inCharacter, const CharacterContact &inContact) { return true; }/// Called whenever the character collides with a body for the first time./// @param inCharacter Character that is being solved- /// @param inBodyID2 Body ID of body that is being hit- /// @param inSubShapeID2 Sub shape ID of shape that is being hit- /// @param inContactPosition World space contact position- /// @param inContactNormal World space contact normal+ /// @param inContact Contact that we're colliding against/// @param ioSettings Settings returned by the contact callback to indicate how the character should behave- virtual void OnContactAdded(const CharacterVirtual *inCharacter, const BodyID &inBodyID2, const SubShapeID &inSubShapeID2, RVec3Arg inContactPosition, Vec3Arg inContactNormal, CharacterContactSettings &ioSettings) { /* Default do nothing */ }+ virtual void OnContactAdded(const CharacterVirtual *inCharacter, const CharacterContact &inContact, CharacterContactSettings &ioSettings) { /* Default do nothing */ }/// Called whenever the character persists colliding with a body./// @param inCharacter Character that is being solved- /// @param inBodyID2 Body ID of body that is being hit- /// @param inSubShapeID2 Sub shape ID of shape that is being hit- /// @param inContactPosition World space contact position- /// @param inContactNormal World space contact normal+ /// @param inContact Contact that we're colliding against/// @param ioSettings Settings returned by the contact callback to indicate how the character should behave- virtual void OnContactPersisted(const CharacterVirtual *inCharacter, const BodyID &inBodyID2, const SubShapeID &inSubShapeID2, RVec3Arg inContactPosition, Vec3Arg inContactNormal, CharacterContactSettings &ioSettings) { /* Default do nothing */ }+ virtual void OnContactPersisted(const CharacterVirtual *inCharacter, const CharacterContact &inContact, CharacterContactSettings &ioSettings) { /* Default do nothing */ }/// Called whenever the character loses contact with a body./// Note that there is no guarantee that the body or its sub shape still exists at this point. The body may have been deleted since the last update.@@ -123,11 +184,14 @@ public:/// @param inSubShapeID2 Sub shape ID of shape that is being hitvirtual void OnContactRemoved(const CharacterVirtual *inCharacter, const BodyID &inBodyID2, const SubShapeID &inSubShapeID2) { /* Default do nothing */ }+ /// Same as OnContactValidate but when colliding with a CharacterVirtual+ virtual bool OnCharacterContactValidate(const CharacterVirtual *inCharacter, const CharacterContact &inContact) { return true; }+/// Same as OnContactAdded but when colliding with a CharacterVirtual- virtual void OnCharacterContactAdded(const CharacterVirtual *inCharacter, const CharacterVirtual *inOtherCharacter, const SubShapeID &inSubShapeID2, RVec3Arg inContactPosition, Vec3Arg inContactNormal, CharacterContactSettings &ioSettings) { /* Default do nothing */ }+ virtual void OnCharacterContactAdded(const CharacterVirtual *inCharacter, const CharacterContact &inContact, CharacterContactSettings &ioSettings) { /* Default do nothing */ }/// Same as OnContactPersisted but when colliding with a CharacterVirtual- virtual void OnCharacterContactPersisted(const CharacterVirtual *inCharacter, const CharacterVirtual *inOtherCharacter, const SubShapeID &inSubShapeID2, RVec3Arg inContactPosition, Vec3Arg inContactNormal, CharacterContactSettings &ioSettings) { /* Default do nothing */ }+ virtual void OnCharacterContactPersisted(const CharacterVirtual *inCharacter, const CharacterContact &inContact, CharacterContactSettings &ioSettings) { /* Default do nothing */ }/// Same as OnContactRemoved but when colliding with a CharacterVirtual/// Note that inOtherCharacterID can be the ID of a character that has been deleted. This happens if the character was in contact with this character during the last update, but has been deleted since.@@ -436,74 +500,11 @@ public:static inline bool sDrawConstraints = false; ///< Draw the current state of the constraints for iteration 0 when creating themstatic inline bool sDrawWalkStairs = false; ///< Draw the state of the walk stairs algorithmstatic inline bool sDrawStickToFloor = false; ///< Draw the state of the stick to floor algorithm+ static inline bool sDrawSupportingVolume = false; ///< Draw the supporting volume plane#endif- /// Uniquely identifies a contact between a character and another body or character- class ContactKey- {- public:- /// Constructor- ContactKey() = default;- ContactKey(const ContactKey &inContact) = default;- ContactKey(const BodyID &inBodyB, const SubShapeID &inSubShapeID) : mBodyB(inBodyB), mSubShapeIDB(inSubShapeID) { }- ContactKey(const CharacterID &inCharacterIDB, const SubShapeID &inSubShapeID) : mCharacterIDB(inCharacterIDB), mSubShapeIDB(inSubShapeID) { }- ContactKey & operator = (const ContactKey &inContact) = default;-- /// Checks if two contacts refer to the same body (or virtual character)- inline bool IsSameBody(const ContactKey &inOther) const { return mBodyB == inOther.mBodyB && mCharacterIDB == inOther.mCharacterIDB; }-- /// Equality operator- bool operator == (const ContactKey &inRHS) const- {- return mBodyB == inRHS.mBodyB && mCharacterIDB == inRHS.mCharacterIDB && mSubShapeIDB == inRHS.mSubShapeIDB;- }-- bool operator != (const ContactKey &inRHS) const- {- return !(*this == inRHS);- }-- /// Hash of this structure- uint64 GetHash() const- {- static_assert(sizeof(BodyID) + sizeof(CharacterID) + sizeof(SubShapeID) == sizeof(ContactKey), "No padding expected");- return HashBytes(this, sizeof(ContactKey));- }-- // Saving / restoring state for replay- void SaveState(StateRecorder &inStream) const;- void RestoreState(StateRecorder &inStream);-- BodyID mBodyB; ///< ID of body we're colliding with (if not invalid)- CharacterID mCharacterIDB; ///< Character we're colliding with (if not invalid)- SubShapeID mSubShapeIDB; ///< Sub shape ID of body or character we're colliding with- };-- /// Encapsulates a collision contact- struct Contact : public ContactKey- {- // Saving / restoring state for replay- void SaveState(StateRecorder &inStream) const;- void RestoreState(StateRecorder &inStream);-- RVec3 mPosition; ///< Position where the character makes contact- Vec3 mLinearVelocity; ///< Velocity of the contact point- Vec3 mContactNormal; ///< Contact normal, pointing towards the character- Vec3 mSurfaceNormal; ///< Surface normal of the contact- float mDistance; ///< Distance to the contact <= 0 means that it is an actual contact, > 0 means predictive- float mFraction; ///< Fraction along the path where this contact takes place- EMotionType mMotionTypeB; ///< Motion type of B, used to determine the priority of the contact- bool mIsSensorB; ///< If B is a sensor- const CharacterVirtual * mCharacterB = nullptr; ///< Character we're colliding with (if not nullptr). Note that this may be a dangling pointer when accessed through GetActiveContacts(), use mCharacterIDB instead.- uint64 mUserData; ///< User data of B- const PhysicsMaterial * mMaterial; ///< Material of B- bool mHadCollision = false; ///< If the character actually collided with the contact (can be false if a predictive contact never becomes a real one)- bool mWasDiscarded = false; ///< If the contact validate callback chose to discard this contact or when the body is a sensor- bool mCanPushCharacter = true; ///< When true, the velocity of the contact point can push the character- };-- using TempContactList = Array<Contact, STLTempAllocator<Contact>>;- using ContactList = Array<Contact>;+ using TempContactList = Array<CharacterContact, STLTempAllocator<CharacterContact>>;+ using ContactList = Array<CharacterContact>;/// Access to the internal list of contacts that the character has found./// Note that only contacts that have their mHadCollision flag set are actual contacts.@@ -512,7 +513,7 @@ public:/// Check if the character is currently in contact with or has collided with another body in the last operation (e.g. Update or WalkStairs)bool HasCollidedWith(const BodyID &inBody) const{- for (const CharacterVirtual::Contact &c : mActiveContacts)+ for (const CharacterContact &c : mActiveContacts)if (c.mHadCollision && c.mBodyB == inBody)return true;return false;@@ -521,7 +522,7 @@ public:/// Check if the character is currently in contact with or has collided with another character in the last time step (e.g. Update or WalkStairs)bool HasCollidedWith(const CharacterID &inCharacterID) const{- for (const CharacterVirtual::Contact &c : mActiveContacts)+ for (const CharacterContact &c : mActiveContacts)if (c.mHadCollision && c.mCharacterIDB == inCharacterID)return true;return false;@@ -537,7 +538,7 @@ private:// Sorting predicate for making contact order deterministicstruct ContactOrderingPredicate{- inline bool operator () (const Contact &inLHS, const Contact &inRHS) const+ inline bool operator () (const CharacterContact &inLHS, const CharacterContact &inRHS) const{if (inLHS.mBodyB != inRHS.mBodyB)return inLHS.mBodyB < inRHS.mBodyB;@@ -549,12 +550,12 @@ private:}};- using IgnoredContactList = Array<ContactKey, STLTempAllocator<ContactKey>>;+ using IgnoredContactList = Array<CharacterContactKey, STLTempAllocator<CharacterContactKey>>;// A constraint that limits the movement of the characterstruct Constraint{- Contact * mContact; ///< Contact that this constraint was generated from+ CharacterContact * mContact; ///< Contact that this constraint was generated fromfloat mTOI; ///< Calculated time of impact (can be negative if penetrating)float mProjectedVelocity; ///< Velocity of the contact projected on the contact normal (negative if separating)Vec3 mLinearVelocity; ///< Velocity of the contact (can contain a corrective velocity to resolve penetration)@@ -586,10 +587,11 @@ private:};// A collision collector that collects hits for CastShape+ template <bool IgnoreInitialOverlap>class ContactCastCollector : public CastShapeCollector{public:- ContactCastCollector(PhysicsSystem *inSystem, const CharacterVirtual *inCharacter, Vec3Arg inDisplacement, Vec3Arg inUp, const IgnoredContactList &inIgnoredContacts, RVec3Arg inBaseOffset, Contact &outContact) : mBaseOffset(inBaseOffset), mDisplacement(inDisplacement), mUp(inUp), mSystem(inSystem), mCharacter(inCharacter), mIgnoredContacts(inIgnoredContacts), mContact(outContact) { }+ ContactCastCollector(PhysicsSystem *inSystem, const CharacterVirtual *inCharacter, Vec3Arg inDisplacement, Vec3Arg inUp, const IgnoredContactList &inIgnoredContacts, RVec3Arg inBaseOffset, CharacterContact &outContact) : mBaseOffset(inBaseOffset), mDisplacement(inDisplacement), mUp(inUp), mSystem(inSystem), mCharacter(inCharacter), mIgnoredContacts(inIgnoredContacts), mContact(outContact) { }virtual void SetUserData(uint64 inUserData) override { mOtherCharacter = reinterpret_cast<CharacterVirtual *>(inUserData); }@@ -602,13 +604,13 @@ private:const CharacterVirtual * mCharacter;CharacterVirtual * mOtherCharacter = nullptr;const IgnoredContactList & mIgnoredContacts;- Contact & mContact;+ CharacterContact & mContact;};// Helper function to convert a Jolt collision result into a contacttemplate <class taCollector>- inline static void sFillContactProperties(const CharacterVirtual *inCharacter, Contact &outContact, const Body &inBody, Vec3Arg inUp, RVec3Arg inBaseOffset, const taCollector &inCollector, const CollideShapeResult &inResult);- inline static void sFillCharacterContactProperties(Contact &outContact, const CharacterVirtual *inOtherCharacter, RVec3Arg inBaseOffset, const CollideShapeResult &inResult);+ inline static void sFillContactProperties(const CharacterVirtual *inCharacter, CharacterContact &outContact, const Body &inBody, Vec3Arg inUp, RVec3Arg inBaseOffset, const taCollector &inCollector, const CollideShapeResult &inResult);+ inline static void sFillCharacterContactProperties(CharacterContact &outContact, const CharacterVirtual *inOtherCharacter, RVec3Arg inBaseOffset, const CollideShapeResult &inResult);// Move the shape from ioPosition and try to displace it by inVelocity * inDeltaTime, this will try to slide the shape along the world geometryvoid MoveShape(RVec3 &ioPosition, Vec3Arg inVelocity, float inDeltaTime, ContactList *outActiveContacts, const BroadPhaseLayerFilter &inBroadPhaseLayerFilter, const ObjectLayerFilter &inObjectLayerFilter, const BodyFilter &inBodyFilter, const ShapeFilter &inShapeFilter, TempAllocator &inAllocator@@ -618,10 +620,10 @@ private:);// Ask the callback if inContact is a valid contact point- bool ValidateContact(const Contact &inContact) const;+ bool ValidateContact(const CharacterContact &inContact) const;// Trigger the contact callback for inContact and get the contact settings- void ContactAdded(const Contact &inContact, CharacterContactSettings &ioSettings);+ void ContactAdded(const CharacterContact &inContact, CharacterContactSettings &ioSettings);// Tests the shape for collision around inPositionvoid GetContactsAtPosition(RVec3Arg inPosition, Vec3Arg inMovementDirection, const Shape *inShape, TempContactList &outContacts, const BroadPhaseLayerFilter &inBroadPhaseLayerFilter, const ObjectLayerFilter &inObjectLayerFilter, const BodyFilter &inBodyFilter, const ShapeFilter &inShapeFilter) const;@@ -650,8 +652,15 @@ private:// Handle contact with physics object that we're colliding againstbool HandleContact(Vec3Arg inVelocity, Constraint &ioConstraint, float inDeltaTime);- // Does a swept test of the shape from inPosition with displacement inDisplacement, returns true if there was a collision- bool GetFirstContactForSweep(RVec3Arg inPosition, Vec3Arg inDisplacement, Contact &outContact, const IgnoredContactList &inIgnoredContacts, const BroadPhaseLayerFilter &inBroadPhaseLayerFilter, const ObjectLayerFilter &inObjectLayerFilter, const BodyFilter &inBodyFilter, const ShapeFilter &inShapeFilter) const;+ // Does a swept test of the shape from inPosition with displacement inDisplacement, returns true if there was a collision.+ // This sweeps to see if there is enough space for the character to move. Character padding is only applied in the movement direction of the character.+ // Ignores collisions when they already exist at the start of the movement.+ bool ValidateMovement(RVec3Arg inPosition, Vec3Arg inDisplacement, CharacterContact &outContact, const IgnoredContactList &inIgnoredContacts, const BroadPhaseLayerFilter &inBroadPhaseLayerFilter, const ObjectLayerFilter &inObjectLayerFilter, const BodyFilter &inBodyFilter, const ShapeFilter &inShapeFilter) const;++ // Does a swept test of the shape from inPosition with displacement inDisplacement, returns true if there was a collision.+ // This does a full sweep of character including character padding.+ // Includes collisions when they already exist at the start of the movement.+ bool GetFirstContactForSweep(RVec3Arg inPosition, Vec3Arg inDisplacement, CharacterContact &outContact, const IgnoredContactList &inIgnoredContacts, const BroadPhaseLayerFilter &inBroadPhaseLayerFilter, const ObjectLayerFilter &inObjectLayerFilter, const BodyFilter &inBodyFilter, const ShapeFilter &inShapeFilter) const;// Store contacts so that we have proper ground informationvoid StoreActiveContacts(const TempContactList &inContacts, TempAllocator &inAllocator);@@ -660,7 +669,7 @@ private:void UpdateSupportingContact(bool inSkipContactVelocityCheck, TempAllocator &inAllocator);/// This function can be called after moving the character to a new colliding position- void MoveToContact(RVec3Arg inPosition, const Contact &inContact, const BroadPhaseLayerFilter &inBroadPhaseLayerFilter, const ObjectLayerFilter &inObjectLayerFilter, const BodyFilter &inBodyFilter, const ShapeFilter &inShapeFilter, TempAllocator &inAllocator);+ void MoveToContact(RVec3Arg inPosition, const CharacterContact &inContact, const BroadPhaseLayerFilter &inBroadPhaseLayerFilter, const ObjectLayerFilter &inObjectLayerFilter, const BodyFilter &inBodyFilter, const ShapeFilter &inShapeFilter, TempAllocator &inAllocator);// This function returns the actual center of mass of the shape, not corrected for the character paddinginline RMat44 GetCenterOfMassTransform(RVec3Arg inPosition, QuatArg inRotation, const Shape *inShape) const@@ -733,7 +742,7 @@ private:int mCount = 0;};- using ListenerContacts = UnorderedMap<ContactKey, ListenerContactValue>;+ using ListenerContacts = UnorderedMap<CharacterContactKey, ListenerContactValue>;ListenerContacts mListenerContacts;// Remembers the delta time of the last updatediff --git a/thirdparty/jolt_physics/Jolt/Physics/Collision/BroadPhase/ObjectVsBroadPhaseLayerFilterMask.h b/thirdparty/jolt_physics/Jolt/Physics/Collision/BroadPhase/ObjectVsBroadPhaseLayerFilterMask.hindex 20305a5f0ca..f45c6e085f4 100644--- a/thirdparty/jolt_physics/Jolt/Physics/Collision/BroadPhase/ObjectVsBroadPhaseLayerFilterMask.h+++ b/thirdparty/jolt_physics/Jolt/Physics/Collision/BroadPhase/ObjectVsBroadPhaseLayerFilterMask.h@@ -15,7 +15,7 @@ class ObjectVsBroadPhaseLayerFilterMask : public ObjectVsBroadPhaseLayerFilterpublic:JPH_OVERRIDE_NEW_DELETE-/// Constructor+ /// ConstructorObjectVsBroadPhaseLayerFilterMask(const BroadPhaseLayerInterfaceMask &inBroadPhaseLayerInterface) :mBroadPhaseLayerInterface(inBroadPhaseLayerInterface){diff --git a/thirdparty/jolt_physics/Jolt/Physics/Collision/BroadPhase/QuadTree.cpp b/thirdparty/jolt_physics/Jolt/Physics/Collision/BroadPhase/QuadTree.cppindex f3f5d90803a..3b2683d6d47 100644--- a/thirdparty/jolt_physics/Jolt/Physics/Collision/BroadPhase/QuadTree.cpp+++ b/thirdparty/jolt_physics/Jolt/Physics/Collision/BroadPhase/QuadTree.cpp@@ -1000,8 +1000,6 @@ JPH_INLINE void QuadTree::WalkTree(const ObjectLayerFilter &inObjectLayerFilter,ObjectLayer object_layer = inTracking[body_id.GetIndex()].mObjectLayer; // We're not taking a lock on the body, so it may be in the process of being removed so check if the object layer is invalidif (object_layer != cObjectLayerInvalid && inObjectLayerFilter.ShouldCollide(object_layer)){- JPH_PROFILE("VisitBody");-// Track amount of hitsJPH_IF_TRACK_BROADPHASE_STATS(++hits_collected;)diff --git a/thirdparty/jolt_physics/Jolt/Physics/Collision/CastConvexVsTriangles.cpp b/thirdparty/jolt_physics/Jolt/Physics/Collision/CastConvexVsTriangles.cppindex 4fb6c58c185..d62822ab6a5 100644--- a/thirdparty/jolt_physics/Jolt/Physics/Collision/CastConvexVsTriangles.cpp+++ b/thirdparty/jolt_physics/Jolt/Physics/Collision/CastConvexVsTriangles.cpp@@ -58,7 +58,7 @@ void CastConvexVsTriangles::Cast(Vec3Arg inV0, Vec3Arg inV1, Vec3Arg inV2, uint8EPAPenetrationDepth epa;float fraction = mCollector.GetEarlyOutFraction();Vec3 contact_point_a, contact_point_b, contact_normal;- if (epa.CastShape(mShapeCast.mCenterOfMassStart, mShapeCast.mDirection, mShapeCastSettings.mCollisionTolerance, mShapeCastSettings.mPenetrationTolerance, *mSupport, triangle, mSupport->GetConvexRadius(), 0.0f, mShapeCastSettings.mReturnDeepestPoint, fraction, contact_point_a, contact_point_b, contact_normal))+ if (epa.CastShape(mShapeCast.mCenterOfMassStart, mShapeCast.mDirection, mShapeCastSettings.mCollisionTolerance, mShapeCastSettings.mPenetrationTolerance, *mSupport, triangle, mSupport->GetConvexRadius() + mShapeCastSettings.mExtraConvexRadius, 0.0f, mShapeCastSettings.mReturnDeepestPoint, fraction, contact_point_a, contact_point_b, contact_normal)){// Check if we have enabled active edge detectionif (mShapeCastSettings.mActiveEdgeMode == EActiveEdgeMode::CollideOnlyWithActive && inActiveEdges != 0b111)diff --git a/thirdparty/jolt_physics/Jolt/Physics/Collision/CastSphereVsTriangles.cpp b/thirdparty/jolt_physics/Jolt/Physics/Collision/CastSphereVsTriangles.cppindex 990dfa68b90..5b60ee1dace 100644--- a/thirdparty/jolt_physics/Jolt/Physics/Collision/CastSphereVsTriangles.cpp+++ b/thirdparty/jolt_physics/Jolt/Physics/Collision/CastSphereVsTriangles.cpp@@ -30,7 +30,7 @@ CastSphereVsTriangles::CastSphereVsTriangles(const ShapeCast &inShapeCast, constconst SphereShape *sphere = static_cast<const SphereShape *>(inShapeCast.mShape);// Scale the radius- mRadius = sphere->GetRadius() * abs(inShapeCast.mScale.GetX());+ mRadius = sphere->GetRadius() * abs(inShapeCast.mScale.GetX()) + inShapeCastSettings.mExtraConvexRadius;// Determine if shape is inside out or notmScaleSign = ScaleHelpers::IsInsideOut(inScale)? -1.0f : 1.0f;@@ -102,12 +102,12 @@ float CastSphereVsTriangles::RayCylinder(Vec3Arg inRayDirection, Vec3Arg inCylinreturn FLT_MAX; // Segment runs parallel to cylinder axis, stop processing, we will either hit at fraction = 0 or we'll hit a vertexfloat b = axis_len_sq * start.Dot(inRayDirection) - direction_dot_axis * start_dot_axis; // should be multiplied by 2, instead we'll divide a and c by 2 when we solve the quadratic equationfloat c = axis_len_sq * (start.LengthSq() - Square(inRadius)) - Square(start_dot_axis);- float det = Square(b) - a * c; // normally 4 * a * c but since both a and c need to be divided by 2 we lose the 4+ float det = DifferenceOfProducts(b, b, a, c); // normally 4 * a * c but since both a and c need to be divided by 2 we lose the 4if (det < 0.0f)return FLT_MAX; // No solution to quadratic equation// Solve fraction t where the ray hits the cylinder- float t = -(b + sqrt(det)) / a; // normally divided by 2 * a but since a should be divided by 2 we lose the 2+ float t = -(b + Sqrt(det)) / a; // normally divided by 2 * a but since a should be divided by 2 we lose the 2if (t < 0.0f || t > 1.0f)return FLT_MAX; // Intersection lies outside segmentif (start_dot_axis + t * direction_dot_axis < 0.0f || start_dot_axis + t * direction_dot_axis > axis_len_sq)@@ -145,7 +145,7 @@ void CastSphereVsTriangles::Cast(Vec3Arg inV0, Vec3Arg inV1, Vec3Arg inV2, uint8if (q_len_sq <= Square(mRadius)){// Early out if this hit is deeper than the collector's early out value- float q_len = sqrt(q_len_sq);+ float q_len = Sqrt(q_len_sq);float penetration_depth = mRadius - q_len;if (-penetration_depth >= mCollector.GetEarlyOutFraction())return;diff --git a/thirdparty/jolt_physics/Jolt/Physics/Collision/CollideSphereVsTriangles.cpp b/thirdparty/jolt_physics/Jolt/Physics/Collision/CollideSphereVsTriangles.cppindex 566efb38aec..998d0afbc90 100644--- a/thirdparty/jolt_physics/Jolt/Physics/Collision/CollideSphereVsTriangles.cpp+++ b/thirdparty/jolt_physics/Jolt/Physics/Collision/CollideSphereVsTriangles.cpp@@ -68,7 +68,7 @@ void CollideSphereVsTriangles::Collide(Vec3Arg inV0, Vec3Arg inV1, Vec3Arg inV2,return;// Calculate penetration depth- float penetration_depth = mRadius - sqrt(point2_len_sq);+ float penetration_depth = mRadius - Sqrt(point2_len_sq);if (-penetration_depth >= mCollector.GetEarlyOutFraction())return;diff --git a/thirdparty/jolt_physics/Jolt/Physics/Collision/CollisionGroup.h b/thirdparty/jolt_physics/Jolt/Physics/Collision/CollisionGroup.hindex 938e686f6ec..6fcb18d5671 100644--- a/thirdparty/jolt_physics/Jolt/Physics/Collision/CollisionGroup.h+++ b/thirdparty/jolt_physics/Jolt/Physics/Collision/CollisionGroup.h@@ -33,6 +33,18 @@ public:/// Construct with all propertiesCollisionGroup(const GroupFilter *inFilter, GroupID inGroupID, SubGroupID inSubGroupID) : mGroupFilter(inFilter), mGroupID(inGroupID), mSubGroupID(inSubGroupID) { }++ /// Test if two collision groups are equal+ bool operator == (const CollisionGroup &inRHS) const+ {+ return mGroupFilter == inRHS.mGroupFilter && mGroupID == inRHS.mGroupID && mSubGroupID == inRHS.mSubGroupID;+ }++ bool operator != (const CollisionGroup &inRHS) const+ {+ return !(*this == inRHS);+ }+/// Set the collision group filterinline void SetGroupFilter(const GroupFilter *inFilter){diff --git a/thirdparty/jolt_physics/Jolt/Physics/Collision/EstimateCollisionResponse.cpp b/thirdparty/jolt_physics/Jolt/Physics/Collision/EstimateCollisionResponse.cppindex 53cf12b5d41..4ac92eeb47e 100644--- a/thirdparty/jolt_physics/Jolt/Physics/Collision/EstimateCollisionResponse.cpp+++ b/thirdparty/jolt_physics/Jolt/Physics/Collision/EstimateCollisionResponse.cpp@@ -6,20 +6,16 @@#include <Jolt/Physics/Collision/EstimateCollisionResponse.h>#include <Jolt/Physics/Body/Body.h>+#include <Jolt/Physics/Constraints/ConstraintPart/ContactConstraintPart.h>+#include <Jolt/Physics/Constraints/ConstraintPart/AngularFrictionConstraintPart.h>JPH_NAMESPACE_BEGINvoid EstimateCollisionResponse(const Body &inBody1, const Body &inBody2, const ContactManifold &inManifold, CollisionEstimationResult &outResult, float inCombinedFriction, float inCombinedRestitution, float inMinVelocityForRestitution, uint inNumIterations){- // Note this code is based on AxisConstraintPart, see that class for more comments on the math-ContactPoints::size_type num_points = inManifold.mRelativeContactPointsOn1.size();JPH_ASSERT(num_points == inManifold.mRelativeContactPointsOn2.size());- // Start with zero impulses- outResult.mImpulses.resize(num_points);- memset(outResult.mImpulses.data(), 0, num_points * sizeof(CollisionEstimationResult::Impulse));-// Calculate friction directionsoutResult.mTangent1 = inManifold.mWorldSpaceNormal.GetNormalizedPerpendicular();outResult.mTangent2 = inManifold.mWorldSpaceNormal.Cross(outResult.mTangent1);@@ -74,82 +70,25 @@ void EstimateCollisionResponse(const Body &inBody1, const Body &inBody2, const CVec3 com1 = Vec3(inBody1.GetCenterOfMassPosition() - inManifold.mBaseOffset);Vec3 com2 = Vec3(inBody2.GetCenterOfMassPosition() - inManifold.mBaseOffset);- struct AxisConstraint- {- inline void Initialize(Vec3Arg inR1, Vec3Arg inR2, Vec3Arg inWorldSpaceNormal, float inInvM1, float inInvM2, Mat44Arg inInvI1, Mat44Arg inInvI2)- {- // Calculate effective mass: K^-1 = (J M^-1 J^T)^-1- mR1PlusUxAxis = inR1.Cross(inWorldSpaceNormal);- mR2xAxis = inR2.Cross(inWorldSpaceNormal);- mInvI1_R1PlusUxAxis = inInvI1.Multiply3x3(mR1PlusUxAxis);- mInvI2_R2xAxis = inInvI2.Multiply3x3(mR2xAxis);- mEffectiveMass = 1.0f / (inInvM1 + mInvI1_R1PlusUxAxis.Dot(mR1PlusUxAxis) + inInvM2 + mInvI2_R2xAxis.Dot(mR2xAxis));- mBias = 0.0f;- }-- inline float SolveGetLambda(Vec3Arg inWorldSpaceNormal, const CollisionEstimationResult &inResult) const- {- // Calculate jacobian multiplied by linear/angular velocity- float jv = inWorldSpaceNormal.Dot(inResult.mLinearVelocity1 - inResult.mLinearVelocity2) + mR1PlusUxAxis.Dot(inResult.mAngularVelocity1) - mR2xAxis.Dot(inResult.mAngularVelocity2);-- // Lagrange multiplier is:- //- // lambda = -K^-1 (J v + b)- return mEffectiveMass * (jv - mBias);- }-- inline void SolveApplyLambda(Vec3Arg inWorldSpaceNormal, float inInvM1, float inInvM2, float inLambda, CollisionEstimationResult &ioResult) const- {- // Apply impulse to body velocities- ioResult.mLinearVelocity1 -= (inLambda * inInvM1) * inWorldSpaceNormal;- ioResult.mAngularVelocity1 -= inLambda * mInvI1_R1PlusUxAxis;- ioResult.mLinearVelocity2 += (inLambda * inInvM2) * inWorldSpaceNormal;- ioResult.mAngularVelocity2 += inLambda * mInvI2_R2xAxis;- }-- inline void Solve(Vec3Arg inWorldSpaceNormal, float inInvM1, float inInvM2, float inMinLambda, float inMaxLambda, float &ioTotalLambda, CollisionEstimationResult &ioResult) const- {- // Calculate new total lambda- float total_lambda = ioTotalLambda + SolveGetLambda(inWorldSpaceNormal, ioResult);-- // Clamp impulse- total_lambda = Clamp(total_lambda, inMinLambda, inMaxLambda);-- SolveApplyLambda(inWorldSpaceNormal, inInvM1, inInvM2, total_lambda - ioTotalLambda, ioResult);-- ioTotalLambda = total_lambda;- }-- Vec3 mR1PlusUxAxis;- Vec3 mR2xAxis;- Vec3 mInvI1_R1PlusUxAxis;- Vec3 mInvI2_R2xAxis;- float mEffectiveMass;- float mBias;- };-- struct Constraint- {- AxisConstraint mContact;- AxisConstraint mFriction1;- AxisConstraint mFriction2;- };-// Initialize the constraint properties- Constraint constraints[ContactPoints::Capacity];+ ContactConstraintPart<EMotionType::Dynamic, EMotionType::Dynamic> contact_constraints[ContactPoints::Capacity];+ Vec3 contact_points[ContactPoints::Capacity];+ Vec3 friction_point = Vec3::sZero();for (uint c = 0; c < num_points; ++c){- Constraint &constraint = constraints[c];-// Calculate contact points relative to body 1 and 2Vec3 p = 0.5f * (inManifold.mRelativeContactPointsOn1[c] + inManifold.mRelativeContactPointsOn2[c]);++ // Calculate friction point+ contact_points[c] = p;+ friction_point += p;++ // Calculate contact point relative to comVec3 r1 = p - com1;Vec3 r2 = p - com2;- // Initialize contact constraint- constraint.mContact.Initialize(r1, r2, inManifold.mWorldSpaceNormal, inv_m1, inv_m2, inv_i1, inv_i2);-// Handle elastic collisions+ float bias = 0.0f;if (inCombinedRestitution > 0.0f){// Calculate velocity of contact point@@ -158,15 +97,42 @@ void EstimateCollisionResponse(const Body &inBody1, const Body &inBody2, const C// If it is big enough, apply restitutionif (normal_velocity < -inMinVelocityForRestitution)- constraint.mContact.mBias = inCombinedRestitution * normal_velocity;+ bias = inCombinedRestitution * normal_velocity;}- if (inCombinedFriction > 0.0f)- {- // Initialize friction constraints- constraint.mFriction1.Initialize(r1, r2, outResult.mTangent1, inv_m1, inv_m2, inv_i1, inv_i2);- constraint.mFriction2.Initialize(r1, r2, outResult.mTangent2, inv_m1, inv_m2, inv_i1, inv_i2);- }+ // Initialize contact constraint+ ContactConstraintPart<EMotionType::Dynamic, EMotionType::Dynamic> &constraint = contact_constraints[c];+ constraint.SetTotalLambda(0.0f);+ constraint.CalculateConstraintProperties(inv_m1, inv_i1, r1, inv_m2, inv_i2, r2, inManifold.mWorldSpaceNormal, bias);+ }++ // Calculate distance to friction center for each point+ float num_points_f = float(num_points);+ friction_point /= num_points_f;+ float distance_to_friction_center[ContactPoints::Capacity];+ for (uint c = 0; c < num_points; ++c)+ {+ Vec3 delta = contact_points[c] - friction_point;+ distance_to_friction_center[c] = (delta - delta.Dot(inManifold.mWorldSpaceNormal) * inManifold.mWorldSpaceNormal).Length();+ }+ outResult.mFrictionPoint = friction_point;++ // Initialize friction constraints+ ContactConstraintPart<EMotionType::Dynamic, EMotionType::Dynamic> friction1, friction2;+ AngularFrictionConstraintPart<EMotionType::Dynamic, EMotionType::Dynamic> angular_friction;+ angular_friction.SetTotalLambda(0.0f);+ friction1.SetTotalLambda(0.0f);+ friction2.SetTotalLambda(0.0f);+ if (inCombinedFriction > 0.0f)+ {+ Vec3 r1 = friction_point - com1;+ Vec3 r2 = friction_point - com2;++ friction1.CalculateConstraintProperties(inv_m1, inv_i1, r1, inv_m2, inv_i2, r2, outResult.mTangent1);+ friction2.CalculateConstraintProperties(inv_m1, inv_i1, r1, inv_m2, inv_i2, r2, outResult.mTangent2);++ if (num_points > 1)+ angular_friction.CalculateConstraintProperties(inv_i1, inv_i2, inManifold.mWorldSpaceNormal);}// If there's only 1 contact point, we only need 1 iteration@@ -176,38 +142,53 @@ void EstimateCollisionResponse(const Body &inBody1, const Body &inBody2, const Cfor (int iteration = 0; iteration < num_iterations; ++iteration){// Solve friction constraints first- if (inCombinedFriction > 0.0f && iteration > 0) // For first iteration the contact impulse is zero so there's no point in applying friction+ if (inCombinedFriction > 0.0f)+ {+ // Calculate max impulse that can be applied+ float max_linear_lambda = 0.0f, max_angular_lambda = 0.0f;for (uint c = 0; c < num_points; ++c){- const Constraint &constraint = constraints[c];- CollisionEstimationResult::Impulse &impulse = outResult.mImpulses[c];-- float lambda1 = impulse.mFrictionImpulse1 + constraint.mFriction1.SolveGetLambda(outResult.mTangent1, outResult);- float lambda2 = impulse.mFrictionImpulse2 + constraint.mFriction2.SolveGetLambda(outResult.mTangent2, outResult);+ float lambda = contact_constraints[c].GetTotalLambda();+ max_linear_lambda += lambda;+ max_angular_lambda += distance_to_friction_center[c] * lambda;+ }+ max_linear_lambda *= inCombinedFriction;+ max_angular_lambda *= inCombinedFriction;- // Calculate max impulse based on contact impulse- float max_impulse = inCombinedFriction * impulse.mContactImpulse;+ // Calculate impulse to stop motion in tangential direction+ float lambda1 = friction1.SolveVelocityConstraintGetTotalLambda(outResult.mLinearVelocity1, outResult.mAngularVelocity1, outResult.mLinearVelocity2, outResult.mAngularVelocity2, outResult.mTangent1);+ float lambda2 = friction2.SolveVelocityConstraintGetTotalLambda(outResult.mLinearVelocity1, outResult.mAngularVelocity1, outResult.mLinearVelocity2, outResult.mAngularVelocity2, outResult.mTangent2);- // If the total lambda that we will apply is too large, scale it back- float total_lambda_sq = Square(lambda1) + Square(lambda2);- if (total_lambda_sq > Square(max_impulse))- {- float scale = max_impulse / sqrt(total_lambda_sq);- lambda1 *= scale;- lambda2 *= scale;- }+ // If the total lambda that we will apply is too large, scale it back+ float total_lambda_sq = Square(lambda1) + Square(lambda2);+ if (total_lambda_sq > Square(max_linear_lambda))+ {+ float scale = max_linear_lambda / Sqrt(total_lambda_sq);+ lambda1 *= scale;+ lambda2 *= scale;+ }- constraint.mFriction1.SolveApplyLambda(outResult.mTangent1, inv_m1, inv_m2, lambda1 - impulse.mFrictionImpulse1, outResult);- constraint.mFriction2.SolveApplyLambda(outResult.mTangent2, inv_m1, inv_m2, lambda2 - impulse.mFrictionImpulse2, outResult);+ // Apply the friction impulse+ friction1.SolveVelocityConstraintApplyLambda(outResult.mLinearVelocity1, outResult.mAngularVelocity1, outResult.mLinearVelocity2, outResult.mAngularVelocity2, inv_m1, inv_m2, outResult.mTangent1, lambda1);+ friction2.SolveVelocityConstraintApplyLambda(outResult.mLinearVelocity1, outResult.mAngularVelocity1, outResult.mLinearVelocity2, outResult.mAngularVelocity2, inv_m1, inv_m2, outResult.mTangent2, lambda2);- impulse.mFrictionImpulse1 = lambda1;- impulse.mFrictionImpulse2 = lambda2;- }+ // Apply angular friction+ if (num_points > 1)+ angular_friction.SolveVelocityConstraint(outResult.mAngularVelocity1, outResult.mAngularVelocity2, inManifold.mWorldSpaceNormal, -max_angular_lambda, max_angular_lambda);+ }// Solve contact constraints lastfor (uint c = 0; c < num_points; ++c)- constraints[c].mContact.Solve(inManifold.mWorldSpaceNormal, inv_m1, inv_m2, 0.0f, FLT_MAX, outResult.mImpulses[c].mContactImpulse, outResult);+ contact_constraints[c].SolveVelocityConstraint(outResult.mLinearVelocity1, outResult.mAngularVelocity1, outResult.mLinearVelocity2, outResult.mAngularVelocity2, inv_m1, inv_m2, inManifold.mWorldSpaceNormal, 0.0f, FLT_MAX);}++ // Store impulses+ outResult.mContactImpulse.resize(num_points);+ for (uint c = 0; c < num_points; ++c)+ outResult.mContactImpulse[c] = contact_constraints[c].GetTotalLambda();+ outResult.mFrictionImpulse1 = friction1.GetTotalLambda();+ outResult.mFrictionImpulse2 = friction2.GetTotalLambda();+ outResult.mAngularFrictionImpulse = angular_friction.GetTotalLambda();}JPH_NAMESPACE_ENDdiff --git a/thirdparty/jolt_physics/Jolt/Physics/Collision/EstimateCollisionResponse.h b/thirdparty/jolt_physics/Jolt/Physics/Collision/EstimateCollisionResponse.hindex 45098d1477e..14f119fa5f7 100644--- a/thirdparty/jolt_physics/Jolt/Physics/Collision/EstimateCollisionResponse.h+++ b/thirdparty/jolt_physics/Jolt/Physics/Collision/EstimateCollisionResponse.h@@ -16,19 +16,15 @@ struct CollisionEstimationResultVec3 mLinearVelocity2; ///< The estimated linear velocity of body 2 after collisionVec3 mAngularVelocity2; ///< The estimated angular velocity of body 2 after collision+ Vec3 mFrictionPoint; ///< Point at which friction was applied (relative to mBaseOffset of the manifold)Vec3 mTangent1; ///< Normalized tangent of contact normalVec3 mTangent2; ///< Second normalized tangent of contact normal (forms a basis with mTangent1 and mWorldSpaceNormal)- struct Impulse- {- float mContactImpulse; ///< Estimated contact impulses (kg m / s)- float mFrictionImpulse1; ///< Estimated friction impulses in the direction of tangent 1 (kg m / s)- float mFrictionImpulse2; ///< Estimated friction impulses in the direction of tangent 2 (kg m / s)- };+ float mFrictionImpulse1 = 0; ///< Estimated friction impulses in the direction of tangent 1 (kg m / s)+ float mFrictionImpulse2 = 0; ///< Estimated friction impulses in the direction of tangent 2 (kg m / s)+ float mAngularFrictionImpulse = 0; ///< Estimated angular friction impulse around the world space normal (kg m^2 / s)- using Impulses = StaticArray<Impulse, ContactPoints::Capacity>;-- Impulses mImpulses;+ StaticArray<float, ContactPoints::Capacity> mContactImpulse; ///< Estimated contact impulses (kg m / s)};/// This function estimates the contact impulses and body velocity changes as a result of a collision.diff --git a/thirdparty/jolt_physics/Jolt/Physics/Collision/NarrowPhaseQuery.cpp b/thirdparty/jolt_physics/Jolt/Physics/Collision/NarrowPhaseQuery.cppindex 1a8c2c784e6..c1da1a2afed 100644--- a/thirdparty/jolt_physics/Jolt/Physics/Collision/NarrowPhaseQuery.cpp+++ b/thirdparty/jolt_physics/Jolt/Physics/Collision/NarrowPhaseQuery.cpp@@ -376,9 +376,13 @@ void NarrowPhaseQuery::CastShape(const RShapeCast &inShapeCast, const ShapeCastSconst ShapeFilter & mShapeFilter;};+ // Calculate bounds for shape and expand by extra convex radius+ AABox bounds = inShapeCast.mShapeWorldBounds;+ bounds.ExpandBy(Vec3::sReplicate(inShapeCastSettings.mExtraConvexRadius));+// Do broadphase testMyCollector collector(inShapeCast, inShapeCastSettings, inBaseOffset, ioCollector, *mBodyLockInterface, inBodyFilter, inShapeFilter);- mBroadPhaseQuery->CastAABox({ inShapeCast.mShapeWorldBounds, inShapeCast.mDirection }, collector, inBroadPhaseLayerFilter, inObjectLayerFilter);+ mBroadPhaseQuery->CastAABox({ bounds, inShapeCast.mDirection }, collector, inBroadPhaseLayerFilter, inObjectLayerFilter);}void NarrowPhaseQuery::CollectTransformedShapes(const AABox &inBox, TransformedShapeCollector &ioCollector, const BroadPhaseLayerFilter &inBroadPhaseLayerFilter, const ObjectLayerFilter &inObjectLayerFilter, const BodyFilter &inBodyFilter, const ShapeFilter &inShapeFilter) constdiff --git a/thirdparty/jolt_physics/Jolt/Physics/Collision/Shape/CapsuleShape.h b/thirdparty/jolt_physics/Jolt/Physics/Collision/Shape/CapsuleShape.hindex 77af7eceb61..1645ca83f46 100644--- a/thirdparty/jolt_physics/Jolt/Physics/Collision/Shape/CapsuleShape.h+++ b/thirdparty/jolt_physics/Jolt/Physics/Collision/Shape/CapsuleShape.h@@ -26,7 +26,8 @@ public:/// Checks if the settings of this capsule make this shape a spherebool IsSphere() const { return mHalfHeightOfCylinder == 0.0f; }- // See: ShapeSettings+ /// Create a shape according to the settings specified by this object.+ /// Note when mHalfHeightOfCylinder is 0, this will create a SphereShape instead of a CapsuleShape.virtual ShapeResult Create() const override;float mRadius = 0.0f;diff --git a/thirdparty/jolt_physics/Jolt/Physics/Collision/Shape/CompoundShapeVisitors.h b/thirdparty/jolt_physics/Jolt/Physics/Collision/Shape/CompoundShapeVisitors.hindex b5686737a60..e85d2911af8 100644--- a/thirdparty/jolt_physics/Jolt/Physics/Collision/Shape/CompoundShapeVisitors.h+++ b/thirdparty/jolt_physics/Jolt/Physics/Collision/Shape/CompoundShapeVisitors.h@@ -154,7 +154,7 @@ struct CompoundShape::CastShapeVisitor{JPH_INLINE CastShapeVisitor(const ShapeCast &inShapeCast, const ShapeCastSettings &inShapeCastSettings, const CompoundShape *inShape, Vec3Arg inScale, const ShapeFilter &inShapeFilter, Mat44Arg inCenterOfMassTransform2, const SubShapeIDCreator &inSubShapeIDCreator1, const SubShapeIDCreator &inSubShapeIDCreator2, CastShapeCollector &ioCollector) :mBoxCenter(inShapeCast.mShapeWorldBounds.GetCenter()),- mBoxExtent(inShapeCast.mShapeWorldBounds.GetExtent()),+ mBoxExtent(inShapeCast.mShapeWorldBounds.GetExtent() + Vec3::sReplicate(inShapeCastSettings.mExtraConvexRadius)),mScale(inScale),mShapeCast(inShapeCast),mShapeCastSettings(inShapeCastSettings),diff --git a/thirdparty/jolt_physics/Jolt/Physics/Collision/Shape/ConvexShape.cpp b/thirdparty/jolt_physics/Jolt/Physics/Collision/Shape/ConvexShape.cppindex ede12d31bde..803ec0ec566 100644--- a/thirdparty/jolt_physics/Jolt/Physics/Collision/Shape/ConvexShape.cpp+++ b/thirdparty/jolt_physics/Jolt/Physics/Collision/Shape/ConvexShape.cpp@@ -280,9 +280,9 @@ void ConvexShape::sCastConvexVsConvex(const ShapeCast &inShapeCast, const ShapeCEPAPenetrationDepth epa;float fraction = ioCollector.GetEarlyOutFraction();Vec3 contact_point_a, contact_point_b, contact_normal;- if (epa.CastShape(inShapeCast.mCenterOfMassStart, inShapeCast.mDirection, inShapeCastSettings.mCollisionTolerance, inShapeCastSettings.mPenetrationTolerance, *cast_support, *target_support, cast_support->GetConvexRadius(), target_support->GetConvexRadius(), inShapeCastSettings.mReturnDeepestPoint, fraction, contact_point_a, contact_point_b, contact_normal)+ if (epa.CastShape(inShapeCast.mCenterOfMassStart, inShapeCast.mDirection, inShapeCastSettings.mCollisionTolerance, inShapeCastSettings.mPenetrationTolerance, *cast_support, *target_support, cast_support->GetConvexRadius() + inShapeCastSettings.mExtraConvexRadius, target_support->GetConvexRadius(), inShapeCastSettings.mReturnDeepestPoint, fraction, contact_point_a, contact_point_b, contact_normal)&& (inShapeCastSettings.mBackFaceModeConvex == EBackFaceMode::CollideWithBackFaces- || contact_normal.Dot(inShapeCast.mDirection) > 0.0f)) // Test if backfacing+ || contact_normal.Dot(inShapeCast.mDirection) >= 0.0f)) // Test if backfacing{// Convert to world spacecontact_point_a = inCenterOfMassTransform2 * contact_point_a;diff --git a/thirdparty/jolt_physics/Jolt/Physics/Collision/Shape/CylinderShape.cpp b/thirdparty/jolt_physics/Jolt/Physics/Collision/Shape/CylinderShape.cppindex 826df0dd6d3..6c28c8ba6c7 100644--- a/thirdparty/jolt_physics/Jolt/Physics/Collision/Shape/CylinderShape.cpp+++ b/thirdparty/jolt_physics/Jolt/Physics/Collision/Shape/CylinderShape.cpp@@ -143,7 +143,7 @@ public:// A Fast and Robust GJK Implementation for Collision Detection of Convex Objects - Gino van den Bergen// page 8float x = inDirection.GetX(), y = inDirection.GetY(), z = inDirection.GetZ();- float o = sqrt(Square(x) + Square(z));+ float o = Sqrt(Square(x) + Square(z));if (o > 0.0f)return Vec3((mRadius * x) / o, Sign(y) * mHalfHeight, (mRadius * z) / o);else@@ -207,7 +207,7 @@ void CylinderShape::GetSupportingFace(const SubShapeID &inSubShapeID, Vec3Arg inif (xz_sq > y_sq){// Hitting side- float f = -scaled_radius / sqrt(xz_sq);+ float f = -scaled_radius / Sqrt(xz_sq);float vx = x * f;float vz = z * f;outVertices.push_back(inCenterOfMassTransform * Vec3(vx, scaled_half_height, vz));@@ -222,7 +222,7 @@ void CylinderShape::GetSupportingFace(const SubShapeID &inSubShapeID, Vec3Arg inMat44 transform = inCenterOfMassTransform;if (xz_sq > 0.00765427f * y_sq){- Vec4 base_x = Vec4(x, 0, z, 0) / sqrt(xz_sq);+ Vec4 base_x = Vec4(x, 0, z, 0) / Sqrt(xz_sq);Vec4 base_z = base_x.Swizzle<SWIZZLE_Z, SWIZZLE_Y, SWIZZLE_X, SWIZZLE_W>() * Vec4(-1, 0, 1, 0);transform = transform * Mat44(base_x, Vec4(0, 1, 0, 0), base_z, Vec4(0, 0, 0, 1));}diff --git a/thirdparty/jolt_physics/Jolt/Physics/Collision/Shape/HeightFieldShape.cpp b/thirdparty/jolt_physics/Jolt/Physics/Collision/Shape/HeightFieldShape.cppindex d859b22e161..0907fee7e66 100644--- a/thirdparty/jolt_physics/Jolt/Physics/Collision/Shape/HeightFieldShape.cpp+++ b/thirdparty/jolt_physics/Jolt/Physics/Collision/Shape/HeightFieldShape.cpp@@ -2355,7 +2355,7 @@ void HeightFieldShape::sCastConvexVsHeightField(const ShapeCast &inShapeCast, covisitor.mShape2 = shape;visitor.mInvDirection.Set(inShapeCast.mDirection);visitor.mBoxCenter = inShapeCast.mShapeWorldBounds.GetCenter();- visitor.mBoxExtent = inShapeCast.mShapeWorldBounds.GetExtent();+ visitor.mBoxExtent = inShapeCast.mShapeWorldBounds.GetExtent() + Vec3::sReplicate(inShapeCastSettings.mExtraConvexRadius);visitor.mSubShapeIDCreator2 = inSubShapeIDCreator2;shape->WalkHeightField(visitor);}diff --git a/thirdparty/jolt_physics/Jolt/Physics/Collision/Shape/MeshShape.cpp b/thirdparty/jolt_physics/Jolt/Physics/Collision/Shape/MeshShape.cppindex 8297285e831..3c95a61af72 100644--- a/thirdparty/jolt_physics/Jolt/Physics/Collision/Shape/MeshShape.cpp+++ b/thirdparty/jolt_physics/Jolt/Physics/Collision/Shape/MeshShape.cpp@@ -26,6 +26,7 @@#include <Jolt/Core/StreamOut.h>#include <Jolt/Core/Profiler.h>#include <Jolt/Core/UnorderedMap.h>+#include <Jolt/Core/UnorderedSet.h>#include <Jolt/Geometry/AABox4.h>#include <Jolt/Geometry/RayAABox.h>#include <Jolt/Geometry/Indexify.h>@@ -930,7 +931,7 @@ void MeshShape::sCastConvexVsMesh(const ShapeCast &inShapeCast, const ShapeCastSVisitor visitor(inShapeCast, inShapeCastSettings, inScale, inCenterOfMassTransform2, inSubShapeIDCreator1, ioCollector);visitor.mInvDirection.Set(inShapeCast.mDirection);visitor.mBoxCenter = inShapeCast.mShapeWorldBounds.GetCenter();- visitor.mBoxExtent = inShapeCast.mShapeWorldBounds.GetExtent();+ visitor.mBoxExtent = inShapeCast.mShapeWorldBounds.GetExtent() + Vec3::sReplicate(inShapeCastSettings.mExtraConvexRadius);shape->WalkTreePerTriangle(inSubShapeIDCreator2, visitor);}diff --git a/thirdparty/jolt_physics/Jolt/Physics/Collision/Shape/PlaneShape.cpp b/thirdparty/jolt_physics/Jolt/Physics/Collision/Shape/PlaneShape.cppindex c1401fd7fcc..7a43b56e6bb 100644--- a/thirdparty/jolt_physics/Jolt/Physics/Collision/Shape/PlaneShape.cpp+++ b/thirdparty/jolt_physics/Jolt/Physics/Collision/Shape/PlaneShape.cpp@@ -166,8 +166,6 @@ void PlaneShape::Draw(DebugRenderer *inRenderer, RMat44Arg inCenterOfMassTransfobool PlaneShape::CastRay(const RayCast &inRay, const SubShapeIDCreator &inSubShapeIDCreator, RayCastResult &ioHit) const{- JPH_PROFILE_FUNCTION();-// Test starting inside of negative half spacefloat distance = mPlane.SignedDistance(inRay.mOrigin);if (distance <= 0.0f)@@ -196,8 +194,6 @@ bool PlaneShape::CastRay(const RayCast &inRay, const SubShapeIDCreator &inSubShavoid PlaneShape::CastRay(const RayCast &inRay, const RayCastSettings &inRayCastSettings, const SubShapeIDCreator &inSubShapeIDCreator, CastRayCollector &ioCollector, const ShapeFilter &inShapeFilter) const{- JPH_PROFILE_FUNCTION();-// Test shape filterif (!inShapeFilter.ShouldCollide(this, inSubShapeIDCreator.GetID()))return;@@ -235,8 +231,6 @@ void PlaneShape::CastRay(const RayCast &inRay, const RayCastSettings &inRayCastSvoid PlaneShape::CollidePoint(Vec3Arg inPoint, const SubShapeIDCreator &inSubShapeIDCreator, CollidePointCollector &ioCollector, const ShapeFilter &inShapeFilter) const{- JPH_PROFILE_FUNCTION();-// Test shape filterif (!inShapeFilter.ShouldCollide(this, inSubShapeIDCreator.GetID()))return;@@ -248,8 +242,6 @@ void PlaneShape::CollidePoint(Vec3Arg inPoint, const SubShapeIDCreator &inSubShavoid PlaneShape::CollideSoftBodyVertices(Mat44Arg inCenterOfMassTransform, Vec3Arg inScale, const CollideSoftBodyVertexIterator &inVertices, uint inNumVertices, int inCollidingShapeIndex) const{- JPH_PROFILE_FUNCTION();-// Convert plane to world spacePlane plane = mPlane.Scaled(inScale).GetTransformed(inCenterOfMassTransform);@@ -290,8 +282,6 @@ inline static void sGetSupportingFace(const ConvexShape *inShape, Vec3Arg inShapvoid PlaneShape::sCastConvexVsPlane(const ShapeCast &inShapeCast, const ShapeCastSettings &inShapeCastSettings, const Shape *inShape, Vec3Arg inScale, [[maybe_unused]] const ShapeFilter &inShapeFilter, Mat44Arg inCenterOfMassTransform2, const SubShapeIDCreator &inSubShapeIDCreator1, const SubShapeIDCreator &inSubShapeIDCreator2, CastShapeCollector &ioCollector){- JPH_PROFILE_FUNCTION();-// Get the shapesJPH_ASSERT(inShapeCast.mShape->GetType() == EShapeType::Convex);JPH_ASSERT(inShape->GetType() == EShapeType::Plane);@@ -310,7 +300,7 @@ void PlaneShape::sCastConvexVsPlane(const ShapeCast &inShapeCast, const ShapeCasVec3 normal_in_convex_shape_space = inShapeCast.mCenterOfMassStart.Multiply3x3Transposed(normal);Vec3 support_point = inShapeCast.mCenterOfMassStart * shape1_support->GetSupport(-normal_in_convex_shape_space);float signed_distance = plane.SignedDistance(support_point);- float convex_radius = shape1_support->GetConvexRadius();+ float convex_radius = shape1_support->GetConvexRadius() + inShapeCastSettings.mExtraConvexRadius;float penetration_depth = -signed_distance + convex_radius;float dot = inShapeCast.mDirection.Dot(normal);@@ -444,8 +434,6 @@ int PlaneShape::GetTrianglesNext(GetTrianglesContext &ioContext, int inMaxTriangvoid PlaneShape::sCollideConvexVsPlane(const Shape *inShape1, const Shape *inShape2, Vec3Arg inScale1, Vec3Arg inScale2, Mat44Arg inCenterOfMassTransform1, Mat44Arg inCenterOfMassTransform2, const SubShapeIDCreator &inSubShapeIDCreator1, const SubShapeIDCreator &inSubShapeIDCreator2, const CollideShapeSettings &inCollideShapeSettings, CollideShapeCollector &ioCollector, [[maybe_unused]] const ShapeFilter &inShapeFilter){- JPH_PROFILE_FUNCTION();-// Get the shapesJPH_ASSERT(inShape1->GetType() == EShapeType::Convex);JPH_ASSERT(inShape2->GetType() == EShapeType::Plane);diff --git a/thirdparty/jolt_physics/Jolt/Physics/Collision/Shape/Shape.cpp b/thirdparty/jolt_physics/Jolt/Physics/Collision/Shape/Shape.cppindex e5af580bb0d..b646b324c9f 100644--- a/thirdparty/jolt_physics/Jolt/Physics/Collision/Shape/Shape.cpp+++ b/thirdparty/jolt_physics/Jolt/Physics/Collision/Shape/Shape.cpp@@ -12,9 +12,8 @@#include <Jolt/Physics/Collision/RayCast.h>#include <Jolt/Physics/Collision/CastResult.h>#include <Jolt/Physics/Collision/CollidePointResult.h>-#include <Jolt/Core/StreamIn.h>-#include <Jolt/Core/StreamOut.h>-#include <Jolt/Core/Factory.h>+#include <Jolt/Core/StreamUtils.h>+#include <Jolt/Core/UnorderedSet.h>#include <Jolt/ObjectStream/TypeDeclarations.h>JPH_NAMESPACE_BEGINdiff --git a/thirdparty/jolt_physics/Jolt/Physics/Collision/Shape/Shape.h b/thirdparty/jolt_physics/Jolt/Physics/Collision/Shape/Shape.hindex 4d9bb5354b8..3832306c4bb 100644--- a/thirdparty/jolt_physics/Jolt/Physics/Collision/Shape/Shape.h+++ b/thirdparty/jolt_physics/Jolt/Physics/Collision/Shape/Shape.h@@ -13,9 +13,8 @@#include <Jolt/Core/Color.h>#include <Jolt/Core/Result.h>#include <Jolt/Core/NonCopyable.h>-#include <Jolt/Core/UnorderedMap.h>-#include <Jolt/Core/UnorderedSet.h>-#include <Jolt/Core/StreamUtils.h>+#include <Jolt/Core/UnorderedSetFwd.h>+#include <Jolt/Core/ObjectToIDMap.h>#include <Jolt/ObjectStream/SerializableObject.h>JPH_NAMESPACE_BEGINdiff --git a/thirdparty/jolt_physics/Jolt/Physics/Collision/Shape/SphereShape.cpp b/thirdparty/jolt_physics/Jolt/Physics/Collision/Shape/SphereShape.cppindex 00bf4ee35f7..bae5f689d5d 100644--- a/thirdparty/jolt_physics/Jolt/Physics/Collision/Shape/SphereShape.cpp+++ b/thirdparty/jolt_physics/Jolt/Physics/Collision/Shape/SphereShape.cpp@@ -198,7 +198,7 @@ void SphereShape::GetSubmergedVolume(Mat44Arg inCenterOfMassTransform, Vec3Arg iif (sDrawSubmergedVolumes){Vec3 circle_center = inCenterOfMassTransform.GetTranslation() - distance_to_surface * inSurface.GetNormal();- float circle_radius = sqrt(Square(scaled_radius) - Square(distance_to_surface));+ float circle_radius = Sqrt(Square(scaled_radius) - Square(distance_to_surface));DebugRenderer::sInstance->DrawPie(inBaseOffset + circle_center, circle_radius, inSurface.GetNormal(), inSurface.GetNormal().GetNormalizedPerpendicular(), -JPH_PI, JPH_PI, Color::sGreen, DebugRenderer::ECastShadow::Off);}#endif // JPH_DEBUG_RENDERERdiff --git a/thirdparty/jolt_physics/Jolt/Physics/Collision/Shape/StaticCompoundShape.h b/thirdparty/jolt_physics/Jolt/Physics/Collision/Shape/StaticCompoundShape.hindex ea0a86fd3ba..509b33a5f9a 100644--- a/thirdparty/jolt_physics/Jolt/Physics/Collision/Shape/StaticCompoundShape.h+++ b/thirdparty/jolt_physics/Jolt/Physics/Collision/Shape/StaticCompoundShape.h@@ -19,7 +19,8 @@ class JPH_EXPORT StaticCompoundShapeSettings final : public CompoundShapeSettingJPH_DECLARE_SERIALIZABLE_VIRTUAL(JPH_EXPORT, StaticCompoundShapeSettings)public:- // See: ShapeSettings+ /// Create a shape according to the settings specified by this object.+ /// Note when there is only 1 sub shape, this will create a RotatedTranslatedShape, or when the sub shape has no rotation/translation, it will return the child shape itself.virtual ShapeResult Create() const override;/// Specialization of Create() function that allows specifying a temp allocator to avoid temporary memory allocations on the heapdiff --git a/thirdparty/jolt_physics/Jolt/Physics/Collision/Shape/TaperedCapsuleShape.gliffy b/thirdparty/jolt_physics/Jolt/Physics/Collision/Shape/TaperedCapsuleShape.gliffyindex 3e5221b8655..4f3d01e8c62 100644--- a/thirdparty/jolt_physics/Jolt/Physics/Collision/Shape/TaperedCapsuleShape.gliffy+++ b/thirdparty/jolt_physics/Jolt/Physics/Collision/Shape/TaperedCapsuleShape.gliffy@@ -1 +1 @@-{"contentType":"application/gliffy+json","version":"1.1","metadata":{"title":"untitled","revision":0,"exportBorder":false},"embeddedResources":{"index":0,"resources":[]},"stage":{"objects":[{"x":870,"y":406,"rotation":0,"id":62,"uid":"com.gliffy.shape.basic.basic_v1.default.line","width":100,"height":100,"lockAspectRatio":false,"lockShape":false,"order":62,"graphic":{"type":"Line","Line":{"strokeWidth":2,"strokeColor":"#000000","fillColor":"none","dashStyle":"1.0,1.0","startArrow":0,"endArrow":0,"startArrowRotation":"auto","endArrowRotation":"auto","ortho":false,"interpolationType":"linear","cornerRadius":null,"controlPath":[[1.5,5.5],[1.5,-46.196228102251325]],"lockSegments":{}}},"children":null,"constraints":{"constraints":[],"startConstraint":{"type":"StartPositionConstraint","StartPositionConstraint":{"nodeId":4,"px":0.5,"py":0.5}}},"linkMap":[]},{"x":410,"y":406,"rotation":0,"id":60,"uid":"com.gliffy.shape.basic.basic_v1.default.line","width":100,"height":100,"lockAspectRatio":false,"lockShape":false,"order":60,"graphic":{"type":"Line","Line":{"strokeWidth":2,"strokeColor":"#000000","fillColor":"none","dashStyle":"1.0,1.0","startArrow":0,"endArrow":0,"startArrowRotation":"auto","endArrowRotation":"auto","ortho":false,"interpolationType":"linear","cornerRadius":null,"controlPath":[[0,5.5],[0,-49.03668490108288]],"lockSegments":{}}},"children":null,"constraints":{"constraints":[],"startConstraint":{"type":"StartPositionConstraint","StartPositionConstraint":{"nodeId":0,"px":0.5,"py":0.5}}},"linkMap":[]},{"x":614,"y":385,"rotation":0,"id":58,"uid":"com.gliffy.shape.basic.basic_v1.default.line","width":100,"height":100,"lockAspectRatio":false,"lockShape":false,"order":58,"graphic":{"type":"Line","Line":{"strokeWidth":2,"strokeColor":"#000000","fillColor":"none","dashStyle":null,"startArrow":0,"endArrow":2,"startArrowRotation":"auto","endArrowRotation":"auto","ortho":false,"interpolationType":"linear","cornerRadius":null,"controlPath":[[0,0],[-204.06126531020038,0]],"lockSegments":{}}},"children":null,"linkMap":[]},{"x":626,"y":385,"rotation":0,"id":57,"uid":"com.gliffy.shape.basic.basic_v1.default.line","width":100,"height":100,"lockAspectRatio":false,"lockShape":false,"order":57,"graphic":{"type":"Line","Line":{"strokeWidth":2,"strokeColor":"#000000","fillColor":"none","dashStyle":null,"startArrow":0,"endArrow":2,"startArrowRotation":"auto","endArrowRotation":"auto","ortho":false,"interpolationType":"linear","cornerRadius":null,"controlPath":[[0,0],[248.0020161208372,0]],"lockSegments":{}}},"children":null,"linkMap":[]},{"x":818,"y":520,"rotation":0,"id":55,"uid":"com.gliffy.shape.basic.basic_v1.default.line","width":100,"height":100,"lockAspectRatio":false,"lockShape":false,"order":55,"graphic":{"type":"Line","Line":{"strokeWidth":2,"strokeColor":"#000000","fillColor":"none","dashStyle":null,"startArrow":0,"endArrow":2,"startArrowRotation":"auto","endArrowRotation":"auto","ortho":false,"interpolationType":"linear","cornerRadius":null,"controlPath":[[0,0],[-48,76]],"lockSegments":{}}},"children":null,"linkMap":[]},{"x":830,"y":502,"rotation":0,"id":54,"uid":"com.gliffy.shape.basic.basic_v1.default.line","width":100,"height":100,"lockAspectRatio":false,"lockShape":false,"order":54,"graphic":{"type":"Line","Line":{"strokeWidth":2,"strokeColor":"#000000","fillColor":"none","dashStyle":null,"startArrow":0,"endArrow":2,"startArrowRotation":"auto","endArrowRotation":"auto","ortho":false,"interpolationType":"linear","cornerRadius":null,"controlPath":[[0,0],[48,-82]],"lockSegments":{}}},"children":null,"linkMap":[]},{"x":373,"y":410,"rotation":0,"id":50,"uid":"com.gliffy.shape.basic.basic_v1.default.text","width":28,"height":23,"lockAspectRatio":false,"lockShape":false,"order":19,"graphic":{"type":"Text","Text":{"tid":null,"valign":"middle","overflow":"none","vposition":"none","hposition":"none","html":"<p style=\"text-align:center;\"><span style=\"font-size: 12px; font-family: Arial; white-space: pre-wrap; line-height: 14px; color: rgb(0, 0, 0);\">tx</span></p>","paddingLeft":2,"paddingRight":2,"paddingBottom":2,"paddingTop":2}},"children":null,"linkMap":[]},{"x":387,"y":392,"rotation":0,"id":49,"uid":"com.gliffy.shape.basic.basic_v1.default.text","width":26,"height":23,"lockAspectRatio":false,"lockShape":false,"order":18,"graphic":{"type":"Text","Text":{"tid":null,"valign":"middle","overflow":"none","vposition":"none","hposition":"none","html":"<p style=\"text-align:center;\"><span style=\"font-size: 12px; font-family: Arial; white-space: pre-wrap; line-height: 14px; color: rgb(0, 0, 0);\">ty</span></p>","paddingLeft":2,"paddingRight":2,"paddingBottom":2,"paddingTop":2}},"children":null,"linkMap":[]},{"x":722,"y":488,"rotation":0,"id":45,"uid":"com.gliffy.shape.basic.basic_v1.default.text","width":20,"height":20,"lockAspectRatio":false,"lockShape":false,"order":16,"graphic":{"type":"Text","Text":{"tid":null,"valign":"middle","overflow":"none","vposition":"none","hposition":"none","html":"<p style=\"text-align:center;\"><span style=\"font-size: 12px; font-family: Arial; white-space: pre-wrap; line-height: 14px; color: rgb(0, 0, 0);\">bx</span></p>","paddingLeft":2,"paddingRight":2,"paddingBottom":2,"paddingTop":2}},"children":null,"linkMap":[]},{"x":440,"y":411.5,"rotation":0,"id":40,"uid":"com.gliffy.shape.basic.basic_v1.default.text","width":29,"height":28.500000000000004,"lockAspectRatio":false,"lockShape":false,"order":13,"graphic":{"type":"Text","Text":{"tid":null,"valign":"middle","overflow":"none","vposition":"none","hposition":"none","html":"<p style=\"text-align:center;\"><span style=\"font-size: 12px; font-family: Arial; white-space: pre-wrap; line-height: 14px; color: rgb(0, 0, 0);\">α</span></p>","paddingLeft":2,"paddingRight":2,"paddingBottom":2,"paddingTop":2}},"children":null,"linkMap":[]},{"x":411,"y":414,"rotation":0,"id":34,"uid":"com.gliffy.shape.basic.basic_v1.default.line","width":100,"height":100,"lockAspectRatio":false,"lockShape":false,"order":12,"graphic":{"type":"Line","Line":{"strokeWidth":2,"strokeColor":"#000000","fillColor":"none","dashStyle":"1.0,1.0","startArrow":0,"endArrow":0,"startArrowRotation":"auto","endArrowRotation":"auto","ortho":false,"interpolationType":"linear","cornerRadius":null,"controlPath":[[-1,-2.5],[349,180]],"lockSegments":{}}},"children":null,"constraints":{"constraints":[],"startConstraint":{"type":"StartPositionConstraint","StartPositionConstraint":{"nodeId":0,"px":0.5,"py":0.5}}},"linkMap":[]},{"x":744,"y":613,"rotation":0,"id":32,"uid":"com.gliffy.shape.basic.basic_v1.default.line","width":100,"height":100,"lockAspectRatio":false,"lockShape":false,"order":11,"graphic":{"type":"Line","Line":{"strokeWidth":2,"strokeColor":"#000000","fillColor":"none","dashStyle":"1.0,1.0","startArrow":0,"endArrow":0,"startArrowRotation":"auto","endArrowRotation":"auto","ortho":false,"interpolationType":"linear","cornerRadius":null,"controlPath":[[0,0],[-1.1368683772161603e-13,-201.00995000248122]],"lockSegments":{}}},"children":null,"linkMap":[]},{"x":394,"y":436,"rotation":0,"id":30,"uid":"com.gliffy.shape.basic.basic_v1.default.line","width":100,"height":100,"lockAspectRatio":false,"lockShape":false,"order":10,"graphic":{"type":"Line","Line":{"strokeWidth":2,"strokeColor":"#000000","fillColor":"none","dashStyle":"1.0,1.0","startArrow":0,"endArrow":0,"startArrowRotation":"auto","endArrowRotation":"auto","ortho":false,"interpolationType":"linear","cornerRadius":null,"controlPath":[[0,0],[0,-26.076809620810593]],"lockSegments":{}}},"children":null,"linkMap":[]},{"x":607,"y":368.5,"rotation":0,"id":26,"uid":"com.gliffy.shape.basic.basic_v1.default.text","width":20,"height":30,"lockAspectRatio":false,"lockShape":false,"order":9,"graphic":{"type":"Text","Text":{"tid":null,"valign":"middle","overflow":"none","vposition":"none","hposition":"none","html":"<p style=\"text-align:center;\"><span style=\"font-size: 12px; font-family: Arial; white-space: pre-wrap; line-height: 14px; color: rgb(0, 0, 0);\">h</span></p>","paddingLeft":2,"paddingRight":2,"paddingBottom":2,"paddingTop":2}},"children":null,"linkMap":[]},{"x":401,"y":412.5,"rotation":0,"id":25,"uid":"com.gliffy.shape.basic.basic_v1.default.text","width":20,"height":30,"lockAspectRatio":false,"lockShape":false,"order":8,"graphic":{"type":"Text","Text":{"tid":null,"valign":"middle","overflow":"none","vposition":"none","hposition":"none","html":"<p style=\"text-align:center;\"><span style=\"font-size: 12px; font-family: Arial; white-space: pre-wrap; line-height: 14px; color: rgb(0, 0, 0);\">tr</span></p>","paddingLeft":2,"paddingRight":2,"paddingBottom":2,"paddingTop":2}},"children":null,"linkMap":[]},{"x":808.5,"y":500,"rotation":0,"id":23,"uid":"com.gliffy.shape.basic.basic_v1.default.text","width":49,"height":27,"lockAspectRatio":false,"lockShape":false,"order":7,"graphic":{"type":"Text","Text":{"tid":null,"valign":"middle","overflow":"none","vposition":"none","hposition":"none","html":"<p style=\"text-align:center;\"><span style=\"font-size: 12px; font-family: Arial; white-space: pre-wrap; line-height: 14px; color: rgb(0, 0, 0);\">br - tr</span></p>","paddingLeft":2,"paddingRight":2,"paddingBottom":2,"paddingTop":2}},"children":null,"linkMap":[]},{"x":402,"y":416,"rotation":0,"id":21,"uid":"com.gliffy.shape.basic.basic_v1.default.line","width":100,"height":100,"lockAspectRatio":false,"lockShape":false,"order":6,"graphic":{"type":"Line","Line":{"strokeWidth":2,"strokeColor":"#000000","fillColor":"none","dashStyle":null,"startArrow":0,"endArrow":0,"startArrowRotation":"auto","endArrowRotation":"auto","ortho":false,"interpolationType":"linear","cornerRadius":null,"controlPath":[[8,-4.5],[-7,21]],"lockSegments":{}}},"children":null,"constraints":{"constraints":[],"startConstraint":{"type":"StartPositionConstraint","StartPositionConstraint":{"nodeId":0,"px":0.5,"py":0.5}}},"linkMap":[]},{"x":347,"y":412,"rotation":0,"id":16,"uid":"com.gliffy.shape.basic.basic_v1.default.line","width":100,"height":100,"lockAspectRatio":false,"lockShape":false,"order":5,"graphic":{"type":"Line","Line":{"strokeWidth":2,"strokeColor":"#000000","fillColor":"none","dashStyle":null,"startArrow":0,"endArrow":0,"startArrowRotation":"auto","endArrowRotation":"auto","ortho":false,"interpolationType":"linear","cornerRadius":null,"controlPath":[[0,0],[523.5,2.5]],"lockSegments":{}}},"children":null,"linkMap":[]},{"x":854,"y":433,"rotation":0,"id":14,"uid":"com.gliffy.shape.basic.basic_v1.default.line","width":100,"height":100,"lockAspectRatio":false,"lockShape":false,"order":4,"graphic":{"type":"Line","Line":{"strokeWidth":2,"strokeColor":"#000000","fillColor":"none","dashStyle":null,"startArrow":0,"endArrow":0,"startArrowRotation":"auto","endArrowRotation":"auto","ortho":false,"interpolationType":"linear","cornerRadius":null,"controlPath":[[17.5,-21.5],[-106,184]],"lockSegments":{}}},"children":null,"constraints":{"constraints":[],"startConstraint":{"type":"StartPositionConstraint","StartPositionConstraint":{"nodeId":4,"px":0.5,"py":0.5}}},"linkMap":[]},{"x":395,"y":437,"rotation":0,"id":9,"uid":"com.gliffy.shape.basic.basic_v1.default.line","width":100,"height":100,"lockAspectRatio":false,"lockShape":false,"order":3,"graphic":{"type":"Line","Line":{"strokeWidth":2,"strokeColor":"#000000","fillColor":"none","dashStyle":null,"startArrow":0,"endArrow":0,"startArrowRotation":"auto","endArrowRotation":"auto","ortho":false,"interpolationType":"linear","cornerRadius":null,"controlPath":[[-52,-25],[695,360]],"lockSegments":{}}},"children":null,"linkMap":[]},{"x":395,"y":384,"rotation":0,"id":7,"uid":"com.gliffy.shape.basic.basic_v1.default.line","width":100,"height":100,"lockAspectRatio":false,"lockShape":false,"order":2,"graphic":{"type":"Line","Line":{"strokeWidth":2,"strokeColor":"#000000","fillColor":"none","dashStyle":null,"startArrow":0,"endArrow":0,"startArrowRotation":"auto","endArrowRotation":"auto","ortho":false,"interpolationType":"linear","cornerRadius":null,"controlPath":[[-49,26],[703,-359]],"lockSegments":{}}},"children":null,"linkMap":[]},{"x":630,"y":169.99999999999997,"rotation":0,"id":4,"uid":"com.gliffy.shape.basic.basic_v1.default.circle","width":483.00000000000006,"height":483.00000000000006,"lockAspectRatio":true,"lockShape":false,"order":1,"graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.ellipse.basic_v1","strokeWidth":2,"strokeColor":"#333333","fillColor":"#FFFFFF","gradient":false,"dropShadow":false,"state":0,"shadowX":0,"shadowY":0,"opacity":1}},"children":[],"linkMap":[]},{"x":380,"y":381.5,"rotation":0,"id":0,"uid":"com.gliffy.shape.basic.basic_v1.default.circle","width":60,"height":60,"lockAspectRatio":true,"lockShape":false,"order":0,"graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.ellipse.basic_v1","strokeWidth":2,"strokeColor":"#333333","fillColor":"#FFFFFF","gradient":false,"dropShadow":false,"state":0,"shadowX":0,"shadowY":0,"opacity":1}},"children":[],"linkMap":[]},{"x":728,"y":612,"rotation":0,"id":41,"uid":"com.gliffy.shape.basic.basic_v1.default.text","width":29,"height":28.500000000000004,"lockAspectRatio":false,"lockShape":false,"order":14,"graphic":{"type":"Text","Text":{"tid":null,"valign":"middle","overflow":"none","vposition":"none","hposition":"none","html":"<p style=\"text-align:center;\"><span style=\"font-size: 12px; font-family: Arial; white-space: pre-wrap; line-height: 14px; color: rgb(0, 0, 0);\">α</span></p>","paddingLeft":2,"paddingRight":2,"paddingBottom":2,"paddingTop":2}},"children":null,"linkMap":[]},{"x":375,"y":432.5,"rotation":0,"id":42,"uid":"com.gliffy.shape.basic.basic_v1.default.text","width":29,"height":28.500000000000004,"lockAspectRatio":false,"lockShape":false,"order":15,"graphic":{"type":"Text","Text":{"tid":null,"valign":"middle","overflow":"none","vposition":"none","hposition":"none","html":"<p style=\"text-align:center;\"><span style=\"font-size: 12px; font-family: Arial; white-space: pre-wrap; line-height: 14px; color: rgb(0, 0, 0);\">α</span></p>","paddingLeft":2,"paddingRight":2,"paddingBottom":2,"paddingTop":2}},"children":null,"linkMap":[]},{"x":753,"y":595.5,"rotation":0,"id":53,"uid":"com.gliffy.shape.basic.basic_v1.default.text","width":20,"height":30,"lockAspectRatio":false,"lockShape":false,"order":20,"graphic":{"type":"Text","Text":{"tid":null,"valign":"middle","overflow":"none","vposition":"none","hposition":"none","html":"<p style=\"text-align:center;\"><span style=\"font-size: 12px; font-family: Arial; white-space: pre-wrap; line-height: 14px; color: rgb(0, 0, 0);\">tr</span></p>","paddingLeft":2,"paddingRight":2,"paddingBottom":2,"paddingTop":2}},"children":null,"linkMap":[]},{"x":794,"y":400,"rotation":0,"id":65,"uid":"com.gliffy.shape.basic.basic_v1.default.line","width":100,"height":100,"lockAspectRatio":false,"lockShape":false,"order":65,"graphic":{"type":"Line","Line":{"strokeWidth":2,"strokeColor":"#000000","fillColor":"none","dashStyle":null,"startArrow":0,"endArrow":2,"startArrowRotation":"auto","endArrowRotation":"auto","ortho":false,"interpolationType":"linear","cornerRadius":null,"controlPath":[[0,0],[-48.01041553663117,0]],"lockSegments":{}}},"children":null,"linkMap":[]},{"x":790,"y":393.25,"rotation":0,"id":46,"uid":"com.gliffy.shape.basic.basic_v1.default.text","width":29,"height":14,"lockAspectRatio":false,"lockShape":false,"order":17,"graphic":{"type":"Text","Text":{"tid":null,"valign":"middle","overflow":"none","vposition":"none","hposition":"none","html":"<p style=\"text-align:center;\"><span style=\"font-size: 12px; font-family: Arial; white-space: pre-wrap; line-height: 14px; color: rgb(0, 0, 0);\">by</span></p>","paddingLeft":2,"paddingRight":2,"paddingBottom":2,"paddingTop":2}},"children":null,"linkMap":[]},{"x":818,"y":400,"rotation":0,"id":66,"uid":"com.gliffy.shape.basic.basic_v1.default.line","width":100,"height":100,"lockAspectRatio":false,"lockShape":false,"order":66,"graphic":{"type":"Line","Line":{"strokeWidth":2,"strokeColor":"#000000","fillColor":"none","dashStyle":null,"startArrow":0,"endArrow":2,"startArrowRotation":"auto","endArrowRotation":"auto","ortho":false,"interpolationType":"linear","cornerRadius":null,"controlPath":[[0,0],[54.230987451824944,0]],"lockSegments":{}}},"children":null,"linkMap":[]}],"background":"#FFFFFF","width":1113,"height":802,"maxWidth":5000,"maxHeight":5000,"nodeIndex":69,"autoFit":true,"exportBorder":false,"gridOn":true,"snapToGrid":false,"drawingGuidesOn":false,"pageBreaksOn":false,"printGridOn":false,"printPaper":"LETTER","printShrinkToFit":false,"printPortrait":true,"shapeStyles":{"com.gliffy.shape.basic.basic_v1.default":{"fill":"#FFFFFF","stroke":"#333333","strokeWidth":2}},"lineStyles":{"global":{"dashStyle":null,"endArrow":2,"startArrow":0}},"textStyles":{},"themeData":null}}\ No newline at end of file+{"contentType":"application/gliffy+json","version":"1.1","metadata":{"title":"untitled","revision":0,"exportBorder":false},"embeddedResources":{"index":0,"resources":[]},"stage":{"objects":[{"x":870,"y":406,"rotation":0,"id":62,"uid":"com.gliffy.shape.basic.basic_v1.default.line","width":100,"height":100,"lockAspectRatio":false,"lockShape":false,"order":62,"graphic":{"type":"Line","Line":{"strokeWidth":2,"strokeColor":"#000000","fillColor":"none","dashStyle":"1.0,1.0","startArrow":0,"endArrow":0,"startArrowRotation":"auto","endArrowRotation":"auto","ortho":false,"interpolationType":"linear","cornerRadius":null,"controlPath":[[1.5,5.5],[1.5,-46.196228102251325]],"lockSegments":{}}},"children":null,"constraints":{"constraints":[],"startConstraint":{"type":"StartPositionConstraint","StartPositionConstraint":{"nodeId":4,"px":0.5,"py":0.5}}},"linkMap":[]},{"x":410,"y":406,"rotation":0,"id":60,"uid":"com.gliffy.shape.basic.basic_v1.default.line","width":100,"height":100,"lockAspectRatio":false,"lockShape":false,"order":60,"graphic":{"type":"Line","Line":{"strokeWidth":2,"strokeColor":"#000000","fillColor":"none","dashStyle":"1.0,1.0","startArrow":0,"endArrow":0,"startArrowRotation":"auto","endArrowRotation":"auto","ortho":false,"interpolationType":"linear","cornerRadius":null,"controlPath":[[0,5.5],[0,-49.03668490108288]],"lockSegments":{}}},"children":null,"constraints":{"constraints":[],"startConstraint":{"type":"StartPositionConstraint","StartPositionConstraint":{"nodeId":0,"px":0.5,"py":0.5}}},"linkMap":[]},{"x":614,"y":385,"rotation":0,"id":58,"uid":"com.gliffy.shape.basic.basic_v1.default.line","width":100,"height":100,"lockAspectRatio":false,"lockShape":false,"order":58,"graphic":{"type":"Line","Line":{"strokeWidth":2,"strokeColor":"#000000","fillColor":"none","dashStyle":null,"startArrow":0,"endArrow":2,"startArrowRotation":"auto","endArrowRotation":"auto","ortho":false,"interpolationType":"linear","cornerRadius":null,"controlPath":[[0,0],[-204.06126531020038,0]],"lockSegments":{}}},"children":null,"linkMap":[]},{"x":626,"y":385,"rotation":0,"id":57,"uid":"com.gliffy.shape.basic.basic_v1.default.line","width":100,"height":100,"lockAspectRatio":false,"lockShape":false,"order":57,"graphic":{"type":"Line","Line":{"strokeWidth":2,"strokeColor":"#000000","fillColor":"none","dashStyle":null,"startArrow":0,"endArrow":2,"startArrowRotation":"auto","endArrowRotation":"auto","ortho":false,"interpolationType":"linear","cornerRadius":null,"controlPath":[[0,0],[248.0020161208372,0]],"lockSegments":{}}},"children":null,"linkMap":[]},{"x":818,"y":520,"rotation":0,"id":55,"uid":"com.gliffy.shape.basic.basic_v1.default.line","width":100,"height":100,"lockAspectRatio":false,"lockShape":false,"order":55,"graphic":{"type":"Line","Line":{"strokeWidth":2,"strokeColor":"#000000","fillColor":"none","dashStyle":null,"startArrow":0,"endArrow":2,"startArrowRotation":"auto","endArrowRotation":"auto","ortho":false,"interpolationType":"linear","cornerRadius":null,"controlPath":[[0,0],[-48,76]],"lockSegments":{}}},"children":null,"linkMap":[]},{"x":830,"y":502,"rotation":0,"id":54,"uid":"com.gliffy.shape.basic.basic_v1.default.line","width":100,"height":100,"lockAspectRatio":false,"lockShape":false,"order":54,"graphic":{"type":"Line","Line":{"strokeWidth":2,"strokeColor":"#000000","fillColor":"none","dashStyle":null,"startArrow":0,"endArrow":2,"startArrowRotation":"auto","endArrowRotation":"auto","ortho":false,"interpolationType":"linear","cornerRadius":null,"controlPath":[[0,0],[48,-82]],"lockSegments":{}}},"children":null,"linkMap":[]},{"x":373,"y":410,"rotation":0,"id":50,"uid":"com.gliffy.shape.basic.basic_v1.default.text","width":28,"height":23,"lockAspectRatio":false,"lockShape":false,"order":19,"graphic":{"type":"Text","Text":{"tid":null,"valign":"middle","overflow":"none","vposition":"none","hposition":"none","html":"<p style=\"text-align:center;\"><span style=\"font-size: 12px; font-family: Arial; white-space: pre-wrap; line-height: 14px; color: rgb(0, 0, 0);\">tx</span></p>","paddingLeft":2,"paddingRight":2,"paddingBottom":2,"paddingTop":2}},"children":null,"linkMap":[]},{"x":387,"y":392,"rotation":0,"id":49,"uid":"com.gliffy.shape.basic.basic_v1.default.text","width":26,"height":23,"lockAspectRatio":false,"lockShape":false,"order":18,"graphic":{"type":"Text","Text":{"tid":null,"valign":"middle","overflow":"none","vposition":"none","hposition":"none","html":"<p style=\"text-align:center;\"><span style=\"font-size: 12px; font-family: Arial; white-space: pre-wrap; line-height: 14px; color: rgb(0, 0, 0);\">ty</span></p>","paddingLeft":2,"paddingRight":2,"paddingBottom":2,"paddingTop":2}},"children":null,"linkMap":[]},{"x":722,"y":488,"rotation":0,"id":45,"uid":"com.gliffy.shape.basic.basic_v1.default.text","width":20,"height":20,"lockAspectRatio":false,"lockShape":false,"order":16,"graphic":{"type":"Text","Text":{"tid":null,"valign":"middle","overflow":"none","vposition":"none","hposition":"none","html":"<p style=\"text-align:center;\"><span style=\"font-size: 12px; font-family: Arial; white-space: pre-wrap; line-height: 14px; color: rgb(0, 0, 0);\">bx</span></p>","paddingLeft":2,"paddingRight":2,"paddingBottom":2,"paddingTop":2}},"children":null,"linkMap":[]},{"x":440,"y":411.5,"rotation":0,"id":40,"uid":"com.gliffy.shape.basic.basic_v1.default.text","width":29,"height":28.500000000000004,"lockAspectRatio":false,"lockShape":false,"order":13,"graphic":{"type":"Text","Text":{"tid":null,"valign":"middle","overflow":"none","vposition":"none","hposition":"none","html":"<p style=\"text-align:center;\"><span style=\"font-size: 12px; font-family: Arial; white-space: pre-wrap; line-height: 14px; color: rgb(0, 0, 0);\">α</span></p>","paddingLeft":2,"paddingRight":2,"paddingBottom":2,"paddingTop":2}},"children":null,"linkMap":[]},{"x":411,"y":414,"rotation":0,"id":34,"uid":"com.gliffy.shape.basic.basic_v1.default.line","width":100,"height":100,"lockAspectRatio":false,"lockShape":false,"order":12,"graphic":{"type":"Line","Line":{"strokeWidth":2,"strokeColor":"#000000","fillColor":"none","dashStyle":"1.0,1.0","startArrow":0,"endArrow":0,"startArrowRotation":"auto","endArrowRotation":"auto","ortho":false,"interpolationType":"linear","cornerRadius":null,"controlPath":[[-1,-2.5],[349,180]],"lockSegments":{}}},"children":null,"constraints":{"constraints":[],"startConstraint":{"type":"StartPositionConstraint","StartPositionConstraint":{"nodeId":0,"px":0.5,"py":0.5}}},"linkMap":[]},{"x":744,"y":613,"rotation":0,"id":32,"uid":"com.gliffy.shape.basic.basic_v1.default.line","width":100,"height":100,"lockAspectRatio":false,"lockShape":false,"order":11,"graphic":{"type":"Line","Line":{"strokeWidth":2,"strokeColor":"#000000","fillColor":"none","dashStyle":"1.0,1.0","startArrow":0,"endArrow":0,"startArrowRotation":"auto","endArrowRotation":"auto","ortho":false,"interpolationType":"linear","cornerRadius":null,"controlPath":[[0,0],[-1.1368683772161603e-13,-201.00995000248122]],"lockSegments":{}}},"children":null,"linkMap":[]},{"x":394,"y":436,"rotation":0,"id":30,"uid":"com.gliffy.shape.basic.basic_v1.default.line","width":100,"height":100,"lockAspectRatio":false,"lockShape":false,"order":10,"graphic":{"type":"Line","Line":{"strokeWidth":2,"strokeColor":"#000000","fillColor":"none","dashStyle":"1.0,1.0","startArrow":0,"endArrow":0,"startArrowRotation":"auto","endArrowRotation":"auto","ortho":false,"interpolationType":"linear","cornerRadius":null,"controlPath":[[0,0],[0,-26.076809620810593]],"lockSegments":{}}},"children":null,"linkMap":[]},{"x":607,"y":368.5,"rotation":0,"id":26,"uid":"com.gliffy.shape.basic.basic_v1.default.text","width":20,"height":30,"lockAspectRatio":false,"lockShape":false,"order":9,"graphic":{"type":"Text","Text":{"tid":null,"valign":"middle","overflow":"none","vposition":"none","hposition":"none","html":"<p style=\"text-align:center;\"><span style=\"font-size: 12px; font-family: Arial; white-space: pre-wrap; line-height: 14px; color: rgb(0, 0, 0);\">h</span></p>","paddingLeft":2,"paddingRight":2,"paddingBottom":2,"paddingTop":2}},"children":null,"linkMap":[]},{"x":401,"y":412.5,"rotation":0,"id":25,"uid":"com.gliffy.shape.basic.basic_v1.default.text","width":20,"height":30,"lockAspectRatio":false,"lockShape":false,"order":8,"graphic":{"type":"Text","Text":{"tid":null,"valign":"middle","overflow":"none","vposition":"none","hposition":"none","html":"<p style=\"text-align:center;\"><span style=\"font-size: 12px; font-family: Arial; white-space: pre-wrap; line-height: 14px; color: rgb(0, 0, 0);\">tr</span></p>","paddingLeft":2,"paddingRight":2,"paddingBottom":2,"paddingTop":2}},"children":null,"linkMap":[]},{"x":808.5,"y":500,"rotation":0,"id":23,"uid":"com.gliffy.shape.basic.basic_v1.default.text","width":49,"height":27,"lockAspectRatio":false,"lockShape":false,"order":7,"graphic":{"type":"Text","Text":{"tid":null,"valign":"middle","overflow":"none","vposition":"none","hposition":"none","html":"<p style=\"text-align:center;\"><span style=\"font-size: 12px; font-family: Arial; white-space: pre-wrap; line-height: 14px; color: rgb(0, 0, 0);\">br - tr</span></p>","paddingLeft":2,"paddingRight":2,"paddingBottom":2,"paddingTop":2}},"children":null,"linkMap":[]},{"x":402,"y":416,"rotation":0,"id":21,"uid":"com.gliffy.shape.basic.basic_v1.default.line","width":100,"height":100,"lockAspectRatio":false,"lockShape":false,"order":6,"graphic":{"type":"Line","Line":{"strokeWidth":2,"strokeColor":"#000000","fillColor":"none","dashStyle":null,"startArrow":0,"endArrow":0,"startArrowRotation":"auto","endArrowRotation":"auto","ortho":false,"interpolationType":"linear","cornerRadius":null,"controlPath":[[8,-4.5],[-7,21]],"lockSegments":{}}},"children":null,"constraints":{"constraints":[],"startConstraint":{"type":"StartPositionConstraint","StartPositionConstraint":{"nodeId":0,"px":0.5,"py":0.5}}},"linkMap":[]},{"x":347,"y":412,"rotation":0,"id":16,"uid":"com.gliffy.shape.basic.basic_v1.default.line","width":100,"height":100,"lockAspectRatio":false,"lockShape":false,"order":5,"graphic":{"type":"Line","Line":{"strokeWidth":2,"strokeColor":"#000000","fillColor":"none","dashStyle":null,"startArrow":0,"endArrow":0,"startArrowRotation":"auto","endArrowRotation":"auto","ortho":false,"interpolationType":"linear","cornerRadius":null,"controlPath":[[0,0],[523.5,2.5]],"lockSegments":{}}},"children":null,"linkMap":[]},{"x":854,"y":433,"rotation":0,"id":14,"uid":"com.gliffy.shape.basic.basic_v1.default.line","width":100,"height":100,"lockAspectRatio":false,"lockShape":false,"order":4,"graphic":{"type":"Line","Line":{"strokeWidth":2,"strokeColor":"#000000","fillColor":"none","dashStyle":null,"startArrow":0,"endArrow":0,"startArrowRotation":"auto","endArrowRotation":"auto","ortho":false,"interpolationType":"linear","cornerRadius":null,"controlPath":[[17.5,-21.5],[-106,184]],"lockSegments":{}}},"children":null,"constraints":{"constraints":[],"startConstraint":{"type":"StartPositionConstraint","StartPositionConstraint":{"nodeId":4,"px":0.5,"py":0.5}}},"linkMap":[]},{"x":395,"y":437,"rotation":0,"id":9,"uid":"com.gliffy.shape.basic.basic_v1.default.line","width":100,"height":100,"lockAspectRatio":false,"lockShape":false,"order":3,"graphic":{"type":"Line","Line":{"strokeWidth":2,"strokeColor":"#000000","fillColor":"none","dashStyle":null,"startArrow":0,"endArrow":0,"startArrowRotation":"auto","endArrowRotation":"auto","ortho":false,"interpolationType":"linear","cornerRadius":null,"controlPath":[[-52,-25],[695,360]],"lockSegments":{}}},"children":null,"linkMap":[]},{"x":395,"y":384,"rotation":0,"id":7,"uid":"com.gliffy.shape.basic.basic_v1.default.line","width":100,"height":100,"lockAspectRatio":false,"lockShape":false,"order":2,"graphic":{"type":"Line","Line":{"strokeWidth":2,"strokeColor":"#000000","fillColor":"none","dashStyle":null,"startArrow":0,"endArrow":0,"startArrowRotation":"auto","endArrowRotation":"auto","ortho":false,"interpolationType":"linear","cornerRadius":null,"controlPath":[[-49,26],[703,-359]],"lockSegments":{}}},"children":null,"linkMap":[]},{"x":630,"y":169.99999999999997,"rotation":0,"id":4,"uid":"com.gliffy.shape.basic.basic_v1.default.circle","width":483.00000000000006,"height":483.00000000000006,"lockAspectRatio":true,"lockShape":false,"order":1,"graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.ellipse.basic_v1","strokeWidth":2,"strokeColor":"#333333","fillColor":"#FFFFFF","gradient":false,"dropShadow":false,"state":0,"shadowX":0,"shadowY":0,"opacity":1}},"children":[],"linkMap":[]},{"x":380,"y":381.5,"rotation":0,"id":0,"uid":"com.gliffy.shape.basic.basic_v1.default.circle","width":60,"height":60,"lockAspectRatio":true,"lockShape":false,"order":0,"graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.ellipse.basic_v1","strokeWidth":2,"strokeColor":"#333333","fillColor":"#FFFFFF","gradient":false,"dropShadow":false,"state":0,"shadowX":0,"shadowY":0,"opacity":1}},"children":[],"linkMap":[]},{"x":728,"y":612,"rotation":0,"id":41,"uid":"com.gliffy.shape.basic.basic_v1.default.text","width":29,"height":28.500000000000004,"lockAspectRatio":false,"lockShape":false,"order":14,"graphic":{"type":"Text","Text":{"tid":null,"valign":"middle","overflow":"none","vposition":"none","hposition":"none","html":"<p style=\"text-align:center;\"><span style=\"font-size: 12px; font-family: Arial; white-space: pre-wrap; line-height: 14px; color: rgb(0, 0, 0);\">α</span></p>","paddingLeft":2,"paddingRight":2,"paddingBottom":2,"paddingTop":2}},"children":null,"linkMap":[]},{"x":375,"y":432.5,"rotation":0,"id":42,"uid":"com.gliffy.shape.basic.basic_v1.default.text","width":29,"height":28.500000000000004,"lockAspectRatio":false,"lockShape":false,"order":15,"graphic":{"type":"Text","Text":{"tid":null,"valign":"middle","overflow":"none","vposition":"none","hposition":"none","html":"<p style=\"text-align:center;\"><span style=\"font-size: 12px; font-family: Arial; white-space: pre-wrap; line-height: 14px; color: rgb(0, 0, 0);\">α</span></p>","paddingLeft":2,"paddingRight":2,"paddingBottom":2,"paddingTop":2}},"children":null,"linkMap":[]},{"x":753,"y":595.5,"rotation":0,"id":53,"uid":"com.gliffy.shape.basic.basic_v1.default.text","width":20,"height":30,"lockAspectRatio":false,"lockShape":false,"order":20,"graphic":{"type":"Text","Text":{"tid":null,"valign":"middle","overflow":"none","vposition":"none","hposition":"none","html":"<p style=\"text-align:center;\"><span style=\"font-size: 12px; font-family: Arial; white-space: pre-wrap; line-height: 14px; color: rgb(0, 0, 0);\">tr</span></p>","paddingLeft":2,"paddingRight":2,"paddingBottom":2,"paddingTop":2}},"children":null,"linkMap":[]},{"x":794,"y":400,"rotation":0,"id":65,"uid":"com.gliffy.shape.basic.basic_v1.default.line","width":100,"height":100,"lockAspectRatio":false,"lockShape":false,"order":65,"graphic":{"type":"Line","Line":{"strokeWidth":2,"strokeColor":"#000000","fillColor":"none","dashStyle":null,"startArrow":0,"endArrow":2,"startArrowRotation":"auto","endArrowRotation":"auto","ortho":false,"interpolationType":"linear","cornerRadius":null,"controlPath":[[0,0],[-48.01041553663117,0]],"lockSegments":{}}},"children":null,"linkMap":[]},{"x":790,"y":393.25,"rotation":0,"id":46,"uid":"com.gliffy.shape.basic.basic_v1.default.text","width":29,"height":14,"lockAspectRatio":false,"lockShape":false,"order":17,"graphic":{"type":"Text","Text":{"tid":null,"valign":"middle","overflow":"none","vposition":"none","hposition":"none","html":"<p style=\"text-align:center;\"><span style=\"font-size: 12px; font-family: Arial; white-space: pre-wrap; line-height: 14px; color: rgb(0, 0, 0);\">by</span></p>","paddingLeft":2,"paddingRight":2,"paddingBottom":2,"paddingTop":2}},"children":null,"linkMap":[]},{"x":818,"y":400,"rotation":0,"id":66,"uid":"com.gliffy.shape.basic.basic_v1.default.line","width":100,"height":100,"lockAspectRatio":false,"lockShape":false,"order":66,"graphic":{"type":"Line","Line":{"strokeWidth":2,"strokeColor":"#000000","fillColor":"none","dashStyle":null,"startArrow":0,"endArrow":2,"startArrowRotation":"auto","endArrowRotation":"auto","ortho":false,"interpolationType":"linear","cornerRadius":null,"controlPath":[[0,0],[54.230987451824944,0]],"lockSegments":{}}},"children":null,"linkMap":[]}],"background":"#FFFFFF","width":1113,"height":802,"maxWidth":5000,"maxHeight":5000,"nodeIndex":69,"autoFit":true,"exportBorder":false,"gridOn":true,"snapToGrid":false,"drawingGuidesOn":false,"pageBreaksOn":false,"printGridOn":false,"printPaper":"LETTER","printShrinkToFit":false,"printPortrait":true,"shapeStyles":{"com.gliffy.shape.basic.basic_v1.default":{"fill":"#FFFFFF","stroke":"#333333","strokeWidth":2}},"lineStyles":{"global":{"dashStyle":null,"endArrow":2,"startArrow":0}},"textStyles":{},"themeData":null}}diff --git a/thirdparty/jolt_physics/Jolt/Physics/Collision/Shape/TaperedCapsuleShape.h b/thirdparty/jolt_physics/Jolt/Physics/Collision/Shape/TaperedCapsuleShape.hindex 5e53ee13602..2b8fdf2777e 100644--- a/thirdparty/jolt_physics/Jolt/Physics/Collision/Shape/TaperedCapsuleShape.h+++ b/thirdparty/jolt_physics/Jolt/Physics/Collision/Shape/TaperedCapsuleShape.h@@ -29,7 +29,8 @@ public:/// Checks if the settings of this tapered capsule make this shape a spherebool IsSphere() const;- // See: ShapeSettings+ /// Create a shape according to the settings specified by this object.+ /// Note that when one sphere fully contains the other sphere, this will return a RotatedTranslatedShape with a SphereShape, or a SphereShape if mHalfHeightOfTaperedCylinder is 0.virtual ShapeResult Create() const override;float mHalfHeightOfTaperedCylinder = 0.0f;diff --git a/thirdparty/jolt_physics/Jolt/Physics/Collision/Shape/TaperedCylinderShape.cpp b/thirdparty/jolt_physics/Jolt/Physics/Collision/Shape/TaperedCylinderShape.cppindex 9222d25f1c3..497fce32ccb 100644--- a/thirdparty/jolt_physics/Jolt/Physics/Collision/Shape/TaperedCylinderShape.cpp+++ b/thirdparty/jolt_physics/Jolt/Physics/Collision/Shape/TaperedCylinderShape.cpp@@ -149,7 +149,7 @@ public:virtual Vec3 GetSupport(Vec3Arg inDirection) const override{float x = inDirection.GetX(), y = inDirection.GetY(), z = inDirection.GetZ();- float o = sqrt(Square(x) + Square(z));+ float o = Sqrt(Square(x) + Square(z));if (o > 0.0f){Vec3 top_support((mTopRadius * x) / o, mTop, (mTopRadius * z) / o);@@ -263,7 +263,7 @@ void TaperedCylinderShape::GetSupportingFace(const SubShapeID &inSubShapeID, Vecfloat y_sq = Square(inDirection.GetY());if (xz_sq > 0.00765427f * y_sq){- base_x /= sqrt(xz_sq);+ base_x /= Sqrt(xz_sq);Vec4 base_z = base_x.Swizzle<SWIZZLE_Z, SWIZZLE_Y, SWIZZLE_X, SWIZZLE_W>() * Vec4(-1, 0, 1, 0);transform = transform * Mat44(base_x, Vec4(0, 1, 0, 0), base_z, Vec4(0, 0, 0, 1));}diff --git a/thirdparty/jolt_physics/Jolt/Physics/Collision/Shape/TaperedCylinderShape.h b/thirdparty/jolt_physics/Jolt/Physics/Collision/Shape/TaperedCylinderShape.hindex e48ca93d0f8..0807a46c02f 100644--- a/thirdparty/jolt_physics/Jolt/Physics/Collision/Shape/TaperedCylinderShape.h+++ b/thirdparty/jolt_physics/Jolt/Physics/Collision/Shape/TaperedCylinderShape.h@@ -21,7 +21,8 @@ public:/// Create a tapered cylinder centered around the origin with bottom at (0, -inHalfHeightOfTaperedCylinder, 0) with radius inBottomRadius and top at (0, inHalfHeightOfTaperedCylinder, 0) with radius inTopRadiusTaperedCylinderShapeSettings(float inHalfHeightOfTaperedCylinder, float inTopRadius, float inBottomRadius, float inConvexRadius = cDefaultConvexRadius, const PhysicsMaterial *inMaterial = nullptr);- // See: ShapeSettings+ /// Create a shape according to the settings specified by this object.+ /// Note that this will return a CylinderShape if top and bottom radii are equal.virtual ShapeResult Create() const override;float mHalfHeight = 0.0f;diff --git a/thirdparty/jolt_physics/Jolt/Physics/Collision/ShapeCast.h b/thirdparty/jolt_physics/Jolt/Physics/Collision/ShapeCast.hindex 4271ac06f7e..01da6a97897 100644--- a/thirdparty/jolt_physics/Jolt/Physics/Collision/ShapeCast.h+++ b/thirdparty/jolt_physics/Jolt/Physics/Collision/ShapeCast.h@@ -96,6 +96,9 @@ public:/// Set the backfacing mode for all shapesvoid SetBackFaceMode(EBackFaceMode inMode) { mBackFaceModeTriangles = mBackFaceModeConvex = inMode; }+ /// When > 0 the query shape is inflated by an extra convex radius, this makes it bigger in every direction by this margin. (unit: meter)+ float mExtraConvexRadius = 0.0f;+/// How backfacing triangles should be treated (should we report moving from back to front for triangle based shapes, e.g. for MeshShape/HeightFieldShape?)EBackFaceMode mBackFaceModeTriangles = EBackFaceMode::IgnoreBackFaces;diff --git a/thirdparty/jolt_physics/Jolt/Physics/Constraints/ConstraintPart/AngleConstraintPart.h b/thirdparty/jolt_physics/Jolt/Physics/Constraints/ConstraintPart/AngleConstraintPart.hindex f7493102e2a..3e6a9137137 100644--- a/thirdparty/jolt_physics/Jolt/Physics/Constraints/ConstraintPart/AngleConstraintPart.h+++ b/thirdparty/jolt_physics/Jolt/Physics/Constraints/ConstraintPart/AngleConstraintPart.h@@ -72,7 +72,7 @@ class AngleConstraintPart}public:- /// Calculate properties used during the functions below+ /// Calculate properties used during the functions below. Creates a constraint without spring./// @param inBody1 The first body that this constraint is attached to/// @param inBody2 The second body that this constraint is attached to/// @param inWorldSpaceAxis The axis of rotation along which the constraint acts (normalized)@@ -91,12 +91,11 @@ public:}}- /// Calculate properties used during the functions below+ /// Calculate properties used during the functions below. Set inFrequency to zero if you don't want to drive using a spring./// @param inDeltaTime Time step/// @param inBody1 The first body that this constraint is attached to/// @param inBody2 The second body that this constraint is attached to/// @param inWorldSpaceAxis The axis of rotation along which the constraint acts (normalized)- /// Set the following terms to zero if you don't want to drive the constraint to zero with a spring:/// @param inBias Bias term (b) for the constraint impulse: lambda = J v + b/// @param inC Value of the constraint equation (C)/// @param inFrequency Oscillation frequency (Hz)@@ -107,16 +106,20 @@ public:if (inv_effective_mass == 0.0f)Deactivate();- else+ else if (inFrequency > 0.0f)mSpringPart.CalculateSpringPropertiesWithFrequencyAndDamping(inDeltaTime, inv_effective_mass, inBias, inC, inFrequency, inDamping, mEffectiveMass);+ else+ {+ mEffectiveMass = 1.0f / inv_effective_mass;+ mSpringPart.CalculateSpringPropertiesWithBias(inBias);+ }}- /// Calculate properties used during the functions below+ /// Calculate properties used during the functions below. Set inStiffness and inDamping to zero if you don't want to drive using a spring./// @param inDeltaTime Time step/// @param inBody1 The first body that this constraint is attached to/// @param inBody2 The second body that this constraint is attached to/// @param inWorldSpaceAxis The axis of rotation along which the constraint acts (normalized)- /// Set the following terms to zero if you don't want to drive the constraint to zero with a spring:/// @param inBias Bias term (b) for the constraint impulse: lambda = J v + b/// @param inC Value of the constraint equation (C)/// @param inStiffness Spring stiffness k.@@ -127,21 +130,44 @@ public:if (inv_effective_mass == 0.0f)Deactivate();- else+ else if (inStiffness > 0.0f || inDamping > 0.0f)mSpringPart.CalculateSpringPropertiesWithStiffnessAndDamping(inDeltaTime, inv_effective_mass, inBias, inC, inStiffness, inDamping, mEffectiveMass);+ else+ {+ mEffectiveMass = 1.0f / inv_effective_mass;+ mSpringPart.CalculateSpringPropertiesWithBias(inBias);+ }}- /// Selects one of the above functions based on the spring settings- inline void CalculateConstraintPropertiesWithSettings(float inDeltaTime, const Body &inBody1, const Body &inBody2, Vec3Arg inWorldSpaceAxis, float inBias, float inC, const SpringSettings &inSpringSettings)+ /// Calculate properties used during the functions below based on inSpringSettings.+ /// Turns to a hard limit when inSpringSettings has stiffness / frequency = 0+ inline void CalculateConstraintPropertiesWithSettingsForLimit(float inDeltaTime, const Body &inBody1, const Body &inBody2, Vec3Arg inWorldSpaceAxis, float inBias, float inC, const SpringSettings &inSpringSettings){float inv_effective_mass = CalculateInverseEffectiveMass(inBody1, inBody2, inWorldSpaceAxis);if (inv_effective_mass == 0.0f)Deactivate();- else if (inSpringSettings.mMode == ESpringMode::FrequencyAndDamping)- mSpringPart.CalculateSpringPropertiesWithFrequencyAndDamping(inDeltaTime, inv_effective_mass, inBias, inC, inSpringSettings.mFrequency, inSpringSettings.mDamping, mEffectiveMass);+ else if (!inSpringSettings.HasStiffness())+ {+ mEffectiveMass = 1.0f / inv_effective_mass;+ mSpringPart.CalculateSpringPropertiesWithBias(inBias);+ }+ else+ mSpringPart.CalculateSpringPropertiesWithSettings(inDeltaTime, inv_effective_mass, inBias, inC, inSpringSettings, mEffectiveMass);+ }++ /// Calculate properties used during the functions below based on inSpringSettings.+ /// Assumes the spring has either stiffness or damping.+ inline void CalculateConstraintPropertiesWithSettingsForMotor(float inDeltaTime, const Body &inBody1, const Body &inBody2, Vec3Arg inWorldSpaceAxis, float inBias, float inC, const SpringSettings &inSpringSettings)+ {+ JPH_ASSERT(inSpringSettings.HasStiffnessOrDamping());++ float inv_effective_mass = CalculateInverseEffectiveMass(inBody1, inBody2, inWorldSpaceAxis);++ if (inv_effective_mass == 0.0f)+ Deactivate();else- mSpringPart.CalculateSpringPropertiesWithStiffnessAndDamping(inDeltaTime, inv_effective_mass, inBias, inC, inSpringSettings.mStiffness, inSpringSettings.mDamping, mEffectiveMass);+ mSpringPart.CalculateSpringPropertiesWithSettings(inDeltaTime, inv_effective_mass, inBias, inC, inSpringSettings, mEffectiveMass);}/// Deactivate this constraintdiff --git a/thirdparty/jolt_physics/Jolt/Physics/Constraints/ConstraintPart/AngularFrictionConstraintPart.h b/thirdparty/jolt_physics/Jolt/Physics/Constraints/ConstraintPart/AngularFrictionConstraintPart.hnew file mode 100644index 00000000000..f587f85e3ea--- /dev/null+++ b/thirdparty/jolt_physics/Jolt/Physics/Constraints/ConstraintPart/AngularFrictionConstraintPart.h@@ -0,0 +1,138 @@+// Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)+// SPDX-FileCopyrightText: 2026 Jorrit Rouwe+// SPDX-License-Identifier: MIT++#pragma once++#include <Jolt/Physics/Constraints/ConstraintPart/ContactConstraintPart.h>++JPH_NAMESPACE_BEGIN++/// Decide which members this constraint part needs based on motion type+template <EMotionType Type1>+class AngularFrictionConstraintPart1 : public ContactConstraintPart1<EMotionType::Static>+{+};++template <>+class AngularFrictionConstraintPart1<EMotionType::Dynamic> : public AngularFrictionConstraintPart1<EMotionType::Static>+{+protected:+ // Note: Constructor will not be called+ Float3 mInvI1_Axis;+};++template <EMotionType Type2>+class AngularFrictionConstraintPart2+{+};++template <>+class AngularFrictionConstraintPart2<EMotionType::Dynamic> : public AngularFrictionConstraintPart2<EMotionType::Static>+{+protected:+ // Note: Constructor will not be called+ Float3 mInvI2_Axis;+};++/// This is a copy of AngleConstraintPart, specialized to handle contact constraints. See the documentation of AngleConstraintPart for more documentation behind the math.+template <EMotionType Type1, EMotionType Type2>+class AngularFrictionConstraintPart : public AngularFrictionConstraintPart1<Type1>, public AngularFrictionConstraintPart2<Type2>+{+ /// Internal helper function to update velocities of bodies after Lagrange multiplier is calculated+ JPH_INLINE bool ApplyVelocityStep(Vec3 &ioAngularVelocity1, Vec3 &ioAngularVelocity2, float inLambda) const+ {+ // Apply impulse if delta is not zero+ if (inLambda != 0.0f)+ {+ if constexpr (Type1 == EMotionType::Dynamic)+ ioAngularVelocity1 -= inLambda * Vec3::sLoadFloat3Unsafe(this->mInvI1_Axis);+ if constexpr (Type2 == EMotionType::Dynamic)+ ioAngularVelocity2 += inLambda * Vec3::sLoadFloat3Unsafe(this->mInvI2_Axis);+ return true;+ }++ return false;+ }++public:+ /// See: AngleConstraintPart::CalculateConstraintProperties+ inline void CalculateConstraintProperties(Mat44Arg inInvI1, Mat44Arg inInvI2, Vec3Arg inWorldSpaceAxis, float inBias = 0.0f)+ {+ JPH_ASSERT(inWorldSpaceAxis.IsNormalized(1.0e-4f));++ // Store bias+ mBias = inBias;++ Vec3 invi1_axis, invi2_axis;+ if constexpr (Type1 == EMotionType::Dynamic)+ {+ invi1_axis = inInvI1.Multiply3x3(inWorldSpaceAxis);+ invi1_axis.StoreFloat3(&this->mInvI1_Axis);+ }+ if constexpr (Type2 == EMotionType::Dynamic)+ {+ invi2_axis = inInvI2.Multiply3x3(inWorldSpaceAxis);+ invi2_axis.StoreFloat3(&this->mInvI2_Axis);+ }++ float inv_effective_mass = 0.0f;+ if constexpr (Type1 == EMotionType::Dynamic && Type2 == EMotionType::Dynamic)+ inv_effective_mass = inWorldSpaceAxis.Dot(invi1_axis + invi2_axis);+ else if constexpr (Type1 == EMotionType::Dynamic)+ inv_effective_mass = inWorldSpaceAxis.Dot(invi1_axis);+ else if constexpr (Type2 == EMotionType::Dynamic)+ inv_effective_mass = inWorldSpaceAxis.Dot(invi2_axis);+ else+ JPH_ASSERT(false); // Static vs static is nonsensical!++ if (inv_effective_mass == 0.0f)+ this->Deactivate();+ else+ this->mEffectiveMass = 1.0f / inv_effective_mass;+ }++ /// See: AngleConstraintPart::WarmStart+ inline bool WarmStart(Vec3 &ioAngularVelocity1, Vec3 &ioAngularVelocity2, float inWarmStartImpulseRatio)+ {+ this->mTotalLambda *= inWarmStartImpulseRatio;+ return ApplyVelocityStep(ioAngularVelocity1, ioAngularVelocity2, this->mTotalLambda);+ }++ /// See: AngleConstraintPart::SolveVelocityConstraint+ inline bool SolveVelocityConstraint(Vec3 &ioAngularVelocity1, Vec3 &ioAngularVelocity2, Vec3Arg inWorldSpaceAxis, float inMinLambda, float inMaxLambda)+ {+ float jv;+ if constexpr (Type1 != EMotionType::Static && Type2 != EMotionType::Static)+ jv = inWorldSpaceAxis.Dot(ioAngularVelocity1 - ioAngularVelocity2);+ else if constexpr (Type1 != EMotionType::Static)+ jv = inWorldSpaceAxis.Dot(ioAngularVelocity1);+ else if constexpr (Type2 != EMotionType::Static)+ jv = -inWorldSpaceAxis.Dot(ioAngularVelocity2);+ else+ JPH_ASSERT(false); // Static vs static is nonsensical!++ float lambda = this->mEffectiveMass * (jv - mBias);+ float new_lambda = Clamp(this->mTotalLambda + lambda, inMinLambda, inMaxLambda); // Clamp impulse+ lambda = new_lambda - this->mTotalLambda; // Lambda potentially got clamped, calculate the new impulse to apply+ this->mTotalLambda = new_lambda; // Store accumulated impulse++ return ApplyVelocityStep(ioAngularVelocity1, ioAngularVelocity2, lambda);+ }++private:+ // Note: Constructor will not be called. This serves as 1 extra float so we can read the previous member using Vec3::sLoadFloat3Unsafe+ float mBias;+};++static_assert(sizeof(AngularFrictionConstraintPart<EMotionType::Dynamic, EMotionType::Dynamic>) == 3 * sizeof(float) + 2 * sizeof(Float3));+static_assert(sizeof(AngularFrictionConstraintPart<EMotionType::Dynamic, EMotionType::Kinematic>) == 3 * sizeof(float) + sizeof(Float3));+static_assert(sizeof(AngularFrictionConstraintPart<EMotionType::Dynamic, EMotionType::Static>) == 3 * sizeof(float) + sizeof(Float3));+static_assert(sizeof(AngularFrictionConstraintPart<EMotionType::Kinematic, EMotionType::Dynamic>) == 3 * sizeof(float) + sizeof(Float3));+static_assert(sizeof(AngularFrictionConstraintPart<EMotionType::Kinematic, EMotionType::Kinematic>) == 3 * sizeof(float));+static_assert(sizeof(AngularFrictionConstraintPart<EMotionType::Kinematic, EMotionType::Static>) == 3 * sizeof(float));+static_assert(sizeof(AngularFrictionConstraintPart<EMotionType::Static, EMotionType::Dynamic>) == 3 * sizeof(float) + sizeof(Float3));+static_assert(sizeof(AngularFrictionConstraintPart<EMotionType::Static, EMotionType::Kinematic>) == 3 * sizeof(float));+static_assert(sizeof(AngularFrictionConstraintPart<EMotionType::Static, EMotionType::Static>) == 3 * sizeof(float));++JPH_NAMESPACE_ENDdiff --git a/thirdparty/jolt_physics/Jolt/Physics/Constraints/ConstraintPart/AxisConstraintPart.h b/thirdparty/jolt_physics/Jolt/Physics/Constraints/ConstraintPart/AxisConstraintPart.hindex a41ee3af3c8..58962197f21 100644--- a/thirdparty/jolt_physics/Jolt/Physics/Constraints/ConstraintPart/AxisConstraintPart.h+++ b/thirdparty/jolt_physics/Jolt/Physics/Constraints/ConstraintPart/AxisConstraintPart.h@@ -8,7 +8,6 @@#include <Jolt/Physics/Constraints/ConstraintPart/SpringPart.h>#include <Jolt/Physics/Constraints/SpringSettings.h>#include <Jolt/Physics/StateRecorder.h>-#include <Jolt/Physics/DeterminismLog.h>JPH_NAMESPACE_BEGIN@@ -42,8 +41,7 @@ JPH_NAMESPACE_BEGINclass AxisConstraintPart{/// Internal helper function to update velocities of bodies after Lagrange multiplier is calculated- template <EMotionType Type1, EMotionType Type2>- JPH_INLINE bool ApplyVelocityStep(MotionProperties *ioMotionProperties1, float inInvMass1, MotionProperties *ioMotionProperties2, float inInvMass2, Vec3Arg inWorldSpaceAxis, float inLambda) const+ JPH_INLINE bool ApplyVelocityStep(Body &ioBody1, Body &ioBody2, Vec3Arg inWorldSpaceAxis, float inLambda) const{// Apply impulse if delta is not zeroif (inLambda != 0.0f)@@ -55,15 +53,17 @@ class AxisConstraintPart//// Euler velocity integration:// v' = v + M^-1 P- if constexpr (Type1 == EMotionType::Dynamic)+ if (ioBody1.IsDynamic()){- ioMotionProperties1->SubLinearVelocityStep((inLambda * inInvMass1) * inWorldSpaceAxis);- ioMotionProperties1->SubAngularVelocityStep(inLambda * Vec3::sLoadFloat3Unsafe(mInvI1_R1PlusUxAxis));+ MotionProperties *mp1 = ioBody1.GetMotionPropertiesUnchecked();+ mp1->SubLinearVelocityStep((inLambda * mp1->GetInverseMass()) * inWorldSpaceAxis);+ mp1->SubAngularVelocityStep(inLambda * Vec3::sLoadFloat3Unsafe(mInvI1_R1PlusUxAxis));}- if constexpr (Type2 == EMotionType::Dynamic)+ if (ioBody2.IsDynamic()){- ioMotionProperties2->AddLinearVelocityStep((inLambda * inInvMass2) * inWorldSpaceAxis);- ioMotionProperties2->AddAngularVelocityStep(inLambda * Vec3::sLoadFloat3Unsafe(mInvI2_R2xAxis));+ MotionProperties *mp2 = ioBody2.GetMotionPropertiesUnchecked();+ mp2->AddLinearVelocityStep((inLambda * mp2->GetInverseMass()) * inWorldSpaceAxis);+ mp2->AddAngularVelocityStep(inLambda * Vec3::sLoadFloat3Unsafe(mInvI2_R2xAxis));}return true;}@@ -72,174 +72,70 @@ class AxisConstraintPart}/// Internal helper function to calculate the inverse effective mass- template <EMotionType Type1, EMotionType Type2>- JPH_INLINE float TemplatedCalculateInverseEffectiveMass(float inInvMass1, Mat44Arg inInvI1, Vec3Arg inR1PlusU, float inInvMass2, Mat44Arg inInvI2, Vec3Arg inR2, Vec3Arg inWorldSpaceAxis)+ JPH_INLINE float CalculateInverseEffectiveMass(const Body &inBody1, Vec3Arg inR1PlusU, const Body &inBody2, Vec3Arg inR2, Vec3Arg inWorldSpaceAxis){JPH_ASSERT(inWorldSpaceAxis.IsNormalized(1.0e-5f));- // Calculate properties used below- Vec3 r1_plus_u_x_axis;- if constexpr (Type1 != EMotionType::Static)+ // Calculate inverse effective mass: K = J M^-1 J^T+ float inv_effective_mass;++ if (!inBody1.IsStatic()){- r1_plus_u_x_axis = inR1PlusU.Cross(inWorldSpaceAxis);+ Vec3 r1_plus_u_x_axis = inR1PlusU.Cross(inWorldSpaceAxis);r1_plus_u_x_axis.StoreFloat3(&mR1PlusUxAxis);- }- else- {- #ifdef JPH_DEBUG- Vec3::sNaN().StoreFloat3(&mR1PlusUxAxis);- #endif- }- Vec3 r2_x_axis;- if constexpr (Type2 != EMotionType::Static)- {- r2_x_axis = inR2.Cross(inWorldSpaceAxis);- r2_x_axis.StoreFloat3(&mR2xAxis);- }- else- {- #ifdef JPH_DEBUG- Vec3::sNaN().StoreFloat3(&mR2xAxis);- #endif- }+ if (inBody1.IsDynamic())+ {+ const MotionProperties *mp1 = inBody1.GetMotionPropertiesUnchecked();+ Vec3 invi1_r1_plus_u_x_axis = mp1->MultiplyWorldSpaceInverseInertiaByVector(inBody1.GetRotation(), r1_plus_u_x_axis);+ invi1_r1_plus_u_x_axis.StoreFloat3(&mInvI1_R1PlusUxAxis);- // Calculate inverse effective mass: K = J M^-1 J^T- float inv_effective_mass;+ inv_effective_mass = mp1->GetInverseMass() + invi1_r1_plus_u_x_axis.Dot(r1_plus_u_x_axis);+ }+ else+ {+ JPH_IF_DEBUG(Vec3::sNaN().StoreFloat3(&mInvI1_R1PlusUxAxis);)- if constexpr (Type1 == EMotionType::Dynamic)- {- Vec3 invi1_r1_plus_u_x_axis = inInvI1.Multiply3x3(r1_plus_u_x_axis);- invi1_r1_plus_u_x_axis.StoreFloat3(&mInvI1_R1PlusUxAxis);- inv_effective_mass = inInvMass1 + invi1_r1_plus_u_x_axis.Dot(r1_plus_u_x_axis);+ inv_effective_mass = 0.0f;+ }}else{- (void)r1_plus_u_x_axis; // Fix compiler warning: Not using this (it's not calculated either)+ JPH_IF_DEBUG(Vec3::sNaN().StoreFloat3(&mR1PlusUxAxis);)JPH_IF_DEBUG(Vec3::sNaN().StoreFloat3(&mInvI1_R1PlusUxAxis);)+inv_effective_mass = 0.0f;}- if constexpr (Type2 == EMotionType::Dynamic)+ if (!inBody2.IsStatic()){- Vec3 invi2_r2_x_axis = inInvI2.Multiply3x3(r2_x_axis);- invi2_r2_x_axis.StoreFloat3(&mInvI2_R2xAxis);- inv_effective_mass += inInvMass2 + invi2_r2_x_axis.Dot(r2_x_axis);- }- else- {- (void)r2_x_axis; // Fix compiler warning: Not using this (it's not calculated either)- JPH_IF_DEBUG(Vec3::sNaN().StoreFloat3(&mInvI2_R2xAxis);)- }-- return inv_effective_mass;- }+ Vec3 r2_x_axis = inR2.Cross(inWorldSpaceAxis);+ r2_x_axis.StoreFloat3(&mR2xAxis);- /// Internal helper function to calculate the inverse effective mass- JPH_INLINE float CalculateInverseEffectiveMass(const Body &inBody1, Vec3Arg inR1PlusU, const Body &inBody2, Vec3Arg inR2, Vec3Arg inWorldSpaceAxis)- {- // Dispatch to the correct templated form- switch (inBody1.GetMotionType())- {- case EMotionType::Dynamic:+ if (inBody2.IsDynamic()){- const MotionProperties *mp1 = inBody1.GetMotionPropertiesUnchecked();- float inv_m1 = mp1->GetInverseMass();- Mat44 inv_i1 = inBody1.GetInverseInertia();- switch (inBody2.GetMotionType())- {- case EMotionType::Dynamic:- return TemplatedCalculateInverseEffectiveMass<EMotionType::Dynamic, EMotionType::Dynamic>(inv_m1, inv_i1, inR1PlusU, inBody2.GetMotionPropertiesUnchecked()->GetInverseMass(), inBody2.GetInverseInertia(), inR2, inWorldSpaceAxis);-- case EMotionType::Kinematic:- return TemplatedCalculateInverseEffectiveMass<EMotionType::Dynamic, EMotionType::Kinematic>(inv_m1, inv_i1, inR1PlusU, 0 /* Will not be used */, Mat44() /* Will not be used */, inR2, inWorldSpaceAxis);-- case EMotionType::Static:- return TemplatedCalculateInverseEffectiveMass<EMotionType::Dynamic, EMotionType::Static>(inv_m1, inv_i1, inR1PlusU, 0 /* Will not be used */, Mat44() /* Will not be used */, inR2, inWorldSpaceAxis);-- default:- break;- }- break;- }-- case EMotionType::Kinematic:- JPH_ASSERT(inBody2.IsDynamic());- return TemplatedCalculateInverseEffectiveMass<EMotionType::Kinematic, EMotionType::Dynamic>(0 /* Will not be used */, Mat44() /* Will not be used */, inR1PlusU, inBody2.GetMotionPropertiesUnchecked()->GetInverseMass(), inBody2.GetInverseInertia(), inR2, inWorldSpaceAxis);-- case EMotionType::Static:- JPH_ASSERT(inBody2.IsDynamic());- return TemplatedCalculateInverseEffectiveMass<EMotionType::Static, EMotionType::Dynamic>(0 /* Will not be used */, Mat44() /* Will not be used */, inR1PlusU, inBody2.GetMotionPropertiesUnchecked()->GetInverseMass(), inBody2.GetInverseInertia(), inR2, inWorldSpaceAxis);-- default:- break;- }+ const MotionProperties *mp2 = inBody2.GetMotionPropertiesUnchecked();+ Vec3 invi2_r2_x_axis = mp2->MultiplyWorldSpaceInverseInertiaByVector(inBody2.GetRotation(), r2_x_axis);+ invi2_r2_x_axis.StoreFloat3(&mInvI2_R2xAxis);- JPH_ASSERT(false);- return 0.0f;- }-- /// Internal helper function to calculate the inverse effective mass, version that supports mass scaling- JPH_INLINE float CalculateInverseEffectiveMassWithMassOverride(const Body &inBody1, float inInvMass1, float inInvInertiaScale1, Vec3Arg inR1PlusU, const Body &inBody2, float inInvMass2, float inInvInertiaScale2, Vec3Arg inR2, Vec3Arg inWorldSpaceAxis)- {- // Dispatch to the correct templated form- switch (inBody1.GetMotionType())- {- case EMotionType::Dynamic:+ inv_effective_mass += mp2->GetInverseMass() + invi2_r2_x_axis.Dot(r2_x_axis);+ }+ else{- Mat44 inv_i1 = inInvInertiaScale1 * inBody1.GetInverseInertia();- switch (inBody2.GetMotionType())- {- case EMotionType::Dynamic:- return TemplatedCalculateInverseEffectiveMass<EMotionType::Dynamic, EMotionType::Dynamic>(inInvMass1, inv_i1, inR1PlusU, inInvMass2, inInvInertiaScale2 * inBody2.GetInverseInertia(), inR2, inWorldSpaceAxis);-- case EMotionType::Kinematic:- return TemplatedCalculateInverseEffectiveMass<EMotionType::Dynamic, EMotionType::Kinematic>(inInvMass1, inv_i1, inR1PlusU, 0 /* Will not be used */, Mat44() /* Will not be used */, inR2, inWorldSpaceAxis);-- case EMotionType::Static:- return TemplatedCalculateInverseEffectiveMass<EMotionType::Dynamic, EMotionType::Static>(inInvMass1, inv_i1, inR1PlusU, 0 /* Will not be used */, Mat44() /* Will not be used */, inR2, inWorldSpaceAxis);-- default:- break;- }- break;+ JPH_IF_DEBUG(Vec3::sNaN().StoreFloat3(&mInvI2_R2xAxis);)}-- case EMotionType::Kinematic:- JPH_ASSERT(inBody2.IsDynamic());- return TemplatedCalculateInverseEffectiveMass<EMotionType::Kinematic, EMotionType::Dynamic>(0 /* Will not be used */, Mat44() /* Will not be used */, inR1PlusU, inInvMass2, inInvInertiaScale2 * inBody2.GetInverseInertia(), inR2, inWorldSpaceAxis);-- case EMotionType::Static:- JPH_ASSERT(inBody2.IsDynamic());- return TemplatedCalculateInverseEffectiveMass<EMotionType::Static, EMotionType::Dynamic>(0 /* Will not be used */, Mat44() /* Will not be used */, inR1PlusU, inInvMass2, inInvInertiaScale2 * inBody2.GetInverseInertia(), inR2, inWorldSpaceAxis);-- default:- break;}-- JPH_ASSERT(false);- return 0.0f;- }--public:- /// Templated form of CalculateConstraintProperties with the motion types baked in- template <EMotionType Type1, EMotionType Type2>- JPH_INLINE void TemplatedCalculateConstraintProperties(float inInvMass1, Mat44Arg inInvI1, Vec3Arg inR1PlusU, float inInvMass2, Mat44Arg inInvI2, Vec3Arg inR2, Vec3Arg inWorldSpaceAxis, float inBias = 0.0f)- {- float inv_effective_mass = TemplatedCalculateInverseEffectiveMass<Type1, Type2>(inInvMass1, inInvI1, inR1PlusU, inInvMass2, inInvI2, inR2, inWorldSpaceAxis);-- if (inv_effective_mass == 0.0f)- Deactivate();else{- mEffectiveMass = 1.0f / inv_effective_mass;- mSpringPart.CalculateSpringPropertiesWithBias(inBias);+ JPH_IF_DEBUG(Vec3::sNaN().StoreFloat3(&mR2xAxis);)+ JPH_IF_DEBUG(Vec3::sNaN().StoreFloat3(&mInvI2_R2xAxis);)}- JPH_DET_LOG("TemplatedCalculateConstraintProperties: invM1: " << inInvMass1 << " invI1: " << inInvI1 << " r1PlusU: " << inR1PlusU << " invM2: " << inInvMass2 << " invI2: " << inInvI2 << " r2: " << inR2 << " bias: " << inBias << " r1PlusUxAxis: " << mR1PlusUxAxis << " r2xAxis: " << mR2xAxis << " invI1_R1PlusUxAxis: " << mInvI1_R1PlusUxAxis << " invI2_R2xAxis: " << mInvI2_R2xAxis << " effectiveMass: " << mEffectiveMass << " totalLambda: " << mTotalLambda);+ return inv_effective_mass;}- /// Calculate properties used during the functions below+public:+ /// Calculate properties used during the functions below. Creates a constraint without spring./// @param inBody1 The first body that this constraint is attached to/// @param inBody2 The second body that this constraint is attached to/// @param inR1PlusU See equations above (r1 + u)@@ -259,23 +155,25 @@ public:}}- /// Calculate properties used during the functions below, version that supports mass scaling+ /// Calculate properties used during the functions below. Set inFrequency to zero if you don't want to drive using a spring.+ /// @param inDeltaTime Time step/// @param inBody1 The first body that this constraint is attached to/// @param inBody2 The second body that this constraint is attached to- /// @param inInvMass1 The inverse mass of body 1 (only used when body 1 is dynamic)- /// @param inInvMass2 The inverse mass of body 2 (only used when body 2 is dynamic)- /// @param inInvInertiaScale1 Scale factor for the inverse inertia of body 1- /// @param inInvInertiaScale2 Scale factor for the inverse inertia of body 2/// @param inR1PlusU See equations above (r1 + u)/// @param inR2 See equations above (r2)/// @param inWorldSpaceAxis Axis along which the constraint acts (normalized, pointing from body 1 to 2)/// @param inBias Bias term (b) for the constraint impulse: lambda = J v + b- inline void CalculateConstraintPropertiesWithMassOverride(const Body &inBody1, float inInvMass1, float inInvInertiaScale1, Vec3Arg inR1PlusU, const Body &inBody2, float inInvMass2, float inInvInertiaScale2, Vec3Arg inR2, Vec3Arg inWorldSpaceAxis, float inBias = 0.0f)+ /// @param inC Value of the constraint equation (C).+ /// @param inFrequency Oscillation frequency (Hz).+ /// @param inDamping Damping factor (0 = no damping, 1 = critical damping).+ inline void CalculateConstraintPropertiesWithFrequencyAndDamping(float inDeltaTime, const Body &inBody1, Vec3Arg inR1PlusU, const Body &inBody2, Vec3Arg inR2, Vec3Arg inWorldSpaceAxis, float inBias, float inC, float inFrequency, float inDamping){- float inv_effective_mass = CalculateInverseEffectiveMassWithMassOverride(inBody1, inInvMass1, inInvInertiaScale1, inR1PlusU, inBody2, inInvMass2, inInvInertiaScale2, inR2, inWorldSpaceAxis);+ float inv_effective_mass = CalculateInverseEffectiveMass(inBody1, inR1PlusU, inBody2, inR2, inWorldSpaceAxis);if (inv_effective_mass == 0.0f)Deactivate();+ else if (inFrequency > 0.0f)+ mSpringPart.CalculateSpringPropertiesWithFrequencyAndDamping(inDeltaTime, inv_effective_mass, inBias, inC, inFrequency, inDamping, mEffectiveMass);else{mEffectiveMass = 1.0f / inv_effective_mass;@@ -283,7 +181,7 @@ public:}}- /// Calculate properties used during the functions below+ /// Calculate properties used during the functions below. Set inFrequency and inDamping to zero if you don't want to drive using a spring./// @param inDeltaTime Time step/// @param inBody1 The first body that this constraint is attached to/// @param inBody2 The second body that this constraint is attached to@@ -292,50 +190,52 @@ public:/// @param inWorldSpaceAxis Axis along which the constraint acts (normalized, pointing from body 1 to 2)/// @param inBias Bias term (b) for the constraint impulse: lambda = J v + b/// @param inC Value of the constraint equation (C).- /// @param inFrequency Oscillation frequency (Hz).- /// @param inDamping Damping factor (0 = no damping, 1 = critical damping).- inline void CalculateConstraintPropertiesWithFrequencyAndDamping(float inDeltaTime, const Body &inBody1, Vec3Arg inR1PlusU, const Body &inBody2, Vec3Arg inR2, Vec3Arg inWorldSpaceAxis, float inBias, float inC, float inFrequency, float inDamping)+ /// @param inStiffness Spring stiffness k.+ /// @param inDamping Spring damping coefficient c.+ inline void CalculateConstraintPropertiesWithStiffnessAndDamping(float inDeltaTime, const Body &inBody1, Vec3Arg inR1PlusU, const Body &inBody2, Vec3Arg inR2, Vec3Arg inWorldSpaceAxis, float inBias, float inC, float inStiffness, float inDamping){float inv_effective_mass = CalculateInverseEffectiveMass(inBody1, inR1PlusU, inBody2, inR2, inWorldSpaceAxis);if (inv_effective_mass == 0.0f)Deactivate();+ else if (inStiffness > 0.0f || inDamping > 0.0f)+ mSpringPart.CalculateSpringPropertiesWithStiffnessAndDamping(inDeltaTime, inv_effective_mass, inBias, inC, inStiffness, inDamping, mEffectiveMass);else- mSpringPart.CalculateSpringPropertiesWithFrequencyAndDamping(inDeltaTime, inv_effective_mass, inBias, inC, inFrequency, inDamping, mEffectiveMass);+ {+ mEffectiveMass = 1.0f / inv_effective_mass;+ mSpringPart.CalculateSpringPropertiesWithBias(inBias);+ }}- /// Calculate properties used during the functions below- /// @param inDeltaTime Time step- /// @param inBody1 The first body that this constraint is attached to- /// @param inBody2 The second body that this constraint is attached to- /// @param inR1PlusU See equations above (r1 + u)- /// @param inR2 See equations above (r2)- /// @param inWorldSpaceAxis Axis along which the constraint acts (normalized, pointing from body 1 to 2)- /// @param inBias Bias term (b) for the constraint impulse: lambda = J v + b- /// @param inC Value of the constraint equation (C).- /// @param inStiffness Spring stiffness k.- /// @param inDamping Spring damping coefficient c.- inline void CalculateConstraintPropertiesWithStiffnessAndDamping(float inDeltaTime, const Body &inBody1, Vec3Arg inR1PlusU, const Body &inBody2, Vec3Arg inR2, Vec3Arg inWorldSpaceAxis, float inBias, float inC, float inStiffness, float inDamping)+ /// Calculate properties used during the functions below based on inSpringSettings.+ /// Turns to a hard limit when inSpringSettings has stiffness / frequency = 0+ inline void CalculateConstraintPropertiesWithSettingsForLimit(float inDeltaTime, const Body &inBody1, Vec3Arg inR1PlusU, const Body &inBody2, Vec3Arg inR2, Vec3Arg inWorldSpaceAxis, float inBias, float inC, const SpringSettings &inSpringSettings){float inv_effective_mass = CalculateInverseEffectiveMass(inBody1, inR1PlusU, inBody2, inR2, inWorldSpaceAxis);if (inv_effective_mass == 0.0f)Deactivate();+ else if (!inSpringSettings.HasStiffness())+ {+ mEffectiveMass = 1.0f / inv_effective_mass;+ mSpringPart.CalculateSpringPropertiesWithBias(inBias);+ }else- mSpringPart.CalculateSpringPropertiesWithStiffnessAndDamping(inDeltaTime, inv_effective_mass, inBias, inC, inStiffness, inDamping, mEffectiveMass);+ mSpringPart.CalculateSpringPropertiesWithSettings(inDeltaTime, inv_effective_mass, inBias, inC, inSpringSettings, mEffectiveMass);}- /// Selects one of the above functions based on the spring settings- inline void CalculateConstraintPropertiesWithSettings(float inDeltaTime, const Body &inBody1, Vec3Arg inR1PlusU, const Body &inBody2, Vec3Arg inR2, Vec3Arg inWorldSpaceAxis, float inBias, float inC, const SpringSettings &inSpringSettings)+ /// Calculate properties used during the functions below based on inSpringSettings.+ /// Assumes the spring has either stiffness or damping.+ inline void CalculateConstraintPropertiesWithSettingsForMotor(float inDeltaTime, const Body &inBody1, Vec3Arg inR1PlusU, const Body &inBody2, Vec3Arg inR2, Vec3Arg inWorldSpaceAxis, float inBias, float inC, const SpringSettings &inSpringSettings){+ JPH_ASSERT(inSpringSettings.HasStiffnessOrDamping());+float inv_effective_mass = CalculateInverseEffectiveMass(inBody1, inR1PlusU, inBody2, inR2, inWorldSpaceAxis);if (inv_effective_mass == 0.0f)Deactivate();- else if (inSpringSettings.mMode == ESpringMode::FrequencyAndDamping)- mSpringPart.CalculateSpringPropertiesWithFrequencyAndDamping(inDeltaTime, inv_effective_mass, inBias, inC, inSpringSettings.mFrequency, inSpringSettings.mDamping, mEffectiveMass);else- mSpringPart.CalculateSpringPropertiesWithStiffnessAndDamping(inDeltaTime, inv_effective_mass, inBias, inC, inSpringSettings.mStiffness, inSpringSettings.mDamping, mEffectiveMass);+ mSpringPart.CalculateSpringPropertiesWithSettings(inDeltaTime, inv_effective_mass, inBias, inC, inSpringSettings, mEffectiveMass);}/// Deactivate this constraint@@ -351,198 +251,65 @@ public:return mEffectiveMass != 0.0f;}- /// Templated form of WarmStart with the motion types baked in- template <EMotionType Type1, EMotionType Type2>- inline void TemplatedWarmStart(MotionProperties *ioMotionProperties1, float inInvMass1, MotionProperties *ioMotionProperties2, float inInvMass2, Vec3Arg inWorldSpaceAxis, float inWarmStartImpulseRatio)+ /// Must be called from the WarmStartVelocityConstraint call to apply the previous frame's impulses+ /// @param ioBody1 The first body that this constraint is attached to+ /// @param ioBody2 The second body that this constraint is attached to+ /// @param inWorldSpaceAxis Axis along which the constraint acts (normalized)+ /// @param inWarmStartImpulseRatio Ratio of new step to old time step (dt_new / dt_old) for scaling the lagrange multiplier of the previous frame+ inline void WarmStart(Body &ioBody1, Body &ioBody2, Vec3Arg inWorldSpaceAxis, float inWarmStartImpulseRatio){mTotalLambda *= inWarmStartImpulseRatio;- ApplyVelocityStep<Type1, Type2>(ioMotionProperties1, inInvMass1, ioMotionProperties2, inInvMass2, inWorldSpaceAxis, mTotalLambda);+ ApplyVelocityStep(ioBody1, ioBody2, inWorldSpaceAxis, mTotalLambda);}- /// Must be called from the WarmStartVelocityConstraint call to apply the previous frame's impulses+ /// Iteratively update the velocity constraint. Makes sure d/dt C(...) = 0, where C is the constraint equation./// @param ioBody1 The first body that this constraint is attached to/// @param ioBody2 The second body that this constraint is attached to/// @param inWorldSpaceAxis Axis along which the constraint acts (normalized)- /// @param inWarmStartImpulseRatio Ratio of new step to old time step (dt_new / dt_old) for scaling the lagrange multiplier of the previous frame- inline void WarmStart(Body &ioBody1, Body &ioBody2, Vec3Arg inWorldSpaceAxis, float inWarmStartImpulseRatio)+ /// @param inMinLambda Minimum value of constraint impulse to apply (N s)+ /// @param inMaxLambda Maximum value of constraint impulse to apply (N s)+ inline bool SolveVelocityConstraint(Body &ioBody1, Body &ioBody2, Vec3Arg inWorldSpaceAxis, float inMinLambda, float inMaxLambda){- EMotionType motion_type1 = ioBody1.GetMotionType();- MotionProperties *motion_properties1 = ioBody1.GetMotionPropertiesUnchecked();-- EMotionType motion_type2 = ioBody2.GetMotionType();- MotionProperties *motion_properties2 = ioBody2.GetMotionPropertiesUnchecked();+ const MotionProperties *mp1 = ioBody1.GetMotionPropertiesUnchecked();+ const MotionProperties *mp2 = ioBody2.GetMotionPropertiesUnchecked();- // Dispatch to the correct templated form- // Note: Warm starting doesn't differentiate between kinematic/static bodies so we handle both as static bodies- if (motion_type1 == EMotionType::Dynamic)+ // Calculate jacobian multiplied by linear velocity+ float jv;+ if (!ioBody1.IsStatic()){- if (motion_type2 == EMotionType::Dynamic)- TemplatedWarmStart<EMotionType::Dynamic, EMotionType::Dynamic>(motion_properties1, motion_properties1->GetInverseMass(), motion_properties2, motion_properties2->GetInverseMass(), inWorldSpaceAxis, inWarmStartImpulseRatio);+ if (!ioBody2.IsStatic())+ jv = inWorldSpaceAxis.Dot(mp1->GetLinearVelocity() - mp2->GetLinearVelocity());else- TemplatedWarmStart<EMotionType::Dynamic, EMotionType::Static>(motion_properties1, motion_properties1->GetInverseMass(), motion_properties2, 0.0f /* Unused */, inWorldSpaceAxis, inWarmStartImpulseRatio);+ jv = inWorldSpaceAxis.Dot(mp1->GetLinearVelocity());}else{- JPH_ASSERT(motion_type2 == EMotionType::Dynamic);- TemplatedWarmStart<EMotionType::Static, EMotionType::Dynamic>(motion_properties1, 0.0f /* Unused */, motion_properties2, motion_properties2->GetInverseMass(), inWorldSpaceAxis, inWarmStartImpulseRatio);+ JPH_ASSERT(!ioBody2.IsStatic());+ jv = inWorldSpaceAxis.Dot(-mp2->GetLinearVelocity());}- }-- /// Templated form of SolveVelocityConstraint with the motion types baked in, part 1: get the total lambda- template <EMotionType Type1, EMotionType Type2>- JPH_INLINE float TemplatedSolveVelocityConstraintGetTotalLambda(const MotionProperties *ioMotionProperties1, const MotionProperties *ioMotionProperties2, Vec3Arg inWorldSpaceAxis) const- {- // Calculate jacobian multiplied by linear velocity- float jv;- if constexpr (Type1 != EMotionType::Static && Type2 != EMotionType::Static)- jv = inWorldSpaceAxis.Dot(ioMotionProperties1->GetLinearVelocity() - ioMotionProperties2->GetLinearVelocity());- else if constexpr (Type1 != EMotionType::Static)- jv = inWorldSpaceAxis.Dot(ioMotionProperties1->GetLinearVelocity());- else if constexpr (Type2 != EMotionType::Static)- jv = inWorldSpaceAxis.Dot(-ioMotionProperties2->GetLinearVelocity());- else- JPH_ASSERT(false); // Static vs static is nonsensical!// Calculate jacobian multiplied by angular velocity- if constexpr (Type1 != EMotionType::Static)- jv += Vec3::sLoadFloat3Unsafe(mR1PlusUxAxis).Dot(ioMotionProperties1->GetAngularVelocity());- if constexpr (Type2 != EMotionType::Static)- jv -= Vec3::sLoadFloat3Unsafe(mR2xAxis).Dot(ioMotionProperties2->GetAngularVelocity());+ if (!ioBody1.IsStatic())+ jv += Vec3::sLoadFloat3Unsafe(mR1PlusUxAxis).Dot(mp1->GetAngularVelocity());+ if (!ioBody2.IsStatic())+ jv -= Vec3::sLoadFloat3Unsafe(mR2xAxis).Dot(mp2->GetAngularVelocity());// Lagrange multiplier is://// lambda = -K^-1 (J v + b)float lambda = mEffectiveMass * (jv - mSpringPart.GetBias(mTotalLambda));+ float new_lambda = Clamp(mTotalLambda + lambda, inMinLambda, inMaxLambda); // Clamp impulse+ lambda = new_lambda - mTotalLambda; // Lambda potentially got clamped, calculate the new impulse to apply+ mTotalLambda = new_lambda; // Store accumulated impulse- // Return the total accumulated lambda- return mTotalLambda + lambda;- }-- /// Templated form of SolveVelocityConstraint with the motion types baked in, part 2: apply new lambda- template <EMotionType Type1, EMotionType Type2>- JPH_INLINE bool TemplatedSolveVelocityConstraintApplyLambda(MotionProperties *ioMotionProperties1, float inInvMass1, MotionProperties *ioMotionProperties2, float inInvMass2, Vec3Arg inWorldSpaceAxis, float inTotalLambda)- {- float delta_lambda = inTotalLambda - mTotalLambda; // Calculate change in lambda- mTotalLambda = inTotalLambda; // Store accumulated impulse-- return ApplyVelocityStep<Type1, Type2>(ioMotionProperties1, inInvMass1, ioMotionProperties2, inInvMass2, inWorldSpaceAxis, delta_lambda);- }-- /// Templated form of SolveVelocityConstraint with the motion types baked in- template <EMotionType Type1, EMotionType Type2>- inline bool TemplatedSolveVelocityConstraint(MotionProperties *ioMotionProperties1, float inInvMass1, MotionProperties *ioMotionProperties2, float inInvMass2, Vec3Arg inWorldSpaceAxis, float inMinLambda, float inMaxLambda)- {- float total_lambda = TemplatedSolveVelocityConstraintGetTotalLambda<Type1, Type2>(ioMotionProperties1, ioMotionProperties2, inWorldSpaceAxis);-- // Clamp impulse to specified range- total_lambda = Clamp(total_lambda, inMinLambda, inMaxLambda);-- return TemplatedSolveVelocityConstraintApplyLambda<Type1, Type2>(ioMotionProperties1, inInvMass1, ioMotionProperties2, inInvMass2, inWorldSpaceAxis, total_lambda);+ return ApplyVelocityStep(ioBody1, ioBody2, inWorldSpaceAxis, lambda);}- /// Iteratively update the velocity constraint. Makes sure d/dt C(...) = 0, where C is the constraint equation.- /// @param ioBody1 The first body that this constraint is attached to- /// @param ioBody2 The second body that this constraint is attached to- /// @param inWorldSpaceAxis Axis along which the constraint acts (normalized)- /// @param inMinLambda Minimum value of constraint impulse to apply (N s)- /// @param inMaxLambda Maximum value of constraint impulse to apply (N s)- inline bool SolveVelocityConstraint(Body &ioBody1, Body &ioBody2, Vec3Arg inWorldSpaceAxis, float inMinLambda, float inMaxLambda)- {- EMotionType motion_type1 = ioBody1.GetMotionType();- MotionProperties *motion_properties1 = ioBody1.GetMotionPropertiesUnchecked();-- EMotionType motion_type2 = ioBody2.GetMotionType();- MotionProperties *motion_properties2 = ioBody2.GetMotionPropertiesUnchecked();-- // Dispatch to the correct templated form- switch (motion_type1)- {- case EMotionType::Dynamic:- switch (motion_type2)- {- case EMotionType::Dynamic:- return TemplatedSolveVelocityConstraint<EMotionType::Dynamic, EMotionType::Dynamic>(motion_properties1, motion_properties1->GetInverseMass(), motion_properties2, motion_properties2->GetInverseMass(), inWorldSpaceAxis, inMinLambda, inMaxLambda);-- case EMotionType::Kinematic:- return TemplatedSolveVelocityConstraint<EMotionType::Dynamic, EMotionType::Kinematic>(motion_properties1, motion_properties1->GetInverseMass(), motion_properties2, 0.0f /* Unused */, inWorldSpaceAxis, inMinLambda, inMaxLambda);-- case EMotionType::Static:- return TemplatedSolveVelocityConstraint<EMotionType::Dynamic, EMotionType::Static>(motion_properties1, motion_properties1->GetInverseMass(), motion_properties2, 0.0f /* Unused */, inWorldSpaceAxis, inMinLambda, inMaxLambda);-- default:- JPH_ASSERT(false);- break;- }- break;-- case EMotionType::Kinematic:- JPH_ASSERT(motion_type2 == EMotionType::Dynamic);- return TemplatedSolveVelocityConstraint<EMotionType::Kinematic, EMotionType::Dynamic>(motion_properties1, 0.0f /* Unused */, motion_properties2, motion_properties2->GetInverseMass(), inWorldSpaceAxis, inMinLambda, inMaxLambda);-- case EMotionType::Static:- JPH_ASSERT(motion_type2 == EMotionType::Dynamic);- return TemplatedSolveVelocityConstraint<EMotionType::Static, EMotionType::Dynamic>(motion_properties1, 0.0f /* Unused */, motion_properties2, motion_properties2->GetInverseMass(), inWorldSpaceAxis, inMinLambda, inMaxLambda);-- default:- JPH_ASSERT(false);- break;- }-- return false;- }-- /// Iteratively update the velocity constraint. Makes sure d/dt C(...) = 0, where C is the constraint equation.- /// @param ioBody1 The first body that this constraint is attached to- /// @param ioBody2 The second body that this constraint is attached to- /// @param inInvMass1 The inverse mass of body 1 (only used when body 1 is dynamic)- /// @param inInvMass2 The inverse mass of body 2 (only used when body 2 is dynamic)- /// @param inWorldSpaceAxis Axis along which the constraint acts (normalized)- /// @param inMinLambda Minimum value of constraint impulse to apply (N s)- /// @param inMaxLambda Maximum value of constraint impulse to apply (N s)- inline bool SolveVelocityConstraintWithMassOverride(Body &ioBody1, float inInvMass1, Body &ioBody2, float inInvMass2, Vec3Arg inWorldSpaceAxis, float inMinLambda, float inMaxLambda)+ /// Return lagrange multiplier+ float GetTotalLambda() const{- EMotionType motion_type1 = ioBody1.GetMotionType();- MotionProperties *motion_properties1 = ioBody1.GetMotionPropertiesUnchecked();-- EMotionType motion_type2 = ioBody2.GetMotionType();- MotionProperties *motion_properties2 = ioBody2.GetMotionPropertiesUnchecked();-- // Dispatch to the correct templated form- switch (motion_type1)- {- case EMotionType::Dynamic:- switch (motion_type2)- {- case EMotionType::Dynamic:- return TemplatedSolveVelocityConstraint<EMotionType::Dynamic, EMotionType::Dynamic>(motion_properties1, inInvMass1, motion_properties2, inInvMass2, inWorldSpaceAxis, inMinLambda, inMaxLambda);-- case EMotionType::Kinematic:- return TemplatedSolveVelocityConstraint<EMotionType::Dynamic, EMotionType::Kinematic>(motion_properties1, inInvMass1, motion_properties2, 0.0f /* Unused */, inWorldSpaceAxis, inMinLambda, inMaxLambda);-- case EMotionType::Static:- return TemplatedSolveVelocityConstraint<EMotionType::Dynamic, EMotionType::Static>(motion_properties1, inInvMass1, motion_properties2, 0.0f /* Unused */, inWorldSpaceAxis, inMinLambda, inMaxLambda);-- default:- JPH_ASSERT(false);- break;- }- break;-- case EMotionType::Kinematic:- JPH_ASSERT(motion_type2 == EMotionType::Dynamic);- return TemplatedSolveVelocityConstraint<EMotionType::Kinematic, EMotionType::Dynamic>(motion_properties1, 0.0f /* Unused */, motion_properties2, inInvMass2, inWorldSpaceAxis, inMinLambda, inMaxLambda);-- case EMotionType::Static:- JPH_ASSERT(motion_type2 == EMotionType::Dynamic);- return TemplatedSolveVelocityConstraint<EMotionType::Static, EMotionType::Dynamic>(motion_properties1, 0.0f /* Unused */, motion_properties2, inInvMass2, inWorldSpaceAxis, inMinLambda, inMaxLambda);-- default:- JPH_ASSERT(false);- break;- }-- return false;+ return mTotalLambda;}/// Iteratively update the position constraint. Makes sure C(...) = 0.@@ -594,69 +361,6 @@ public:return false;}- /// Iteratively update the position constraint. Makes sure C(...) = 0.- /// @param ioBody1 The first body that this constraint is attached to- /// @param ioBody2 The second body that this constraint is attached to- /// @param inInvMass1 The inverse mass of body 1 (only used when body 1 is dynamic)- /// @param inInvMass2 The inverse mass of body 2 (only used when body 2 is dynamic)- /// @param inWorldSpaceAxis Axis along which the constraint acts (normalized)- /// @param inC Value of the constraint equation (C)- /// @param inBaumgarte Baumgarte constant (fraction of the error to correct)- inline bool SolvePositionConstraintWithMassOverride(Body &ioBody1, float inInvMass1, Body &ioBody2, float inInvMass2, Vec3Arg inWorldSpaceAxis, float inC, float inBaumgarte) const- {- // Only apply position constraint when the constraint is hard, otherwise the velocity bias will fix the constraint- if (inC != 0.0f && !mSpringPart.IsActive())- {- // Calculate lagrange multiplier (lambda) for Baumgarte stabilization:- //- // lambda = -K^-1 * beta / dt * C- //- // We should divide by inDeltaTime, but we should multiply by inDeltaTime in the Euler step below so they're cancelled out- float lambda = -mEffectiveMass * inBaumgarte * inC;-- // Directly integrate velocity change for one time step- //- // Euler velocity integration:- // dv = M^-1 P- //- // Impulse:- // P = J^T lambda- //- // Euler position integration:- // x' = x + dv * dt- //- // Note we don't accumulate velocities for the stabilization. This is using the approach described in 'Modeling and- // Solving Constraints' by Erin Catto presented at GDC 2007. On slide 78 it is suggested to split up the Baumgarte- // stabilization for positional drift so that it does not actually add to the momentum. We combine an Euler velocity- // integrate + a position integrate and then discard the velocity change.- if (ioBody1.IsDynamic())- {- ioBody1.SubPositionStep((lambda * inInvMass1) * inWorldSpaceAxis);- ioBody1.SubRotationStep(lambda * Vec3::sLoadFloat3Unsafe(mInvI1_R1PlusUxAxis));- }- if (ioBody2.IsDynamic())- {- ioBody2.AddPositionStep((lambda * inInvMass2) * inWorldSpaceAxis);- ioBody2.AddRotationStep(lambda * Vec3::sLoadFloat3Unsafe(mInvI2_R2xAxis));- }- return true;- }-- return false;- }-- /// Override total lagrange multiplier, can be used to set the initial value for warm starting- inline void SetTotalLambda(float inLambda)- {- mTotalLambda = inLambda;- }-- /// Return lagrange multiplier- inline float GetTotalLambda() const- {- return mTotalLambda;- }-/// Save state of this constraint partvoid SaveState(StateRecorder &inStream) const{diff --git a/thirdparty/jolt_physics/Jolt/Physics/Constraints/ConstraintPart/ContactConstraintPart.h b/thirdparty/jolt_physics/Jolt/Physics/Constraints/ConstraintPart/ContactConstraintPart.hnew file mode 100644index 00000000000..ae2b281d31f--- /dev/null+++ b/thirdparty/jolt_physics/Jolt/Physics/Constraints/ConstraintPart/ContactConstraintPart.h@@ -0,0 +1,254 @@+// Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)+// SPDX-FileCopyrightText: 2026 Jorrit Rouwe+// SPDX-License-Identifier: MIT++#pragma once++#include <Jolt/Physics/Body/Body.h>++JPH_NAMESPACE_BEGIN++/// Decide which members this constraint part needs based on motion type+template <EMotionType Type1>+class ContactConstraintPart1+{+public:+ /// Deactivate this constraint+ inline void Deactivate()+ {+ mEffectiveMass = 0.0f;+ mTotalLambda = 0.0f;+ }++ /// Check if constraint is active+ inline bool IsActive() const+ {+ return mEffectiveMass != 0.0f;+ }++ /// Override total lagrange multiplier, can be used to set the initial value for warm starting+ inline void SetTotalLambda(float inLambda)+ {+ mTotalLambda = inLambda;+ }++ /// Return lagrange multiplier+ inline float GetTotalLambda() const+ {+ return mTotalLambda;+ }++protected:+ // Note: Constructor will not be called+ float mEffectiveMass;+ float mTotalLambda;+};++template <>+class ContactConstraintPart1<EMotionType::Kinematic> : public ContactConstraintPart1<EMotionType::Static>+{+protected:+ // Note: Constructor will not be called+ Float3 mR1PlusUxAxis;+};++template <>+class ContactConstraintPart1<EMotionType::Dynamic> : public ContactConstraintPart1<EMotionType::Kinematic>+{+protected:+ // Note: Constructor will not be called+ Float3 mInvI1_R1PlusUxAxis;+};++template <EMotionType Type2>+class ContactConstraintPart2+{+};++template <>+class ContactConstraintPart2<EMotionType::Kinematic> : public ContactConstraintPart2<EMotionType::Static>+{+protected:+ // Note: Constructor will not be called+ Float3 mR2xAxis;+};++template <>+class ContactConstraintPart2<EMotionType::Dynamic> : public ContactConstraintPart2<EMotionType::Kinematic>+{+protected:+ // Note: Constructor will not be called+ Float3 mInvI2_R2xAxis;+};++/// This is a copy of AxisConstraintPart, specialized to handle contact constraints. See the documentation of AxisConstraintPart for more documentation behind the math.+template <EMotionType Type1, EMotionType Type2>+class ContactConstraintPart : public ContactConstraintPart1<Type1>, public ContactConstraintPart2<Type2>+{+private:+ /// See AxisConstraintPart::ApplyVelocityStep+ JPH_INLINE bool ApplyVelocityStep(Vec3 &ioLinearVelocity1, Vec3 &ioAngularVelocity1, Vec3 &ioLinearVelocity2, Vec3 &ioAngularVelocity2, float inInvMass1, float inInvMass2, Vec3Arg inWorldSpaceAxis, float inLambda) const+ {+ if (inLambda != 0.0f)+ {+ if constexpr (Type1 == EMotionType::Dynamic)+ {+ ioLinearVelocity1 -= (inLambda * inInvMass1) * inWorldSpaceAxis;+ ioAngularVelocity1 -= inLambda * Vec3::sLoadFloat3Unsafe(this->mInvI1_R1PlusUxAxis);+ }+ if constexpr (Type2 == EMotionType::Dynamic)+ {+ ioLinearVelocity2 += (inLambda * inInvMass2) * inWorldSpaceAxis;+ ioAngularVelocity2 += inLambda * Vec3::sLoadFloat3Unsafe(this->mInvI2_R2xAxis);+ }+ return true;+ }++ return false;+ }++public:+ /// See AxisConstraintPart::CalculateConstraintProperties+ JPH_INLINE void CalculateConstraintProperties(float inInvMass1, Mat44Arg inInvI1, Vec3Arg inR1PlusU, float inInvMass2, Mat44Arg inInvI2, Vec3Arg inR2, Vec3Arg inWorldSpaceAxis, float inBias = 0.0f)+ {+ JPH_ASSERT(inWorldSpaceAxis.IsNormalized(1.0e-5f));++ // Store bias+ mBias = inBias;++ // Calculate inverse effective mass: K = J M^-1 J^T+ float inv_effective_mass;++ if constexpr (Type1 != EMotionType::Static)+ {+ Vec3 r1_plus_u_x_axis = inR1PlusU.Cross(inWorldSpaceAxis);+ r1_plus_u_x_axis.StoreFloat3(&this->mR1PlusUxAxis);++ if constexpr (Type1 == EMotionType::Dynamic)+ {+ Vec3 invi1_r1_plus_u_x_axis = inInvI1.Multiply3x3(r1_plus_u_x_axis);+ invi1_r1_plus_u_x_axis.StoreFloat3(&this->mInvI1_R1PlusUxAxis);++ inv_effective_mass = inInvMass1 + invi1_r1_plus_u_x_axis.Dot(r1_plus_u_x_axis);+ }+ else+ inv_effective_mass = 0.0f;+ }+ else+ inv_effective_mass = 0.0f;++ if constexpr (Type2 != EMotionType::Static)+ {+ Vec3 r2_x_axis = inR2.Cross(inWorldSpaceAxis);+ r2_x_axis.StoreFloat3(&this->mR2xAxis);++ if constexpr (Type2 == EMotionType::Dynamic)+ {+ Vec3 invi2_r2_x_axis = inInvI2.Multiply3x3(r2_x_axis);+ invi2_r2_x_axis.StoreFloat3(&this->mInvI2_R2xAxis);++ inv_effective_mass += inInvMass2 + invi2_r2_x_axis.Dot(r2_x_axis);+ }+ }++ if (inv_effective_mass == 0.0f)+ this->Deactivate();+ else+ this->mEffectiveMass = 1.0f / inv_effective_mass;+ }++ /// See AxisConstraintPart::WarmStart+ JPH_INLINE bool WarmStart(Vec3 &ioLinearVelocity1, Vec3 &ioAngularVelocity1, Vec3 &ioLinearVelocity2, Vec3 &ioAngularVelocity2, float inInvMass1, float inInvMass2, Vec3Arg inWorldSpaceAxis, float inWarmStartImpulseRatio)+ {+ this->mTotalLambda *= inWarmStartImpulseRatio;++ return ApplyVelocityStep(ioLinearVelocity1, ioAngularVelocity1, ioLinearVelocity2, ioAngularVelocity2, inInvMass1, inInvMass2, inWorldSpaceAxis, this->mTotalLambda);+ }++ /// Part 1 of AxisConstraint::SolveVelocityConstraint: get the total lambda+ JPH_INLINE float SolveVelocityConstraintGetTotalLambda(Vec3Arg inLinearVelocity1, Vec3Arg inAngularVelocity1, Vec3Arg inLinearVelocity2, Vec3Arg inAngularVelocity2, Vec3Arg inWorldSpaceAxis) const+ {+ // Calculate jacobian multiplied by linear velocity+ float jv;+ if constexpr (Type1 != EMotionType::Static && Type2 != EMotionType::Static)+ jv = inWorldSpaceAxis.Dot(inLinearVelocity1 - inLinearVelocity2);+ else if constexpr (Type1 != EMotionType::Static)+ jv = inWorldSpaceAxis.Dot(inLinearVelocity1);+ else if constexpr (Type2 != EMotionType::Static)+ jv = inWorldSpaceAxis.Dot(-inLinearVelocity2);+ else+ JPH_ASSERT(false); // Static vs static is nonsensical!++ // Calculate jacobian multiplied by angular velocity+ if constexpr (Type1 != EMotionType::Static)+ jv += Vec3::sLoadFloat3Unsafe(this->mR1PlusUxAxis).Dot(inAngularVelocity1);+ if constexpr (Type2 != EMotionType::Static)+ jv -= Vec3::sLoadFloat3Unsafe(this->mR2xAxis).Dot(inAngularVelocity2);++ // Lagrange multiplier is:+ //+ // lambda = -K^-1 (J v + b)+ float lambda = this->mEffectiveMass * (jv - mBias);++ // Return the total accumulated lambda+ return this->mTotalLambda + lambda;+ }++ /// Part 2 of AxisConstraint::SolveVelocityConstraint: apply new lambda+ JPH_INLINE bool SolveVelocityConstraintApplyLambda(Vec3 &ioLinearVelocity1, Vec3 &ioAngularVelocity1, Vec3 &ioLinearVelocity2, Vec3 &ioAngularVelocity2, float inInvMass1, float inInvMass2, Vec3Arg inWorldSpaceAxis, float inTotalLambda)+ {+ float delta_lambda = inTotalLambda - this->mTotalLambda; // Calculate change in lambda+ this->mTotalLambda = inTotalLambda; // Store accumulated impulse++ return ApplyVelocityStep(ioLinearVelocity1, ioAngularVelocity1, ioLinearVelocity2, ioAngularVelocity2, inInvMass1, inInvMass2, inWorldSpaceAxis, delta_lambda);+ }++ /// See: AxisConstraintPart::SolveVelocityConstraint+ JPH_INLINE bool SolveVelocityConstraint(Vec3 &ioLinearVelocity1, Vec3 &ioAngularVelocity1, Vec3 &ioLinearVelocity2, Vec3 &ioAngularVelocity2, float inInvMass1, float inInvMass2, Vec3Arg inWorldSpaceAxis, float inMinLambda, float inMaxLambda)+ {+ float total_lambda = SolveVelocityConstraintGetTotalLambda(ioLinearVelocity1, ioAngularVelocity1, ioLinearVelocity2, ioAngularVelocity2, inWorldSpaceAxis);++ // Clamp impulse to specified range+ total_lambda = Clamp(total_lambda, inMinLambda, inMaxLambda);++ return SolveVelocityConstraintApplyLambda(ioLinearVelocity1, ioAngularVelocity1, ioLinearVelocity2, ioAngularVelocity2, inInvMass1, inInvMass2, inWorldSpaceAxis, total_lambda);+ }++ /// See: AxisConstraintPart::SolvePositionConstraint+ JPH_INLINE bool SolvePositionConstraint(Body &ioBody1, float inInvMass1, Body &ioBody2, float inInvMass2, Vec3Arg inWorldSpaceAxis, float inC, float inBaumgarte) const+ {+ if (inC != 0.0f)+ {+ float lambda = -this->mEffectiveMass * inBaumgarte * inC;+ if constexpr (Type1 == EMotionType::Dynamic)+ {+ ioBody1.SubPositionStep((lambda * inInvMass1) * inWorldSpaceAxis);+ ioBody1.SubRotationStep(lambda * Vec3::sLoadFloat3Unsafe(this->mInvI1_R1PlusUxAxis));+ }+ if constexpr (Type2 == EMotionType::Dynamic)+ {+ ioBody2.AddPositionStep((lambda * inInvMass2) * inWorldSpaceAxis);+ ioBody2.AddRotationStep(lambda * Vec3::sLoadFloat3Unsafe(this->mInvI2_R2xAxis));+ }+ return true;+ }++ return false;+ }++private:+ // Note: Constructor will not be called. This serves as 1 extra float so we can read the previous member using Vec3::sLoadFloat3Unsafe+ float mBias;+};++static_assert(sizeof(ContactConstraintPart<EMotionType::Dynamic, EMotionType::Dynamic>) == 3 * sizeof(float) + 4 * sizeof(Float3));+static_assert(sizeof(ContactConstraintPart<EMotionType::Dynamic, EMotionType::Kinematic>) == 3 * sizeof(float) + 3 * sizeof(Float3));+static_assert(sizeof(ContactConstraintPart<EMotionType::Dynamic, EMotionType::Static>) == 3 * sizeof(float) + 2 * sizeof(Float3));+static_assert(sizeof(ContactConstraintPart<EMotionType::Kinematic, EMotionType::Dynamic>) == 3 * sizeof(float) + 3 * sizeof(Float3));+static_assert(sizeof(ContactConstraintPart<EMotionType::Kinematic, EMotionType::Kinematic>) == 3 * sizeof(float) + 2 * sizeof(Float3));+static_assert(sizeof(ContactConstraintPart<EMotionType::Kinematic, EMotionType::Static>) == 3 * sizeof(float) + sizeof(Float3));+static_assert(sizeof(ContactConstraintPart<EMotionType::Static, EMotionType::Dynamic>) == 3 * sizeof(float) + 2 * sizeof(Float3));+static_assert(sizeof(ContactConstraintPart<EMotionType::Static, EMotionType::Kinematic>) == 3 * sizeof(float) + sizeof(Float3));+static_assert(sizeof(ContactConstraintPart<EMotionType::Static, EMotionType::Static>) == 3 * sizeof(float));++JPH_NAMESPACE_ENDdiff --git a/thirdparty/jolt_physics/Jolt/Physics/Constraints/ConstraintPart/SpringPart.h b/thirdparty/jolt_physics/Jolt/Physics/Constraints/ConstraintPart/SpringPart.hindex 0a8a4a9730c..21ba4b65187 100644--- a/thirdparty/jolt_physics/Jolt/Physics/Constraints/ConstraintPart/SpringPart.h+++ b/thirdparty/jolt_physics/Jolt/Physics/Constraints/ConstraintPart/SpringPart.h@@ -4,6 +4,8 @@#pragma once+#include <Jolt/Physics/Constraints/SpringSettings.h>+JPH_NAMESPACE_BEGIN#ifndef JPH_PLATFORM_DOXYGEN // Somehow Doxygen gets confused and thinks the parameters to CalculateSpringProperties belong to this macroJPH_MSVC_SUPPRESS_WARNING(4723) // potential divide by 0 - caused by line: outEffectiveMass = 1.0f / inInvEffectiveMass, note that JPH_NAMESPACE_BEGIN already pushes the warning state@@ -12,9 +14,29 @@ JPH_MSVC_SUPPRESS_WARNING(4723) // potential divide by 0 - caused by line: outEf/// Class used in other constraint parts to calculate the required bias factor in the lagrange multiplier for creating springsclass SpringPart{-private:- JPH_INLINE void CalculateSpringPropertiesHelper(float inDeltaTime, float inInvEffectiveMass, float inBias, float inC, float inStiffness, float inDamping, float &outEffectiveMass)+public:+ /// Turn off the spring and set a bias only+ ///+ /// @param inBias Bias term (b) for the constraint impulse: lambda = J v + b+ JPH_INLINE void CalculateSpringPropertiesWithBias(float inBias)+ {+ mSoftness = 0.0f;+ mBias = inBias;+ }++ /// Calculate spring properties with spring Stiffness (k) and damping (c), this is based on the spring equation: F = -k * x - c * v+ ///+ /// @param inDeltaTime Time step+ /// @param inInvEffectiveMass Inverse effective mass K+ /// @param inBias Bias term (b) for the constraint impulse: lambda = J v + b+ /// @param inC Value of the constraint equation (C).+ /// @param inStiffness Spring stiffness k.+ /// @param inDamping Spring damping coefficient c.+ /// @param outEffectiveMass On return, this contains the new effective mass K^-1+ JPH_INLINE void CalculateSpringPropertiesWithStiffnessAndDamping(float inDeltaTime, float inInvEffectiveMass, float inBias, float inC, float inStiffness, float inDamping, float &outEffectiveMass){+ JPH_ASSERT(inStiffness > 0.0f || inDamping > 0.0f);+// Soft constraints as per: Soft Constraints: Reinventing The Spring - Erin Catto - GDC 2011// Note that the calculation of beta and gamma below are based on the solution of an implicit Euler integration scheme@@ -64,77 +86,71 @@ private:outEffectiveMass = 1.0f / (inInvEffectiveMass + mSoftness);}-public:- /// Turn off the spring and set a bias only- ///- /// @param inBias Bias term (b) for the constraint impulse: lambda = J v + b- inline void CalculateSpringPropertiesWithBias(float inBias)- {- mSoftness = 0.0f;- mBias = inBias;- }-/// Calculate spring properties based on frequency and damping ratio////// @param inDeltaTime Time step/// @param inInvEffectiveMass Inverse effective mass K/// @param inBias Bias term (b) for the constraint impulse: lambda = J v + b- /// @param inC Value of the constraint equation (C). Set to zero if you don't want to drive the constraint to zero with a spring.- /// @param inFrequency Oscillation frequency (Hz). Set to zero if you don't want to drive the constraint to zero with a spring.- /// @param inDamping Damping factor (0 = no damping, 1 = critical damping). Set to zero if you don't want to drive the constraint to zero with a spring.+ /// @param inC Value of the constraint equation (C).+ /// @param inFrequency Oscillation frequency (Hz).+ /// @param inDamping Damping factor (0 = no damping, 1 = critical damping)./// @param outEffectiveMass On return, this contains the new effective mass K^-1- inline void CalculateSpringPropertiesWithFrequencyAndDamping(float inDeltaTime, float inInvEffectiveMass, float inBias, float inC, float inFrequency, float inDamping, float &outEffectiveMass)+ JPH_INLINE void CalculateSpringPropertiesWithFrequencyAndDamping(float inDeltaTime, float inInvEffectiveMass, float inBias, float inC, float inFrequency, float inDamping, float &outEffectiveMass){+ JPH_ASSERT(inFrequency > 0.0f);+outEffectiveMass = 1.0f / inInvEffectiveMass;- if (inFrequency > 0.0f)- {- // Calculate angular frequency- float omega = 2.0f * JPH_PI * inFrequency;+ // Calculate angular frequency+ float omega = 2.0f * JPH_PI * inFrequency;- // Calculate spring stiffness k and damping constant c (page 45)- float k = outEffectiveMass * Square(omega);- float c = 2.0f * outEffectiveMass * inDamping * omega;+ // Calculate spring stiffness k and damping constant c (page 45)+ float k = outEffectiveMass * Square(omega);+ float c = 2.0f * outEffectiveMass * inDamping * omega;- CalculateSpringPropertiesHelper(inDeltaTime, inInvEffectiveMass, inBias, inC, k, c, outEffectiveMass);- }- else- {- CalculateSpringPropertiesWithBias(inBias);- }+ CalculateSpringPropertiesWithStiffnessAndDamping(inDeltaTime, inInvEffectiveMass, inBias, inC, k, c, outEffectiveMass);}- /// Calculate spring properties with spring Stiffness (k) and damping (c), this is based on the spring equation: F = -k * x - c * v+ /// Calculate spring properties with spring stiffness (k) and damping (c) in acceleration mode, this is based on the spring equation: F = m_eff * (-k * x - c * v) where m_eff is the effective mass of the constraint////// @param inDeltaTime Time step/// @param inInvEffectiveMass Inverse effective mass K/// @param inBias Bias term (b) for the constraint impulse: lambda = J v + b- /// @param inC Value of the constraint equation (C). Set to zero if you don't want to drive the constraint to zero with a spring.- /// @param inStiffness Spring stiffness k. Set to zero if you don't want to drive the constraint to zero with a spring.- /// @param inDamping Spring damping coefficient c. Set to zero if you don't want to drive the constraint to zero with a spring.+ /// @param inC Value of the constraint equation (C).+ /// @param inStiffness Spring stiffness k.+ /// @param inDamping Spring damping coefficient c./// @param outEffectiveMass On return, this contains the new effective mass K^-1- inline void CalculateSpringPropertiesWithStiffnessAndDamping(float inDeltaTime, float inInvEffectiveMass, float inBias, float inC, float inStiffness, float inDamping, float &outEffectiveMass)+ JPH_INLINE void CalculateSpringPropertiesWithMassNormalizedStiffnessAndDamping(float inDeltaTime, float inInvEffectiveMass, float inBias, float inC, float inStiffness, float inDamping, float &outEffectiveMass){- if (inStiffness > 0.0f)- {- CalculateSpringPropertiesHelper(inDeltaTime, inInvEffectiveMass, inBias, inC, inStiffness, inDamping, outEffectiveMass);- }- else- {- outEffectiveMass = 1.0f / inInvEffectiveMass;+ CalculateSpringPropertiesWithStiffnessAndDamping(inDeltaTime, inInvEffectiveMass, inBias, inC, inStiffness / inInvEffectiveMass, inDamping / inInvEffectiveMass, outEffectiveMass);+ }- CalculateSpringPropertiesWithBias(inBias);+ /// Calculate spring properties based on SpringSettings object.+ /// Assumes the spring has either stiffness or damping.+ JPH_INLINE void CalculateSpringPropertiesWithSettings(float inDeltaTime, float inInvEffectiveMass, float inBias, float inC, const SpringSettings &inSpringSettings, float &outEffectiveMass)+ {+ switch (inSpringSettings.mMode)+ {+ case ESpringMode::FrequencyAndDamping:+ CalculateSpringPropertiesWithFrequencyAndDamping(inDeltaTime, inInvEffectiveMass, inBias, inC, inSpringSettings.mFrequency, inSpringSettings.mDamping, outEffectiveMass);+ break;+ case ESpringMode::StiffnessAndDamping:+ CalculateSpringPropertiesWithStiffnessAndDamping(inDeltaTime, inInvEffectiveMass, inBias, inC, inSpringSettings.mStiffness, inSpringSettings.mDamping, outEffectiveMass);+ break;+ case ESpringMode::MassNormalizedStiffnessAndDamping:+ CalculateSpringPropertiesWithMassNormalizedStiffnessAndDamping(inDeltaTime, inInvEffectiveMass, inBias, inC, inSpringSettings.mStiffness, inSpringSettings.mDamping, outEffectiveMass);+ break;}}/// Returns if this spring is active- inline bool IsActive() const+ JPH_INLINE bool IsActive() const{return mSoftness != 0.0f;}/// Get total bias b, including supplied bias and bias for spring: lambda = J v + b- inline float GetBias(float inTotalLambda) const+ JPH_INLINE float GetBias(float inTotalLambda) const{// Remainder of post by Erin Catto: http://www.bulletphysics.org/Bullet/phpBB3/viewtopic.php?f=4&t=1354//diff --git a/thirdparty/jolt_physics/Jolt/Physics/Constraints/ConstraintPart/SwingTwistConstraintPart.h b/thirdparty/jolt_physics/Jolt/Physics/Constraints/ConstraintPart/SwingTwistConstraintPart.hindex c2a47547f5e..1418435440e 100644--- a/thirdparty/jolt_physics/Jolt/Physics/Constraints/ConstraintPart/SwingTwistConstraintPart.h+++ b/thirdparty/jolt_physics/Jolt/Physics/Constraints/ConstraintPart/SwingTwistConstraintPart.h@@ -250,7 +250,7 @@ public:else if ((outClampedAxis & cClampedSwingYMin) != 0){float z = ioSwing.GetZ();- ioSwing = Quat(0, 0, z, sqrt(1.0f - Square(z)));+ ioSwing = Quat(0, 0, z, Sqrt(1.0f - Square(z)));}}}@@ -277,7 +277,7 @@ public:else if ((outClampedAxis & cClampedSwingZMin) != 0){float y = ioSwing.GetY();- ioSwing = Quat(0, y, 0, sqrt(1.0f - Square(y)));+ ioSwing = Quat(0, y, 0, Sqrt(1.0f - Square(y)));}}else@@ -291,7 +291,7 @@ public:if (!ellipse.IsInside(point)){Float2 closest = ellipse.GetClosestPoint(point);- ioSwing = Quat(0, closest.x, closest.y, sqrt(max(0.0f, 1.0f - Square(closest.x) - Square(closest.y))));+ ioSwing = Quat(0, closest.x, closest.y, Sqrt(max(0.0f, 1.0f - Square(closest.x) - Square(closest.y))));outClampedAxis |= cClampedSwingYMin | cClampedSwingYMax | cClampedSwingZMin | cClampedSwingZMax; // We're not using the flags on which side we got clamped here}}diff --git a/thirdparty/jolt_physics/Jolt/Physics/Constraints/ContactConstraintManager.cpp b/thirdparty/jolt_physics/Jolt/Physics/Constraints/ContactConstraintManager.cppindex 09dfab49215..efb7aee2e39 100644--- a/thirdparty/jolt_physics/Jolt/Physics/Constraints/ContactConstraintManager.cpp+++ b/thirdparty/jolt_physics/Jolt/Physics/Constraints/ContactConstraintManager.cpp@@ -14,6 +14,7 @@#include <Jolt/Physics/DeterminismLog.h>#include <Jolt/Core/TempAllocator.h>#include <Jolt/Core/QuickSort.h>+#include <Jolt/Core/Prefetch.h>#ifdef JPH_DEBUG_RENDERER#include <Jolt/Renderer/DebugRenderer.h>#endif // JPH_DEBUG_RENDERER@@ -35,23 +36,11 @@ bool ContactConstraintManager::sDrawContactManifolds = false;// ContactConstraintManager::WorldContactPoint////////////////////////////////////////////////////////////////////////////////////////////////////////-void ContactConstraintManager::WorldContactPoint::CalculateNonPenetrationConstraintProperties(const Body &inBody1, float inInvMass1, float inInvInertiaScale1, const Body &inBody2, float inInvMass2, float inInvInertiaScale2, RVec3Arg inWorldSpacePosition1, RVec3Arg inWorldSpacePosition2, Vec3Arg inWorldSpaceNormal)-{- // Calculate collision points relative to body- RVec3 p = 0.5_r * (inWorldSpacePosition1 + inWorldSpacePosition2);- Vec3 r1 = Vec3(p - inBody1.GetCenterOfMassPosition());- Vec3 r2 = Vec3(p - inBody2.GetCenterOfMassPosition());-- mNonPenetrationConstraint.CalculateConstraintPropertiesWithMassOverride(inBody1, inInvMass1, inInvInertiaScale1, r1, inBody2, inInvMass2, inInvInertiaScale2, r2, inWorldSpaceNormal);-}-template <EMotionType Type1, EMotionType Type2>-JPH_INLINE void ContactConstraintManager::WorldContactPoint::TemplatedCalculateFrictionAndNonPenetrationConstraintProperties(float inDeltaTime, Vec3Arg inGravity, const Body &inBody1, const Body &inBody2, float inInvM1, float inInvM2, Mat44Arg inInvI1, Mat44Arg inInvI2, RVec3Arg inWorldSpacePosition1, RVec3Arg inWorldSpacePosition2, Vec3Arg inWorldSpaceNormal, Vec3Arg inWorldSpaceTangent1, Vec3Arg inWorldSpaceTangent2, const ContactSettings &inSettings, float inMinVelocityForRestitution)+JPH_INLINE void ContactConstraintManager::WorldContactPoint<Type1, Type2>::CalculateNonPenetrationConstraintProperties(float inDeltaTime, Vec3Arg inGravity, const Body &inBody1, const Body &inBody2, float inInvM1, float inInvM2, Mat44Arg inInvI1, Mat44Arg inInvI2, RVec3Arg inWorldSpacePosition1, RVec3Arg inWorldSpacePosition2, Vec3Arg inWorldSpaceNormal, const ContactSettings &inSettings, float inMinVelocityForRestitution){- JPH_DET_LOG("TemplatedCalculateFrictionAndNonPenetrationConstraintProperties: p1: " << inWorldSpacePosition1 << " p2: " << inWorldSpacePosition2- << " normal: " << inWorldSpaceNormal << " tangent1: " << inWorldSpaceTangent1 << " tangent2: " << inWorldSpaceTangent2- << " restitution: " << inSettings.mCombinedRestitution << " friction: " << inSettings.mCombinedFriction << " minv: " << inMinVelocityForRestitution- << " surface_vel: " << inSettings.mRelativeLinearSurfaceVelocity << " surface_ang: " << inSettings.mRelativeAngularSurfaceVelocity);+ JPH_DET_LOG("CalculateNonPenetrationConstraintProperties: p1: " << inWorldSpacePosition1 << " p2: " << inWorldSpacePosition2+ << " normal: " << inWorldSpaceNormal << " restitution: " << inSettings.mCombinedRestitution << " minv: " << inMinVelocityForRestitution);// Calculate collision points relative to bodyRVec3 p = 0.5_r * (inWorldSpacePosition1 + inWorldSpacePosition2);@@ -141,53 +130,92 @@ JPH_INLINE void ContactConstraintManager::WorldContactPoint::TemplatedCalculateFnormal_velocity_bias = speculative_contact_velocity_bias;}- mNonPenetrationConstraint.TemplatedCalculateConstraintProperties<Type1, Type2>(inInvM1, inInvI1, r1, inInvM2, inInvI2, r2, inWorldSpaceNormal, normal_velocity_bias);+ mNonPenetrationConstraint.CalculateConstraintProperties(inInvM1, inInvI1, r1, inInvM2, inInvI2, r2, inWorldSpaceNormal, normal_velocity_bias);+}+////////////////////////////////////////////////////////////////////////////////////////////////////////+// ContactConstraintManager::ContactConstraint+////////////////////////////////////////////////////////////////////////////////////////////////////////++template <EMotionType Type1, EMotionType Type2>+void ContactConstraintManager::ContactConstraint<Type1, Type2>::CalculateFrictionConstraintProperties(const Body &inBody1, const Body &inBody2, float inInvM1, float inInvM2, Mat44Arg inInvI1, Mat44Arg inInvI2, const RVec3 *inWorldSpaceContacts, Vec3Arg inWorldSpaceNormal, Vec3Arg inWorldSpaceTangent1, Vec3Arg inWorldSpaceTangent2, const ContactSettings &inSettings)+{// Calculate friction partif (inSettings.mCombinedFriction > 0.0f){+ // Calculate point where the friction applies by averaging the contact points+ RVec3 friction_point = RVec3::sZero();+ for (uint32 i = 0; i < mNumContactPoints; ++i)+ friction_point += inWorldSpaceContacts[i];+ friction_point /= Real(mNumContactPoints);++ JPH_DET_LOG("CalculateFrictionConstraintProperties: point: " << friction_point+ << " friction: " << inSettings.mCombinedFriction+ << " surface_vel: " << inSettings.mRelativeLinearSurfaceVelocity << " surface_ang: " << inSettings.mRelativeAngularSurfaceVelocity);++ // Calculate distance of contact points to friction center in the normal plane+ for (uint32 i = 0; i < mNumContactPoints; ++i)+ {+ Vec3 delta = Vec3(inWorldSpaceContacts[i] - friction_point);+ mContactPoints[i].mDistanceToFrictionCenter = (delta - delta.Dot(inWorldSpaceNormal) * inWorldSpaceNormal).Length();+ }++ // Calculate relative friction points+ Vec3 r1 = Vec3(friction_point - inBody1.GetCenterOfMassPosition());+ Vec3 r2 = Vec3(friction_point - inBody2.GetCenterOfMassPosition());+// Get surface velocity relative to tangentsVec3 ws_surface_velocity = inSettings.mRelativeLinearSurfaceVelocity + inSettings.mRelativeAngularSurfaceVelocity.Cross(r1);float surface_velocity1 = inWorldSpaceTangent1.Dot(ws_surface_velocity);float surface_velocity2 = inWorldSpaceTangent2.Dot(ws_surface_velocity);- // Implement friction as 2 AxisConstraintParts- mFrictionConstraint1.TemplatedCalculateConstraintProperties<Type1, Type2>(inInvM1, inInvI1, r1, inInvM2, inInvI2, r2, inWorldSpaceTangent1, surface_velocity1);- mFrictionConstraint2.TemplatedCalculateConstraintProperties<Type1, Type2>(inInvM1, inInvI1, r1, inInvM2, inInvI2, r2, inWorldSpaceTangent2, surface_velocity2);+ // Implement friction as 2 ContactConstraintParts+ mFrictionConstraint1.CalculateConstraintProperties(inInvM1, inInvI1, r1, inInvM2, inInvI2, r2, inWorldSpaceTangent1, surface_velocity1);+ mFrictionConstraint2.CalculateConstraintProperties(inInvM1, inInvI1, r1, inInvM2, inInvI2, r2, inWorldSpaceTangent2, surface_velocity2);++ // Only apply angular friction if we have more than 1 contact point+ if (mNumContactPoints > 1)+ mAngularFrictionConstraint.CalculateConstraintProperties(inInvI1, inInvI2, inWorldSpaceNormal, inSettings.mRelativeAngularSurfaceVelocity.Dot(inWorldSpaceNormal));+ else+ mAngularFrictionConstraint.Deactivate();}else{// Turn off friction constraintmFrictionConstraint1.Deactivate();mFrictionConstraint2.Deactivate();+ mAngularFrictionConstraint.Deactivate();}}-////////////////////////////////////////////////////////////////////////////////////////////////////////-// ContactConstraintManager::ContactConstraint-////////////////////////////////////////////////////////////////////////////////////////////////////////-#ifdef JPH_DEBUG_RENDERER-void ContactConstraintManager::ContactConstraint::Draw(DebugRenderer *inRenderer, ColorArg inManifoldColor) const+template <EMotionType Type1, EMotionType Type2>+void ContactConstraintManager::ContactConstraint<Type1, Type2>::Draw(DebugRenderer *inRenderer, const ManifoldCache &inManifoldCache, ColorArg inManifoldColor) const{- if (mContactPoints.empty())+ if (mNumContactPoints == 0)return;+ const CachedManifold &cached_manifold = inManifoldCache.FromHandle(mCachedManifoldHandle)->GetValue();+// Get body transformsRMat44 transform_body1 = mBody1->GetCenterOfMassTransform();RMat44 transform_body2 = mBody2->GetCenterOfMassTransform();- RVec3 prev_point = transform_body1 * Vec3::sLoadFloat3Unsafe(mContactPoints.back().mContactPoint->mPosition1);- for (const WorldContactPoint &wcp : mContactPoints)+ RVec3 prev_point = transform_body1 * Vec3::sLoadFloat3Unsafe(cached_manifold.mContactPoints[mNumContactPoints - 1].mPosition1);+ for (uint32 i = 0; i < mNumContactPoints; ++i){+ const WorldContactPoint<Type1, Type2> &wcp = mContactPoints[i];+ const CachedContactPoint &ccp = cached_manifold.mContactPoints[i];+// Test if any lambda from the previous frame was transferredfloat radius = wcp.mNonPenetrationConstraint.GetTotalLambda() == 0.0f- && wcp.mFrictionConstraint1.GetTotalLambda() == 0.0f- && wcp.mFrictionConstraint2.GetTotalLambda() == 0.0f? 0.1f : 0.2f;+ && mFrictionConstraint1.GetTotalLambda() == 0.0f+ && mFrictionConstraint2.GetTotalLambda() == 0.0f+ && mAngularFrictionConstraint.GetTotalLambda() == 0.0f? 0.1f : 0.2f;- RVec3 next_point = transform_body1 * Vec3::sLoadFloat3Unsafe(wcp.mContactPoint->mPosition1);+ RVec3 next_point = transform_body1 * Vec3::sLoadFloat3Unsafe(ccp.mPosition1);inRenderer->DrawMarker(next_point, Color::sCyan, radius);- inRenderer->DrawMarker(transform_body2 * Vec3::sLoadFloat3Unsafe(wcp.mContactPoint->mPosition2), Color::sPurple, radius);+ inRenderer->DrawMarker(transform_body2 * Vec3::sLoadFloat3Unsafe(ccp.mPosition2), Color::sPurple, radius);// Draw edgeinRenderer->DrawArrow(prev_point, next_point, inManifoldColor, 0.05f);@@ -195,7 +223,7 @@ void ContactConstraintManager::ContactConstraint::Draw(DebugRenderer *inRenderer}// Draw normal- RVec3 wp = transform_body1 * Vec3::sLoadFloat3Unsafe(mContactPoints[0].mContactPoint->mPosition1);+ RVec3 wp = transform_body1 * Vec3::sLoadFloat3Unsafe(cached_manifold.mContactPoints[0].mPosition1);inRenderer->DrawArrow(wp, wp + GetWorldSpaceNormal(), Color::sRed, 0.05f);// Get tangents@@ -217,7 +245,6 @@ void ContactConstraintManager::CachedContactPoint::SaveState(StateRecorder &inStinStream.Write(mPosition1);inStream.Write(mPosition2);inStream.Write(mNonPenetrationLambda);- inStream.Write(mFrictionLambda);}void ContactConstraintManager::CachedContactPoint::RestoreState(StateRecorder &inStream)@@ -225,7 +252,6 @@ void ContactConstraintManager::CachedContactPoint::RestoreState(StateRecorder &iinStream.Read(mPosition1);inStream.Read(mPosition2);inStream.Read(mNonPenetrationLambda);- inStream.Read(mFrictionLambda);}////////////////////////////////////////////////////////////////////////////////////////////////////////@@ -235,11 +261,15 @@ void ContactConstraintManager::CachedContactPoint::RestoreState(StateRecorder &ivoid ContactConstraintManager::CachedManifold::SaveState(StateRecorder &inStream) const{inStream.Write(mContactNormal);+ inStream.Write(mFrictionLambda);+ inStream.Write(mAngularFrictionLambda);}void ContactConstraintManager::CachedManifold::RestoreState(StateRecorder &inStream){inStream.Read(mContactNormal);+ inStream.Read(mFrictionLambda);+ inStream.Read(mAngularFrictionLambda);}////////////////////////////////////////////////////////////////////////////////////////////////////////@@ -264,11 +294,13 @@ void ContactConstraintManager::CachedBodyPair::RestoreState(StateRecorder &inStrvoid ContactConstraintManager::ManifoldCache::Init(uint inMaxBodyPairs, uint inMaxContactConstraints, uint inCachedManifoldsSize){+ JPH_ASSERT(inMaxContactConstraints <= cMaxContactConstraintsLimit); // Should have been enforced by caller+uint max_body_pairs = min(inMaxBodyPairs, cMaxBodyPairsLimit);JPH_ASSERT(max_body_pairs == inMaxBodyPairs, "Cannot support this many body pairs!");- JPH_ASSERT(inMaxContactConstraints <= cMaxContactConstraintsLimit); // Should have been enforced by caller+ max_body_pairs = max(max_body_pairs, 4u); // Because our hash map requires at least 4 buckets, we need to have a minimum number of body pairs- mAllocator.Init(uint(min(uint64(max_body_pairs) * sizeof(BodyPairMap::KeyValue) + inCachedManifoldsSize, uint64(~uint(0)))));+ mAllocator.Init(uint(min(uint64(max_body_pairs) * sizeof(BPKeyValue) + inCachedManifoldsSize, uint64(~uint(0)))));mCachedManifolds.Init(GetNextPowerOf2(inMaxContactConstraints));mCachedBodyPairs.Init(GetNextPowerOf2(max_body_pairs));@@ -335,7 +367,11 @@ uint32 ContactConstraintManager::ManifoldCache::ToHandle(const MKeyValue *inKeyVconst ContactConstraintManager::MKeyValue *ContactConstraintManager::ManifoldCache::FromHandle(uint32 inHandle) const{- JPH_ASSERT(mIsFinalized);+ return mCachedManifolds.FromHandle(inHandle);+}++ContactConstraintManager::MKeyValue *ContactConstraintManager::ManifoldCache::FromHandle(uint32 inHandle)+{return mCachedManifolds.FromHandle(inHandle);}@@ -561,7 +597,7 @@ bool ContactConstraintManager::ManifoldCache::RestoreState(const ManifoldCache &// When validating, get all existing manifoldsArray<const MKeyValue *> all_m;- if (inStream.IsValidating())+ if (inStream.IsValidating() && i < all_bp.size())inReadCache.GetAllManifoldsSorted(all_bp[i]->GetValue(), all_m);// Read amount of manifolds@@ -692,6 +728,7 @@ ContactConstraintManager::ContactConstraintManager(const PhysicsSettings &inPhysContactConstraintManager::~ContactConstraintManager(){JPH_ASSERT(mConstraints == nullptr);+ JPH_ASSERT(mConstraintIdxToOffset == nullptr);}void ContactConstraintManager::Init(uint inMaxBodyPairs, uint inMaxContactConstraints)@@ -699,10 +736,11 @@ void ContactConstraintManager::Init(uint inMaxBodyPairs, uint inMaxContactConstr// Limit the number of constraints so that the allocation size fits in an unsigned integermMaxConstraints = min(inMaxContactConstraints, cMaxContactConstraintsLimit);JPH_ASSERT(mMaxConstraints == inMaxContactConstraints, "Cannot support this many contact constraints!");+ mMaxConstraints = max(mMaxConstraints, 4u); // Because our hash map requires at least 4 buckets, we need to have a minimum number of constraints// Calculate worst case cache usage- constexpr uint cMaxManifoldSizePerConstraint = sizeof(CachedManifold) + (MaxContactPoints - 1) * sizeof(CachedContactPoint);- static_assert(cMaxManifoldSizePerConstraint < sizeof(ContactConstraint)); // If not true, then the next line can overflow+ constexpr uint cMaxManifoldSizePerConstraint = sizeof(MKeyValue) + CachedManifold::sGetRequiredExtraSize(MaxContactPoints);+ static_assert(cMaxManifoldSizePerConstraint < cMaxConstraintSize); // If not true, then the next line can overflowuint cached_manifolds_size = mMaxConstraints * cMaxManifoldSizePerConstraint;// Init the caches@@ -715,165 +753,99 @@ void ContactConstraintManager::PrepareConstraintBuffer(PhysicsUpdateContext *inC// Store contextmUpdateContext = inContext;+ // Store read / write cache+ mReadCache = &mCache[mCacheWriteIdx ^ 1];+ mWriteCache = &mCache[mCacheWriteIdx];+// Allocate temporary constraint bufferJPH_ASSERT(mConstraints == nullptr);- mConstraints = (ContactConstraint *)inContext->mTempAllocator->Allocate(mMaxConstraints * sizeof(ContactConstraint));+ mConstraints = (uint8 *)inContext->mTempAllocator->Allocate(mMaxConstraints * cMaxConstraintSize);+ JPH_ASSERT(mConstraintIdxToOffset == nullptr);+ mConstraintIdxToOffset = (uint32 *)inContext->mTempAllocator->Allocate(mMaxConstraints * sizeof(uint32));}template <EMotionType Type1, EMotionType Type2>-JPH_INLINE void ContactConstraintManager::TemplatedCalculateFrictionAndNonPenetrationConstraintProperties(ContactConstraint &ioConstraint, const ContactSettings &inSettings, float inDeltaTime, Vec3Arg inGravity, RMat44Arg inTransformBody1, RMat44Arg inTransformBody2, const Body &inBody1, const Body &inBody2)+JPH_INLINE ContactConstraintManager::ContactConstraint<Type1, Type2> *ContactConstraintManager::CreateConstraint(bool &ioActivateAndLinkBodies, Body &inBody1, Body &inBody2, uint64 inSortKey, uint32 inCachedManifoldHandle, Vec3Arg inWorldSpaceNormal, const ContactSettings &inSettings, uint32 inNumContactPoints){- // Calculate scaled mass and inertia- Mat44 inv_i1;- if constexpr (Type1 == EMotionType::Dynamic)- {- const MotionProperties *mp1 = inBody1.GetMotionPropertiesUnchecked();- inv_i1 = inSettings.mInvInertiaScale1 * mp1->GetInverseInertiaForRotation(inTransformBody1.GetRotation());- }- else- {- inv_i1 = Mat44::sZero();- }-- Mat44 inv_i2;- if constexpr (Type2 == EMotionType::Dynamic)- {- const MotionProperties *mp2 = inBody2.GetMotionPropertiesUnchecked();- inv_i2 = inSettings.mInvInertiaScale2 * mp2->GetInverseInertiaForRotation(inTransformBody2.GetRotation());- }- else- {- inv_i2 = Mat44::sZero();- }-- // Calculate tangents- Vec3 t1, t2;- ioConstraint.GetTangents(t1, t2);-- Vec3 ws_normal = ioConstraint.GetWorldSpaceNormal();+ // Calculate the size of this constraint+ uint32 constraint_size = (uint32)AlignUp(sizeof(ContactConstraint<Type1, Type2>) + (inNumContactPoints - 1) * sizeof(WorldContactPoint<Type1, Type2>), alignof(ContactConstraint<Type1, Type2>));+ JPH_ASSERT(constraint_size <= cMaxConstraintSize);++ // Reserve space for constraint+ uint64 constraint_idx_and_constraint_offset = mNumConstraintsAndNextConstraintOffset.fetch_add((uint64(constraint_size) << 32) + 1, memory_order_relaxed);+ uint32 constraint_idx = uint32(constraint_idx_and_constraint_offset);+ if (constraint_idx >= mMaxConstraints)+ return nullptr;- // Setup velocity constraint properties- float min_velocity_for_restitution = mPhysicsSettings.mMinVelocityForRestitution;- for (WorldContactPoint &wcp : ioConstraint.mContactPoints)- {- RVec3 p1 = inTransformBody1 * Vec3::sLoadFloat3Unsafe(wcp.mContactPoint->mPosition1);- RVec3 p2 = inTransformBody2 * Vec3::sLoadFloat3Unsafe(wcp.mContactPoint->mPosition2);- wcp.TemplatedCalculateFrictionAndNonPenetrationConstraintProperties<Type1, Type2>(inDeltaTime, inGravity, inBody1, inBody2, ioConstraint.mInvMass1, ioConstraint.mInvMass2, inv_i1, inv_i2, p1, p2, ws_normal, t1, t2, inSettings, min_velocity_for_restitution);- }-}+ bool body1_dynamic = inBody1.IsDynamic();+ bool body2_dynamic = inBody2.IsDynamic();-inline void ContactConstraintManager::CalculateFrictionAndNonPenetrationConstraintProperties(ContactConstraint &ioConstraint, const ContactSettings &inSettings, float inDeltaTime, Vec3Arg inGravity, RMat44Arg inTransformBody1, RMat44Arg inTransformBody2, const Body &inBody1, const Body &inBody2)-{- // Dispatch to the correct templated form- switch (inBody1.GetMotionType())+ if (ioActivateAndLinkBodies){- case EMotionType::Dynamic:- switch (inBody2.GetMotionType())- {- case EMotionType::Dynamic:- TemplatedCalculateFrictionAndNonPenetrationConstraintProperties<EMotionType::Dynamic, EMotionType::Dynamic>(ioConstraint, inSettings, inDeltaTime, inGravity, inTransformBody1, inTransformBody2, inBody1, inBody2);- break;-- case EMotionType::Kinematic:- TemplatedCalculateFrictionAndNonPenetrationConstraintProperties<EMotionType::Dynamic, EMotionType::Kinematic>(ioConstraint, inSettings, inDeltaTime, inGravity, inTransformBody1, inTransformBody2, inBody1, inBody2);- break;-- case EMotionType::Static:- TemplatedCalculateFrictionAndNonPenetrationConstraintProperties<EMotionType::Dynamic, EMotionType::Static>(ioConstraint, inSettings, inDeltaTime, inGravity, inTransformBody1, inTransformBody2, inBody1, inBody2);- break;-- default:- JPH_ASSERT(false);- break;- }- break;-- case EMotionType::Kinematic:- JPH_ASSERT(inBody2.IsDynamic());- TemplatedCalculateFrictionAndNonPenetrationConstraintProperties<EMotionType::Kinematic, EMotionType::Dynamic>(ioConstraint, inSettings, inDeltaTime, inGravity, inTransformBody1, inTransformBody2, inBody1, inBody2);- break;-- case EMotionType::Static:- JPH_ASSERT(inBody2.IsDynamic());- TemplatedCalculateFrictionAndNonPenetrationConstraintProperties<EMotionType::Static, EMotionType::Dynamic>(ioConstraint, inSettings, inDeltaTime, inGravity, inTransformBody1, inTransformBody2, inBody1, inBody2);- break;-- default:- JPH_ASSERT(false);- break;+ // Do this only once+ ioActivateAndLinkBodies = false;++ // Wake up sleeping bodies+ BodyID body_ids[2];+ int num_bodies = 0;+ if (body1_dynamic && !inBody1.IsActive())+ body_ids[num_bodies++] = inBody1.GetID();+ if (body2_dynamic && !inBody2.IsActive())+ body_ids[num_bodies++] = inBody2.GetID();+ if (num_bodies > 0)+ mUpdateContext->mBodyManager->ActivateBodies(body_ids, num_bodies);++ // Link the two bodies only if both are dynamic. If one of them is static or kinematic they don't need to go into+ // the same simulation island as a constraint cannot affect the velocity of a kinematic body.+ if (body1_dynamic && body2_dynamic)+ mUpdateContext->mIslandBuilder->LinkBodies(inBody1.GetIndexInActiveBodiesInternal(), inBody2.GetIndexInActiveBodiesInternal());}-}--void ContactConstraintManager::GetContactsFromCache(ContactAllocator &ioContactAllocator, Body &inBody1, Body &inBody2, bool &outPairHandled, bool &outConstraintCreated)-{- // Start with nothing found and not handled- outConstraintCreated = false;- outPairHandled = false;- // Swap bodies so that body 1 id < body 2 id- Body *body1, *body2;- if (inBody1.GetID() < inBody2.GetID())- {- body1 = &inBody1;- body2 = &inBody2;- }+ // Link the contact to the first dynamic body+ if (body1_dynamic)+ mUpdateContext->mIslandBuilder->LinkContact(constraint_idx, inBody1.GetIndexInActiveBodiesInternal());else{- body1 = &inBody2;- body2 = &inBody1;+ JPH_ASSERT(body2_dynamic);+ mUpdateContext->mIslandBuilder->LinkContact(constraint_idx, inBody2.GetIndexInActiveBodiesInternal());}- // Find the cached body pair- BodyPair body_pair_key(body1->GetID(), body2->GetID());- uint64 body_pair_hash = body_pair_key.GetHash();- const ManifoldCache &read_cache = mCache[mCacheWriteIdx ^ 1];- const BPKeyValue *kv = read_cache.Find(body_pair_key, body_pair_hash);- if (kv == nullptr)- return;- const CachedBodyPair &input_cbp = kv->GetValue();-- // Get relative translation- Quat inv_r1 = body1->GetRotation().Conjugated();- Vec3 delta_position = inv_r1 * Vec3(body2->GetCenterOfMassPosition() - body1->GetCenterOfMassPosition());-- // Get old position delta- Vec3 old_delta_position = Vec3::sLoadFloat3Unsafe(input_cbp.mDeltaPosition);-- // Check if bodies are still roughly in the same relative position- if ((delta_position - old_delta_position).LengthSq() > mPhysicsSettings.mBodyPairCacheMaxDeltaPositionSq)- return;-- // Determine relative orientation- Quat delta_rotation = inv_r1 * body2->GetRotation();-- // Reconstruct old quaternion delta- Quat old_delta_rotation = Quat::sLoadFloat3Unsafe(input_cbp.mDeltaRotation);-- // Check if bodies are still roughly in the same relative orientation- // The delta between 2 quaternions p and q is: p q^* = [rotation_axis * sin(angle / 2), cos(angle / 2)]- // From the W component we can extract the angle: cos(angle / 2) = px * qx + py * qy + pz * qz + pw * qw = p . q- // Since we want to abort if the rotation is smaller than -angle or bigger than angle, we can write the comparison as |p . q| < cos(angle / 2)- if (abs(delta_rotation.Dot(old_delta_rotation)) < mPhysicsSettings.mBodyPairCacheCosMaxDeltaRotationDiv2)- return;-- // The cache is valid, return that we've handled this body pair- outPairHandled = true;-- // Copy the cached body pair to this frame- ManifoldCache &write_cache = mCache[mCacheWriteIdx];- BPKeyValue *output_bp_kv = write_cache.Create(ioContactAllocator, body_pair_key, body_pair_hash);- if (output_bp_kv == nullptr)- return; // Out of cache space- CachedBodyPair *output_cbp = &output_bp_kv->GetValue();- memcpy(output_cbp, &input_cbp, sizeof(CachedBodyPair));+ // Store offset for constraint+ uint32 constraint_offset = uint32(constraint_idx_and_constraint_offset >> 32);+ JPH_ASSERT(constraint_offset + constraint_size <= mMaxConstraints * cMaxConstraintSize);+ mConstraintIdxToOffset[constraint_idx] = constraint_offset;++ // Construct constraint+ ContactConstraint<Type1, Type2> *constraint = reinterpret_cast<ContactConstraint<Type1, Type2> *>(mConstraints + constraint_offset);+ JPH_ASSERT(IsAligned(constraint, alignof(ContactConstraint<Type1, Type2>)));+ new (constraint) ContactConstraint<Type1, Type2>();+ constraint->mBody1 = &inBody1;+ constraint->mBody2 = &inBody2;+ constraint->mSortKey = inSortKey;+ inWorldSpaceNormal.StoreFloat3(&constraint->mWorldSpaceNormal);+ constraint->mCombinedFriction = inSettings.mCombinedFriction;+ constraint->mInvInertiaScale1 = inSettings.mInvInertiaScale1;+ constraint->mInvInertiaScale2 = inSettings.mInvInertiaScale2;+ constraint->mCachedManifoldHandle = inCachedManifoldHandle;+ constraint->mNumContactPoints = inNumContactPoints;++#ifdef JPH_TRACK_SIMULATION_STATS+ // Track new contact constraints+ if constexpr (Type1 != EMotionType::Static)+ inBody1.GetMotionPropertiesUnchecked()->GetSimulationStats().mNumContactConstraints.fetch_add(1, memory_order_relaxed);+ if constexpr (Type2 != EMotionType::Static)+ inBody2.GetMotionPropertiesUnchecked()->GetSimulationStats().mNumContactConstraints.fetch_add(1, memory_order_relaxed);+#endif- // If there were no contacts, we have handled the contact- if (input_cbp.mFirstCachedManifold == ManifoldMap::cInvalidHandle)- return;+ return constraint;+}+template <EMotionType Type1, EMotionType Type2>+void ContactConstraintManager::TemplatedGetContactsFromCache(ContactAllocator &ioContactAllocator, Body &inBody1, Body &inBody2, const CachedBodyPair &inCachedBodyPair, CachedBodyPair &outCachedBodyPair)+{// Get body transforms- RMat44 transform_body1 = body1->GetCenterOfMassTransform();- RMat44 transform_body2 = body2->GetCenterOfMassTransform();+ RMat44 transform_body1 = inBody1.GetCenterOfMassTransform();+ RMat44 transform_body2 = inBody2.GetCenterOfMassTransform();// Get time step and gravityfloat delta_time = mUpdateContext->mStepDeltaTime;@@ -881,20 +853,21 @@ void ContactConstraintManager::GetContactsFromCache(ContactAllocator &ioContactA// Copy manifoldsuint32 output_handle = ManifoldMap::cInvalidHandle;- uint32 input_handle = input_cbp.mFirstCachedManifold;+ uint32 input_handle = inCachedBodyPair.mFirstCachedManifold;+ bool link_bodies = true;do{JPH_PROFILE("Add Constraint From Cached Manifold");// Find the existing manifold- const MKeyValue *input_kv = read_cache.FromHandle(input_handle);+ const MKeyValue *input_kv = mReadCache->FromHandle(input_handle);const SubShapeIDPair &input_key = input_kv->GetKey();const CachedManifold &input_cm = input_kv->GetValue();JPH_ASSERT(input_cm.mNumContactPoints > 0); // There should be contact points in this manifold!// Create room for manifold in write buffer and copy datauint64 input_hash = input_key.GetHash();- MKeyValue *output_kv = write_cache.Create(ioContactAllocator, input_key, input_hash, input_cm.mNumContactPoints);+ MKeyValue *output_kv = mWriteCache->Create(ioContactAllocator, input_key, input_hash, input_cm.mNumContactPoints);if (output_kv == nullptr)break; // Out of cache spaceCachedManifold *output_cm = &output_kv->GetValue();@@ -902,13 +875,13 @@ void ContactConstraintManager::GetContactsFromCache(ContactAllocator &ioContactA// Link the object under the body pairsoutput_cm->mNextWithSameBodyPair = output_handle;- output_handle = write_cache.ToHandle(output_kv);+ output_handle = mWriteCache->ToHandle(output_kv);// Calculate default contact settingsContactSettings settings;- settings.mCombinedFriction = mCombineFriction(*body1, input_key.GetSubShapeID1(), *body2, input_key.GetSubShapeID2());- settings.mCombinedRestitution = mCombineRestitution(*body1, input_key.GetSubShapeID1(), *body2, input_key.GetSubShapeID2());- settings.mIsSensor = body1->IsSensor() || body2->IsSensor();+ settings.mCombinedFriction = mCombineFriction(inBody1, input_key.GetSubShapeID1(), inBody2, input_key.GetSubShapeID2());+ settings.mCombinedRestitution = mCombineRestitution(inBody1, input_key.GetSubShapeID1(), inBody2, input_key.GetSubShapeID2());+ settings.mIsSensor = inBody1.IsSensor() || inBody2.IsSensor();// Calculate world space contact normalVec3 world_space_normal = transform_body2.Multiply3x3(Vec3::sLoadFloat3Unsafe(output_cm->mContactNormal)).Normalized();@@ -936,68 +909,83 @@ void ContactConstraintManager::GetContactsFromCache(ContactAllocator &ioContactAmanifold.mPenetrationDepth = penetration_depth; // We don't have the penetration depth anymore, estimate it// Notify callback- mContactListener->OnContactPersisted(*body1, *body2, manifold, settings);+ mContactListener->OnContactPersisted(inBody1, inBody2, manifold, settings);}- JPH_ASSERT(settings.mIsSensor || !(body1->IsSensor() || body2->IsSensor()), "Sensors cannot be converted into regular bodies by a contact callback!");+ JPH_ASSERT(settings.mIsSensor || !(inBody1.IsSensor() || inBody2.IsSensor()), "Sensors cannot be converted into regular bodies by a contact callback!");if (!settings.mIsSensor // If one of the bodies is a sensor, don't actually create the constraint- && ((body1->IsDynamic() && settings.mInvMassScale1 != 0.0f) // One of the bodies must have mass to be able to create a contact constraint- || (body2->IsDynamic() && settings.mInvMassScale2 != 0.0f)))+ && ((Type1 == EMotionType::Dynamic && settings.mInvMassScale1 != 0.0f) // One of the bodies must have mass to be able to create a contact constraint+ || (Type2 == EMotionType::Dynamic && settings.mInvMassScale2 != 0.0f))){- // Add contact constraint in world space for the solver- uint32 constraint_idx = mNumConstraints++;- if (constraint_idx >= mMaxConstraints)+ // Create a new constraint+ ContactConstraint<Type1, Type2> *constraint = CreateConstraint<Type1, Type2>(link_bodies, inBody1, inBody2, input_hash, output_handle, world_space_normal, settings, output_cm->mNumContactPoints);+ if (constraint == nullptr){ioContactAllocator.mErrors |= EPhysicsUpdateError::ContactConstraintsFull;break;}- // A constraint will be created- outConstraintCreated = true;-- ContactConstraint &constraint = mConstraints[constraint_idx];- new (&constraint) ContactConstraint();- constraint.mBody1 = body1;- constraint.mBody2 = body2;- constraint.mSortKey = input_hash;- world_space_normal.StoreFloat3(&constraint.mWorldSpaceNormal);- constraint.mCombinedFriction = settings.mCombinedFriction;- constraint.mInvMass1 = body1->GetMotionPropertiesUnchecked() != nullptr? settings.mInvMassScale1 * body1->GetMotionPropertiesUnchecked()->GetInverseMassUnchecked() : 0.0f;- constraint.mInvInertiaScale1 = settings.mInvInertiaScale1;- constraint.mInvMass2 = body2->GetMotionPropertiesUnchecked() != nullptr? settings.mInvMassScale2 * body2->GetMotionPropertiesUnchecked()->GetInverseMassUnchecked() : 0.0f;- constraint.mInvInertiaScale2 = settings.mInvInertiaScale2;- constraint.mContactPoints.resize(output_cm->mNumContactPoints);- for (uint32 i = 0; i < output_cm->mNumContactPoints; ++i)+ JPH_DET_LOG("GetContactsFromCache: id1: " << inBody1.GetID() << " id2: " << inBody2.GetID() << " key: " << constraint->mSortKey);++ // Calculate scaled mass and inertia+ Mat44 inv_i1;+ if constexpr (Type1 == EMotionType::Dynamic){- CachedContactPoint &ccp = output_cm->mContactPoints[i];- WorldContactPoint &wcp = constraint.mContactPoints[i];- wcp.mNonPenetrationConstraint.SetTotalLambda(ccp.mNonPenetrationLambda);- wcp.mFrictionConstraint1.SetTotalLambda(ccp.mFrictionLambda[0]);- wcp.mFrictionConstraint2.SetTotalLambda(ccp.mFrictionLambda[1]);- wcp.mContactPoint = &ccp;+ const MotionProperties *mp1 = inBody1.GetMotionPropertiesUnchecked();+ constraint->mInvMass1 = settings.mInvMassScale1 * mp1->GetInverseMass();+ inv_i1 = settings.mInvInertiaScale1 * mp1->GetInverseInertiaForRotation(transform_body1.GetRotation());+ }+ else+ {+ constraint->mInvMass1 = 0.0f;+ inv_i1 = Mat44::sZero();}- JPH_DET_LOG("GetContactsFromCache: id1: " << constraint.mBody1->GetID() << " id2: " << constraint.mBody2->GetID() << " key: " << constraint.mSortKey);+ Mat44 inv_i2;+ if constexpr (Type2 == EMotionType::Dynamic)+ {+ const MotionProperties *mp2 = inBody2.GetMotionPropertiesUnchecked();+ constraint->mInvMass2 = settings.mInvMassScale2 * mp2->GetInverseMass();+ inv_i2 = settings.mInvInertiaScale2 * mp2->GetInverseInertiaForRotation(transform_body2.GetRotation());+ }+ else+ {+ constraint->mInvMass2 = 0.0f;+ inv_i2 = Mat44::sZero();+ }++ // Setup non-penetration constraints+ RVec3 ws_contacts[MaxContactPoints];+ for (uint32 i = 0; i < constraint->mNumContactPoints; ++i)+ {+ const CachedContactPoint &ccp = output_cm->mContactPoints[i];+ WorldContactPoint<Type1, Type2> &wcp = constraint->mContactPoints[i];++ RVec3 p1_ws = transform_body1 * Vec3::sLoadFloat3Unsafe(ccp.mPosition1);+ RVec3 p2_ws = transform_body2 * Vec3::sLoadFloat3Unsafe(ccp.mPosition2);- // Calculate friction and non-penetration constraint properties for all contact points- CalculateFrictionAndNonPenetrationConstraintProperties(constraint, settings, delta_time, gravity, transform_body1, transform_body2, *body1, *body2);+ // Remember where to apply friction+ ws_contacts[i] = 0.5_r * (p1_ws + p2_ws);- // Notify island builder- mUpdateContext->mIslandBuilder->LinkContact(constraint_idx, body1->GetIndexInActiveBodiesInternal(), body2->GetIndexInActiveBodiesInternal());+ wcp.mNonPenetrationConstraint.SetTotalLambda(ccp.mNonPenetrationLambda);+ wcp.CalculateNonPenetrationConstraintProperties(delta_time, gravity, inBody1, inBody2, constraint->mInvMass1, constraint->mInvMass2, inv_i1, inv_i2, p1_ws, p2_ws, world_space_normal, settings, mPhysicsSettings.mMinVelocityForRestitution);+ }++ // Calculate tangents+ Vec3 t1, t2;+ constraint->GetTangents(t1, t2);++ // Setup friction constraints+ constraint->mFrictionConstraint1.SetTotalLambda(output_cm->mFrictionLambda[0]);+ constraint->mFrictionConstraint2.SetTotalLambda(output_cm->mFrictionLambda[1]);+ constraint->mAngularFrictionConstraint.SetTotalLambda(output_cm->mAngularFrictionLambda);+ constraint->CalculateFrictionConstraintProperties(inBody1, inBody2, constraint->mInvMass1, constraint->mInvMass2, inv_i1, inv_i2, ws_contacts, world_space_normal, t1, t2, settings);#ifdef JPH_DEBUG_RENDERER// Draw the manifoldif (sDrawContactManifolds)- constraint.Draw(DebugRenderer::sInstance, Color::sYellow);+ constraint->Draw(DebugRenderer::sInstance, *mWriteCache, Color::sYellow);#endif // JPH_DEBUG_RENDERER-- #ifdef JPH_TRACK_SIMULATION_STATS- // Track new contact constraints- if (!body1->IsStatic())- body1->GetMotionPropertiesUnchecked()->GetSimulationStats().mNumContactConstraints.fetch_add(1, memory_order_relaxed);- if (!body2->IsStatic())- body2->GetMotionPropertiesUnchecked()->GetSimulationStats().mNumContactConstraints.fetch_add(1, memory_order_relaxed);- #endif}// Mark contact as persisted so that we won't fire OnContactRemoved callbacks@@ -1007,7 +995,96 @@ void ContactConstraintManager::GetContactsFromCache(ContactAllocator &ioContactAinput_handle = input_cm.mNextWithSameBodyPair;}while (input_handle != ManifoldMap::cInvalidHandle);- output_cbp->mFirstCachedManifold = output_handle;+ outCachedBodyPair.mFirstCachedManifold = output_handle;+}++void ContactConstraintManager::GetContactsFromCache(ContactAllocator &ioContactAllocator, Body &inBody1, Body &inBody2, bool &outPairHandled)+{+ // Start with not handled+ outPairHandled = false;++ // Swap bodies so that body 1 id < body 2 id+ Body *body1, *body2;+ if (inBody1.GetID() < inBody2.GetID())+ {+ body1 = &inBody1;+ body2 = &inBody2;+ }+ else+ {+ body1 = &inBody2;+ body2 = &inBody1;+ }++ // Find the cached body pair+ BodyPair body_pair_key(body1->GetID(), body2->GetID());+ uint64 body_pair_hash = body_pair_key.GetHash();+ const BPKeyValue *kv = mReadCache->Find(body_pair_key, body_pair_hash);+ if (kv == nullptr)+ return;+ const CachedBodyPair &input_cbp = kv->GetValue();++ // Get relative translation+ Quat inv_r1 = body1->GetRotation().Conjugated();+ Vec3 delta_position = inv_r1 * Vec3(body2->GetCenterOfMassPosition() - body1->GetCenterOfMassPosition());++ // Get old position delta+ Vec3 old_delta_position = Vec3::sLoadFloat3Unsafe(input_cbp.mDeltaPosition);++ // Check if bodies are still roughly in the same relative position+ if ((delta_position - old_delta_position).LengthSq() > mPhysicsSettings.mBodyPairCacheMaxDeltaPositionSq)+ return;++ // Determine relative orientation+ Quat delta_rotation = inv_r1 * body2->GetRotation();++ // Reconstruct old quaternion delta+ Quat old_delta_rotation = Quat::sLoadFloat3Unsafe(input_cbp.mDeltaRotation);++ // Check if bodies are still roughly in the same relative orientation+ // The delta between 2 quaternions p and q is: p q^* = [rotation_axis * sin(angle / 2), cos(angle / 2)]+ // From the W component we can extract the angle: cos(angle / 2) = px * qx + py * qy + pz * qz + pw * qw = p . q+ // Since we want to abort if the rotation is smaller than -angle or bigger than angle, we can write the comparison as |p . q| < cos(angle / 2)+ if (abs(delta_rotation.Dot(old_delta_rotation)) < mPhysicsSettings.mBodyPairCacheCosMaxDeltaRotationDiv2)+ return;++ // The cache is valid, return that we've handled this body pair+ outPairHandled = true;++ // Copy the cached body pair to this frame+ BPKeyValue *output_bp_kv = mWriteCache->Create(ioContactAllocator, body_pair_key, body_pair_hash);+ if (output_bp_kv == nullptr)+ return; // Out of cache space+ CachedBodyPair *output_cbp = &output_bp_kv->GetValue();+ memcpy(output_cbp, &input_cbp, sizeof(CachedBodyPair));++ // If there were no contacts, we have handled the contact+ if (input_cbp.mFirstCachedManifold == ManifoldMap::cInvalidHandle)+ return;++ // Build dispatch table+ // Note: Non-dynamic vs non-dynamic can happen in this case due to one body being a sensor, so we need to have an extended table here+ using DispatchFunc = void (ContactConstraintManager::*)(ContactAllocator &, Body &, Body &, const CachedBodyPair &, CachedBodyPair &);+ static const DispatchFunc table[3][3] = {+ {+ nullptr, // Static vs static doesn't exist+ &ContactConstraintManager::TemplatedGetContactsFromCache<EMotionType::Static, EMotionType::Kinematic>,+ &ContactConstraintManager::TemplatedGetContactsFromCache<EMotionType::Static, EMotionType::Dynamic>+ },+ {+ &ContactConstraintManager::TemplatedGetContactsFromCache<EMotionType::Kinematic, EMotionType::Static>,+ &ContactConstraintManager::TemplatedGetContactsFromCache<EMotionType::Kinematic, EMotionType::Kinematic>,+ &ContactConstraintManager::TemplatedGetContactsFromCache<EMotionType::Kinematic, EMotionType::Dynamic>+ },+ {+ &ContactConstraintManager::TemplatedGetContactsFromCache<EMotionType::Dynamic, EMotionType::Static>,+ &ContactConstraintManager::TemplatedGetContactsFromCache<EMotionType::Dynamic, EMotionType::Kinematic>,+ &ContactConstraintManager::TemplatedGetContactsFromCache<EMotionType::Dynamic, EMotionType::Dynamic>+ }+ };++ // Dispatch to the correct templated form+ (this->*table[(int)body1->GetMotionType()][(int)body2->GetMotionType()])(ioContactAllocator, *body1, *body2, input_cbp, *output_cbp);}ContactConstraintManager::BodyPairHandle ContactConstraintManager::AddBodyPair(ContactAllocator &ioContactAllocator, const Body &inBody1, const Body &inBody2)@@ -1028,7 +1105,7 @@ ContactConstraintManager::BodyPairHandle ContactConstraintManager::AddBodyPair(C// Add an entryBodyPair body_pair_key(body1->GetID(), body2->GetID());uint64 body_pair_hash = body_pair_key.GetHash();- BPKeyValue *body_pair_kv = mCache[mCacheWriteIdx].Create(ioContactAllocator, body_pair_key, body_pair_hash);+ BPKeyValue *body_pair_kv = mWriteCache->Create(ioContactAllocator, body_pair_key, body_pair_hash);if (body_pair_kv == nullptr)return nullptr; // Out of cache spaceCachedBodyPair *cbp = &body_pair_kv->GetValue();@@ -1051,7 +1128,7 @@ ContactConstraintManager::BodyPairHandle ContactConstraintManager::AddBodyPair(C}template <EMotionType Type1, EMotionType Type2>-bool ContactConstraintManager::TemplatedAddContactConstraint(ContactAllocator &ioContactAllocator, BodyPairHandle inBodyPairHandle, Body &inBody1, Body &inBody2, const ContactManifold &inManifold)+void ContactConstraintManager::TemplatedAddContactConstraint(ContactAllocator &ioContactAllocator, bool &ioActivateAndLinkBodies, BodyPairHandle inBodyPairHandle, Body &inBody1, Body &inBody2, const ContactManifold &inManifold){// Calculate hashSubShapeIDPair key { inBody1.GetID(), inManifold.mSubShapeID1, inBody2.GetID(), inManifold.mSubShapeID2 };@@ -1065,11 +1142,11 @@ bool ContactConstraintManager::TemplatedAddContactConstraint(ContactAllocator &i// Reserve space for new contact cache entry// Note that for dynamic vs dynamic we always require the first body to have a lower body id to get a consistent key// under which to look up the contact- ManifoldCache &write_cache = mCache[mCacheWriteIdx];- MKeyValue *new_manifold_kv = write_cache.Create(ioContactAllocator, key, key_hash, num_contact_points);+ MKeyValue *new_manifold_kv = mWriteCache->Create(ioContactAllocator, key, key_hash, num_contact_points);if (new_manifold_kv == nullptr)- return false; // Out of cache space+ return; // Out of cache spaceCachedManifold *new_manifold = &new_manifold_kv->GetValue();+ uint32 new_manifold_handle = mWriteCache->ToHandle(new_manifold_kv);// Transform the world space normal to the space of body 2 (this is usually the static body)RMat44 inverse_transform_body2 = inBody2.GetInverseCenterOfMassTransform();@@ -1082,8 +1159,7 @@ bool ContactConstraintManager::TemplatedAddContactConstraint(ContactAllocator &isettings.mIsSensor = inBody1.IsSensor() || inBody2.IsSensor();// Get the contact points for the old cache entry- const ManifoldCache &read_cache = mCache[mCacheWriteIdx ^ 1];- const MKeyValue *old_manifold_kv = read_cache.Find(key, key_hash);+ const MKeyValue *old_manifold_kv = mReadCache->Find(key, key_hash);const CachedContactPoint *ccp_start;const CachedContactPoint *ccp_end;if (old_manifold_kv != nullptr)@@ -1114,138 +1190,117 @@ bool ContactConstraintManager::TemplatedAddContactConstraint(ContactAllocator &i// Get inverse transform for body 1RMat44 inverse_transform_body1 = inBody1.GetInverseCenterOfMassTransform();- bool contact_constraint_created = false;-// If one of the bodies is a sensor, don't actually create the constraintJPH_ASSERT(settings.mIsSensor || !(inBody1.IsSensor() || inBody2.IsSensor()), "Sensors cannot be converted into regular bodies by a contact callback!");if (!settings.mIsSensor- && ((inBody1.IsDynamic() && settings.mInvMassScale1 != 0.0f) // One of the bodies must have mass to be able to create a contact constraint- || (inBody2.IsDynamic() && settings.mInvMassScale2 != 0.0f)))+ && ((Type1 == EMotionType::Dynamic && settings.mInvMassScale1 != 0.0f) // One of the bodies must have mass to be able to create a contact constraint+ || (Type2 == EMotionType::Dynamic && settings.mInvMassScale2 != 0.0f))){- // Add contact constraint- uint32 constraint_idx = mNumConstraints++;- if (constraint_idx >= mMaxConstraints)+ // Create a new constraint+ ContactConstraint<Type1, Type2> *constraint = CreateConstraint<Type1, Type2>(ioActivateAndLinkBodies, inBody1, inBody2, key_hash, new_manifold_handle, inManifold.mWorldSpaceNormal, settings, num_contact_points);+ if (constraint == nullptr){ioContactAllocator.mErrors |= EPhysicsUpdateError::ContactConstraintsFull;// Manifold has been created already, we're not filling it in, so we need to reset the contact number of points.// Note that we don't hook it up to the body pair cache so that it won't be used as a cache during the next simulation.new_manifold->mNumContactPoints = 0;- return false;+ return;}- // We will create a contact constraint- contact_constraint_created = true;-- ContactConstraint &constraint = mConstraints[constraint_idx];- new (&constraint) ContactConstraint();- constraint.mBody1 = &inBody1;- constraint.mBody2 = &inBody2;- constraint.mSortKey = key_hash;- inManifold.mWorldSpaceNormal.StoreFloat3(&constraint.mWorldSpaceNormal);- constraint.mCombinedFriction = settings.mCombinedFriction;- constraint.mInvMass1 = inBody1.GetMotionPropertiesUnchecked() != nullptr? settings.mInvMassScale1 * inBody1.GetMotionPropertiesUnchecked()->GetInverseMassUnchecked() : 0.0f;- constraint.mInvInertiaScale1 = settings.mInvInertiaScale1;- constraint.mInvMass2 = inBody2.GetMotionPropertiesUnchecked() != nullptr? settings.mInvMassScale2 * inBody2.GetMotionPropertiesUnchecked()->GetInverseMassUnchecked() : 0.0f;- constraint.mInvInertiaScale2 = settings.mInvInertiaScale2;-- JPH_DET_LOG("TemplatedAddContactConstraint: id1: " << constraint.mBody1->GetID() << " id2: " << constraint.mBody2->GetID() << " key: " << constraint.mSortKey);-- // Notify island builder- mUpdateContext->mIslandBuilder->LinkContact(constraint_idx, inBody1.GetIndexInActiveBodiesInternal(), inBody2.GetIndexInActiveBodiesInternal());+ JPH_DET_LOG("AddContactConstraint: id1: " << constraint->mBody1->GetID() << " id2: " << constraint->mBody2->GetID() << " key: " << constraint->mSortKey);// Get time step and gravityfloat delta_time = mUpdateContext->mStepDeltaTime;Vec3 gravity = mUpdateContext->mPhysicsSystem->GetGravity();// Calculate scaled mass and inertia- float inv_m1;Mat44 inv_i1;if constexpr (Type1 == EMotionType::Dynamic){const MotionProperties *mp1 = inBody1.GetMotionPropertiesUnchecked();- inv_m1 = settings.mInvMassScale1 * mp1->GetInverseMass();+ constraint->mInvMass1 = settings.mInvMassScale1 * mp1->GetInverseMass();inv_i1 = settings.mInvInertiaScale1 * mp1->GetInverseInertiaForRotation(inverse_transform_body1.Transposed3x3());}else{- inv_m1 = 0.0f;+ constraint->mInvMass1 = 0.0f;inv_i1 = Mat44::sZero();}- float inv_m2;Mat44 inv_i2;if constexpr (Type2 == EMotionType::Dynamic){const MotionProperties *mp2 = inBody2.GetMotionPropertiesUnchecked();- inv_m2 = settings.mInvMassScale2 * mp2->GetInverseMass();+ constraint->mInvMass2 = settings.mInvMassScale2 * mp2->GetInverseMass();inv_i2 = settings.mInvInertiaScale2 * mp2->GetInverseInertiaForRotation(inverse_transform_body2.Transposed3x3());}else{- inv_m2 = 0.0f;+ constraint->mInvMass2 = 0.0f;inv_i2 = Mat44::sZero();}- // Calculate tangents- Vec3 t1, t2;- constraint.GetTangents(t1, t2);-- constraint.mContactPoints.resize(num_contact_points);+ RVec3 ws_contacts[MaxContactPoints];for (int i = 0; i < num_contact_points; ++i){// Convert to world space and set positions- WorldContactPoint &wcp = constraint.mContactPoints[i];+ WorldContactPoint<Type1, Type2> &wcp = constraint->mContactPoints[i];RVec3 p1_ws = inManifold.mBaseOffset + inManifold.mRelativeContactPointsOn1[i];RVec3 p2_ws = inManifold.mBaseOffset + inManifold.mRelativeContactPointsOn2[i];+ // Remember where to apply friction+ ws_contacts[i] = 0.5_r * (p1_ws + p2_ws);+// Convert to local space to the bodyVec3 p1_ls = Vec3(inverse_transform_body1 * p1_ws);Vec3 p2_ls = Vec3(inverse_transform_body2 * p2_ws);+ // Store contact points+ CachedContactPoint &cp = new_manifold->mContactPoints[i];+ p1_ls.StoreFloat3(&cp.mPosition1);+ p2_ls.StoreFloat3(&cp.mPosition2);+// Check if we have a close contact point from last update- bool lambda_set = false;+ wcp.mNonPenetrationConstraint.SetTotalLambda(0.0f);for (const CachedContactPoint *ccp = ccp_start; ccp < ccp_end; ccp++)if (Vec3::sLoadFloat3Unsafe(ccp->mPosition1).IsClose(p1_ls, mPhysicsSettings.mContactPointPreserveLambdaMaxDistSq)&& Vec3::sLoadFloat3Unsafe(ccp->mPosition2).IsClose(p2_ls, mPhysicsSettings.mContactPointPreserveLambdaMaxDistSq)){// Get lambdas from previous framewcp.mNonPenetrationConstraint.SetTotalLambda(ccp->mNonPenetrationLambda);- wcp.mFrictionConstraint1.SetTotalLambda(ccp->mFrictionLambda[0]);- wcp.mFrictionConstraint2.SetTotalLambda(ccp->mFrictionLambda[1]);- lambda_set = true;break;}- if (!lambda_set)- {- wcp.mNonPenetrationConstraint.SetTotalLambda(0.0f);- wcp.mFrictionConstraint1.SetTotalLambda(0.0f);- wcp.mFrictionConstraint2.SetTotalLambda(0.0f);- }-- // Create new contact point- CachedContactPoint &cp = new_manifold->mContactPoints[i];- p1_ls.StoreFloat3(&cp.mPosition1);- p2_ls.StoreFloat3(&cp.mPosition2);- wcp.mContactPoint = &cp;// Setup velocity constraint- wcp.TemplatedCalculateFrictionAndNonPenetrationConstraintProperties<Type1, Type2>(delta_time, gravity, inBody1, inBody2, inv_m1, inv_m2, inv_i1, inv_i2, p1_ws, p2_ws, inManifold.mWorldSpaceNormal, t1, t2, settings, mPhysicsSettings.mMinVelocityForRestitution);+ wcp.CalculateNonPenetrationConstraintProperties(delta_time, gravity, inBody1, inBody2, constraint->mInvMass1, constraint->mInvMass2, inv_i1, inv_i2, p1_ws, p2_ws, inManifold.mWorldSpaceNormal, settings, mPhysicsSettings.mMinVelocityForRestitution);+ }++ // Calculate tangents+ Vec3 t1, t2;+ constraint->GetTangents(t1, t2);++ // Setup friction constraint+ if (old_manifold_kv != nullptr)+ {+ const CachedManifold *old_manifold = &old_manifold_kv->GetValue();+ constraint->mFrictionConstraint1.SetTotalLambda(old_manifold->mFrictionLambda[0]);+ constraint->mFrictionConstraint2.SetTotalLambda(old_manifold->mFrictionLambda[1]);+ constraint->mAngularFrictionConstraint.SetTotalLambda(old_manifold->mAngularFrictionLambda);}+ else+ {+ constraint->mFrictionConstraint1.SetTotalLambda(0.0f);+ constraint->mFrictionConstraint2.SetTotalLambda(0.0f);+ constraint->mAngularFrictionConstraint.SetTotalLambda(0.0f);+ }+ constraint->CalculateFrictionConstraintProperties(inBody1, inBody2, constraint->mInvMass1, constraint->mInvMass2, inv_i1, inv_i2, ws_contacts, inManifold.mWorldSpaceNormal, t1, t2, settings);- #ifdef JPH_DEBUG_RENDERER+#ifdef JPH_DEBUG_RENDERER// Draw the manifoldif (sDrawContactManifolds)- constraint.Draw(DebugRenderer::sInstance, Color::sOrange);+ constraint->Draw(DebugRenderer::sInstance, *mWriteCache, Color::sOrange);#endif // JPH_DEBUG_RENDERER-- #ifdef JPH_TRACK_SIMULATION_STATS- // Track new contact constraints- if constexpr (Type1 != EMotionType::Static)- inBody1.GetMotionPropertiesUnchecked()->GetSimulationStats().mNumContactConstraints.fetch_add(1, memory_order_relaxed);- if constexpr (Type2 != EMotionType::Static)- inBody2.GetMotionPropertiesUnchecked()->GetSimulationStats().mNumContactConstraints.fetch_add(1, memory_order_relaxed);- #endif}else{@@ -1263,21 +1318,20 @@ bool ContactConstraintManager::TemplatedAddContactConstraint(ContactAllocator &i// Reset contact impulses, we haven't applied anycp.mNonPenetrationLambda = 0.0f;- cp.mFrictionLambda[0] = 0.0f;- cp.mFrictionLambda[1] = 0.0f;}++ new_manifold->mFrictionLambda[0] = 0.0f;+ new_manifold->mFrictionLambda[1] = 0.0f;+ new_manifold->mAngularFrictionLambda = 0.0f;}// Store cached contact point in body pair cacheCachedBodyPair *cbp = reinterpret_cast<CachedBodyPair *>(inBodyPairHandle);new_manifold->mNextWithSameBodyPair = cbp->mFirstCachedManifold;- cbp->mFirstCachedManifold = write_cache.ToHandle(new_manifold_kv);-- // A contact constraint was added- return contact_constraint_created;+ cbp->mFirstCachedManifold = new_manifold_handle;}-bool ContactConstraintManager::AddContactConstraint(ContactAllocator &ioContactAllocator, BodyPairHandle inBodyPairHandle, Body &inBody1, Body &inBody2, const ContactManifold &inManifold)+void ContactConstraintManager::AddContactConstraint(ContactAllocator &ioContactAllocator, bool &ioActivateAndLinkBodies, BodyPairHandle inBodyPairHandle, Body &inBody1, Body &inBody2, const ContactManifold &inManifold){JPH_PROFILE_FUNCTION();@@ -1305,70 +1359,29 @@ bool ContactConstraintManager::AddContactConstraint(ContactAllocator &ioContactAmanifold = &inManifold;}- // Dispatch to the correct templated form- // Note: Non-dynamic vs non-dynamic can happen in this case due to one body being a sensor, so we need to have an extended switch case here- switch (body1->GetMotionType())- {- case EMotionType::Dynamic:+ // Build dispatch table+ // Note: Non-dynamic vs non-dynamic can happen in this case due to one body being a sensor, so we need to have an extended table here+ using DispatchFunc = void (ContactConstraintManager::*)(ContactAllocator &, bool &, BodyPairHandle, Body &, Body &, const ContactManifold &);+ static const DispatchFunc table[3][3] = {{- switch (body2->GetMotionType())- {- case EMotionType::Dynamic:- return TemplatedAddContactConstraint<EMotionType::Dynamic, EMotionType::Dynamic>(ioContactAllocator, inBodyPairHandle, *body1, *body2, *manifold);-- case EMotionType::Kinematic:- return TemplatedAddContactConstraint<EMotionType::Dynamic, EMotionType::Kinematic>(ioContactAllocator, inBodyPairHandle, *body1, *body2, *manifold);-- case EMotionType::Static:- return TemplatedAddContactConstraint<EMotionType::Dynamic, EMotionType::Static>(ioContactAllocator, inBodyPairHandle, *body1, *body2, *manifold);-- default:- JPH_ASSERT(false);- break;- }- break;- }-- case EMotionType::Kinematic:- switch (body2->GetMotionType())+ nullptr, // Static vs static doesn't exist+ &ContactConstraintManager::TemplatedAddContactConstraint<EMotionType::Static, EMotionType::Kinematic>,+ &ContactConstraintManager::TemplatedAddContactConstraint<EMotionType::Static, EMotionType::Dynamic>+ },{- case EMotionType::Dynamic:- return TemplatedAddContactConstraint<EMotionType::Kinematic, EMotionType::Dynamic>(ioContactAllocator, inBodyPairHandle, *body1, *body2, *manifold);-- case EMotionType::Kinematic:- return TemplatedAddContactConstraint<EMotionType::Kinematic, EMotionType::Kinematic>(ioContactAllocator, inBodyPairHandle, *body1, *body2, *manifold);-- case EMotionType::Static:- return TemplatedAddContactConstraint<EMotionType::Kinematic, EMotionType::Static>(ioContactAllocator, inBodyPairHandle, *body1, *body2, *manifold);-- default:- JPH_ASSERT(false);- break;- }- break;-- case EMotionType::Static:- switch (body2->GetMotionType())+ &ContactConstraintManager::TemplatedAddContactConstraint<EMotionType::Kinematic, EMotionType::Static>,+ &ContactConstraintManager::TemplatedAddContactConstraint<EMotionType::Kinematic, EMotionType::Kinematic>,+ &ContactConstraintManager::TemplatedAddContactConstraint<EMotionType::Kinematic, EMotionType::Dynamic>+ },{- case EMotionType::Dynamic:- return TemplatedAddContactConstraint<EMotionType::Static, EMotionType::Dynamic>(ioContactAllocator, inBodyPairHandle, *body1, *body2, *manifold);-- case EMotionType::Kinematic:- return TemplatedAddContactConstraint<EMotionType::Static, EMotionType::Kinematic>(ioContactAllocator, inBodyPairHandle, *body1, *body2, *manifold);-- case EMotionType::Static: // Static vs static not possible- default:- JPH_ASSERT(false);- break;+ &ContactConstraintManager::TemplatedAddContactConstraint<EMotionType::Dynamic, EMotionType::Static>,+ &ContactConstraintManager::TemplatedAddContactConstraint<EMotionType::Dynamic, EMotionType::Kinematic>,+ &ContactConstraintManager::TemplatedAddContactConstraint<EMotionType::Dynamic, EMotionType::Dynamic>}- break;-- default:- JPH_ASSERT(false);- break;- }+ };- return false;+ // Dispatch to the correct templated form+ return (this->*table[(int)body1->GetMotionType()][(int)body2->GetMotionType()])(ioContactAllocator, ioActivateAndLinkBodies, inBodyPairHandle, *body1, *body2, *manifold);}void ContactConstraintManager::OnCCDContactAdded(ContactAllocator &ioContactAllocator, const Body &inBody1, const Body &inBody2, const ContactManifold &inManifold, ContactSettings &outSettings)@@ -1406,13 +1419,11 @@ void ContactConstraintManager::OnCCDContactAdded(ContactAllocator &ioContactAllouint64 key_hash = key.GetHash();// Check if we already created this contact this physics update- ManifoldCache &write_cache = mCache[mCacheWriteIdx];- MKVAndCreated new_manifold_kv = write_cache.FindOrCreate(ioContactAllocator, key, key_hash, 0);+ MKVAndCreated new_manifold_kv = mWriteCache->FindOrCreate(ioContactAllocator, key, key_hash, 0);if (new_manifold_kv.second){// This contact is new for this physics update, check if previous update we already had this contact.- const ManifoldCache &read_cache = mCache[mCacheWriteIdx ^ 1];- const MKeyValue *old_manifold_kv = read_cache.Find(key, key_hash);+ const MKeyValue *old_manifold_kv = mReadCache->Find(key, key_hash);if (old_manifold_kv == nullptr){// New contact@@ -1455,13 +1466,19 @@ void ContactConstraintManager::OnCCDContactAdded(ContactAllocator &ioContactAlloJPH_ASSERT(outSettings.mIsSensor || !(inBody1.IsSensor() || inBody2.IsSensor()), "Sensors cannot be converted into regular bodies by a contact callback!");}-void ContactConstraintManager::SortContacts(uint32 *inConstraintIdxBegin, uint32 *inConstraintIdxEnd) const+void ContactConstraintManager::ConstraintIdxToConstraintOffset(uint32 *ioConstraintIdxBegin, const uint32 *inConstraintIdxEnd) const+{+ for (uint32 *i = ioConstraintIdxBegin; i < inConstraintIdxEnd; ++i)+ *i = mConstraintIdxToOffset[*i];+}++void ContactConstraintManager::SortContacts(uint32 *ioConstraintOffsetBegin, uint32 *inConstraintOffsetEnd) const{JPH_PROFILE_FUNCTION();- QuickSort(inConstraintIdxBegin, inConstraintIdxEnd, [this](uint32 inLHS, uint32 inRHS) {- const ContactConstraint &lhs = mConstraints[inLHS];- const ContactConstraint &rhs = mConstraints[inRHS];+ QuickSort(ioConstraintOffsetBegin, inConstraintOffsetEnd, [this](uint32 inLHS, uint32 inRHS) {+ const ContactConstraintBase &lhs = *reinterpret_cast<const ContactConstraintBase *>(mConstraints + inLHS);+ const ContactConstraintBase &rhs = *reinterpret_cast<const ContactConstraintBase *>(mConstraints + inRHS);// Most of the time the sort key will be different so we sort on thatif (lhs.mSortKey != rhs.mSortKey)@@ -1526,248 +1543,448 @@ bool ContactConstraintManager::WereBodiesInContact(const BodyID &inBody1ID, cons}template <EMotionType Type1, EMotionType Type2>-JPH_INLINE void ContactConstraintManager::sWarmStartConstraint(ContactConstraint &ioConstraint, MotionProperties *ioMotionProperties1, MotionProperties *ioMotionProperties2, float inWarmStartImpulseRatio)+void ContactConstraintManager::sGetVelocities(const MotionProperties *inMotionProperties1, const MotionProperties *inMotionProperties2, Vec3 &outLinearVelocity1, Vec3 &outAngularVelocity1, Vec3 &outLinearVelocity2, Vec3 &outAngularVelocity2){- // Calculate tangents- Vec3 t1, t2;- ioConstraint.GetTangents(t1, t2);+ if constexpr (Type1 != EMotionType::Static)+ {+ outLinearVelocity1 = inMotionProperties1->GetLinearVelocity();+ outAngularVelocity1 = inMotionProperties1->GetAngularVelocity();+ }+ else+ {+ JPH_IF_DEBUG(outLinearVelocity1 = Vec3::sNaN();)+ JPH_IF_DEBUG(outAngularVelocity1 = Vec3::sNaN();)+ }++ if constexpr (Type2 != EMotionType::Static)+ {+ outLinearVelocity2 = inMotionProperties2->GetLinearVelocity();+ outAngularVelocity2 = inMotionProperties2->GetAngularVelocity();+ }+ else+ {+ JPH_IF_DEBUG(outLinearVelocity2 = Vec3::sNaN();)+ JPH_IF_DEBUG(outAngularVelocity2 = Vec3::sNaN();)+ }+}- Vec3 ws_normal = ioConstraint.GetWorldSpaceNormal();+template <EMotionType Type1, EMotionType Type2>+void ContactConstraintManager::sSetVelocities(MotionProperties *ioMotionProperties1, MotionProperties *ioMotionProperties2, Vec3Arg inLinearVelocity1, Vec3Arg inAngularVelocity1, Vec3Arg inLinearVelocity2, Vec3Arg inAngularVelocity2)+{+ if constexpr (Type1 == EMotionType::Dynamic)+ {+ ioMotionProperties1->ApplyLinearVelocityStep(inLinearVelocity1);+ ioMotionProperties1->ApplyAngularVelocityStep(inAngularVelocity1);+ }- for (WorldContactPoint &wcp : ioConstraint.mContactPoints)+ if constexpr (Type2 == EMotionType::Dynamic){- // Warm starting: Apply impulse from last frame- if (wcp.mFrictionConstraint1.IsActive() || wcp.mFrictionConstraint2.IsActive())- {- wcp.mFrictionConstraint1.TemplatedWarmStart<Type1, Type2>(ioMotionProperties1, ioConstraint.mInvMass1, ioMotionProperties2, ioConstraint.mInvMass2, t1, inWarmStartImpulseRatio);- wcp.mFrictionConstraint2.TemplatedWarmStart<Type1, Type2>(ioMotionProperties1, ioConstraint.mInvMass1, ioMotionProperties2, ioConstraint.mInvMass2, t2, inWarmStartImpulseRatio);- }- wcp.mNonPenetrationConstraint.TemplatedWarmStart<Type1, Type2>(ioMotionProperties1, ioConstraint.mInvMass1, ioMotionProperties2, ioConstraint.mInvMass2, ws_normal, inWarmStartImpulseRatio);+ ioMotionProperties2->ApplyLinearVelocityStep(inLinearVelocity2);+ ioMotionProperties2->ApplyAngularVelocityStep(inAngularVelocity2);}}-template <class MotionPropertiesCallback>-void ContactConstraintManager::WarmStartVelocityConstraints(const uint32 *inConstraintIdxBegin, const uint32 *inConstraintIdxEnd, float inWarmStartImpulseRatio, MotionPropertiesCallback &ioCallback)+template <EMotionType Type1, EMotionType Type2>+void ContactConstraintManager::sWarmStartConstraint(ContactConstraintBase &ioConstraint, MotionProperties *ioMotionProperties1, MotionProperties *ioMotionProperties2, float inWarmStartImpulseRatio){- JPH_PROFILE_FUNCTION();+ ContactConstraint<Type1, Type2> &constraint = static_cast<ContactConstraint<Type1, Type2> &>(ioConstraint);++ bool any_impulse_applied = false;++ // Calculate tangents+ Vec3 t1, t2;+ constraint.GetTangents(t1, t2);- for (const uint32 *constraint_idx = inConstraintIdxBegin; constraint_idx < inConstraintIdxEnd; ++constraint_idx)+ // Get velocities+ Vec3 linear_velocity1, angular_velocity1, linear_velocity2, angular_velocity2;+ sGetVelocities<Type1, Type2>(ioMotionProperties1, ioMotionProperties2, linear_velocity1, angular_velocity1, linear_velocity2, angular_velocity2);++ Vec3 ws_normal = constraint.GetWorldSpaceNormal();++ // Warm starting: Apply impulse from last frame+ if (constraint.mFrictionConstraint1.IsActive() && constraint.mFrictionConstraint1.WarmStart(linear_velocity1, angular_velocity1, linear_velocity2, angular_velocity2, constraint.mInvMass1, constraint.mInvMass2, t1, inWarmStartImpulseRatio))+ any_impulse_applied = true;+ if (constraint.mFrictionConstraint2.IsActive() && constraint.mFrictionConstraint2.WarmStart(linear_velocity1, angular_velocity1, linear_velocity2, angular_velocity2, constraint.mInvMass1, constraint.mInvMass2, t2, inWarmStartImpulseRatio))+ any_impulse_applied = true;+ if (constraint.mAngularFrictionConstraint.IsActive() && constraint.mAngularFrictionConstraint.WarmStart(angular_velocity1, angular_velocity2, inWarmStartImpulseRatio))+ any_impulse_applied = true;++ for (uint32 i = 0; i < constraint.mNumContactPoints; ++i){- ContactConstraint &constraint = mConstraints[*constraint_idx];+ WorldContactPoint<Type1, Type2> &wcp = constraint.mContactPoints[i];+ if (wcp.mNonPenetrationConstraint.WarmStart(linear_velocity1, angular_velocity1, linear_velocity2, angular_velocity2, constraint.mInvMass1, constraint.mInvMass2, ws_normal, inWarmStartImpulseRatio))+ any_impulse_applied = true;+ }- // Fetch bodies- Body &body1 = *constraint.mBody1;- EMotionType motion_type1 = body1.GetMotionType();- MotionProperties *motion_properties1 = body1.GetMotionPropertiesUnchecked();+ // Apply changed velocities+ if (any_impulse_applied)+ sSetVelocities<Type1, Type2>(ioMotionProperties1, ioMotionProperties2, linear_velocity1, angular_velocity1, linear_velocity2, angular_velocity2);+}- Body &body2 = *constraint.mBody2;- EMotionType motion_type2 = body2.GetMotionType();- MotionProperties *motion_properties2 = body2.GetMotionPropertiesUnchecked();+template <class MotionPropertiesCallback>+void ContactConstraintManager::WarmStartVelocityConstraints(const uint32 *inConstraintOffsetBegin, const uint32 *inConstraintOffsetEnd, float inWarmStartImpulseRatio, MotionPropertiesCallback &ioCallback)+{+ JPH_PROFILE_FUNCTION();- // Dispatch to the correct templated form- // Note: Warm starting doesn't differentiate between kinematic/static bodies so we handle both as static bodies- if (motion_type1 == EMotionType::Dynamic)+ // Build dispatch table+ using DispatchFunc = void (*)(ContactConstraintBase &, MotionProperties *, MotionProperties *, float);+ static const DispatchFunc table[3][3] = {{- if (motion_type2 == EMotionType::Dynamic)- {- sWarmStartConstraint<EMotionType::Dynamic, EMotionType::Dynamic>(constraint, motion_properties1, motion_properties2, inWarmStartImpulseRatio);+ nullptr, // Static vs static doesn't exist+ nullptr, // Static vs kinematic doesn't exist+ sWarmStartConstraint<EMotionType::Static, EMotionType::Dynamic>+ },+ {+ nullptr, // Kinematic vs static doesn't exist+ nullptr, // Kinematic vs kinematic doesn't exist+ sWarmStartConstraint<EMotionType::Kinematic, EMotionType::Dynamic>+ },+ {+ sWarmStartConstraint<EMotionType::Dynamic, EMotionType::Static>,+ sWarmStartConstraint<EMotionType::Dynamic, EMotionType::Kinematic>,+ sWarmStartConstraint<EMotionType::Dynamic, EMotionType::Dynamic>+ }+ };- ioCallback(motion_properties2);- }- else- sWarmStartConstraint<EMotionType::Dynamic, EMotionType::Static>(constraint, motion_properties1, motion_properties2, inWarmStartImpulseRatio);+ if (inConstraintOffsetBegin >= inConstraintOffsetEnd)+ return;- ioCallback(motion_properties1);+ ContactConstraintBase *next_constraint = reinterpret_cast<ContactConstraintBase *>(mConstraints + *inConstraintOffsetBegin);+ for (const uint32 *next_constraint_offset = inConstraintOffsetBegin + 1; next_constraint != nullptr; ++next_constraint_offset)+ {+ ContactConstraintBase &constraint = *next_constraint;+ if (next_constraint_offset < inConstraintOffsetEnd)+ {+ next_constraint = reinterpret_cast<ContactConstraintBase *>(mConstraints + *next_constraint_offset);+ PrefetchL1(next_constraint);}else- {- JPH_ASSERT(motion_type2 == EMotionType::Dynamic);+ next_constraint = nullptr;- sWarmStartConstraint<EMotionType::Static, EMotionType::Dynamic>(constraint, motion_properties1, motion_properties2, inWarmStartImpulseRatio);+ // Dispatch to the correct templated form+ Body &body1 = *constraint.mBody1;+ Body &body2 = *constraint.mBody2;+ MotionProperties *motion_properties1 = body1.GetMotionPropertiesUnchecked();+ MotionProperties *motion_properties2 = body2.GetMotionPropertiesUnchecked();+ table[(int)body1.GetMotionType()][(int)body2.GetMotionType()](constraint, motion_properties1, motion_properties2, inWarmStartImpulseRatio);+ // Call callbacks+ if (body1.IsDynamic())+ ioCallback(motion_properties1);+ if (body2.IsDynamic())ioCallback(motion_properties2);- }}}// Specialize for the two body callback types-template void ContactConstraintManager::WarmStartVelocityConstraints<CalculateSolverSteps>(const uint32 *inConstraintIdxBegin, const uint32 *inConstraintIdxEnd, float inWarmStartImpulseRatio, CalculateSolverSteps &ioCallback);-template void ContactConstraintManager::WarmStartVelocityConstraints<DummyCalculateSolverSteps>(const uint32 *inConstraintIdxBegin, const uint32 *inConstraintIdxEnd, float inWarmStartImpulseRatio, DummyCalculateSolverSteps &ioCallback);+template void ContactConstraintManager::WarmStartVelocityConstraints<CalculateSolverSteps>(const uint32 *inConstraintOffsetBegin, const uint32 *inConstraintOffsetEnd, float inWarmStartImpulseRatio, CalculateSolverSteps &ioCallback);+template void ContactConstraintManager::WarmStartVelocityConstraints<DummyCalculateSolverSteps>(const uint32 *inConstraintOffsetBegin, const uint32 *inConstraintOffsetEnd, float inWarmStartImpulseRatio, DummyCalculateSolverSteps &ioCallback);template <EMotionType Type1, EMotionType Type2>-JPH_INLINE bool ContactConstraintManager::sSolveVelocityConstraint(ContactConstraint &ioConstraint, MotionProperties *ioMotionProperties1, MotionProperties *ioMotionProperties2)+bool ContactConstraintManager::sSolveVelocityConstraint(ContactConstraintBase &ioConstraint, MotionProperties *ioMotionProperties1, MotionProperties *ioMotionProperties2){+ ContactConstraint<Type1, Type2> &constraint = static_cast<ContactConstraint<Type1, Type2> &>(ioConstraint);+bool any_impulse_applied = false;// Calculate tangentsVec3 t1, t2;- ioConstraint.GetTangents(t1, t2);+ constraint.GetTangents(t1, t2);++ // Get velocities+ Vec3 linear_velocity1, angular_velocity1, linear_velocity2, angular_velocity2;+ sGetVelocities<Type1, Type2>(ioMotionProperties1, ioMotionProperties2, linear_velocity1, angular_velocity1, linear_velocity2, angular_velocity2);- // First apply all friction constraints (non-penetration is more important than friction)- for (WorldContactPoint &wcp : ioConstraint.mContactPoints)+ bool linear_friction_active = constraint.mFrictionConstraint1.IsActive() || constraint.mFrictionConstraint2.IsActive();+ bool angular_friction_active = constraint.mAngularFrictionConstraint.IsActive();++ // Calculate max impulse that can be applied. Note that we're using the non-penetration impulse from the previous iteration here.+ // We do this because non-penetration is more important so is solved last (the last things that are solved in an iterative solver+ // contribute the most).+ float max_linear_lambda = 0.0f, max_angular_lambda = 0.0f;+ if (linear_friction_active || angular_friction_active){- // Check if friction is enabled- if (wcp.mFrictionConstraint1.IsActive() || wcp.mFrictionConstraint2.IsActive())+ for (uint32 i = 0; i < constraint.mNumContactPoints; ++i){- // Calculate impulse to stop motion in tangential direction- float lambda1 = wcp.mFrictionConstraint1.TemplatedSolveVelocityConstraintGetTotalLambda<Type1, Type2>(ioMotionProperties1, ioMotionProperties2, t1);- float lambda2 = wcp.mFrictionConstraint2.TemplatedSolveVelocityConstraintGetTotalLambda<Type1, Type2>(ioMotionProperties1, ioMotionProperties2, t2);- float total_lambda_sq = Square(lambda1) + Square(lambda2);-- // Calculate max impulse that can be applied. Note that we're using the non-penetration impulse from the previous iteration here.- // We do this because non-penetration is more important so is solved last (the last things that are solved in an iterative solver- // contribute the most).- float max_lambda_f = ioConstraint.mCombinedFriction * wcp.mNonPenetrationConstraint.GetTotalLambda();-- // If the total lambda that we will apply is too large, scale it back- if (total_lambda_sq > Square(max_lambda_f))- {- float scale = max_lambda_f / sqrt(total_lambda_sq);- lambda1 *= scale;- lambda2 *= scale;- }+ WorldContactPoint<Type1, Type2> &wcp = constraint.mContactPoints[i];+ float lambda = wcp.mNonPenetrationConstraint.GetTotalLambda();+ max_linear_lambda += lambda;+ max_angular_lambda += wcp.mDistanceToFrictionCenter * lambda;+ }+ max_linear_lambda *= constraint.mCombinedFriction;+ max_angular_lambda *= constraint.mCombinedFriction;+ }- // Apply the friction impulse- if (wcp.mFrictionConstraint1.TemplatedSolveVelocityConstraintApplyLambda<Type1, Type2>(ioMotionProperties1, ioConstraint.mInvMass1, ioMotionProperties2, ioConstraint.mInvMass2, t1, lambda1))- any_impulse_applied = true;- if (wcp.mFrictionConstraint2.TemplatedSolveVelocityConstraintApplyLambda<Type1, Type2>(ioMotionProperties1, ioConstraint.mInvMass1, ioMotionProperties2, ioConstraint.mInvMass2, t2, lambda2))- any_impulse_applied = true;+ // First apply friction constraint (non-penetration is more important than friction)+ if (linear_friction_active)+ {+ // Calculate impulse to stop motion in tangential direction+ float lambda1 = constraint.mFrictionConstraint1.SolveVelocityConstraintGetTotalLambda(linear_velocity1, angular_velocity1, linear_velocity2, angular_velocity2, t1);+ float lambda2 = constraint.mFrictionConstraint2.SolveVelocityConstraintGetTotalLambda(linear_velocity1, angular_velocity1, linear_velocity2, angular_velocity2, t2);++ // If the total lambda that we will apply is too large, scale it back+ float total_lambda_sq = Square(lambda1) + Square(lambda2);+ if (total_lambda_sq > Square(max_linear_lambda))+ {+ float scale = max_linear_lambda / Sqrt(total_lambda_sq);+ lambda1 *= scale;+ lambda2 *= scale;}++ // Apply the friction impulse+ if (constraint.mFrictionConstraint1.SolveVelocityConstraintApplyLambda(linear_velocity1, angular_velocity1, linear_velocity2, angular_velocity2, constraint.mInvMass1, constraint.mInvMass2, t1, lambda1))+ any_impulse_applied = true;+ if (constraint.mFrictionConstraint2.SolveVelocityConstraintApplyLambda(linear_velocity1, angular_velocity1, linear_velocity2, angular_velocity2, constraint.mInvMass1, constraint.mInvMass2, t2, lambda2))+ any_impulse_applied = true;}- Vec3 ws_normal = ioConstraint.GetWorldSpaceNormal();+ // Apply angular friction+ Vec3 ws_normal = constraint.GetWorldSpaceNormal();+ if (angular_friction_active && constraint.mAngularFrictionConstraint.SolveVelocityConstraint(angular_velocity1, angular_velocity2, ws_normal, -max_angular_lambda, max_angular_lambda))+ any_impulse_applied = true;// Then apply all non-penetration constraints- for (WorldContactPoint &wcp : ioConstraint.mContactPoints)+ for (uint32 i = 0; i < constraint.mNumContactPoints; ++i){- // Solve non penetration velocities- if (wcp.mNonPenetrationConstraint.TemplatedSolveVelocityConstraint<Type1, Type2>(ioMotionProperties1, ioConstraint.mInvMass1, ioMotionProperties2, ioConstraint.mInvMass2, ws_normal, 0.0f, FLT_MAX))+ WorldContactPoint<Type1, Type2> &wcp = constraint.mContactPoints[i];++ // Calculate impulse+ float total_lambda = wcp.mNonPenetrationConstraint.SolveVelocityConstraintGetTotalLambda(linear_velocity1, angular_velocity1, linear_velocity2, angular_velocity2, ws_normal);++ // Contact constraints can only push and not pull+ total_lambda = max(total_lambda, 0.0f);++ // Apply impulse+ if (wcp.mNonPenetrationConstraint.SolveVelocityConstraintApplyLambda(linear_velocity1, angular_velocity1, linear_velocity2, angular_velocity2, constraint.mInvMass1, constraint.mInvMass2, ws_normal, total_lambda))any_impulse_applied = true;}- return any_impulse_applied;+ if (!any_impulse_applied)+ return false;++ sSetVelocities<Type1, Type2>(ioMotionProperties1, ioMotionProperties2, linear_velocity1, angular_velocity1, linear_velocity2, angular_velocity2);+ return true;}-bool ContactConstraintManager::SolveVelocityConstraints(const uint32 *inConstraintIdxBegin, const uint32 *inConstraintIdxEnd)+bool ContactConstraintManager::SolveVelocityConstraints(const uint32 *inConstraintOffsetBegin, const uint32 *inConstraintOffsetEnd){JPH_PROFILE_FUNCTION();+ // Build dispatch table+ using DispatchFunc = bool (*)(ContactConstraintBase &, MotionProperties *, MotionProperties *);+ static const DispatchFunc table[3][3] = {+ {+ nullptr, // Static vs static doesn't exist+ nullptr, // Static vs kinematic doesn't exist+ sSolveVelocityConstraint<EMotionType::Static, EMotionType::Dynamic>+ },+ {+ nullptr, // Kinematic vs static doesn't exist+ nullptr, // Kinematic vs kinematic doesn't exist+ sSolveVelocityConstraint<EMotionType::Kinematic, EMotionType::Dynamic>+ },+ {+ sSolveVelocityConstraint<EMotionType::Dynamic, EMotionType::Static>,+ sSolveVelocityConstraint<EMotionType::Dynamic, EMotionType::Kinematic>,+ sSolveVelocityConstraint<EMotionType::Dynamic, EMotionType::Dynamic>+ }+ };++ if (inConstraintOffsetBegin >= inConstraintOffsetEnd)+ return false;+bool any_impulse_applied = false;- for (const uint32 *constraint_idx = inConstraintIdxBegin; constraint_idx < inConstraintIdxEnd; ++constraint_idx)+ ContactConstraintBase *next_constraint = reinterpret_cast<ContactConstraintBase *>(mConstraints + *inConstraintOffsetBegin);+ for (const uint32 *next_constraint_offset = inConstraintOffsetBegin + 1; next_constraint != nullptr; ++next_constraint_offset){- ContactConstraint &constraint = mConstraints[*constraint_idx];+ ContactConstraintBase &constraint = *next_constraint;+ if (next_constraint_offset < inConstraintOffsetEnd)+ {+ next_constraint = reinterpret_cast<ContactConstraintBase *>(mConstraints + *next_constraint_offset);+ PrefetchL1(next_constraint);+ }+ else+ next_constraint = nullptr;- // Fetch bodies+ // Dispatch to the correct templated formBody &body1 = *constraint.mBody1;- EMotionType motion_type1 = body1.GetMotionType();- MotionProperties *motion_properties1 = body1.GetMotionPropertiesUnchecked();-Body &body2 = *constraint.mBody2;- EMotionType motion_type2 = body2.GetMotionType();- MotionProperties *motion_properties2 = body2.GetMotionPropertiesUnchecked();+ any_impulse_applied |= table[(int)body1.GetMotionType()][(int)body2.GetMotionType()](constraint, body1.GetMotionPropertiesUnchecked(), body2.GetMotionPropertiesUnchecked());+ }- // Dispatch to the correct templated form- switch (motion_type1)- {- case EMotionType::Dynamic:- switch (motion_type2)- {- case EMotionType::Dynamic:- any_impulse_applied |= sSolveVelocityConstraint<EMotionType::Dynamic, EMotionType::Dynamic>(constraint, motion_properties1, motion_properties2);- break;+ return any_impulse_applied;+}- case EMotionType::Kinematic:- any_impulse_applied |= sSolveVelocityConstraint<EMotionType::Dynamic, EMotionType::Kinematic>(constraint, motion_properties1, motion_properties2);- break;+template <EMotionType Type1, EMotionType Type2>+void ContactConstraintManager::sStoreAppliedImpulses(ContactConstraintBase &ioConstraint, ManifoldCache &inManifoldCache)+{+ ContactConstraint<Type1, Type2> &constraint = static_cast<ContactConstraint<Type1, Type2> &>(ioConstraint);+ CachedManifold &cached_manifold = inManifoldCache.FromHandle(constraint.mCachedManifoldHandle)->GetValue();- case EMotionType::Static:- any_impulse_applied |= sSolveVelocityConstraint<EMotionType::Dynamic, EMotionType::Static>(constraint, motion_properties1, motion_properties2);- break;+ for (uint32 i = 0; i < constraint.mNumContactPoints; ++i)+ {+ const WorldContactPoint<Type1, Type2> &wcp = constraint.mContactPoints[i];+ CachedContactPoint &ccp = cached_manifold.mContactPoints[i];+ ccp.mNonPenetrationLambda = wcp.mNonPenetrationConstraint.GetTotalLambda();+ }- default:- JPH_ASSERT(false);- break;- }- break;+ cached_manifold.mFrictionLambda[0] = constraint.mFrictionConstraint1.GetTotalLambda();+ cached_manifold.mFrictionLambda[1] = constraint.mFrictionConstraint2.GetTotalLambda();+ cached_manifold.mAngularFrictionLambda = constraint.mAngularFrictionConstraint.GetTotalLambda();+}- case EMotionType::Kinematic:- JPH_ASSERT(motion_type2 == EMotionType::Dynamic);- any_impulse_applied |= sSolveVelocityConstraint<EMotionType::Kinematic, EMotionType::Dynamic>(constraint, motion_properties1, motion_properties2);- break;+void ContactConstraintManager::StoreAppliedImpulses(const uint32 *inConstraintOffsetBegin, const uint32 *inConstraintOffsetEnd) const+{+ // Build dispatch table+ using DispatchFunc = void (*)(ContactConstraintBase &, ManifoldCache &);+ static const DispatchFunc table[3][3] = {+ {+ nullptr, // Static vs static doesn't exist+ nullptr, // Static vs kinematic doesn't exist+ sStoreAppliedImpulses<EMotionType::Static, EMotionType::Dynamic>+ },+ {+ nullptr, // Kinematic vs static doesn't exist+ nullptr, // Kinematic vs kinematic doesn't exist+ sStoreAppliedImpulses<EMotionType::Kinematic, EMotionType::Dynamic>+ },+ {+ sStoreAppliedImpulses<EMotionType::Dynamic, EMotionType::Static>,+ sStoreAppliedImpulses<EMotionType::Dynamic, EMotionType::Kinematic>,+ sStoreAppliedImpulses<EMotionType::Dynamic, EMotionType::Dynamic>+ }+ };- case EMotionType::Static:- JPH_ASSERT(motion_type2 == EMotionType::Dynamic);- any_impulse_applied |= sSolveVelocityConstraint<EMotionType::Static, EMotionType::Dynamic>(constraint, motion_properties1, motion_properties2);- break;+ if (inConstraintOffsetBegin >= inConstraintOffsetEnd)+ return;- default:- JPH_ASSERT(false);- break;+ // Copy back total applied impulse to cache for the next frame+ ContactConstraintBase *next_constraint = reinterpret_cast<ContactConstraintBase *>(mConstraints + *inConstraintOffsetBegin);+ for (const uint32 *next_constraint_offset = inConstraintOffsetBegin + 1; next_constraint != nullptr; ++next_constraint_offset)+ {+ ContactConstraintBase &constraint = *next_constraint;+ if (next_constraint_offset < inConstraintOffsetEnd)+ {+ next_constraint = reinterpret_cast<ContactConstraintBase *>(mConstraints + *next_constraint_offset);+ PrefetchL1(next_constraint);}- }+ else+ next_constraint = nullptr;- return any_impulse_applied;+ // Dispatch to the correct templated form+ table[(int)constraint.mBody1->GetMotionType()][(int)constraint.mBody2->GetMotionType()](constraint, *mWriteCache);+ }}-void ContactConstraintManager::StoreAppliedImpulses(const uint32 *inConstraintIdxBegin, const uint32 *inConstraintIdxEnd) const+template <EMotionType Type1, EMotionType Type2>+bool ContactConstraintManager::sSolvePositionConstraint(ContactConstraintBase &ioConstraint, Body &ioBody1, Body &ioBody2, const PhysicsSettings &inSettings, const ManifoldCache &inManifoldCache){- // Copy back total applied impulse to cache for the next frame- for (const uint32 *constraint_idx = inConstraintIdxBegin; constraint_idx < inConstraintIdxEnd; ++constraint_idx)+ ContactConstraint<Type1, Type2> &constraint = static_cast<ContactConstraint<Type1, Type2> &>(ioConstraint);+ const CachedManifold &cached_manifold = inManifoldCache.FromHandle(constraint.mCachedManifoldHandle)->GetValue();++ // Get transforms+ RMat44 transform1 = ioBody1.GetCenterOfMassTransform();+ RMat44 transform2 = ioBody2.GetCenterOfMassTransform();++ Vec3 ws_normal = constraint.GetWorldSpaceNormal();++ bool any_impulse_applied = false;++ for (uint32 i = 0; i < constraint.mNumContactPoints; ++i){- const ContactConstraint &constraint = mConstraints[*constraint_idx];+ WorldContactPoint<Type1, Type2> &wcp = constraint.mContactPoints[i];+ const CachedContactPoint &ccp = cached_manifold.mContactPoints[i];++ // Calculate new contact point positions in world space (the bodies may have moved)+ RVec3 p1 = transform1 * Vec3::sLoadFloat3Unsafe(ccp.mPosition1);+ RVec3 p2 = transform2 * Vec3::sLoadFloat3Unsafe(ccp.mPosition2);- for (const WorldContactPoint &wcp : constraint.mContactPoints)+ // Calculate separation along the normal (negative if interpenetrating)+ // Allow a little penetration by default (PhysicsSettings::mPenetrationSlop) to avoid jittering between contact/no-contact which wipes out the contact cache and warm start impulses+ // Clamp penetration to a max PhysicsSettings::mMaxPenetrationDistance so that we don't apply a huge impulse if we're penetrating a lot+ float separation = max(Vec3(p2 - p1).Dot(ws_normal) + inSettings.mPenetrationSlop, -inSettings.mMaxPenetrationDistance);++ // Only enforce constraint when separation < 0 (otherwise we're apart)+ if (separation < 0.0f){- wcp.mContactPoint->mNonPenetrationLambda = wcp.mNonPenetrationConstraint.GetTotalLambda();- wcp.mContactPoint->mFrictionLambda[0] = wcp.mFrictionConstraint1.GetTotalLambda();- wcp.mContactPoint->mFrictionLambda[1] = wcp.mFrictionConstraint2.GetTotalLambda();+ // Calculate scaled inertia+ Mat44 inv_i1;+ if constexpr (Type1 == EMotionType::Dynamic)+ inv_i1 = constraint.mInvInertiaScale1 * ioBody1.GetInverseInertia();+ else+ inv_i1 = Mat44::sZero();++ Mat44 inv_i2;+ if constexpr (Type2 == EMotionType::Dynamic)+ inv_i2 = constraint.mInvInertiaScale2 * ioBody2.GetInverseInertia();+ else+ inv_i2 = Mat44::sZero();++ // Calculate collision points relative to body+ RVec3 p = 0.5_r * (p1 + p2);+ Vec3 r1 = Vec3(p - ioBody1.GetCenterOfMassPosition());+ Vec3 r2 = Vec3(p - ioBody2.GetCenterOfMassPosition());++ // Update constraint properties (bodies may have moved)+ wcp.mNonPenetrationConstraint.CalculateConstraintProperties(constraint.mInvMass1, inv_i1, r1, constraint.mInvMass2, inv_i2, r2, ws_normal);++ // Solve position errors+ if (wcp.mNonPenetrationConstraint.SolvePositionConstraint(ioBody1, constraint.mInvMass1, ioBody2, constraint.mInvMass2, ws_normal, separation, inSettings.mBaumgarte))+ any_impulse_applied = true;}}++ return any_impulse_applied;}-bool ContactConstraintManager::SolvePositionConstraints(const uint32 *inConstraintIdxBegin, const uint32 *inConstraintIdxEnd)+bool ContactConstraintManager::SolvePositionConstraints(const uint32 *inConstraintOffsetBegin, const uint32 *inConstraintOffsetEnd){JPH_PROFILE_FUNCTION();+ // Build dispatch table+ using DispatchFunc = bool (*)(ContactConstraintBase &, Body &, Body &, const PhysicsSettings &, const ManifoldCache &);+ static const DispatchFunc table[3][3] = {+ {+ nullptr, // Static vs static doesn't exist+ nullptr, // Static vs kinematic doesn't exist+ sSolvePositionConstraint<EMotionType::Static, EMotionType::Dynamic>+ },+ {+ nullptr, // Kinematic vs static doesn't exist+ nullptr, // Kinematic vs kinematic doesn't exist+ sSolvePositionConstraint<EMotionType::Kinematic, EMotionType::Dynamic>+ },+ {+ sSolvePositionConstraint<EMotionType::Dynamic, EMotionType::Static>,+ sSolvePositionConstraint<EMotionType::Dynamic, EMotionType::Kinematic>,+ sSolvePositionConstraint<EMotionType::Dynamic, EMotionType::Dynamic>+ }+ };++ if (inConstraintOffsetBegin >= inConstraintOffsetEnd)+ return false;+bool any_impulse_applied = false;- for (const uint32 *constraint_idx = inConstraintIdxBegin; constraint_idx < inConstraintIdxEnd; ++constraint_idx)+ ContactConstraintBase *next_constraint = reinterpret_cast<ContactConstraintBase *>(mConstraints + *inConstraintOffsetBegin);+ for (const uint32 *next_constraint_offset = inConstraintOffsetBegin + 1; next_constraint != nullptr; ++next_constraint_offset){- ContactConstraint &constraint = mConstraints[*constraint_idx];+ ContactConstraintBase &constraint = *next_constraint;+ if (next_constraint_offset < inConstraintOffsetEnd)+ {+ next_constraint = reinterpret_cast<ContactConstraintBase *>(mConstraints + *next_constraint_offset);+ PrefetchL1(next_constraint);+ }+ else+ next_constraint = nullptr;// Fetch bodiesBody &body1 = *constraint.mBody1;Body &body2 = *constraint.mBody2;- // Get transforms- RMat44 transform1 = body1.GetCenterOfMassTransform();- RMat44 transform2 = body2.GetCenterOfMassTransform();-- Vec3 ws_normal = constraint.GetWorldSpaceNormal();-- for (WorldContactPoint &wcp : constraint.mContactPoints)- {- // Calculate new contact point positions in world space (the bodies may have moved)- RVec3 p1 = transform1 * Vec3::sLoadFloat3Unsafe(wcp.mContactPoint->mPosition1);- RVec3 p2 = transform2 * Vec3::sLoadFloat3Unsafe(wcp.mContactPoint->mPosition2);-- // Calculate separation along the normal (negative if interpenetrating)- // Allow a little penetration by default (PhysicsSettings::mPenetrationSlop) to avoid jittering between contact/no-contact which wipes out the contact cache and warm start impulses- // Clamp penetration to a max PhysicsSettings::mMaxPenetrationDistance so that we don't apply a huge impulse if we're penetrating a lot- float separation = max(Vec3(p2 - p1).Dot(ws_normal) + mPhysicsSettings.mPenetrationSlop, -mPhysicsSettings.mMaxPenetrationDistance);-- // Only enforce constraint when separation < 0 (otherwise we're apart)- if (separation < 0.0f)- {- // Update constraint properties (bodies may have moved)- wcp.CalculateNonPenetrationConstraintProperties(body1, constraint.mInvMass1, constraint.mInvInertiaScale1, body2, constraint.mInvMass2, constraint.mInvInertiaScale2, p1, p2, ws_normal);-- // Solve position errors- if (wcp.mNonPenetrationConstraint.SolvePositionConstraintWithMassOverride(body1, constraint.mInvMass1, body2, constraint.mInvMass2, ws_normal, separation, mPhysicsSettings.mBaumgarte))- any_impulse_applied = true;- }- }+ // Dispatch to the correct templated form+ any_impulse_applied |= table[(int)body1.GetMotionType()][(int)body2.GetMotionType()](constraint, body1, body2, mPhysicsSettings, *mWriteCache);}return any_impulse_applied;@@ -1776,18 +1993,26 @@ bool ContactConstraintManager::SolvePositionConstraints(const uint32 *inConstraivoid ContactConstraintManager::RecycleConstraintBuffer(){// Reset constraint array- mNumConstraints = 0;+ mNumConstraintsAndNextConstraintOffset = 0;++ // Store read / write cache+ mReadCache = &mCache[mCacheWriteIdx ^ 1];+ mWriteCache = &mCache[mCacheWriteIdx];}void ContactConstraintManager::FinishConstraintBuffer(){// Free constraints buffer- mUpdateContext->mTempAllocator->Free(mConstraints, mMaxConstraints * sizeof(ContactConstraint));+ mUpdateContext->mTempAllocator->Free(mConstraintIdxToOffset, mMaxConstraints * sizeof(uint32));+ mConstraintIdxToOffset = nullptr;+ mUpdateContext->mTempAllocator->Free(mConstraints, mMaxConstraints * cMaxConstraintSize);mConstraints = nullptr;- mNumConstraints = 0;+ mNumConstraintsAndNextConstraintOffset = 0;// Reset update contextmUpdateContext = nullptr;+ mReadCache = nullptr;+ mWriteCache = nullptr;}void ContactConstraintManager::SaveState(StateRecorder &inStream, const StateRecorderFilter *inFilter) constdiff --git a/thirdparty/jolt_physics/Jolt/Physics/Constraints/ContactConstraintManager.h b/thirdparty/jolt_physics/Jolt/Physics/Constraints/ContactConstraintManager.hindex dfe5fc8c381..d76f3fc38a6 100644--- a/thirdparty/jolt_physics/Jolt/Physics/Constraints/ContactConstraintManager.h+++ b/thirdparty/jolt_physics/Jolt/Physics/Constraints/ContactConstraintManager.h@@ -10,10 +10,12 @@#include <Jolt/Physics/Body/BodyPair.h>#include <Jolt/Physics/Collision/Shape/SubShapeIDPair.h>#include <Jolt/Physics/Collision/ManifoldBetweenTwoFaces.h>-#include <Jolt/Physics/Constraints/ConstraintPart/AxisConstraintPart.h>-#include <Jolt/Physics/Constraints/ConstraintPart/DualAxisConstraintPart.h>+#include <Jolt/Physics/Constraints/ConstraintPart/ContactConstraintPart.h>+#include <Jolt/Physics/Constraints/ConstraintPart/AngularFrictionConstraintPart.h>+#include <Jolt/Physics/StateRecorder.h>#include <Jolt/Core/HashCombine.h>#include <Jolt/Core/NonCopyable.h>+#include <Jolt/Math/Vector.h>JPH_SUPPRESS_WARNINGS_STD_BEGIN#include <atomic>@@ -94,8 +96,7 @@ public:/// Check if the contact points from the previous frame are reusable and if so copy them./// When the cache was usable and the pair has been handled: outPairHandled = true.- /// When a contact constraint was produced: outConstraintCreated = true.- void GetContactsFromCache(ContactAllocator &ioContactAllocator, Body &inBody1, Body &inBody2, bool &outPairHandled, bool &outConstraintCreated);+ void GetContactsFromCache(ContactAllocator &ioContactAllocator, Body &inBody1, Body &inBody2, bool &outPairHandled);/// Handle used to keep track of the current body pairusing BodyPairHandle = void *;@@ -107,11 +108,11 @@ public:/// Add a contact constraint for this frame.////// @param ioContactAllocator The allocator that reserves memory for the contacts+ /// @param ioActivateAndLinkBodies When true, this function attempts to activate and link the bodies and then sets ioActivateAndLinkBodies to false so that it only happens once/// @param inBodyPair The handle for the contact cache for this body pair/// @param inBody1 The first body that is colliding/// @param inBody2 The second body that is colliding/// @param inManifold The manifold that describes the collision- /// @return true if a contact constraint was created (can be false in the case of a sensor)////// This is using the approach described in 'Modeling and Solving Constraints' by Erin Catto presented at GDC 2009 (and later years with slight modifications)./// We're using the formulas from slide 50 - 53 combined.@@ -145,7 +146,7 @@ public:/// r1, r2 = contact point relative to center of mass of body 1 and body 2 (r1 = p1 - x1, r2 = p2 - x2)./// v1, v2 = (linear velocity, angular velocity): 6 vectors containing linear and angular velocity for body 1 and 2./// M = mass matrix, a diagonal matrix of the mass and inertia with diagonal [m1, I1, m2, I2].- bool AddContactConstraint(ContactAllocator &ioContactAllocator, BodyPairHandle inBodyPair, Body &inBody1, Body &inBody2, const ContactManifold &inManifold);+ void AddContactConstraint(ContactAllocator &ioContactAllocator, bool &ioActivateAndLinkBodies, BodyPairHandle inBodyPair, Body &inBody1, Body &inBody2, const ContactManifold &inManifold);/// Finalizes the contact cache, the contact cache that was generated during the calls to AddContactConstraint in this update/// will be used from now on to read from. After finalizing the contact cache, the contact removed callbacks will be called.@@ -158,22 +159,25 @@ public:bool WereBodiesInContact(const BodyID &inBody1ID, const BodyID &inBody2ID) const;/// Get the number of contact constraints that were found- uint32 GetNumConstraints() const { return min<uint32>(mNumConstraints, mMaxConstraints); }+ uint32 GetNumConstraints() const { return min<uint32>(uint32(mNumConstraintsAndNextConstraintOffset.load(memory_order_relaxed)), mMaxConstraints); }++ /// Update constraint indices to constraint offsets+ void ConstraintIdxToConstraintOffset(uint32 *ioConstraintIdxBegin, const uint32 *inConstraintIdxEnd) const;/// Sort contact constraints deterministically- void SortContacts(uint32 *inConstraintIdxBegin, uint32 *inConstraintIdxEnd) const;+ void SortContacts(uint32 *ioConstraintOffsetBegin, uint32 *inConstraintOffsetEnd) const;/// Get the affected bodies for a given constraint- inline void GetAffectedBodies(uint32 inConstraintIdx, const Body *&outBody1, const Body *&outBody2) const+ inline void GetAffectedBodies(uint32 inConstraintOffset, const Body *&outBody1, const Body *&outBody2) const{- const ContactConstraint &constraint = mConstraints[inConstraintIdx];+ const ContactConstraintBase &constraint = *reinterpret_cast<const ContactConstraintBase *>(mConstraints + inConstraintOffset);outBody1 = constraint.mBody1;outBody2 = constraint.mBody2;}/// Apply last frame's impulses as an initial guess for this frame's impulsestemplate <class MotionPropertiesCallback>- void WarmStartVelocityConstraints(const uint32 *inConstraintIdxBegin, const uint32 *inConstraintIdxEnd, float inWarmStartImpulseRatio, MotionPropertiesCallback &ioCallback);+ void WarmStartVelocityConstraints(const uint32 *inConstraintOffsetBegin, const uint32 *inConstraintOffsetEnd, float inWarmStartImpulseRatio, MotionPropertiesCallback &ioCallback);/// Solve velocity constraints, when almost nothing changes this should only apply very small impulses/// since we're warm starting with the total impulse applied in the last frame above.@@ -205,10 +209,10 @@ public:/// e = the restitution coefficient, v_n^- is the normal velocity prior to the collision////// Restitution is only applied when v_n^- is large enough and the points are moving towards collision- bool SolveVelocityConstraints(const uint32 *inConstraintIdxBegin, const uint32 *inConstraintIdxEnd);+ bool SolveVelocityConstraints(const uint32 *inConstraintOffsetBegin, const uint32 *inConstraintOffsetEnd);/// Save back the lambdas to the contact cache for the next warm start- void StoreAppliedImpulses(const uint32 *inConstraintIdxBegin, const uint32 *inConstraintIdxEnd) const;+ void StoreAppliedImpulses(const uint32 *inConstraintOffsetBegin, const uint32 *inConstraintOffsetEnd) const;/// Solve position constraints./// This is using the approach described in 'Modeling and Solving Constraints' by Erin Catto presented at GDC 2007.@@ -226,7 +230,7 @@ public:////// beta = baumgarte stabilization factor./// dt = delta time.- bool SolvePositionConstraints(const uint32 *inConstraintIdxBegin, const uint32 *inConstraintIdxEnd);+ bool SolvePositionConstraints(const uint32 *inConstraintOffsetBegin, const uint32 *inConstraintOffsetEnd);/// Recycle the constraint buffer. Should be called between collision simulation steps.void RecycleConstraintBuffer();@@ -272,10 +276,9 @@ private:/// Total applied impulse during the last update that it was usedfloat mNonPenetrationLambda;- Vector<2> mFrictionLambda;};- static_assert(sizeof(CachedContactPoint) == 36, "Unexpected size");+ static_assert(sizeof(CachedContactPoint) == 28, "Unexpected size");static_assert(alignof(CachedContactPoint) == 4, "Assuming 4 byte aligned");/// A single cached manifold@@ -283,10 +286,10 @@ private:{public:/// Calculate size in bytes needed beyond the size of the class to store inNumContactPoints- static int sGetRequiredExtraSize(int inNumContactPoints) { return max(0, inNumContactPoints - 1) * sizeof(CachedContactPoint); }+ static constexpr int sGetRequiredExtraSize(int inNumContactPoints) { return max(0, inNumContactPoints - 1) * sizeof(CachedContactPoint); }/// Calculate total class size needed for storing inNumContactPoints- static int sGetRequiredTotalSize(int inNumContactPoints) { return sizeof(CachedManifold) + sGetRequiredExtraSize(inNumContactPoints); }+ static constexpr int sGetRequiredTotalSize(int inNumContactPoints) { return sizeof(CachedManifold) + sGetRequiredExtraSize(inNumContactPoints); }/// Saving / restoring state for replayvoid SaveState(StateRecorder &inStream) const;@@ -299,6 +302,10 @@ private:/// Note: this value is read through sLoadFloat3Unsafe.Float3 mContactNormal;+ /// Total applied impulse during the last update that it was used+ Vector<2> mFrictionLambda;+ float mAngularFrictionLambda;+/// Flags for this cached manifoldenum class EFlags : uint16{@@ -316,7 +323,7 @@ private:CachedContactPoint mContactPoints[1];};- static_assert(sizeof(CachedManifold) == 56, "This structure is expect to not contain any waste due to alignment");+ static_assert(sizeof(CachedManifold) == 60, "This structure is expect to not contain any waste due to alignment");static_assert(alignof(CachedManifold) == 4, "Assuming 4 byte aligned");/// Define a map that maps SubShapeIDPair -> manifold@@ -374,6 +381,7 @@ private:MKVAndCreated FindOrCreate(ContactAllocator &ioContactAllocator, const SubShapeIDPair &inKey, uint64 inKeyHash, int inNumContactPoints);uint32 ToHandle(const MKeyValue *inKeyValue) const;const MKeyValue * FromHandle(uint32 inHandle) const;+ MKeyValue * FromHandle(uint32 inHandle);/// Find / create entry for BodyPair -> CachedBodyPairconst BPKeyValue * Find(const BodyPair &inKey, uint64 inKeyHash) const;@@ -418,37 +426,30 @@ private:ManifoldCache mCache[2]; ///< We have one cache to read from and one to write toint mCacheWriteIdx = 0; ///< Which cache we're currently writing to+ ManifoldCache * mReadCache = nullptr; ///< The cache we're currently reading from (fixed at the start of the step so that it remains even after we swap mCacheWriteIdx in FinalizeContactCacheAndCallContactPointRemovedCallbacks, valid only during stepping)+ ManifoldCache * mWriteCache = nullptr; ///< The cache we're currently writing to (fixed at the start of the step so that it remains even after we swap mCacheWriteIdx in FinalizeContactCacheAndCallContactPointRemovedCallbacks, valid only during stepping)/// World space contact point, used for solving penetrations+ template <EMotionType Type1, EMotionType Type2>class WorldContactPoint{public:- /// Calculate constraint properties below- void CalculateNonPenetrationConstraintProperties(const Body &inBody1, float inInvMass1, float inInvInertiaScale1, const Body &inBody2, float inInvMass2, float inInvInertiaScale2, RVec3Arg inWorldSpacePosition1, RVec3Arg inWorldSpacePosition2, Vec3Arg inWorldSpaceNormal);+ using ConstraintPart = ContactConstraintPart<Type1, Type2>;- template <EMotionType Type1, EMotionType Type2>- JPH_INLINE void TemplatedCalculateFrictionAndNonPenetrationConstraintProperties(float inDeltaTime, Vec3Arg inGravity, const Body &inBody1, const Body &inBody2, float inInvM1, float inInvM2, Mat44Arg inInvI1, Mat44Arg inInvI2, RVec3Arg inWorldSpacePosition1, RVec3Arg inWorldSpacePosition2, Vec3Arg inWorldSpaceNormal, Vec3Arg inWorldSpaceTangent1, Vec3Arg inWorldSpaceTangent2, const ContactSettings &inSettings, float inMinVelocityForRestitution);+ /// Calculate constraint properties for the non penetration constraint+ JPH_INLINE void CalculateNonPenetrationConstraintProperties(float inDeltaTime, Vec3Arg inGravity, const Body &inBody1, const Body &inBody2, float inInvM1, float inInvM2, Mat44Arg inInvI1, Mat44Arg inInvI2, RVec3Arg inWorldSpacePosition1, RVec3Arg inWorldSpacePosition2, Vec3Arg inWorldSpaceNormal, const ContactSettings &inSettings, float inMinVelocityForRestitution);/// The constraint parts- AxisConstraintPart mNonPenetrationConstraint;- AxisConstraintPart mFrictionConstraint1;- AxisConstraintPart mFrictionConstraint2;+ ConstraintPart mNonPenetrationConstraint;+ // Note that this needs to be followed by data of size float, see comment at ContactConstraintPart- /// Contact cache- CachedContactPoint * mContactPoint;+ /// Distance between the friction center and this contact point+ float mDistanceToFrictionCenter;};- using WorldContactPoints = StaticArray<WorldContactPoint, MaxContactPoints>;-- /// Contact constraint class, used for solving penetrations- class ContactConstraint+ class ContactConstraintBase{public:- #ifdef JPH_DEBUG_RENDERER- /// Draw the state of the contact constraint- void Draw(DebugRenderer *inRenderer, ColorArg inManifoldColor) const;- #endif // JPH_DEBUG_RENDERER-/// Convert the world space normal to a Vec3JPH_INLINE Vec3 GetWorldSpaceNormal() const{@@ -472,35 +473,76 @@ private:float mInvInertiaScale1;float mInvMass2;float mInvInertiaScale2;- WorldContactPoints mContactPoints;+ uint32 mCachedManifoldHandle;+ uint32 mNumContactPoints;+ };++ /// Contact constraint class, used for solving penetrations+ template <EMotionType Type1, EMotionType Type2>+ class ContactConstraint : public ContactConstraintBase+ {+ public:+ /// Calculate constraint properties for the friction constraint+ JPH_INLINE void CalculateFrictionConstraintProperties(const Body &inBody1, const Body &inBody2, float inInvM1, float inInvM2, Mat44Arg inInvI1, Mat44Arg inInvI2, const RVec3 *inWorldSpaceContacts, Vec3Arg inWorldSpaceNormal, Vec3Arg inWorldSpaceTangent1, Vec3Arg inWorldSpaceTangent2, const ContactSettings &inSettings);++ #ifdef JPH_DEBUG_RENDERER+ /// Draw the state of the contact constraint+ void Draw(DebugRenderer *inRenderer, const ManifoldCache &inManifoldCache, ColorArg inManifoldColor) const;+ #endif // JPH_DEBUG_RENDERER++ ContactConstraintPart<Type1, Type2> mFrictionConstraint1;+ ContactConstraintPart<Type1, Type2> mFrictionConstraint2;+ AngularFrictionConstraintPart<Type1, Type2> mAngularFrictionConstraint;++ WorldContactPoint<Type1, Type2> mContactPoints[1];};public:+ /// Maximum size a single constraint can take+ static constexpr uint32 cMaxConstraintSize = sizeof(ContactConstraint<EMotionType::Dynamic, EMotionType::Dynamic>) + (MaxContactPoints - 1) * sizeof(WorldContactPoint<EMotionType::Dynamic, EMotionType::Dynamic>);+/// The maximum value that can be passed to Init for inMaxContactConstraints. Note you should really use a lower value, using this value will cost a lot of memory!- static constexpr uint cMaxContactConstraintsLimit = ~uint(0) / sizeof(ContactConstraint);+ static constexpr uint cMaxContactConstraintsLimit = ~uint(0) / cMaxConstraintSize;/// The maximum value that can be passed to Init for inMaxBodyPairs. Note you should really use a lower value, using this value will cost a lot of memory!static constexpr uint cMaxBodyPairsLimit = ~uint(0) / sizeof(BodyPairMap::KeyValue);private:- /// Internal helper function to calculate the friction and non-penetration constraint properties. Templated to the motion type to reduce the amount of branches and calculations.+ /// Create a new contact constrainttemplate <EMotionType Type1, EMotionType Type2>- JPH_INLINE void TemplatedCalculateFrictionAndNonPenetrationConstraintProperties(ContactConstraint &ioConstraint, const ContactSettings &inSettings, float inDeltaTime, Vec3Arg inGravity, RMat44Arg inTransformBody1, RMat44Arg inTransformBody2, const Body &inBody1, const Body &inBody2);+ JPH_INLINE ContactConstraint<Type1, Type2> *CreateConstraint(bool &ioActivateAndLinkBodies, Body &inBody1, Body &inBody2, uint64 inSortKey, uint32 inCachedManifoldHandle, Vec3Arg inWorldSpaceNormal, const ContactSettings &inSettings, uint32 inNumContactPoints);- /// Internal helper function to calculate the friction and non-penetration constraint properties.- inline void CalculateFrictionAndNonPenetrationConstraintProperties(ContactConstraint &ioConstraint, const ContactSettings &inSettings, float inDeltaTime, Vec3Arg inGravity, RMat44Arg inTransformBody1, RMat44Arg inTransformBody2, const Body &inBody1, const Body &inBody2);+ /// Internal helper function to add a contact constraint from the cache. Templated to the motion type to reduce the amount of branches and calculations.+ template <EMotionType Type1, EMotionType Type2>+ void TemplatedGetContactsFromCache(ContactAllocator &ioContactAllocator, Body &inBody1, Body &inBody2, const CachedBodyPair &inCachedBodyPair, CachedBodyPair &outCachedBodyPair);/// Internal helper function to add a contact constraint. Templated to the motion type to reduce the amount of branches and calculations.template <EMotionType Type1, EMotionType Type2>- bool TemplatedAddContactConstraint(ContactAllocator &ioContactAllocator, BodyPairHandle inBodyPairHandle, Body &inBody1, Body &inBody2, const ContactManifold &inManifold);+ void TemplatedAddContactConstraint(ContactAllocator &ioContactAllocator, bool &ioActivateAndLinkBodies, BodyPairHandle inBodyPairHandle, Body &inBody1, Body &inBody2, const ContactManifold &inManifold);++ /// Read the velocities from the motion properties+ template <EMotionType Type1, EMotionType Type2>+ static JPH_INLINE void sGetVelocities(const MotionProperties *inMotionProperties1, const MotionProperties *inMotionProperties2, Vec3 &outLinearVelocity1, Vec3 &outAngularVelocity1, Vec3 &outLinearVelocity2, Vec3 &outAngularVelocity2);++ /// Apply changed velocities to the motion properties+ template <EMotionType Type1, EMotionType Type2>+ static JPH_INLINE void sSetVelocities(MotionProperties *ioMotionProperties1, MotionProperties *ioMotionProperties2, Vec3Arg inLinearVelocity1, Vec3Arg inAngularVelocity1, Vec3Arg inLinearVelocity2, Vec3Arg inAngularVelocity2);/// Internal helper function to warm start contact constraint. Templated to the motion type to reduce the amount of branches and calculations.template <EMotionType Type1, EMotionType Type2>- JPH_INLINE static void sWarmStartConstraint(ContactConstraint &ioConstraint, MotionProperties *ioMotionProperties1, MotionProperties *ioMotionProperties2, float inWarmStartImpulseRatio);+ static void sWarmStartConstraint(ContactConstraintBase &ioConstraint, MotionProperties *ioMotionProperties1, MotionProperties *ioMotionProperties2, float inWarmStartImpulseRatio);++ /// Internal helper function to solve a single velocity constraint. Templated to the motion type to reduce the amount of branches and calculations.+ template <EMotionType Type1, EMotionType Type2>+ static bool sSolveVelocityConstraint(ContactConstraintBase &ioConstraint, MotionProperties *ioMotionProperties1, MotionProperties *ioMotionProperties2);++ /// Internal helper function to store lambdas applied during sSolveVelocityConstraint.+ template <EMotionType Type1, EMotionType Type2>+ static void sStoreAppliedImpulses(ContactConstraintBase &ioConstraint, ManifoldCache &inManifoldCache);- /// Internal helper function to solve a single contact constraint. Templated to the motion type to reduce the amount of branches and calculations.+ /// Internal helper function to solve a single position constraint. Templated to the motion type to reduce the amount of branches and calculations.template <EMotionType Type1, EMotionType Type2>- JPH_INLINE static bool sSolveVelocityConstraint(ContactConstraint &ioConstraint, MotionProperties *ioMotionProperties1, MotionProperties *ioMotionProperties2);+ static bool sSolvePositionConstraint(ContactConstraintBase &ioConstraint, Body &ioBody1, Body &ioBody2, const PhysicsSettings &inSettings, const ManifoldCache &inManifoldCache);/// The main physics settings instanceconst PhysicsSettings & mPhysicsSettings;@@ -509,13 +551,14 @@ private:ContactListener * mContactListener = nullptr;/// Functions that are used to combine friction and restitution of 2 bodies- CombineFunction mCombineFriction = [](const Body &inBody1, const SubShapeID &, const Body &inBody2, const SubShapeID &) { return sqrt(inBody1.GetFriction() * inBody2.GetFriction()); };+ CombineFunction mCombineFriction = [](const Body &inBody1, const SubShapeID &, const Body &inBody2, const SubShapeID &) { return Sqrt(inBody1.GetFriction() * inBody2.GetFriction()); };CombineFunction mCombineRestitution = [](const Body &inBody1, const SubShapeID &, const Body &inBody2, const SubShapeID &) { return max(inBody1.GetRestitution(), inBody2.GetRestitution()); };/// The constraints that were added this frame- ContactConstraint * mConstraints = nullptr;+ uint8 * mConstraints = nullptr; ///< Cast to ContactConstraint<MotionType1, MotionType2> depending on the motion types of the bodies in the constraint+ uint32 * mConstraintIdxToOffset = nullptr; ///< Maps from constraint index to offset in mConstraintsuint32 mMaxConstraints = 0;- atomic<uint32> mNumConstraints { 0 };+ atomic<uint64> mNumConstraintsAndNextConstraintOffset { 0 }; // Lower 32 bits: number of constraints, upper 32 bits next constraint offset/// Context used for this physics updatePhysicsUpdateContext * mUpdateContext;diff --git a/thirdparty/jolt_physics/Jolt/Physics/Constraints/DistanceConstraint.cpp b/thirdparty/jolt_physics/Jolt/Physics/Constraints/DistanceConstraint.cppindex e70bfb24ced..fee8aed865f 100644--- a/thirdparty/jolt_physics/Jolt/Physics/Constraints/DistanceConstraint.cpp+++ b/thirdparty/jolt_physics/Jolt/Physics/Constraints/DistanceConstraint.cpp@@ -130,7 +130,7 @@ void DistanceConstraint::CalculateConstraintProperties(float inDeltaTime)if (mMinDistance == mMaxDistance){- mAxisConstraint.CalculateConstraintPropertiesWithSettings(inDeltaTime, *mBody1, r1_plus_u, *mBody2, r2, mWorldSpaceNormal, 0.0f, delta_len - mMinDistance, mLimitsSpringSettings);+ mAxisConstraint.CalculateConstraintPropertiesWithSettingsForLimit(inDeltaTime, *mBody1, r1_plus_u, *mBody2, r2, mWorldSpaceNormal, 0.0f, delta_len - mMinDistance, mLimitsSpringSettings);// Single distance, allow constraint forces in both directionsmMinLambda = -FLT_MAX;@@ -138,7 +138,7 @@ void DistanceConstraint::CalculateConstraintProperties(float inDeltaTime)}else if (delta_len <= mMinDistance){- mAxisConstraint.CalculateConstraintPropertiesWithSettings(inDeltaTime, *mBody1, r1_plus_u, *mBody2, r2, mWorldSpaceNormal, 0.0f, delta_len - mMinDistance, mLimitsSpringSettings);+ mAxisConstraint.CalculateConstraintPropertiesWithSettingsForLimit(inDeltaTime, *mBody1, r1_plus_u, *mBody2, r2, mWorldSpaceNormal, 0.0f, delta_len - mMinDistance, mLimitsSpringSettings);// Allow constraint forces to make distance bigger onlymMinLambda = 0;@@ -146,7 +146,7 @@ void DistanceConstraint::CalculateConstraintProperties(float inDeltaTime)}else if (delta_len >= mMaxDistance){- mAxisConstraint.CalculateConstraintPropertiesWithSettings(inDeltaTime, *mBody1, r1_plus_u, *mBody2, r2, mWorldSpaceNormal, 0.0f, delta_len - mMaxDistance, mLimitsSpringSettings);+ mAxisConstraint.CalculateConstraintPropertiesWithSettingsForLimit(inDeltaTime, *mBody1, r1_plus_u, *mBody2, r2, mWorldSpaceNormal, 0.0f, delta_len - mMaxDistance, mLimitsSpringSettings);// Allow constraint forces to make distance smaller onlymMinLambda = -FLT_MAX;diff --git a/thirdparty/jolt_physics/Jolt/Physics/Constraints/HingeConstraint.cpp b/thirdparty/jolt_physics/Jolt/Physics/Constraints/HingeConstraint.cppindex 86bc828eab3..9977c7e99f7 100644--- a/thirdparty/jolt_physics/Jolt/Physics/Constraints/HingeConstraint.cpp+++ b/thirdparty/jolt_physics/Jolt/Physics/Constraints/HingeConstraint.cpp@@ -197,7 +197,7 @@ void HingeConstraint::CalculateRotationLimitsConstraintProperties(float inDeltaT{// Apply constraint if outside of limitsif (mHasLimits && (mTheta <= mLimitsMin || mTheta >= mLimitsMax))- mRotationLimitsConstraintPart.CalculateConstraintPropertiesWithSettings(inDeltaTime, *mBody1, *mBody2, mA1, 0.0f, GetSmallestAngleToLimit(), mLimitsSpringSettings);+ mRotationLimitsConstraintPart.CalculateConstraintPropertiesWithSettingsForLimit(inDeltaTime, *mBody1, *mBody2, mA1, 0.0f, GetSmallestAngleToLimit(), mLimitsSpringSettings);elsemRotationLimitsConstraintPart.Deactivate();}@@ -219,7 +219,14 @@ void HingeConstraint::CalculateMotorConstraintProperties(float inDeltaTime)case EMotorState::Position:if (mMotorSettings.mSpringSettings.HasStiffness())- mMotorConstraintPart.CalculateConstraintPropertiesWithSettings(inDeltaTime, *mBody1, *mBody2, mA1, 0.0f, CenterAngleAroundZero(mTheta - mTargetAngle), mMotorSettings.mSpringSettings);+ mMotorConstraintPart.CalculateConstraintPropertiesWithSettingsForMotor(inDeltaTime, *mBody1, *mBody2, mA1, 0.0f, CenterAngleAroundZero(mTheta - mTargetAngle), mMotorSettings.mSpringSettings);+ else+ mMotorConstraintPart.Deactivate();+ break;++ case EMotorState::PositionAndVelocity:+ if (mMotorSettings.mSpringSettings.HasStiffnessOrDamping())+ mMotorConstraintPart.CalculateConstraintPropertiesWithSettingsForMotor(inDeltaTime, *mBody1, *mBody2, mA1, -mTargetAngularVelocity, CenterAngleAroundZero(mTheta - mTargetAngle), mMotorSettings.mSpringSettings);elsemMotorConstraintPart.Deactivate();break;@@ -286,6 +293,7 @@ bool HingeConstraint::SolveVelocityConstraint(float inDeltaTime)case EMotorState::Velocity:case EMotorState::Position:+ case EMotorState::PositionAndVelocity:motor = mMotorConstraintPart.SolveVelocityConstraint(*mBody1, *mBody2, mA1, inDeltaTime * mMotorSettings.mMinTorqueLimit, inDeltaTime * mMotorSettings.mMaxTorqueLimit);break;}diff --git a/thirdparty/jolt_physics/Jolt/Physics/Constraints/HingeConstraint.h b/thirdparty/jolt_physics/Jolt/Physics/Constraints/HingeConstraint.hindex 398ccc1a062..d1fa63bc59b 100644--- a/thirdparty/jolt_physics/Jolt/Physics/Constraints/HingeConstraint.h+++ b/thirdparty/jolt_physics/Jolt/Physics/Constraints/HingeConstraint.h@@ -124,7 +124,7 @@ public:float GetTargetAngle() const { return mTargetAngle; }/// Set the target orientation in body space (R2 = R1 * inOrientation, where R1 and R2 are the world space rotations for body 1 and 2).- /// Calculates the local space target angle and calls SetTargetAngle. Motor state must be EMotorState::Position for this to have any effect.+ /// Calculates the local space target angle and calls SetTargetAngle. Motor state must be EMotorState::Position or EMotorState::PositionAndVelocity for this to have any effect./// May set the wrong angle if inOrientation contains large rotations around other axis than the hinge axis.void SetTargetOrientationBS(QuatArg inOrientation);diff --git a/thirdparty/jolt_physics/Jolt/Physics/Constraints/MotorSettings.h b/thirdparty/jolt_physics/Jolt/Physics/Constraints/MotorSettings.hindex 601fa3dc3f9..43940ff6cd7 100644--- a/thirdparty/jolt_physics/Jolt/Physics/Constraints/MotorSettings.h+++ b/thirdparty/jolt_physics/Jolt/Physics/Constraints/MotorSettings.h@@ -16,10 +16,24 @@ class StreamOut;enum class EMotorState{Off, ///< Motor is off- Velocity, ///< Motor will drive to target velocity- Position ///< Motor will drive to target position+ Velocity, ///< Motor will drive to target velocity limited only by max force/torque that the motor can apply+ Position, ///< Motor will drive to target position using: force = stiffness * (target_position - current_position) - damping * current_velocity+ PositionAndVelocity, ///< Motor will drive both to target position and velocity using: force = stiffness * (target_position - current_position) + damping * (target_velocity - current_velocity)};+// Ability to check if position/velocity is enabled for a motor state+constexpr bool IsVelocityMotor(EMotorState inMotorState) { return (int(inMotorState) & int(EMotorState::Velocity)) != 0; }+constexpr bool IsPositionMotor(EMotorState inMotorState) { return (int(inMotorState) & int(EMotorState::Position)) != 0; }++static_assert(!IsVelocityMotor(EMotorState::Off));+static_assert(IsVelocityMotor(EMotorState::Velocity));+static_assert(!IsVelocityMotor(EMotorState::Position));+static_assert(IsPositionMotor(EMotorState::PositionAndVelocity));+static_assert(!IsPositionMotor(EMotorState::Off));+static_assert(!IsPositionMotor(EMotorState::Velocity));+static_assert(IsPositionMotor(EMotorState::Position));+static_assert(IsPositionMotor(EMotorState::PositionAndVelocity));+/// Class that contains the settings for a constraint motor./// See the main page of the API documentation for more information on how to configure a motor.class JPH_EXPORT MotorSettings@@ -31,7 +45,9 @@ public:MotorSettings() = default;MotorSettings(const MotorSettings &) = default;MotorSettings & operator = (const MotorSettings &) = default;+ MotorSettings(ESpringMode inMode, float inFrequency, float inDamping) : mSpringSettings(inMode, inFrequency, inDamping) { JPH_ASSERT(IsValid()); }MotorSettings(float inFrequency, float inDamping) : mSpringSettings(ESpringMode::FrequencyAndDamping, inFrequency, inDamping) { JPH_ASSERT(IsValid()); }+ MotorSettings(ESpringMode inMode, float inFrequency, float inDamping, float inForceLimit, float inTorqueLimit) : mSpringSettings(inMode, inFrequency, inDamping), mMinForceLimit(-inForceLimit), mMaxForceLimit(inForceLimit), mMinTorqueLimit(-inTorqueLimit), mMaxTorqueLimit(inTorqueLimit) { JPH_ASSERT(IsValid()); }MotorSettings(float inFrequency, float inDamping, float inForceLimit, float inTorqueLimit) : mSpringSettings(ESpringMode::FrequencyAndDamping, inFrequency, inDamping), mMinForceLimit(-inForceLimit), mMaxForceLimit(inForceLimit), mMinTorqueLimit(-inTorqueLimit), mMaxTorqueLimit(inTorqueLimit) { JPH_ASSERT(IsValid()); }/// Set asymmetric force limits@@ -59,8 +75,8 @@ public:SpringSettings mSpringSettings { ESpringMode::FrequencyAndDamping, 2.0f, 1.0f }; ///< Settings for the spring that is used to drive to the position target (not used when motor is a velocity motor).float mMinForceLimit = -FLT_MAX; ///< Minimum force to apply in case of a linear constraint (N). Usually this is -mMaxForceLimit unless you want a motor that can e.g. push but not pull. Not used when motor is an angular motor.float mMaxForceLimit = FLT_MAX; ///< Maximum force to apply in case of a linear constraint (N). Not used when motor is an angular motor.- float mMinTorqueLimit = -FLT_MAX; ///< Minimum torque to apply in case of a angular constraint (N m). Usually this is -mMaxTorqueLimit unless you want a motor that can e.g. push but not pull. Not used when motor is a position motor.- float mMaxTorqueLimit = FLT_MAX; ///< Maximum torque to apply in case of a angular constraint (N m). Not used when motor is a position motor.+ float mMinTorqueLimit = -FLT_MAX; ///< Minimum torque to apply in case of a angular constraint (N m). Usually this is -mMaxTorqueLimit unless you want a motor that can e.g. push but not pull. Not used when motor is a linear motor.+ float mMaxTorqueLimit = FLT_MAX; ///< Maximum torque to apply in case of a angular constraint (N m). Not used when motor is a linear motor.};JPH_NAMESPACE_ENDdiff --git a/thirdparty/jolt_physics/Jolt/Physics/Constraints/PathConstraint.cpp b/thirdparty/jolt_physics/Jolt/Physics/Constraints/PathConstraint.cppindex e5b6eb7da03..92bbc619337 100644--- a/thirdparty/jolt_physics/Jolt/Physics/Constraints/PathConstraint.cpp+++ b/thirdparty/jolt_physics/Jolt/Physics/Constraints/PathConstraint.cpp@@ -104,6 +104,24 @@ void PathConstraint::SetPath(const PathConstraintPath *inPath, float inPathFract}}+float PathConstraint::CalculateConstraintValue() const+{+ float c;+ if (mPath->IsLooping())+ {+ float max_fraction = mPath->GetPathMaxFraction();+ c = fmod(mPathFraction - mTargetPathFraction, max_fraction);+ float half_max_fraction = 0.5f * max_fraction;+ if (c > half_max_fraction)+ c -= max_fraction;+ else if (c < -half_max_fraction)+ c += max_fraction;+ }+ else+ c = mPathFraction - mTargetPathFraction;+ return c;+}+void PathConstraint::CalculateConstraintProperties(float inDeltaTime){// Get transforms of body 1 and 2@@ -197,23 +215,14 @@ void PathConstraint::CalculateConstraintProperties(float inDeltaTime)case EMotorState::Position:if (mPositionMotorSettings.mSpringSettings.HasStiffness())- {- // Calculate constraint value to drive to- float c;- if (mPath->IsLooping())- {- float max_fraction = mPath->GetPathMaxFraction();- c = fmod(mPathFraction - mTargetPathFraction, max_fraction);- float half_max_fraction = 0.5f * max_fraction;- if (c > half_max_fraction)- c -= max_fraction;- else if (c < -half_max_fraction)- c += max_fraction;- }- else- c = mPathFraction - mTargetPathFraction;- mPositionMotorConstraintPart.CalculateConstraintPropertiesWithSettings(inDeltaTime, *mBody1, mR1 + mU, *mBody2, mR2, mPathTangent, 0.0f, c, mPositionMotorSettings.mSpringSettings);- }+ mPositionMotorConstraintPart.CalculateConstraintPropertiesWithSettingsForMotor(inDeltaTime, *mBody1, mR1 + mU, *mBody2, mR2, mPathTangent, 0.0f, CalculateConstraintValue(), mPositionMotorSettings.mSpringSettings);+ else+ mPositionMotorConstraintPart.Deactivate();+ break;++ case EMotorState::PositionAndVelocity:+ if (mPositionMotorSettings.mSpringSettings.HasStiffnessOrDamping())+ mPositionMotorConstraintPart.CalculateConstraintPropertiesWithSettingsForMotor(inDeltaTime, *mBody1, mR1 + mU, *mBody2, mR2, mPathTangent, -mTargetVelocity, CalculateConstraintValue(), mPositionMotorSettings.mSpringSettings);elsemPositionMotorConstraintPart.Deactivate();break;@@ -277,6 +286,7 @@ bool PathConstraint::SolveVelocityConstraint(float inDeltaTime)case EMotorState::Velocity:case EMotorState::Position:+ case EMotorState::PositionAndVelocity:motor = mPositionMotorConstraintPart.SolveVelocityConstraint(*mBody1, *mBody2, mPathTangent, inDeltaTime * mPositionMotorSettings.mMinForceLimit, inDeltaTime * mPositionMotorSettings.mMaxForceLimit);break;}@@ -388,26 +398,18 @@ void PathConstraint::DrawConstraint(DebugRenderer *inRenderer) constinRenderer->DrawText3D(x1, StringFormat("%.1f", (double)mPathFraction));// Draw motor- switch (mPositionMotorState)+ if (IsPositionMotor(mPositionMotorState)){- case EMotorState::Position:- {- // Draw target marker- Vec3 position, tangent, normal, binormal;- mPath->GetPointOnPath(mTargetPathFraction, position, tangent, normal, binormal);- inRenderer->DrawMarker(path_to_world * position, Color::sYellow, 1.0f);- break;- }-- case EMotorState::Velocity:- {- RVec3 position = mBody2->GetCenterOfMassPosition() + mR2;- inRenderer->DrawArrow(position, position + mPathTangent * mTargetVelocity, Color::sRed, 0.1f);- break;- }+ // Draw target marker+ Vec3 position, tangent, normal, binormal;+ mPath->GetPointOnPath(mTargetPathFraction, position, tangent, normal, binormal);+ inRenderer->DrawMarker(path_to_world * position, Color::sYellow, 1.0f);+ }- case EMotorState::Off:- break;+ if (IsVelocityMotor(mPositionMotorState))+ {+ RVec3 position = mBody2->GetCenterOfMassPosition() + mR2;+ inRenderer->DrawArrow(position, position + mPathTangent * mTargetVelocity, Color::sRed, 0.1f);}}}diff --git a/thirdparty/jolt_physics/Jolt/Physics/Constraints/PathConstraint.h b/thirdparty/jolt_physics/Jolt/Physics/Constraints/PathConstraint.hindex 3d15438bc9f..8017b1d1cd4 100644--- a/thirdparty/jolt_physics/Jolt/Physics/Constraints/PathConstraint.h+++ b/thirdparty/jolt_physics/Jolt/Physics/Constraints/PathConstraint.h@@ -140,6 +140,9 @@ private:// Internal helper function to calculate the values belowvoid CalculateConstraintProperties(float inDeltaTime);+ // Internal helper function to calculate the current constraint value C+ inline float CalculateConstraintValue() const;+// CONFIGURATION PROPERTIES FOLLOWRefConst<PathConstraintPath> mPath; ///< The path that attaches the two bodiesdiff --git a/thirdparty/jolt_physics/Jolt/Physics/Constraints/SixDOFConstraint.cpp b/thirdparty/jolt_physics/Jolt/Physics/Constraints/SixDOFConstraint.cppindex 6ec73d68932..89b2490b907 100644--- a/thirdparty/jolt_physics/Jolt/Physics/Constraints/SixDOFConstraint.cpp+++ b/thirdparty/jolt_physics/Jolt/Physics/Constraints/SixDOFConstraint.cpp@@ -296,7 +296,7 @@ void SixDOFConstraint::CacheRotationPositionMotorActive(){mRotationPositionMotorActive = 0;for (int i = 0; i < 3; ++i)- if (mMotorState[EAxis::RotationX + i] == EMotorState::Position)+ if (IsPositionMotor(mMotorState[EAxis::RotationX + i]))mRotationPositionMotorActive |= 1 << i;}@@ -409,7 +409,7 @@ void SixDOFConstraint::SetupVelocityConstraint(float inDeltaTime)}if (constraint_active)- mTranslationConstraintPart[i].CalculateConstraintPropertiesWithSettings(inDeltaTime, *mBody1, r1_plus_u, *mBody2, r2, translation_axis, 0.0f, constraint_value, mLimitsSpringSettings[i]);+ mTranslationConstraintPart[i].CalculateConstraintPropertiesWithSettingsForLimit(inDeltaTime, *mBody1, r1_plus_u, *mBody2, r2, translation_axis, 0.0f, constraint_value, mLimitsSpringSettings[i]);elsemTranslationConstraintPart[i].Deactivate();@@ -431,7 +431,17 @@ void SixDOFConstraint::SetupVelocityConstraint(float inDeltaTime){const SpringSettings &spring_settings = mMotorSettings[i].mSpringSettings;if (spring_settings.HasStiffness())- mMotorTranslationConstraintPart[i].CalculateConstraintPropertiesWithSettings(inDeltaTime, *mBody1, r1_plus_u, *mBody2, r2, translation_axis, 0.0f, translation_axis.Dot(u) - mTargetPosition[i], spring_settings);+ mMotorTranslationConstraintPart[i].CalculateConstraintPropertiesWithSettingsForMotor(inDeltaTime, *mBody1, r1_plus_u, *mBody2, r2, translation_axis, 0.0f, translation_axis.Dot(u) - mTargetPosition[i], spring_settings);+ else+ mMotorTranslationConstraintPart[i].Deactivate();+ break;+ }++ case EMotorState::PositionAndVelocity:+ {+ const SpringSettings &spring_settings = mMotorSettings[i].mSpringSettings;+ if (spring_settings.HasStiffnessOrDamping())+ mMotorTranslationConstraintPart[i].CalculateConstraintPropertiesWithSettingsForMotor(inDeltaTime, *mBody1, r1_plus_u, *mBody2, r2, translation_axis, -mTargetVelocity[i], translation_axis.Dot(u) - mTargetPosition[i], spring_settings);elsemMotorTranslationConstraintPart[i].Deactivate();break;@@ -562,7 +572,17 @@ void SixDOFConstraint::SetupVelocityConstraint(float inDeltaTime){const SpringSettings &spring_settings = mMotorSettings[axis].mSpringSettings;if (spring_settings.HasStiffness())- mMotorRotationConstraintPart[i].CalculateConstraintPropertiesWithSettings(inDeltaTime, *mBody1, *mBody2, rotation_axis, 0.0f, rotation_error[i], spring_settings);+ mMotorRotationConstraintPart[i].CalculateConstraintPropertiesWithSettingsForMotor(inDeltaTime, *mBody1, *mBody2, rotation_axis, 0.0f, rotation_error[i], spring_settings);+ else+ mMotorRotationConstraintPart[i].Deactivate();+ break;+ }++ case EMotorState::PositionAndVelocity:+ {+ const SpringSettings &spring_settings = mMotorSettings[axis].mSpringSettings;+ if (spring_settings.HasStiffnessOrDamping())+ mMotorRotationConstraintPart[i].CalculateConstraintPropertiesWithSettingsForMotor(inDeltaTime, *mBody1, *mBody2, rotation_axis, -mTargetAngularVelocity[i], rotation_error[i], spring_settings);elsemMotorRotationConstraintPart[i].Deactivate();break;@@ -635,6 +655,7 @@ bool SixDOFConstraint::SolveVelocityConstraint(float inDeltaTime)case EMotorState::Velocity:case EMotorState::Position:+ case EMotorState::PositionAndVelocity:// Drive motorimpulse |= mMotorTranslationConstraintPart[i].SolveVelocityConstraint(*mBody1, *mBody2, mTranslationAxis[i], inDeltaTime * mMotorSettings[i].mMinForceLimit, inDeltaTime * mMotorSettings[i].mMaxForceLimit);break;@@ -658,6 +679,7 @@ bool SixDOFConstraint::SolveVelocityConstraint(float inDeltaTime)case EMotorState::Velocity:case EMotorState::Position:+ case EMotorState::PositionAndVelocity:// Drive motorimpulse |= mMotorRotationConstraintPart[i].SolveVelocityConstraint(*mBody1, *mBody2, mRotationAxis[i], inDeltaTime * mMotorSettings[axis].mMinTorqueLimit, inDeltaTime * mMotorSettings[axis].mMaxTorqueLimit);break;@@ -803,15 +825,15 @@ void SixDOFConstraint::DrawConstraint(DebugRenderer *inRenderer) const// Draw target rotationQuat m_swing, m_twist;mTargetOrientation.GetSwingTwist(m_swing, m_twist);- if (mMotorState[EAxis::RotationX] == EMotorState::Position)+ if (IsPositionMotor(mMotorState[EAxis::RotationX]))inRenderer->DrawLine(position1, position1 + mDrawConstraintSize * (rotation1 * m_twist).RotateAxisY(), Color::sYellow);- if (mMotorState[EAxis::RotationY] == EMotorState::Position || mMotorState[EAxis::RotationZ] == EMotorState::Position)+ if (IsPositionMotor(mMotorState[EAxis::RotationY]) || IsPositionMotor(mMotorState[EAxis::RotationZ]))inRenderer->DrawLine(position1, position1 + mDrawConstraintSize * (rotation1 * m_swing).RotateAxisX(), Color::sYellow);// Draw target angular velocityVec3 target_angular_velocity = Vec3::sZero();for (int i = 0; i < 3; ++i)- if (mMotorState[EAxis::RotationX + i] == EMotorState::Velocity)+ if (IsVelocityMotor(mMotorState[EAxis::RotationX + i]))target_angular_velocity.SetComponent(i, mTargetAngularVelocity[i]);if (target_angular_velocity != Vec3::sZero())inRenderer->DrawArrow(position1, position1 + rotation2 * target_angular_velocity, Color::sRed, 0.1f);diff --git a/thirdparty/jolt_physics/Jolt/Physics/Constraints/SliderConstraint.cpp b/thirdparty/jolt_physics/Jolt/Physics/Constraints/SliderConstraint.cppindex 75335c32cba..da1b4101c07 100644--- a/thirdparty/jolt_physics/Jolt/Physics/Constraints/SliderConstraint.cpp+++ b/thirdparty/jolt_physics/Jolt/Physics/Constraints/SliderConstraint.cpp@@ -225,7 +225,7 @@ void SliderConstraint::CalculatePositionLimitsConstraintProperties(float inDelta// Check if distance is within limitsbool below_min = mD <= mLimitsMin;if (mHasLimits && (below_min || mD >= mLimitsMax))- mPositionLimitsConstraintPart.CalculateConstraintPropertiesWithSettings(inDeltaTime, *mBody1, mR1 + mU, *mBody2, mR2, mWorldSpaceSliderAxis, 0.0f, mD - (below_min? mLimitsMin : mLimitsMax), mLimitsSpringSettings);+ mPositionLimitsConstraintPart.CalculateConstraintPropertiesWithSettingsForLimit(inDeltaTime, *mBody1, mR1 + mU, *mBody2, mR2, mWorldSpaceSliderAxis, 0.0f, mD - (below_min? mLimitsMin : mLimitsMax), mLimitsSpringSettings);elsemPositionLimitsConstraintPart.Deactivate();}@@ -247,7 +247,14 @@ void SliderConstraint::CalculateMotorConstraintProperties(float inDeltaTime)case EMotorState::Position:if (mMotorSettings.mSpringSettings.HasStiffness())- mMotorConstraintPart.CalculateConstraintPropertiesWithSettings(inDeltaTime, *mBody1, mR1 + mU, *mBody2, mR2, mWorldSpaceSliderAxis, 0.0f, mD - mTargetPosition, mMotorSettings.mSpringSettings);+ mMotorConstraintPart.CalculateConstraintPropertiesWithSettingsForMotor(inDeltaTime, *mBody1, mR1 + mU, *mBody2, mR2, mWorldSpaceSliderAxis, 0.0f, mD - mTargetPosition, mMotorSettings.mSpringSettings);+ else+ mMotorConstraintPart.Deactivate();+ break;++ case EMotorState::PositionAndVelocity:+ if (mMotorSettings.mSpringSettings.HasStiffnessOrDamping())+ mMotorConstraintPart.CalculateConstraintPropertiesWithSettingsForMotor(inDeltaTime, *mBody1, mR1 + mU, *mBody2, mR2, mWorldSpaceSliderAxis, -mTargetVelocity, mD - mTargetPosition, mMotorSettings.mSpringSettings);elsemMotorConstraintPart.Deactivate();break;@@ -301,6 +308,7 @@ bool SliderConstraint::SolveVelocityConstraint(float inDeltaTime)case EMotorState::Velocity:case EMotorState::Position:+ case EMotorState::PositionAndVelocity:motor = mMotorConstraintPart.SolveVelocityConstraint(*mBody1, *mBody2, mWorldSpaceSliderAxis, inDeltaTime * mMotorSettings.mMinForceLimit, inDeltaTime * mMotorSettings.mMaxForceLimit);break;}@@ -394,22 +402,14 @@ void SliderConstraint::DrawConstraint(DebugRenderer *inRenderer) constinRenderer->DrawLine(position1, position2, Color::sGreen);// Draw motor- switch (mMotorState)- {- case EMotorState::Position:+ if (IsPositionMotor(mMotorState))inRenderer->DrawMarker(position1 + mTargetPosition * slider_axis, Color::sYellow, 1.0f);- break;- case EMotorState::Velocity:- {- Vec3 cur_vel = (mBody2->GetLinearVelocity() - mBody1->GetLinearVelocity()).Dot(slider_axis) * slider_axis;- inRenderer->DrawLine(position2, position2 + cur_vel, Color::sBlue);- inRenderer->DrawArrow(position2 + cur_vel, position2 + mTargetVelocity * slider_axis, Color::sRed, 0.1f);- break;- }-- case EMotorState::Off:- break;+ if (IsVelocityMotor(mMotorState))+ {+ Vec3 cur_vel = (mBody2->GetLinearVelocity() - mBody1->GetLinearVelocity()).Dot(slider_axis) * slider_axis;+ inRenderer->DrawLine(position2, position2 + cur_vel, Color::sBlue);+ inRenderer->DrawArrow(position2 + cur_vel, position2 + mTargetVelocity * slider_axis, Color::sRed, 0.1f);}}diff --git a/thirdparty/jolt_physics/Jolt/Physics/Constraints/SpringSettings.h b/thirdparty/jolt_physics/Jolt/Physics/Constraints/SpringSettings.hindex bfa49caac08..1ca7565c4f0 100644--- a/thirdparty/jolt_physics/Jolt/Physics/Constraints/SpringSettings.h+++ b/thirdparty/jolt_physics/Jolt/Physics/Constraints/SpringSettings.h@@ -14,8 +14,9 @@ class StreamOut;/// Enum used by constraints to specify how the spring is definedenum class ESpringMode : uint8{- FrequencyAndDamping, ///< Frequency and damping are specified- StiffnessAndDamping, ///< Stiffness and damping are specified+ FrequencyAndDamping, ///< Frequency and damping are specified.+ StiffnessAndDamping, ///< Stiffness and damping are specified.+ MassNormalizedStiffnessAndDamping, ///< Stiffness and damping divided by mass / inertia are specified (also known as acceleration mode). This makes it easier to tune the spring and makes it mass independent.};/// Settings for a linear or angular spring@@ -39,30 +40,46 @@ public:/// Check if the spring has a valid frequency / stiffness, if not the spring will be hardinline bool HasStiffness() const { return mFrequency > 0.0f; }- /// Selects the way in which the spring is defined- /// If the mode is StiffnessAndDamping then mFrequency becomes the stiffness (k) and mDamping becomes the damping ratio (c) in the spring equation F = -k * x - c * v. Otherwise the properties are as documented.+ /// Check if this spring has stiffness or damping (making it active), if not the constraint will be hard+ inline bool HasStiffnessOrDamping() const { return mFrequency > 0.0f || (mMode != ESpringMode::FrequencyAndDamping && mDamping > 0.0f); }++ /// Selects the way in which the spring is defined. See the descriptions of the mFrequency, mStiffness and mDamping properties.ESpringMode mMode = ESpringMode::FrequencyAndDamping;union{- /// Valid when mSpringMode = ESpringMode::FrequencyAndDamping.- /// If mFrequency > 0 the constraint will be soft and mFrequency specifies the oscillation frequency in Hz.- /// If mFrequency <= 0, mDamping is ignored and the constraint will have hard limits (as hard as the time step / the number of velocity / position solver steps allows).+ /// Valid when mMode = ESpringMode::FrequencyAndDamping.+ /// If > 0 the constraint will be soft and this specifies the oscillation frequency in Hz.+ /// If <= 0, mDamping is ignored and the constraint will have hard limits (as hard as the time step / the number of velocity / position solver steps allows).float mFrequency = 0.0f;- /// Valid when mSpringMode = ESpringMode::StiffnessAndDamping.- /// If mStiffness > 0 the constraint will be soft and mStiffness specifies the stiffness (k) in the spring equation F = -k * x - c * v for a linear or T = -k * theta - c * w for an angular spring.- /// If mStiffness <= 0, mDamping is ignored and the constraint will have hard limits (as hard as the time step / the number of velocity / position solver steps allows).+ /// When mMode = ESpringMode::StiffnessAndDamping:+ /// Specifies the stiffness (k) in the spring equation F = -k * x - c * v for a linear or T = -k * theta - c * w for an angular spring.+ /// Units are N / m for a linear spring and N m / rad for an angular spring.////// Note that stiffness values are large numbers. To calculate a ballpark value for the needed stiffness you can use:/// force = stiffness * delta_spring_length = mass * gravity <=> stiffness = mass * gravity / delta_spring_length./// So if your object weighs 1500 kg and the spring compresses by 2 meters, you need a stiffness in the order of 1500 * 9.81 / 2 ~ 7500 N/m.+ ///+ /// When mMode = ESpringMode::MassNormalizedStiffnessAndDamping:+ /// Specifies the stiffness (k) in the spring equation F = m_eff * (-k * x - c * v) for a linear or T = i_eff * (-k * theta - c * w) for an angular spring.+ /// m_eff / i_eff is the effective mass / inertia of the constraint.+ /// Units are 1 / s^2 for a linear spring and 1 / rad s^2 for an angular spring.+ ///+ /// Since the stiffness is multiplied by the effective mass / inertia of the constraint, you can use much smaller stiffness values and they will be mass independent.float mStiffness;};- /// When mSpringMode = ESpringMode::FrequencyAndDamping mDamping is the damping ratio (0 = no damping, 1 = critical damping).- /// When mSpringMode = ESpringMode::StiffnessAndDamping mDamping is the damping (c) in the spring equation F = -k * x - c * v for a linear or T = -k * theta - c * w for an angular spring.- /// Note that if you set mDamping = 0, you will not get an infinite oscillation. Because we integrate physics using an explicit Euler scheme, there is always energy loss.+ /// When mMode = ESpringMode::FrequencyAndDamping this is the damping ratio (0 = no damping, 1 = critical damping).+ ///+ /// When mMode = ESpringMode::StiffnessAndDamping this is the damping (c) in the spring equation F = -k * x - c * v for a linear or T = -k * theta - c * w for an angular spring.+ /// Units are N s / m for a linear spring and N s m / rad for an angular spring.+ ///+ /// When mMode = ESpringMode::MassNormalizedStiffnessAndDamping this is the damping (c) in the spring equation F = m_eff * (-k * x - c * v) for a linear or T = i_eff * (-k * theta - c * w) for an angular spring.+ /// m_eff / i_eff is the effective mass / inertia of the constraint.+ /// Units are 1 / s for a linear spring and 1 / rad s for an angular spring.+ ///+ /// Note that if you set this to 0, you will not get an infinite oscillation. Because we integrate physics using an explicit Euler scheme, there is always energy loss./// This is done to keep the simulation from exploding, because with a damping of 0 and even the slightest rounding error, the oscillation could become bigger and bigger until the simulation explodes.float mDamping = 0.0f;};diff --git a/thirdparty/jolt_physics/Jolt/Physics/Constraints/SwingTwistConstraint.cpp b/thirdparty/jolt_physics/Jolt/Physics/Constraints/SwingTwistConstraint.cppindex bcd74ff305a..bf57a92acb7 100644--- a/thirdparty/jolt_physics/Jolt/Physics/Constraints/SwingTwistConstraint.cpp+++ b/thirdparty/jolt_physics/Jolt/Physics/Constraints/SwingTwistConstraint.cpp@@ -220,7 +220,7 @@ void SwingTwistConstraint::SetupVelocityConstraint(float inDeltaTime)mWorldSpaceMotorAxis[i] = ws_axis.GetColumn3(i);Vec3 rotation_error;- if (mSwingMotorState == EMotorState::Position || mTwistMotorState == EMotorState::Position)+ if (IsPositionMotor(mSwingMotorState) || IsPositionMotor(mTwistMotorState)){// Get target orientation along the shortest path from qQuat target_orientation = q.Dot(mTargetOrientation) > 0.0f? mTargetOrientation : -mTargetOrientation;@@ -281,7 +281,21 @@ void SwingTwistConstraint::SetupVelocityConstraint(float inDeltaTime)if (mSwingMotorSettings.mSpringSettings.HasStiffness()){for (int i = 1; i < 3; ++i)- mMotorConstraintPart[i].CalculateConstraintPropertiesWithSettings(inDeltaTime, *mBody1, *mBody2, mWorldSpaceMotorAxis[i], 0.0f, rotation_error[i], mSwingMotorSettings.mSpringSettings);+ mMotorConstraintPart[i].CalculateConstraintPropertiesWithSettingsForMotor(inDeltaTime, *mBody1, *mBody2, mWorldSpaceMotorAxis[i], 0.0f, rotation_error[i], mSwingMotorSettings.mSpringSettings);+ }+ else+ {+ for (int i = 1; i < 3; ++i)+ mMotorConstraintPart[i].Deactivate();+ }+ break;++ case EMotorState::PositionAndVelocity:+ // Use motor to drive rotation error to zero+ if (mSwingMotorSettings.mSpringSettings.HasStiffnessOrDamping())+ {+ for (int i = 1; i < 3; ++i)+ mMotorConstraintPart[i].CalculateConstraintPropertiesWithSettingsForMotor(inDeltaTime, *mBody1, *mBody2, mWorldSpaceMotorAxis[i], -mTargetAngularVelocity[i], rotation_error[i], mSwingMotorSettings.mSpringSettings);}else{@@ -315,7 +329,15 @@ void SwingTwistConstraint::SetupVelocityConstraint(float inDeltaTime)case EMotorState::Position:// Use motor to drive rotation error to zeroif (mTwistMotorSettings.mSpringSettings.HasStiffness())- mMotorConstraintPart[0].CalculateConstraintPropertiesWithSettings(inDeltaTime, *mBody1, *mBody2, mWorldSpaceMotorAxis[0], 0.0f, rotation_error[0], mTwistMotorSettings.mSpringSettings);+ mMotorConstraintPart[0].CalculateConstraintPropertiesWithSettingsForMotor(inDeltaTime, *mBody1, *mBody2, mWorldSpaceMotorAxis[0], 0.0f, rotation_error[0], mTwistMotorSettings.mSpringSettings);+ else+ mMotorConstraintPart[0].Deactivate();+ break;++ case EMotorState::PositionAndVelocity:+ // Use motor to drive rotation error to zero+ if (mTwistMotorSettings.mSpringSettings.HasStiffnessOrDamping())+ mMotorConstraintPart[0].CalculateConstraintPropertiesWithSettingsForMotor(inDeltaTime, *mBody1, *mBody2, mWorldSpaceMotorAxis[0], -mTargetAngularVelocity[0], rotation_error[0], mTwistMotorSettings.mSpringSettings);elsemMotorConstraintPart[0].Deactivate();break;@@ -440,12 +462,12 @@ void SwingTwistConstraint::DrawConstraint(DebugRenderer *inRenderer) constinRenderer->DrawLine(position1, position1 + mDrawConstraintSize * (rotation1 * q_twist).RotateAxisY(), Color::sWhite);inRenderer->DrawLine(position1, position1 + mDrawConstraintSize * (rotation1 * q_swing).RotateAxisX(), Color::sWhite);- if (mSwingMotorState == EMotorState::Velocity || mTwistMotorState == EMotorState::Velocity)+ if (IsVelocityMotor(mSwingMotorState) || IsVelocityMotor(mTwistMotorState)){// Draw target angular velocityinRenderer->DrawArrow(position1, position1 + rotation2 * mTargetAngularVelocity, Color::sRed, 0.1f);}- if (mSwingMotorState == EMotorState::Position || mTwistMotorState == EMotorState::Position)+ if (IsPositionMotor(mSwingMotorState) || IsPositionMotor(mTwistMotorState)){// Draw motor swing and twistQuat swing, twist;diff --git a/thirdparty/jolt_physics/Jolt/Physics/Constraints/SwingTwistConstraint.h b/thirdparty/jolt_physics/Jolt/Physics/Constraints/SwingTwistConstraint.hindex 5e3e896f44c..5275faae129 100644--- a/thirdparty/jolt_physics/Jolt/Physics/Constraints/SwingTwistConstraint.h+++ b/thirdparty/jolt_physics/Jolt/Physics/Constraints/SwingTwistConstraint.h@@ -133,6 +133,9 @@ public:void SetTargetAngularVelocityCS(Vec3Arg inAngularVelocity) { mTargetAngularVelocity = inAngularVelocity; }Vec3 GetTargetAngularVelocityCS() const { return mTargetAngularVelocity; }+ /// Set the target angular velocity of body 2 in body 2 space+ void SetTargetAngularVelocityBS(Vec3Arg inAngularVelocity) { mTargetAngularVelocity = mConstraintToBody2.InverseRotate(inAngularVelocity); }+/// Set the target orientation in constraint space (drives constraint to: GetRotationInConstraintSpace() == inOrientation)void SetTargetOrientationCS(QuatArg inOrientation);Quat GetTargetOrientationCS() const { return mTargetOrientation; }diff --git a/thirdparty/jolt_physics/Jolt/Physics/Constraints/TwoBodyConstraint.cpp b/thirdparty/jolt_physics/Jolt/Physics/Constraints/TwoBodyConstraint.cppindex 9ee7cc5d892..07ffb7b78c9 100644--- a/thirdparty/jolt_physics/Jolt/Physics/Constraints/TwoBodyConstraint.cpp+++ b/thirdparty/jolt_physics/Jolt/Physics/Constraints/TwoBodyConstraint.cpp@@ -22,18 +22,38 @@ JPH_IMPLEMENT_SERIALIZABLE_ABSTRACT(TwoBodyConstraintSettings)void TwoBodyConstraint::BuildIslands(uint32 inConstraintIndex, IslandBuilder &ioBuilder, BodyManager &inBodyManager){+#ifdef JPH_ENABLE_ASSERTS+ // Validates that a body that is sleeping has zero velocity.+ mBody1->ValidateMotion();+ mBody2->ValidateMotion();+#endif++ bool body1_dynamic = mBody1->IsDynamic();+ bool body2_dynamic = mBody2->IsDynamic();+// Activate bodiesBodyID body_ids[2];int num_bodies = 0;- if (mBody1->IsDynamic() && !mBody1->IsActive())+ if (body1_dynamic && !mBody1->IsActive())body_ids[num_bodies++] = mBody1->GetID();- if (mBody2->IsDynamic() && !mBody2->IsActive())+ if (body2_dynamic && !mBody2->IsActive())body_ids[num_bodies++] = mBody2->GetID();if (num_bodies > 0)inBodyManager.ActivateBodies(body_ids, num_bodies);- // Link the bodies into the same island- ioBuilder.LinkConstraint(inConstraintIndex, mBody1->GetIndexInActiveBodiesInternal(), mBody2->GetIndexInActiveBodiesInternal());+ // Link the two bodies only if both are dynamic. If one of them is static or kinematic they don't need to go into+ // the same simulation island as a constraint cannot affect the velocity of a kinematic body.+ if (body1_dynamic && body2_dynamic)+ ioBuilder.LinkBodies(mBody1->GetIndexInActiveBodiesInternal(), mBody2->GetIndexInActiveBodiesInternal());++ // Link the constraint to the first dynamic body+ if (body1_dynamic)+ ioBuilder.LinkConstraint(inConstraintIndex, mBody1->GetIndexInActiveBodiesInternal());+ else+ {+ JPH_ASSERT(body2_dynamic);+ ioBuilder.LinkConstraint(inConstraintIndex, mBody2->GetIndexInActiveBodiesInternal());+ }}uint TwoBodyConstraint::BuildIslandSplits(LargeIslandSplitter &ioSplitter) constdiff --git a/thirdparty/jolt_physics/Jolt/Physics/DeterminismLog.h b/thirdparty/jolt_physics/Jolt/Physics/DeterminismLog.hindex e2930ff3cea..c7f92500dd3 100644--- a/thirdparty/jolt_physics/Jolt/Physics/DeterminismLog.h+++ b/thirdparty/jolt_physics/Jolt/Physics/DeterminismLog.h@@ -32,10 +32,29 @@ private:}public:- DeterminismLog()- {- mLog.open("detlog.txt", std::ios::out | std::ios::trunc | std::ios::binary); // Binary because we don't want a difference between Unix and Windows line endings.+ /// When base path is set, use it as the base path for the log file, otherwise use the current working directory+ inline static const char *sBasePath = nullptr;++ void Open()+ {+ // Determine file name+ char file_name[1024] = "detlog.txt";+ if (sBasePath != nullptr)+ snprintf(file_name, sizeof(file_name), "%s/detlog.txt", sBasePath);+ Trace("Opening determinism log file: %s", file_name);+#ifdef JPH_PLATFORM_ANDROID+ Trace("Retrieve it using: adb pull %s detlog.txt", file_name);+#endif++ // Open the file+ mLog.open(file_name, std::ios::out | std::ios::trunc | std::ios::binary); // Binary because we don't want a difference between Unix and Windows line endings.mLog.fill('0');+ JPH_ASSERT(mLog.is_open());+ }++ void Close()+ {+ mLog.close();}DeterminismLog & operator << (char inValue)@@ -50,7 +69,7 @@ public:return *this;}- DeterminismLog & operator << (const string &inValue)+ DeterminismLog & operator << (const String &inValue){mLog << std::dec << inValue;return *this;@@ -142,7 +161,9 @@ private:};/// Will log something to the determinism log, usage: JPH_DET_LOG("label " << value);-#define JPH_DET_LOG(...) DeterminismLog::sLog << __VA_ARGS__ << '\n'+#define JPH_DET_LOG_OPEN() DeterminismLog::sLog.Open()+#define JPH_DET_LOG(...) DeterminismLog::sLog << __VA_ARGS__ << '\n'+#define JPH_DET_LOG_CLOSE() DeterminismLog::sLog.Close()JPH_NAMESPACE_END@@ -152,7 +173,9 @@ JPH_SUPPRESS_WARNING_PUSHJPH_SUPPRESS_WARNINGS/// By default we log nothing+#define JPH_DET_LOG_OPEN()#define JPH_DET_LOG(...)+#define JPH_DET_LOG_CLOSE()JPH_SUPPRESS_WARNING_POPdiff --git a/thirdparty/jolt_physics/Jolt/Physics/IslandBuilder.cpp b/thirdparty/jolt_physics/Jolt/Physics/IslandBuilder.cppindex 60bb930e411..cf2ac47d9b1 100644--- a/thirdparty/jolt_physics/Jolt/Physics/IslandBuilder.cpp+++ b/thirdparty/jolt_physics/Jolt/Physics/IslandBuilder.cpp@@ -72,6 +72,7 @@ void IslandBuilder::PrepareNonContactConstraints(uint32 inNumConstraints, TempAlJPH_ASSERT(mBodyLinks != nullptr);// Check that the builder has been reset+ JPH_ASSERT(mNumConstraints == 0);JPH_ASSERT(mNumIslands == 0);// Store number of constraints@@ -154,20 +155,20 @@ void IslandBuilder::LinkBodies(uint32 inFirst, uint32 inSecond)}}-void IslandBuilder::LinkConstraint(uint32 inConstraintIndex, uint32 inFirst, uint32 inSecond)+void IslandBuilder::LinkConstraint(uint32 inConstraintIndex, uint32 inIndexInActiveBodyList){- LinkBodies(inFirst, inSecond);-JPH_ASSERT(inConstraintIndex < mNumConstraints);- uint32 min_value = min(inFirst, inSecond); // Use fact that invalid index is 0xffffffff, we want the active body of two- JPH_ASSERT(min_value != Body::cInactiveIndex); // At least one of the bodies must be active- mConstraintLinks[inConstraintIndex] = min_value;+ JPH_ASSERT(inIndexInActiveBodyList != MotionProperties::cInactiveIndex); // Body should be active++ mConstraintLinks[inConstraintIndex] = inIndexInActiveBodyList;}-void IslandBuilder::LinkContact(uint32 inContactIndex, uint32 inFirst, uint32 inSecond)+void IslandBuilder::LinkContact(uint32 inContactIndex, uint32 inIndexInActiveBodyList){JPH_ASSERT(inContactIndex < mMaxContacts);- mContactLinks[inContactIndex] = min(inFirst, inSecond); // Use fact that invalid index is 0xffffffff, we want the active body of two+ JPH_ASSERT(inIndexInActiveBodyList != MotionProperties::cInactiveIndex); // Body should be active++ mContactLinks[inContactIndex] = inIndexInActiveBodyList;}#ifdef JPH_VALIDATE_ISLAND_BUILDER@@ -294,7 +295,7 @@ void IslandBuilder::BuildConstraintIslands(const uint32 *inConstraintToBody, uinuint32 *constraint_ends = (uint32 *)inTempAllocator->Allocate((mNumIslands + 1) * sizeof(uint32));// Reset sizes- for (uint32 island = 0; island < mNumIslands; ++island)+ for (uint32 island = 0; island <= mNumIslands; ++island)constraint_ends[island] = 0;// Loop over array and increment start relative position for the next island@@ -440,9 +441,11 @@ void IslandBuilder::ResetIslands(TempAllocator *inTempAllocator)#ifdef JPH_TRACK_SIMULATION_STATSinTempAllocator->Free(mIslandStats, mNumIslands * sizeof(IslandStats));+ mIslandStats = nullptr;#endifinTempAllocator->Free(mNumPositionSteps, mNumIslands * sizeof(uint8));+ mNumPositionSteps = nullptr;if (mIslandsSorted != nullptr){@@ -468,7 +471,7 @@ void IslandBuilder::ResetIslands(TempAllocator *inTempAllocator)inTempAllocator->Free(mBodyIslandEnds, (mNumActiveBodies + 1) * sizeof(uint32));mBodyIslandEnds = nullptr;- inTempAllocator->Free(mBodyIslands, mNumActiveBodies * sizeof(uint32));+ inTempAllocator->Free(mBodyIslands, mNumActiveBodies * sizeof(BodyID));mBodyIslands = nullptr;inTempAllocator->Free(mConstraintLinks, mNumConstraints * sizeof(uint32));diff --git a/thirdparty/jolt_physics/Jolt/Physics/IslandBuilder.h b/thirdparty/jolt_physics/Jolt/Physics/IslandBuilder.hindex 24eee59dc59..16d932a49c2 100644--- a/thirdparty/jolt_physics/Jolt/Physics/IslandBuilder.h+++ b/thirdparty/jolt_physics/Jolt/Physics/IslandBuilder.h@@ -34,10 +34,10 @@ public:void LinkBodies(uint32 inFirst, uint32 inSecond);/// Link a constraint to a body by their index in the BodyManager::mActiveBodies- void LinkConstraint(uint32 inConstraintIndex, uint32 inFirst, uint32 inSecond);+ void LinkConstraint(uint32 inConstraintIndex, uint32 inIndexInActiveBodyList);/// Link a contact to a body by their index in the BodyManager::mActiveBodies- void LinkContact(uint32 inContactIndex, uint32 inFirst, uint32 inSecond);+ void LinkContact(uint32 inContactIndex, uint32 inIndexInActiveBodyList);/// Finalize the islands after all bodies have been Link()-edvoid Finalize(const BodyID *inActiveBodies, uint32 inNumActiveBodies, uint32 inNumContacts, TempAllocator *inTempAllocator);diff --git a/thirdparty/jolt_physics/Jolt/Physics/LargeIslandSplitter.cpp b/thirdparty/jolt_physics/Jolt/Physics/LargeIslandSplitter.cppindex 50ab1c583fa..a34ca748882 100644--- a/thirdparty/jolt_physics/Jolt/Physics/LargeIslandSplitter.cpp+++ b/thirdparty/jolt_physics/Jolt/Physics/LargeIslandSplitter.cpp@@ -188,7 +188,8 @@ void LargeIslandSplitter::Prepare(const IslandBuilder &inIslandBuilder, uint32 iJPH_PROFILE_FUNCTION();// Count the total number of constraints and contacts that we will be putting in splits- mContactAndConstraintsSize = 0;+ JPH_ASSERT(mNumSplitIslands == 0);+ JPH_ASSERT(mContactAndConstraintsSize == 0);for (uint32 island = 0; island < inIslandBuilder.GetNumIslands(); ++island){// Get the contacts in this island@@ -285,8 +286,6 @@ uint LargeIslandSplitter::AssignToNonParallelSplit(const Body *inBody)bool LargeIslandSplitter::SplitIsland(uint32 inIslandIndex, const IslandBuilder &inIslandBuilder, const BodyManager &inBodyManager, const ContactConstraintManager &inContactManager, Constraint **inActiveConstraints, CalculateSolverSteps &ioStepsCalculator){- JPH_PROFILE_FUNCTION();-// Get the contacts in this islanduint32 *contacts_start, *contacts_end;inIslandBuilder.GetContactsInIsland(inIslandIndex, contacts_start, contacts_end);@@ -302,6 +301,9 @@ bool LargeIslandSplitter::SplitIsland(uint32 inIslandIndex, const IslandBuilderif (island_size < cLargeIslandTreshold)return false;+ // Start measuring after the early out+ JPH_PROFILE_FUNCTION();+// Get bodies in this islandBodyID *bodies_start, *bodies_end;inIslandBuilder.GetBodiesInIsland(inIslandIndex, bodies_start, bodies_end);diff --git a/thirdparty/jolt_physics/Jolt/Physics/PhysicsScene.cpp b/thirdparty/jolt_physics/Jolt/Physics/PhysicsScene.cppindex e1c4145f9be..8767e744727 100644--- a/thirdparty/jolt_physics/Jolt/Physics/PhysicsScene.cpp+++ b/thirdparty/jolt_physics/Jolt/Physics/PhysicsScene.cpp@@ -8,6 +8,7 @@#include <Jolt/Physics/PhysicsSystem.h>#include <Jolt/Physics/Body/BodyLockMulti.h>#include <Jolt/ObjectStream/TypeDeclarations.h>+#include <Jolt/Core/UnorderedMap.h>JPH_NAMESPACE_BEGINdiff --git a/thirdparty/jolt_physics/Jolt/Physics/PhysicsSystem.cpp b/thirdparty/jolt_physics/Jolt/Physics/PhysicsSystem.cppindex 90a69c415d4..de4d0eed85b 100644--- a/thirdparty/jolt_physics/Jolt/Physics/PhysicsSystem.cpp+++ b/thirdparty/jolt_physics/Jolt/Physics/PhysicsSystem.cpp@@ -158,6 +158,7 @@ void PhysicsSystem::GatherIslandStats(){Body &body = mBodyManager.GetBody(*body_id);MotionProperties::SimulationStats &out_stats = body.GetMotionProperties()->GetSimulationStats();+ ++out_stats.mNumCollisionSteps;out_stats.mNumVelocitySteps = stats.mNumVelocitySteps;out_stats.mNumPositionSteps = stats.mNumPositionSteps;if (body.GetMotionType() == EMotionType::Dynamic)@@ -212,7 +213,7 @@ EPhysicsUpdateError PhysicsSystem::Update(float inDeltaTime, int inCollisionStep// Calculate ratio between current and previous frame delta time to scale initial constraint forcesfloat step_delta_time = inDeltaTime / inCollisionSteps;- float warm_start_impulse_ratio = mPhysicsSettings.mConstraintWarmStart && mPreviousStepDeltaTime > 0.0f? step_delta_time / mPreviousStepDeltaTime : 0.0f;+ float warm_start_impulse_ratio = mPreviousStepDeltaTime > 0.0f? step_delta_time / mPreviousStepDeltaTime : 0.0f;mPreviousStepDeltaTime = step_delta_time;// Create the context used for passing information between jobs@@ -220,6 +221,7 @@ EPhysicsUpdateError PhysicsSystem::Update(float inDeltaTime, int inCollisionStepcontext.mPhysicsSystem = this;context.mJobSystem = inJobSystem;context.mBarrier = inJobSystem->CreateBarrier();+ context.mBodyManager = &mBodyManager;context.mIslandBuilder = &mIslandBuilder;context.mStepDeltaTime = step_delta_time;context.mWarmStartImpulseRatio = warm_start_impulse_ratio;@@ -812,7 +814,7 @@ void PhysicsSystem::JobBuildIslandsFromConstraints(PhysicsUpdateContext *ioConte{#ifdef JPH_ENABLE_ASSERTS// We read constraints and positions- BodyAccess::Grant grant(BodyAccess::EAccess::None, BodyAccess::EAccess::Read);+ BodyAccess::Grant grant(BodyAccess::EAccess::Read, BodyAccess::EAccess::Read);// Can only activate bodiesBodyManager::GrantActiveBodiesAccess grant_active(true, false);@@ -1046,8 +1048,6 @@ void PhysicsSystem::sDefaultSimCollideBodyVsBody(const Body &inBody1, const Bodyvoid PhysicsSystem::ProcessBodyPair(ContactAllocator &ioContactAllocator, const BodyPair &inBodyPair){- JPH_PROFILE_FUNCTION();-// Fetch body pairBody *body1 = &mBodyManager.GetBody(inBodyPair.mBodyA);Body *body2 = &mBodyManager.GetBody(inBodyPair.mBodyB);@@ -1055,6 +1055,9 @@ void PhysicsSystem::ProcessBodyPair(ContactAllocator &ioContactAllocator, constJPH_DET_LOG("ProcessBodyPair: id1: " << inBodyPair.mBodyA << " id2: " << inBodyPair.mBodyB << " p1: " << body1->GetCenterOfMassPosition() << " p2: " << body2->GetCenterOfMassPosition() << " r1: " << body1->GetRotation() << " r2: " << body2->GetRotation());+ // Validates that a body that is sleeping has zero velocity.+ JPH_IF_ENABLE_ASSERTS(body2->ValidateMotion());+// Check for soft bodiesif (body2->IsSoftBody()){@@ -1074,9 +1077,9 @@ void PhysicsSystem::ProcessBodyPair(ContactAllocator &ioContactAllocator, conststd::swap(body1, body2);// Check if the contact points from the previous frame are reusable and if so copy them- bool pair_handled = false, constraint_created = false;+ bool pair_handled = false;if (mPhysicsSettings.mUseBodyPairContactCache && !(body1->IsCollisionCacheInvalid() || body2->IsCollisionCacheInvalid()))- mContactManager.GetContactsFromCache(ioContactAllocator, *body1, *body2, pair_handled, constraint_created);+ mContactManager.GetContactsFromCache(ioContactAllocator, *body1, *body2, pair_handled);// If the cache hasn't handled this body pair do actual collision detectionif (!pair_handled)@@ -1225,6 +1228,7 @@ void PhysicsSystem::ProcessBodyPair(ContactAllocator &ioContactAllocator, constmSimCollideBodyVsBody(*body1, *body2, transform1, transform2, settings, collector, shape_filter.GetFilter());// Add the contacts+ bool link_and_activate_bodies = true;for (ContactManifold &manifold : collector.mManifolds){// Normalize the normal (is a sum of all normals from merged manifolds)@@ -1235,7 +1239,7 @@ void PhysicsSystem::ProcessBodyPair(ContactAllocator &ioContactAllocator, constPruneContactPoints(manifold.mWorldSpaceNormal, manifold.mRelativeContactPointsOn1, manifold.mRelativeContactPointsOn2 JPH_IF_DEBUG_RENDERER(, manifold.mBaseOffset));// Actually add the contact points to the manager- constraint_created |= mContactManager.AddContactConstraint(ioContactAllocator, body_pair_handle, *body1, *body2, manifold);+ mContactManager.AddContactConstraint(ioContactAllocator, link_and_activate_bodies, body_pair_handle, *body1, *body2, manifold);}}else@@ -1307,7 +1311,7 @@ void PhysicsSystem::ProcessBodyPair(ContactAllocator &ioContactAllocator, constmanifold.mSubShapeID2 = inResult.mSubShapeID2;// Actually add the contact points to the manager- mConstraintCreated |= mSystem->mContactManager.AddContactConstraint(mContactAllocator, mBodyPairHandle, *mBody1, *mBody2, manifold);+ mSystem->mContactManager.AddContactConstraint(mContactAllocator, mLinkAndActivateBodies, mBodyPairHandle, *mBody1, *mBody2, manifold);}PhysicsSystem * mSystem;@@ -1316,14 +1320,12 @@ void PhysicsSystem::ProcessBodyPair(ContactAllocator &ioContactAllocator, constBody * mBody2;ContactConstraintManager::BodyPairHandle mBodyPairHandle;bool mValidateBodyPair = true;- bool mConstraintCreated = false;+ bool mLinkAndActivateBodies = true;};NonReductionCollideShapeCollector collector(this, ioContactAllocator, body1, body2, body_pair_handle);// Perform collision detection between the two shapesmSimCollideBodyVsBody(*body1, *body2, transform1, transform2, settings, collector, shape_filter.GetFilter());-- constraint_created = collector.mConstraintCreated;}#ifdef JPH_TRACK_SIMULATION_STATS@@ -1340,27 +1342,10 @@ void PhysicsSystem::ProcessBodyPair(ContactAllocator &ioContactAllocator, constJPH_ASSERT(body1->GetMotionType() == body2->GetMotionType());num_ticks /= 2;body1->GetMotionProperties()->GetSimulationStats().mNarrowPhaseTicks.fetch_add(num_ticks, memory_order_relaxed);- body1->GetMotionProperties()->GetSimulationStats().mNarrowPhaseTicks.fetch_add(num_ticks, memory_order_relaxed);+ body2->GetMotionProperties()->GetSimulationStats().mNarrowPhaseTicks.fetch_add(num_ticks, memory_order_relaxed);}#endif}-- // If a contact constraint was created, we need to do some extra work- if (constraint_created)- {- // Wake up sleeping bodies- BodyID body_ids[2];- int num_bodies = 0;- if (body1->IsDynamic() && !body1->IsActive())- body_ids[num_bodies++] = body1->GetID();- if (body2->IsDynamic() && !body2->IsActive())- body_ids[num_bodies++] = body2->GetID();- if (num_bodies > 0)- mBodyManager.ActivateBodies(body_ids, num_bodies);-- // Link the two bodies- mIslandBuilder.LinkBodies(body1->GetIndexInActiveBodiesInternal(), body2->GetIndexInActiveBodiesInternal());- }}void PhysicsSystem::JobFinalizeIslands(PhysicsUpdateContext *ioContext)@@ -1409,7 +1394,7 @@ void PhysicsSystem::JobSolveVelocityConstraints(PhysicsUpdateContext *ioContext,Constraint **active_constraints = ioContext->mActiveConstraints;// Only the first step to correct for the delta time difference in the previous update- float warm_start_impulse_ratio = ioStep->mIsFirst? ioContext->mWarmStartImpulseRatio : 1.0f;+ float warm_start_impulse_ratio = mPhysicsSettings.mConstraintWarmStart? (ioStep->mIsFirst? ioContext->mWarmStartImpulseRatio : 1.0f) : 0.0f;bool check_islands = true, check_split_islands = mPhysicsSettings.mUseLargeIslandSplitter;for (;;)@@ -1508,6 +1493,9 @@ void PhysicsSystem::JobSolveVelocityConstraints(PhysicsUpdateContext *ioContext,uint64 start_tick = GetProcessorTickCount();#endif+ // Convert indices to offsets so that we lose one indirection in the solver. We couldn't do this earlier as we need constraint indices to build islands.+ mContactManager.ConstraintIdxToConstraintOffset(contacts_begin, contacts_end);+// Sorting is costly but needed for a deterministic simulation, allow the user to turn this offif (mPhysicsSettings.mDeterministicSimulation){@@ -1559,15 +1547,6 @@ void PhysicsSystem::JobSolveVelocityConstraints(PhysicsUpdateContext *ioContext,stats.mVelocityConstraintTicks.fetch_add(num_ticks, memory_order_relaxed);stats.mIsLargeIsland = is_large_island;#endif-- // We processed work, loop again- continue;- }-- if (check_islands)- {- // If there are islands, we don't need to wait and can pick up new work- continue;}else if (check_split_islands){@@ -1859,8 +1838,6 @@ void PhysicsSystem::JobFindCCDContacts(const PhysicsUpdateContext *ioContext, Phvirtual void AddHit(const ShapeCastResult &inResult) override{- JPH_PROFILE_FUNCTION();-// Check if this is a possible earlier hit than the one beforefloat fraction = inResult.mFraction;if (fraction < mCCDBody.mFractionPlusSlop)@@ -1963,8 +1940,8 @@ void PhysicsSystem::JobFindCCDContacts(const PhysicsUpdateContext *ioContext, Ph}}- bool mValidateBodyPair; ///< If we still have to call the ValidateContactPoint for this body pair- bool mRejectAll; ///< Reject all further contacts between this body pair+ bool mValidateBodyPair = true; ///< If we still have to call the ValidateContactPoint for this body pair+ bool mRejectAll = false; ///< Reject all further contacts between this body pairprivate:const BodyManager & mBodyManager;@@ -1973,7 +1950,6 @@ void PhysicsSystem::JobFindCCDContacts(const PhysicsUpdateContext *ioContext, PhCCDBody & mCCDBody;ShapeCastResult & mResult;float mDeltaTime;- BodyID mAcceptedBodyID;};// Narrowphase collector@@ -2000,8 +1976,6 @@ void PhysicsSystem::JobFindCCDContacts(const PhysicsUpdateContext *ioContext, Phvirtual void AddHit(const BroadPhaseCastResult &inResult) override{- JPH_PROFILE_FUNCTION();-JPH_ASSERT(inResult.mFraction <= GetEarlyOutFraction(), "This hit should not have been passed on to the collector");// Test if we're colliding with ourselves@@ -2138,6 +2112,78 @@ void PhysicsSystem::JobFindCCDContacts(const PhysicsUpdateContext *ioContext, PhsFinalizeContactAllocator(*ioStep, contact_allocator);}+template <EMotionType Type2>+void PhysicsSystem::sSolveCCDContact(Body &ioBody1, float inInvM1, Mat44Arg inInvI1, Vec3Arg inR1PlusU, Body &ioBody2, Vec3Arg inR2, Vec3Arg inContactNormal, float inNormalVelocityBias, Vec3Arg inFrictionDirection, const ContactSettings &inContactSettings)+{+ MotionProperties *body_mp = ioBody1.GetMotionProperties();++ // Get inverse mass of body 2+ float inv_m2;+ Mat44 inv_i2;+ if constexpr (Type2 == EMotionType::Dynamic)+ {+ inv_m2 = inContactSettings.mInvMassScale2 * ioBody2.GetMotionPropertiesUnchecked()->GetInverseMassUnchecked();+ inv_i2 = inContactSettings.mInvInertiaScale2 * ioBody2.GetInverseInertia();+ }+ else+ {+ inv_m2 = 0.0f;+ inv_i2 = Mat44::sZero();+ }++ // Get velocities+ Vec3 linear_velocity1 = body_mp->GetLinearVelocity();+ Vec3 angular_velocity1 = body_mp->GetAngularVelocity();+ Vec3 linear_velocity2, angular_velocity2;+ if constexpr (Type2 != EMotionType::Static)+ {+ const MotionProperties *body2_mp = ioBody2.GetMotionPropertiesUnchecked();+ linear_velocity2 = body2_mp->GetLinearVelocity();+ angular_velocity2 = body2_mp->GetAngularVelocity();+ }+ else+ {+ linear_velocity2 = Vec3::sZero();+ angular_velocity2 = Vec3::sZero();+ }++ // Solve contact constraint+ ContactConstraintPart<EMotionType::Dynamic, EMotionType::Dynamic> contact_constraint;+ contact_constraint.SetTotalLambda(0.0f);+ contact_constraint.CalculateConstraintProperties(inInvM1, inInvI1, inR1PlusU, inv_m2, inv_i2, inR2, inContactNormal, inNormalVelocityBias);+ contact_constraint.SolveVelocityConstraint(linear_velocity1, angular_velocity1, linear_velocity2, angular_velocity2, inInvM1, inv_m2, inContactNormal, -FLT_MAX, FLT_MAX);++ // Apply friction+ if (inContactSettings.mCombinedFriction > 0.0f)+ {+ // Calculate friction direction by removing normal velocity from the relative velocity+ float friction_direction_len_sq = inFrictionDirection.LengthSq();+ if (friction_direction_len_sq > 1.0e-12f)+ {+ // Normalize friction direction+ Vec3 friction_direction = inFrictionDirection / Sqrt(friction_direction_len_sq);++ // Calculate max friction impulse+ float max_lambda_f = inContactSettings.mCombinedFriction * contact_constraint.GetTotalLambda();++ ContactConstraintPart<EMotionType::Dynamic, EMotionType::Dynamic> friction;+ friction.SetTotalLambda(0.0f);+ friction.CalculateConstraintProperties(inInvM1, inInvI1, inR1PlusU, inv_m2, inv_i2, inR2, friction_direction, 0.0f);+ friction.SolveVelocityConstraint(linear_velocity1, angular_velocity1, linear_velocity2, angular_velocity2, inInvM1, inv_m2, friction_direction, -max_lambda_f, max_lambda_f);+ }+ }++ // Write back velocities+ body_mp->SetLinearVelocityClamped(linear_velocity1);+ body_mp->SetAngularVelocityClamped(angular_velocity1);+ if constexpr (Type2 != EMotionType::Static)+ {+ MotionProperties *body2_mp = ioBody2.GetMotionProperties();+ body2_mp->SetLinearVelocityClamped(linear_velocity2);+ body2_mp->SetAngularVelocityClamped(angular_velocity2);+ }+}+void PhysicsSystem::JobResolveCCDContacts(PhysicsUpdateContext *ioContext, PhysicsUpdateContext::Step *ioStep){#ifdef JPH_ENABLE_ASSERTS@@ -2231,6 +2277,7 @@ void PhysicsSystem::JobResolveCCDContacts(PhysicsUpdateContext *ioContext, Physi// Calculate inverse mass for body 1float inv_m1 = contact_settings.mInvMassScale1 * body_mp->GetInverseMass();+ Mat44 inv_i1 = contact_settings.mInvInertiaScale1 * body1.GetInverseInertia();if (body2.IsRigidBody()){@@ -2249,41 +2296,17 @@ void PhysicsSystem::JobResolveCCDContacts(PhysicsUpdateContext *ioContext, Physielsenormal_velocity_bias = 0.0f;- // Get inverse mass of body 2- float inv_m2 = body2.GetMotionPropertiesUnchecked() != nullptr? contact_settings.mInvMassScale2 * body2.GetMotionPropertiesUnchecked()->GetInverseMassUnchecked() : 0.0f;-- // Solve contact constraint- AxisConstraintPart contact_constraint;- contact_constraint.CalculateConstraintPropertiesWithMassOverride(body1, inv_m1, contact_settings.mInvInertiaScale1, r1_plus_u, body2, inv_m2, contact_settings.mInvInertiaScale2, r2, ccd_body->mContactNormal, normal_velocity_bias);- contact_constraint.SolveVelocityConstraintWithMassOverride(body1, inv_m1, body2, inv_m2, ccd_body->mContactNormal, -FLT_MAX, FLT_MAX);-- // Apply friction- if (contact_settings.mCombinedFriction > 0.0f)- {- // Calculate friction direction by removing normal velocity from the relative velocity- Vec3 friction_direction = relative_velocity - normal_velocity * ccd_body->mContactNormal;- float friction_direction_len_sq = friction_direction.LengthSq();- if (friction_direction_len_sq > 1.0e-12f)- {- // Normalize friction direction- friction_direction /= sqrt(friction_direction_len_sq);-- // Calculate max friction impulse- float max_lambda_f = contact_settings.mCombinedFriction * contact_constraint.GetTotalLambda();-- AxisConstraintPart friction;- friction.CalculateConstraintPropertiesWithMassOverride(body1, inv_m1, contact_settings.mInvInertiaScale1, r1_plus_u, body2, inv_m2, contact_settings.mInvInertiaScale2, r2, friction_direction);- friction.SolveVelocityConstraintWithMassOverride(body1, inv_m1, body2, inv_m2, friction_direction, -max_lambda_f, max_lambda_f);- }- }-- // Clamp velocity of body 2- if (body2.IsDynamic())- {- MotionProperties *body2_mp = body2.GetMotionProperties();- body2_mp->ClampLinearVelocity();- body2_mp->ClampAngularVelocity();- }+ // Calculate direction in which the friction operates+ Vec3 friction_direction = relative_velocity - normal_velocity * ccd_body->mContactNormal;++ // Dispatch to the correct form+ using DispatchFunc = void (*)(Body &, float, Mat44Arg, Vec3Arg, Body &, Vec3Arg, Vec3Arg, float, Vec3Arg, const ContactSettings &);+ static const DispatchFunc table[3] = {+ sSolveCCDContact<EMotionType::Static>,+ sSolveCCDContact<EMotionType::Kinematic>,+ sSolveCCDContact<EMotionType::Dynamic>+ };+ table[(int)body2.GetMotionType()](body1, inv_m1, inv_i1, r1_plus_u, body2, r2, ccd_body->mContactNormal, normal_velocity_bias, friction_direction, contact_settings);}else{@@ -2324,12 +2347,14 @@ void PhysicsSystem::JobResolveCCDContacts(PhysicsUpdateContext *ioContext, Physi// Calculate resulting velocity change (the math here is similar to AxisConstraintPart but without an inertia term for body 2 as we treat it as a point mass)Vec3 r1_plus_u_x_n = r1_plus_u.Cross(ccd_body->mContactNormal);- Vec3 invi1_r1_plus_u_x_n = contact_settings.mInvInertiaScale1 * body1.GetInverseInertia().Multiply3x3(r1_plus_u_x_n);+ Vec3 invi1_r1_plus_u_x_n = inv_i1.Multiply3x3(r1_plus_u_x_n);float jv = r1_plus_u_x_n.Dot(body_mp->GetAngularVelocity()) - normal_velocity - normal_velocity_bias;float inv_effective_mass = inv_m1 + inv_m2 + invi1_r1_plus_u_x_n.Dot(r1_plus_u_x_n);float lambda = jv / inv_effective_mass;body_mp->SubLinearVelocityStep((lambda * inv_m1) * ccd_body->mContactNormal);+ body_mp->ClampLinearVelocity();body_mp->SubAngularVelocityStep(lambda * invi1_r1_plus_u_x_n);+ body_mp->ClampAngularVelocity();Vec3 delta_v2 = inv_body2_transform.Multiply3x3(lambda * ccd_body->mContactNormal);vtx0.mVelocity += delta_v2 * vtx0.mInvMass;vtx1.mVelocity += delta_v2 * vtx1.mInvMass;@@ -2349,10 +2374,6 @@ void PhysicsSystem::JobResolveCCDContacts(PhysicsUpdateContext *ioContext, Physi}}- // Clamp velocity of body 1- body_mp->ClampLinearVelocity();- body_mp->ClampAngularVelocity();-// Activate the 2nd body if it is not already activeif (body2.IsDynamic() && !body2.IsActive()){@@ -2663,15 +2684,6 @@ void PhysicsSystem::JobSolvePositionConstraints(PhysicsUpdateContext *ioContext,// Accumulate time spent in updating bounding boxstats.mUpdateBoundsTicks.fetch_add(GetProcessorTickCount() - solve_position_ticks, memory_order_relaxed);#endif-- // We processed work, loop again- continue;- }-- if (check_islands)- {- // If there are islands, we don't need to wait and can pick up new work- continue;}else if (check_split_islands){diff --git a/thirdparty/jolt_physics/Jolt/Physics/PhysicsSystem.h b/thirdparty/jolt_physics/Jolt/Physics/PhysicsSystem.hindex cff88d279c9..b244a516079 100644--- a/thirdparty/jolt_physics/Jolt/Physics/PhysicsSystem.h+++ b/thirdparty/jolt_physics/Jolt/Physics/PhysicsSystem.h@@ -200,6 +200,9 @@ public:/// Returns a locking interface that locks the body so other threads cannot modify it.inline const BodyLockInterfaceLocking & GetBodyLockInterface() const { return mBodyLockInterfaceLocking; }+ /// Return the BroadPhaseLayerInterface that this class has been initialized with+ const BroadPhaseLayerInterface &GetBroadPhaseLayerInterface() const { return mBodyManager.GetBroadPhaseLayerInterface(); }+/// Broadphase layer filter that decides if two objects can collide, this was passed to the Init function.const ObjectVsBroadPhaseLayerFilter &GetObjectVsBroadPhaseLayerFilter() const { return *mObjectVsBroadPhaseLayerFilter; }@@ -305,6 +308,10 @@ private:/// Called at the end of JobSolveVelocityConstraints to check if bodies need to go to sleep and to update their bounding box in the broadphasevoid CheckSleepAndUpdateBounds(uint32 inIslandIndex, const PhysicsUpdateContext *ioContext, const PhysicsUpdateContext::Step *ioStep, BodiesToSleep &ioBodiesToSleep);+ /// Helper function that solves the velocity of a CCD contact+ template <EMotionType Type2>+ static void sSolveCCDContact(Body &ioBody1, float inInvM1, Mat44Arg inInvI1, Vec3Arg inR1PlusU, Body &ioBody2, Vec3Arg inR2, Vec3Arg inContactNormal, float inNormalVelocityBias, Vec3Arg inFrictionDirection, const ContactSettings &inContactSettings);+/// Number of constraints to process at once in JobDetermineActiveConstraintsstatic constexpr int cDetermineActiveConstraintsBatchSize = 64;diff --git a/thirdparty/jolt_physics/Jolt/Physics/PhysicsUpdateContext.h b/thirdparty/jolt_physics/Jolt/Physics/PhysicsUpdateContext.hindex c0987a2f73c..c25f6ad22ab 100644--- a/thirdparty/jolt_physics/Jolt/Physics/PhysicsUpdateContext.h+++ b/thirdparty/jolt_physics/Jolt/Physics/PhysicsUpdateContext.h@@ -14,6 +14,7 @@JPH_NAMESPACE_BEGINclass PhysicsSystem;+class BodyManager;class IslandBuilder;class Constraint;class TempAllocator;@@ -163,6 +164,7 @@ public:BodyPair * mBodyPairs = nullptr; ///< A list of body pairs found by the broadphase+ BodyManager * mBodyManager; ///< Keeps track of all bodies in the simulationIslandBuilder * mIslandBuilder; ///< Keeps track of connected bodies and builds islands for multithreaded velocity/position updateSteps mSteps;diff --git a/thirdparty/jolt_physics/Jolt/Physics/Ragdoll/Ragdoll.cpp b/thirdparty/jolt_physics/Jolt/Physics/Ragdoll/Ragdoll.cppindex 660eb4da9f0..306e40aaf39 100644--- a/thirdparty/jolt_physics/Jolt/Physics/Ragdoll/Ragdoll.cpp+++ b/thirdparty/jolt_physics/Jolt/Physics/Ragdoll/Ragdoll.cpp@@ -14,8 +14,7 @@#include <Jolt/Physics/Collision/CollideShape.h>#include <Jolt/Physics/Collision/CollisionDispatch.h>#include <Jolt/ObjectStream/TypeDeclarations.h>-#include <Jolt/Core/StreamIn.h>-#include <Jolt/Core/StreamOut.h>+#include <Jolt/Core/StreamUtils.h>JPH_NAMESPACE_BEGIN@@ -680,6 +679,50 @@ void Ragdoll::DriveToPoseUsingMotors(const SkeletonPose &inPose)}}+void Ragdoll::DriveToPoseUsingMotors(const SkeletonPose &inPrevPose, const SkeletonPose &inPose, float inDeltaTime)+{+ JPH_ASSERT(inPrevPose.GetSkeleton() == mRagdollSettings->mSkeleton);+ JPH_ASSERT(inPose.GetSkeleton() == mRagdollSettings->mSkeleton);+ JPH_ASSERT(inDeltaTime > 0.0f);++ // Move bodies into the correct position using constraints+ for (int i = 0; i < (int)inPose.GetJointMatrices().size(); ++i)+ {+ int constraint_idx = mRagdollSettings->GetConstraintIndexForBodyIndex(i);+ if (constraint_idx >= 0)+ {+ // Get desired rotation of this body relative to its parent+ const SkeletalAnimation::JointState &prev_joint_state = inPrevPose.GetJoint(i);+ const SkeletalAnimation::JointState &joint_state = inPose.GetJoint(i);++ // Calculate the angular velocity needed to get from the previous pose to the current pose in the given delta time in body 1 space+ Vec3 angular_velocity = (joint_state.mRotation * prev_joint_state.mRotation.Conjugated()).GetAngularVelocity(inDeltaTime);++ // Drive constraint to target+ TwoBodyConstraint *constraint = mConstraints[constraint_idx];+ EConstraintSubType sub_type = constraint->GetSubType();+ if (sub_type == EConstraintSubType::SwingTwist)+ {+ SwingTwistConstraint *st_constraint = static_cast<SwingTwistConstraint *>(constraint);+ st_constraint->SetSwingMotorState(EMotorState::PositionAndVelocity);+ st_constraint->SetTwistMotorState(EMotorState::PositionAndVelocity);+ Quat body1_to_body2 = constraint->GetBody2()->GetRotation().Conjugated() * constraint->GetBody1()->GetRotation();+ st_constraint->SetTargetAngularVelocityBS(body1_to_body2 * angular_velocity);+ st_constraint->SetTargetOrientationBS(joint_state.mRotation);+ }+ else if (sub_type == EConstraintSubType::Hinge)+ {+ HingeConstraint *h_constraint = static_cast<HingeConstraint *>(constraint);+ h_constraint->SetMotorState(EMotorState::PositionAndVelocity);+ h_constraint->SetTargetAngularVelocity(h_constraint->GetLocalSpaceHingeAxis1().Dot(angular_velocity));+ h_constraint->SetTargetOrientationBS(joint_state.mRotation);+ }+ else+ JPH_ASSERT(false, "Constraint type not implemented!");+ }+ }+}+void Ragdoll::SetLinearAndAngularVelocity(Vec3Arg inLinearVelocity, Vec3Arg inAngularVelocity, bool inLockBodies){BodyInterface &bi = sRagdollGetBodyInterface(mSystem, inLockBodies);diff --git a/thirdparty/jolt_physics/Jolt/Physics/Ragdoll/Ragdoll.h b/thirdparty/jolt_physics/Jolt/Physics/Ragdoll/Ragdoll.hindex ff8e5232123..0b69133bd37 100644--- a/thirdparty/jolt_physics/Jolt/Physics/Ragdoll/Ragdoll.h+++ b/thirdparty/jolt_physics/Jolt/Physics/Ragdoll/Ragdoll.h@@ -183,9 +183,15 @@ public:/// Lower level version of DriveToPoseUsingKinematics that directly takes the world space joint matricesvoid DriveToPoseUsingKinematics(RVec3Arg inRootOffset, const Mat44 *inJointMatrices, float inDeltaTime, bool inLockBodies = true);- /// Drive the ragdoll to a specific pose by activating the motors on each constraint+ /// Drive the ragdoll to a specific pose by activating the motors on each constraint.void DriveToPoseUsingMotors(const SkeletonPose &inPose);+ /// Drive the ragdoll to a specific pose by activating the motors on each constraint. Drives both to target position and velocity.+ /// @param inPrevPose The previous pose of the ragdoll, used to calculate the target velocity for each motor+ /// @param inPose The target pose of the ragdoll, used to calculate the target position for each motor+ /// @param inDeltaTime The time between inPrevPose and inPose, used to calculate the target velocity for each motor+ void DriveToPoseUsingMotors(const SkeletonPose &inPrevPose, const SkeletonPose &inPose, float inDeltaTime);+/// Control the linear and velocity of all bodies in the ragdollvoid SetLinearAndAngularVelocity(Vec3Arg inLinearVelocity, Vec3Arg inAngularVelocity, bool inLockBodies = true);diff --git a/thirdparty/jolt_physics/Jolt/Physics/SoftBody/SoftBodyCreationSettings.cpp b/thirdparty/jolt_physics/Jolt/Physics/SoftBody/SoftBodyCreationSettings.cppindex d6a64ad0aac..6eb8271974a 100644--- a/thirdparty/jolt_physics/Jolt/Physics/SoftBody/SoftBodyCreationSettings.cpp+++ b/thirdparty/jolt_physics/Jolt/Physics/SoftBody/SoftBodyCreationSettings.cpp@@ -6,8 +6,7 @@#include <Jolt/Physics/SoftBody/SoftBodyCreationSettings.h>#include <Jolt/ObjectStream/TypeDeclarations.h>-#include <Jolt/Core/StreamIn.h>-#include <Jolt/Core/StreamOut.h>+#include <Jolt/Core/StreamUtils.h>JPH_NAMESPACE_BEGINdiff --git a/thirdparty/jolt_physics/Jolt/Physics/SoftBody/SoftBodyCreationSettings.h b/thirdparty/jolt_physics/Jolt/Physics/SoftBody/SoftBodyCreationSettings.hindex 4a617c11be8..b1911c73ce3 100644--- a/thirdparty/jolt_physics/Jolt/Physics/SoftBody/SoftBodyCreationSettings.h+++ b/thirdparty/jolt_physics/Jolt/Physics/SoftBody/SoftBodyCreationSettings.h@@ -8,7 +8,7 @@#include <Jolt/Physics/Collision/ObjectLayer.h>#include <Jolt/Physics/Collision/CollisionGroup.h>#include <Jolt/ObjectStream/SerializableObject.h>-#include <Jolt/Core/StreamUtils.h>+#include <Jolt/Core/ObjectToIDMap.h>JPH_NAMESPACE_BEGINdiff --git a/thirdparty/jolt_physics/Jolt/Physics/SoftBody/SoftBodyMotionProperties.cpp b/thirdparty/jolt_physics/Jolt/Physics/SoftBody/SoftBodyMotionProperties.cppindex 327145ed466..e38d5de7ed4 100644--- a/thirdparty/jolt_physics/Jolt/Physics/SoftBody/SoftBodyMotionProperties.cpp+++ b/thirdparty/jolt_physics/Jolt/Physics/SoftBody/SoftBodyMotionProperties.cpp@@ -413,7 +413,7 @@ void SoftBodyMotionProperties::ApplyDihedralBendConstraints(const SoftBodyUpdate// Calculate constraint equation// As per "Strain Based Dynamics" Appendix A we need to negate the gradients when (n1 x n2) . e > 0, instead we make sure that the sign of the constraint equation is correctfloat sign = Sign(n2.Cross(n1).Dot(e));- float d = n1.Dot(n2) / sqrt(n1_len_sq_n2_len_sq);+ float d = n1.Dot(n2) / Sqrt(n1_len_sq_n2_len_sq);float c = sign * ACosApproximate(d) - b->mInitialAngle;// Ensure the range is -PI to PI@@ -545,7 +545,7 @@ void SoftBodyMotionProperties::ApplySkinConstraints(const SoftBodyUpdateContextif (delta_len_sq < Square(s->mBackStopRadius)){// Push the vertex to the surface of the back stop sphere- float delta_len = sqrt(delta_len_sq);+ float delta_len = Sqrt(delta_len_sq);vertex.mPosition = delta_len > 0.0f?center + delta * (s->mBackStopRadius / delta_len): center + skin_state.mNormal * s->mBackStopRadius;@@ -559,7 +559,7 @@ void SoftBodyMotionProperties::ApplySkinConstraints(const SoftBodyUpdateContextfloat delta_len_sq = delta.LengthSq();float max_distance_sq = Square(max_distance);if (delta_len_sq > max_distance_sq)- vertex.mPosition = skin_pos + delta * sqrt(max_distance_sq / delta_len_sq);+ vertex.mPosition = skin_pos + delta * Sqrt(max_distance_sq / delta_len_sq);}}else@@ -693,7 +693,7 @@ void SoftBodyMotionProperties::ApplyLRAConstraints(uint inStartIndex, uint inEndVec3 delta = vertex1.mPosition - x0;float delta_len_sq = delta.LengthSq();if (delta_len_sq > Square(lra->mMaxDistance))- vertex1.mPosition = x0 + delta * lra->mMaxDistance / sqrt(delta_len_sq);+ vertex1.mPosition = x0 + delta * lra->mMaxDistance / Sqrt(delta_len_sq);}}@@ -858,7 +858,7 @@ void SoftBodyMotionProperties::UpdateSoftBodyState(SoftBodyUpdateContext &ioCont// Clamp if velocity is too highif (v_sq > max_linear_velocity_sq)- v.mVelocity *= sqrt(max_linear_velocity_sq / v_sq);+ v.mVelocity *= Sqrt(max_linear_velocity_sq / v_sq);// Calculate local linear/angular velocitylinear_velocity += v.mVelocity;diff --git a/thirdparty/jolt_physics/Jolt/Physics/SoftBody/SoftBodySharedSettings.cpp b/thirdparty/jolt_physics/Jolt/Physics/SoftBody/SoftBodySharedSettings.cppindex 403aee1d4c4..514142f5cf1 100644--- a/thirdparty/jolt_physics/Jolt/Physics/SoftBody/SoftBodySharedSettings.cpp+++ b/thirdparty/jolt_physics/Jolt/Physics/SoftBody/SoftBodySharedSettings.cpp@@ -7,10 +7,8 @@#include <Jolt/Physics/SoftBody/SoftBodySharedSettings.h>#include <Jolt/Physics/SoftBody/SoftBodyUpdateContext.h>#include <Jolt/ObjectStream/TypeDeclarations.h>-#include <Jolt/Core/StreamIn.h>-#include <Jolt/Core/StreamOut.h>+#include <Jolt/Core/StreamUtils.h>#include <Jolt/Core/QuickSort.h>-#include <Jolt/Core/UnorderedMap.h>#include <Jolt/Core/UnorderedSet.h>#include <Jolt/Core/BinaryHeap.h>@@ -524,7 +522,7 @@ void SoftBodySharedSettings::CalculateBendConstraintConstants()// Normals of both trianglesVec3 n1 = e0.Cross(e1);Vec3 n2 = e2.Cross(e0);- float denom = sqrt(n1.LengthSq() * n2.LengthSq());+ float denom = Sqrt(n1.LengthSq() * n2.LengthSq());if (denom < 1.0e-12f)b.mInitialAngle = 0.0f;elsediff --git a/thirdparty/jolt_physics/Jolt/Physics/SoftBody/SoftBodySharedSettings.h b/thirdparty/jolt_physics/Jolt/Physics/SoftBody/SoftBodySharedSettings.hindex c12d5cac40c..fdee0666cca 100644--- a/thirdparty/jolt_physics/Jolt/Physics/SoftBody/SoftBodySharedSettings.h+++ b/thirdparty/jolt_physics/Jolt/Physics/SoftBody/SoftBodySharedSettings.h@@ -6,7 +6,7 @@#include <Jolt/Core/Reference.h>#include <Jolt/Physics/Collision/PhysicsMaterial.h>-#include <Jolt/Core/StreamUtils.h>+#include <Jolt/Core/ObjectToIDMap.h>JPH_NAMESPACE_BEGINdiff --git a/thirdparty/jolt_physics/Jolt/Physics/Vehicle/VehicleCollisionTester.cpp b/thirdparty/jolt_physics/Jolt/Physics/Vehicle/VehicleCollisionTester.cppindex 11756e2934f..f126e922969 100644--- a/thirdparty/jolt_physics/Jolt/Physics/Vehicle/VehicleCollisionTester.cpp+++ b/thirdparty/jolt_physics/Jolt/Physics/Vehicle/VehicleCollisionTester.cpp@@ -346,7 +346,7 @@ void VehicleCollisionTesterCastCylinder::PredictContactProperties(PhysicsSystem// Get the support point of this normal in local space of the cylinder// See CylinderShape::Cylinder::GetSupportfloat x = inverse_local_normal.GetX(), y = inverse_local_normal.GetY(), z = inverse_local_normal.GetZ();- float o = sqrt(Square(x) + Square(z));+ float o = Sqrt(Square(x) + Square(z));Vec3 support_point;if (o > 0.0f)support_point = Vec3((radius * x) / o, Sign(y) * half_width, (radius * z) / o);diff --git a/thirdparty/jolt_physics/Jolt/Physics/Vehicle/VehicleConstraint.cpp b/thirdparty/jolt_physics/Jolt/Physics/Vehicle/VehicleConstraint.cppindex 1d84ea3eb00..cf961ec3d14 100644--- a/thirdparty/jolt_physics/Jolt/Physics/Vehicle/VehicleConstraint.cpp+++ b/thirdparty/jolt_physics/Jolt/Physics/Vehicle/VehicleConstraint.cpp@@ -153,6 +153,10 @@ void VehicleConstraint::OnStep(const PhysicsStepListenerContext &inContext){JPH_PROFILE_FUNCTION();+ // Step only if we're in the broadphase+ if (!mBody->IsInBroadPhase())+ return;+// Callback to higher-level systems. We do it before PreCollide, in case steering changes.if (mPreStepCallback != nullptr)mPreStepCallback(*this, inContext);@@ -362,17 +366,16 @@ void VehicleConstraint::BuildIslands(uint32 inConstraintIndex, IslandBuilder &ioinBodyManager.ActivateBodies(body_ids, num_bodies);}- // Link the bodies into the same island- uint32 min_active_index = Body::cInactiveIndex;+ // Link dynamic bodies into the same island as the vehiclefor (int i = 0; i < num_bodies; ++i){const Body &body = inBodyManager.GetBody(body_ids[i]);- min_active_index = min(min_active_index, body.GetIndexInActiveBodiesInternal());- ioBuilder.LinkBodies(mBody->GetIndexInActiveBodiesInternal(), body.GetIndexInActiveBodiesInternal());+ if (body.IsDynamic())+ ioBuilder.LinkBodies(mBody->GetIndexInActiveBodiesInternal(), body.GetIndexInActiveBodiesInternal());}- // Link the constraint in the island- ioBuilder.LinkConstraint(inConstraintIndex, mBody->GetIndexInActiveBodiesInternal(), min_active_index);+ // Link the vehicle constraint to the car body+ ioBuilder.LinkConstraint(inConstraintIndex, mBody->GetIndexInActiveBodiesInternal());}uint VehicleConstraint::BuildIslandSplits(LargeIslandSplitter &ioSplitter) const@@ -437,7 +440,8 @@ void VehicleConstraint::SetupVelocityConstraint(float inDeltaTime)if (settings->mSuspensionMaxLength > settings->mSuspensionMinLength){float stiffness, damping;- if (settings->mSuspensionSpring.mMode == ESpringMode::FrequencyAndDamping)+ ESpringMode mode = settings->mSuspensionSpring.mMode;+ if (mode == ESpringMode::FrequencyAndDamping || mode == ESpringMode::MassNormalizedStiffnessAndDamping){// Calculate effective mass based on vehicle configuration (the stiffness of the spring should not be affected by the dynamics of the vehicle): K = 1 / (J M^-1 J^T)// Note that if no suspension force point is supplied we don't know where the force is applied so we assume it is applied at average suspension length@@ -446,10 +450,19 @@ void VehicleConstraint::SetupVelocityConstraint(float inDeltaTime)const MotionProperties *mp = mBody->GetMotionProperties();float effective_mass = 1.0f / (mp->GetInverseMass() + force_point_x_neg_up.Dot(mp->GetLocalSpaceInverseInertia().Multiply3x3(force_point_x_neg_up)));- // Convert frequency and damping to stiffness and damping- float omega = 2.0f * JPH_PI * settings->mSuspensionSpring.mFrequency;- stiffness = effective_mass * Square(omega);- damping = 2.0f * effective_mass * settings->mSuspensionSpring.mDamping * omega;+ if (mode == ESpringMode::FrequencyAndDamping)+ {+ // Convert frequency and damping to stiffness and damping+ float omega = 2.0f * JPH_PI * settings->mSuspensionSpring.mFrequency;+ stiffness = effective_mass * Square(omega);+ damping = 2.0f * effective_mass * settings->mSuspensionSpring.mDamping * omega;+ }+ else+ {+ // Multiply only by effective mass+ stiffness = effective_mass * settings->mSuspensionSpring.mStiffness;+ damping = effective_mass * settings->mSuspensionSpring.mDamping;+ }}else{diff --git a/thirdparty/jolt_physics/Jolt/Physics/Vehicle/VehicleConstraint.h b/thirdparty/jolt_physics/Jolt/Physics/Vehicle/VehicleConstraint.hindex 3c1ac78ce60..7aeca47dc26 100644--- a/thirdparty/jolt_physics/Jolt/Physics/Vehicle/VehicleConstraint.h+++ b/thirdparty/jolt_physics/Jolt/Physics/Vehicle/VehicleConstraint.h@@ -183,7 +183,7 @@ public:uint GetNumStepsBetweenCollisionTestInactive() const { return mNumStepsBetweenCollisionTestInactive; }// Generic interface of a constraint- virtual bool IsActive() const override { return mIsActive && Constraint::IsActive(); }+ virtual bool IsActive() const override { return mIsActive && mBody->IsInBroadPhase() && Constraint::IsActive(); }virtual void NotifyShapeChanged(const BodyID &inBodyID, Vec3Arg inDeltaCOM) override { /* Do nothing */ }virtual void SetupVelocityConstraint(float inDeltaTime) override;virtual void ResetWarmStart() override;@@ -239,8 +239,8 @@ private:{float body_friction = inBody2.GetFriction();- ioLongitudinalFriction = sqrt(ioLongitudinalFriction * body_friction);- ioLateralFriction = sqrt(ioLateralFriction * body_friction);+ ioLongitudinalFriction = Sqrt(ioLongitudinalFriction * body_friction);+ ioLateralFriction = Sqrt(ioLateralFriction * body_friction);};// Callbacksdiff --git a/thirdparty/jolt_physics/Jolt/RegisterTypes.cpp b/thirdparty/jolt_physics/Jolt/RegisterTypes.cppindex e343dd2fa70..e89600cc6eb 100644--- a/thirdparty/jolt_physics/Jolt/RegisterTypes.cpp+++ b/thirdparty/jolt_physics/Jolt/RegisterTypes.cpp@@ -59,6 +59,7 @@ JPH_DECLARE_RTTI_WITH_NAMESPACE_FOR_FACTORY(JPH_EXPORT, JPH, GroupFilter)JPH_DECLARE_RTTI_WITH_NAMESPACE_FOR_FACTORY(JPH_EXPORT, JPH, GroupFilterTable)JPH_DECLARE_RTTI_WITH_NAMESPACE_FOR_FACTORY(JPH_EXPORT, JPH, BodyCreationSettings)JPH_DECLARE_RTTI_WITH_NAMESPACE_FOR_FACTORY(JPH_EXPORT, JPH, SoftBodyCreationSettings)+JPH_DECLARE_RTTI_WITH_NAMESPACE_FOR_FACTORY(JPH_EXPORT, JPH, HairSettings)JPH_NAMESPACE_BEGINdiff --git a/thirdparty/jolt_physics/Jolt/Renderer/DebugRenderer.cpp b/thirdparty/jolt_physics/Jolt/Renderer/DebugRenderer.cppindex e95eff801d9..8dd0ff339fb 100644--- a/thirdparty/jolt_physics/Jolt/Renderer/DebugRenderer.cpp+++ b/thirdparty/jolt_physics/Jolt/Renderer/DebugRenderer.cpp@@ -635,15 +635,15 @@ AABox DebugRenderer::sCalculateBounds(const Vertex *inVertices, int inVertexCounreturn bounds;}-DebugRenderer::Batch DebugRenderer::CreateTriangleBatch(const VertexList &inVertices, const IndexedTriangleNoMaterialList &inTriangles)+DebugRenderer::Batch DebugRenderer::CreateTriangleBatch(const Float3 *inVertices, int inVertexCount, const IndexedTriangleNoMaterial *inTriangles, int inTriangleCount){JPH_PROFILE_FUNCTION();Array<Vertex> vertices;// Create render vertices- vertices.resize(inVertices.size());- for (size_t v = 0; v < inVertices.size(); ++v)+ vertices.resize(inVertexCount);+ for (int v = 0; v < inVertexCount; ++v){vertices[v].mPosition = inVertices[v];vertices[v].mNormal = Float3(0, 0, 0);@@ -652,7 +652,7 @@ DebugRenderer::Batch DebugRenderer::CreateTriangleBatch(const VertexList &inVert}// Calculate normals- for (size_t i = 0; i < inTriangles.size(); ++i)+ for (int i = 0; i < inTriangleCount; ++i){const IndexedTriangleNoMaterial &tri = inTriangles[i];@@ -671,7 +671,7 @@ DebugRenderer::Batch DebugRenderer::CreateTriangleBatch(const VertexList &inVertfor (size_t i = 0; i < vertices.size(); ++i)Vec3::sLoadFloat3Unsafe(vertices[i].mNormal).Normalized().StoreFloat3(&vertices[i].mNormal);- return CreateTriangleBatch(&vertices[0], (int)vertices.size(), &inTriangles[0].mIdx[0], (int)(3 * inTriangles.size()));+ return CreateTriangleBatch(&vertices[0], (int)vertices.size(), &inTriangles[0].mIdx[0], 3 * inTriangleCount);}DebugRenderer::Batch DebugRenderer::CreateTriangleBatchForConvex(SupportFunction inGetSupport, int inLevel, AABox *outBounds)@@ -913,7 +913,7 @@ void DebugRenderer::DrawSwingConeLimits(RMat44Arg inMatrix, float inSwingYHalfAn// Calculate the corresponding z value of the quaternionfloat z_sq = e1_sq - e1_sq / e2_sq * Square(y);- z = z_sq <= 0.0f? 0.0f : sqrt(z_sq);+ z = z_sq <= 0.0f? 0.0f : Sqrt(z_sq);}else{@@ -922,7 +922,7 @@ void DebugRenderer::DrawSwingConeLimits(RMat44Arg inMatrix, float inSwingYHalfAn// Calculate the corresponding y value of the quaternionfloat y_sq = e2_sq - e2_sq / e1_sq * Square(z);- y = y_sq <= 0.0f? 0.0f : sqrt(y_sq);+ y = y_sq <= 0.0f? 0.0f : Sqrt(y_sq);}// If we're tracing the opposite side, flip the values@@ -934,7 +934,7 @@ void DebugRenderer::DrawSwingConeLimits(RMat44Arg inMatrix, float inSwingYHalfAn// Create quaternionVec3 q_xyz(0, y, z);- float w = sqrt(1.0f - q_xyz.LengthSq());+ float w = Sqrt(1.0f - q_xyz.LengthSq());Quat q(Vec4(q_xyz, w));// Store vertexdiff --git a/thirdparty/jolt_physics/Jolt/Renderer/DebugRenderer.h b/thirdparty/jolt_physics/Jolt/Renderer/DebugRenderer.hindex a311d1a587e..fbb2a47406a 100644--- a/thirdparty/jolt_physics/Jolt/Renderer/DebugRenderer.h+++ b/thirdparty/jolt_physics/Jolt/Renderer/DebugRenderer.h@@ -253,7 +253,8 @@ public:virtual Batch CreateTriangleBatch(const Vertex *inVertices, int inVertexCount, const uint32 *inIndices, int inIndexCount) = 0;Batch CreateTriangleBatch(const Array<Triangle> &inTriangles) { return CreateTriangleBatch(inTriangles.empty()? nullptr : &inTriangles[0], int(inTriangles.size())); }Batch CreateTriangleBatch(const Array<Vertex> &inVertices, const Array<uint32> &inIndices) { return CreateTriangleBatch(inVertices.empty()? nullptr : &inVertices[0], int(inVertices.size()), inIndices.empty()? nullptr : &inIndices[0], int(inIndices.size())); }- Batch CreateTriangleBatch(const VertexList &inVertices, const IndexedTriangleNoMaterialList &inTriangles);+ Batch CreateTriangleBatch(const Float3 *inVertices, int inVertexCount, const IndexedTriangleNoMaterial *inTriangles, int inTriangleCount);+ Batch CreateTriangleBatch(const VertexList &inVertices, const IndexedTriangleNoMaterialList &inTriangles) { return CreateTriangleBatch(inVertices.data(), (int)inVertices.size(), inTriangles.data(), (int)inTriangles.size()); }/// Create a primitive for a convex shape using its support functionusing SupportFunction = function<Vec3 (Vec3Arg inDirection)>;diff --git a/thirdparty/jolt_physics/Jolt/Skeleton/SkeletalAnimation.h b/thirdparty/jolt_physics/Jolt/Skeleton/SkeletalAnimation.hindex a5769f14c3c..f1db8efb967 100644--- a/thirdparty/jolt_physics/Jolt/Skeleton/SkeletalAnimation.h+++ b/thirdparty/jolt_physics/Jolt/Skeleton/SkeletalAnimation.h@@ -6,12 +6,13 @@#include <Jolt/Core/Reference.h>#include <Jolt/Core/Result.h>-#include <Jolt/Core/StreamUtils.h>#include <Jolt/ObjectStream/SerializableObject.h>JPH_NAMESPACE_BEGINclass SkeletonPose;+class StreamIn;+class StreamOut;/// Resource for a skinned animationclass JPH_EXPORT SkeletalAnimation : public RefTarget<SkeletalAnimation>diff --git a/thirdparty/jolt_physics/patches/0001-backport-upstream-commit-ee3725250.patch b/thirdparty/jolt_physics/patches/0001-backport-upstream-commit-ee3725250.patchdeleted file mode 100644index 466ca097082..00000000000--- a/thirdparty/jolt_physics/patches/0001-backport-upstream-commit-ee3725250.patch+++ /dev/null@@ -1,53 +0,0 @@-diff --git a/thirdparty/jolt_physics/Jolt/Physics/Collision/CastConvexVsTriangles.cpp b/thirdparty/jolt_physics/Jolt/Physics/Collision/CastConvexVsTriangles.cpp-index e8a8c21459..4fb6c58c18 100644---- a/thirdparty/jolt_physics/Jolt/Physics/Collision/CastConvexVsTriangles.cpp-+++ b/thirdparty/jolt_physics/Jolt/Physics/Collision/CastConvexVsTriangles.cpp-@@ -92,11 +92,14 @@ void CastConvexVsTriangles::Cast(Vec3Arg inV0, Vec3Arg inV1, Vec3Arg inV2, uint8- static_cast<const ConvexShape *>(mShapeCast.mShape)->GetSupportingFace(SubShapeID(), transform_1_to_2.Multiply3x3Transposed(-contact_normal), mShapeCast.mScale, mCenterOfMassTransform2 * transform_1_to_2, result.mShape1Face);-- // Get face of the triangle-- triangle.GetSupportingFace(contact_normal, result.mShape2Face);-+ result.mShape2Face.resize(3);-+ result.mShape2Face[0] = mCenterOfMassTransform2 * v0;-+ result.mShape2Face[1] = mCenterOfMassTransform2 * v1;-+ result.mShape2Face[2] = mCenterOfMassTransform2 * v2;--- // Convert to world space-- for (Vec3 &p : result.mShape2Face)-- p = mCenterOfMassTransform2 * p;-+ // When inside out, we need to swap the triangle winding-+ if (mScaleSign < 0.0f)-+ std::swap(result.mShape2Face[1], result.mShape2Face[2]);- }-- JPH_IF_TRACK_NARROWPHASE_STATS(TrackNarrowPhaseCollector track;)-diff --git a/thirdparty/jolt_physics/Jolt/Physics/Collision/CollideConvexVsTriangles.cpp b/thirdparty/jolt_physics/Jolt/Physics/Collision/CollideConvexVsTriangles.cpp-index e03659454d..05c21eebfa 100644---- a/thirdparty/jolt_physics/Jolt/Physics/Collision/CollideConvexVsTriangles.cpp-+++ b/thirdparty/jolt_physics/Jolt/Physics/Collision/CollideConvexVsTriangles.cpp-@@ -145,6 +145,10 @@ void CollideConvexVsTriangles::Collide(Vec3Arg inV0, Vec3Arg inV1, Vec3Arg inV2,- result.mShape2Face[0] = mTransform1 * v0;- result.mShape2Face[1] = mTransform1 * v1;- result.mShape2Face[2] = mTransform1 * v2;-+-+ // When inside out, we need to swap the triangle winding-+ if (mScaleSign2 < 0.0f)-+ std::swap(result.mShape2Face[1], result.mShape2Face[2]);- }-- // Notify the collector-diff --git a/thirdparty/jolt_physics/Jolt/Physics/Collision/CollideSphereVsTriangles.cpp b/thirdparty/jolt_physics/Jolt/Physics/Collision/CollideSphereVsTriangles.cpp-index 18441ea73b..566efb38ae 100644---- a/thirdparty/jolt_physics/Jolt/Physics/Collision/CollideSphereVsTriangles.cpp-+++ b/thirdparty/jolt_physics/Jolt/Physics/Collision/CollideSphereVsTriangles.cpp-@@ -111,6 +111,10 @@ void CollideSphereVsTriangles::Collide(Vec3Arg inV0, Vec3Arg inV1, Vec3Arg inV2,- result.mShape2Face[0] = mTransform2 * (mSphereCenterIn2 + v0);- result.mShape2Face[1] = mTransform2 * (mSphereCenterIn2 + v1);- result.mShape2Face[2] = mTransform2 * (mSphereCenterIn2 + v2);-+-+ // When inside out, we need to swap the triangle winding-+ if (mScaleSign2 < 0.0f)-+ std::swap(result.mShape2Face[1], result.mShape2Face[2]);- }-- // Notify the collectordiff --git a/thirdparty/jolt_physics/patches/0002-backport-upstream-commit-bc7f1fb8c.patch b/thirdparty/jolt_physics/patches/0002-backport-upstream-commit-bc7f1fb8c.patchdeleted file mode 100644index dde2762c475..00000000000--- a/thirdparty/jolt_physics/patches/0002-backport-upstream-commit-bc7f1fb8c.patch+++ /dev/null@@ -1,236 +0,0 @@-diff --git a/thirdparty/jolt_physics/Jolt/Physics/Constraints/ContactConstraintManager.cpp b/thirdparty/jolt_physics/Jolt/Physics/Constraints/ContactConstraintManager.cpp-index 7de3a4483e..972fc13583 100644---- a/thirdparty/jolt_physics/Jolt/Physics/Constraints/ContactConstraintManager.cpp-+++ b/thirdparty/jolt_physics/Jolt/Physics/Constraints/ContactConstraintManager.cpp-@@ -46,7 +46,7 @@ void ContactConstraintManager::WorldContactPoint::CalculateNonPenetrationConstra- }-- template <EMotionType Type1, EMotionType Type2>--JPH_INLINE void ContactConstraintManager::WorldContactPoint::TemplatedCalculateFrictionAndNonPenetrationConstraintProperties(float inDeltaTime, float inGravityDeltaTimeDotNormal, const Body &inBody1, const Body &inBody2, float inInvM1, float inInvM2, Mat44Arg inInvI1, Mat44Arg inInvI2, RVec3Arg inWorldSpacePosition1, RVec3Arg inWorldSpacePosition2, Vec3Arg inWorldSpaceNormal, Vec3Arg inWorldSpaceTangent1, Vec3Arg inWorldSpaceTangent2, const ContactSettings &inSettings, float inMinVelocityForRestitution)-+JPH_INLINE void ContactConstraintManager::WorldContactPoint::TemplatedCalculateFrictionAndNonPenetrationConstraintProperties(float inDeltaTime, Vec3Arg inGravity, const Body &inBody1, const Body &inBody2, float inInvM1, float inInvM2, Mat44Arg inInvI1, Mat44Arg inInvI2, RVec3Arg inWorldSpacePosition1, RVec3Arg inWorldSpacePosition2, Vec3Arg inWorldSpaceNormal, Vec3Arg inWorldSpaceTangent1, Vec3Arg inWorldSpaceTangent2, const ContactSettings &inSettings, float inMinVelocityForRestitution)- {- JPH_DET_LOG("TemplatedCalculateFrictionAndNonPenetrationConstraintProperties: p1: " << inWorldSpacePosition1 << " p2: " << inWorldSpacePosition2- << " normal: " << inWorldSpaceNormal << " tangent1: " << inWorldSpaceTangent1 << " tangent2: " << inWorldSpaceTangent2-@@ -58,39 +58,19 @@ JPH_INLINE void ContactConstraintManager::WorldContactPoint::TemplatedCalculateF- Vec3 r1 = Vec3(p - inBody1.GetCenterOfMassPosition());- Vec3 r2 = Vec3(p - inBody2.GetCenterOfMassPosition());--- // The gravity is applied in the beginning of the time step. If we get here, there was a collision-- // at the beginning of the time step, so we've applied too much gravity. This means that our-- // calculated restitution can be too high, so when we apply restitution, we cancel the added-- // velocity due to gravity.-- float gravity_dt_dot_normal;-+ const MotionProperties *mp1 = inBody1.GetMotionPropertiesUnchecked();-+ const MotionProperties *mp2 = inBody2.GetMotionPropertiesUnchecked();-- // Calculate velocity of collision points- Vec3 relative_velocity;- if constexpr (Type1 != EMotionType::Static && Type2 != EMotionType::Static)-- {-- const MotionProperties *mp1 = inBody1.GetMotionPropertiesUnchecked();-- const MotionProperties *mp2 = inBody2.GetMotionPropertiesUnchecked();- relative_velocity = mp2->GetPointVelocityCOM(r2) - mp1->GetPointVelocityCOM(r1);-- gravity_dt_dot_normal = inGravityDeltaTimeDotNormal * (mp2->GetGravityFactor() - mp1->GetGravityFactor());-- }- else if constexpr (Type1 != EMotionType::Static)-- {-- const MotionProperties *mp1 = inBody1.GetMotionPropertiesUnchecked();- relative_velocity = -mp1->GetPointVelocityCOM(r1);-- gravity_dt_dot_normal = inGravityDeltaTimeDotNormal * mp1->GetGravityFactor();-- }- else if constexpr (Type2 != EMotionType::Static)-- {-- const MotionProperties *mp2 = inBody2.GetMotionPropertiesUnchecked();- relative_velocity = mp2->GetPointVelocityCOM(r2);-- gravity_dt_dot_normal = inGravityDeltaTimeDotNormal * mp2->GetGravityFactor();-- }- else-- {-- JPH_ASSERT(false); // Static vs static makes no sense-- relative_velocity = Vec3::sZero();-- gravity_dt_dot_normal = 0.0f;-- }-+ static_assert(false, "Static vs static makes no sense");- float normal_velocity = relative_velocity.Dot(inWorldSpaceNormal);-- // How much the shapes are penetrating (> 0 if penetrating, < 0 if separated)-@@ -114,11 +94,40 @@ JPH_INLINE void ContactConstraintManager::WorldContactPoint::TemplatedCalculateF- // position rather than from a position where it is touching the other object. This causes the object- // to appear to move faster for 1 frame (the opposite of time stealing).- if (normal_velocity < -speculative_contact_velocity_bias)-- normal_velocity_bias = inSettings.mCombinedRestitution * (normal_velocity - gravity_dt_dot_normal);-+ {-+ // The gravity / constant forces are applied in the beginning of the time step.-+ // If we get here, there was a collision at the beginning of the time step, so we've applied too much force.-+ // This means that our calculated restitution can be too high resulting in an increase in energy.-+ // So, when we apply restitution, we cancel the added velocity due to these forces.-+ Vec3 relative_acceleration;-+-+ // Calculate effect of gravity-+ if constexpr (Type1 != EMotionType::Static && Type2 != EMotionType::Static)-+ relative_acceleration = inGravity * (mp2->GetGravityFactor() - mp1->GetGravityFactor());-+ else if constexpr (Type1 != EMotionType::Static)-+ relative_acceleration = -inGravity * mp1->GetGravityFactor();-+ else if constexpr (Type2 != EMotionType::Static)-+ relative_acceleration = inGravity * mp2->GetGravityFactor();-+ else-+ static_assert(false, "Static vs static makes no sense");-+-+ // Calculate effect of accumulated forces-+ if constexpr (Type1 == EMotionType::Dynamic)-+ relative_acceleration -= mp1->GetAccumulatedForce() * mp1->GetInverseMass();-+ if constexpr (Type2 == EMotionType::Dynamic)-+ relative_acceleration += mp2->GetAccumulatedForce() * mp2->GetInverseMass();-+-+ // We only compensate forces towards the contact normal.-+ float force_delta_velocity = min(0.0f, relative_acceleration.Dot(inWorldSpaceNormal) * inDeltaTime);-+-+ normal_velocity_bias = inSettings.mCombinedRestitution * (normal_velocity - force_delta_velocity);-+ }- else-+ {- // In this case we have predicted that we don't hit the other object, but if we do (due to other constraints changing velocities)- // the speculative contact will prevent penetration but will not apply restitution leading to another artifact.- normal_velocity_bias = speculative_contact_velocity_bias;-+ }- }- else- {-@@ -706,7 +715,7 @@ void ContactConstraintManager::PrepareConstraintBuffer(PhysicsUpdateContext *inC- }-- template <EMotionType Type1, EMotionType Type2>--JPH_INLINE void ContactConstraintManager::TemplatedCalculateFrictionAndNonPenetrationConstraintProperties(ContactConstraint &ioConstraint, const ContactSettings &inSettings, float inDeltaTime, Vec3Arg inGravityDeltaTime, RMat44Arg inTransformBody1, RMat44Arg inTransformBody2, const Body &inBody1, const Body &inBody2)-+JPH_INLINE void ContactConstraintManager::TemplatedCalculateFrictionAndNonPenetrationConstraintProperties(ContactConstraint &ioConstraint, const ContactSettings &inSettings, float inDeltaTime, Vec3Arg inGravity, RMat44Arg inTransformBody1, RMat44Arg inTransformBody2, const Body &inBody1, const Body &inBody2)- {- // Calculate scaled mass and inertia- Mat44 inv_i1;-@@ -737,20 +746,17 @@ JPH_INLINE void ContactConstraintManager::TemplatedCalculateFrictionAndNonPenetr-- Vec3 ws_normal = ioConstraint.GetWorldSpaceNormal();--- // Calculate value for restitution correction-- float gravity_dt_dot_normal = inGravityDeltaTime.Dot(ws_normal);--- // Setup velocity constraint properties- float min_velocity_for_restitution = mPhysicsSettings.mMinVelocityForRestitution;- for (WorldContactPoint &wcp : ioConstraint.mContactPoints)- {- RVec3 p1 = inTransformBody1 * Vec3::sLoadFloat3Unsafe(wcp.mContactPoint->mPosition1);- RVec3 p2 = inTransformBody2 * Vec3::sLoadFloat3Unsafe(wcp.mContactPoint->mPosition2);-- wcp.TemplatedCalculateFrictionAndNonPenetrationConstraintProperties<Type1, Type2>(inDeltaTime, gravity_dt_dot_normal, inBody1, inBody2, ioConstraint.mInvMass1, ioConstraint.mInvMass2, inv_i1, inv_i2, p1, p2, ws_normal, t1, t2, inSettings, min_velocity_for_restitution);-+ wcp.TemplatedCalculateFrictionAndNonPenetrationConstraintProperties<Type1, Type2>(inDeltaTime, inGravity, inBody1, inBody2, ioConstraint.mInvMass1, ioConstraint.mInvMass2, inv_i1, inv_i2, p1, p2, ws_normal, t1, t2, inSettings, min_velocity_for_restitution);- }- }---inline void ContactConstraintManager::CalculateFrictionAndNonPenetrationConstraintProperties(ContactConstraint &ioConstraint, const ContactSettings &inSettings, float inDeltaTime, Vec3Arg inGravityDeltaTime, RMat44Arg inTransformBody1, RMat44Arg inTransformBody2, const Body &inBody1, const Body &inBody2)-+inline void ContactConstraintManager::CalculateFrictionAndNonPenetrationConstraintProperties(ContactConstraint &ioConstraint, const ContactSettings &inSettings, float inDeltaTime, Vec3Arg inGravity, RMat44Arg inTransformBody1, RMat44Arg inTransformBody2, const Body &inBody1, const Body &inBody2)- {- // Dispatch to the correct templated form- switch (inBody1.GetMotionType())-@@ -759,15 +765,15 @@ inline void ContactConstraintManager::CalculateFrictionAndNonPenetrationConstrai- switch (inBody2.GetMotionType())- {- case EMotionType::Dynamic:-- TemplatedCalculateFrictionAndNonPenetrationConstraintProperties<EMotionType::Dynamic, EMotionType::Dynamic>(ioConstraint, inSettings, inDeltaTime, inGravityDeltaTime, inTransformBody1, inTransformBody2, inBody1, inBody2);-+ TemplatedCalculateFrictionAndNonPenetrationConstraintProperties<EMotionType::Dynamic, EMotionType::Dynamic>(ioConstraint, inSettings, inDeltaTime, inGravity, inTransformBody1, inTransformBody2, inBody1, inBody2);- break;-- case EMotionType::Kinematic:-- TemplatedCalculateFrictionAndNonPenetrationConstraintProperties<EMotionType::Dynamic, EMotionType::Kinematic>(ioConstraint, inSettings, inDeltaTime, inGravityDeltaTime, inTransformBody1, inTransformBody2, inBody1, inBody2);-+ TemplatedCalculateFrictionAndNonPenetrationConstraintProperties<EMotionType::Dynamic, EMotionType::Kinematic>(ioConstraint, inSettings, inDeltaTime, inGravity, inTransformBody1, inTransformBody2, inBody1, inBody2);- break;-- case EMotionType::Static:-- TemplatedCalculateFrictionAndNonPenetrationConstraintProperties<EMotionType::Dynamic, EMotionType::Static>(ioConstraint, inSettings, inDeltaTime, inGravityDeltaTime, inTransformBody1, inTransformBody2, inBody1, inBody2);-+ TemplatedCalculateFrictionAndNonPenetrationConstraintProperties<EMotionType::Dynamic, EMotionType::Static>(ioConstraint, inSettings, inDeltaTime, inGravity, inTransformBody1, inTransformBody2, inBody1, inBody2);- break;-- default:-@@ -778,12 +784,12 @@ inline void ContactConstraintManager::CalculateFrictionAndNonPenetrationConstrai-- case EMotionType::Kinematic:- JPH_ASSERT(inBody2.IsDynamic());-- TemplatedCalculateFrictionAndNonPenetrationConstraintProperties<EMotionType::Kinematic, EMotionType::Dynamic>(ioConstraint, inSettings, inDeltaTime, inGravityDeltaTime, inTransformBody1, inTransformBody2, inBody1, inBody2);-+ TemplatedCalculateFrictionAndNonPenetrationConstraintProperties<EMotionType::Kinematic, EMotionType::Dynamic>(ioConstraint, inSettings, inDeltaTime, inGravity, inTransformBody1, inTransformBody2, inBody1, inBody2);- break;-- case EMotionType::Static:- JPH_ASSERT(inBody2.IsDynamic());-- TemplatedCalculateFrictionAndNonPenetrationConstraintProperties<EMotionType::Static, EMotionType::Dynamic>(ioConstraint, inSettings, inDeltaTime, inGravityDeltaTime, inTransformBody1, inTransformBody2, inBody1, inBody2);-+ TemplatedCalculateFrictionAndNonPenetrationConstraintProperties<EMotionType::Static, EMotionType::Dynamic>(ioConstraint, inSettings, inDeltaTime, inGravity, inTransformBody1, inTransformBody2, inBody1, inBody2);- break;-- default:-@@ -863,11 +869,9 @@ void ContactConstraintManager::GetContactsFromCache(ContactAllocator &ioContactA- RMat44 transform_body1 = body1->GetCenterOfMassTransform();- RMat44 transform_body2 = body2->GetCenterOfMassTransform();--- // Get time step-+ // Get time step and gravity- float delta_time = mUpdateContext->mStepDeltaTime;---- // Calculate value for restitution correction-- Vec3 gravity_dt = mUpdateContext->mPhysicsSystem->GetGravity() * delta_time;-+ Vec3 gravity = mUpdateContext->mPhysicsSystem->GetGravity();-- // Copy manifolds- uint32 output_handle = ManifoldMap::cInvalidHandle;-@@ -970,7 +974,7 @@ void ContactConstraintManager::GetContactsFromCache(ContactAllocator &ioContactA- JPH_DET_LOG("GetContactsFromCache: id1: " << constraint.mBody1->GetID() << " id2: " << constraint.mBody2->GetID() << " key: " << constraint.mSortKey);-- // Calculate friction and non-penetration constraint properties for all contact points-- CalculateFrictionAndNonPenetrationConstraintProperties(constraint, settings, delta_time, gravity_dt, transform_body1, transform_body2, *body1, *body2);-+ CalculateFrictionAndNonPenetrationConstraintProperties(constraint, settings, delta_time, gravity, transform_body1, transform_body2, *body1, *body2);-- // Notify island builder- mUpdateContext->mIslandBuilder->LinkContact(constraint_idx, body1->GetIndexInActiveBodiesInternal(), body2->GetIndexInActiveBodiesInternal());-@@ -1144,11 +1148,9 @@ bool ContactConstraintManager::TemplatedAddContactConstraint(ContactAllocator &i- // Notify island builder- mUpdateContext->mIslandBuilder->LinkContact(constraint_idx, inBody1.GetIndexInActiveBodiesInternal(), inBody2.GetIndexInActiveBodiesInternal());--- // Get time step-+ // Get time step and gravity- float delta_time = mUpdateContext->mStepDeltaTime;---- // Calculate value for restitution correction-- float gravity_dt_dot_normal = inManifold.mWorldSpaceNormal.Dot(mUpdateContext->mPhysicsSystem->GetGravity() * delta_time);-+ Vec3 gravity = mUpdateContext->mPhysicsSystem->GetGravity();-- // Calculate scaled mass and inertia- float inv_m1;-@@ -1222,7 +1224,7 @@ bool ContactConstraintManager::TemplatedAddContactConstraint(ContactAllocator &i- wcp.mContactPoint = &cp;-- // Setup velocity constraint-- wcp.TemplatedCalculateFrictionAndNonPenetrationConstraintProperties<Type1, Type2>(delta_time, gravity_dt_dot_normal, inBody1, inBody2, inv_m1, inv_m2, inv_i1, inv_i2, p1_ws, p2_ws, inManifold.mWorldSpaceNormal, t1, t2, settings, mPhysicsSettings.mMinVelocityForRestitution);-+ wcp.TemplatedCalculateFrictionAndNonPenetrationConstraintProperties<Type1, Type2>(delta_time, gravity, inBody1, inBody2, inv_m1, inv_m2, inv_i1, inv_i2, p1_ws, p2_ws, inManifold.mWorldSpaceNormal, t1, t2, settings, mPhysicsSettings.mMinVelocityForRestitution);- }-- #ifdef JPH_DEBUG_RENDERER-diff --git a/thirdparty/jolt_physics/Jolt/Physics/Constraints/ContactConstraintManager.h b/thirdparty/jolt_physics/Jolt/Physics/Constraints/ContactConstraintManager.h-index 0b5938b77e..dfe5fc8c38 100644---- a/thirdparty/jolt_physics/Jolt/Physics/Constraints/ContactConstraintManager.h-+++ b/thirdparty/jolt_physics/Jolt/Physics/Constraints/ContactConstraintManager.h-@@ -427,7 +427,7 @@ private:- void CalculateNonPenetrationConstraintProperties(const Body &inBody1, float inInvMass1, float inInvInertiaScale1, const Body &inBody2, float inInvMass2, float inInvInertiaScale2, RVec3Arg inWorldSpacePosition1, RVec3Arg inWorldSpacePosition2, Vec3Arg inWorldSpaceNormal);-- template <EMotionType Type1, EMotionType Type2>-- JPH_INLINE void TemplatedCalculateFrictionAndNonPenetrationConstraintProperties(float inDeltaTime, float inGravityDeltaTimeDotNormal, const Body &inBody1, const Body &inBody2, float inInvM1, float inInvM2, Mat44Arg inInvI1, Mat44Arg inInvI2, RVec3Arg inWorldSpacePosition1, RVec3Arg inWorldSpacePosition2, Vec3Arg inWorldSpaceNormal, Vec3Arg inWorldSpaceTangent1, Vec3Arg inWorldSpaceTangent2, const ContactSettings &inSettings, float inMinVelocityForRestitution);-+ JPH_INLINE void TemplatedCalculateFrictionAndNonPenetrationConstraintProperties(float inDeltaTime, Vec3Arg inGravity, const Body &inBody1, const Body &inBody2, float inInvM1, float inInvM2, Mat44Arg inInvI1, Mat44Arg inInvI2, RVec3Arg inWorldSpacePosition1, RVec3Arg inWorldSpacePosition2, Vec3Arg inWorldSpaceNormal, Vec3Arg inWorldSpaceTangent1, Vec3Arg inWorldSpaceTangent2, const ContactSettings &inSettings, float inMinVelocityForRestitution);-- /// The constraint parts- AxisConstraintPart mNonPenetrationConstraint;-@@ -485,10 +485,10 @@ public:- private:- /// Internal helper function to calculate the friction and non-penetration constraint properties. Templated to the motion type to reduce the amount of branches and calculations.- template <EMotionType Type1, EMotionType Type2>-- JPH_INLINE void TemplatedCalculateFrictionAndNonPenetrationConstraintProperties(ContactConstraint &ioConstraint, const ContactSettings &inSettings, float inDeltaTime, Vec3Arg inGravityDeltaTime, RMat44Arg inTransformBody1, RMat44Arg inTransformBody2, const Body &inBody1, const Body &inBody2);-+ JPH_INLINE void TemplatedCalculateFrictionAndNonPenetrationConstraintProperties(ContactConstraint &ioConstraint, const ContactSettings &inSettings, float inDeltaTime, Vec3Arg inGravity, RMat44Arg inTransformBody1, RMat44Arg inTransformBody2, const Body &inBody1, const Body &inBody2);-- /// Internal helper function to calculate the friction and non-penetration constraint properties.-- inline void CalculateFrictionAndNonPenetrationConstraintProperties(ContactConstraint &ioConstraint, const ContactSettings &inSettings, float inDeltaTime, Vec3Arg inGravityDeltaTime, RMat44Arg inTransformBody1, RMat44Arg inTransformBody2, const Body &inBody1, const Body &inBody2);-+ inline void CalculateFrictionAndNonPenetrationConstraintProperties(ContactConstraint &ioConstraint, const ContactSettings &inSettings, float inDeltaTime, Vec3Arg inGravity, RMat44Arg inTransformBody1, RMat44Arg inTransformBody2, const Body &inBody1, const Body &inBody2);-- /// Internal helper function to add a contact constraint. Templated to the motion type to reduce the amount of branches and calculations.- template <EMotionType Type1, EMotionType Type2>diff --git a/thirdparty/jolt_physics/patches/0003-backport-upstream-commit-365a15367.patch b/thirdparty/jolt_physics/patches/0003-backport-upstream-commit-365a15367.patchdeleted file mode 100644index 11690b04d91..00000000000--- a/thirdparty/jolt_physics/patches/0003-backport-upstream-commit-365a15367.patch+++ /dev/null@@ -1,28 +0,0 @@-diff --git a/thirdparty/jolt_physics/Jolt/Physics/Constraints/ContactConstraintManager.cpp b/thirdparty/jolt_physics/Jolt/Physics/Constraints/ContactConstraintManager.cpp-index 972fc13583..09dfab4921 100644---- a/thirdparty/jolt_physics/Jolt/Physics/Constraints/ContactConstraintManager.cpp-+++ b/thirdparty/jolt_physics/Jolt/Physics/Constraints/ContactConstraintManager.cpp-@@ -70,7 +70,10 @@ JPH_INLINE void ContactConstraintManager::WorldContactPoint::TemplatedCalculateF- else if constexpr (Type2 != EMotionType::Static)- relative_velocity = mp2->GetPointVelocityCOM(r2);- else-- static_assert(false, "Static vs static makes no sense");-+ {-+ JPH_ASSERT(false, "Static vs static makes no sense");-+ relative_velocity = Vec3::sZero();-+ }- float normal_velocity = relative_velocity.Dot(inWorldSpaceNormal);-- // How much the shapes are penetrating (> 0 if penetrating, < 0 if separated)-@@ -109,7 +112,10 @@ JPH_INLINE void ContactConstraintManager::WorldContactPoint::TemplatedCalculateF- else if constexpr (Type2 != EMotionType::Static)- relative_acceleration = inGravity * mp2->GetGravityFactor();- else-- static_assert(false, "Static vs static makes no sense");-+ {-+ JPH_ASSERT(false, "Static vs static makes no sense");-+ relative_acceleration = Vec3::sZero();-+ }-- // Calculate effect of accumulated forces- if constexpr (Type1 == EMotionType::Dynamic)diff --git a/thirdparty/jolt_physics/patches/0004-backport-upstream-commit-e0a6a9a16.patch b/thirdparty/jolt_physics/patches/0004-backport-upstream-commit-e0a6a9a16.patchdeleted file mode 100644index 72788af482b..00000000000--- a/thirdparty/jolt_physics/patches/0004-backport-upstream-commit-e0a6a9a16.patch+++ /dev/null@@ -1,61 +0,0 @@-diff --git a/thirdparty/jolt_physics/Jolt/Math/Quat.h b/thirdparty/jolt_physics/Jolt/Math/Quat.h-index 6e7e3bef6c..1971e2ddf1 100644---- a/thirdparty/jolt_physics/Jolt/Math/Quat.h-+++ b/thirdparty/jolt_physics/Jolt/Math/Quat.h-@@ -111,6 +111,9 @@ public:- /// Get axis and angle that represents this quaternion, outAngle will always be in the range \f$[0, \pi]\f$- JPH_INLINE void GetAxisAngle(Vec3 &outAxis, float &outAngle) const;--+ /// Calculate angular velocity given that this quaternion represents the rotation that is reached after inDeltaTime when starting from identity rotation-+ JPH_INLINE Vec3 GetAngularVelocity(float inDeltaTime) const;-+- /// Create quaternion that rotates a vector from the direction of inFrom to the direction of inTo along the shortest path- /// @see https://www.euclideanspace.com/maths/algebra/vectors/angleBetween/index.htm- JPH_INLINE static Quat sFromTo(Vec3Arg inFrom, Vec3Arg inTo);-diff --git a/thirdparty/jolt_physics/Jolt/Math/Quat.inl b/thirdparty/jolt_physics/Jolt/Math/Quat.inl-index 57e1947b30..7c160a5f23 100644---- a/thirdparty/jolt_physics/Jolt/Math/Quat.inl-+++ b/thirdparty/jolt_physics/Jolt/Math/Quat.inl-@@ -151,6 +151,26 @@ void Quat::GetAxisAngle(Vec3 &outAxis, float &outAngle) const- }- }--+Vec3 Quat::GetAngularVelocity(float inDeltaTime) const-+{-+ JPH_ASSERT(IsNormalized());-+-+ // w = cos(angle / 2), ensure it is positive so that we get an angle in the range [0, PI]-+ Quat w_pos = EnsureWPositive();-+-+ // The imaginary part of the quaternion is axis * sin(angle / 2),-+ // if the length is small use the approximation sin(x) = x to calculate angular velocity-+ Vec3 xyz = w_pos.GetXYZ();-+ float xyz_len_sq = xyz.LengthSq();-+ if (xyz_len_sq < 4.0e-4f) // Max error introduced is sin(0.02) - 0.02 = 7e-5 (when w is near 1 the angle becomes more inaccurate in the code below, so don't make this number too small)-+ return (2.0f / inDeltaTime) * xyz;-+-+ // Otherwise calculate the angle from w = cos(angle / 2) and determine the axis by normalizing the imaginary part-+ // Note that it is also possible to calculate the angle through angle = 2 * atan2(|xyz|, w). This is more accurate but also 2x as expensive.-+ float angle = 2.0f * ACos(w_pos.GetW());-+ return (xyz / (sqrt(xyz_len_sq) * inDeltaTime)) * angle;-+}-+- Quat Quat::sFromTo(Vec3Arg inFrom, Vec3Arg inTo)- {- /*-diff --git a/thirdparty/jolt_physics/Jolt/Physics/Body/MotionProperties.inl b/thirdparty/jolt_physics/Jolt/Physics/Body/MotionProperties.inl-index 474ab15c18..e6caae61f5 100644---- a/thirdparty/jolt_physics/Jolt/Physics/Body/MotionProperties.inl-+++ b/thirdparty/jolt_physics/Jolt/Physics/Body/MotionProperties.inl-@@ -17,10 +17,7 @@ void MotionProperties::MoveKinematic(Vec3Arg inDeltaPosition, QuatArg inDeltaRot- mLinearVelocity = LockTranslation(inDeltaPosition / inDeltaTime);-- // Calculate required angular velocity-- Vec3 axis;-- float angle;-- inDeltaRotation.GetAxisAngle(axis, angle);-- mAngularVelocity = LockAngular(axis * (angle / inDeltaTime));-+ mAngularVelocity = LockAngular(inDeltaRotation.GetAngularVelocity(inDeltaTime));- }-- void MotionProperties::ClampLinearVelocity()diff --git a/thirdparty/jolt_physics/patches/0005-backport-upstream-commit-449b645.patch b/thirdparty/jolt_physics/patches/0005-backport-upstream-commit-449b645.patchdeleted file mode 100644index 87afad03415..00000000000--- a/thirdparty/jolt_physics/patches/0005-backport-upstream-commit-449b645.patch+++ /dev/null@@ -1,297 +0,0 @@-diff --git a/thirdparty/jolt_physics/Jolt/Physics/Collision/CollideShape.h b/thirdparty/jolt_physics/Jolt/Physics/Collision/CollideShape.h-index cfec8139..134f300d 100644---- a/thirdparty/jolt_physics/Jolt/Physics/Collision/CollideShape.h-+++ b/thirdparty/jolt_physics/Jolt/Physics/Collision/CollideShape.h-@@ -101,6 +101,9 @@ public:-- /// How backfacing triangles should be treated- EBackFaceMode mBackFaceMode = EBackFaceMode::IgnoreBackFaces;-+-+ /// Max squared distance to consider a vertex to be the same as another vertex, used by the internal edge removal algorithm to determine if two edges are shared. (unit: meter^2)-+ float mInternalEdgeRemovalVertexToleranceSq = cDefaultInternalEdgeRemovalVertexToleranceSq;- };-- JPH_NAMESPACE_END-diff --git a/thirdparty/jolt_physics/Jolt/Physics/Collision/InternalEdgeRemovingCollector.h b/thirdparty/jolt_physics/Jolt/Physics/Collision/InternalEdgeRemovingCollector.h-index cec7d7be..eee55022 100644---- a/thirdparty/jolt_physics/Jolt/Physics/Collision/InternalEdgeRemovingCollector.h-+++ b/thirdparty/jolt_physics/Jolt/Physics/Collision/InternalEdgeRemovingCollector.h-@@ -31,7 +31,7 @@ class InternalEdgeRemovingCollector : public CollideShapeCollector- {- for (const Voided &vf : mVoidedFeatures)- if (vf.mSubShapeID == inSubShapeID-- && inV.IsClose(Vec3::sLoadFloat3Unsafe(vf.mFeature), 1.0e-8f))-+ && inV.IsClose(Vec3::sLoadFloat3Unsafe(vf.mFeature), mVertexToleranceSq))- return true;- return false;- }-@@ -76,13 +76,15 @@ class InternalEdgeRemovingCollector : public CollideShapeCollector-- public:- /// Constructor, configures a collector to be called with all the results that do not hit internal edges-- explicit InternalEdgeRemovingCollector(CollideShapeCollector &inChainedCollector-+ explicit InternalEdgeRemovingCollector(CollideShapeCollector &inChainedCollector,-+ float inVertexToleranceSq- #ifdef JPH_INTERNAL_EDGE_REMOVING_COLLECTOR_DEBUG- , RVec3Arg inBaseOffset- #endif // JPH_INTERNAL_EDGE_REMOVING_COLLECTOR_DEBUG- ) :- CollideShapeCollector(inChainedCollector),-- mChainedCollector(inChainedCollector)-+ mChainedCollector(inChainedCollector),-+ mVertexToleranceSq(inVertexToleranceSq)- #ifdef JPH_INTERNAL_EDGE_REMOVING_COLLECTOR_DEBUG- , mBaseOffset(inBaseOffset)- #endif // JPH_INTERNAL_EDGE_REMOVING_COLLECTOR_DEBUG-@@ -249,7 +251,7 @@ public:- JPH_ASSERT(inCollideShapeSettings.mActiveEdgeMode == EActiveEdgeMode::CollideWithAll); // Won't work without colliding with all edges- JPH_ASSERT(inCollideShapeSettings.mCollectFacesMode == ECollectFacesMode::CollectFaces); // Won't work without collecting faces--- InternalEdgeRemovingCollector wrapper(ioCollector-+ InternalEdgeRemovingCollector wrapper(ioCollector, inCollideShapeSettings.mInternalEdgeRemovalVertexToleranceSq- #ifdef JPH_INTERNAL_EDGE_REMOVING_COLLECTOR_DEBUG- , inBaseOffset- #endif // JPH_INTERNAL_EDGE_REMOVING_COLLECTOR_DEBUG-@@ -271,6 +273,7 @@ private:- CollideShapeCollector & mChainedCollector;- Array<Voided, STLLocalAllocator<Voided, cMaxLocalVoidedFeatures>> mVoidedFeatures;- Array<CollideShapeResult, STLLocalAllocator<CollideShapeResult, cMaxLocalDelayedResults>> mDelayedResults;-+ float mVertexToleranceSq; // Max squared distance to consider a vertex to be the same as another vertex, used to determine if a feature is voided- #ifdef JPH_INTERNAL_EDGE_REMOVING_COLLECTOR_DEBUG- RVec3 mBaseOffset; // Base offset for the query, used to draw the results in the right place- #endif // JPH_INTERNAL_EDGE_REMOVING_COLLECTOR_DEBUG-diff --git a/thirdparty/jolt_physics/Jolt/Physics/Collision/NarrowPhaseQuery.cpp b/thirdparty/jolt_physics/Jolt/Physics/Collision/NarrowPhaseQuery.cpp-index 670cee33..1a8c2c78 100644---- a/thirdparty/jolt_physics/Jolt/Physics/Collision/NarrowPhaseQuery.cpp-+++ b/thirdparty/jolt_physics/Jolt/Physics/Collision/NarrowPhaseQuery.cpp-@@ -301,7 +301,7 @@ void NarrowPhaseQuery::CollideShapeWithInternalEdgeRemoval(const Shape *inShape,- settings.mActiveEdgeMode = EActiveEdgeMode::CollideWithAll;- settings.mCollectFacesMode = ECollectFacesMode::CollectFaces;--- InternalEdgeRemovingCollector wrapper(ioCollector-+ InternalEdgeRemovingCollector wrapper(ioCollector, settings.mInternalEdgeRemovalVertexToleranceSq- #ifdef JPH_INTERNAL_EDGE_REMOVING_COLLECTOR_DEBUG- , inBaseOffset- #endif // JPH_INTERNAL_EDGE_REMOVING_COLLECTOR_DEBUG-diff --git a/thirdparty/jolt_physics/Jolt/Physics/Collision/Shape/HeightFieldShape.cpp b/thirdparty/jolt_physics/Jolt/Physics/Collision/Shape/HeightFieldShape.cpp-index ff55f4ba..d859b22e 100644---- a/thirdparty/jolt_physics/Jolt/Physics/Collision/Shape/HeightFieldShape.cpp-+++ b/thirdparty/jolt_physics/Jolt/Physics/Collision/Shape/HeightFieldShape.cpp-@@ -185,9 +185,9 @@ uint32 HeightFieldShapeSettings::CalculateBitsPerSampleForError(float inMaxError- // Not accurate enough, increase bits per sample- bits_per_sample++;--- // Don't go above 8 bits per sample-- if (bits_per_sample == 8)-- return bits_per_sample;-+ // Don't go above cMaxBitsPerSample bits per sample-+ if (bits_per_sample == cMaxBitsPerSample)-+ return cMaxBitsPerSample;- }- }- }-@@ -416,7 +416,7 @@ void HeightFieldShape::StoreMaterialIndices(const HeightFieldShapeSettings &inSe-- void HeightFieldShape::CacheValues()- {-- mSampleMask = uint8((uint32(1) << mBitsPerSample) - 1);-+ mSampleMask = uint16((uint32(1) << mBitsPerSample) - 1);- }-- void HeightFieldShape::AllocateBuffers()-@@ -424,7 +424,7 @@ void HeightFieldShape::AllocateBuffers()- uint num_blocks = GetNumBlocks();- uint max_stride = (num_blocks + 1) >> 1;- mRangeBlocksSize = sGridOffsets[sGetMaxLevel(num_blocks) - 1] + Square(max_stride);-- mHeightSamplesSize = (mSampleCount * mSampleCount * mBitsPerSample + 7) / 8 + 1;-+ mHeightSamplesSize = (mSampleCount * mSampleCount * mBitsPerSample + 7) / 8 + 2; // Since we read 3 bytes per sample, we need 2 extra bytes of padding- mActiveEdgesSize = (Square(mSampleCount - 1) * 3 + 7) / 8 + 1; // See explanation at HeightFieldShape::CalculateActiveEdges-- JPH_ASSERT(mRangeBlocks == nullptr && mHeightSamples == nullptr && mActiveEdges == nullptr);-@@ -457,9 +457,9 @@ HeightFieldShape::HeightFieldShape(const HeightFieldShapeSettings &inSettings, S- }-- // Check bits per sample-- if (inSettings.mBitsPerSample < 1 || inSettings.mBitsPerSample > 8)-+ if (inSettings.mBitsPerSample < 1 || inSettings.mBitsPerSample > HeightFieldShapeConstants::cMaxBitsPerSample)- {-- outResult.SetError("HeightFieldShape: Bits per sample must be in the range [1, 8]!");-+ outResult.SetError("HeightFieldShape: Bits per sample must be in the range [1, 16]!");- return;- }--@@ -727,9 +727,10 @@ HeightFieldShape::HeightFieldShape(const HeightFieldShapeSettings &inSettings, S- uint byte_pos = sample >> 3;- uint bit_pos = sample & 0b111;- output_value <<= bit_pos;-- JPH_ASSERT(byte_pos + 1 < mHeightSamplesSize);-+ JPH_ASSERT(byte_pos + 2 < mHeightSamplesSize); // We read max 16 bits which could be spread out over 3 bytes- mHeightSamples[byte_pos] |= uint8(output_value);- mHeightSamples[byte_pos + 1] |= uint8(output_value >> 8);-+ mHeightSamples[byte_pos + 2] |= uint8(output_value >> 16);- sample += inSettings.mBitsPerSample;- }--@@ -816,7 +817,7 @@ inline void HeightFieldShape::GetBlockOffsetAndScale(uint inBlockX, uint inBlock- outBlockScale = float(block.mMax[n] - block.mMin[n]) / float(mSampleMask);- }---inline uint8 HeightFieldShape::GetHeightSample(uint inX, uint inY) const-+inline uint16 HeightFieldShape::GetHeightSample(uint inX, uint inY) const- {- JPH_ASSERT(inX < mSampleCount);- JPH_ASSERT(inY < mSampleCount);-@@ -827,16 +828,16 @@ inline uint8 HeightFieldShape::GetHeightSample(uint inX, uint inY) const- uint bit_pos = sample & 0b111;-- // Fetch the height sample value-- JPH_ASSERT(byte_pos + 1 < mHeightSamplesSize);-+ JPH_ASSERT(byte_pos + 2 < mHeightSamplesSize); // We read max 16 bits which could be spread out over 3 bytes- const uint8 *height_samples = mHeightSamples + byte_pos;-- uint16 height_sample = uint16(height_samples[0]) | uint16(uint16(height_samples[1]) << 8);-- return uint8(height_sample >> bit_pos) & mSampleMask;-+ uint32 height_sample = uint32(height_samples[0]) | (uint32(height_samples[1]) << 8) | (uint32(height_samples[2]) << 16);-+ return uint16(height_sample >> bit_pos) & mSampleMask;- }-- inline Vec3 HeightFieldShape::GetPosition(uint inX, uint inY, float inBlockOffset, float inBlockScale, bool &outNoCollision) const- {- // Get quantized value-- uint8 height_sample = GetHeightSample(inX, inY);-+ uint16 height_sample = GetHeightSample(inX, inY);- outNoCollision = height_sample == mSampleMask;-- // Add 0.5 to the quantized value to minimize the error (see constructor)-@@ -980,7 +981,7 @@ void HeightFieldShape::GetHeights(uint inX, uint inY, uint inSizeX, uint inSizeY- uint output_y = block_y * mBlockSize + sample_y;-- // Get quantized value-- uint8 height_sample = GetHeightSample(inX + output_x, inY + output_y);-+ uint16 height_sample = GetHeightSample(inX + output_x, inY + output_y);-- // Dequantize- float h = height_sample != mSampleMask? offset + height_sample * scale : cNoCollisionValue;-@@ -1129,7 +1130,7 @@ void HeightFieldShape::SetHeights(uint inX, uint inY, uint inSizeX, uint inSizeY- {- // Quantize height- float h = heights[sample_y * heights_stride + sample_x];-- uint8 quantized_height = h != cNoCollisionValue? uint8(Clamp((int)floor((h - offset) / scale), 0, int(mSampleMask) - 1)) : mSampleMask;-+ uint16 quantized_height = h != cNoCollisionValue? uint16(Clamp((int)floor((h - offset) / scale), 0, int(mSampleMask) - 1)) : mSampleMask;-- // Determine bit position of sample- uint sample = ((affected_y + sample_y) * mSampleCount + affected_x + sample_x) * uint(mBitsPerSample);-@@ -1137,13 +1138,14 @@ void HeightFieldShape::SetHeights(uint inX, uint inY, uint inSizeX, uint inSizeY- uint bit_pos = sample & 0b111;-- // Update the height value sample-- JPH_ASSERT(byte_pos + 1 < mHeightSamplesSize);-+ JPH_ASSERT(byte_pos + 2 < mHeightSamplesSize); // We read max 16 bits which could be spread out over 3 bytes- uint8 *height_samples = mHeightSamples + byte_pos;-- uint16 height_sample = uint16(height_samples[0]) | uint16(uint16(height_samples[1]) << 8);-- height_sample &= ~(uint16(mSampleMask) << bit_pos);-- height_sample |= uint16(quantized_height) << bit_pos;-+ uint32 height_sample = uint32(height_samples[0]) | (uint32(height_samples[1]) << 8) | (uint32(height_samples[2]) << 16);-+ height_sample &= ~(uint32(mSampleMask) << bit_pos);-+ height_sample |= uint32(quantized_height) << bit_pos;- height_samples[0] = uint8(height_sample);- height_samples[1] = uint8(height_sample >> 8);-+ height_samples[2] = uint8(height_sample >> 16);- }- }--diff --git a/thirdparty/jolt_physics/Jolt/Physics/Collision/Shape/HeightFieldShape.h b/thirdparty/jolt_physics/Jolt/Physics/Collision/Shape/HeightFieldShape.h-index 5aa6de88..c9bdc605 100644---- a/thirdparty/jolt_physics/Jolt/Physics/Collision/Shape/HeightFieldShape.h-+++ b/thirdparty/jolt_physics/Jolt/Physics/Collision/Shape/HeightFieldShape.h-@@ -33,6 +33,9 @@ namespace HeightFieldShapeConstants- /// When height samples are converted to 16 bit:- constexpr uint16 cNoCollisionValue16 = 0xffff; ///< This is the magic value for 'no collision'- constexpr uint16 cMaxHeightValue16 = 0xfffe; ///< This is the maximum allowed height value-+-+ /// Maximum value for HeightFieldShapeSettings::mBitsPerSample-+ constexpr uint32 cMaxBitsPerSample = 16;- };-- /// Class that constructs a HeightFieldShape-@@ -63,7 +66,7 @@ public:-- /// Given mBlockSize, mSampleCount and mHeightSamples, calculate the amount of bits needed to stay below absolute error inMaxError- /// @param inMaxError Maximum allowed error in mHeightSamples after compression (note that this does not take mScale.Y into account)-- /// @return Needed bits per sample in the range [1, 8].-+ /// @return Needed bits per sample in the range [1, 16].- uint32 CalculateBitsPerSampleForError(float inMaxError) const;-- /// The height field is a surface defined by: mOffset + mScale * (x, mHeightSamples[y * mSampleCount + x], y).-@@ -83,12 +86,12 @@ public:- uint32 mMaterialsCapacity = 0;-- /// The heightfield is divided in blocks of mBlockSize * mBlockSize * 2 triangles and the acceleration structure culls blocks only,-- /// bigger block sizes reduce memory consumption but also reduce query performance. Sensible values are [2, 8], does not need to be-+ /// bigger block sizes reduce memory consumption but also reduce query performance. Valid values are [2, 8], does not need to be- /// a power of 2. Note that at run-time we'll perform one more grid subdivision, so the effective block size is half of what is provided here.- uint32 mBlockSize = 2;--- /// How many bits per sample to use to compress the height field. Can be in the range [1, 8].-- /// Note that each sample is compressed relative to the min/max value of its block of mBlockSize * mBlockSize pixels so the effective precision is higher.-+ /// How many bits per sample to use to compress the height field. Can be in the range [1, 16].-+ /// Note that each sample is compressed relative to the min/max value of its block of mBlockSize * mBlockSize samples so the effective precision is higher.- /// Also note that increasing mBlockSize saves more memory than reducing the amount of bits per sample.- uint32 mBitsPerSample = 8;--@@ -307,7 +310,7 @@ private:- inline void GetBlockOffsetAndScale(uint inBlockX, uint inBlockY, uint inRangeBlockOffset, uint inRangeBlockStride, float &outBlockOffset, float &outBlockScale) const;-- /// Get the height sample at position (inX, inY)-- inline uint8 GetHeightSample(uint inX, uint inY) const;-+ inline uint16 GetHeightSample(uint inX, uint inY) const;-- /// Faster version of GetPosition when block offset and scale are already known- inline Vec3 GetPosition(uint inX, uint inY, float inBlockOffset, float inBlockScale, bool &outNoCollision) const;-@@ -358,7 +361,7 @@ private:- uint32 mRangeBlocksSize = 0; ///< Size of mRangeBlocks in elements- uint32 mActiveEdgesSize = 0; ///< Size of mActiveEdges in bytes- uint8 mBitsPerSample = 8; ///< See HeightFieldShapeSettings::mBitsPerSample-- uint8 mSampleMask = 0xff; ///< All bits set for a sample: (1 << mBitsPerSample) - 1, used to indicate that there's no collision-+ uint16 mSampleMask = 0xff; ///< All bits set for a sample: (1 << mBitsPerSample) - 1, used to indicate that there's no collision- uint16 mMinSample = HeightFieldShapeConstants::cNoCollisionValue16; ///< Min and max value in mHeightSamples quantized to 16 bit, for calculating bounding box- uint16 mMaxSample = HeightFieldShapeConstants::cNoCollisionValue16;- RangeBlock * mRangeBlocks = nullptr; ///< Hierarchical grid of range data describing the height variations within 1 block. The grid for level <level> starts at offset sGridOffsets[<level>]-diff --git a/thirdparty/jolt_physics/Jolt/Physics/PhysicsSettings.h b/thirdparty/jolt_physics/Jolt/Physics/PhysicsSettings.h-index 1109e253..cbd88d1a 100644---- a/thirdparty/jolt_physics/Jolt/Physics/PhysicsSettings.h-+++ b/thirdparty/jolt_physics/Jolt/Physics/PhysicsSettings.h-@@ -16,7 +16,10 @@ constexpr float cDefaultPenetrationTolerance = 1.0e-4f; ///< Stop when there's l- constexpr float cDefaultConvexRadius = 0.05f;-- /// Used by (Tapered)CapsuleShape to determine when supporting face is an edge rather than a point (unit: meter)--static constexpr float cCapsuleProjectionSlop = 0.02f;-+constexpr float cCapsuleProjectionSlop = 0.02f;-+-+/// Max squared distance to consider a vertex to be the same as another vertex, used by the internal edge removal algorithm to determine if two edges are shared (unit: meter^2)-+constexpr float cDefaultInternalEdgeRemovalVertexToleranceSq = 1.0e-8f;-- /// Maximum amount of jobs to allow- constexpr int cMaxPhysicsJobs = 2048;-@@ -73,6 +76,9 @@ struct PhysicsSettings- /// Maximum allowed distance between old and new contact point to preserve contact forces for warm start (units: meter^2)- float mContactPointPreserveLambdaMaxDistSq = Square(0.01f); ///< 1 cm--+ /// Max squared distance to consider a vertex to be the same as another vertex, used by the internal edge removal algorithm to determine if two edges are shared. (unit: meter^2)-+ float mInternalEdgeRemovalVertexToleranceSq = cDefaultInternalEdgeRemovalVertexToleranceSq;-+- /// Number of solver velocity iterations to run- /// Note that this needs to be >= 2 in order for friction to work (friction is applied using the non-penetration impulse from the previous iteration)- uint mNumVelocitySteps = 10;-diff --git a/thirdparty/jolt_physics/Jolt/Physics/PhysicsSystem.cpp b/thirdparty/jolt_physics/Jolt/Physics/PhysicsSystem.cpp-index 7b4babfc..c2ead513 100644---- a/thirdparty/jolt_physics/Jolt/Physics/PhysicsSystem.cpp-+++ b/thirdparty/jolt_physics/Jolt/Physics/PhysicsSystem.cpp-@@ -1096,6 +1096,7 @@ void PhysicsSystem::ProcessBodyPair(ContactAllocator &ioContactAllocator, const- settings.mActiveEdgeMode = mPhysicsSettings.mCheckActiveEdges? EActiveEdgeMode::CollideOnlyWithActive : EActiveEdgeMode::CollideWithAll;- settings.mMaxSeparationDistance = body1->IsSensor() || body2->IsSensor()? 0.0f : mPhysicsSettings.mSpeculativeContactDistance;- settings.mActiveEdgeMovementDirection = body1->GetLinearVelocity() - body2->GetLinearVelocity();-+ settings.mInternalEdgeRemovalVertexToleranceSq = mPhysicsSettings.mInternalEdgeRemovalVertexToleranceSq;-- // Create shape filter- SimShapeFilterWrapper shape_filter(mSimShapeFilter, body1);-2.52.0.windows.1diff --git a/thirdparty/jolt_physics/patches/0006-backport-upstream-commit-63765d1.patch b/thirdparty/jolt_physics/patches/0006-backport-upstream-commit-63765d1.patchdeleted file mode 100644index 9123a7b1992..00000000000--- a/thirdparty/jolt_physics/patches/0006-backport-upstream-commit-63765d1.patch+++ /dev/null@@ -1,289 +0,0 @@-diff --git a/thirdparty/jolt_physics/Jolt/Physics/PhysicsSystem.cpp b/thirdparty/jolt_physics/Jolt/Physics/PhysicsSystem.cpp-index d972dd2c..0a3f21b8 100644---- a/thirdparty/jolt_physics/Jolt/Physics/PhysicsSystem.cpp-+++ b/thirdparty/jolt_physics/Jolt/Physics/PhysicsSystem.cpp-@@ -26,6 +26,7 @@- #include <Jolt/Physics/DeterminismLog.h>- #include <Jolt/Physics/SoftBody/SoftBodyMotionProperties.h>- #include <Jolt/Physics/SoftBody/SoftBodyShape.h>-+#include <Jolt/Physics/SoftBody/SoftBodyContactListener.h>- #include <Jolt/Geometry/RayAABox.h>- #include <Jolt/Geometry/ClosestPoint.h>- #include <Jolt/Core/JobSystem.h>-@@ -1833,9 +1834,10 @@ void PhysicsSystem::JobFindCCDContacts(const PhysicsUpdateContext *ioContext, Ph- class CCDNarrowPhaseCollector : public CastShapeCollector- {- public:-- CCDNarrowPhaseCollector(const BodyManager &inBodyManager, ContactConstraintManager &inContactConstraintManager, CCDBody &inCCDBody, ShapeCastResult &inResult, float inDeltaTime) :-+ CCDNarrowPhaseCollector(const BodyManager &inBodyManager, ContactConstraintManager &inContactConstraintManager, SoftBodyContactListener *inSoftBodyContactListener, CCDBody &inCCDBody, ShapeCastResult &inResult, float inDeltaTime) :- mBodyManager(inBodyManager),- mContactConstraintManager(inContactConstraintManager),-+ mSoftBodyContactListener(inSoftBodyContactListener),- mCCDBody(inCCDBody),- mResult(inResult),- mDeltaTime(inDeltaTime)-@@ -1871,26 +1873,53 @@ void PhysicsSystem::JobFindCCDContacts(const PhysicsUpdateContext *ioContext, Ph- {- // Validate the contact result- const Body &body1 = mBodyManager.GetBody(mCCDBody.mBodyID1);-- ValidateResult validate_result = mContactConstraintManager.ValidateContactPoint(body1, body2, body1.GetCenterOfMassPosition(), inResult); // Note that the center of mass of body 1 is the start of the sweep and is used as base offset below-- switch (validate_result)-+ if (body2.IsRigidBody())- {-- case ValidateResult::AcceptContact:-- // Just continue-- break;---- case ValidateResult::AcceptAllContactsForThisBodyPair:-- // Accept this and all following contacts from this body-- mValidateBodyPair = false;-- break;---- case ValidateResult::RejectContact:-- return;---- case ValidateResult::RejectAllContactsForThisBodyPair:-- // Reject this and all following contacts from this body-- mRejectAll = true;-- ForceEarlyOut();-- return;-+ ValidateResult validate_result = mContactConstraintManager.ValidateContactPoint(body1, body2, body1.GetCenterOfMassPosition(), inResult); // Note that the center of mass of body 1 is the start of the sweep and is used as base offset below-+ switch (validate_result)-+ {-+ case ValidateResult::AcceptContact:-+ // Just continue-+ break;-+-+ case ValidateResult::AcceptAllContactsForThisBodyPair:-+ // Accept this and all following contacts from this body-+ mValidateBodyPair = false;-+ break;-+-+ case ValidateResult::RejectContact:-+ return;-+-+ case ValidateResult::RejectAllContactsForThisBodyPair:-+ // Reject this and all following contacts from this body-+ mRejectAll = true;-+ ForceEarlyOut();-+ return;-+ }-+ }-+ else-+ {-+ SoftBodyContactSettings sb_settings;-+ sb_settings.mIsSensor = false;-+ if ((mSoftBodyContactListener == nullptr-+ || mSoftBodyContactListener->OnSoftBodyContactValidate(body2, body1, sb_settings) == SoftBodyValidateResult::AcceptContact) // Note reversal, soft body needs to be first parameter-+ && !sb_settings.mIsSensor) // If the contact listener turned this into a sensor, we want to ignore it-+ {-+ // Convert the soft body contact settings (note bodies are swapped)-+ mCCDBody.mContactSettings.mInvMassScale1 = sb_settings.mInvMassScale2;-+ mCCDBody.mContactSettings.mInvMassScale2 = sb_settings.mInvMassScale1;-+ mCCDBody.mContactSettings.mInvInertiaScale1 = sb_settings.mInvInertiaScale2;-+-+ // Accept this and all following contacts from this body-+ mValidateBodyPair = false;-+ }-+ else-+ {-+ // Reject this and all following contacts from this body-+ mRejectAll = true;-+ ForceEarlyOut();-+ return;-+ }- }- }--@@ -1927,6 +1956,7 @@ void PhysicsSystem::JobFindCCDContacts(const PhysicsUpdateContext *ioContext, Ph- private:- const BodyManager & mBodyManager;- ContactConstraintManager & mContactConstraintManager;-+ SoftBodyContactListener * mSoftBodyContactListener;- CCDBody & mCCDBody;- ShapeCastResult & mResult;- float mDeltaTime;-@@ -1935,7 +1965,7 @@ void PhysicsSystem::JobFindCCDContacts(const PhysicsUpdateContext *ioContext, Ph-- // Narrowphase collector- ShapeCastResult cast_shape_result;-- CCDNarrowPhaseCollector np_collector(mBodyManager, mContactManager, ccd_body, cast_shape_result, ioContext->mStepDeltaTime);-+ CCDNarrowPhaseCollector np_collector(mBodyManager, mContactManager, mSoftBodyContactListener, ccd_body, cast_shape_result, ioContext->mStepDeltaTime);-- // This collector wraps the narrowphase collector and collects the closest hit- class CCDBroadPhaseCollector : public CastShapeBodyCollector-@@ -2058,7 +2088,15 @@ void PhysicsSystem::JobFindCCDContacts(const PhysicsUpdateContext *ioContext, Ph- manifold.mWorldSpaceNormal = ccd_body.mContactNormal;-- // Call contact point callbacks-- mContactManager.OnCCDContactAdded(contact_allocator, body, body2, manifold, ccd_body.mContactSettings);-+ if (body2.IsRigidBody())-+ mContactManager.OnCCDContactAdded(contact_allocator, body, body2, manifold, ccd_body.mContactSettings);-+ else-+ {-+ // We already have mass and inertia scale from the OnSoftBodyContactValidate callback, but we need to fill in the rest of the contact settings-+ ccd_body.mContactSettings.mCombinedFriction = 0.0f; // Soft bodies CCD contacts don't apply friction-+ ccd_body.mContactSettings.mCombinedRestitution = mContactManager.GetCombineRestitution()(body, SubShapeID(), body2, SubShapeID()); // Soft bodies don't pass sub shape IDs because the restitution is uniform across the entire body-+ ccd_body.mContactSettings.mIsSensor = false; // We've filtered out sensors already-+ }-- if (ccd_body.mContactSettings.mIsSensor)- {-@@ -2281,6 +2319,19 @@ void PhysicsSystem::JobResolveCCDContacts(PhysicsUpdateContext *ioContext, Physi- vtx0.mVelocity += delta_v2 * vtx0.mInvMass;- vtx1.mVelocity += delta_v2 * vtx1.mInvMass;- vtx2.mVelocity += delta_v2 * vtx2.mInvMass;-+-+ // If there's a contact listener, we need to flag this vertex as having had collision and force a contact callback.-+ // Note that during the soft body update that follows this, it is likely that a new collision will be found and that this will be overwritten.-+ if (mSoftBodyContactListener != nullptr)-+ {-+ BodyID body_id = ccd_body->mBodyID1;-+ Vec3 local_normal = inv_body2_transform.Multiply3x3(ccd_body->mContactNormal);-+ Plane contact_plane = Plane::sFromPointAndNormal(local_contact, local_normal);-+ vtx0.MarkCCDContact(body_id, contact_plane);-+ vtx1.MarkCCDContact(body_id, contact_plane);-+ vtx2.MarkCCDContact(body_id, contact_plane);-+ soft_mp->RequestContactCallback();-+ }- }-- // Clamp velocity of body 1-diff --git a/thirdparty/jolt_physics/Jolt/Physics/SoftBody/SoftBodyManifold.h b/thirdparty/jolt_physics/Jolt/Physics/SoftBody/SoftBodyManifold.h-index de21ec50..57a244ad 100644---- a/thirdparty/jolt_physics/Jolt/Physics/SoftBody/SoftBodyManifold.h-+++ b/thirdparty/jolt_physics/Jolt/Physics/SoftBody/SoftBodyManifold.h-@@ -36,7 +36,15 @@ public:- /// Get the body with which the vertex has collided in this update- JPH_INLINE BodyID GetContactBodyID(const SoftBodyVertex &inVertex) const- {-- return inVertex.mHasContact? mCollidingShapes[inVertex.mCollidingShapeIndex].mBodyID : BodyID();-+ if (!inVertex.mHasContact)-+ return BodyID();-+-+ // If this is a CCD contact, the BodyID is encoded in mCollidingShapeIndex-+ if (inVertex.mCollidingShapeIndex & int(BodyID::cBroadPhaseBit))-+ return BodyID(uint32(inVertex.mCollidingShapeIndex) ^ BodyID::cBroadPhaseBit);-+-+ // Otherwise we can get it from mCollidingShapes-+ return mCollidingShapes[inVertex.mCollidingShapeIndex].mBodyID;- }-- /// Get the number of sensors that are in contact with the soft body-diff --git a/thirdparty/jolt_physics/Jolt/Physics/SoftBody/SoftBodyMotionProperties.cpp b/thirdparty/jolt_physics/Jolt/Physics/SoftBody/SoftBodyMotionProperties.cpp-index 4aa88d20..327145ed 100644---- a/thirdparty/jolt_physics/Jolt/Physics/SoftBody/SoftBodyMotionProperties.cpp-+++ b/thirdparty/jolt_physics/Jolt/Physics/SoftBody/SoftBodyMotionProperties.cpp-@@ -121,15 +121,13 @@ void SoftBodyMotionProperties::DetermineCollidingShapes(const SoftBodyUpdateCont- {- JPH_PROFILE_FUNCTION();--- // Reset flag prior to collision detection-- mNeedContactCallback.store(false, memory_order_relaxed);--- struct Collector : public CollideShapeBodyCollector- {-- Collector(const SoftBodyUpdateContext &inContext, const PhysicsSystem &inSystem, const BodyLockInterface &inBodyLockInterface, const AABox &inLocalBounds, SimShapeFilterWrapper &inShapeFilter, Array<CollidingShape> &ioHits, Array<CollidingSensor> &ioSensors) :-+ Collector(const SoftBodyUpdateContext &inContext, const PhysicsSystem &inSystem, const BodyLockInterface &inBodyLockInterface, const AABox &inLocalBounds, const AABox &inWorldBounds, SimShapeFilterWrapper &inShapeFilter, Array<CollidingShape> &ioHits, Array<CollidingSensor> &ioSensors) :- mContext(inContext),- mInverseTransform(inContext.mCenterOfMassTransform.InversedRotationTranslation()),- mLocalBounds(inLocalBounds),-+ mWorldBounds(inWorldBounds),- mBodyLockInterface(inBodyLockInterface),- mCombineFriction(inSystem.GetCombineFriction()),- mCombineRestitution(inSystem.GetCombineRestitution()),-@@ -147,7 +145,8 @@ void SoftBodyMotionProperties::DetermineCollidingShapes(const SoftBodyUpdateCont- const Body &soft_body = *mContext.mBody;- const Body &body = lock.GetBody();- if (body.IsRigidBody() // TODO: We should support soft body vs soft body-- && soft_body.GetCollisionGroup().CanCollide(body.GetCollisionGroup()))-+ && soft_body.GetCollisionGroup().CanCollide(body.GetCollisionGroup())-+ && mWorldBounds.Overlaps(body.GetWorldSpaceBounds())) // In the broadphase we widen the bounding box when a body moves, do a final check to see if the bounding boxes actually overlap- {- SoftBodyContactSettings settings;- settings.mIsSensor = body.IsSensor();-@@ -227,6 +226,7 @@ void SoftBodyMotionProperties::DetermineCollidingShapes(const SoftBodyUpdateCont- const SoftBodyUpdateContext &mContext;- RMat44 mInverseTransform;- AABox mLocalBounds;-+ AABox mWorldBounds;- const BodyLockInterface & mBodyLockInterface;- ContactConstraintManager::CombineFunction mCombineFriction;- ContactConstraintManager::CombineFunction mCombineRestitution;-@@ -246,7 +246,7 @@ void SoftBodyMotionProperties::DetermineCollidingShapes(const SoftBodyUpdateCont- // Create shape filter- SimShapeFilterWrapper shape_filter(inContext.mSimShapeFilter, inContext.mBody);--- Collector collector(inContext, inSystem, inBodyLockInterface, local_bounds, shape_filter, mCollidingShapes, mCollidingSensors);-+ Collector collector(inContext, inSystem, inBodyLockInterface, local_bounds, world_bounds, shape_filter, mCollidingShapes, mCollidingSensors);- ObjectLayer layer = inContext.mBody->GetObjectLayer();- DefaultBroadPhaseLayerFilter broadphase_layer_filter = inSystem.GetDefaultBroadPhaseLayerFilter(layer);- DefaultObjectLayerFilter object_layer_filter = inSystem.GetDefaultLayerFilter(layer);-@@ -285,7 +285,7 @@ void SoftBodyMotionProperties::DetermineSensorCollisions(CollidingSensor &ioSens-- // We need a contact callback if one of the sensors collided- if (ioSensor.mHasContact)-- mNeedContactCallback.store(true, memory_order_relaxed);-+ RequestContactCallback();- }-- void SoftBodyMotionProperties::ApplyPressure(const SoftBodyUpdateContext &inContext)-@@ -714,6 +714,7 @@ void SoftBodyMotionProperties::ApplyCollisionConstraintsAndUpdateVelocities(cons- v.mVelocity = (v.mPosition - v.mPreviousPosition) / dt;-- // Satisfy collision constraint-+ static_assert(int(BodyID::cBroadPhaseBit) < 0); // CCD contacts should be negative too (see: SoftBodyVertex::MarkCCDContact)- if (v.mCollidingShapeIndex >= 0)- {- // Check if there is a collision-@@ -724,7 +725,7 @@ void SoftBodyMotionProperties::ApplyCollisionConstraintsAndUpdateVelocities(cons- v.mHasContact = true;-- // We need a contact callback if one of the vertices collided-- mNeedContactCallback.store(true, memory_order_relaxed);-+ RequestContactCallback();-- // Note that we already calculated the velocity, so this does not affect the velocity (next iteration starts by setting previous position to current position)- CollidingShape &cs = mCollidingShapes[v.mCollidingShapeIndex];-@@ -839,6 +840,8 @@ void SoftBodyMotionProperties::UpdateSoftBodyState(SoftBodyUpdateContext &ioCont- }-- ioContext.mContactListener->OnSoftBodyContactAdded(*ioContext.mBody, SoftBodyManifold(this));-+-+ mNeedContactCallback.store(false, memory_order_relaxed);- }-- // Loop through vertices once more to update the global state-diff --git a/thirdparty/jolt_physics/Jolt/Physics/SoftBody/SoftBodyMotionProperties.h b/thirdparty/jolt_physics/Jolt/Physics/SoftBody/SoftBodyMotionProperties.h-index 8768efd6..918ce366 100644---- a/thirdparty/jolt_physics/Jolt/Physics/SoftBody/SoftBodyMotionProperties.h-+++ b/thirdparty/jolt_physics/Jolt/Physics/SoftBody/SoftBodyMotionProperties.h-@@ -176,6 +176,9 @@ public:- /// Update the velocities of all rigid bodies that we collided with. Not part of the public API.- void UpdateRigidBodyVelocities(const SoftBodyUpdateContext &inContext, BodyInterface &inBodyInterface);--+ /// Set a flag to indicate that the ContactListener::OnSoftBodyContactAdded should be called-+ inline void RequestContactCallback() { mNeedContactCallback.store(true, memory_order_relaxed); }-+- private:- // SoftBodyManifold needs to have access to CollidingShape- friend class SoftBodyManifold;-diff --git a/thirdparty/jolt_physics/Jolt/Physics/SoftBody/SoftBodyVertex.h b/thirdparty/jolt_physics/Jolt/Physics/SoftBody/SoftBodyVertex.h-index 72d4291e..261362ef 100644---- a/thirdparty/jolt_physics/Jolt/Physics/SoftBody/SoftBodyVertex.h-+++ b/thirdparty/jolt_physics/Jolt/Physics/SoftBody/SoftBodyVertex.h-@@ -23,6 +23,14 @@ public:- mHasContact = false;- }--+ /// Mark this vertex as being in contact with inBodyID-+ inline void MarkCCDContact(const BodyID &inBodyID, const Plane &inContactPlane)-+ {-+ mCollisionPlane = inContactPlane;-+ mCollidingShapeIndex = int(inBodyID.GetIndexAndSequenceNumber() | BodyID::cBroadPhaseBit); // We reuse the broad phase bit to indicate this is a CCD contact-+ mHasContact = true;-+ }-+- Vec3 mPreviousPosition; ///< Internal use only. Position at the previous time step- Vec3 mPosition; ///< Position, relative to the center of mass of the soft body- Vec3 mVelocity; ///< Velocity, relative to the center of mass of the soft body