tinyphysicsengine.h 49 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887
  1. #ifndef _TINYPHYSICSENGINE_H
  2. #define _TINYPHYSICSENGINE_H
  3. /**
  4. WORK IN PROGRESS, UNUSABLE YET
  5. Simple/suckless header-only hybrid 3D physics engine with no floating point,
  6. only 32 bit int arithmetic, similar to e.g. small3dlib.
  7. Conventions and formats are the same or similar to those of small3dlib so as
  8. to make them easily integrate with each other.
  9. Orientations/rotations are in extrinsic Euler angles in the ZXY order (by Z,
  10. then by X, then by Y).
  11. Where it matters (e.g. rotations about axes) we consider a left-handed coord.
  12. system (x right, y up, z forward).
  13. --------------------
  14. by drummyfish, 2022
  15. This work's goal is to never be encumbered by any exclusive intellectual
  16. property rights. The work is therefore provided under CC0 1.0 + additional
  17. WAIVER OF ALL INTELLECTUAL PROPERTY RIGHTS that waives the rest of
  18. intellectual property rights not already waived by CC0 1.0. The WAIVER OF ALL
  19. INTELLECTUAL PROPERTY RGHTS is as follows:
  20. Each contributor to this work agrees that they waive any exclusive rights,
  21. including but not limited to copyright, patents, trademark, trade dress,
  22. industrial design, plant varieties and trade secrets, to any and all ideas,
  23. concepts, processes, discoveries, improvements and inventions conceived,
  24. discovered, made, designed, researched or developed by the contributor either
  25. solely or jointly with others, which relate to this work or result from this
  26. work. Should any waiver of such right be judged legally invalid or
  27. ineffective under applicable law, the contributor hereby grants to each
  28. affected person a royalty-free, non transferable, non sublicensable, non
  29. exclusive, irrevocable and unconditional license to this right.
  30. */
  31. #include <stdint.h>
  32. typedef int32_t TPE_Unit;
  33. typedef int16_t TPE_UnitReduced; ///< Like TPE_Unit but saving space
  34. #define TPE_FRACTIONS_PER_UNIT 512
  35. #define TPE_JOINT_SIZE_MULTIPLIER 32
  36. #define TPE_INFINITY 2147483647
  37. #define TPE_JOINT_SIZE(joint) ((joint).sizeDivided * TPE_JOINT_SIZE_MULTIPLIER)
  38. #ifndef TPE_APPROXIMATE_LENGTH
  39. #define TPE_APPROXIMATE_LENGTH 0 /**< whether or not use length/distance
  40. approximation rather than exact
  41. calculation (1 is faster but less
  42. accurate) */
  43. #endif
  44. #if !TPE_APPROXIMATE_LENGTH
  45. #define TPE_DISTANCE TPE_dist
  46. #define TPE_LENGTH TPE_vec3Len
  47. #else
  48. #define TPE_DISTANCE TPE_distApprox
  49. #define TPE_LENGTH TPE_vec3LenApprox
  50. #endif
  51. // TODO: faster and more accurate distance approx function based on regions/LUT
  52. #ifndef TPE_LOG
  53. #define TPE_LOG(s) ;
  54. #endif
  55. #ifndef TPE_LOW_SPEED
  56. /** Speed, in TPE_Units per ticks, that is considered low (used e.g. for auto
  57. disabling bodies). */
  58. #define TPE_LOW_SPEED 30
  59. #endif
  60. #ifndef TPE_RESHAPE_TENSION_LIMIT
  61. /** Tension limit, in TPE_Units, after which a non-soft body will be reshaped.
  62. Smaller number will keep more stable shapes but will cost more performance. */
  63. #define TPE_RESHAPE_TENSION_LIMIT 20
  64. #endif
  65. #ifndef TPE_RESHAPE_ITERATIONS
  66. /** How many iterations of reshaping will be performed by the step function if
  67. the body's shape needs to be reshaped. Greater number will keep shapes more
  68. stable but will cost some performance. */
  69. #define TPE_RESHAPE_ITERATIONS 3
  70. #endif
  71. #ifndef TPE_DEACTIVATE_AFTER
  72. /** After how many ticks of low speed should a body be disabled. This mustn't
  73. be greater than 255. */
  74. #define TPE_DEACTIVATE_AFTER 128
  75. #endif
  76. #ifndef TPE_LIGHT_DEACTIVATION
  77. /** When a body is activated by a collision, its deactivation counter will be
  78. set to this value, i.e. after a collision the body will be prone to deactivate
  79. sooner than normally. This is to handle situations with many bodies touching
  80. each other that would normally keep activating each other, never coming to
  81. rest. */
  82. #define TPE_LIGHT_DEACTIVATION \
  83. (TPE_DEACTIVATE_AFTER - TPE_DEACTIVATE_AFTER / 10)
  84. #endif
  85. #ifndef TPE_TENSION_ACCELERATION_DIVIDER
  86. /** Number by which the base acceleration (TPE_FRACTIONS_PER_UNIT per tick
  87. squared) caused by the connection tension will be divided. This should be power
  88. of 2. */
  89. #define TPE_TENSION_ACCELERATION_DIVIDER 32
  90. #endif
  91. #ifndef TPE_TENSION_ACCELERATION_THRESHOLD
  92. /** Limit within which acceleration caused by connection tension won't be
  93. applied. */
  94. #define TPE_TENSION_ACCELERATION_THRESHOLD 5
  95. #endif
  96. #ifndef TPE_COLLISION_RESOLUTION_ITERATIONS
  97. /** Maximum number of iterations to try to uncollide two colliding bodies. */
  98. #define TPE_COLLISION_RESOLUTION_ITERATIONS 3
  99. #endif
  100. #ifndef TPE_COLLISION_RESOLUTION_MARGIN
  101. /** Margin, in TPE_Units, by which a body will be shifted back to get out of
  102. collision. */
  103. #define TPE_COLLISION_RESOLUTION_MARGIN (TPE_FRACTIONS_PER_UNIT / 64)
  104. #endif
  105. #define TPE_PRINTF_VEC3(v) printf("[%d %d %d]",(v).x,(v).y,(v).z);
  106. typedef struct
  107. {
  108. TPE_Unit x;
  109. TPE_Unit y;
  110. TPE_Unit z;
  111. } TPE_Vec3;
  112. typedef struct
  113. {
  114. TPE_Vec3 position;
  115. TPE_UnitReduced velocity[3];
  116. uint8_t sizeDivided; /**< size (radius, ...), for saving space divided by
  117. TPE_JOINT_SIZE_MULTIPLIER */
  118. } TPE_Joint;
  119. typedef struct
  120. {
  121. uint8_t joint1;
  122. uint16_t joint2;
  123. uint16_t length; ///< connection's preferred length, uint16_t saves space
  124. } TPE_Connection;
  125. #define TPE_BODY_FLAG_DEACTIVATED 1 /**< Not being updated due to low energy,
  126. "sleeping", will be woken by
  127. collisions etc. */
  128. #define TPE_BODY_FLAG_NONROTATING 2 /**< When set, the body won't rotate, will
  129. only move linearly. */
  130. #define TPE_BODY_FLAG_DISABLED 4 /**< Disabled, not taking part in
  131. simulation. */
  132. #define TPE_BODY_FLAG_SOFT 8 /**< Soft connections, effort won't be made
  133. to keep the body's shape. */
  134. /** Function used for defining static environment, working similarly to an SDF
  135. (signed distance function). The parameters are: 3D point P, max distance D.
  136. The function should behave like this: if P is inside the solid environment
  137. volume, P will be returned; otherwise closest point (by Euclidean distance) to
  138. the solid environment volume from P will be returned, except for a case when
  139. this closest point would be further away than D, in which case any arbitrary
  140. point further away than D may be returned (this allows for potentially
  141. potentially faster implementation). */
  142. typedef TPE_Vec3 (*TPE_ClosestPointFunction)(TPE_Vec3, TPE_Unit);
  143. /** Function used by the debug drawing functions to draw individual pixels to
  144. the screen. The parameters are following: pixel x, pixel y, pixel color. */
  145. typedef void (*TPE_DebugDrawFunction)(uint16_t, uint16_t, uint8_t);
  146. typedef struct
  147. {
  148. TPE_Joint *joints;
  149. uint8_t jointCount;
  150. TPE_Connection *connections;
  151. uint8_t connectionCount;
  152. TPE_UnitReduced jointMass;
  153. TPE_UnitReduced friction;
  154. TPE_UnitReduced elasticity;
  155. uint8_t flags;
  156. uint8_t deactivateCount;
  157. } TPE_Body;
  158. typedef struct
  159. {
  160. TPE_Body *bodies;
  161. uint16_t bodyCount;
  162. TPE_ClosestPointFunction environmentFunction;
  163. } TPE_World;
  164. void TPE_bodyInit(TPE_Body *body,
  165. TPE_Joint *joints, uint8_t jointCount,
  166. TPE_Connection *connections, uint8_t connectionCount,
  167. TPE_Unit mass);
  168. void TPE_worldInit(TPE_World *world,
  169. TPE_Body *bodies, uint16_t bodyCount,
  170. TPE_ClosestPointFunction environmentFunction);
  171. void TPE_vec3Normalize(TPE_Vec3 *v);
  172. TPE_Vec3 TPE_pointRotate(TPE_Vec3 point, TPE_Vec3 rotation);
  173. TPE_Vec3 TPE_rotationInverse(TPE_Vec3 rotation);
  174. void TPE_getVelocitiesAfterCollision(
  175. TPE_Unit *v1,
  176. TPE_Unit *v2,
  177. TPE_Unit m1,
  178. TPE_Unit m2,
  179. TPE_Unit elasticity);
  180. TPE_Vec3 TPE_vec3(TPE_Unit x, TPE_Unit y, TPE_Unit z);
  181. TPE_Vec3 TPE_vec3Minus(TPE_Vec3 v1, TPE_Vec3 v2);
  182. TPE_Vec3 TPE_vec3Plus(TPE_Vec3 v1, TPE_Vec3 v2);
  183. TPE_Vec3 TPE_vec3Cross(TPE_Vec3 v1, TPE_Vec3 v2);
  184. TPE_Vec3 TPE_vec3Project(TPE_Vec3 v, TPE_Vec3 base);
  185. TPE_Vec3 TPE_vec3Times(TPE_Vec3 v, TPE_Unit units);
  186. TPE_Vec3 TPE_vec3TimesNonNormalized(TPE_Vec3 v, TPE_Unit q);
  187. TPE_Vec3 TPE_vec3Normalized(TPE_Vec3 v);
  188. /* Computes orientation/rotation (see docs for orientation format) from two
  189. vectors (which should be at least a close to being perpensicular and do NOT
  190. need to be normalized). */
  191. TPE_Vec3 TPE_orientationFromVecs(TPE_Vec3 forward, TPE_Vec3 right);
  192. TPE_Unit TPE_vec3Dot(TPE_Vec3 v1, TPE_Vec3 v2);
  193. TPE_Unit TPE_sqrt(TPE_Unit value);
  194. TPE_Unit TPE_vec3Len(TPE_Vec3 v);
  195. TPE_Unit TPE_vec3LenApprox(TPE_Vec3 v);
  196. static inline TPE_Unit TPE_nonZero(TPE_Unit x);
  197. static inline TPE_Unit TPE_dist(TPE_Vec3 p1, TPE_Vec3 p2);
  198. static inline TPE_Unit TPE_distApprox(TPE_Vec3 p1, TPE_Vec3 p2);
  199. TPE_Joint TPE_joint(TPE_Vec3 position, TPE_Unit size);
  200. uint8_t TPE_jointsResolveCollision(TPE_Joint *j1, TPE_Joint *j2,
  201. TPE_Unit mass1, TPE_Unit mass2, TPE_Unit elasticity, TPE_Unit friction);
  202. /** Tests and potentially resolves a collision between a joint and environment,
  203. returns 0 if no collision happened, 1 if it happened and was resolved normally
  204. and 2 if it couldn't be resolved normally. */
  205. uint8_t TPE_jointEnvironmentResolveCollision(TPE_Joint *joint, TPE_Unit
  206. elasticity, TPE_Unit friction, TPE_ClosestPointFunction env);
  207. uint8_t TPE_bodyEnvironmentCollide(const TPE_Body *body,
  208. TPE_ClosestPointFunction env);
  209. uint8_t TPE_bodyEnvironmentResolveCollision(TPE_Body *body,
  210. TPE_ClosestPointFunction env);
  211. void TPE_bodyGetAABB(const TPE_Body *body, TPE_Vec3 *vMin, TPE_Vec3 *vMax);
  212. uint8_t TPE_checkOverlapAABB(TPE_Vec3 v1Min, TPE_Vec3 v1Max, TPE_Vec3 v2Min,
  213. TPE_Vec3 v2Max);
  214. uint8_t TPE_bodiesResolveCollision(TPE_Body *b1, TPE_Body *b2);
  215. void TPE_jointPin(TPE_Joint *joint, TPE_Vec3 position);
  216. // -----------------------------------------------------------------------------
  217. // body generation functions:
  218. void TPE_makeBox(TPE_Joint joints[8], TPE_Connection connections[16],
  219. TPE_Unit width, TPE_Unit depth, TPE_Unit height, TPE_Unit jointSize);
  220. void TPE_makeCenterBox(TPE_Joint joints[9], TPE_Connection connections[18],
  221. TPE_Unit width, TPE_Unit depth, TPE_Unit height, TPE_Unit jointSize);
  222. void TPE_makeRect(TPE_Joint joints[4], TPE_Connection connections[6],
  223. TPE_Unit width, TPE_Unit depth, TPE_Unit jointSize);
  224. void TPE_makeTriangle(TPE_Joint joints[3], TPE_Connection connections[3],
  225. TPE_Unit sideLength, TPE_Unit jointSize);
  226. void TPE_makeCenterRect(TPE_Joint joints[5], TPE_Connection connections[8],
  227. TPE_Unit width, TPE_Unit depth, TPE_Unit jointSize);
  228. void TPE_make2Line(TPE_Joint joints[2], TPE_Connection connections[1],
  229. TPE_Unit length, TPE_Unit jointSize);
  230. //------------------------------------------------------------------------------
  231. // environment functions:
  232. TPE_Vec3 TPE_envAABoxInside(TPE_Vec3 point, TPE_Vec3 center, TPE_Vec3 size);
  233. TPE_Vec3 TPE_envAABox(TPE_Vec3 point, TPE_Vec3 center, TPE_Vec3 maxCornerVec);
  234. TPE_Vec3 TPE_envBox(TPE_Vec3 point, TPE_Vec3 center, TPE_Vec3 maxCornerVec,
  235. TPE_Vec3 rotation);
  236. TPE_Vec3 TPE_envSphere(TPE_Vec3 point, TPE_Vec3 center, TPE_Unit radius);
  237. TPE_Vec3 TPE_envHalfPlane(TPE_Vec3 point, TPE_Vec3 center, TPE_Vec3 normal);
  238. //---------------------------
  239. void TPE_worldStep(TPE_World *world);
  240. TPE_Unit TPE_bodyNetSpeed(const TPE_Body *body);
  241. TPE_Unit TPE_bodyAverageSpeed(const TPE_Body *body);
  242. void TPE_bodyDeactivate(TPE_Body *body);
  243. void TPE_bodyLimitAverageSpeed(TPE_Body *body, TPE_Unit speedMin,
  244. TPE_Unit speedMax);
  245. void TPE_bodyMultiplyNetSpeed(TPE_Body *body, TPE_Unit factor);
  246. /** Attempts to shift the joints of a soft body so that the tension of all
  247. strings becomes zero while keeping the joints near their current position. This
  248. function performs one iteration of the equalizing algorithm and doesn't
  249. guarantee a perfect solution, it may help to run multiple iterations (call this
  250. function multiple times). */
  251. void TPE_bodyReshape(TPE_Body *body, TPE_ClosestPointFunction
  252. environmentFunction);
  253. /** Move a soft body by certain offset. */
  254. void TPE_bodyMove(TPE_Body *body, TPE_Vec3 offset);
  255. /** Zero velocities of all soft body joints. */
  256. void TPE_bodyStop(TPE_Body *body);
  257. void TPE_bodyActivate(TPE_Body *body);
  258. /** Add velocity to a soft body. */
  259. void TPE_bodyAccelerate(TPE_Body *body, TPE_Vec3 velocity);
  260. /** Add angular velocity to a soft body. The rotation vector specifies the axis
  261. of rotation by its direction and angular velocity by its magnitude (magnitude
  262. of TPE_FRACTIONS_PER_UNIT will add linear velocity of TPE_FRACTIONS_PER_UNIT per
  263. tick to a point in the distance of TPE_FRACTIONS_PER_UNIT from the rotation
  264. axis). */
  265. void TPE_bodySpin(TPE_Body *body, TPE_Vec3 rotation);
  266. /** Instantly rotate soft body, the rotation vector specifies the rotation axis
  267. by its direction and the rotation angle by its magnitude (TPE_FRACTIONS_PER_UNIT
  268. stands for full angle, i.e. 2 * PI x). */
  269. void TPE_bodyRotateByAxis(TPE_Body *body, TPE_Vec3 rotation);
  270. /** Compute the center of mass of a soft body. */
  271. TPE_Vec3 TPE_bodyGetCenter(const TPE_Body *body);
  272. /** Compute sine, TPE_FRACTIONS_PER_UNIT as argument corresponds to 2 * PI
  273. radians. Returns a number from -TPE_FRACTIONS_PER_UNIT to
  274. TPE_FRACTIONS_PER_UNIT. */
  275. TPE_Unit TPE_sin(TPE_Unit x);
  276. TPE_Unit TPE_cos(TPE_Unit x);
  277. TPE_Unit TPE_atan(TPE_Unit x);
  278. /** Draws a debug view of a 3D physics world using a provided pixel drawing
  279. function. This can be used to overlay a simple visualization of the physics
  280. objects to your main render, to spot exact borders of objects etc. The
  281. function draws simple dotted lines and circles with different "colors" for
  282. different types of objects (joints, connections, environemnt). camPos, camRot
  283. and camView should match the camera settings of your main renderer. CamView.x
  284. is horizontal resolution in pixels, camView.y is the vertical resolution,
  285. CamView.z says the camera focal length (~FOV) in TPE_Units. envGridRes is the
  286. resolution of an environment probe grid (the function will probe points in
  287. space and draw borders of the physics environemnt), envGridSize is the size
  288. (int TPE_Units) of the grid cell. Note the function may be slow (reducing
  289. envGridRes can help, workable value can be e.g. 16). */
  290. void TPE_worldDebugDraw(TPE_World *world, TPE_DebugDrawFunction drawFunc,
  291. TPE_Vec3 camPos, TPE_Vec3 camRot, TPE_Vec3 camView, uint16_t envGridRes,
  292. TPE_Unit envGridSize);
  293. //------------------------------------------------------------------------------
  294. static inline TPE_Unit TPE_nonZero(TPE_Unit x)
  295. {
  296. return x != 0 ? x : 1;
  297. }
  298. TPE_Joint TPE_joint(TPE_Vec3 position, TPE_Unit size)
  299. {
  300. TPE_Joint result;
  301. result.velocity[0] = 0;
  302. result.velocity[1] = 0;
  303. result.velocity[2] = 0;
  304. result.position = position;
  305. size /= TPE_JOINT_SIZE_MULTIPLIER;
  306. if (size > 0xff)
  307. TPE_LOG("WARNING: joint size too big in TPE_joint");
  308. result.sizeDivided = size;
  309. return result;
  310. }
  311. TPE_Vec3 TPE_vec3(TPE_Unit x, TPE_Unit y, TPE_Unit z)
  312. {
  313. TPE_Vec3 r;
  314. r.x = x;
  315. r.y = y;
  316. r.z = z;
  317. return r;
  318. }
  319. TPE_Unit TPE_sqrt(TPE_Unit value)
  320. {
  321. int8_t sign = 1;
  322. if (value < 0)
  323. {
  324. sign = -1;
  325. value *= -1;
  326. }
  327. uint32_t result = 0;
  328. uint32_t a = value;
  329. uint32_t b = 1u << 30;
  330. while (b > a)
  331. b >>= 2;
  332. while (b != 0)
  333. {
  334. if (a >= result + b)
  335. {
  336. a -= result + b;
  337. result = result + 2 * b;
  338. }
  339. b >>= 2;
  340. result >>= 1;
  341. }
  342. return result * sign;
  343. }
  344. TPE_Unit TPE_vec3Len(TPE_Vec3 v)
  345. {
  346. return TPE_sqrt(v.x * v.x + v.y * v.y + v.z * v.z);
  347. }
  348. TPE_Unit TPE_vec3LenApprox(TPE_Vec3 v)
  349. {
  350. if (v.x < 0)
  351. v.x *= -1;
  352. if (v.y < 0)
  353. v.y *= -1;
  354. if (v.z < 0)
  355. v.z *= -1;
  356. TPE_Unit sum = v.x + v.y + v.z;
  357. v.x = (v.x > v.y) ?
  358. (v.x > v.z ? v.x : v.z) :
  359. (v.y > v.z ? v.y : v.z);
  360. return (v.x + sum) / 2;
  361. }
  362. TPE_Unit TPE_dist(TPE_Vec3 p1, TPE_Vec3 p2)
  363. {
  364. p1 = TPE_vec3Minus(p1,p2);
  365. return TPE_vec3Len(p1);
  366. }
  367. TPE_Unit TPE_distApprox(TPE_Vec3 p1, TPE_Vec3 p2)
  368. {
  369. p1 = TPE_vec3Minus(p1,p2);
  370. return TPE_vec3LenApprox(p1);
  371. }
  372. void TPE_bodyInit(TPE_Body *body,
  373. TPE_Joint *joints, uint8_t jointCount,
  374. TPE_Connection *connections, uint8_t connectionCount,
  375. TPE_Unit mass)
  376. {
  377. body->joints = joints;
  378. body->jointCount = jointCount;
  379. body->connections = connections;
  380. body->connectionCount = connectionCount;
  381. body->deactivateCount = 0;
  382. body->friction = TPE_FRACTIONS_PER_UNIT / 2;
  383. body->elasticity = TPE_FRACTIONS_PER_UNIT / 2;
  384. body->flags = 0;
  385. body->jointMass = mass / jointCount;
  386. if (body->jointMass == 0)
  387. body->jointMass = 1;
  388. for (uint32_t i = 0; i < connectionCount; ++i)
  389. {
  390. TPE_Unit d = TPE_DISTANCE(
  391. joints[connections[i].joint1].position,
  392. joints[connections[i].joint2].position);
  393. if (d > 0xffff)
  394. TPE_LOG("WARNING: joint distance too long in TPE_bodyInit");
  395. connections[i].length = d != 0 ? d : 1; // prevent later division by zero
  396. }
  397. }
  398. void TPE_worldInit(TPE_World *world,
  399. TPE_Body *bodies, uint16_t bodyCount,
  400. TPE_ClosestPointFunction environmentFunction)
  401. {
  402. world->bodies = bodies;
  403. world->bodyCount = bodyCount;
  404. world->environmentFunction = environmentFunction;
  405. }
  406. #define C(n,a,b) connections[n].joint1 = a; connections[n].joint2 = b;
  407. void TPE_make2Line(TPE_Joint joints[2], TPE_Connection connections[1],
  408. TPE_Unit length, TPE_Unit jointSize)
  409. {
  410. joints[0] = TPE_joint(TPE_vec3(length / 2,0,0),jointSize);
  411. joints[1] = TPE_joint(TPE_vec3(length / -2,0,0),jointSize);
  412. C(0, 0,1)
  413. }
  414. void TPE_makeRect(TPE_Joint joints[4], TPE_Connection connections[6],
  415. TPE_Unit width, TPE_Unit depth, TPE_Unit jointSize)
  416. {
  417. width /= 2;
  418. depth /= 2;
  419. for (uint8_t i = 0; i < 4; ++i)
  420. joints[i] = TPE_joint(
  421. TPE_vec3((i % 2) ? -1 * width : width,
  422. 0,(i / 2) ? - 1 * depth : depth),
  423. jointSize);
  424. C(0, 0,1) C(1, 0,2) C (2, 3,1) C(3, 3,2)
  425. C(4, 0,3) C(5, 1,2)
  426. }
  427. void TPE_makeCenterRect(TPE_Joint joints[5], TPE_Connection connections[8],
  428. TPE_Unit width, TPE_Unit depth, TPE_Unit jointSize)
  429. {
  430. TPE_makeRect(joints,connections,width,depth,jointSize);
  431. joints[4] = TPE_joint(TPE_vec3(0,0,0),jointSize);
  432. C(6, 0,4) C(7, 3,4)
  433. }
  434. void TPE_makeTriangle(TPE_Joint joints[3], TPE_Connection connections[3],
  435. TPE_Unit sideLength, TPE_Unit jointSize)
  436. {
  437. joints[0] = TPE_joint(TPE_vec3(sideLength / 2,0,
  438. TPE_sqrt((sideLength * sideLength) / 2) / 2),
  439. jointSize);
  440. joints[1] = joints[0];
  441. joints[1].position.x *= -1;
  442. joints[2] = TPE_joint(TPE_vec3(0,0,-1 * joints[0].position.z),jointSize);
  443. C(0, 0,1) C(1, 1,2) C(2, 2,0)
  444. }
  445. void TPE_makeBox(TPE_Joint joints[8], TPE_Connection connections[16],
  446. TPE_Unit width, TPE_Unit depth, TPE_Unit height, TPE_Unit jointSize)
  447. {
  448. width /= 2;
  449. depth /= 2;
  450. height /= 2;
  451. for (uint8_t i = 0; i < 8; ++i)
  452. joints[i] = TPE_joint(
  453. TPE_vec3(
  454. (i % 2) ? width : (-1 * width),
  455. ((i >> 2) % 2) ? height : (-1 * height),
  456. ((i >> 1) % 2) ? depth : (-1 * depth)),
  457. jointSize);
  458. C(0, 0,1) C(1, 1,3) C(2, 3,2) C(3, 2,0) // top
  459. C(4, 4,5) C(5, 5,7) C(6, 7,6) C(7, 6,4) // bottom
  460. C(8, 0,4) C(9, 1,5) C(10,3,7) C(11,2,6) // middle
  461. C(12,0,7) C(13,1,6) C(14,2,5) C(15,3,4) // diagonal
  462. }
  463. void TPE_makeCenterBox(TPE_Joint joints[9], TPE_Connection connections[18],
  464. TPE_Unit width, TPE_Unit depth, TPE_Unit height, TPE_Unit jointSize)
  465. {
  466. TPE_makeBox(joints,connections,width,depth,height,jointSize);
  467. joints[8] = TPE_joint(TPE_vec3(0,0,0),jointSize);
  468. C(16, 0,8) C(17, 7,8)
  469. }
  470. #undef C
  471. void TPE_bodyDeactivate(TPE_Body *body)
  472. {
  473. body->flags |= TPE_BODY_FLAG_DEACTIVATED;
  474. }
  475. void TPE_worldStep(TPE_World *world)
  476. {
  477. for (uint16_t i = 0; i < world->bodyCount; ++i)
  478. {
  479. TPE_Body *body = world->bodies + i;
  480. if (body->flags & (TPE_BODY_FLAG_DEACTIVATED | TPE_BODY_FLAG_DISABLED))
  481. continue;
  482. TPE_Joint *joint = body->joints, *joint2;
  483. for (uint16_t j = 0; j < body->jointCount; ++j) // apply velocities
  484. {
  485. // non-rotating bodies will copy the 1st joint's velocity
  486. if (body->flags & TPE_BODY_FLAG_NONROTATING)
  487. for (uint8_t k = 0; k < 3; ++k)
  488. joint->velocity[k] = body->joints[0].velocity[k];
  489. joint->position.x += joint->velocity[0];
  490. joint->position.y += joint->velocity[1];
  491. joint->position.z += joint->velocity[2];
  492. joint++;
  493. }
  494. TPE_Connection *connection = body->connections;
  495. TPE_Vec3 aabbMin, aabbMax;
  496. TPE_bodyGetAABB(body,&aabbMin,&aabbMax);
  497. for (uint16_t j = 0; j < world->bodyCount; ++j)
  498. {
  499. if (j > i || (world->bodies[j].flags & TPE_BODY_FLAG_DEACTIVATED))
  500. {
  501. // firstly quick-check collision of body AA bounding boxes
  502. TPE_Vec3 aabbMin2, aabbMax2;
  503. TPE_bodyGetAABB(&world->bodies[j],&aabbMin2,&aabbMax2);
  504. if (TPE_checkOverlapAABB(aabbMin,aabbMax,aabbMin2,aabbMax2) &&
  505. TPE_bodiesResolveCollision(body,world->bodies + j))
  506. {
  507. TPE_bodyActivate(body);
  508. body->deactivateCount = TPE_LIGHT_DEACTIVATION;
  509. TPE_bodyActivate(world->bodies + j);
  510. world->bodies[j].deactivateCount = TPE_LIGHT_DEACTIVATION;
  511. }
  512. }
  513. }
  514. TPE_bodyEnvironmentResolveCollision(body,world->environmentFunction);
  515. TPE_Unit bodyTension = 0;
  516. if (!(body->flags & TPE_BODY_FLAG_NONROTATING))
  517. {
  518. for (uint16_t j = 0; j < body->connectionCount; ++j) // update velocities
  519. {
  520. joint = &(body->joints[connection->joint1]);
  521. joint2 = &(body->joints[connection->joint2]);
  522. TPE_Vec3 dir = TPE_vec3Minus(joint2->position,joint->position);
  523. TPE_Unit len = TPE_LENGTH(dir);
  524. len = (len * TPE_FRACTIONS_PER_UNIT) /
  525. connection->length - TPE_FRACTIONS_PER_UNIT;
  526. bodyTension += len > 0 ? len : -len;
  527. if (len > TPE_TENSION_ACCELERATION_THRESHOLD ||
  528. len < -1 * TPE_TENSION_ACCELERATION_THRESHOLD)
  529. {
  530. TPE_vec3Normalize(&dir);
  531. dir.x /= TPE_TENSION_ACCELERATION_DIVIDER;
  532. dir.y /= TPE_TENSION_ACCELERATION_DIVIDER;
  533. dir.z /= TPE_TENSION_ACCELERATION_DIVIDER;
  534. if (len < 0)
  535. {
  536. dir.x *= -1;
  537. dir.y *= -1;
  538. dir.z *= -1;
  539. }
  540. joint->velocity[0] += dir.x;
  541. joint->velocity[1] += dir.y;
  542. joint->velocity[2] += dir.z;
  543. joint2->velocity[0] -= dir.x;
  544. joint2->velocity[1] -= dir.y;
  545. joint2->velocity[2] -= dir.z;
  546. }
  547. connection++;
  548. }
  549. if (body->connectionCount > 0 && !(body->flags & TPE_BODY_FLAG_SOFT))
  550. {
  551. TPE_bodyReshape(body,world->environmentFunction);
  552. bodyTension /= body->connectionCount;
  553. if (bodyTension > TPE_RESHAPE_TENSION_LIMIT)
  554. for (uint8_t k = 0; k < TPE_RESHAPE_ITERATIONS; ++k)
  555. TPE_bodyReshape(body,world->environmentFunction);
  556. }
  557. } // if (rotating)
  558. if (body->deactivateCount >= TPE_DEACTIVATE_AFTER)
  559. {
  560. TPE_bodyStop(body);
  561. body->deactivateCount = 0;
  562. body->flags |= TPE_BODY_FLAG_DEACTIVATED;
  563. }
  564. else if (TPE_bodyAverageSpeed(body) <= TPE_LOW_SPEED) // TODO: optimize
  565. body->deactivateCount++;
  566. else
  567. body->deactivateCount = 0;
  568. }
  569. }
  570. void TPE_bodyActivate(TPE_Body *body)
  571. {
  572. // the if check has to be here, don't remove it
  573. if (body->flags & TPE_BODY_FLAG_DEACTIVATED)
  574. {
  575. TPE_bodyStop(body);
  576. body->flags &= ~TPE_BODY_FLAG_DEACTIVATED;
  577. body->deactivateCount = 0;
  578. }
  579. }
  580. TPE_Unit TPE_bodyNetSpeed(const TPE_Body *body)
  581. {
  582. TPE_Unit velocity = 0;
  583. const TPE_Joint *joint = body->joints;
  584. for (uint16_t i = 0; i < body->jointCount; ++i)
  585. {
  586. velocity += TPE_LENGTH(
  587. TPE_vec3(joint->velocity[0],joint->velocity[1],joint->velocity[2]));
  588. joint++;
  589. }
  590. return velocity;
  591. }
  592. TPE_Unit TPE_bodyAverageSpeed(const TPE_Body *body)
  593. {
  594. return TPE_bodyNetSpeed(body) / body->jointCount;
  595. }
  596. void TPE_bodyMultiplyNetSpeed(TPE_Body *body, TPE_Unit factor)
  597. {
  598. TPE_Joint *joint = body->joints;
  599. for (uint16_t j = 0; j < body->jointCount; ++j)
  600. {
  601. for (uint8_t k = 0; k < 3; ++k)
  602. joint->velocity[k] =
  603. (((TPE_Unit) joint->velocity[k]) * factor) /
  604. TPE_FRACTIONS_PER_UNIT;
  605. joint++;
  606. }
  607. }
  608. void TPE_bodyLimitAverageSpeed(TPE_Body *body, TPE_Unit speedMin,
  609. TPE_Unit speedMax)
  610. {
  611. for (uint8_t i = 0; i < 16; ++i)
  612. {
  613. TPE_Unit speed = TPE_bodyAverageSpeed(body);
  614. if (speed >= speedMin && speed <= speedMax)
  615. return;
  616. TPE_Unit fraction =
  617. (((speedMax + speedMin) / 2) * TPE_FRACTIONS_PER_UNIT) /
  618. TPE_nonZero(speed);
  619. TPE_bodyMultiplyNetSpeed(body,fraction);
  620. }
  621. }
  622. void TPE_bodyReshape(TPE_Body *body,
  623. TPE_ClosestPointFunction environmentFunction)
  624. {
  625. for (uint16_t i = 0; i < body->connectionCount; ++i)
  626. {
  627. TPE_Connection *c = &body->connections[i];
  628. TPE_Joint *j1 = &(body->joints[c->joint1]);
  629. TPE_Joint *j2 = &(body->joints[c->joint2]);
  630. TPE_Vec3 dir = TPE_vec3Minus(j2->position,j1->position);
  631. TPE_Vec3 middle = TPE_vec3Plus(j1->position,j2->position);
  632. middle.x /= 2;
  633. middle.y /= 2;
  634. middle.z /= 2;
  635. TPE_vec3Normalize(&dir);
  636. dir.x = (dir.x * c->length) / TPE_FRACTIONS_PER_UNIT;
  637. dir.y = (dir.y * c->length) / TPE_FRACTIONS_PER_UNIT;
  638. dir.z = (dir.z * c->length) / TPE_FRACTIONS_PER_UNIT;
  639. TPE_Vec3 positionBackup = j1->position;
  640. j1->position.x = middle.x - dir.x / 2;
  641. j1->position.y = middle.y - dir.y / 2;
  642. j1->position.z = middle.z - dir.z / 2;
  643. if (environmentFunction != 0 && TPE_LENGTH(TPE_vec3Minus(j1->position,
  644. environmentFunction(j1->position,TPE_JOINT_SIZE(*j1))))
  645. < TPE_JOINT_SIZE(*j1))
  646. j1->position = positionBackup;
  647. positionBackup = j2->position;
  648. j2->position.x = j1->position.x + dir.x;
  649. j2->position.y = j1->position.y + dir.y;
  650. j2->position.z = j1->position.z + dir.z;
  651. if (environmentFunction != 0 && TPE_LENGTH(TPE_vec3Minus(j2->position,
  652. environmentFunction(j2->position,TPE_JOINT_SIZE(*j2))))
  653. < TPE_JOINT_SIZE(*j2))
  654. j2->position = positionBackup;
  655. }
  656. }
  657. TPE_Vec3 TPE_vec3Plus(TPE_Vec3 v1, TPE_Vec3 v2)
  658. {
  659. v1.x += v2.x;
  660. v1.y += v2.y;
  661. v1.z += v2.z;
  662. return v1;
  663. }
  664. TPE_Vec3 TPE_vec3Minus(TPE_Vec3 v1, TPE_Vec3 v2)
  665. {
  666. v1.x -= v2.x;
  667. v1.y -= v2.y;
  668. v1.z -= v2.z;
  669. return v1;
  670. }
  671. void TPE_vec3Normalize(TPE_Vec3 *v)
  672. {
  673. TPE_Unit l = TPE_LENGTH(*v);
  674. if (l != 0)
  675. {
  676. v->x = (v->x * TPE_FRACTIONS_PER_UNIT) / l;
  677. v->y = (v->y * TPE_FRACTIONS_PER_UNIT) / l;
  678. v->z = (v->z * TPE_FRACTIONS_PER_UNIT) / l;
  679. }
  680. }
  681. TPE_Vec3 TPE_bodyGetCenter(const TPE_Body *body)
  682. {
  683. // TODO: take into account possibly different joint sizes? does it even matter?
  684. TPE_Vec3 result = TPE_vec3(0,0,0);
  685. const TPE_Joint *j = body->joints;
  686. for (uint16_t i = 0; i < body->jointCount; ++i)
  687. {
  688. result = TPE_vec3Plus(result,j->position);
  689. j++;
  690. }
  691. result.x /= body->jointCount;
  692. result.y /= body->jointCount;
  693. result.z /= body->jointCount;
  694. return result;
  695. }
  696. void TPE_bodySpin(TPE_Body *body, TPE_Vec3 rotation)
  697. {
  698. TPE_Vec3 center = TPE_bodyGetCenter(body);
  699. for (uint16_t i = 0; i < body->jointCount; ++i)
  700. {
  701. TPE_Joint *j = body->joints + i;
  702. TPE_Vec3 toPoint = TPE_vec3Minus(j->position,center);
  703. toPoint = TPE_vec3Project(toPoint,rotation);
  704. toPoint = TPE_vec3Plus(center,toPoint);
  705. toPoint = TPE_vec3Minus(j->position,toPoint);
  706. toPoint = TPE_vec3Cross(toPoint,rotation);
  707. j->velocity[0] += toPoint.x;
  708. j->velocity[1] += toPoint.y;
  709. j->velocity[2] += toPoint.z;
  710. }
  711. }
  712. void TPE_bodyRotateByAxis(TPE_Body *body, TPE_Vec3 rotation)
  713. {
  714. TPE_Vec3 bodyCenter = TPE_bodyGetCenter(body);
  715. TPE_Unit angle = TPE_LENGTH(rotation);
  716. TPE_vec3Normalize(&rotation);
  717. for (uint16_t i = 0; i < body->jointCount; ++i)
  718. {
  719. TPE_Joint *j = body->joints + i;
  720. TPE_Vec3 toPoint = TPE_vec3Minus(j->position,bodyCenter);
  721. toPoint = TPE_vec3Project(toPoint,rotation);
  722. TPE_Vec3 rotationCenter = TPE_vec3Plus(bodyCenter,toPoint);
  723. toPoint = TPE_vec3Minus(j->position,rotationCenter);
  724. TPE_Vec3 toPoint2 = TPE_vec3Cross(toPoint,rotation);
  725. j->position = TPE_vec3Plus(rotationCenter,
  726. TPE_vec3Plus(
  727. TPE_vec3Times(toPoint,TPE_cos(angle)),
  728. TPE_vec3Times(toPoint2,TPE_sin(angle))));
  729. }
  730. }
  731. TPE_Vec3 TPE_vec3Cross(TPE_Vec3 v1, TPE_Vec3 v2)
  732. {
  733. TPE_Vec3 r;
  734. r.x = (v1.y * v2.z - v1.z * v2.y) / TPE_FRACTIONS_PER_UNIT;
  735. r.y = (v1.z * v2.x - v1.x * v2.z) / TPE_FRACTIONS_PER_UNIT;
  736. r.z = (v1.x * v2.y - v1.y * v2.x) / TPE_FRACTIONS_PER_UNIT;
  737. return r;
  738. }
  739. TPE_Vec3 TPE_vec3Project(TPE_Vec3 v, TPE_Vec3 base)
  740. {
  741. TPE_Vec3 r;
  742. TPE_vec3Normalize(&base);
  743. TPE_Unit p = TPE_vec3Dot(v,base);
  744. r.x = (p * base.x) / TPE_FRACTIONS_PER_UNIT;
  745. r.y = (p * base.y) / TPE_FRACTIONS_PER_UNIT;
  746. r.z = (p * base.z) / TPE_FRACTIONS_PER_UNIT;
  747. return r;
  748. }
  749. void TPE_bodyMove(TPE_Body *body, TPE_Vec3 offset)
  750. {
  751. for (uint16_t i = 0; i < body->jointCount; ++i)
  752. body->joints[i].position = TPE_vec3Plus(body->joints[i].position,
  753. offset);
  754. }
  755. void TPE_bodyAccelerate(TPE_Body *body, TPE_Vec3 velocity)
  756. {
  757. TPE_bodyActivate(body);
  758. for (uint16_t i = 0; i < body->jointCount; ++i)
  759. {
  760. body->joints[i].velocity[0] += velocity.x;
  761. body->joints[i].velocity[1] += velocity.y;
  762. body->joints[i].velocity[2] += velocity.z;
  763. }
  764. }
  765. void TPE_bodyStop(TPE_Body *body)
  766. {
  767. for (uint16_t i = 0; i < body->jointCount; ++i)
  768. {
  769. body->joints[i].velocity[0] = 0;
  770. body->joints[i].velocity[1] = 0;
  771. body->joints[i].velocity[2] = 0;
  772. }
  773. }
  774. void _TPE_bodyNonrotatingJointCollided(TPE_Body *b, int16_t jointIndex,
  775. TPE_Vec3 origPos, uint8_t success)
  776. {
  777. origPos = TPE_vec3Minus(b->joints[jointIndex].position,origPos);
  778. for (uint16_t i = 0; i < b->jointCount; ++i)
  779. if (i != jointIndex)
  780. {
  781. b->joints[i].position = TPE_vec3Plus(b->joints[i].position,origPos);
  782. if (success)
  783. for (uint8_t j = 0; j < 3; ++j)
  784. b->joints[i].velocity[j] = b->joints[jointIndex].velocity[j];
  785. }
  786. }
  787. TPE_Unit TPE_vec3Dot(TPE_Vec3 v1, TPE_Vec3 v2)
  788. {
  789. return (v1.x * v2.x + v1.y * v2.y + v1.z * v2.z) / TPE_FRACTIONS_PER_UNIT;
  790. }
  791. TPE_Unit TPE_cos(TPE_Unit x)
  792. {
  793. return TPE_sin(x + TPE_FRACTIONS_PER_UNIT / 4);
  794. }
  795. TPE_Unit TPE_sin(TPE_Unit x)
  796. {
  797. int8_t sign = 1;
  798. if (x < 0) // odd function
  799. {
  800. x *= -1;
  801. sign = -1;
  802. }
  803. x %= TPE_FRACTIONS_PER_UNIT;
  804. if (x > TPE_FRACTIONS_PER_UNIT / 2)
  805. {
  806. x -= TPE_FRACTIONS_PER_UNIT / 2;
  807. sign *= -1;
  808. }
  809. TPE_Unit tmp = TPE_FRACTIONS_PER_UNIT - 2 * x;
  810. #define _PI2 ((TPE_Unit) (9.8696044 * TPE_FRACTIONS_PER_UNIT))
  811. return sign * // Bhaskara's approximation
  812. (((32 * x * _PI2) / TPE_FRACTIONS_PER_UNIT) * tmp) /
  813. ((_PI2 * (5 * TPE_FRACTIONS_PER_UNIT - (8 * x * tmp) /
  814. TPE_FRACTIONS_PER_UNIT)) / TPE_FRACTIONS_PER_UNIT);
  815. #undef _PI2
  816. }
  817. uint8_t TPE_bodiesResolveCollision(TPE_Body *b1, TPE_Body *b2)
  818. {
  819. uint8_t r = 0;
  820. for (uint16_t i = 0; i < b1->jointCount; ++i)
  821. for (uint16_t j = 0; j < b2->jointCount; ++j)
  822. {
  823. TPE_Vec3 origPos2 = b2->joints[j].position;
  824. TPE_Vec3 origPos1 = b1->joints[i].position;
  825. if (TPE_jointsResolveCollision(&(b1->joints[i]),&(b2->joints[j]),
  826. b1->jointMass,b2->jointMass,(b1->elasticity + b2->elasticity) / 2,
  827. (b1->friction + b2->friction) / 2))
  828. {
  829. r = 1;
  830. if (b1->flags & TPE_BODY_FLAG_NONROTATING)
  831. _TPE_bodyNonrotatingJointCollided(b1,i,origPos1,1);
  832. if (b2->flags & TPE_BODY_FLAG_NONROTATING)
  833. _TPE_bodyNonrotatingJointCollided(b2,j,origPos2,1);
  834. }
  835. }
  836. return r;
  837. }
  838. uint8_t TPE_jointsResolveCollision(TPE_Joint *j1, TPE_Joint *j2,
  839. TPE_Unit mass1, TPE_Unit mass2, TPE_Unit elasticity, TPE_Unit friction)
  840. {
  841. TPE_Vec3 dir = TPE_vec3Minus(j2->position,j1->position);
  842. TPE_Unit d = TPE_LENGTH(dir) - TPE_JOINT_SIZE(*j1) - TPE_JOINT_SIZE(*j2);
  843. if (d < 0) // collision?
  844. {
  845. // separate bodies, the shift distance will depend on the weight ratio:
  846. d = -1 * d + TPE_COLLISION_RESOLUTION_MARGIN;
  847. TPE_vec3Normalize(&dir);
  848. TPE_Unit ratio = (mass2 * TPE_FRACTIONS_PER_UNIT) /
  849. TPE_nonZero(mass1 + mass2);
  850. TPE_Unit shiftDistance = (ratio * d) / TPE_FRACTIONS_PER_UNIT;
  851. TPE_Vec3 shift = TPE_vec3Times(dir,shiftDistance);
  852. j1->position = TPE_vec3Minus(j1->position,shift);
  853. shiftDistance = d - shiftDistance;
  854. shift = TPE_vec3Times(dir,shiftDistance);
  855. j2->position = TPE_vec3Plus(j2->position,shift);
  856. // compute new velocities:
  857. TPE_Unit v1, v2;
  858. TPE_Vec3 vel = TPE_vec3(j1->velocity[0],j1->velocity[1],j1->velocity[2]);
  859. vel = TPE_vec3Project(vel,dir);
  860. j1->velocity[0] = j1->velocity[0] - vel.x;
  861. j1->velocity[1] = j1->velocity[1] - vel.y;
  862. j1->velocity[2] = j1->velocity[2] - vel.z;
  863. /* friction explanation: Not physically correct (doesn't depend on load),
  864. friction basically means we weighted average the velocities of the bodies
  865. in the direction perpendicular to the hit normal, in the ratio of their
  866. masses, friction coefficient just says how much of this effect we apply
  867. (it multiplies the friction vectors we are subtracting) */
  868. TPE_Vec3 frictionVec =
  869. TPE_vec3(j1->velocity[0],j1->velocity[1],j1->velocity[2]);
  870. v1 = TPE_vec3Dot(vel,dir);
  871. vel = TPE_vec3(j2->velocity[0],j2->velocity[1],j2->velocity[2]);
  872. vel = TPE_vec3Project(vel,dir);
  873. j2->velocity[0] = j2->velocity[0] - vel.x;
  874. j2->velocity[1] = j2->velocity[1] - vel.y;
  875. j2->velocity[2] = j2->velocity[2] - vel.z;
  876. frictionVec = TPE_vec3Minus(
  877. TPE_vec3(j2->velocity[0],j2->velocity[1],j2->velocity[2]),
  878. frictionVec);
  879. v2 = TPE_vec3Dot(vel,dir);
  880. TPE_getVelocitiesAfterCollision(&v1,&v2,mass1,mass2,elasticity);
  881. vel = TPE_vec3Times(dir,v1);
  882. #define assignVec(j,i,d,o) \
  883. j->velocity[i] = j->velocity[i] + vel.d o (((frictionVec.d * ratio) / \
  884. TPE_FRACTIONS_PER_UNIT) * friction) / TPE_FRACTIONS_PER_UNIT;
  885. assignVec(j1,0,x,+)
  886. assignVec(j1,1,y,+)
  887. assignVec(j1,2,z,+)
  888. vel = TPE_vec3Times(dir,v2);
  889. ratio = TPE_FRACTIONS_PER_UNIT - ratio;
  890. assignVec(j2,0,x,-)
  891. assignVec(j2,1,y,-)
  892. assignVec(j2,2,z,-)
  893. #undef assignVec
  894. return 1;
  895. }
  896. return 0;
  897. }
  898. TPE_Vec3 TPE_vec3Times(TPE_Vec3 v, TPE_Unit units)
  899. {
  900. v.x = (v.x * units) / TPE_FRACTIONS_PER_UNIT;
  901. v.y = (v.y * units) / TPE_FRACTIONS_PER_UNIT;
  902. v.z = (v.z * units) / TPE_FRACTIONS_PER_UNIT;
  903. return v;
  904. }
  905. TPE_Vec3 TPE_vec3TimesNonNormalized(TPE_Vec3 v, TPE_Unit q)
  906. {
  907. v.x *= q;
  908. v.y *= q;
  909. v.z *= q;
  910. return v;
  911. }
  912. void TPE_getVelocitiesAfterCollision(
  913. TPE_Unit *v1,
  914. TPE_Unit *v2,
  915. TPE_Unit m1,
  916. TPE_Unit m2,
  917. TPE_Unit elasticity
  918. )
  919. {
  920. /* In the following a lot of TPE_FRACTIONS_PER_UNIT cancel out, feel free to
  921. check if confused. */
  922. TPE_Unit m1Pm2 = TPE_nonZero(m1 + m2);
  923. TPE_Unit v2Mv1 = TPE_nonZero(*v2 - *v1);
  924. TPE_Unit m1v1Pm2v2 = ((m1 * *v1) + (m2 * *v2));
  925. *v1 = (((elasticity * m2 / TPE_FRACTIONS_PER_UNIT) * v2Mv1)
  926. + m1v1Pm2v2) / m1Pm2;
  927. *v2 = (((elasticity * m1 / TPE_FRACTIONS_PER_UNIT) * -1 * v2Mv1)
  928. + m1v1Pm2v2) / m1Pm2;
  929. }
  930. uint8_t TPE_jointEnvironmentResolveCollision(TPE_Joint *joint, TPE_Unit elasticity,
  931. TPE_Unit friction, TPE_ClosestPointFunction env)
  932. {
  933. TPE_Vec3 toJoint = TPE_vec3Minus(joint->position,env(joint->position,TPE_JOINT_SIZE(*joint)));
  934. TPE_Unit len = TPE_LENGTH(toJoint);
  935. if (len <= TPE_JOINT_SIZE(*joint))
  936. {
  937. // colliding
  938. TPE_Vec3 positionBackup = joint->position, shift;
  939. uint8_t success = 0;
  940. if (len > 0)
  941. {
  942. /* Joint center is still outside the geometry so we can determine the
  943. normal and use it to shift it outside. This can still leave the joint
  944. colliding though, so try to repeat it a few times. */
  945. for (int i = 0; i < TPE_COLLISION_RESOLUTION_ITERATIONS; ++i)
  946. {
  947. shift = toJoint;
  948. TPE_vec3Normalize(&shift);
  949. shift = TPE_vec3Times(shift,TPE_JOINT_SIZE(*joint) - len +
  950. TPE_FRACTIONS_PER_UNIT / TPE_COLLISION_RESOLUTION_MARGIN);
  951. joint->position = TPE_vec3Plus(joint->position,shift);
  952. toJoint = TPE_vec3Minus(joint->position,env(joint->position,TPE_JOINT_SIZE(*joint)));
  953. len = TPE_LENGTH(toJoint); // still colliding?
  954. if (len >= TPE_JOINT_SIZE(*joint))
  955. {
  956. success = 1;
  957. break;
  958. }
  959. }
  960. }
  961. if (!success)
  962. {
  963. /* Shifting along normal was unsuccessfull, now try different approach:
  964. shift back by joint velocity. */
  965. shift = TPE_vec3(-1 * joint->velocity[0],-1 * joint->velocity[1],
  966. -1 * joint->velocity[2]);
  967. for (int i = 0; i < TPE_COLLISION_RESOLUTION_ITERATIONS; ++i)
  968. {
  969. joint->position = TPE_vec3Plus(joint->position,shift);
  970. toJoint = TPE_vec3Minus(joint->position,env(joint->position,TPE_JOINT_SIZE(*joint)));
  971. len = TPE_LENGTH(toJoint); // still colliding?
  972. if (len >= TPE_JOINT_SIZE(*joint))
  973. {
  974. success = 1;
  975. break;
  976. }
  977. shift.x /= 2; // decrease the step a bit
  978. shift.y /= 2;
  979. shift.z /= 2;
  980. }
  981. }
  982. if (success)
  983. {
  984. TPE_Vec3 vel = TPE_vec3(joint->velocity[0],joint->velocity[1],
  985. joint->velocity[2]);
  986. vel = TPE_vec3Project(vel,shift);
  987. TPE_Vec3 vel2 = TPE_vec3Minus(
  988. TPE_vec3(joint->velocity[0],joint->velocity[1],joint->velocity[2]),vel);
  989. vel2 = TPE_vec3Times(vel2,friction);
  990. vel = TPE_vec3Times(vel,TPE_FRACTIONS_PER_UNIT + elasticity);
  991. joint->velocity[0] -= vel.x + vel2.x;
  992. joint->velocity[1] -= vel.y + vel2.y;
  993. joint->velocity[2] -= vel.z + vel2.z;
  994. }
  995. else
  996. {
  997. TPE_LOG("WARNING: joint-environment collision couldn't be resolved");
  998. joint->position = positionBackup;
  999. joint->velocity[0] = 0;
  1000. joint->velocity[1] = 0;
  1001. joint->velocity[2] = 0;
  1002. return 2;
  1003. }
  1004. return 1;
  1005. }
  1006. return 0;
  1007. }
  1008. uint8_t TPE_bodyEnvironmentCollide(const TPE_Body *body,
  1009. TPE_ClosestPointFunction env)
  1010. {
  1011. // TODO: should bounding vol check be here? maybe in param?
  1012. for (uint16_t i = 0; i < body->jointCount; ++i)
  1013. {
  1014. const TPE_Joint *joint = body->joints + i;
  1015. TPE_Unit size = TPE_JOINT_SIZE(*joint);
  1016. if (TPE_DISTANCE(joint->position,env(joint->position,size)) <= size)
  1017. return 1;
  1018. }
  1019. return 0;
  1020. }
  1021. uint8_t TPE_bodyEnvironmentResolveCollision(TPE_Body *body,
  1022. TPE_ClosestPointFunction env)
  1023. {
  1024. /* Bounding sphere test first. NOTE: This is not a minimal bounding sphere
  1025. but one created from the bounding box. Hopes are that this can be faster.
  1026. TODO: actually test if the minimal B sphere is faster */
  1027. TPE_Vec3 v1, v2;
  1028. TPE_bodyGetAABB(body,&v1,&v2);
  1029. v1.x = (v1.x + v2.x) / 2;
  1030. v1.y = (v1.y + v2.y) / 2;
  1031. v1.z = (v1.z + v2.z) / 2;
  1032. TPE_Unit d = TPE_DISTANCE(v1,v2);
  1033. if (TPE_DISTANCE(v1,env(v1,d)) > d)
  1034. return 0;
  1035. // now test the full body collision:
  1036. uint8_t collision = 0;
  1037. for (uint16_t i = 0; i < body->jointCount; ++i)
  1038. {
  1039. TPE_Vec3 previousPos = body->joints[i].position;
  1040. uint8_t r = TPE_jointEnvironmentResolveCollision(
  1041. body->joints + i,body->elasticity,body->friction,env);
  1042. if (r)
  1043. {
  1044. collision = 1;
  1045. if (body->flags & TPE_BODY_FLAG_NONROTATING)
  1046. _TPE_bodyNonrotatingJointCollided(body,i,previousPos,r == 1);
  1047. }
  1048. }
  1049. return collision;
  1050. }
  1051. TPE_Vec3 TPE_vec3Normalized(TPE_Vec3 v)
  1052. {
  1053. TPE_vec3Normalize(&v);
  1054. return v;
  1055. }
  1056. TPE_Unit TPE_atan(TPE_Unit x)
  1057. {
  1058. /* atan approximation by polynomial
  1059. WARNING: this will break with different value of TPE_FRACTIONS_PER_UNIT */
  1060. TPE_Unit sign = 1, x2 = x * x;
  1061. if (x < 0)
  1062. {
  1063. x *= -1;
  1064. sign = -1;
  1065. }
  1066. if (x > 30000) // anti overflow
  1067. return sign * (TPE_FRACTIONS_PER_UNIT / 4);
  1068. return sign *
  1069. (307 * x + x2) / ((267026 + 633 * x + x2) / 128);
  1070. }
  1071. void _TPE_vec2Rotate(TPE_Unit *x, TPE_Unit *y, TPE_Unit angle)
  1072. {
  1073. TPE_Unit tmp = *x;
  1074. TPE_Unit s = TPE_sin(angle);
  1075. TPE_Unit c = TPE_cos(angle);
  1076. *x = (c * *x - s * *y) / TPE_FRACTIONS_PER_UNIT;
  1077. *y = (s * tmp + c * *y) / TPE_FRACTIONS_PER_UNIT;
  1078. }
  1079. TPE_Unit _TPE_vec2Angle(TPE_Unit x, TPE_Unit y)
  1080. {
  1081. TPE_Unit r = 0;
  1082. if (x != 0)
  1083. {
  1084. r = TPE_atan((y * TPE_FRACTIONS_PER_UNIT) / x);
  1085. if (x < 0)
  1086. r += TPE_FRACTIONS_PER_UNIT / 2;
  1087. else if (r < 0)
  1088. r += TPE_FRACTIONS_PER_UNIT;
  1089. }
  1090. else
  1091. {
  1092. if (y < 0)
  1093. r = (3 * TPE_FRACTIONS_PER_UNIT) / 4;
  1094. else if (y > 0)
  1095. r = TPE_FRACTIONS_PER_UNIT / 4;
  1096. // else (y == 0) r stays 0
  1097. }
  1098. return r;
  1099. }
  1100. TPE_Vec3 TPE_orientationFromVecs(TPE_Vec3 forward, TPE_Vec3 right)
  1101. {
  1102. TPE_Vec3 result;
  1103. // get rotation around Y:
  1104. result.y = _TPE_vec2Angle(forward.z,-1 * forward.x);
  1105. // now rotate back by this angle to align with x = 0 plane:
  1106. _TPE_vec2Rotate(&forward.z,&forward.x,result.y);
  1107. _TPE_vec2Rotate(&right.z,&right.x,result.y);
  1108. // now do the same for the second axis:
  1109. result.x =
  1110. _TPE_vec2Angle(forward.z,forward.y);
  1111. _TPE_vec2Rotate(&right.z,&right.y,-1 * result.x);
  1112. result.z = _TPE_vec2Angle(right.x,-1 * right.y);
  1113. return result;
  1114. }
  1115. TPE_Vec3 _TPE_project3DPoint(TPE_Vec3 p, TPE_Vec3 camPos, TPE_Vec3 camRot,
  1116. TPE_Vec3 camView)
  1117. {
  1118. // transform to camera space:
  1119. p = TPE_vec3Minus(p,camPos);
  1120. _TPE_vec2Rotate(&p.z,&p.x,camRot.y);
  1121. _TPE_vec2Rotate(&p.z,&p.y,-1 * camRot.x);
  1122. _TPE_vec2Rotate(&p.y,&p.x,-1 * camRot.z);
  1123. if (p.z <= 0)
  1124. return p;
  1125. p.x = (p.x * camView.z) / p.z;
  1126. p.y = (p.y * camView.z) / p.z;
  1127. p.x = camView.x / 2 + (p.x * camView.x) / (2 * TPE_FRACTIONS_PER_UNIT);
  1128. p.y = camView.y / 2 - (p.y * camView.x) / (2 * TPE_FRACTIONS_PER_UNIT);
  1129. // ^ x here intentional
  1130. return p;
  1131. }
  1132. void _TPE_drawDebugPixel(
  1133. TPE_Unit x, TPE_Unit y, TPE_Unit w, TPE_Unit h, uint8_t c,
  1134. TPE_DebugDrawFunction f)
  1135. {
  1136. if (x >= 0 && x < w && y >= 0 && y < h)
  1137. f(x,y,c);
  1138. }
  1139. void TPE_worldDebugDraw(TPE_World *world, TPE_DebugDrawFunction drawFunc,
  1140. TPE_Vec3 camPos, TPE_Vec3 camRot, TPE_Vec3 camView, uint16_t envGridRes,
  1141. TPE_Unit envGridSize)
  1142. {
  1143. if (world->environmentFunction != 0)
  1144. {
  1145. // environment:
  1146. TPE_Vec3 testPoint;
  1147. TPE_Vec3 center = TPE_vec3(0,TPE_sin(camRot.x),TPE_cos(camRot.x));
  1148. _TPE_vec2Rotate(&center.x,&center.z,camRot.y);
  1149. TPE_Unit gridHalfSize = (envGridSize * envGridRes) / 2;
  1150. center = TPE_vec3Times(center,gridHalfSize);
  1151. center = TPE_vec3Plus(camPos,center);
  1152. center.x = (center.x / envGridSize) * envGridSize;
  1153. center.y = (center.y / envGridSize) * envGridSize;
  1154. center.z = (center.z / envGridSize) * envGridSize;
  1155. testPoint.y = center.y - gridHalfSize;
  1156. for (uint8_t j = 0; j < envGridRes; ++j)
  1157. {
  1158. testPoint.x = center.x - gridHalfSize;
  1159. for (uint8_t k = 0; k < envGridRes; ++k)
  1160. {
  1161. testPoint.z = center.z - gridHalfSize;
  1162. for (uint8_t l = 0; l < envGridRes; ++l)
  1163. {
  1164. TPE_Vec3 r = world->environmentFunction(testPoint,envGridSize);
  1165. if ((r.x != testPoint.x || r.y != testPoint.y || r.z != testPoint.z))
  1166. {
  1167. // TODO: accel. by testing cheb dist first?
  1168. r = _TPE_project3DPoint(r,camPos,camRot,camView);
  1169. if (r.z > 0)
  1170. _TPE_drawDebugPixel(r.x,r.y,camView.x,camView.y,2,drawFunc);
  1171. }
  1172. testPoint.z += envGridSize;
  1173. }
  1174. testPoint.x += envGridSize;
  1175. }
  1176. testPoint.y += envGridSize;
  1177. }
  1178. }
  1179. for (uint16_t i = 0; i < world->bodyCount; ++i)
  1180. {
  1181. // connections:
  1182. for (uint16_t j = 0; j < world->bodies[i].connectionCount; ++j)
  1183. {
  1184. TPE_Vec3
  1185. p1 = world->bodies[i].joints[world->bodies[i].connections[j].joint1].position,
  1186. p2 = world->bodies[i].joints[world->bodies[i].connections[j].joint2].position;
  1187. p1 = _TPE_project3DPoint(p1,camPos,camRot,camView);
  1188. p2 = _TPE_project3DPoint(p2,camPos,camRot,camView);
  1189. if (p1.z <= 0 || p2.z <= 0)
  1190. continue;
  1191. TPE_Vec3 diff = TPE_vec3Minus(p2,p1);
  1192. #define SEGS 16
  1193. for (uint16_t k = 0; k < SEGS; ++k)
  1194. {
  1195. p2.x = p1.x + (diff.x * k) / SEGS;
  1196. p2.y = p1.y + (diff.y * k) / SEGS;
  1197. if (p2.z > 0)
  1198. _TPE_drawDebugPixel(p2.x,p2.y,camView.x,camView.y,0,drawFunc);
  1199. }
  1200. #undef SEGS
  1201. }
  1202. // joints:
  1203. for (uint16_t j = 0; j < world->bodies[i].jointCount; ++j)
  1204. {
  1205. TPE_Vec3 p = _TPE_project3DPoint(world->bodies[i].joints[j].position,
  1206. camPos,camRot,camView);
  1207. if (p.z > 0)
  1208. {
  1209. _TPE_drawDebugPixel(p.x,p.y,camView.x,camView.y,1,drawFunc);
  1210. TPE_Unit size = TPE_JOINT_SIZE(world->bodies[i].joints[j]) / 2;
  1211. size = (size * camView.x) / TPE_FRACTIONS_PER_UNIT;
  1212. size = (size * camView.z) / p.z;
  1213. #define SEGS 4
  1214. for (uint8_t k = 0; k < SEGS + 1; ++k)
  1215. {
  1216. TPE_Unit
  1217. dx = (TPE_sin(TPE_FRACTIONS_PER_UNIT * k / (8 * SEGS)) * size)
  1218. / TPE_FRACTIONS_PER_UNIT,
  1219. dy = (TPE_cos(TPE_FRACTIONS_PER_UNIT * k / (8 * SEGS)) * size)
  1220. / TPE_FRACTIONS_PER_UNIT;
  1221. #define dp(a,b,c,d) \
  1222. _TPE_drawDebugPixel(p.x a b,p.y c d,camView.x,camView.y,1,drawFunc);
  1223. dp(+,dx,+,dy) dp(+,dx,-,dy) dp(-,dx,+,dy) dp(-,dx,-,dy)
  1224. dp(+,dy,+,dx) dp(+,dy,-,dx) dp(-,dy,+,dx) dp(-,dy,-,dx)
  1225. #undef dp
  1226. #undef SEGS
  1227. }
  1228. }
  1229. }
  1230. }
  1231. }
  1232. TPE_Vec3 TPE_envBox(TPE_Vec3 point, TPE_Vec3 center, TPE_Vec3 maxCornerVec,
  1233. TPE_Vec3 rotation)
  1234. {
  1235. point = TPE_pointRotate(TPE_vec3Minus(point,center),
  1236. TPE_rotationInverse(rotation));
  1237. return TPE_vec3Plus(center,TPE_pointRotate(TPE_envAABox(point,TPE_vec3(0,0,0),
  1238. maxCornerVec),rotation));
  1239. }
  1240. TPE_Vec3 TPE_envAABox(TPE_Vec3 point, TPE_Vec3 center, TPE_Vec3 maxCornerVec)
  1241. {
  1242. TPE_Vec3 shifted = TPE_vec3Minus(point,center);
  1243. int8_t sign[3] = {1, 1, 1};
  1244. if (shifted.x < 0)
  1245. {
  1246. shifted.x *= -1;
  1247. sign[0] = -1;
  1248. }
  1249. if (shifted.y < 0)
  1250. {
  1251. shifted.y *= -1;
  1252. sign[1] = -1;
  1253. }
  1254. if (shifted.z < 0)
  1255. {
  1256. shifted.z *= -1;
  1257. sign[2] = -1;
  1258. }
  1259. uint8_t region =
  1260. (shifted.x > maxCornerVec.x) |
  1261. ((shifted.y > maxCornerVec.y) << 1) |
  1262. ((shifted.z > maxCornerVec.z) << 2);
  1263. switch (region)
  1264. {
  1265. #define align(c,i) point.c = center.c + sign[i] * maxCornerVec.c
  1266. case 0x01: align(x,0); break;
  1267. case 0x02: align(y,1); break;
  1268. case 0x04: align(z,2); break;
  1269. case 0x03: align(x,0); align(y,1); break;
  1270. case 0x05: align(x,0); align(z,2); break;
  1271. case 0x06: align(y,1); align(z,2); break;
  1272. case 0x07: align(x,0); align(y,1); align(z,2); break;
  1273. default: break;
  1274. #undef align
  1275. }
  1276. return point;
  1277. }
  1278. TPE_Vec3 TPE_envAABoxInside(TPE_Vec3 point, TPE_Vec3 center, TPE_Vec3 size)
  1279. {
  1280. size.x /= 2;
  1281. size.y /= 2;
  1282. size.z /= 2;
  1283. TPE_Vec3 shifted = TPE_vec3Minus(point,center);
  1284. TPE_Vec3 a = TPE_vec3Minus(size,shifted),
  1285. b = TPE_vec3Plus(shifted,size);
  1286. int8_t sx = 1, sy = 1, sz = 1;
  1287. if (b.x < a.x)
  1288. {
  1289. a.x = b.x;
  1290. sx = -1;
  1291. }
  1292. if (b.y < a.y)
  1293. {
  1294. a.y = b.y;
  1295. sy = -1;
  1296. }
  1297. if (b.z < a.z)
  1298. {
  1299. a.z = b.z;
  1300. sz = -1;
  1301. }
  1302. if (a.x < 0 || a.y < 0 || a.z < 0)
  1303. return point;
  1304. if (a.x < a.y)
  1305. {
  1306. if (a.x < a.z)
  1307. point.x = center.x + sx * size.x;
  1308. else
  1309. point.z = center.z + sz * size.z;
  1310. }
  1311. else
  1312. {
  1313. if (a.y < a.z)
  1314. point.y = center.y + sy * size.y;
  1315. else
  1316. point.z = center.z + sz * size.z;
  1317. }
  1318. return point;
  1319. }
  1320. TPE_Vec3 TPE_envSphere(TPE_Vec3 point, TPE_Vec3 center, TPE_Unit radius)
  1321. {
  1322. // TODO: optim?
  1323. TPE_Vec3 dir = TPE_vec3Minus(point,center);
  1324. TPE_Unit l = TPE_LENGTH(dir);
  1325. if (l <= radius)
  1326. return point;
  1327. dir.x = (dir.x * radius) / l;
  1328. dir.y = (dir.y * radius) / l;
  1329. dir.z = (dir.z * radius) / l;
  1330. return TPE_vec3Plus(center,dir);
  1331. }
  1332. TPE_Vec3 TPE_envHalfPlane(TPE_Vec3 point, TPE_Vec3 center, TPE_Vec3 normal)
  1333. {
  1334. TPE_Vec3 point2 = TPE_vec3Minus(point,center);
  1335. TPE_Unit tmp = point2.x * normal.x + point2.y * normal.y + point2.z * normal.z;
  1336. if (tmp < 0)
  1337. return point;
  1338. TPE_Unit l = TPE_LENGTH(normal);
  1339. tmp /= l;
  1340. normal.x = (normal.x * TPE_FRACTIONS_PER_UNIT) / l;
  1341. normal.y = (normal.y * TPE_FRACTIONS_PER_UNIT) / l;
  1342. normal.z = (normal.z * TPE_FRACTIONS_PER_UNIT) / l;
  1343. return TPE_vec3Minus(point,
  1344. TPE_vec3Times(normal,tmp));
  1345. }
  1346. uint8_t TPE_checkOverlapAABB(TPE_Vec3 v1Min, TPE_Vec3 v1Max, TPE_Vec3 v2Min,
  1347. TPE_Vec3 v2Max)
  1348. {
  1349. TPE_Unit dist;
  1350. #define test(c) \
  1351. dist = v1Min.c + v1Max.c - v2Max.c - v2Min.c; \
  1352. if (dist < 0) dist *= -1; \
  1353. if (dist > v1Max.c - v1Min.c + v2Max.c - v2Min.c) return 0;
  1354. test(x)
  1355. test(y)
  1356. test(z)
  1357. #undef test
  1358. return 1;
  1359. }
  1360. void TPE_bodyGetAABB(const TPE_Body *body, TPE_Vec3 *vMin, TPE_Vec3 *vMax)
  1361. {
  1362. *vMin = body->joints[0].position;
  1363. *vMax = *vMin;
  1364. TPE_Unit js = TPE_JOINT_SIZE(body->joints[0]);
  1365. vMin->x -= js;
  1366. vMin->y -= js;
  1367. vMin->z -= js;
  1368. vMax->x += js;
  1369. vMax->y += js;
  1370. vMax->z += js;
  1371. for (uint16_t i = 1; i < body->jointCount; ++i)
  1372. {
  1373. TPE_Unit v;
  1374. js = TPE_JOINT_SIZE(body->joints[i]);
  1375. #define test(c) \
  1376. v = body->joints[i].position.c - js; \
  1377. if (v < vMin->c) \
  1378. vMin->c = v; \
  1379. v += 2 * js; \
  1380. if (v > vMax->c) \
  1381. vMax->c = v;
  1382. test(x)
  1383. test(y)
  1384. test(z)
  1385. #undef test
  1386. }
  1387. }
  1388. void TPE_jointPin(TPE_Joint *joint, TPE_Vec3 position)
  1389. {
  1390. joint->position = position;
  1391. joint->velocity[0] = 0;
  1392. joint->velocity[1] = 0;
  1393. joint->velocity[2] = 0;
  1394. }
  1395. TPE_Vec3 TPE_pointRotate(TPE_Vec3 point, TPE_Vec3 rotation)
  1396. {
  1397. _TPE_vec2Rotate(&point.y,&point.x,rotation.z);
  1398. _TPE_vec2Rotate(&point.z,&point.y,rotation.x);
  1399. _TPE_vec2Rotate(&point.x,&point.z,rotation.y);
  1400. return point;
  1401. }
  1402. TPE_Vec3 TPE_rotationInverse(TPE_Vec3 rotation)
  1403. {
  1404. /* If r1 = (X,Y,Z) is rotation in convention ABC then r1^-1 = (-X,-Y,-Z) in
  1405. convention CBA is its inverse rotation. We exploit this, i.e. we rotate
  1406. forward/right vectors in opposite axis order and then turn the result
  1407. into normal rotation/orientation. */
  1408. TPE_Vec3 f = TPE_vec3(0,0,TPE_FRACTIONS_PER_UNIT);
  1409. TPE_Vec3 r = TPE_vec3(TPE_FRACTIONS_PER_UNIT,0,0);
  1410. rotation.x *= -1;
  1411. rotation.y *= -1;
  1412. rotation.z *= -1;
  1413. _TPE_vec2Rotate(&f.x,&f.z,rotation.y);
  1414. _TPE_vec2Rotate(&f.z,&f.y,rotation.x);
  1415. _TPE_vec2Rotate(&f.y,&f.x,rotation.z);
  1416. _TPE_vec2Rotate(&r.x,&r.z,rotation.y);
  1417. _TPE_vec2Rotate(&r.z,&r.y,rotation.x);
  1418. _TPE_vec2Rotate(&r.y,&r.x,rotation.z);
  1419. return TPE_orientationFromVecs(f,r);
  1420. }
  1421. #endif // guard