67 if (dt <= 0.0f)
return;
68 dt = std::min(dt, 1.0f / 30.0f);
70 glm::vec3 gravityVector{0.0f, -9.81f, 0.0f};
76 rb.hadContactThisFrame =
false;
77 rb.unstableContactThisFrame =
false;
81 bool externalVel = glm::length(rb.velocity) > 0.08f;
82 bool externalAngVel= glm::length(rb.angularVelocity) > 0.15f;
83 bool externalForce = glm::length(rb.force) > 0.01f ||
84 glm::length(rb.torque) > 0.01f;
85 if (externalVel || externalAngVel || externalForce) {
89 rb.force = glm::vec3(0.0f);
90 rb.torque = glm::vec3(0.0f);
95 float massVal = rb.mass;
96 if (massVal < 1e-4f || std::isnan(massVal) || std::isinf(massVal)) {
101 glm::vec3 gravityForce = gravityVector * rb.gravityScale * massVal;
102 glm::vec3 totalForce = rb.force + gravityForce;
104 if (rb.freezePositionX) { totalForce.x = 0.0f; rb.velocity.x = 0.0f; }
105 if (rb.freezePositionY) { totalForce.y = 0.0f; rb.velocity.y = 0.0f; }
106 if (rb.freezePositionZ) { totalForce.z = 0.0f; rb.velocity.z = 0.0f; }
108 glm::vec3 accel = totalForce / massVal;
109 if (std::isnan(accel.x) || std::isinf(accel.x)) accel = glm::vec3(0.0f);
111 rb.velocity += accel * dt;
112 rb.velocity *= std::exp(-rb.linearDrag * dt);
114 if (rb.freezePositionX) rb.velocity.x = 0.0f;
115 if (rb.freezePositionY) rb.velocity.y = 0.0f;
116 if (rb.freezePositionZ) rb.velocity.z = 0.0f;
118 if (std::isnan(rb.velocity.x) || std::isinf(rb.velocity.x)) rb.velocity = glm::vec3(0.0f);
120 transform.position += rb.velocity * dt;
122 if (std::isnan(transform.position.x) || std::isinf(transform.position.x) ||
123 std::isnan(transform.position.y) || std::isinf(transform.position.y) ||
124 std::isnan(transform.position.z) || std::isinf(transform.position.z)) {
125 transform.position = glm::vec3(0.0f);
126 rb.velocity = glm::vec3(0.0f);
129 if (std::isnan(rb.angularVelocity.x) || std::isinf(rb.angularVelocity.x)) {
130 rb.angularVelocity = glm::vec3(0.0f);
133 if (rb.freezeRotationX) { rb.torque.x = 0.0f; rb.angularVelocity.x = 0.0f; }
134 if (rb.freezeRotationY) { rb.torque.y = 0.0f; rb.angularVelocity.y = 0.0f; }
135 if (rb.freezeRotationZ) { rb.torque.z = 0.0f; rb.angularVelocity.z = 0.0f; }
137 float inertiaScale = 0.5f * massVal;
138 glm::vec3 angularAccel = rb.torque / (inertiaScale > 1e-4f ? inertiaScale : 1.0f);
139 rb.angularVelocity += angularAccel * dt;
141 rb.angularVelocity *= std::exp(-rb.angularDrag * dt);
143 if (rb.freezeRotationX) rb.angularVelocity.x = 0.0f;
144 if (rb.freezeRotationY) rb.angularVelocity.y = 0.0f;
145 if (rb.freezeRotationZ) rb.angularVelocity.z = 0.0f;
149 rb.force = glm::vec3(0.0f);
150 rb.torque = glm::vec3(0.0f);
154 struct ColliderEntry {
160 std::vector<ColliderEntry> colliders;
162 colliders.push_back({entity, &transform, &collider});
165 const int passes = 6;
166 const float solverDt = dt /
static_cast<float>(passes);
167 for (
int pass = 0; pass < passes; ++pass) {
168 for (
size_t i = 0; i < colliders.size(); ++i) {
169 for (
size_t j = i + 1; j < colliders.size(); ++j) {
170 auto& entryA = colliders[i];
171 auto& entryB = colliders[j];
174 entryA.entity, *entryA.collider,
175 entryB.entity, *entryB.collider
180 entryA.entity, *entryA.transform, *entryA.collider,
181 entryB.entity, *entryB.transform, *entryB.collider,
192 const float sleepLinThresh = 0.08f;
193 const float sleepAngThresh = 0.15f;
197 if (rb.sleeping)
continue;
199 float linSpeed = glm::length(rb.velocity);
200 float angSpeed = glm::length(rb.angularVelocity);
202 if (linSpeed < sleepLinThresh && angSpeed < sleepAngThresh) {
203 if (rb.hadContactThisFrame && !rb.unstableContactThisFrame) {
205 if (rb.sleepTimer >= 0.5f) {
206 rb.velocity = glm::vec3(0.0f);
207 rb.angularVelocity = glm::vec3(0.0f);
209 rb.sleepTimer = 0.0f;
212 rb.sleepTimer = 0.0f;
216 rb.sleepTimer = 0.0f;
224 closestHit.
distance = std::numeric_limits<float>::max();
228 glm::vec3 colPos = glm::vec3(worldM * glm::vec4(collider.offset, 1.0f));
232 float scaleX = glm::length(glm::vec3(worldM[0]));
233 float scaleY = glm::length(glm::vec3(worldM[1]));
234 float scaleZ = glm::length(glm::vec3(worldM[2]));
235 float worldRadius = collider.radius * std::max({scaleX, scaleY, scaleZ});
237 glm::vec3 oc = ray.
origin - colPos;
239 float c = glm::dot(oc, oc) - worldRadius * worldRadius;
241 if (c > 0.0f && b > 0.0f)
continue;
242 float discriminant = b * b - c;
244 if (discriminant >= 0.0f) {
245 float t = -b - std::sqrt(discriminant);
246 if (t < 0.0f) t = -b + std::sqrt(discriminant);
255 glm::vec3 aabbMin = colPos - collider.extents;
256 glm::vec3 aabbMax = colPos + collider.extents;
258 float tmin = 0.0f, tmax = std::numeric_limits<float>::max();
259 bool intersect =
true;
261 for (
int i = 0; i < 3; ++i) {
262 if (std::abs(ray.
direction[i]) < 1e-6f) {
263 if (ray.
origin[i] < aabbMin[i] || ray.
origin[i] > aabbMax[i]) {
269 float t1 = (aabbMin[i] - ray.
origin[i]) * invD;
270 float t2 = (aabbMax[i] - ray.
origin[i]) * invD;
271 if (t1 > t2) std::swap(t1, t2);
272 tmin = std::max(tmin, t1);
273 tmax = std::min(tmax, t2);
281 if (intersect && tmax >= 0.0f) {
286 glm::vec3 hitLocal = hit.
position - colPos;
287 glm::vec3 normal(0.0f);
288 float minDist = std::numeric_limits<float>::max();
289 for (
int i = 0; i < 3; ++i) {
290 float distToMax = std::abs(collider.extents[i] - hitLocal[i]);
291 if (distToMax < minDist) {
293 normal = glm::vec3(0.0f);
296 float distToMin = std::abs(-collider.extents[i] - hitLocal[i]);
297 if (distToMin < minDist) {
299 normal = glm::vec3(0.0f);
306 glm::mat4 invM = glm::inverse(worldM);
307 glm::vec3 localOrigin = glm::vec3(invM * glm::vec4(ray.
origin, 1.0f));
308 glm::vec3 localDir = glm::normalize(glm::vec3(invM * glm::vec4(ray.
direction, 0.0f)));
310 glm::vec3 boxMin = collider.offset - collider.extents;
311 glm::vec3 boxMax = collider.offset + collider.extents;
313 float tmin = 0.0f, tmax = std::numeric_limits<float>::max();
314 bool intersect =
true;
316 for (
int i = 0; i < 3; ++i) {
317 if (std::abs(localDir[i]) < 1e-6f) {
318 if (localOrigin[i] < boxMin[i] || localOrigin[i] > boxMax[i]) {
323 float invD = 1.0f / localDir[i];
324 float t1 = (boxMin[i] - localOrigin[i]) * invD;
325 float t2 = (boxMax[i] - localOrigin[i]) * invD;
326 if (t1 > t2) std::swap(t1, t2);
327 tmin = std::max(tmin, t1);
328 tmax = std::min(tmax, t2);
336 if (intersect && tmax >= 0.0f) {
337 glm::vec3 localHitPos = localOrigin + localDir * tmin;
338 glm::vec3 worldHitPos = glm::vec3(worldM * glm::vec4(localHitPos, 1.0f));
344 glm::vec3 hitLocal = localHitPos - collider.offset;
345 glm::vec3 localNormal(0.0f);
346 float minDist = std::numeric_limits<float>::max();
347 for (
int i = 0; i < 3; ++i) {
348 float distToMax = std::abs(collider.extents[i] - hitLocal[i]);
349 if (distToMax < minDist) {
351 localNormal = glm::vec3(0.0f);
352 localNormal[i] = 1.0f;
354 float distToMin = std::abs(-collider.extents[i] - hitLocal[i]);
355 if (distToMin < minDist) {
357 localNormal = glm::vec3(0.0f);
358 localNormal[i] = -1.0f;
361 hit.
normal = glm::normalize(glm::vec3(worldM * glm::vec4(localNormal, 0.0f)));
367 closestHit.
entity = entity;
533 glm::vec3 candidateAxes[15];
536 for (
int i = 0; i < 3; ++i) candidateAxes[axisCount++] = obbA.
axes[i];
537 for (
int i = 0; i < 3; ++i) candidateAxes[axisCount++] = obbB.
axes[i];
538 for (
int i = 0; i < 3; ++i) {
539 for (
int j = 0; j < 3; ++j) {
540 glm::vec3
axis = glm::cross(obbA.
axes[i], obbB.
axes[j]);
541 float axisLen = glm::length(
axis);
542 if (axisLen > 1e-4f) {
543 candidateAxes[axisCount++] =
axis / axisLen;
548 float minBiasedOverlap = std::numeric_limits<float>::max();
549 float bestUnbiasedOverlap = 0.0f;
550 glm::vec3 bestAxis(0.0f);
552 for (
int i = 0; i < axisCount; ++i) {
553 glm::vec3 L = candidateAxes[i];
554 float d = std::abs(glm::dot(T, L));
556 float rA = obbA.
extents.x * std::abs(glm::dot(obbA.
axes[0], L)) +
557 obbA.
extents.y * std::abs(glm::dot(obbA.
axes[1], L)) +
558 obbA.
extents.z * std::abs(glm::dot(obbA.
axes[2], L));
560 float rB = obbB.
extents.x * std::abs(glm::dot(obbB.
axes[0], L)) +
561 obbB.
extents.y * std::abs(glm::dot(obbB.
axes[1], L)) +
562 obbB.
extents.z * std::abs(glm::dot(obbB.
axes[2], L));
564 float overlap = (rA + rB) - d;
565 if (overlap <= 0.0f)
return info;
567 float biasedOverlap = overlap;
568 if (i >= 6) biasedOverlap *= 1.15f;
570 if (biasedOverlap < minBiasedOverlap) {
571 minBiasedOverlap = biasedOverlap;
572 bestUnbiasedOverlap = overlap;
579 if (glm::dot(T, bestAxis) < 0.0f) bestAxis = -bestAxis;
582 int bestAxisIndex = -1;
583 for (
int i = 0; i < axisCount; ++i) {
584 if (glm::length(candidateAxes[i] - bestAxis) < 1e-3f || glm::length(candidateAxes[i] + bestAxis) < 1e-3f) {
590 if (bestAxisIndex >= 0 && bestAxisIndex < 6) {
592 glm::vec3 planePointA = obbA.
center;
593 for (
int i = 0; i < 3; ++i) {
594 planePointA += (glm::dot(obbA.
axes[i], bestAxis) >= 0.0f ? 1.0f : -1.0f) * obbA.
extents[i] * obbA.
axes[i];
597 glm::vec3 planePointB = obbB.
center;
598 for (
int i = 0; i < 3; ++i) {
599 planePointB += (glm::dot(obbB.
axes[i], -bestAxis) >= 0.0f ? 1.0f : -1.0f) * obbB.
extents[i] * obbB.
axes[i];
603 glm::vec3 verticesB[8];
605 for (
float x : {-1.0f, 1.0f}) {
606 for (
float y : {-1.0f, 1.0f}) {
607 for (
float z : {-1.0f, 1.0f}) {
612 for (
const auto& V : verticesB) {
613 float depth = glm::dot(planePointA - V, bestAxis);
614 if (
depth > -1e-4f) {
615 glm::vec3 toV = V - obbA.
center;
617 for (
int i = 0; i < 3; ++i) {
618 if (std::abs(glm::dot(toV, obbA.
axes[i])) > obbA.
extents[i] + 0.05f) { inside =
false;
break; }
628 glm::vec3 verticesA[8];
630 for (
float x : {-1.0f, 1.0f}) {
631 for (
float y : {-1.0f, 1.0f}) {
632 for (
float z : {-1.0f, 1.0f}) {
637 for (
const auto& V : verticesA) {
638 float depth = glm::dot(V - planePointB, bestAxis);
639 if (
depth > -1e-4f) {
640 glm::vec3 toV = V - obbB.
center;
642 for (
int i = 0; i < 3; ++i) {
643 if (std::abs(glm::dot(toV, obbB.
axes[i])) > obbB.
extents[i] + 0.05f) { inside =
false;
break; }
655 glm::vec3 supportA = obbA.
center;
656 for (
int i = 0; i < 3; ++i) supportA += (glm::dot(obbA.
axes[i], bestAxis) >= 0.0f ? 1.0f : -1.0f) * obbA.
extents[i] * obbA.
axes[i];
657 glm::vec3 supportB = obbB.
center;
658 for (
int i = 0; i < 3; ++i) supportB += (glm::dot(obbB.
axes[i], -bestAxis) >= 0.0f ? 1.0f : -1.0f) * obbB.
extents[i] * obbB.
axes[i];
660 if (bestAxisIndex >= 0 && bestAxisIndex < 3) info.
contactPoints[0] = supportB;
661 else if (bestAxisIndex >= 3 && bestAxisIndex < 6) info.
contactPoints[0] = supportA;
738 if (staticA && staticB)
return;
745 glm::vec3 normal = glm::normalize(colInfo.
normal);
747 if (staticA || staticB) {
748 const OBB& staticOBB = staticA ? obbA : obbB;
749 float maxDot = 0.0f;
int bestAxisIndex = -1;
float bestSign = 1.0f;
750 for (
int i = 0; i < 3; ++i) {
751 float dotVal = glm::dot(normal, staticOBB.
axes[i]);
752 if (std::abs(dotVal) > maxDot) { maxDot = std::abs(dotVal); bestAxisIndex = i; bestSign = (dotVal >= 0.0f) ? 1.0f : -1.0f; }
754 if (maxDot > 0.95f) normal = bestSign * staticOBB.
axes[bestAxisIndex];
758 if (!staticB) rbB->hadContactThisFrame =
true;
760 bool aSleeping = rbA && rbA->
sleeping;
761 bool bSleeping = rbB && rbB->sleeping;
763 if (!rb || !rb->
sleeping || otherStatic || !other || other->sleeping)
return;
766 wakeIfMoving(rbA, rbB, staticB); wakeIfMoving(rbB, rbA, staticA);
768 aSleeping = rbA && rbA->
sleeping; bSleeping = rbB && rbB->sleeping;
769 bool skipVelocityA = aSleeping && (staticB || bSleeping);
770 bool skipVelocityB = bSleeping && (staticA || aSleeping);
773 glm::mat3 invInertiaWorldA(0.0f);
774 float invMassA = (staticA || rbA->
mass < 1e-4f) ? 0.0f : 1.0f / rbA->
mass;
775 if (!staticA && rbA->
mass > 1e-4f) {
776 glm::mat3 R = glm::mat3(obbA.
axes[0], obbA.
axes[1], obbA.
axes[2]);
777 glm::mat3 invInertiaLocal(0.0f);
779 invInertiaLocal = glm::mat3(2.5f / (rbA->
mass * colA.
radius * colA.
radius));
782 invInertiaLocal[0][0] = 1.0f / ((1.0f / 12.0f) * rbA->
mass * (ey * ey + ez * ez));
783 invInertiaLocal[1][1] = 1.0f / ((1.0f / 12.0f) * rbA->
mass * (ex * ex + ez * ez));
784 invInertiaLocal[2][2] = 1.0f / ((1.0f / 12.0f) * rbA->
mass * (ex * ex + ey * ey));
786 invInertiaWorldA = R * invInertiaLocal * glm::transpose(R);
789 glm::mat3 invInertiaWorldB(0.0f);
790 float invMassB = (staticB || rbB->mass < 1e-4f) ? 0.0f : 1.0f / rbB->mass;
791 if (!staticB && rbB->mass > 1e-4f) {
792 glm::mat3 R = glm::mat3(obbB.
axes[0], obbB.
axes[1], obbB.
axes[2]);
793 glm::mat3 invInertiaLocal(0.0f);
795 invInertiaLocal = glm::mat3(2.5f / (rbB->mass * colB.
radius * colB.
radius));
798 invInertiaLocal[0][0] = 1.0f / ((1.0f / 12.0f) * rbB->mass * (ey * ey + ez * ez));
799 invInertiaLocal[1][1] = 1.0f / ((1.0f / 12.0f) * rbB->mass * (ex * ex + ez * ez));
800 invInertiaLocal[2][2] = 1.0f / ((1.0f / 12.0f) * rbB->mass * (ex * ex + ey * ey));
802 invInertiaWorldB = R * invInertiaLocal * glm::transpose(R);
805 auto computeK = [&](
float invM_A,
float invM_B,
const glm::mat3& invI_A,
const glm::mat3& invI_B,
const glm::vec3& r_A,
const glm::vec3& r_B,
const glm::vec3& dir) {
806 float K = invM_A + invM_B;
807 if (invM_A > 0.0f) K += glm::dot(glm::cross(invI_A * glm::cross(r_A, dir), r_A), dir);
808 if (invM_B > 0.0f) K += glm::dot(glm::cross(invI_B * glm::cross(r_B, dir), r_B), dir);
813 if (contactCount == 0)
return;
816 float slop = 0.0001f;
817 float baumgarte = 0.5f;
818 for (
int cp = 0; cp < contactCount; ++cp) {
823 if (penetration > slop) {
824 float K_pos = computeK(invMassA, invMassB, invInertiaWorldA, invInertiaWorldB, rA, rB, normal);
826 float J_p = ((penetration - slop) * baumgarte / K_pos) /
static_cast<float>(contactCount);
827 glm::vec3 C_p = J_p * normal;
840 if (skipVelocityA && skipVelocityB)
return;
843 glm::vec3 initialVelA = rbA ? rbA->
velocity : glm::vec3(0.0f);
844 glm::vec3 initialVelB = rbB ? rbB->velocity : glm::vec3(0.0f);
845 glm::vec3 initialAngVelA = rbA ? rbA->
angularVelocity : glm::vec3(0.0f);
846 glm::vec3 initialAngVelB = rbB ? rbB->angularVelocity : glm::vec3(0.0f);
848 glm::vec3 accumulatedVelA{0.0f}, accumulatedVelB{0.0f};
849 glm::vec3 accumulatedAngVelA{0.0f}, accumulatedAngVelB{0.0f};
850 float totalImpulseScalar = 0.0f;
852 for (
int cp = 0; cp < contactCount; ++cp) {
856 glm::vec3 contactVelA = initialVelA + glm::cross(initialAngVelA, rA);
857 glm::vec3 contactVelB = initialVelB + glm::cross(initialAngVelB, rB);
858 glm::vec3 relativeVel = contactVelB - contactVelA;
860 float velAlongNormal = glm::dot(relativeVel, normal);
861 float restitutionA = rbA ? rbA->
restitution : 0.5f;
862 float restitutionB = rbB ? rbB->restitution : 0.5f;
863 float e = std::min(restitutionA, restitutionB);
865 if (velAlongNormal > -0.25f || glm::dot(initialVelB - initialVelA, normal) > -0.25f) e = 0.0f;
867 float K_vel = computeK(invMassA, invMassB, invInertiaWorldA, invInertiaWorldB, rA, rB, normal);
868 float impulseScalar = 0.0f;
870 if (K_vel > 1e-4f && velAlongNormal < 0.0f) {
871 impulseScalar = (-(1.0f + e) * velAlongNormal / K_vel) /
static_cast<float>(contactCount);
874 if (impulseScalar > 0.0f) {
875 glm::vec3 impulse = impulseScalar * normal;
876 if (!staticA && !skipVelocityA) {
877 accumulatedVelA -= invMassA * impulse;
878 accumulatedAngVelA -= invInertiaWorldA * glm::cross(rA, impulse);
880 if (!staticB && !skipVelocityB) {
881 accumulatedVelB += invMassB * impulse;
882 accumulatedAngVelB += invInertiaWorldB * glm::cross(rB, impulse);
884 totalImpulseScalar += impulseScalar;
888 glm::vec3 tangent = relativeVel - glm::dot(relativeVel, normal) * normal;
889 float tangentLen = glm::length(tangent);
890 if (tangentLen > 1e-5f) {
891 tangent = glm::normalize(tangent);
892 float K_tangent = computeK(invMassA, invMassB, invInertiaWorldA, invInertiaWorldB, rA, rB, tangent);
893 if (K_tangent > 1e-4f) {
894 float tangentImpulseScalar = (-tangentLen / K_tangent) /
static_cast<float>(contactCount);
895 float frictionA = rbA ? rbA->
friction : 0.3f;
896 float frictionB = rbB ? rbB->friction : 0.3f;
897 float mu = std::sqrt(frictionA * frictionB);
899 float effectiveNormalImpulse = impulseScalar;
901 float activeMass = (rbA && !staticA) ? rbA->
mass : ((rbB && !staticB) ? rbB->mass : 1.0f);
902 effectiveNormalImpulse = (activeMass * 9.81f * dt) /
static_cast<float>(contactCount);
904 float maxFriction = mu * effectiveNormalImpulse;
906 if (std::abs(tangentImpulseScalar) > maxFriction) {
907 tangentImpulseScalar = (tangentImpulseScalar > 0.0f) ? maxFriction : -maxFriction;
910 glm::vec3 tangentImpulse = tangentImpulseScalar * tangent;
911 if (!staticA && !skipVelocityA) {
912 accumulatedVelA -= invMassA * tangentImpulse;
913 accumulatedAngVelA -= invInertiaWorldA * glm::cross(rA, tangentImpulse);
915 if (!staticB && !skipVelocityB) {
916 accumulatedVelB += invMassB * tangentImpulse;
917 accumulatedAngVelB += invInertiaWorldB * glm::cross(rB, tangentImpulse);
924 if (rbA && !staticA && !skipVelocityA) { rbA->
velocity += accumulatedVelA; rbA->
angularVelocity += accumulatedAngVelA; }
925 if (rbB && !staticB && !skipVelocityB) { rbB->velocity += accumulatedVelB; rbB->angularVelocity += accumulatedAngVelB; }
928 glm::vec3 relAngVel = (rbB ? rbB->angularVelocity : glm::vec3(0.0f)) - (rbA ? rbA->
angularVelocity : glm::vec3(0.0f));
929 float angVelAlongN = glm::dot(relAngVel, normal);
930 if (std::abs(angVelAlongN) > 1e-5f) {
932 if (!staticA) K_rot += glm::dot(invInertiaWorldA * normal, normal);
933 if (!staticB) K_rot += glm::dot(invInertiaWorldB * normal, normal);
936 float rotImpulseScalar = -angVelAlongN / K_rot;
937 float frictionA = rbA ? rbA->
friction : 0.3f;
938 float frictionB = rbB ? rbB->friction : 0.3f;
939 float maxRotFriction = std::sqrt(frictionA * frictionB) * 0.1f * totalImpulseScalar;
941 if (std::abs(rotImpulseScalar) > maxRotFriction) rotImpulseScalar = (rotImpulseScalar > 0.0f) ? maxRotFriction : -maxRotFriction;
942 glm::vec3 rotImpulse = rotImpulseScalar * normal;
944 if (!staticA && !skipVelocityA) rbA->
angularVelocity -= invInertiaWorldA * rotImpulse;
945 if (!staticB && !skipVelocityB) rbB->angularVelocity += invInertiaWorldB * rotImpulse;
959 if (!staticA) applyVelocityConstraints(rbA);
960 if (!staticB) applyVelocityConstraints(rbB);