Jelajahi Sumber

Add anti overflow

Miloslav Ciz 4 tahun lalu
induk
melakukan
c36ab27741
2 mengubah file dengan 16 tambahan dan 16 penghapusan
  1. 5 9
      test_sdl.c
  2. 11 7
      tinyphysicsengine.h

+ 5 - 9
test_sdl.c

@@ -346,8 +346,8 @@ int main()
 //  addBody(TPE_SHAPE_CAPSULE,256,0,0);
 //addBody(TPE_SHAPE_CAPSULE,300,1024,0);
 
-  addBody(TPE_SHAPE_CUBOID,1200,1200,1200);
-  addBody(TPE_SHAPE_CUBOID,1400,800,1000);
+  addBody(TPE_SHAPE_CUBOID,1000,600,800);
+  addBody(TPE_SHAPE_CUBOID,700,800,650);
 
   //-------
   S3L_Model3D models[bodyCount];
@@ -363,8 +363,8 @@ int main()
 
   TPE_Unit frame = 0;
 
-bodies[0].body.position.x = -700;
-bodies[1].body.position.x = 800;
+bodies[0].body.position.x = -200;
+bodies[1].body.position.x = 100;
 bodies[1].body.position.z = -100;
 
 bodies[0].body.position = TPE_vec4(2875,-950,0,0);
@@ -382,11 +382,6 @@ TPE_rotationToQuaternion(TPE_vec4(0,0,255,0),40,&quat);
 TPE_bodySetOrientation(&(bodies[0].body),quat);
 */
 
-TPE_Vec4 aaaaaa = TPE_bodyGetPointVelocity(&(bodies[0].body),
-TPE_vec4(300,0,0,0));
-
-TPE_PRINTF_VEC4(aaaaaa)
-
 int collided = 0;
 
   while (running)
@@ -403,6 +398,7 @@ int collided = 0;
     TPE_Vec4 p, n;
 
 #define BOUND 3000
+
 for (int i = 0; i < bodyCount; ++i)
 {
   if (bodies[i].body.position.x > BOUND ||

+ 11 - 7
tinyphysicsengine.h

@@ -638,15 +638,18 @@ void _TPE_cutLineSegmentByPlanes(TPE_Vec4 center, TPE_Vec4 sideOffset,
 
   TPE_Unit denom = TPE_nonZero(TPE_vec3DotProductPlain(sideOffset,lineDir));
 
-  TPE_Unit tA = 
-    ((TPE_vec3DotProductPlain(sideOffset,dc) - da) * TPE_FRACTIONS_PER_UNIT) 
-    / denom;
+#define tAntiOverflow(t) \
+  TPE_Unit t = TPE_vec3DotProductPlain(sideOffset,dc) - da;\
+  t = (TPE_abs(t) < 500000) ? (t * TPE_FRACTIONS_PER_UNIT) / denom :\
+    (((t / 64) * TPE_FRACTIONS_PER_UNIT) / TPE_nonZero(denom / 64));
+
+  tAntiOverflow(tA)  
 
   dc = TPE_vec3Minus(center,sideOffset);
 
-  TPE_Unit tB = 
-    ((TPE_vec3DotProductPlain(sideOffset,dc) - da) * TPE_FRACTIONS_PER_UNIT) 
-    / denom;
+  tAntiOverflow(tB)
+
+#undef tAntiOverflow
 
   if (tB < tA)
   {
@@ -671,7 +674,8 @@ TPE_Unit TPE_bodyCollides(const TPE_Body *body1, const TPE_Body *body2,
 
   if (collType != TPE_COLLISION_TYPE(TPE_SHAPE_SPHERE,TPE_SHAPE_SPHERE))
   {
-    // initial bounding sphere check to quickly discard impossible collisions
+    /* initial bounding sphere check to quickly discard impossible collisions,
+       plus this also prevents overflow errors in long-distance computations */
 
     // TODO: taxicab could be also considered here