btKinematicCharacterController.cpp 31 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000
  1. /*
  2. Bullet Continuous Collision Detection and Physics Library
  3. Copyright (c) 2003-2008 Erwin Coumans http://bulletphysics.com
  4. This software is provided 'as-is', without any express or implied warranty.
  5. In no event will the authors be held liable for any damages arising from the use of this software.
  6. Permission is granted to anyone to use this software for any purpose,
  7. including commercial applications, and to alter it and redistribute it freely,
  8. subject to the following restrictions:
  9. 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
  10. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
  11. 3. This notice may not be removed or altered from any source distribution.
  12. */
  13. #include <stdio.h>
  14. #include "LinearMath/btIDebugDraw.h"
  15. #include "BulletCollision/CollisionDispatch/btGhostObject.h"
  16. #include "BulletCollision/CollisionShapes/btMultiSphereShape.h"
  17. #include "BulletCollision/BroadphaseCollision/btOverlappingPairCache.h"
  18. #include "BulletCollision/BroadphaseCollision/btCollisionAlgorithm.h"
  19. #include "BulletCollision/CollisionDispatch/btCollisionWorld.h"
  20. #include "LinearMath/btDefaultMotionState.h"
  21. #include "btKinematicCharacterController.h"
  22. // static helper method
  23. static btVector3
  24. getNormalizedVector(const btVector3& v)
  25. {
  26. btVector3 n(0, 0, 0);
  27. if (v.length() > SIMD_EPSILON) {
  28. n = v.normalized();
  29. }
  30. return n;
  31. }
  32. ///@todo Interact with dynamic objects,
  33. ///Ride kinematicly animated platforms properly
  34. ///More realistic (or maybe just a config option) falling
  35. /// -> Should integrate falling velocity manually and use that in stepDown()
  36. ///Support jumping
  37. ///Support ducking
  38. class btKinematicClosestNotMeRayResultCallback : public btCollisionWorld::ClosestRayResultCallback
  39. {
  40. public:
  41. btKinematicClosestNotMeRayResultCallback (btCollisionObject* me) : btCollisionWorld::ClosestRayResultCallback(btVector3(0.0, 0.0, 0.0), btVector3(0.0, 0.0, 0.0))
  42. {
  43. m_me = me;
  44. }
  45. virtual btScalar addSingleResult(btCollisionWorld::LocalRayResult& rayResult,bool normalInWorldSpace)
  46. {
  47. if (rayResult.m_collisionObject == m_me)
  48. return 1.0;
  49. return ClosestRayResultCallback::addSingleResult (rayResult, normalInWorldSpace);
  50. }
  51. protected:
  52. btCollisionObject* m_me;
  53. };
  54. class btKinematicClosestNotMeConvexResultCallback : public btCollisionWorld::ClosestConvexResultCallback
  55. {
  56. public:
  57. btKinematicClosestNotMeConvexResultCallback (btCollisionObject* me, const btVector3& up, btScalar minSlopeDot)
  58. : btCollisionWorld::ClosestConvexResultCallback(btVector3(0.0, 0.0, 0.0), btVector3(0.0, 0.0, 0.0))
  59. , m_me(me)
  60. , m_up(up)
  61. , m_minSlopeDot(minSlopeDot)
  62. {
  63. }
  64. virtual btScalar addSingleResult(btCollisionWorld::LocalConvexResult& convexResult,bool normalInWorldSpace)
  65. {
  66. if (convexResult.m_hitCollisionObject == m_me)
  67. return btScalar(1.0);
  68. if (!convexResult.m_hitCollisionObject->hasContactResponse())
  69. return btScalar(1.0);
  70. btVector3 hitNormalWorld;
  71. if (normalInWorldSpace)
  72. {
  73. hitNormalWorld = convexResult.m_hitNormalLocal;
  74. } else
  75. {
  76. ///need to transform normal into worldspace
  77. hitNormalWorld = convexResult.m_hitCollisionObject->getWorldTransform().getBasis()*convexResult.m_hitNormalLocal;
  78. }
  79. btScalar dotUp = m_up.dot(hitNormalWorld);
  80. if (dotUp < m_minSlopeDot) {
  81. return btScalar(1.0);
  82. }
  83. return ClosestConvexResultCallback::addSingleResult (convexResult, normalInWorldSpace);
  84. }
  85. protected:
  86. btCollisionObject* m_me;
  87. const btVector3 m_up;
  88. btScalar m_minSlopeDot;
  89. };
  90. /*
  91. * Returns the reflection direction of a ray going 'direction' hitting a surface with normal 'normal'
  92. *
  93. * from: http://www-cs-students.stanford.edu/~adityagp/final/node3.html
  94. */
  95. btVector3 btKinematicCharacterController::computeReflectionDirection (const btVector3& direction, const btVector3& normal)
  96. {
  97. return direction - (btScalar(2.0) * direction.dot(normal)) * normal;
  98. }
  99. /*
  100. * Returns the portion of 'direction' that is parallel to 'normal'
  101. */
  102. btVector3 btKinematicCharacterController::parallelComponent (const btVector3& direction, const btVector3& normal)
  103. {
  104. btScalar magnitude = direction.dot(normal);
  105. return normal * magnitude;
  106. }
  107. /*
  108. * Returns the portion of 'direction' that is perpindicular to 'normal'
  109. */
  110. btVector3 btKinematicCharacterController::perpindicularComponent (const btVector3& direction, const btVector3& normal)
  111. {
  112. return direction - parallelComponent(direction, normal);
  113. }
  114. btKinematicCharacterController::btKinematicCharacterController (btPairCachingGhostObject* ghostObject,btConvexShape* convexShape,btScalar stepHeight, const btVector3& up)
  115. {
  116. m_ghostObject = ghostObject;
  117. m_up.setValue(0.0f, 0.0f, 1.0f);
  118. m_jumpAxis.setValue(0.0f, 0.0f, 1.0f);
  119. m_addedMargin = 0.02;
  120. m_walkDirection.setValue(0.0,0.0,0.0);
  121. m_AngVel.setValue(0.0, 0.0, 0.0);
  122. m_useGhostObjectSweepTest = true;
  123. m_turnAngle = btScalar(0.0);
  124. m_convexShape=convexShape;
  125. m_useWalkDirection = true; // use walk direction by default, legacy behavior
  126. m_velocityTimeInterval = 0.0;
  127. m_verticalVelocity = 0.0;
  128. m_verticalOffset = 0.0;
  129. m_gravity = 9.8 * 3.0 ; // 3G acceleration.
  130. m_fallSpeed = 55.0; // Terminal velocity of a sky diver in m/s.
  131. m_jumpSpeed = 10.0; // ?
  132. m_SetjumpSpeed = m_jumpSpeed;
  133. m_wasOnGround = false;
  134. m_wasJumping = false;
  135. m_interpolateUp = true;
  136. m_currentStepOffset = 0.0;
  137. m_maxPenetrationDepth = 0.2;
  138. full_drop = false;
  139. bounce_fix = false;
  140. m_linearDamping = btScalar(0.0);
  141. m_angularDamping = btScalar(0.0);
  142. setUp(up);
  143. setStepHeight(stepHeight);
  144. setMaxSlope(btRadians(45.0));
  145. }
  146. btKinematicCharacterController::~btKinematicCharacterController ()
  147. {
  148. }
  149. btPairCachingGhostObject* btKinematicCharacterController::getGhostObject()
  150. {
  151. return m_ghostObject;
  152. }
  153. bool btKinematicCharacterController::recoverFromPenetration ( btCollisionWorld* collisionWorld)
  154. {
  155. // Here we must refresh the overlapping paircache as the penetrating movement itself or the
  156. // previous recovery iteration might have used setWorldTransform and pushed us into an object
  157. // that is not in the previous cache contents from the last timestep, as will happen if we
  158. // are pushed into a new AABB overlap. Unhandled this means the next convex sweep gets stuck.
  159. //
  160. // Do this by calling the broadphase's setAabb with the moved AABB, this will update the broadphase
  161. // paircache and the ghostobject's internal paircache at the same time. /BW
  162. btVector3 minAabb, maxAabb;
  163. m_convexShape->getAabb(m_ghostObject->getWorldTransform(), minAabb,maxAabb);
  164. collisionWorld->getBroadphase()->setAabb(m_ghostObject->getBroadphaseHandle(),
  165. minAabb,
  166. maxAabb,
  167. collisionWorld->getDispatcher());
  168. bool penetration = false;
  169. collisionWorld->getDispatcher()->dispatchAllCollisionPairs(m_ghostObject->getOverlappingPairCache(), collisionWorld->getDispatchInfo(), collisionWorld->getDispatcher());
  170. m_currentPosition = m_ghostObject->getWorldTransform().getOrigin();
  171. // btScalar maxPen = btScalar(0.0);
  172. for (int i = 0; i < m_ghostObject->getOverlappingPairCache()->getNumOverlappingPairs(); i++)
  173. {
  174. m_manifoldArray.resize(0);
  175. btBroadphasePair* collisionPair = &m_ghostObject->getOverlappingPairCache()->getOverlappingPairArray()[i];
  176. btCollisionObject* obj0 = static_cast<btCollisionObject*>(collisionPair->m_pProxy0->m_clientObject);
  177. btCollisionObject* obj1 = static_cast<btCollisionObject*>(collisionPair->m_pProxy1->m_clientObject);
  178. if ((obj0 && !obj0->hasContactResponse()) || (obj1 && !obj1->hasContactResponse()))
  179. continue;
  180. if (!needsCollision(obj0, obj1))
  181. continue;
  182. if (collisionPair->m_algorithm)
  183. collisionPair->m_algorithm->getAllContactManifolds(m_manifoldArray);
  184. for (int j=0;j<m_manifoldArray.size();j++)
  185. {
  186. btPersistentManifold* manifold = m_manifoldArray[j];
  187. btScalar directionSign = manifold->getBody0() == m_ghostObject ? btScalar(-1.0) : btScalar(1.0);
  188. for (int p=0;p<manifold->getNumContacts();p++)
  189. {
  190. const btManifoldPoint&pt = manifold->getContactPoint(p);
  191. btScalar dist = pt.getDistance();
  192. if (dist < -m_maxPenetrationDepth)
  193. {
  194. // TODO: cause problems on slopes, not sure if it is needed
  195. //if (dist < maxPen)
  196. //{
  197. // maxPen = dist;
  198. // m_touchingNormal = pt.m_normalWorldOnB * directionSign;//??
  199. //}
  200. m_currentPosition += pt.m_normalWorldOnB * directionSign * dist * btScalar(0.2);
  201. penetration = true;
  202. } else {
  203. //printf("touching %f\n", dist);
  204. }
  205. }
  206. //manifold->clearManifold();
  207. }
  208. }
  209. btTransform newTrans = m_ghostObject->getWorldTransform();
  210. newTrans.setOrigin(m_currentPosition);
  211. m_ghostObject->setWorldTransform(newTrans);
  212. // printf("m_touchingNormal = %f,%f,%f\n",m_touchingNormal[0],m_touchingNormal[1],m_touchingNormal[2]);
  213. return penetration;
  214. }
  215. void btKinematicCharacterController::stepUp ( btCollisionWorld* world)
  216. {
  217. btScalar stepHeight = 0.0f;
  218. if (m_verticalVelocity < 0.0)
  219. stepHeight = m_stepHeight;
  220. // phase 1: up
  221. btTransform start, end;
  222. start.setIdentity ();
  223. end.setIdentity ();
  224. /* FIXME: Handle penetration properly */
  225. start.setOrigin(m_currentPosition);
  226. m_targetPosition = m_currentPosition + m_up * (stepHeight) + m_jumpAxis * ((m_verticalOffset > 0.f ? m_verticalOffset : 0.f));
  227. m_currentPosition = m_targetPosition;
  228. end.setOrigin (m_targetPosition);
  229. start.setRotation(m_currentOrientation);
  230. end.setRotation(m_targetOrientation);
  231. btKinematicClosestNotMeConvexResultCallback callback(m_ghostObject, -m_up, m_maxSlopeCosine);
  232. callback.m_collisionFilterGroup = getGhostObject()->getBroadphaseHandle()->m_collisionFilterGroup;
  233. callback.m_collisionFilterMask = getGhostObject()->getBroadphaseHandle()->m_collisionFilterMask;
  234. if (m_useGhostObjectSweepTest)
  235. {
  236. m_ghostObject->convexSweepTest (m_convexShape, start, end, callback, world->getDispatchInfo().m_allowedCcdPenetration);
  237. }
  238. else
  239. {
  240. world->convexSweepTest(m_convexShape, start, end, callback, world->getDispatchInfo().m_allowedCcdPenetration);
  241. }
  242. if (callback.hasHit() && m_ghostObject->hasContactResponse() && needsCollision(m_ghostObject, callback.m_hitCollisionObject))
  243. {
  244. // Only modify the position if the hit was a slope and not a wall or ceiling.
  245. if (callback.m_hitNormalWorld.dot(m_up) > 0.0)
  246. {
  247. // we moved up only a fraction of the step height
  248. m_currentStepOffset = stepHeight * callback.m_closestHitFraction;
  249. if (m_interpolateUp == true)
  250. m_currentPosition.setInterpolate3 (m_currentPosition, m_targetPosition, callback.m_closestHitFraction);
  251. else
  252. m_currentPosition = m_targetPosition;
  253. }
  254. btTransform& xform = m_ghostObject->getWorldTransform();
  255. xform.setOrigin(m_currentPosition);
  256. m_ghostObject->setWorldTransform(xform);
  257. // fix penetration if we hit a ceiling for example
  258. int numPenetrationLoops = 0;
  259. m_touchingContact = false;
  260. while (recoverFromPenetration(world))
  261. {
  262. numPenetrationLoops++;
  263. m_touchingContact = true;
  264. if (numPenetrationLoops > 4)
  265. {
  266. //printf("character could not recover from penetration = %d\n", numPenetrationLoops);
  267. break;
  268. }
  269. }
  270. m_targetPosition = m_ghostObject->getWorldTransform().getOrigin();
  271. m_currentPosition = m_targetPosition;
  272. if (m_verticalOffset > 0)
  273. {
  274. m_verticalOffset = 0.0;
  275. m_verticalVelocity = 0.0;
  276. m_currentStepOffset = m_stepHeight;
  277. }
  278. } else {
  279. m_currentStepOffset = stepHeight;
  280. m_currentPosition = m_targetPosition;
  281. }
  282. }
  283. bool btKinematicCharacterController::needsCollision(const btCollisionObject* body0, const btCollisionObject* body1)
  284. {
  285. bool collides = (body0->getBroadphaseHandle()->m_collisionFilterGroup & body1->getBroadphaseHandle()->m_collisionFilterMask) != 0;
  286. collides = collides && (body1->getBroadphaseHandle()->m_collisionFilterGroup & body0->getBroadphaseHandle()->m_collisionFilterMask);
  287. return collides;
  288. }
  289. void btKinematicCharacterController::updateTargetPositionBasedOnCollision (const btVector3& hitNormal, btScalar tangentMag, btScalar normalMag)
  290. {
  291. btVector3 movementDirection = m_targetPosition - m_currentPosition;
  292. btScalar movementLength = movementDirection.length();
  293. if (movementLength>SIMD_EPSILON)
  294. {
  295. movementDirection.normalize();
  296. btVector3 reflectDir = computeReflectionDirection (movementDirection, hitNormal);
  297. reflectDir.normalize();
  298. btVector3 parallelDir, perpindicularDir;
  299. parallelDir = parallelComponent (reflectDir, hitNormal);
  300. perpindicularDir = perpindicularComponent (reflectDir, hitNormal);
  301. m_targetPosition = m_currentPosition;
  302. if (0)//tangentMag != 0.0)
  303. {
  304. btVector3 parComponent = parallelDir * btScalar (tangentMag*movementLength);
  305. // printf("parComponent=%f,%f,%f\n",parComponent[0],parComponent[1],parComponent[2]);
  306. m_targetPosition += parComponent;
  307. }
  308. if (normalMag != 0.0)
  309. {
  310. btVector3 perpComponent = perpindicularDir * btScalar (normalMag*movementLength);
  311. // printf("perpComponent=%f,%f,%f\n",perpComponent[0],perpComponent[1],perpComponent[2]);
  312. m_targetPosition += perpComponent;
  313. }
  314. } else
  315. {
  316. // printf("movementLength don't normalize a zero vector\n");
  317. }
  318. }
  319. void btKinematicCharacterController::stepForwardAndStrafe ( btCollisionWorld* collisionWorld, const btVector3& walkMove)
  320. {
  321. // printf("m_normalizedDirection=%f,%f,%f\n",
  322. // m_normalizedDirection[0],m_normalizedDirection[1],m_normalizedDirection[2]);
  323. // phase 2: forward and strafe
  324. btTransform start, end;
  325. m_targetPosition = m_currentPosition + walkMove;
  326. start.setIdentity ();
  327. end.setIdentity ();
  328. btScalar fraction = 1.0;
  329. btScalar distance2 = (m_currentPosition-m_targetPosition).length2();
  330. // printf("distance2=%f\n",distance2);
  331. int maxIter = 10;
  332. while (fraction > btScalar(0.01) && maxIter-- > 0)
  333. {
  334. start.setOrigin (m_currentPosition);
  335. end.setOrigin (m_targetPosition);
  336. btVector3 sweepDirNegative(m_currentPosition - m_targetPosition);
  337. start.setRotation(m_currentOrientation);
  338. end.setRotation(m_targetOrientation);
  339. btKinematicClosestNotMeConvexResultCallback callback (m_ghostObject, sweepDirNegative, btScalar(0.0));
  340. callback.m_collisionFilterGroup = getGhostObject()->getBroadphaseHandle()->m_collisionFilterGroup;
  341. callback.m_collisionFilterMask = getGhostObject()->getBroadphaseHandle()->m_collisionFilterMask;
  342. btScalar margin = m_convexShape->getMargin();
  343. m_convexShape->setMargin(margin + m_addedMargin);
  344. if (!(start == end))
  345. {
  346. if (m_useGhostObjectSweepTest)
  347. {
  348. m_ghostObject->convexSweepTest(m_convexShape, start, end, callback, collisionWorld->getDispatchInfo().m_allowedCcdPenetration);
  349. }
  350. else
  351. {
  352. collisionWorld->convexSweepTest(m_convexShape, start, end, callback, collisionWorld->getDispatchInfo().m_allowedCcdPenetration);
  353. }
  354. }
  355. m_convexShape->setMargin(margin);
  356. fraction -= callback.m_closestHitFraction;
  357. if (callback.hasHit() && m_ghostObject->hasContactResponse() && needsCollision(m_ghostObject, callback.m_hitCollisionObject))
  358. {
  359. // we moved only a fraction
  360. //btScalar hitDistance;
  361. //hitDistance = (callback.m_hitPointWorld - m_currentPosition).length();
  362. // m_currentPosition.setInterpolate3 (m_currentPosition, m_targetPosition, callback.m_closestHitFraction);
  363. updateTargetPositionBasedOnCollision (callback.m_hitNormalWorld);
  364. btVector3 currentDir = m_targetPosition - m_currentPosition;
  365. distance2 = currentDir.length2();
  366. if (distance2 > SIMD_EPSILON)
  367. {
  368. currentDir.normalize();
  369. /* See Quake2: "If velocity is against original velocity, stop ead to avoid tiny oscilations in sloping corners." */
  370. if (currentDir.dot(m_normalizedDirection) <= btScalar(0.0))
  371. {
  372. break;
  373. }
  374. } else
  375. {
  376. // printf("currentDir: don't normalize a zero vector\n");
  377. break;
  378. }
  379. }
  380. else
  381. {
  382. m_currentPosition = m_targetPosition;
  383. }
  384. }
  385. }
  386. void btKinematicCharacterController::stepDown ( btCollisionWorld* collisionWorld, btScalar dt)
  387. {
  388. btTransform start, end, end_double;
  389. bool runonce = false;
  390. // phase 3: down
  391. /*btScalar additionalDownStep = (m_wasOnGround && !onGround()) ? m_stepHeight : 0.0;
  392. btVector3 step_drop = m_up * (m_currentStepOffset + additionalDownStep);
  393. btScalar downVelocity = (additionalDownStep == 0.0 && m_verticalVelocity<0.0?-m_verticalVelocity:0.0) * dt;
  394. btVector3 gravity_drop = m_up * downVelocity;
  395. m_targetPosition -= (step_drop + gravity_drop);*/
  396. btVector3 orig_position = m_targetPosition;
  397. btScalar downVelocity = (m_verticalVelocity<0.f?-m_verticalVelocity:0.f) * dt;
  398. if (m_verticalVelocity > 0.0)
  399. return;
  400. if(downVelocity > 0.0 && downVelocity > m_fallSpeed
  401. && (m_wasOnGround || !m_wasJumping))
  402. downVelocity = m_fallSpeed;
  403. btVector3 step_drop = m_up * (m_currentStepOffset + downVelocity);
  404. m_targetPosition -= step_drop;
  405. btKinematicClosestNotMeConvexResultCallback callback(m_ghostObject, m_up, m_maxSlopeCosine);
  406. callback.m_collisionFilterGroup = getGhostObject()->getBroadphaseHandle()->m_collisionFilterGroup;
  407. callback.m_collisionFilterMask = getGhostObject()->getBroadphaseHandle()->m_collisionFilterMask;
  408. btKinematicClosestNotMeConvexResultCallback callback2(m_ghostObject, m_up, m_maxSlopeCosine);
  409. callback2.m_collisionFilterGroup = getGhostObject()->getBroadphaseHandle()->m_collisionFilterGroup;
  410. callback2.m_collisionFilterMask = getGhostObject()->getBroadphaseHandle()->m_collisionFilterMask;
  411. while (1)
  412. {
  413. start.setIdentity ();
  414. end.setIdentity ();
  415. end_double.setIdentity ();
  416. start.setOrigin (m_currentPosition);
  417. end.setOrigin (m_targetPosition);
  418. start.setRotation(m_currentOrientation);
  419. end.setRotation(m_targetOrientation);
  420. //set double test for 2x the step drop, to check for a large drop vs small drop
  421. end_double.setOrigin (m_targetPosition - step_drop);
  422. if (m_useGhostObjectSweepTest)
  423. {
  424. m_ghostObject->convexSweepTest (m_convexShape, start, end, callback, collisionWorld->getDispatchInfo().m_allowedCcdPenetration);
  425. if (!callback.hasHit() && m_ghostObject->hasContactResponse())
  426. {
  427. //test a double fall height, to see if the character should interpolate it's fall (full) or not (partial)
  428. m_ghostObject->convexSweepTest (m_convexShape, start, end_double, callback2, collisionWorld->getDispatchInfo().m_allowedCcdPenetration);
  429. }
  430. } else
  431. {
  432. collisionWorld->convexSweepTest (m_convexShape, start, end, callback, collisionWorld->getDispatchInfo().m_allowedCcdPenetration);
  433. if (!callback.hasHit() && m_ghostObject->hasContactResponse())
  434. {
  435. //test a double fall height, to see if the character should interpolate it's fall (large) or not (small)
  436. collisionWorld->convexSweepTest (m_convexShape, start, end_double, callback2, collisionWorld->getDispatchInfo().m_allowedCcdPenetration);
  437. }
  438. }
  439. btScalar downVelocity2 = (m_verticalVelocity<0.f?-m_verticalVelocity:0.f) * dt;
  440. bool has_hit;
  441. if (bounce_fix == true)
  442. has_hit = (callback.hasHit() || callback2.hasHit()) && m_ghostObject->hasContactResponse() && needsCollision(m_ghostObject, callback.m_hitCollisionObject);
  443. else
  444. has_hit = callback2.hasHit() && m_ghostObject->hasContactResponse() && needsCollision(m_ghostObject, callback2.m_hitCollisionObject);
  445. btScalar stepHeight = 0.0f;
  446. if (m_verticalVelocity < 0.0)
  447. stepHeight = m_stepHeight;
  448. if (downVelocity2 > 0.0 && downVelocity2 < stepHeight && has_hit == true && runonce == false
  449. && (m_wasOnGround || !m_wasJumping))
  450. {
  451. //redo the velocity calculation when falling a small amount, for fast stairs motion
  452. //for larger falls, use the smoother/slower interpolated movement by not touching the target position
  453. m_targetPosition = orig_position;
  454. downVelocity = stepHeight;
  455. step_drop = m_up * (m_currentStepOffset + downVelocity);
  456. m_targetPosition -= step_drop;
  457. runonce = true;
  458. continue; //re-run previous tests
  459. }
  460. break;
  461. }
  462. if ((m_ghostObject->hasContactResponse() && (callback.hasHit() && needsCollision(m_ghostObject, callback.m_hitCollisionObject))) || runonce == true)
  463. {
  464. // we dropped a fraction of the height -> hit floor
  465. btScalar fraction = (m_currentPosition.getY() - callback.m_hitPointWorld.getY()) / 2;
  466. //printf("hitpoint: %g - pos %g\n", callback.m_hitPointWorld.getY(), m_currentPosition.getY());
  467. if (bounce_fix == true)
  468. {
  469. if (full_drop == true)
  470. m_currentPosition.setInterpolate3 (m_currentPosition, m_targetPosition, callback.m_closestHitFraction);
  471. else
  472. //due to errors in the closestHitFraction variable when used with large polygons, calculate the hit fraction manually
  473. m_currentPosition.setInterpolate3 (m_currentPosition, m_targetPosition, fraction);
  474. }
  475. else
  476. m_currentPosition.setInterpolate3 (m_currentPosition, m_targetPosition, callback.m_closestHitFraction);
  477. full_drop = false;
  478. m_verticalVelocity = 0.0;
  479. m_verticalOffset = 0.0;
  480. m_wasJumping = false;
  481. } else {
  482. // we dropped the full height
  483. full_drop = true;
  484. if (bounce_fix == true)
  485. {
  486. downVelocity = (m_verticalVelocity<0.f?-m_verticalVelocity:0.f) * dt;
  487. if (downVelocity > m_fallSpeed && (m_wasOnGround || !m_wasJumping))
  488. {
  489. m_targetPosition += step_drop; //undo previous target change
  490. downVelocity = m_fallSpeed;
  491. step_drop = m_up * (m_currentStepOffset + downVelocity);
  492. m_targetPosition -= step_drop;
  493. }
  494. }
  495. //printf("full drop - %g, %g\n", m_currentPosition.getY(), m_targetPosition.getY());
  496. m_currentPosition = m_targetPosition;
  497. }
  498. }
  499. void btKinematicCharacterController::setWalkDirection
  500. (
  501. const btVector3& walkDirection
  502. )
  503. {
  504. m_useWalkDirection = true;
  505. m_walkDirection = walkDirection;
  506. m_normalizedDirection = getNormalizedVector(m_walkDirection);
  507. }
  508. void btKinematicCharacterController::setVelocityForTimeInterval
  509. (
  510. const btVector3& velocity,
  511. btScalar timeInterval
  512. )
  513. {
  514. // printf("setVelocity!\n");
  515. // printf(" interval: %f\n", timeInterval);
  516. // printf(" velocity: (%f, %f, %f)\n",
  517. // velocity.x(), velocity.y(), velocity.z());
  518. m_useWalkDirection = false;
  519. m_walkDirection = velocity;
  520. m_normalizedDirection = getNormalizedVector(m_walkDirection);
  521. m_velocityTimeInterval += timeInterval;
  522. }
  523. void btKinematicCharacterController::setAngularVelocity(const btVector3& velocity)
  524. {
  525. m_AngVel = velocity;
  526. }
  527. const btVector3& btKinematicCharacterController::getAngularVelocity() const
  528. {
  529. return m_AngVel;
  530. }
  531. void btKinematicCharacterController::setLinearVelocity(const btVector3& velocity)
  532. {
  533. m_walkDirection = velocity;
  534. // HACK: if we are moving in the direction of the up, treat it as a jump :(
  535. if (m_walkDirection.length2() > 0)
  536. {
  537. btVector3 w = velocity.normalized();
  538. btScalar c = w.dot(m_up);
  539. if (c != 0)
  540. {
  541. //there is a component in walkdirection for vertical velocity
  542. btVector3 upComponent = m_up * (btSin(SIMD_HALF_PI - btAcos(c)) * m_walkDirection.length());
  543. m_walkDirection -= upComponent;
  544. m_verticalVelocity = (c < 0.0f ? -1 : 1) * upComponent.length();
  545. if (c > 0.0f)
  546. {
  547. m_wasJumping = true;
  548. m_jumpPosition = m_ghostObject->getWorldTransform().getOrigin();
  549. }
  550. }
  551. }
  552. else
  553. m_verticalVelocity = 0.0f;
  554. }
  555. btVector3 btKinematicCharacterController::getLinearVelocity() const
  556. {
  557. return m_walkDirection + (m_verticalVelocity * m_up);
  558. }
  559. void btKinematicCharacterController::reset ( btCollisionWorld* collisionWorld )
  560. {
  561. m_verticalVelocity = 0.0;
  562. m_verticalOffset = 0.0;
  563. m_wasOnGround = false;
  564. m_wasJumping = false;
  565. m_walkDirection.setValue(0,0,0);
  566. m_velocityTimeInterval = 0.0;
  567. //clear pair cache
  568. btHashedOverlappingPairCache *cache = m_ghostObject->getOverlappingPairCache();
  569. while (cache->getOverlappingPairArray().size() > 0)
  570. {
  571. cache->removeOverlappingPair(cache->getOverlappingPairArray()[0].m_pProxy0, cache->getOverlappingPairArray()[0].m_pProxy1, collisionWorld->getDispatcher());
  572. }
  573. }
  574. void btKinematicCharacterController::warp (const btVector3& origin)
  575. {
  576. btTransform xform;
  577. xform.setIdentity();
  578. xform.setOrigin (origin);
  579. m_ghostObject->setWorldTransform (xform);
  580. }
  581. void btKinematicCharacterController::preStep ( btCollisionWorld* collisionWorld)
  582. {
  583. m_currentPosition = m_ghostObject->getWorldTransform().getOrigin();
  584. m_targetPosition = m_currentPosition;
  585. m_currentOrientation = m_ghostObject->getWorldTransform().getRotation();
  586. m_targetOrientation = m_currentOrientation;
  587. // printf("m_targetPosition=%f,%f,%f\n",m_targetPosition[0],m_targetPosition[1],m_targetPosition[2]);
  588. }
  589. void btKinematicCharacterController::playerStep ( btCollisionWorld* collisionWorld, btScalar dt)
  590. {
  591. // printf("playerStep(): ");
  592. // printf(" dt = %f", dt);
  593. if (m_AngVel.length2() > 0.0f)
  594. {
  595. m_AngVel *= btPow(btScalar(1) - m_angularDamping, dt);
  596. }
  597. // integrate for angular velocity
  598. if (m_AngVel.length2() > 0.0f)
  599. {
  600. btTransform xform;
  601. xform = m_ghostObject->getWorldTransform();
  602. btQuaternion rot(m_AngVel.normalized(), m_AngVel.length() * dt);
  603. btQuaternion orn = rot * xform.getRotation();
  604. xform.setRotation(orn);
  605. m_ghostObject->setWorldTransform(xform);
  606. m_currentPosition = m_ghostObject->getWorldTransform().getOrigin();
  607. m_targetPosition = m_currentPosition;
  608. m_currentOrientation = m_ghostObject->getWorldTransform().getRotation();
  609. m_targetOrientation = m_currentOrientation;
  610. }
  611. // quick check...
  612. if (!m_useWalkDirection && (m_velocityTimeInterval <= 0.0)) {
  613. // printf("\n");
  614. return; // no motion
  615. }
  616. m_wasOnGround = onGround();
  617. //btVector3 lvel = m_walkDirection;
  618. //btScalar c = 0.0f;
  619. if (m_walkDirection.length2() > 0)
  620. {
  621. // apply damping
  622. m_walkDirection *= btPow(btScalar(1) - m_linearDamping, dt);
  623. }
  624. m_verticalVelocity *= btPow(btScalar(1) - m_linearDamping, dt);
  625. // Update fall velocity.
  626. m_verticalVelocity -= m_gravity * dt;
  627. if (m_verticalVelocity > 0.0 && m_verticalVelocity > m_jumpSpeed)
  628. {
  629. m_verticalVelocity = m_jumpSpeed;
  630. }
  631. if (m_verticalVelocity < 0.0 && btFabs(m_verticalVelocity) > btFabs(m_fallSpeed))
  632. {
  633. m_verticalVelocity = -btFabs(m_fallSpeed);
  634. }
  635. m_verticalOffset = m_verticalVelocity * dt;
  636. btTransform xform;
  637. xform = m_ghostObject->getWorldTransform();
  638. // printf("walkDirection(%f,%f,%f)\n",walkDirection[0],walkDirection[1],walkDirection[2]);
  639. // printf("walkSpeed=%f\n",walkSpeed);
  640. stepUp(collisionWorld);
  641. //todo: Experimenting with behavior of controller when it hits a ceiling..
  642. //bool hitUp = stepUp (collisionWorld);
  643. //if (hitUp)
  644. //{
  645. // m_verticalVelocity -= m_gravity * dt;
  646. // if (m_verticalVelocity > 0.0 && m_verticalVelocity > m_jumpSpeed)
  647. // {
  648. // m_verticalVelocity = m_jumpSpeed;
  649. // }
  650. // if (m_verticalVelocity < 0.0 && btFabs(m_verticalVelocity) > btFabs(m_fallSpeed))
  651. // {
  652. // m_verticalVelocity = -btFabs(m_fallSpeed);
  653. // }
  654. // m_verticalOffset = m_verticalVelocity * dt;
  655. // xform = m_ghostObject->getWorldTransform();
  656. //}
  657. if (m_useWalkDirection) {
  658. stepForwardAndStrafe (collisionWorld, m_walkDirection);
  659. } else {
  660. //printf(" time: %f", m_velocityTimeInterval);
  661. // still have some time left for moving!
  662. btScalar dtMoving =
  663. (dt < m_velocityTimeInterval) ? dt : m_velocityTimeInterval;
  664. m_velocityTimeInterval -= dt;
  665. // how far will we move while we are moving?
  666. btVector3 move = m_walkDirection * dtMoving;
  667. //printf(" dtMoving: %f", dtMoving);
  668. // okay, step
  669. stepForwardAndStrafe(collisionWorld, move);
  670. }
  671. stepDown (collisionWorld, dt);
  672. //todo: Experimenting with max jump height
  673. //if (m_wasJumping)
  674. //{
  675. // btScalar ds = m_currentPosition[m_upAxis] - m_jumpPosition[m_upAxis];
  676. // if (ds > m_maxJumpHeight)
  677. // {
  678. // // substract the overshoot
  679. // m_currentPosition[m_upAxis] -= ds - m_maxJumpHeight;
  680. // // max height was reached, so potential energy is at max
  681. // // and kinematic energy is 0, thus velocity is 0.
  682. // if (m_verticalVelocity > 0.0)
  683. // m_verticalVelocity = 0.0;
  684. // }
  685. //}
  686. // printf("\n");
  687. xform.setOrigin (m_currentPosition);
  688. m_ghostObject->setWorldTransform (xform);
  689. int numPenetrationLoops = 0;
  690. m_touchingContact = false;
  691. while (recoverFromPenetration(collisionWorld))
  692. {
  693. numPenetrationLoops++;
  694. m_touchingContact = true;
  695. if (numPenetrationLoops > 4)
  696. {
  697. //printf("character could not recover from penetration = %d\n", numPenetrationLoops);
  698. break;
  699. }
  700. }
  701. }
  702. void btKinematicCharacterController::setFallSpeed (btScalar fallSpeed)
  703. {
  704. m_fallSpeed = fallSpeed;
  705. }
  706. void btKinematicCharacterController::setJumpSpeed (btScalar jumpSpeed)
  707. {
  708. m_jumpSpeed = jumpSpeed;
  709. m_SetjumpSpeed = m_jumpSpeed;
  710. }
  711. void btKinematicCharacterController::setMaxJumpHeight (btScalar maxJumpHeight)
  712. {
  713. m_maxJumpHeight = maxJumpHeight;
  714. }
  715. bool btKinematicCharacterController::canJump () const
  716. {
  717. return onGround();
  718. }
  719. void btKinematicCharacterController::jump(const btVector3& v)
  720. {
  721. m_jumpSpeed = v.length2() == 0 ? m_SetjumpSpeed : v.length();
  722. m_verticalVelocity = m_jumpSpeed;
  723. m_wasJumping = true;
  724. m_jumpAxis = v.length2() == 0 ? m_up : v.normalized();
  725. m_jumpPosition = m_ghostObject->getWorldTransform().getOrigin();
  726. #if 0
  727. currently no jumping.
  728. btTransform xform;
  729. m_rigidBody->getMotionState()->getWorldTransform (xform);
  730. btVector3 up = xform.getBasis()[1];
  731. up.normalize ();
  732. btScalar magnitude = (btScalar(1.0)/m_rigidBody->getInvMass()) * btScalar(8.0);
  733. m_rigidBody->applyCentralImpulse (up * magnitude);
  734. #endif
  735. }
  736. void btKinematicCharacterController::setGravity(const btVector3& gravity)
  737. {
  738. if (gravity.length2() > 0) setUpVector(-gravity);
  739. m_gravity = gravity.length();
  740. }
  741. btVector3 btKinematicCharacterController::getGravity() const
  742. {
  743. return -m_gravity * m_up;
  744. }
  745. void btKinematicCharacterController::setMaxSlope(btScalar slopeRadians)
  746. {
  747. m_maxSlopeRadians = slopeRadians;
  748. m_maxSlopeCosine = btCos(slopeRadians);
  749. }
  750. btScalar btKinematicCharacterController::getMaxSlope() const
  751. {
  752. return m_maxSlopeRadians;
  753. }
  754. void btKinematicCharacterController::setMaxPenetrationDepth(btScalar d)
  755. {
  756. m_maxPenetrationDepth = d;
  757. }
  758. btScalar btKinematicCharacterController::getMaxPenetrationDepth() const
  759. {
  760. return m_maxPenetrationDepth;
  761. }
  762. bool btKinematicCharacterController::onGround () const
  763. {
  764. return (fabs(m_verticalVelocity) < SIMD_EPSILON) && (fabs(m_verticalOffset) < SIMD_EPSILON);
  765. }
  766. void btKinematicCharacterController::setStepHeight(btScalar h)
  767. {
  768. m_stepHeight = h;
  769. }
  770. btVector3* btKinematicCharacterController::getUpAxisDirections()
  771. {
  772. static btVector3 sUpAxisDirection[3] = { btVector3(1.0f, 0.0f, 0.0f), btVector3(0.0f, 1.0f, 0.0f), btVector3(0.0f, 0.0f, 1.0f) };
  773. return sUpAxisDirection;
  774. }
  775. void btKinematicCharacterController::debugDraw(btIDebugDraw* debugDrawer)
  776. {
  777. }
  778. void btKinematicCharacterController::setUpInterpolate(bool value)
  779. {
  780. m_interpolateUp = value;
  781. }
  782. void btKinematicCharacterController::setUp(const btVector3& up)
  783. {
  784. if (up.length2() > 0 && m_gravity > 0.0f)
  785. {
  786. setGravity(-m_gravity * up.normalized());
  787. return;
  788. }
  789. setUpVector(up);
  790. }
  791. void btKinematicCharacterController::setUpVector(const btVector3& up)
  792. {
  793. if (m_up == up)
  794. return;
  795. btVector3 u = m_up;
  796. if (up.length2() > 0)
  797. m_up = up.normalized();
  798. else
  799. m_up = btVector3(0.0, 0.0, 0.0);
  800. if (!m_ghostObject) return;
  801. btQuaternion rot = getRotation(m_up, u);
  802. //set orientation with new up
  803. btTransform xform;
  804. xform = m_ghostObject->getWorldTransform();
  805. btQuaternion orn = rot.inverse() * xform.getRotation();
  806. xform.setRotation(orn);
  807. m_ghostObject->setWorldTransform(xform);
  808. }
  809. btQuaternion btKinematicCharacterController::getRotation(btVector3& v0, btVector3& v1) const
  810. {
  811. if (v0.length2() == 0.0f || v1.length2() == 0.0f)
  812. {
  813. btQuaternion q;
  814. return q;
  815. }
  816. return shortestArcQuatNormalize2(v0, v1);
  817. }