tinyphysicsengine.h 60 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010
  1. #ifndef TINYPHYSICSENGINE_H
  2. #define TINYPHYSICSENGINE_H
  3. /**
  4. author: Miloslav Ciz
  5. license: CC0 1.0 (public domain)
  6. found at https://creativecommons.org/publicdomain/zero/1.0/
  7. + additional waiver of all IP
  8. version: 0.1d
  9. This is a suckless library for simple 3D (and 2D) physics simulation. The
  10. physics is based on the Newtonian model but is further simplified,
  11. particularly in the area of rotation: there is no moment of inertia for
  12. objects, i.e. every object rotates as if it was a ball, and the object can be
  13. rotating around at most one axis at a time, i.e. it is not possible to
  14. simulate e.g. the Dzhanibekov effect. Therefore the library is mostly intended
  15. for entertainment software.
  16. CONVENTIONS:
  17. - Compatibility and simple usage with small3dlib is intended, so most
  18. convention and data types copy those of small3dlib (which takes a lot of
  19. conventions of OpenGL).
  20. - No floating point is used, we instead use integers (effectively a fixed
  21. point). TPE_FRACTIONS_PER_UNIT is an equivalent to 1.0 in floating point and
  22. all numbers are normalized by this constant.
  23. - Units: for any measure only an abstract mathematical unit is used. This unit
  24. always has TPE_FRACTIONS_PER_UNIT parts. You can assign any correcpondence
  25. with real life units to these units. E.g. 1 spatial unit (which you can see
  26. as e.g. 1 meter) is equal to TPE_FRACTIONS_PER_UNIT. Same with temporatl
  27. (e.g. 1 second) and mass (e.g. 1 kilogram) units, and also any derived
  28. units, e.g. a unit of velocity (e.g. 1 m/s) is also equal to 1
  29. TPE_FRACTIONS_PER_UNIT. A full angle is also split into
  30. TPE_FRACTIONS_PER_UNIT parts (instead of 2 * PI or degrees).
  31. - Quaternions are represented as vec4 where x ~ i, y ~ j, z ~ k, w ~ real.
  32. - There is no vec3 type, vec4 is usead for all vectors, for simplicity.
  33. */
  34. #include <stdint.h>
  35. typedef int32_t TPE_Unit;
  36. /** How many fractions a unit is split into. This is NOT SUPPOSED TO BE
  37. REDEFINED, so rather don't do it (otherwise things may overflow etc.). */
  38. #define TPE_FRACTIONS_PER_UNIT 512
  39. #define TPE_INFINITY 2147483647
  40. #define TPE_PI 1608 ///< pi in TPE_Units
  41. #define TPE_SHAPE_POINT 0 ///< single point in space
  42. #define TPE_SHAPE_SPHERE 1 ///< sphere, params.: radius
  43. #define TPE_SHAPE_CAPSULE 2 ///< capsule: radius, height
  44. #define TPE_SHAPE_CUBOID 3 ///< cuboid, params.: width, height, depth
  45. #define TPE_SHAPE_PLANE 4 ///< plane, params.: width, depth
  46. #define TPE_SHAPE_CYLINDER 5 ///< cylinder, params.: radius, height
  47. #define TPE_SHAPE_TRIMESH 6 /**< triangle mesh, params.:
  48. vertex count,
  49. triangle count
  50. vertices (int32_t pointer),
  51. indices (uint16_t pointer) */
  52. #define TPE_MAX_SHAPE_PARAMS 3
  53. #define TPE_MAX_SHAPE_PARAMPOINTERS 2
  54. #define TPE_BODY_FLAG_DISABLED 0x00 ///< won't take part in simul. at all
  55. #define TPE_BODY_FLAG_NONCOLLIDING 0x01 ///< simulated but won't collide
  56. TPE_Unit TPE_wrap(TPE_Unit value, TPE_Unit mod);
  57. TPE_Unit TPE_clamp(TPE_Unit v, TPE_Unit v1, TPE_Unit v2);
  58. static inline TPE_Unit TPE_abs(TPE_Unit x);
  59. static inline TPE_Unit TPE_nonZero(TPE_Unit x);
  60. /** Returns an integer square root of given value. */
  61. TPE_Unit TPE_sqrt(TPE_Unit value);
  62. /** Multiplies two values (with normalization) so that the result is 0 only if
  63. one or both values are zero. */
  64. TPE_Unit TPE_timesAntiZero(TPE_Unit a, TPE_Unit b);
  65. /** Returns a sine of given arguments, both in TPE_Units (see the library
  66. conventions). */
  67. TPE_Unit TPE_sin(TPE_Unit x);
  68. TPE_Unit TPE_cos(TPE_Unit x);
  69. TPE_Unit TPE_asin(TPE_Unit x);
  70. TPE_Unit TPE_acos(TPE_Unit x);
  71. uint8_t TPE_sign(TPE_Unit x);
  72. typedef struct
  73. {
  74. TPE_Unit x;
  75. TPE_Unit y;
  76. TPE_Unit z;
  77. TPE_Unit w;
  78. } TPE_Vec4;
  79. #define TPE_PRINTF_VEC4(v) printf("[%d %d %d %d] ",(v).x,(v).y,(v).z,(v).w);
  80. /** Initializes vec4 to a zero vector. */
  81. void TPE_initVec4(TPE_Vec4 *v);
  82. void TPE_vec4Set(TPE_Vec4 *v, TPE_Unit x, TPE_Unit y, TPE_Unit z, TPE_Unit w);
  83. void TPE_vec3Add(TPE_Vec4 a, TPE_Vec4 b, TPE_Vec4 *result);
  84. void TPE_vec4Add(TPE_Vec4 a, TPE_Vec4 b, TPE_Vec4 *result);
  85. void TPE_vec3Substract(TPE_Vec4 a, TPE_Vec4 b, TPE_Vec4 *result);
  86. void TPE_vec3Average(TPE_Vec4 a, TPE_Vec4 b, TPE_Vec4 *result);
  87. void TPE_vec4Substract(TPE_Vec4 a, TPE_Vec4 b, TPE_Vec4 *result);
  88. void TPE_vec3Multiply(TPE_Vec4 v, TPE_Unit f, TPE_Vec4 *result);
  89. void TPE_vec3MultiplyPlain(TPE_Vec4 v, TPE_Unit f, TPE_Vec4 *result);
  90. void TPE_vec4Multiply(TPE_Vec4 v, TPE_Unit f, TPE_Vec4 *result);
  91. void TPE_vec3CrossProduct(TPE_Vec4 a, TPE_Vec4 b, TPE_Vec4 *result);
  92. void TPE_vec3Normalize(TPE_Vec4 *v);
  93. void TPE_vec4Normalize(TPE_Vec4 *v);
  94. void TPE_vec3Project(TPE_Vec4 v, TPE_Vec4 base, TPE_Vec4 *result);
  95. TPE_Unit TPE_vec3Len(TPE_Vec4 v);
  96. TPE_Unit TPE_vec3LenTaxicab(TPE_Vec4 v);
  97. TPE_Unit TPE_vec3Dist(TPE_Vec4 a, TPE_Vec4 b);
  98. TPE_Unit TPE_vec4Len(TPE_Vec4 v);
  99. TPE_Unit TPE_vec3DotProduct(TPE_Vec4 v1, TPE_Vec4 v2);
  100. TPE_Unit TPE_vec3DotProductPlain(TPE_Vec4 v1, TPE_Vec4 v2);
  101. TPE_Vec4 TPE_vec4(TPE_Unit x, TPE_Unit y, TPE_Unit z, TPE_Unit w);
  102. TPE_Vec4 TPE_vec3Plus(TPE_Vec4 a, TPE_Vec4 b);
  103. TPE_Vec4 TPE_vec3Minus(TPE_Vec4 a, TPE_Vec4 b);
  104. TPE_Vec4 TPE_vec3Times(TPE_Vec4 a, TPE_Unit f);
  105. TPE_Vec4 TPE_vec3TimesAntiZero(TPE_Vec4 a, TPE_Unit f);
  106. TPE_Vec4 TPE_vec3Cross(TPE_Vec4 a, TPE_Vec4 b);
  107. static inline TPE_Vec4 TPE_vec3Normalized(TPE_Vec4 v);
  108. static inline TPE_Vec4 TPE_vec3Projected(TPE_Vec4 v, TPE_Vec4 base);
  109. /** Returns the closest point on given line segment (a,b) to given point (p). */
  110. TPE_Vec4 TPE_lineSegmentClosestPoint(TPE_Vec4 a, TPE_Vec4 b, TPE_Vec4 p);
  111. /** Converts a linear velocity of an orbiting point to the angular velocity
  112. (angle units per time units). This depends on the distance of the point from
  113. the center of rotation. */
  114. TPE_Unit TPE_linearVelocityToAngular(TPE_Unit velocity, TPE_Unit distance);
  115. /** Performs the opposite conversion of TPE_linearVelocityToAngular. */
  116. TPE_Unit TPE_angularVelocityToLinear(TPE_Unit velocity, TPE_Unit distance);
  117. /** Holds a rotation state around a single axis, in a way that prevents rounding
  118. errors from distorting the rotation over time. In theory rotation of a body
  119. could be represented as
  120. [current orientation, axis of rotation, angular velocity]
  121. However applying the rotation and normalizing the orientation quaternion each
  122. simulation step leads to error cumulation and the rotation gets aligned with
  123. one principal axis after some time. Because of this we rather represent the
  124. rotation state as
  125. [original orientation, axis of rotation, angular velocity, current angle]
  126. From this we can at each simulation step compute the current orientation by
  127. applying rotation by current angle to the original rotation without error
  128. cumulation. */
  129. typedef struct
  130. {
  131. TPE_Vec4 originalOrientation; /**< quaternion holding the original
  132. orientation of the body at the time when it
  133. has taken on this rotational state */
  134. TPE_Vec4 axisVelocity; /**< axis of rotation (x,y,z) and a
  135. non-negative angular velocity around this
  136. axis (w), determined ny the right hand
  137. rule */
  138. TPE_Unit currentAngle; /**< angle the body has already rotated along
  139. the rotation axis (from the original
  140. orientation) */
  141. } TPE_RotationState;
  142. typedef struct
  143. {
  144. uint8_t shape;
  145. TPE_Unit shapeParams[TPE_MAX_SHAPE_PARAMS]; ///< parameters of the body type
  146. void *shapeParamPointers[TPE_MAX_SHAPE_PARAMPOINTERS]; ///< pointer parameters
  147. uint8_t flags;
  148. TPE_Unit mass; /**< body mass, setting this to TPE_INFINITY will
  149. make the object static (not moving at all)
  150. which may help performance */
  151. TPE_Vec4 position; ///< position of the body's center of mass
  152. TPE_Vec4 velocity; ///< linear velocity vector
  153. TPE_RotationState rotation; /**< holds the state related to rotation, i.e.
  154. the rotation axis, angular momentum and data
  155. from which current orientation can be
  156. inferred */
  157. TPE_Unit boundingSphereRadius;
  158. } TPE_Body;
  159. /** Initializes a physical body, this should be called on all TPE_Body objects
  160. that are created.*/
  161. void TPE_bodyInit(TPE_Body *body);
  162. /** Recomputes the body bounding sphere, must be called every time the body's
  163. shape parameters change. */
  164. void TPE_bodyRecomputeBounds(TPE_Body *body);
  165. /** Computes a 4x4 transform matrix of given body. The matrix has the same
  166. format as S3L_Mat4 from small3dlib. */
  167. void TPE_bodyGetTransformMatrix(const TPE_Body *body, TPE_Unit matrix[4][4]);
  168. /** Gets the current orientation of a body as a quaternion. */
  169. TPE_Vec4 TPE_bodyGetOrientation(const TPE_Body *body);
  170. /** Multiplies the body's kinetic energy, i.e. changes its linear and angular
  171. velocity. */
  172. void TPE_bodyMultiplyKineticEnergy(TPE_Body *body, TPE_Unit f);
  173. void TPE_bodySetOrientation(TPE_Body *body, TPE_Vec4 orientation);
  174. /** Updates the body position and rotation according to its current velocity
  175. and rotation state. */
  176. void TPE_bodyStep(TPE_Body *body);
  177. /** Sets the rotation state of a body as an axis of rotation and angular
  178. velocity around this axis. */
  179. void TPE_bodySetRotation(TPE_Body *body, TPE_Vec4 axis, TPE_Unit velocity);
  180. /** Adds a rotation to the current rotation of a body. This addition is perfomed
  181. as a vector addition of the current and new rotation represented as vectors
  182. whose direction is the rotation axis and magnitude is the angular velocity
  183. around that axis. */
  184. void TPE_bodyAddRotation(TPE_Body *body, TPE_Vec4 axis, TPE_Unit velocity);
  185. /** Applies impulse (force in short time) to a body at a specified point
  186. (relative to its center), which will potentially change its linear and/or
  187. angular velocity. */
  188. void TPE_bodyApplyImpulse(TPE_Body *body, TPE_Vec4 point, TPE_Vec4 impulse);
  189. /** Computes and returns a body's bounding sphere radius, i.e. the maximum
  190. extent from its center point. */
  191. TPE_Unit TPE_bodyGetMaxExtent(const TPE_Body *body);
  192. /** Computes and returns a body's total kinetic energy (sum of linear and
  193. rotational kin. energy). In rotating bodies this may not be physically
  194. accurate as, for simplicity, we operate with the moment of inertia of sphere
  195. for all bodies (when in reality moment of inertia depends on shape). */
  196. TPE_Unit TPE_bodyGetKineticEnergy(const TPE_Body *body);
  197. /** Collision detection: checks if two bodies are colliding. The return value is
  198. the collision depth along the collision normal (0 if the bodies are not
  199. colliding). World-space collision point is returned via a pointer. Collision
  200. normal (normalized) is also returned via a pointer and its direction is
  201. "away from body1", i.e. if you move body1 in the opposite direction of this
  202. normal by the collision depth (return value), the bodies should no longer
  203. exhibit this particular collision. This function checks the bounding spheres
  204. to quickly opt out of impossible collisions. */
  205. TPE_Unit TPE_bodyCollides(const TPE_Body *body1, const TPE_Body *body2,
  206. TPE_Vec4 *collisionPoint, TPE_Vec4 *collisionNormal);
  207. /** Gets a velocity of a single point on a rigid body, taking into account its
  208. linear velocity and rotation. The point coordinates are relative to the body
  209. center. The point does NOT have to be on the surface, it can be inside and
  210. even outside the body too. */
  211. TPE_Vec4 TPE_bodyGetPointVelocity(const TPE_Body *body, TPE_Vec4 point);
  212. void TPE_resolveCollision(TPE_Body *body1 ,TPE_Body *body2,
  213. TPE_Vec4 collisionPoint, TPE_Vec4 collisionNormal, TPE_Unit collisionDepth,
  214. TPE_Unit energyMultiplier);
  215. /** Gets a uint16_t integer type of collision depending on two shapes, the order
  216. of shapes doesn't matter. */
  217. #define TPE_COLLISION_TYPE(shape1,shape2) \
  218. ((shape1) <= (shape2) ? \
  219. (((uint16_t) (shape1)) << 8) | (shape2) : \
  220. (((uint16_t) (shape2)) << 8) | (shape1))
  221. typedef struct
  222. {
  223. uint16_t bodyCount;
  224. TPE_Body *bodies;
  225. } TPE_PhysicsWorld;
  226. /** Multiplies two quaternions which can be seen as chaining two rotations
  227. represented by them. This is not commutative (a*b != b*a)! Rotations a is
  228. performed firth, then rotation b is performed. */
  229. void TPE_quaternionMultiply(TPE_Vec4 a, TPE_Vec4 b, TPE_Vec4 *result);
  230. /** Initializes quaternion to the rotation identity (i.e. NOT zero
  231. quaternion). */
  232. void TPE_quaternionInit(TPE_Vec4 *quaternion);
  233. /** Converts a rotation given as an axis and angle around this axis (by right
  234. hand rule) to a rotation quaternion. */
  235. void TPE_rotationToQuaternion(TPE_Vec4 axis, TPE_Unit angle,
  236. TPE_Vec4 *quaternion);
  237. void TPE_quaternionToRotation(TPE_Vec4 quaternion, TPE_Vec4 *axis,
  238. TPE_Unit *angle);
  239. /** Computes the conjugate of a quaternion (analogous to matrix inversion, the
  240. quaternion will represent the opposite rotation). */
  241. TPE_Vec4 TPE_quaternionConjugate(TPE_Vec4 quaternion);
  242. /** Converts a rotation quaternion to a 4x4 rotation matrix. The matrix is
  243. indexed as [column][row] and is in the same format as S3L_Mat4 from
  244. small3dlib. */
  245. void TPE_quaternionToRotationMatrix(TPE_Vec4 quaternion, TPE_Unit matrix[4][4]);
  246. void TPE_rotatePoint(TPE_Vec4 *point, TPE_Vec4 quaternion);
  247. void TPE_getVelocitiesAfterCollision(
  248. TPE_Unit *v1,
  249. TPE_Unit *v2,
  250. TPE_Unit m1,
  251. TPE_Unit m2,
  252. TPE_Unit elasticity
  253. );
  254. //------------------------------------------------------------------------------
  255. void TPE_initVec4(TPE_Vec4 *v)
  256. {
  257. v->x = 0;
  258. v->y = 0;
  259. v->z = 0;
  260. v->w = 0;
  261. }
  262. TPE_Vec4 TPE_vec4(TPE_Unit x, TPE_Unit y, TPE_Unit z, TPE_Unit w)
  263. {
  264. TPE_Vec4 r;
  265. r.x = x;
  266. r.y = y;
  267. r.z = z;
  268. r.w = w;
  269. return r;
  270. }
  271. void TPE_vec4Set(TPE_Vec4 *v, TPE_Unit x, TPE_Unit y, TPE_Unit z, TPE_Unit w)
  272. {
  273. v->x = x;
  274. v->y = y;
  275. v->z = z;
  276. v->w = w;
  277. }
  278. TPE_Unit TPE_wrap(TPE_Unit value, TPE_Unit mod)
  279. {
  280. return value >= 0 ? (value % mod) : (mod + (value % mod) - 1);
  281. }
  282. TPE_Unit TPE_clamp(TPE_Unit v, TPE_Unit v1, TPE_Unit v2)
  283. {
  284. return v >= v1 ? (v <= v2 ? v : v2) : v1;
  285. }
  286. TPE_Unit TPE_nonZero(TPE_Unit x)
  287. {
  288. return x + (x == 0);
  289. }
  290. #define TPE_SIN_TABLE_LENGTH 128
  291. static const TPE_Unit TPE_sinTable[TPE_SIN_TABLE_LENGTH] =
  292. {
  293. /* 511 was chosen here as a highest number that doesn't overflow during
  294. compilation for TPE_FRACTIONS_PER_UNIT == 1024 */
  295. (0*TPE_FRACTIONS_PER_UNIT)/511, (6*TPE_FRACTIONS_PER_UNIT)/511,
  296. (12*TPE_FRACTIONS_PER_UNIT)/511, (18*TPE_FRACTIONS_PER_UNIT)/511,
  297. (25*TPE_FRACTIONS_PER_UNIT)/511, (31*TPE_FRACTIONS_PER_UNIT)/511,
  298. (37*TPE_FRACTIONS_PER_UNIT)/511, (43*TPE_FRACTIONS_PER_UNIT)/511,
  299. (50*TPE_FRACTIONS_PER_UNIT)/511, (56*TPE_FRACTIONS_PER_UNIT)/511,
  300. (62*TPE_FRACTIONS_PER_UNIT)/511, (68*TPE_FRACTIONS_PER_UNIT)/511,
  301. (74*TPE_FRACTIONS_PER_UNIT)/511, (81*TPE_FRACTIONS_PER_UNIT)/511,
  302. (87*TPE_FRACTIONS_PER_UNIT)/511, (93*TPE_FRACTIONS_PER_UNIT)/511,
  303. (99*TPE_FRACTIONS_PER_UNIT)/511, (105*TPE_FRACTIONS_PER_UNIT)/511,
  304. (111*TPE_FRACTIONS_PER_UNIT)/511, (118*TPE_FRACTIONS_PER_UNIT)/511,
  305. (124*TPE_FRACTIONS_PER_UNIT)/511, (130*TPE_FRACTIONS_PER_UNIT)/511,
  306. (136*TPE_FRACTIONS_PER_UNIT)/511, (142*TPE_FRACTIONS_PER_UNIT)/511,
  307. (148*TPE_FRACTIONS_PER_UNIT)/511, (154*TPE_FRACTIONS_PER_UNIT)/511,
  308. (160*TPE_FRACTIONS_PER_UNIT)/511, (166*TPE_FRACTIONS_PER_UNIT)/511,
  309. (172*TPE_FRACTIONS_PER_UNIT)/511, (178*TPE_FRACTIONS_PER_UNIT)/511,
  310. (183*TPE_FRACTIONS_PER_UNIT)/511, (189*TPE_FRACTIONS_PER_UNIT)/511,
  311. (195*TPE_FRACTIONS_PER_UNIT)/511, (201*TPE_FRACTIONS_PER_UNIT)/511,
  312. (207*TPE_FRACTIONS_PER_UNIT)/511, (212*TPE_FRACTIONS_PER_UNIT)/511,
  313. (218*TPE_FRACTIONS_PER_UNIT)/511, (224*TPE_FRACTIONS_PER_UNIT)/511,
  314. (229*TPE_FRACTIONS_PER_UNIT)/511, (235*TPE_FRACTIONS_PER_UNIT)/511,
  315. (240*TPE_FRACTIONS_PER_UNIT)/511, (246*TPE_FRACTIONS_PER_UNIT)/511,
  316. (251*TPE_FRACTIONS_PER_UNIT)/511, (257*TPE_FRACTIONS_PER_UNIT)/511,
  317. (262*TPE_FRACTIONS_PER_UNIT)/511, (268*TPE_FRACTIONS_PER_UNIT)/511,
  318. (273*TPE_FRACTIONS_PER_UNIT)/511, (278*TPE_FRACTIONS_PER_UNIT)/511,
  319. (283*TPE_FRACTIONS_PER_UNIT)/511, (289*TPE_FRACTIONS_PER_UNIT)/511,
  320. (294*TPE_FRACTIONS_PER_UNIT)/511, (299*TPE_FRACTIONS_PER_UNIT)/511,
  321. (304*TPE_FRACTIONS_PER_UNIT)/511, (309*TPE_FRACTIONS_PER_UNIT)/511,
  322. (314*TPE_FRACTIONS_PER_UNIT)/511, (319*TPE_FRACTIONS_PER_UNIT)/511,
  323. (324*TPE_FRACTIONS_PER_UNIT)/511, (328*TPE_FRACTIONS_PER_UNIT)/511,
  324. (333*TPE_FRACTIONS_PER_UNIT)/511, (338*TPE_FRACTIONS_PER_UNIT)/511,
  325. (343*TPE_FRACTIONS_PER_UNIT)/511, (347*TPE_FRACTIONS_PER_UNIT)/511,
  326. (352*TPE_FRACTIONS_PER_UNIT)/511, (356*TPE_FRACTIONS_PER_UNIT)/511,
  327. (361*TPE_FRACTIONS_PER_UNIT)/511, (365*TPE_FRACTIONS_PER_UNIT)/511,
  328. (370*TPE_FRACTIONS_PER_UNIT)/511, (374*TPE_FRACTIONS_PER_UNIT)/511,
  329. (378*TPE_FRACTIONS_PER_UNIT)/511, (382*TPE_FRACTIONS_PER_UNIT)/511,
  330. (386*TPE_FRACTIONS_PER_UNIT)/511, (391*TPE_FRACTIONS_PER_UNIT)/511,
  331. (395*TPE_FRACTIONS_PER_UNIT)/511, (398*TPE_FRACTIONS_PER_UNIT)/511,
  332. (402*TPE_FRACTIONS_PER_UNIT)/511, (406*TPE_FRACTIONS_PER_UNIT)/511,
  333. (410*TPE_FRACTIONS_PER_UNIT)/511, (414*TPE_FRACTIONS_PER_UNIT)/511,
  334. (417*TPE_FRACTIONS_PER_UNIT)/511, (421*TPE_FRACTIONS_PER_UNIT)/511,
  335. (424*TPE_FRACTIONS_PER_UNIT)/511, (428*TPE_FRACTIONS_PER_UNIT)/511,
  336. (431*TPE_FRACTIONS_PER_UNIT)/511, (435*TPE_FRACTIONS_PER_UNIT)/511,
  337. (438*TPE_FRACTIONS_PER_UNIT)/511, (441*TPE_FRACTIONS_PER_UNIT)/511,
  338. (444*TPE_FRACTIONS_PER_UNIT)/511, (447*TPE_FRACTIONS_PER_UNIT)/511,
  339. (450*TPE_FRACTIONS_PER_UNIT)/511, (453*TPE_FRACTIONS_PER_UNIT)/511,
  340. (456*TPE_FRACTIONS_PER_UNIT)/511, (459*TPE_FRACTIONS_PER_UNIT)/511,
  341. (461*TPE_FRACTIONS_PER_UNIT)/511, (464*TPE_FRACTIONS_PER_UNIT)/511,
  342. (467*TPE_FRACTIONS_PER_UNIT)/511, (469*TPE_FRACTIONS_PER_UNIT)/511,
  343. (472*TPE_FRACTIONS_PER_UNIT)/511, (474*TPE_FRACTIONS_PER_UNIT)/511,
  344. (476*TPE_FRACTIONS_PER_UNIT)/511, (478*TPE_FRACTIONS_PER_UNIT)/511,
  345. (481*TPE_FRACTIONS_PER_UNIT)/511, (483*TPE_FRACTIONS_PER_UNIT)/511,
  346. (485*TPE_FRACTIONS_PER_UNIT)/511, (487*TPE_FRACTIONS_PER_UNIT)/511,
  347. (488*TPE_FRACTIONS_PER_UNIT)/511, (490*TPE_FRACTIONS_PER_UNIT)/511,
  348. (492*TPE_FRACTIONS_PER_UNIT)/511, (494*TPE_FRACTIONS_PER_UNIT)/511,
  349. (495*TPE_FRACTIONS_PER_UNIT)/511, (497*TPE_FRACTIONS_PER_UNIT)/511,
  350. (498*TPE_FRACTIONS_PER_UNIT)/511, (499*TPE_FRACTIONS_PER_UNIT)/511,
  351. (501*TPE_FRACTIONS_PER_UNIT)/511, (502*TPE_FRACTIONS_PER_UNIT)/511,
  352. (503*TPE_FRACTIONS_PER_UNIT)/511, (504*TPE_FRACTIONS_PER_UNIT)/511,
  353. (505*TPE_FRACTIONS_PER_UNIT)/511, (506*TPE_FRACTIONS_PER_UNIT)/511,
  354. (507*TPE_FRACTIONS_PER_UNIT)/511, (507*TPE_FRACTIONS_PER_UNIT)/511,
  355. (508*TPE_FRACTIONS_PER_UNIT)/511, (509*TPE_FRACTIONS_PER_UNIT)/511,
  356. (509*TPE_FRACTIONS_PER_UNIT)/511, (510*TPE_FRACTIONS_PER_UNIT)/511,
  357. (510*TPE_FRACTIONS_PER_UNIT)/511, (510*TPE_FRACTIONS_PER_UNIT)/511,
  358. (510*TPE_FRACTIONS_PER_UNIT)/511, (510*TPE_FRACTIONS_PER_UNIT)/511
  359. };
  360. #define TPE_SIN_TABLE_UNIT_STEP\
  361. (TPE_FRACTIONS_PER_UNIT / (TPE_SIN_TABLE_LENGTH * 4))
  362. TPE_Unit TPE_sqrt(TPE_Unit value)
  363. {
  364. int8_t sign = 1;
  365. if (value < 0)
  366. {
  367. sign = -1;
  368. value *= -1;
  369. }
  370. uint32_t result = 0;
  371. uint32_t a = value;
  372. uint32_t b = 1u << 30;
  373. while (b > a)
  374. b >>= 2;
  375. while (b != 0)
  376. {
  377. if (a >= result + b)
  378. {
  379. a -= result + b;
  380. result = result + 2 * b;
  381. }
  382. b >>= 2;
  383. result >>= 1;
  384. }
  385. return result * sign;
  386. }
  387. TPE_Unit TPE_sin(TPE_Unit x)
  388. {
  389. x = TPE_wrap(x / TPE_SIN_TABLE_UNIT_STEP,TPE_SIN_TABLE_LENGTH * 4);
  390. int8_t positive = 1;
  391. if (x < TPE_SIN_TABLE_LENGTH)
  392. {
  393. }
  394. else if (x < TPE_SIN_TABLE_LENGTH * 2)
  395. {
  396. x = TPE_SIN_TABLE_LENGTH * 2 - x - 1;
  397. }
  398. else if (x < TPE_SIN_TABLE_LENGTH * 3)
  399. {
  400. x = x - TPE_SIN_TABLE_LENGTH * 2;
  401. positive = 0;
  402. }
  403. else
  404. {
  405. x = TPE_SIN_TABLE_LENGTH - (x - TPE_SIN_TABLE_LENGTH * 3) - 1;
  406. positive = 0;
  407. }
  408. return positive ? TPE_sinTable[x] : -1 * TPE_sinTable[x];
  409. }
  410. TPE_Unit TPE_cos(TPE_Unit x)
  411. {
  412. return TPE_sin(x + TPE_FRACTIONS_PER_UNIT / 4);
  413. }
  414. void TPE_bodyInit(TPE_Body *body)
  415. {
  416. // TODO
  417. TPE_initVec4(&(body->position));
  418. TPE_initVec4(&(body->velocity));
  419. // init orientation to identity unit quaternion (1,0,0,0):
  420. TPE_quaternionInit(&(body->rotation.originalOrientation));
  421. TPE_vec4Set(&(body->rotation.axisVelocity),TPE_FRACTIONS_PER_UNIT,0,0,0);
  422. body->rotation.currentAngle = 0;
  423. body->mass = TPE_FRACTIONS_PER_UNIT;
  424. body->boundingSphereRadius = 0;
  425. }
  426. void TPE_bodySetOrientation(TPE_Body *body, TPE_Vec4 orientation)
  427. {
  428. body->rotation.originalOrientation = orientation;
  429. body->rotation.currentAngle = 0;
  430. }
  431. TPE_Vec4 TPE_bodyGetOrientation(const TPE_Body *body)
  432. {
  433. TPE_Vec4 axisRotation, result;
  434. TPE_rotationToQuaternion(
  435. body->rotation.axisVelocity,
  436. body->rotation.currentAngle,
  437. &axisRotation);
  438. TPE_quaternionMultiply(
  439. body->rotation.originalOrientation,
  440. axisRotation,
  441. &result);
  442. TPE_vec4Normalize(&result);
  443. return result;
  444. }
  445. void TPE_vec3CrossProduct(TPE_Vec4 a, TPE_Vec4 b, TPE_Vec4 *result)
  446. {
  447. TPE_Vec4 r;
  448. r.x = (a.y * b.z - a.z * b.y) / TPE_FRACTIONS_PER_UNIT;
  449. r.y = (a.z * b.x - a.x * b.z) / TPE_FRACTIONS_PER_UNIT;
  450. r.z = (a.x * b.y - a.y * b.x) / TPE_FRACTIONS_PER_UNIT;
  451. *result = r;
  452. }
  453. TPE_Vec4 TPE_vec3Cross(TPE_Vec4 a, TPE_Vec4 b)
  454. {
  455. TPE_vec3CrossProduct(a,b,&a);
  456. return a;
  457. }
  458. void TPE_bodyApplyImpulse(TPE_Body *body, TPE_Vec4 point, TPE_Vec4 impulse)
  459. {
  460. TPE_Unit pointDistance = TPE_vec3Len(point);
  461. if (pointDistance != 0)
  462. {
  463. impulse.x = (impulse.x * TPE_FRACTIONS_PER_UNIT) / body->mass;
  464. impulse.y = (impulse.y * TPE_FRACTIONS_PER_UNIT) / body->mass;
  465. impulse.z = (impulse.z * TPE_FRACTIONS_PER_UNIT) / body->mass;
  466. TPE_vec3Add(body->velocity,impulse,&(body->velocity));
  467. /* normalize the point, we don't use the function as we don't want to
  468. recompute the vector length */
  469. point.x = (point.x * TPE_FRACTIONS_PER_UNIT) / pointDistance;
  470. point.y = (point.y * TPE_FRACTIONS_PER_UNIT) / pointDistance;
  471. point.z = (point.z * TPE_FRACTIONS_PER_UNIT) / pointDistance;
  472. /* for simplicity we'll suppose angular momentum of a sphere: */
  473. impulse = TPE_vec3Cross(impulse,point);
  474. // impulse = TPE_vec3Cross(impulse,point);
  475. TPE_Unit r = TPE_bodyGetMaxExtent(body);
  476. r = TPE_nonZero((2 * r * r) / TPE_FRACTIONS_PER_UNIT);
  477. impulse.x = (impulse.x * 5 * TPE_FRACTIONS_PER_UNIT) / r;
  478. impulse.y = (impulse.y * 5 * TPE_FRACTIONS_PER_UNIT) / r;
  479. impulse.z = (impulse.z * 5 * TPE_FRACTIONS_PER_UNIT) / r;
  480. TPE_PRINTF_VEC4(impulse)
  481. printf("\n");
  482. TPE_bodyAddRotation(body,impulse,TPE_vec3Len(impulse));
  483. }
  484. }
  485. void _TPE_getShapes(const TPE_Body *b1, const TPE_Body *b2, uint8_t shape1,
  486. const TPE_Body **first, const TPE_Body **second)
  487. {
  488. if (b1->shape == shape1)
  489. {
  490. *first = b1;
  491. *second = b2;
  492. }
  493. else
  494. {
  495. *first = b2;
  496. *second = b1;
  497. }
  498. }
  499. void _TPE_getCapsuleCyllinderEndpoints(const TPE_Body *body,
  500. TPE_Vec4 *a, TPE_Vec4 *b)
  501. {
  502. TPE_Vec4 quat = TPE_bodyGetOrientation(body);
  503. *a = TPE_vec4(0,body->shapeParams[1] / 2,0,0);
  504. *b = TPE_vec4(0,-1 * a->y,0,0);
  505. TPE_rotatePoint(a,quat);
  506. TPE_rotatePoint(b,quat);
  507. TPE_vec3Add(*a,body->position,a);
  508. TPE_vec3Add(*b,body->position,b);
  509. }
  510. /** Helpter function for cuboid collision detection. Given a line segment
  511. as a line equation limited by parameter bounds t1 and t2, center point C and
  512. side offset from the center point O, the function further limits the parameter
  513. bounds (t1, t2) to restrict the line only to the region between two planes:
  514. both with normal O, one passing throung point C + O and the other through
  515. C - O. If t2 > t1 after this function finishes, the line segment is completely
  516. outside the region. */
  517. void _TPE_cutLineSegmentByPlanes(TPE_Vec4 center, TPE_Vec4 sideOffset,
  518. TPE_Vec4 lineStart, TPE_Vec4 lineDir, TPE_Unit *t1, TPE_Unit *t2)
  519. {
  520. TPE_Unit da = TPE_vec3DotProductPlain(sideOffset,lineStart);
  521. TPE_Vec4 dc;
  522. dc.z = 0;
  523. // TODO: dor(d,dc) could be cached for all sides between calls to save recomputing
  524. dc = TPE_vec3Plus(center,sideOffset);
  525. TPE_Unit denom = TPE_nonZero(TPE_vec3DotProductPlain(sideOffset,lineDir));
  526. #define tAntiOverflow(t) \
  527. TPE_Unit t = TPE_vec3DotProductPlain(sideOffset,dc) - da;\
  528. t = (TPE_abs(t) < 500000) ? (t * TPE_FRACTIONS_PER_UNIT) / denom :\
  529. (((t / 64) * TPE_FRACTIONS_PER_UNIT) / TPE_nonZero(denom / 64));
  530. tAntiOverflow(tA)
  531. dc = TPE_vec3Minus(center,sideOffset);
  532. tAntiOverflow(tB)
  533. #undef tAntiOverflow
  534. if (tB < tA)
  535. {
  536. TPE_Unit tmp = tA;
  537. tA = tB;
  538. tB = tmp;
  539. }
  540. if (tA > *t1)
  541. *t1 = tA;
  542. if (tB < *t2)
  543. *t2 = tB;
  544. }
  545. TPE_Unit TPE_bodyCollides(const TPE_Body *body1, const TPE_Body *body2,
  546. TPE_Vec4 *collisionPoint, TPE_Vec4 *collisionNormal)
  547. {
  548. // handle collision of different shapes each in a specific case:
  549. uint16_t collType = TPE_COLLISION_TYPE(body1->shape,body2->shape);
  550. if (collType != TPE_COLLISION_TYPE(TPE_SHAPE_SPHERE,TPE_SHAPE_SPHERE))
  551. {
  552. /* initial bounding sphere check to quickly discard impossible collisions,
  553. plus this also prevents overflow errors in long-distance computations */
  554. // TODO: taxicab could be also considered here
  555. if (TPE_vec3Len(TPE_vec3Minus(body1->position,body2->position)) >
  556. body1->boundingSphereRadius + body2->boundingSphereRadius)
  557. return 0;
  558. }
  559. switch (TPE_COLLISION_TYPE(body1->shape,body2->shape))
  560. {
  561. case TPE_COLLISION_TYPE(TPE_SHAPE_SPHERE,TPE_SHAPE_SPHERE):
  562. {
  563. TPE_Vec4 distanceVec;
  564. TPE_vec3Substract(body2->position,body1->position,&distanceVec);
  565. TPE_Unit distance = TPE_vec3Len(distanceVec);
  566. distance -= body1->shapeParams[0] + body2->shapeParams[0];
  567. if (distance < 0)
  568. {
  569. TPE_vec3Average(body1->position,body2->position,collisionPoint);
  570. *collisionNormal = distanceVec;
  571. TPE_vec3Normalize(collisionNormal);
  572. return -1 * distance;
  573. }
  574. break;
  575. }
  576. case TPE_COLLISION_TYPE(TPE_SHAPE_SPHERE,TPE_SHAPE_CAPSULE):
  577. {
  578. const TPE_Body *sphere;
  579. const TPE_Body *capsule;
  580. _TPE_getShapes(body1,body2,TPE_SHAPE_SPHERE,&sphere,&capsule);
  581. TPE_Vec4 cA, cB;
  582. _TPE_getCapsuleCyllinderEndpoints(capsule,&cA,&cB);
  583. TPE_Body sphere2; // sphere at the capsule's closest point
  584. TPE_bodyInit(&sphere2);
  585. sphere2.shape = TPE_SHAPE_SPHERE;
  586. sphere2.shapeParams[0] = capsule->shapeParams[0];
  587. sphere2.position = TPE_lineSegmentClosestPoint(cA,cB,sphere->position);
  588. uint8_t swap = sphere == body2;
  589. return TPE_bodyCollides(swap ? &sphere2 : sphere,swap ? sphere : &sphere2,
  590. collisionPoint,collisionNormal);
  591. break;
  592. }
  593. case TPE_COLLISION_TYPE(TPE_SHAPE_CAPSULE,TPE_SHAPE_CAPSULE):
  594. {
  595. TPE_Vec4 a1, b1, a2, b2;
  596. _TPE_getCapsuleCyllinderEndpoints(body1,&a1,&b1);
  597. _TPE_getCapsuleCyllinderEndpoints(body2,&a2,&b2);
  598. TPE_Unit aa, ab, ba, bb; // squared distances between points
  599. TPE_Vec4 tmp;
  600. tmp = TPE_vec3Minus(a1,a2);
  601. aa = tmp.x * tmp.x + tmp.y * tmp.y + tmp.z * tmp.z;
  602. tmp = TPE_vec3Minus(a1,b2);
  603. ab = tmp.x * tmp.x + tmp.y * tmp.y + tmp.z * tmp.z;
  604. tmp = TPE_vec3Minus(b1,a2);
  605. ba = tmp.x * tmp.x + tmp.y * tmp.y + tmp.z * tmp.z;
  606. tmp = TPE_vec3Minus(b1,b2);
  607. bb = tmp.x * tmp.x + tmp.y * tmp.y + tmp.z * tmp.z;
  608. // let a1 hold the point figuring in the shortest distance:
  609. if (ab < aa)
  610. aa = ab; // means: aa = min(aa,ab)
  611. if (bb < ba)
  612. ba = bb; // means: ba = min(ba,bb)
  613. if (ba < aa) // means: min(ba,bb) < min(aa,ab)
  614. a1 = b1;
  615. a2 = TPE_lineSegmentClosestPoint(a2,b2,a1);
  616. a1 = TPE_lineSegmentClosestPoint(a1,b1,a2);
  617. // now a1 and a2 are the closest two points on capsule axes
  618. TPE_Body sphere1, sphere2;
  619. TPE_bodyInit(&sphere1);
  620. sphere1.shape = TPE_SHAPE_SPHERE;
  621. sphere1.shapeParams[0] = body1->shapeParams[0];
  622. sphere1.position = a1;
  623. TPE_bodyInit(&sphere2);
  624. sphere2.shape = TPE_SHAPE_SPHERE;
  625. sphere2.shapeParams[0] = body2->shapeParams[0];
  626. sphere2.position = a2;
  627. return TPE_bodyCollides(&sphere1,&sphere2,collisionPoint,collisionNormal);
  628. break;
  629. }
  630. case TPE_COLLISION_TYPE(TPE_SHAPE_SPHERE,TPE_SHAPE_CYLINDER):
  631. {
  632. // TODO: would this be better to do via sphere-capsule collision?
  633. const TPE_Body *sphere;
  634. const TPE_Body *cylinder;
  635. _TPE_getShapes(body1,body2,TPE_SHAPE_SPHERE,&sphere,&cylinder);
  636. TPE_Vec4 sphereRelativePos = // by this we shift the cylinder to [0,0,0]
  637. TPE_vec3Minus(sphere->position,cylinder->position);
  638. // vector along the cylinder height:
  639. TPE_Vec4 cylinderAxis = TPE_vec4(0,TPE_FRACTIONS_PER_UNIT,0,0);
  640. TPE_rotatePoint(&cylinderAxis,TPE_bodyGetOrientation(cylinder));
  641. TPE_Vec4 sphereAxisPos = // sphere pos projected to the cylinder axis
  642. TPE_vec3Projected(sphereRelativePos,cylinderAxis);
  643. TPE_Unit sphereAxisDistance = TPE_vec3Len(sphereAxisPos);
  644. TPE_Unit tmp = cylinder->shapeParams[1] / 2; // half of cylinder height
  645. /* now we have three possible regions the sphere can occupy:
  646. C :B: A :B: C
  647. : :_____: :
  648. : |_____| : cylinder
  649. : : : :
  650. : : : : */
  651. if (sphereAxisDistance >= tmp + sphere->shapeParams[0]) // case C: no col.
  652. break;
  653. TPE_Vec4 sphereAxisToRelative =
  654. TPE_vec3Minus(sphereRelativePos,sphereAxisPos);
  655. TPE_Unit sphereCylinderDistance = TPE_vec3Len(sphereAxisToRelative);
  656. tmp = sphereAxisDistance - tmp;
  657. if (tmp < 0) // case A: potential collision with cylinder body
  658. {
  659. TPE_Unit penetration = cylinder->shapeParams[0]
  660. - (sphereCylinderDistance - sphere->shapeParams[0]);
  661. if (penetration > 0)
  662. {
  663. TPE_vec3Normalize(&sphereAxisToRelative);
  664. *collisionPoint = TPE_vec3Plus(cylinder->position,
  665. TPE_vec3Plus(sphereAxisPos,TPE_vec3Times(
  666. sphereAxisToRelative,cylinder->shapeParams[0])));
  667. *collisionNormal = sphereAxisToRelative;
  668. if (sphere == body1)
  669. TPE_vec3MultiplyPlain(*collisionNormal,-1,collisionNormal);
  670. return penetration;
  671. }
  672. else
  673. break;
  674. }
  675. /* case B: here we have two subcases, one with the sphere center being
  676. within the cylinder radius (collision with the cylinder top/bottom),
  677. and the other case (collision with the cylinder top/bottom edge). */
  678. TPE_Vec4 cylinderPlaneMiddle = TPE_vec3Times(
  679. TPE_vec3Normalized(sphereAxisPos),
  680. cylinder->shapeParams[1] / 2);
  681. if (sphereCylinderDistance < cylinder->shapeParams[0]) // top/bottom cap
  682. {
  683. TPE_Unit penetration = cylinder->shapeParams[1] / 2 -
  684. (sphereAxisDistance - sphere->shapeParams[0]);
  685. if (penetration <= 0) // shouldn't normally happen, but rounding errors
  686. penetration = 1;
  687. *collisionNormal = TPE_vec3Normalized(sphereAxisPos);
  688. *collisionPoint =
  689. TPE_vec3Plus(
  690. cylinder->position,
  691. TPE_vec3Plus(sphereAxisToRelative,cylinderPlaneMiddle));
  692. if (body1 == sphere)
  693. TPE_vec3MultiplyPlain(*collisionNormal,-1,collisionNormal);
  694. return penetration;
  695. }
  696. else // potential edge collision
  697. {
  698. TPE_Vec4 edgePoint = TPE_vec3Plus(cylinderPlaneMiddle,
  699. TPE_vec3Times(TPE_vec3Normalized(sphereAxisToRelative),
  700. cylinder->shapeParams[0]));
  701. TPE_Unit penetration = sphere->shapeParams[0] -
  702. TPE_vec3Dist(edgePoint,sphereRelativePos);
  703. if (penetration > 0)
  704. {
  705. *collisionPoint = TPE_vec3Plus(cylinder->position,edgePoint);
  706. *collisionNormal =
  707. TPE_vec3Normalized(TPE_vec3Minus(sphereRelativePos,edgePoint));
  708. if (body1 == sphere)
  709. TPE_vec3MultiplyPlain(*collisionNormal,-1,collisionNormal);
  710. return penetration;
  711. }
  712. }
  713. break;
  714. }
  715. case TPE_COLLISION_TYPE(TPE_SHAPE_CUBOID,TPE_SHAPE_CUBOID):
  716. {
  717. TPE_Vec4 // min/max extent of the colliding area:
  718. collisionExtentMax =
  719. TPE_vec4(-TPE_INFINITY,-TPE_INFINITY,-TPE_INFINITY,0),
  720. collisionExtentMin =
  721. TPE_vec4(TPE_INFINITY,TPE_INFINITY,TPE_INFINITY,0);
  722. uint8_t collisionHappened = 0;
  723. TPE_Vec4 aX1, aY1, aZ1, // first cuboid axes
  724. aX2, aY2, aZ2; // second cuboid axes
  725. for (uint8_t i = 0; i < 2; ++i) // for each body
  726. {
  727. TPE_Vec4 q = TPE_bodyGetOrientation(body1);
  728. // construct the cuboid axes:
  729. aX1 = TPE_vec4(body1->shapeParams[0] / 2,0,0,0);
  730. TPE_rotatePoint(&aX1,q);
  731. aY1 = TPE_vec4(0,body1->shapeParams[1] / 2,0,0);
  732. TPE_rotatePoint(&aY1,q);
  733. aZ1 = TPE_vec4(0,0,body1->shapeParams[2] / 2,0);
  734. TPE_rotatePoint(&aZ1,q);
  735. q = TPE_bodyGetOrientation(body2);
  736. aX2 = TPE_vec4(body2->shapeParams[0] / 2,0,0,0);
  737. TPE_rotatePoint(&aX2,q);
  738. aY2 = TPE_vec4(0,body2->shapeParams[1] / 2,0,0);
  739. TPE_rotatePoint(&aY2,q);
  740. aZ2 = TPE_vec4(0,0,body2->shapeParams[2] / 2,0);
  741. TPE_rotatePoint(&aZ2,q);
  742. uint8_t edges[12] = // list of all cuboid edges as combinations of axes
  743. { // xyz xyz
  744. 0x3b, // +++ -++ |
  745. 0x3e, // +++ ++- | top
  746. 0x13, // -+- -++ |
  747. 0x16, // -+- ++- |
  748. 0x29, // +-+ --+ |
  749. 0x2c, // +-+ +-- | bottom
  750. 0x01, // --- --+ |
  751. 0x04, // --- +-- |
  752. 0x3d, // +++ +-+ |
  753. 0x19, // -++ --+ | sides
  754. 0x10, // -+- --- |
  755. 0x34 // ++- +-- |
  756. };
  757. for (uint8_t j = 0; j < 12; ++j) // for each edge
  758. {
  759. // we check the edge against all sides of the other cuboid
  760. TPE_Vec4 lineStart = body1->position;
  761. TPE_Vec4 lineEnd = body1->position;
  762. uint8_t edge = edges[j];
  763. #define offsetCenter(c,v,a) \
  764. v = (edge & c) ? TPE_vec3Plus(v,a) : TPE_vec3Minus(v,a);
  765. offsetCenter(0x04,lineStart,aX1)
  766. offsetCenter(0x02,lineStart,aY1)
  767. offsetCenter(0x01,lineStart,aZ1)
  768. offsetCenter(0x20,lineEnd,aX1)
  769. offsetCenter(0x10,lineEnd,aY1)
  770. offsetCenter(0x08,lineEnd,aZ1)
  771. #undef offsetCenter
  772. TPE_Unit t1 = 0, t2 = TPE_FRACTIONS_PER_UNIT;
  773. TPE_Vec4 edgeDir = TPE_vec3Minus(lineEnd,lineStart);
  774. for (uint8_t k = 0; k < 3; ++k) // for each axis (pair of sides)
  775. {
  776. TPE_Vec4 *sideOffset;
  777. if (k == 0)
  778. sideOffset = &aX2;
  779. else if (k == 1)
  780. sideOffset = &aY2;
  781. else
  782. sideOffset = &aZ2;
  783. _TPE_cutLineSegmentByPlanes(body2->position,*sideOffset,lineStart,
  784. edgeDir,&t1,&t2);
  785. if (t1 > t2)
  786. break; // no solution already, no point checking on
  787. }
  788. if (t2 > t1) // if part of edge exists between all side planes
  789. {
  790. // edge collided with the cuboid
  791. collisionHappened = 1;
  792. *collisionPoint = edgeDir;
  793. collisionPoint->x = (collisionPoint->x * t1) / TPE_FRACTIONS_PER_UNIT;
  794. collisionPoint->y = (collisionPoint->y * t1) / TPE_FRACTIONS_PER_UNIT;
  795. collisionPoint->z = (collisionPoint->z * t1) / TPE_FRACTIONS_PER_UNIT;
  796. *collisionPoint = TPE_vec3Plus(lineStart,*collisionPoint);
  797. if (collisionPoint->x > collisionExtentMax.x)
  798. collisionExtentMax.x = collisionPoint->x;
  799. if (collisionPoint->x < collisionExtentMin.x)
  800. collisionExtentMin.x = collisionPoint->x;
  801. if (collisionPoint->y > collisionExtentMax.y)
  802. collisionExtentMax.y = collisionPoint->y;
  803. if (collisionPoint->y < collisionExtentMin.y)
  804. collisionExtentMin.y = collisionPoint->y;
  805. if (collisionPoint->z > collisionExtentMax.z)
  806. collisionExtentMax.z = collisionPoint->z;
  807. if (collisionPoint->z < collisionExtentMin.z)
  808. collisionExtentMin.z = collisionPoint->z;
  809. *collisionPoint = edgeDir;
  810. collisionPoint->x = (collisionPoint->x * t2) / TPE_FRACTIONS_PER_UNIT;
  811. collisionPoint->y = (collisionPoint->y * t2) / TPE_FRACTIONS_PER_UNIT;
  812. collisionPoint->z = (collisionPoint->z * t2) / TPE_FRACTIONS_PER_UNIT;
  813. *collisionPoint = TPE_vec3Plus(lineStart,*collisionPoint);
  814. if (collisionPoint->x > collisionExtentMax.x)
  815. collisionExtentMax.x = collisionPoint->x;
  816. if (collisionPoint->x < collisionExtentMin.x)
  817. collisionExtentMin.x = collisionPoint->x;
  818. if (collisionPoint->y > collisionExtentMax.y)
  819. collisionExtentMax.y = collisionPoint->y;
  820. if (collisionPoint->y < collisionExtentMin.y)
  821. collisionExtentMin.y = collisionPoint->y;
  822. if (collisionPoint->z > collisionExtentMax.z)
  823. collisionExtentMax.z = collisionPoint->z;
  824. if (collisionPoint->z < collisionExtentMin.z)
  825. collisionExtentMin.z = collisionPoint->z;
  826. }
  827. } // for each edge
  828. if (i == 0)
  829. {
  830. // now swap the bodies and do it again:
  831. const TPE_Body *tmp = body1;
  832. body1 = body2;
  833. body2 = tmp;
  834. }
  835. } // for each body
  836. if (collisionHappened)
  837. {
  838. // average all collision points to get the center point
  839. *collisionPoint = TPE_vec3Plus(collisionExtentMin,collisionExtentMax);
  840. collisionPoint->x /= 2;
  841. collisionPoint->y /= 2;
  842. collisionPoint->z /= 2;
  843. collisionPoint->w = 0;
  844. /* We'll find the "closest" side to collision point, compute the
  845. penetration depth for both bodies (can't do just one) and return the
  846. bigger one. */
  847. TPE_Unit result = -TPE_INFINITY;
  848. for (int i = 0; i < 2; ++i) // for each body
  849. {
  850. TPE_Vec4 bestAxis = TPE_vec4(1,0,0,0);
  851. TPE_Unit bestDot = -1;
  852. TPE_Unit currentDot;
  853. collisionExtentMin = TPE_vec3Minus(*collisionPoint,
  854. i == 0 ? body1->position : body2->position); // reuse
  855. #define checkAxis(a) \
  856. currentDot = (TPE_vec3DotProduct(a,collisionExtentMin) * TPE_FRACTIONS_PER_UNIT) / \
  857. TPE_nonZero(TPE_vec3DotProduct(a,a)); \
  858. if (currentDot > bestDot) \
  859. { bestDot = currentDot; bestAxis = a; } \
  860. else { \
  861. currentDot *= -1; \
  862. if (currentDot > bestDot) { \
  863. bestDot = currentDot; bestAxis = a; \
  864. TPE_vec3MultiplyPlain(bestAxis,-1,&bestAxis); } \
  865. }
  866. checkAxis(aX1)
  867. checkAxis(aY1)
  868. checkAxis(aZ1)
  869. #undef checkAxis
  870. TPE_Unit len = TPE_nonZero(TPE_vec3Len(bestAxis));
  871. len = len - TPE_vec3DotProductPlain(bestAxis,
  872. TPE_vec3Minus(*collisionPoint,
  873. i == 0 ? body1->position : body2->position)) / len;
  874. if (len > result)
  875. {
  876. result = len;
  877. *collisionNormal = bestAxis;
  878. TPE_vec3Normalize(collisionNormal);
  879. if (i == 0)
  880. TPE_vec3MultiplyPlain(*collisionNormal,-1,collisionNormal);
  881. }
  882. aX1 = aX2; // check the second body's axes in next iteration
  883. aY1 = aY2;
  884. aZ1 = aZ2;
  885. }
  886. return result > 1 ? result : 1;
  887. }
  888. break;
  889. }
  890. default:
  891. break;
  892. }
  893. return 0;
  894. }
  895. TPE_Vec4 TPE_bodyGetPointVelocity(const TPE_Body *body, TPE_Vec4 point)
  896. {
  897. TPE_Vec4 result = body->velocity;
  898. TPE_Vec4 normal = TPE_vec3Cross(
  899. point,TPE_vec3Minus(point,body->rotation.axisVelocity));
  900. TPE_vec3MultiplyPlain(normal,-1,&normal); // TODO: think about WHY
  901. TPE_Unit dist = TPE_vec3Len(normal); // point-line distance
  902. TPE_Unit velocity =
  903. TPE_angularVelocityToLinear(body->rotation.axisVelocity.w,dist);
  904. TPE_vec3Normalize(&normal);
  905. return TPE_vec3Plus(result,TPE_vec3Times(normal,velocity));
  906. }
  907. void TPE_bodyMultiplyKineticEnergy(TPE_Body *body, TPE_Unit f)
  908. {
  909. f = TPE_sqrt(f * TPE_FRACTIONS_PER_UNIT);
  910. TPE_vec3Multiply(body->velocity,f,&(body->velocity));
  911. int8_t sign =
  912. TPE_sign(body->rotation.axisVelocity.w);
  913. body->rotation.axisVelocity.w =
  914. (body->rotation.axisVelocity.w * f) / TPE_FRACTIONS_PER_UNIT;
  915. /* we try to prevent the angular welocity from falling to 0 as that causes
  916. issues with gravity */
  917. if (f > TPE_FRACTIONS_PER_UNIT / 2 &&
  918. sign != 0 && body->rotation.axisVelocity.w == 0)
  919. body->rotation.axisVelocity.w = sign;
  920. }
  921. void TPE_resolveCollision(TPE_Body *body1 ,TPE_Body *body2,
  922. TPE_Vec4 collisionPoint, TPE_Vec4 collisionNormal, TPE_Unit collisionDepth,
  923. TPE_Unit energyMultiplier)
  924. {
  925. /*
  926. TODO:
  927. - false coll. detection?
  928. - coll with static
  929. - handle small values!!!
  930. - handle big values
  931. */
  932. if (body2->mass == TPE_INFINITY) // handle static bodies
  933. {
  934. if (body1->mass == TPE_INFINITY)
  935. return; // static-static collision: do nothing
  936. // switch the bodies so that the static body is always the first one:
  937. TPE_Body *tmp = body1;
  938. body1 = body2;
  939. body2 = tmp;
  940. TPE_vec3MultiplyPlain(collisionNormal,-1,&collisionNormal);
  941. }
  942. TPE_Vec4 p1, p2;
  943. p1 = TPE_vec3Minus(collisionPoint,body1->position);
  944. p2 = TPE_vec3Minus(collisionPoint,body2->position);
  945. // separate the bodies:
  946. collisionPoint = collisionNormal; // reuse collisionPoint
  947. if (body1->mass != TPE_INFINITY)
  948. {
  949. TPE_vec3Multiply(collisionPoint,collisionDepth / 2,&collisionPoint);
  950. TPE_vec3Add(body2->position,collisionPoint,&body2->position);
  951. TPE_vec3Substract(body1->position,collisionPoint,&body1->position);
  952. }
  953. else
  954. {
  955. TPE_vec3Multiply(collisionPoint,collisionDepth,&collisionPoint);
  956. TPE_vec3Add(body2->position,collisionPoint,&body2->position);
  957. }
  958. if (TPE_vec3DotProduct(collisionNormal,(TPE_bodyGetPointVelocity(body1,p1))) <
  959. TPE_vec3DotProduct(collisionNormal,(TPE_bodyGetPointVelocity(body2,p2))))
  960. return; // invalid collision (bodies going away from each other)
  961. /* We now want to find an impulse I such that if we apply I to body2 and -I
  962. to body1, we conserve kinetic energy (or keep as much of it as defined by
  963. energyMultiplier). The direction of I is always the direction of
  964. collisionNormal, we are only looking for the size of the impulse. We don't
  965. have to worry about conserving momentum, it is automatically conserved by us
  966. applying the same (but opposite) impulse to both bodies. The equation is
  967. constructed as:
  968. e_out1 + e_out2 - energyMultiplier * (e_in1 + e_in2) = 0
  969. Where e_in1 (e_in2) is the current kin. energy of body1 (body2) and e_out1
  970. (e_out2) is the energy of body1 (body2) AFTER applying impulse I. The
  971. unknown (x) in the equation is the size of the impulse. Expanding all this,
  972. considering moment of ineartia of a sphere (for simplicity), we get a
  973. quadratic equation with coefficients:
  974. a = 1/(2 * m1) + 1/(2 * m2) +
  975. q1/2 * dot(cross(normal,p1),cross(normal,p1)) +
  976. q2/2 * dot(cross(normal,p2),cross(normal,p2))
  977. b = dot(v2,normal) - dot(v1,normal) +
  978. dot(r2,cross(normal,p2) -
  979. dot(r1,cross(normal,p1)
  980. c = m1/2 * dot(v1,v1) + w1 * dot(r1,r1) +
  981. m2/2 * dot(v2,v2) + w2 * dot(r2,r2) - energyMultiplier * (e_in1 + e_in2)
  982. where
  983. qn = 5 / (2 * mn * dn)
  984. wn = (mn * dn) / 5
  985. dn = maximum extent of body n
  986. The following code is solving this equation: */
  987. TPE_Unit tmp = TPE_bodyGetMaxExtent(body1);
  988. TPE_Unit w1 = ((((body1->mass * tmp) / TPE_FRACTIONS_PER_UNIT) * tmp) /
  989. TPE_FRACTIONS_PER_UNIT) / 5;
  990. TPE_Unit q1 = (TPE_FRACTIONS_PER_UNIT * TPE_FRACTIONS_PER_UNIT * 2) /
  991. TPE_nonZero(w1);
  992. TPE_Vec4 nxp1 = TPE_vec3Cross(collisionNormal,p1);
  993. TPE_Vec4 rot1 =
  994. TPE_vec3Times(body1->rotation.axisVelocity,body1->rotation.axisVelocity.w);
  995. tmp = TPE_bodyGetMaxExtent(body2);
  996. TPE_Unit w2 = ((((body2->mass * tmp) / TPE_FRACTIONS_PER_UNIT) * tmp) /
  997. TPE_FRACTIONS_PER_UNIT) / 5;
  998. TPE_Unit q2 = (TPE_FRACTIONS_PER_UNIT * TPE_FRACTIONS_PER_UNIT * 2) /
  999. TPE_nonZero(w2);
  1000. TPE_Vec4 nxp2 = TPE_vec3Cross(collisionNormal,p2);
  1001. TPE_Vec4 rot2 =
  1002. TPE_vec3Times(body2->rotation.axisVelocity,body2->rotation.axisVelocity.w);
  1003. uint8_t dynamic = body1->mass != TPE_INFINITY;
  1004. // quadratic eq. coefficients:
  1005. TPE_Unit a =
  1006. ((dynamic * TPE_FRACTIONS_PER_UNIT * TPE_FRACTIONS_PER_UNIT) / body1->mass +
  1007. (TPE_FRACTIONS_PER_UNIT * TPE_FRACTIONS_PER_UNIT) / body2->mass) / 2 +
  1008. (dynamic * q1 * TPE_vec3DotProduct(nxp1,nxp1) + q2 * TPE_vec3DotProduct(nxp2,nxp2)) /
  1009. (2 * TPE_FRACTIONS_PER_UNIT);
  1010. TPE_Unit b =
  1011. TPE_vec3DotProduct(body2->velocity,collisionNormal) +
  1012. TPE_vec3DotProduct(rot2,nxp2) -
  1013. dynamic * (
  1014. TPE_vec3DotProduct(body1->velocity,collisionNormal) +
  1015. TPE_vec3DotProduct(rot1,nxp1));
  1016. TPE_Unit
  1017. e1 = dynamic * TPE_bodyGetKineticEnergy(body1),
  1018. e2 = TPE_bodyGetKineticEnergy(body2);
  1019. TPE_Unit c =
  1020. (
  1021. dynamic * body1->mass * TPE_vec3DotProduct(body1->velocity,body1->velocity) +
  1022. body2->mass * TPE_vec3DotProduct(body2->velocity,body2->velocity)
  1023. ) / (2 * TPE_FRACTIONS_PER_UNIT) +
  1024. (
  1025. dynamic * w1 * TPE_vec3DotProduct(rot1,rot1) +
  1026. w2 * TPE_vec3DotProduct(rot2,rot2)
  1027. ) / TPE_FRACTIONS_PER_UNIT
  1028. - (((e1 + e2) * energyMultiplier) / TPE_FRACTIONS_PER_UNIT);
  1029. c = TPE_sqrt(b * b - 4 * a * c); // discriminant
  1030. b *= -1;
  1031. a *= 2;
  1032. // solutions:
  1033. TPE_Unit x1, x2;
  1034. x1 = ((b - c) * TPE_FRACTIONS_PER_UNIT) / a;
  1035. x2 = ((b + c) * TPE_FRACTIONS_PER_UNIT) / a;
  1036. // here at least one solution (x1 or x2) should be 0 (or close)
  1037. if (TPE_abs(x1) < TPE_abs(x2))
  1038. x1 = x2; // we take the non-0 solution
  1039. collisionNormal = TPE_vec3Times(collisionNormal,x1);
  1040. TPE_bodyApplyImpulse(body2,p2,collisionNormal);
  1041. if (body1->mass != TPE_INFINITY)
  1042. {
  1043. TPE_vec3MultiplyPlain(collisionNormal,-1,&collisionNormal);
  1044. TPE_bodyApplyImpulse(body1,p1,collisionNormal);
  1045. }
  1046. // we try to correct possible numerical errors:
  1047. e1 = ((TPE_bodyGetKineticEnergy(body1) +
  1048. TPE_bodyGetKineticEnergy(body2)) * TPE_FRACTIONS_PER_UNIT) /
  1049. TPE_nonZero(e1 + e2);
  1050. energyMultiplier =
  1051. (energyMultiplier * TPE_FRACTIONS_PER_UNIT) / TPE_nonZero(e1);
  1052. if (energyMultiplier > TPE_FRACTIONS_PER_UNIT + 2 || // TODO: magic const.
  1053. energyMultiplier < TPE_FRACTIONS_PER_UNIT - 2)
  1054. {
  1055. TPE_bodyMultiplyKineticEnergy(body1,energyMultiplier);
  1056. TPE_bodyMultiplyKineticEnergy(body2,energyMultiplier);
  1057. }
  1058. }
  1059. TPE_Unit TPE_linearVelocityToAngular(TPE_Unit velocity, TPE_Unit distance)
  1060. {
  1061. TPE_Unit circumfence = (2 * TPE_PI * distance) / TPE_FRACTIONS_PER_UNIT;
  1062. return (velocity * TPE_FRACTIONS_PER_UNIT) / circumfence;
  1063. }
  1064. TPE_Unit TPE_angularVelocityToLinear(TPE_Unit velocity, TPE_Unit distance)
  1065. {
  1066. TPE_Unit circumfence = (2 * TPE_PI * distance) / TPE_FRACTIONS_PER_UNIT;
  1067. return (velocity * circumfence) / TPE_FRACTIONS_PER_UNIT;
  1068. }
  1069. void TPE_bodyStep(TPE_Body *body)
  1070. {
  1071. if (body->mass != TPE_INFINITY)
  1072. {
  1073. TPE_vec3Add(body->position,body->velocity,&(body->position));
  1074. body->rotation.currentAngle += body->rotation.axisVelocity.w;
  1075. }
  1076. }
  1077. void TPE_bodySetRotation(TPE_Body *body, TPE_Vec4 axis, TPE_Unit velocity)
  1078. {
  1079. if (body->rotation.currentAngle != 0)
  1080. body->rotation.originalOrientation = TPE_bodyGetOrientation(body);
  1081. if (velocity < 0)
  1082. {
  1083. axis.x *= -1;
  1084. axis.y *= -1;
  1085. axis.z *= -1;
  1086. velocity *= -1;
  1087. }
  1088. TPE_vec3Normalize(&axis);
  1089. body->rotation.axisVelocity = axis;
  1090. body->rotation.axisVelocity.w = velocity;
  1091. body->rotation.currentAngle = 0;
  1092. }
  1093. void TPE_bodyAddRotation(TPE_Body *body, TPE_Vec4 axis, TPE_Unit velocity)
  1094. {
  1095. /* Rotation is added like this: we convert both the original and added
  1096. rotation to vectors whose direction is along the rotations axis and
  1097. magnitude is the rotation speed, then we add these vectors and convert
  1098. the final vector back to normalized rotation axis + scalar rotation
  1099. speed.*/
  1100. if (velocity == 0)
  1101. return;
  1102. body->rotation.axisVelocity.x =
  1103. (body->rotation.axisVelocity.x * body->rotation.axisVelocity.w)
  1104. / TPE_FRACTIONS_PER_UNIT;
  1105. body->rotation.axisVelocity.y =
  1106. (body->rotation.axisVelocity.y * body->rotation.axisVelocity.w)
  1107. / TPE_FRACTIONS_PER_UNIT;
  1108. body->rotation.axisVelocity.z =
  1109. (body->rotation.axisVelocity.z * body->rotation.axisVelocity.w)
  1110. / TPE_FRACTIONS_PER_UNIT;
  1111. TPE_vec3Normalize(&axis);
  1112. axis.x = (axis.x * velocity) / TPE_FRACTIONS_PER_UNIT;
  1113. axis.y = (axis.y * velocity) / TPE_FRACTIONS_PER_UNIT;
  1114. axis.z = (axis.z * velocity) / TPE_FRACTIONS_PER_UNIT;
  1115. TPE_vec3Add(body->rotation.axisVelocity,axis,&axis);
  1116. axis.w = TPE_vec3Len(axis);
  1117. TPE_bodySetRotation(body,axis,axis.w);
  1118. }
  1119. void TPE_quaternionMultiply(TPE_Vec4 a, TPE_Vec4 b, TPE_Vec4 *result)
  1120. {
  1121. TPE_Vec4 r; // in case result is identical to a or b
  1122. r.x =
  1123. (a.w * b.x +
  1124. a.x * b.w +
  1125. a.y * b.z -
  1126. a.z * b.y) / TPE_FRACTIONS_PER_UNIT;
  1127. r.y =
  1128. (a.w * b.y -
  1129. a.x * b.z +
  1130. a.y * b.w +
  1131. a.z * b.x) / TPE_FRACTIONS_PER_UNIT;
  1132. r.z =
  1133. (a.w * b.z +
  1134. a.x * b.y -
  1135. a.y * b.x +
  1136. a.z * b.w) / TPE_FRACTIONS_PER_UNIT;
  1137. r.w =
  1138. (a.w * b.w -
  1139. a.x * b.x -
  1140. a.y * b.y -
  1141. a.z * b.z) / TPE_FRACTIONS_PER_UNIT;
  1142. result->x = r.x;
  1143. result->y = r.y;
  1144. result->z = r.z;
  1145. result->w = r.w;
  1146. }
  1147. void TPE_rotationToQuaternion(TPE_Vec4 axis, TPE_Unit angle, TPE_Vec4 *quaternion)
  1148. {
  1149. TPE_vec3Normalize(&axis);
  1150. angle /= 2;
  1151. TPE_Unit s = TPE_sin(angle);
  1152. quaternion->x = (s * axis.x) / TPE_FRACTIONS_PER_UNIT;
  1153. quaternion->y = (s * axis.y) / TPE_FRACTIONS_PER_UNIT;
  1154. quaternion->z = (s * axis.z) / TPE_FRACTIONS_PER_UNIT;
  1155. quaternion->w = TPE_cos(angle);
  1156. }
  1157. TPE_Unit TPE_asin(TPE_Unit x)
  1158. {
  1159. x = TPE_clamp(x,-TPE_FRACTIONS_PER_UNIT,TPE_FRACTIONS_PER_UNIT);
  1160. int8_t sign = 1;
  1161. if (x < 0)
  1162. {
  1163. sign = -1;
  1164. x *= -1;
  1165. }
  1166. int16_t low = 0;
  1167. int16_t high = TPE_SIN_TABLE_LENGTH -1;
  1168. int16_t middle;
  1169. while (low <= high) // binary search
  1170. {
  1171. middle = (low + high) / 2;
  1172. TPE_Unit v = TPE_sinTable[middle];
  1173. if (v > x)
  1174. high = middle - 1;
  1175. else if (v < x)
  1176. low = middle + 1;
  1177. else
  1178. break;
  1179. }
  1180. middle *= TPE_SIN_TABLE_UNIT_STEP;
  1181. return sign * middle;
  1182. }
  1183. TPE_Unit TPE_acos(TPE_Unit x)
  1184. {
  1185. return TPE_asin(-1 * x) + TPE_FRACTIONS_PER_UNIT / 4;
  1186. }
  1187. void TPE_quaternionToRotation(TPE_Vec4 quaternion, TPE_Vec4 *axis, TPE_Unit *angle)
  1188. {
  1189. *angle = 2 * TPE_acos(quaternion.x);
  1190. TPE_Unit tmp =
  1191. TPE_nonZero(TPE_sqrt(
  1192. (TPE_FRACTIONS_PER_UNIT -
  1193. (quaternion.x * quaternion.x) / TPE_FRACTIONS_PER_UNIT
  1194. ) * TPE_FRACTIONS_PER_UNIT));
  1195. axis->x = (quaternion.x * TPE_FRACTIONS_PER_UNIT) / tmp;
  1196. axis->y = (quaternion.y * TPE_FRACTIONS_PER_UNIT) / tmp;
  1197. axis->z = (quaternion.z * TPE_FRACTIONS_PER_UNIT) / tmp;
  1198. }
  1199. void TPE_quaternionToRotationMatrix(TPE_Vec4 quaternion, TPE_Unit matrix[4][4])
  1200. {
  1201. TPE_Unit
  1202. _2x2 = (2 * quaternion.x * quaternion.x) / TPE_FRACTIONS_PER_UNIT,
  1203. _2y2 = (2 * quaternion.y * quaternion.y) / TPE_FRACTIONS_PER_UNIT,
  1204. _2z2 = (2 * quaternion.z * quaternion.z) / TPE_FRACTIONS_PER_UNIT,
  1205. _2xy = (2 * quaternion.x * quaternion.y) / TPE_FRACTIONS_PER_UNIT,
  1206. _2xw = (2 * quaternion.x * quaternion.w) / TPE_FRACTIONS_PER_UNIT,
  1207. _2zw = (2 * quaternion.z * quaternion.w) / TPE_FRACTIONS_PER_UNIT,
  1208. _2xz = (2 * quaternion.x * quaternion.z) / TPE_FRACTIONS_PER_UNIT,
  1209. _2yw = (2 * quaternion.y * quaternion.w) / TPE_FRACTIONS_PER_UNIT,
  1210. _2yz = (2 * quaternion.y * quaternion.z) / TPE_FRACTIONS_PER_UNIT;
  1211. #define ONE TPE_FRACTIONS_PER_UNIT
  1212. matrix[0][0] = ONE - _2y2 - _2z2;
  1213. matrix[1][0] = _2xy - _2zw;
  1214. matrix[2][0] = _2xz + _2yw;
  1215. matrix[3][0] = 0;
  1216. matrix[0][1] = _2xy + _2zw;
  1217. matrix[1][1] = ONE - _2x2 - _2z2;
  1218. matrix[2][1] = _2yz - _2xw;
  1219. matrix[3][1] = 0;
  1220. matrix[0][2] = _2xz - _2yw;
  1221. matrix[1][2] = _2yz + _2xw;
  1222. matrix[2][2] = ONE - _2x2 - _2y2;
  1223. matrix[3][2] = 0;
  1224. matrix[0][3] = 0;
  1225. matrix[1][3] = 0;
  1226. matrix[2][3] = 0;
  1227. matrix[3][3] = ONE;
  1228. #undef ONE
  1229. }
  1230. void TPE_vec3Add(const TPE_Vec4 a, const TPE_Vec4 b, TPE_Vec4 *result)
  1231. {
  1232. result->x = a.x + b.x;
  1233. result->y = a.y + b.y;
  1234. result->z = a.z + b.z;
  1235. }
  1236. void TPE_vec4Add(const TPE_Vec4 a, const TPE_Vec4 b, TPE_Vec4 *result)
  1237. {
  1238. result->x = a.x + b.x;
  1239. result->y = a.y + b.y;
  1240. result->z = a.z + b.z;
  1241. result->w = a.w + b.w;
  1242. }
  1243. void TPE_vec3Substract(const TPE_Vec4 a, const TPE_Vec4 b, TPE_Vec4 *result)
  1244. {
  1245. result->x = a.x - b.x;
  1246. result->y = a.y - b.y;
  1247. result->z = a.z - b.z;
  1248. }
  1249. TPE_Vec4 TPE_vec3Plus(TPE_Vec4 a, TPE_Vec4 b)
  1250. {
  1251. a.x += b.x;
  1252. a.y += b.y;
  1253. a.z += b.z;
  1254. return a;
  1255. }
  1256. TPE_Vec4 TPE_vec3Minus(TPE_Vec4 a, TPE_Vec4 b)
  1257. {
  1258. a.x -= b.x;
  1259. a.y -= b.y;
  1260. a.z -= b.z;
  1261. return a;
  1262. }
  1263. TPE_Vec4 TPE_vec3Times(TPE_Vec4 a, TPE_Unit f)
  1264. {
  1265. a.x = (a.x * f) / TPE_FRACTIONS_PER_UNIT;
  1266. a.y = (a.y * f) / TPE_FRACTIONS_PER_UNIT;
  1267. a.z = (a.z * f) / TPE_FRACTIONS_PER_UNIT;
  1268. return a;
  1269. }
  1270. TPE_Vec4 TPE_vec3TimesAntiZero(TPE_Vec4 a, TPE_Unit f)
  1271. {
  1272. a.x *= f;
  1273. if (a.x != 0)
  1274. a.x = a.x >= TPE_FRACTIONS_PER_UNIT ? a.x / TPE_FRACTIONS_PER_UNIT :
  1275. (a.x > 0 ? 1 : -1);
  1276. a.y *= f;
  1277. if (a.y != 0)
  1278. a.y = a.y >= TPE_FRACTIONS_PER_UNIT ? a.y / TPE_FRACTIONS_PER_UNIT :
  1279. (a.y > 0 ? 1 : -1);
  1280. a.z *= f;
  1281. if (a.z != 0)
  1282. a.z = a.z >= TPE_FRACTIONS_PER_UNIT ? a.z / TPE_FRACTIONS_PER_UNIT :
  1283. (a.z > 0 ? 1 : -1);
  1284. /*
  1285. if (a.x != 0)
  1286. a.x = a.x >= TPE_FRACTIONS_PER_UNIT ? a.x / TPE_FRACTIONS_PER_UNIT :
  1287. (a.x > 0 ? 1 : -1);
  1288. if (a.y != 0)
  1289. a.y = a.y >= TPE_FRACTIONS_PER_UNIT ? a.y / TPE_FRACTIONS_PER_UNIT :
  1290. (a.y > 0 ? 1 : -1);
  1291. if (a.z != 0)
  1292. a.z = a.z >= TPE_FRACTIONS_PER_UNIT ? a.z / TPE_FRACTIONS_PER_UNIT :
  1293. (a.z > 0 ? 1 : -1);
  1294. */
  1295. return a;
  1296. }
  1297. void TPE_vec3Average(TPE_Vec4 a, TPE_Vec4 b, TPE_Vec4 *result)
  1298. {
  1299. result->x = (a.x + b.x) / 2;
  1300. result->y = (a.y + b.y) / 2;
  1301. result->z = (a.z + b.z) / 2;
  1302. }
  1303. void TPE_vec4Substract(const TPE_Vec4 a, const TPE_Vec4 b, TPE_Vec4 *result)
  1304. {
  1305. result->x = a.x - b.x;
  1306. result->y = a.y - b.y;
  1307. result->z = a.z - b.z;
  1308. result->w = a.w - b.w;
  1309. }
  1310. void TPE_vec3Multiply(const TPE_Vec4 v, TPE_Unit f, TPE_Vec4 *result)
  1311. {
  1312. result->x = (v.x * f) / TPE_FRACTIONS_PER_UNIT;
  1313. result->y = (v.y * f) / TPE_FRACTIONS_PER_UNIT;
  1314. result->z = (v.z * f) / TPE_FRACTIONS_PER_UNIT;
  1315. }
  1316. void TPE_vec3MultiplyPlain(TPE_Vec4 v, TPE_Unit f, TPE_Vec4 *result)
  1317. {
  1318. result->x = v.x * f;
  1319. result->y = v.y * f;
  1320. result->z = v.z * f;
  1321. }
  1322. void TPE_vec4Multiply(const TPE_Vec4 v, TPE_Unit f, TPE_Vec4 *result)
  1323. {
  1324. result->x = (v.x * f) / TPE_FRACTIONS_PER_UNIT;
  1325. result->y = (v.y * f) / TPE_FRACTIONS_PER_UNIT;
  1326. result->z = (v.z * f) / TPE_FRACTIONS_PER_UNIT;
  1327. result->w = (v.w * f) / TPE_FRACTIONS_PER_UNIT;
  1328. }
  1329. TPE_Unit TPE_abs(TPE_Unit x)
  1330. {
  1331. return (x >= 0) ? x : (-1 * x);
  1332. }
  1333. TPE_Unit TPE_vec3Len(TPE_Vec4 v)
  1334. {
  1335. return TPE_sqrt(v.x * v.x + v.y * v.y + v.z * v.z);
  1336. }
  1337. TPE_Unit TPE_vec3Dist(TPE_Vec4 a, TPE_Vec4 b)
  1338. {
  1339. return TPE_vec3Len(TPE_vec3Minus(a,b));
  1340. }
  1341. TPE_Unit TPE_vec4Len(TPE_Vec4 v)
  1342. {
  1343. return TPE_sqrt(v.x * v.x + v.y * v.y + v.z * v.z + v.w * v.w);
  1344. }
  1345. TPE_Unit TPE_vec3LenTaxicab(TPE_Vec4 v)
  1346. {
  1347. return TPE_abs(v.x) + TPE_abs(v.y) + TPE_abs(v.z);
  1348. }
  1349. TPE_Unit TPE_vec3DotProduct(const TPE_Vec4 v1, const TPE_Vec4 v2)
  1350. {
  1351. return
  1352. (v1.x * v2.x + v1.y * v2.y + v1.z * v2.z) / TPE_FRACTIONS_PER_UNIT;
  1353. }
  1354. TPE_Unit TPE_vec3DotProductPlain(const TPE_Vec4 v1, const TPE_Vec4 v2)
  1355. {
  1356. return v1.x * v2.x + v1.y * v2.y + v1.z * v2.z;
  1357. }
  1358. void TPE_vec3Normalize(TPE_Vec4 *v)
  1359. {
  1360. TPE_Unit l = TPE_vec3Len(*v);
  1361. if (l == 0)
  1362. {
  1363. v->x = TPE_FRACTIONS_PER_UNIT;
  1364. return;
  1365. }
  1366. v->x = (v->x * TPE_FRACTIONS_PER_UNIT) / l;
  1367. v->y = (v->y * TPE_FRACTIONS_PER_UNIT) / l;
  1368. v->z = (v->z * TPE_FRACTIONS_PER_UNIT) / l;
  1369. }
  1370. void TPE_vec4Normalize(TPE_Vec4 *v)
  1371. {
  1372. TPE_Unit l = TPE_vec4Len(*v);
  1373. if (l == 0)
  1374. {
  1375. v->x = TPE_FRACTIONS_PER_UNIT;
  1376. return;
  1377. }
  1378. v->x = (v->x * TPE_FRACTIONS_PER_UNIT) / l;
  1379. v->y = (v->y * TPE_FRACTIONS_PER_UNIT) / l;
  1380. v->z = (v->z * TPE_FRACTIONS_PER_UNIT) / l;
  1381. v->w = (v->w * TPE_FRACTIONS_PER_UNIT) / l;
  1382. }
  1383. void TPE_vec3Project(TPE_Vec4 v, TPE_Vec4 base, TPE_Vec4 *result)
  1384. {
  1385. TPE_Unit p = TPE_vec3DotProduct(v,base);
  1386. result->x = (p * base.x) / TPE_FRACTIONS_PER_UNIT;
  1387. result->y = (p * base.y) / TPE_FRACTIONS_PER_UNIT;
  1388. result->z = (p * base.z) / TPE_FRACTIONS_PER_UNIT;
  1389. }
  1390. TPE_Vec4 TPE_vec3Projected(TPE_Vec4 v, TPE_Vec4 base)
  1391. {
  1392. TPE_Vec4 r;
  1393. TPE_vec3Project(v,base,&r);
  1394. return r;
  1395. }
  1396. void TPE_getVelocitiesAfterCollision(
  1397. TPE_Unit *v1,
  1398. TPE_Unit *v2,
  1399. TPE_Unit m1,
  1400. TPE_Unit m2,
  1401. TPE_Unit elasticity
  1402. )
  1403. {
  1404. /* in the following a lot of TPE_FRACTIONS_PER_UNIT cancel out, feel free to
  1405. check if confused */
  1406. #define ANTI_OVERFLOW 30000
  1407. #define ANTI_OVERFLOW_SCALE 128
  1408. uint8_t overflowDanger = m1 > ANTI_OVERFLOW || *v1 > ANTI_OVERFLOW ||
  1409. m2 > ANTI_OVERFLOW || *v2 > ANTI_OVERFLOW;
  1410. if (overflowDanger)
  1411. {
  1412. m1 = (m1 != 0) ? TPE_nonZero(m1 / ANTI_OVERFLOW_SCALE) : 0;
  1413. m2 = (m2 != 0) ? TPE_nonZero(m2 / ANTI_OVERFLOW_SCALE) : 0;
  1414. *v1 = (*v1 != 0) ? TPE_nonZero(*v1 / ANTI_OVERFLOW_SCALE) : 0;
  1415. *v2 = (*v2 != 0) ? TPE_nonZero(*v2 / ANTI_OVERFLOW_SCALE) : 0;
  1416. }
  1417. TPE_Unit m1Pm2 = TPE_nonZero(m1 + m2);
  1418. TPE_Unit v2Mv1 = TPE_nonZero(*v2 - *v1);
  1419. TPE_Unit m1v1Pm2v2 = ((m1 * *v1) + (m2 * *v2));
  1420. *v1 = (((elasticity * m2 / TPE_FRACTIONS_PER_UNIT) * v2Mv1)
  1421. + m1v1Pm2v2) / m1Pm2;
  1422. *v2 = (((elasticity * m1 / TPE_FRACTIONS_PER_UNIT) * -1 * v2Mv1)
  1423. + m1v1Pm2v2) / m1Pm2;
  1424. if (overflowDanger)
  1425. {
  1426. *v1 *= ANTI_OVERFLOW_SCALE;
  1427. *v2 *= ANTI_OVERFLOW_SCALE;
  1428. }
  1429. #undef ANTI_OVERFLOW
  1430. #undef ANTI_OVERFLOW_SCALE
  1431. }
  1432. void TPE_bodyGetTransformMatrix(const TPE_Body *body, TPE_Unit matrix[4][4])
  1433. {
  1434. TPE_Vec4 orientation;
  1435. orientation = TPE_bodyGetOrientation(body);
  1436. TPE_quaternionToRotationMatrix(orientation,matrix);
  1437. matrix[0][3] = body->position.x;
  1438. matrix[1][3] = body->position.y;
  1439. matrix[2][3] = body->position.z;
  1440. }
  1441. void TPE_quaternionInit(TPE_Vec4 *quaternion)
  1442. {
  1443. quaternion->x = 0;
  1444. quaternion->y = 0;
  1445. quaternion->z = 0;
  1446. quaternion->w = TPE_FRACTIONS_PER_UNIT;
  1447. }
  1448. void TPE_rotatePoint(TPE_Vec4 *point, TPE_Vec4 quaternion)
  1449. {
  1450. // TODO: the first method is bugged, but maybe would be faster?
  1451. #if 0
  1452. TPE_Vec4 quaternionConjugate = TPE_quaternionConjugate(quaternion);
  1453. point->w = 0;
  1454. TPE_quaternionMultiply(quaternion,*point,point);
  1455. TPE_quaternionMultiply(*point,quaternionConjugate,point);
  1456. #else
  1457. TPE_Unit m[4][4];
  1458. TPE_quaternionToRotationMatrix(quaternion,m);
  1459. TPE_Vec4 p = *point;
  1460. point->x = (p.x * m[0][0] + p.y * m[0][1] + p.z * m[0][2]) / TPE_FRACTIONS_PER_UNIT;
  1461. point->y = (p.x * m[1][0] + p.y * m[1][1] + p.z * m[1][2]) / TPE_FRACTIONS_PER_UNIT;
  1462. point->z = (p.x * m[2][0] + p.y * m[2][1] + p.z * m[2][2]) / TPE_FRACTIONS_PER_UNIT;
  1463. #endif
  1464. }
  1465. TPE_Vec4 TPE_quaternionConjugate(TPE_Vec4 quaternion)
  1466. {
  1467. quaternion.x *= -1;
  1468. quaternion.y *= -1;
  1469. quaternion.z *= -1;
  1470. return quaternion;
  1471. }
  1472. TPE_Vec4 TPE_vec3Normalized(TPE_Vec4 v)
  1473. {
  1474. TPE_vec3Normalize(&v);
  1475. return v;
  1476. }
  1477. TPE_Vec4 TPE_lineSegmentClosestPoint(TPE_Vec4 a, TPE_Vec4 b, TPE_Vec4 p)
  1478. {
  1479. TPE_Vec4 ab = TPE_vec3Minus(b,a);
  1480. TPE_Unit t = ((TPE_vec3DotProduct(ab,TPE_vec3Minus(p,a)) *
  1481. TPE_FRACTIONS_PER_UNIT) / TPE_nonZero(TPE_vec3DotProduct(ab,ab)));
  1482. if (t < 0)
  1483. t = 0;
  1484. else if (t > TPE_FRACTIONS_PER_UNIT)
  1485. t = TPE_FRACTIONS_PER_UNIT;
  1486. TPE_vec3Multiply(ab,t,&ab);
  1487. return TPE_vec3Plus(a,ab);
  1488. }
  1489. TPE_Unit TPE_bodyGetKineticEnergy(const TPE_Body *body)
  1490. {
  1491. TPE_Unit v = TPE_vec3Len(body->velocity);
  1492. v *= v;
  1493. v = (v == 0 || v >= TPE_FRACTIONS_PER_UNIT) ?
  1494. v / TPE_FRACTIONS_PER_UNIT : 1;
  1495. v = (body->mass * v) / (2 * TPE_FRACTIONS_PER_UNIT);
  1496. // TODO: handle small values
  1497. // TODO: clean this mess :)
  1498. TPE_Unit r = TPE_bodyGetMaxExtent(body);
  1499. r =
  1500. (
  1501. TPE_timesAntiZero(
  1502. TPE_timesAntiZero(r,r),
  1503. TPE_timesAntiZero(body->rotation.axisVelocity.w,body->rotation.axisVelocity.w)
  1504. )
  1505. *
  1506. body->mass
  1507. )
  1508. / (5 * TPE_FRACTIONS_PER_UNIT);
  1509. if (r == 0 && body->rotation.axisVelocity.w != 0)
  1510. r = 1;
  1511. return v + r;
  1512. }
  1513. TPE_Unit TPE_bodyGetMaxExtent(const TPE_Body *body)
  1514. {
  1515. switch (body->shape)
  1516. {
  1517. case TPE_SHAPE_SPHERE:
  1518. return body->shapeParams[0];
  1519. break;
  1520. case TPE_SHAPE_CUBOID:
  1521. return TPE_vec3Len(TPE_vec4(
  1522. body->shapeParams[0] / 2,
  1523. body->shapeParams[1] / 2,
  1524. body->shapeParams[2] / 2,0));
  1525. break;
  1526. // TODO: other shapes
  1527. default: return 0; break;
  1528. }
  1529. }
  1530. void TPE_bodyRecomputeBounds(TPE_Body *body)
  1531. {
  1532. body->boundingSphereRadius = TPE_bodyGetMaxExtent(body);
  1533. }
  1534. TPE_Unit TPE_timesAntiZero(TPE_Unit a, TPE_Unit b)
  1535. {
  1536. TPE_Unit result = a * b;
  1537. return result >= TPE_FRACTIONS_PER_UNIT ?
  1538. result / TPE_FRACTIONS_PER_UNIT : (result != 0 ? 1 : 0);
  1539. }
  1540. uint8_t TPE_sign(TPE_Unit x)
  1541. {
  1542. return x > 0 ? 1 : (x < 0 ? -1 : 0);
  1543. }
  1544. #endif // guard