btWorld.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381
  1. //-----------------------------------------------------------------------------
  2. // Copyright (c) 2012 GarageGames, LLC
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to
  6. // deal in the Software without restriction, including without limitation the
  7. // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
  8. // sell copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  19. // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
  20. // IN THE SOFTWARE.
  21. //-----------------------------------------------------------------------------
  22. #include "platform/platform.h"
  23. #include "T3D/physics/bullet/btWorld.h"
  24. #include "T3D/physics/bullet/btPlugin.h"
  25. #include "T3D/physics/bullet/btCasts.h"
  26. #include "T3D/physics/physicsUserData.h"
  27. #include "core/stream/bitStream.h"
  28. #include "platform/profiler.h"
  29. #include "sim/netConnection.h"
  30. #include "console/console.h"
  31. #include "console/consoleTypes.h"
  32. #include "scene/sceneRenderState.h"
  33. #include "T3D/gameBase/gameProcess.h"
  34. #ifdef _WIN32
  35. #include "BulletMultiThreaded/Win32ThreadSupport.h"
  36. #elif defined (USE_PTHREADS)
  37. #include "BulletMultiThreaded/PosixThreadSupport.h"
  38. #endif
  39. BtWorld::BtWorld() :
  40. mProcessList( NULL ),
  41. mIsSimulating( false ),
  42. mErrorReport( false ),
  43. mTickCount( 0 ),
  44. mIsEnabled( false ),
  45. mEditorTimeScale( 1.0f ),
  46. mDynamicsWorld( NULL ),
  47. mThreadSupportCollision( NULL )
  48. {
  49. }
  50. BtWorld::~BtWorld()
  51. {
  52. }
  53. bool BtWorld::initWorld( bool isServer, ProcessList *processList )
  54. {
  55. // Collision configuration contains default setup for memory, collision setup.
  56. mCollisionConfiguration = new btDefaultCollisionConfiguration();
  57. // TODO: There is something wrong with multithreading
  58. // and compound convex shapes... so disable it for now.
  59. static const U32 smMaxThreads = 1;
  60. // Different initialization with threading enabled.
  61. if ( smMaxThreads > 1 )
  62. {
  63. // TODO: ifdef assumes smMaxThread is always one at this point. MACOSX support to be decided
  64. #ifdef WIN32
  65. mThreadSupportCollision = new Win32ThreadSupport(
  66. Win32ThreadSupport::Win32ThreadConstructionInfo( isServer ? "bt_servercol" : "bt_clientcol",
  67. processCollisionTask,
  68. createCollisionLocalStoreMemory,
  69. smMaxThreads ) );
  70. mDispatcher = new SpuGatheringCollisionDispatcher( mThreadSupportCollision,
  71. smMaxThreads,
  72. mCollisionConfiguration );
  73. #endif // WIN32
  74. }
  75. else
  76. {
  77. mThreadSupportCollision = NULL;
  78. mDispatcher = new btCollisionDispatcher( mCollisionConfiguration );
  79. }
  80. btVector3 worldMin( -2000, -2000, -1000 );
  81. btVector3 worldMax( 2000, 2000, 1000 );
  82. btAxisSweep3 *sweepBP = new btAxisSweep3( worldMin, worldMax );
  83. mBroadphase = sweepBP;
  84. sweepBP->getOverlappingPairCache()->setInternalGhostPairCallback( new btGhostPairCallback() );
  85. // The default constraint solver. For parallel processing you can use a different solver (see Extras/BulletMultiThreaded).
  86. mSolver = new btSequentialImpulseConstraintSolver;
  87. mDynamicsWorld = new btDiscreteDynamicsWorld( mDispatcher, mBroadphase, mSolver, mCollisionConfiguration );
  88. if ( !mDynamicsWorld )
  89. {
  90. Con::errorf( "BtWorld - %s failed to create dynamics world!", isServer ? "Server" : "Client" );
  91. return false;
  92. }
  93. // Removing the randomization in the solver is required
  94. // to make the simulation deterministic.
  95. mDynamicsWorld->getSolverInfo().m_solverMode &= ~SOLVER_RANDMIZE_ORDER;
  96. mDynamicsWorld->setGravity( btCast<btVector3>( mGravity ) );
  97. AssertFatal( processList, "BtWorld::init() - We need a process list to create the world!" );
  98. mProcessList = processList;
  99. mProcessList->preTickSignal().notify( this, &BtWorld::getPhysicsResults );
  100. mProcessList->postTickSignal().notify( this, &BtWorld::tickPhysics, 1000.0f );
  101. return true;
  102. }
  103. void BtWorld::_destroy()
  104. {
  105. // Release the tick processing signals.
  106. if ( mProcessList )
  107. {
  108. mProcessList->preTickSignal().remove( this, &BtWorld::getPhysicsResults );
  109. mProcessList->postTickSignal().remove( this, &BtWorld::tickPhysics );
  110. mProcessList = NULL;
  111. }
  112. // TODO: Release any remaining
  113. // orphaned rigid bodies here.
  114. SAFE_DELETE( mDynamicsWorld );
  115. SAFE_DELETE( mSolver );
  116. SAFE_DELETE( mBroadphase );
  117. SAFE_DELETE( mDispatcher );
  118. SAFE_DELETE( mThreadSupportCollision );
  119. SAFE_DELETE( mCollisionConfiguration );
  120. }
  121. void BtWorld::tickPhysics( U32 elapsedMs )
  122. {
  123. if ( !mDynamicsWorld || !mIsEnabled )
  124. return;
  125. // Did we forget to call getPhysicsResults somewhere?
  126. AssertFatal( !mIsSimulating, "PhysXWorld::tickPhysics() - Already simulating!" );
  127. // The elapsed time should be non-zero and
  128. // a multiple of TickMs!
  129. AssertFatal( elapsedMs != 0 &&
  130. ( elapsedMs % TickMs ) == 0 , "PhysXWorld::tickPhysics() - Got bad elapsed time!" );
  131. PROFILE_SCOPE(BtWorld_TickPhysics);
  132. // Convert it to seconds.
  133. const F32 elapsedSec = (F32)elapsedMs * 0.001f;
  134. // Simulate... it is recommended to always use Bullet's default fixed timestep/
  135. mDynamicsWorld->stepSimulation( elapsedSec * mEditorTimeScale );
  136. mIsSimulating = true;
  137. //Con::printf( "%s BtWorld::tickPhysics!", this == smClientWorld ? "Client" : "Server" );
  138. }
  139. void BtWorld::getPhysicsResults()
  140. {
  141. if ( !mDynamicsWorld || !mIsSimulating )
  142. return;
  143. PROFILE_SCOPE(BtWorld_GetPhysicsResults);
  144. // Get results from scene.
  145. // mScene->fetchResults( NX_RIGID_BODY_FINISHED, true );
  146. mIsSimulating = false;
  147. mTickCount++;
  148. }
  149. void BtWorld::setEnabled( bool enabled )
  150. {
  151. mIsEnabled = enabled;
  152. if ( !mIsEnabled )
  153. getPhysicsResults();
  154. }
  155. void BtWorld::destroyWorld()
  156. {
  157. _destroy();
  158. }
  159. bool BtWorld::castRay( const Point3F &startPnt, const Point3F &endPnt, RayInfo *ri, const Point3F &impulse )
  160. {
  161. btCollisionWorld::ClosestRayResultCallback result( btCast<btVector3>( startPnt ), btCast<btVector3>( endPnt ) );
  162. mDynamicsWorld->rayTest( btCast<btVector3>( startPnt ), btCast<btVector3>( endPnt ), result );
  163. if ( !result.hasHit() || !result.m_collisionObject )
  164. return false;
  165. if ( ri )
  166. {
  167. ri->object = PhysicsUserData::getObject( result.m_collisionObject->getUserPointer() );
  168. // If we were passed a RayInfo, we can only return true signifying a collision
  169. // if we hit an object that actually has a torque object associated with it.
  170. //
  171. // In some ways this could be considered an error, either a physx object
  172. // has raycast-collision enabled that shouldn't or someone did not set
  173. // an object in this actor's userData.
  174. //
  175. if ( ri->object == NULL )
  176. return false;
  177. ri->distance = ( endPnt - startPnt ).len() * result.m_closestHitFraction;
  178. ri->normal = btCast<Point3F>( result.m_hitNormalWorld );
  179. ri->point = btCast<Point3F>( result.m_hitPointWorld );
  180. ri->t = result.m_closestHitFraction;
  181. }
  182. /*
  183. if ( impulse.isZero() ||
  184. !actor.isDynamic() ||
  185. actor.readBodyFlag( NX_BF_KINEMATIC ) )
  186. return true;
  187. NxVec3 force = pxCast<NxVec3>( impulse );//worldRay.dir * forceAmt;
  188. actor.addForceAtPos( force, hitInfo.worldImpact, NX_IMPULSE );
  189. */
  190. return true;
  191. }
  192. PhysicsBody* BtWorld::castRay( const Point3F &start, const Point3F &end, U32 bodyTypes )
  193. {
  194. btVector3 startPt = btCast<btVector3>( start );
  195. btVector3 endPt = btCast<btVector3>( end );
  196. btCollisionWorld::ClosestRayResultCallback result( startPt, endPt );
  197. mDynamicsWorld->rayTest( startPt, endPt, result );
  198. if ( !result.hasHit() || !result.m_collisionObject )
  199. return NULL;
  200. PhysicsUserData *userData = PhysicsUserData::cast( result.m_collisionObject->getUserPointer() );
  201. if ( !userData )
  202. return NULL;
  203. return userData->getBody();
  204. }
  205. void BtWorld::explosion( const Point3F &pos, F32 radius, F32 forceMagnitude )
  206. {
  207. /*
  208. // Find Actors at the position within the radius
  209. // and apply force to them.
  210. NxVec3 nxPos = pxCast<NxVec3>( pos );
  211. NxShape **shapes = (NxShape**)NxAlloca(10*sizeof(NxShape*));
  212. NxSphere worldSphere( nxPos, radius );
  213. NxU32 numHits = mScene->overlapSphereShapes( worldSphere, NX_ALL_SHAPES, 10, shapes, NULL );
  214. for ( NxU32 i = 0; i < numHits; i++ )
  215. {
  216. NxActor &actor = shapes[i]->getActor();
  217. bool dynamic = actor.isDynamic();
  218. if ( !dynamic )
  219. continue;
  220. bool kinematic = actor.readBodyFlag( NX_BF_KINEMATIC );
  221. if ( kinematic )
  222. continue;
  223. NxVec3 force = actor.getGlobalPosition() - nxPos;
  224. force.normalize();
  225. force *= forceMagnitude;
  226. actor.addForceAtPos( force, nxPos, NX_IMPULSE, true );
  227. }
  228. */
  229. }
  230. void BtWorld::onDebugDraw( const SceneRenderState *state )
  231. {
  232. mDebugDraw.setCuller( &state->getCullingFrustum() );
  233. mDynamicsWorld->setDebugDrawer( &mDebugDraw );
  234. mDynamicsWorld->debugDrawWorld();
  235. mDynamicsWorld->setDebugDrawer( NULL );
  236. mDebugDraw.flush();
  237. }
  238. void BtWorld::reset()
  239. {
  240. if ( !mDynamicsWorld )
  241. return;
  242. ///create a copy of the array, not a reference!
  243. btCollisionObjectArray copyArray = mDynamicsWorld->getCollisionObjectArray();
  244. S32 numObjects = mDynamicsWorld->getNumCollisionObjects();
  245. for ( S32 i=0; i < numObjects; i++ )
  246. {
  247. btCollisionObject* colObj = copyArray[i];
  248. btRigidBody* body = btRigidBody::upcast(colObj);
  249. if (body)
  250. {
  251. if (body->getMotionState())
  252. {
  253. //btDefaultMotionState* myMotionState = (btDefaultMotionState*)body->getMotionState();
  254. //myMotionState->m_graphicsWorldTrans = myMotionState->m_startWorldTrans;
  255. //body->setCenterOfMassTransform( myMotionState->m_graphicsWorldTrans );
  256. //colObj->setInterpolationWorldTransform( myMotionState->m_startWorldTrans );
  257. colObj->forceActivationState(ACTIVE_TAG);
  258. colObj->activate();
  259. colObj->setDeactivationTime(0);
  260. //colObj->setActivationState(WANTS_DEACTIVATION);
  261. }
  262. //removed cached contact points (this is not necessary if all objects have been removed from the dynamics world)
  263. //m_dynamicsWorld->getBroadphase()->getOverlappingPairCache()->cleanProxyFromPairs(colObj->getBroadphaseHandle(),getDynamicsWorld()->getDispatcher());
  264. btRigidBody* body = btRigidBody::upcast(colObj);
  265. if (body && !body->isStaticObject())
  266. {
  267. btRigidBody::upcast(colObj)->setLinearVelocity(btVector3(0,0,0));
  268. btRigidBody::upcast(colObj)->setAngularVelocity(btVector3(0,0,0));
  269. }
  270. }
  271. }
  272. // reset some internal cached data in the broadphase
  273. mDynamicsWorld->getBroadphase()->resetPool( mDynamicsWorld->getDispatcher() );
  274. mDynamicsWorld->getConstraintSolver()->reset();
  275. }
  276. /*
  277. ConsoleFunction( castForceRay, const char*, 4, 4, "( Point3F startPnt, Point3F endPnt, VectorF impulseVec )" )
  278. {
  279. PhysicsWorld *world = PHYSICSPLUGIN->getWorld( "server" );
  280. if ( !world )
  281. return NULL;
  282. char *returnBuffer = Con::getReturnBuffer(256);
  283. Point3F impulse;
  284. Point3F startPnt, endPnt;
  285. dSscanf( argv[1], "%f %f %f", &startPnt.x, &startPnt.y, &startPnt.z );
  286. dSscanf( argv[2], "%f %f %f", &endPnt.x, &endPnt.y, &endPnt.z );
  287. dSscanf( argv[3], "%f %f %f", &impulse.x, &impulse.y, &impulse.z );
  288. Point3F hitPoint;
  289. RayInfo rinfo;
  290. bool hit = world->castRay( startPnt, endPnt, &rinfo, impulse );
  291. DebugDrawer *ddraw = DebugDrawer::get();
  292. if ( ddraw )
  293. {
  294. ddraw->drawLine( startPnt, endPnt, hit ? ColorF::RED : ColorF::GREEN );
  295. ddraw->setLastTTL( 3000 );
  296. }
  297. if ( hit )
  298. {
  299. dSprintf(returnBuffer, 256, "%g %g %g",
  300. rinfo.point.x, rinfo.point.y, rinfo.point.z );
  301. return returnBuffer;
  302. }
  303. else
  304. return NULL;
  305. }
  306. */