physicsShape.cpp 39 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210
  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/physicsShape.h"
  24. #include "console/consoleTypes.h"
  25. #include "core/stream/bitStream.h"
  26. #include "core/resourceManager.h"
  27. #include "math/mathIO.h"
  28. #include "T3D/physics/physicsPlugin.h"
  29. #include "T3D/physics/physicsBody.h"
  30. #include "T3D/physics/physicsWorld.h"
  31. #include "T3D/physics/physicsCollision.h"
  32. #include "T3D/gameBase/gameConnection.h"
  33. #include "collision/concretePolyList.h"
  34. #include "ts/tsShapeInstance.h"
  35. #include "scene/sceneRenderState.h"
  36. #include "gfx/gfxTransformSaver.h"
  37. #include "T3D/physics/physicsDebris.h"
  38. #include "T3D/fx/explosion.h"
  39. #include "T3D/containerQuery.h"
  40. #include "lighting/lightQuery.h"
  41. #include "console/engineAPI.h"
  42. using namespace Torque;
  43. bool PhysicsShape::smNoCorrections = false;
  44. bool PhysicsShape::smNoSmoothing = false;
  45. ImplementEnumType( PhysicsSimType,
  46. "How to handle the physics simulation with the client's and server.\n"
  47. "@ingroup Physics\n\n")
  48. { PhysicsShapeData::SimType_ClientOnly, "ClientOnly", "Only handle physics on the client.\n" },
  49. { PhysicsShapeData::SimType_ServerOnly, "ServerOnly", "Only handle physics on the server.\n" },
  50. { PhysicsShapeData::SimType_ClientServer, "ClientServer", "Handle physics on both the client and server.\n" }
  51. EndImplementEnumType;
  52. IMPLEMENT_CO_DATABLOCK_V1( PhysicsShapeData );
  53. ConsoleDocClass( PhysicsShapeData,
  54. "@brief Defines the properties of a PhysicsShape.\n\n"
  55. "@see PhysicsShape.\n"
  56. "@ingroup Physics"
  57. );
  58. PhysicsShapeData::PhysicsShapeData()
  59. : mass( 1.0f ),
  60. dynamicFriction( 0.0f ),
  61. staticFriction( 0.0f ),
  62. restitution( 0.0f ),
  63. linearDamping( 0.0f ),
  64. angularDamping( 0.0f ),
  65. linearSleepThreshold( 1.0f ),
  66. angularSleepThreshold( 1.0f ),
  67. waterDampingScale( 1.0f ),
  68. buoyancyDensity( 0.0f ),
  69. simType( SimType_ClientServer )
  70. {
  71. mShapeAsset.registerRefreshNotify(this);
  72. }
  73. PhysicsShapeData::~PhysicsShapeData()
  74. {
  75. mShapeAsset.unregisterRefreshNotify();
  76. }
  77. void PhysicsShapeData::initPersistFields()
  78. {
  79. docsURL;
  80. addGroup("Shapes");
  81. INITPERSISTFIELD_SHAPEASSET_REFACTOR(Shape, PhysicsShapeData, "@brief Shape asset to be used with this physics object.\n\n"
  82. "Compatable with Live-Asset Reloading. ")
  83. addField( "debris", TYPEID< SimObjectRef<PhysicsDebrisData> >(), Offset( debris, PhysicsShapeData ),
  84. "@brief Name of a PhysicsDebrisData to spawn when this shape is destroyed (optional)." );
  85. addField( "explosion", TYPEID< SimObjectRef<ExplosionData> >(), Offset( explosion, PhysicsShapeData ),
  86. "@brief Name of an ExplosionData to spawn when this shape is destroyed (optional)." );
  87. addField( "destroyedShape", TYPEID< SimObjectRef<PhysicsShapeData> >(), Offset( destroyedShape, PhysicsShapeData ),
  88. "@brief Name of a PhysicsShapeData to spawn when this shape is destroyed (optional)." );
  89. endGroup("Shapes");
  90. addGroup( "Physics" );
  91. addFieldV( "mass", TypeRangedF32, Offset( mass, PhysicsShapeData ), &CommonValidators::PositiveFloat,
  92. "@brief Value representing the mass of the shape.\n\n"
  93. "A shape's mass influences the magnitude of any force exerted on it. "
  94. "For example, a PhysicsShape with a large mass requires a much larger force to move than "
  95. "the same shape with a smaller mass.\n"
  96. "@note A mass of zero will create a kinematic shape while anything greater will create a dynamic shape.");
  97. addFieldV( "friction", TypeRangedF32, Offset( dynamicFriction, PhysicsShapeData ), &CommonValidators::PositiveFloat,
  98. "@brief Coefficient of kinetic %friction to be applied to the shape.\n\n"
  99. "Kinetic %friction reduces the velocity of a moving object while it is in contact with a surface. "
  100. "A higher coefficient will result in a larger velocity reduction. "
  101. "A shape's friction should be lower than it's staticFriction, but larger than 0.\n\n"
  102. "@note This value is only applied while an object is in motion. For an object starting at rest, see PhysicsShape::staticFriction");
  103. addFieldV( "staticFriction", TypeRangedF32, Offset( staticFriction, PhysicsShapeData ), &CommonValidators::PositiveFloat,
  104. "@brief Coefficient of static %friction to be applied to the shape.\n\n"
  105. "Static %friction determines the force needed to start moving an at-rest object in contact with a surface. "
  106. "If the force applied onto shape cannot overcome the force of static %friction, the shape will remain at rest. "
  107. "A larger coefficient will require a larger force to start motion. "
  108. "This value should be larger than zero and the physicsShape's friction.\n\n"
  109. "@note This value is only applied while an object is at rest. For an object in motion, see PhysicsShape::friction");
  110. addFieldV( "restitution", TypeRangedF32, Offset( restitution, PhysicsShapeData ), &CommonValidators::PositiveFloat,
  111. "@brief Coeffecient of a bounce applied to the shape in response to a collision.\n\n"
  112. "Restitution is a ratio of a shape's velocity before and after a collision. "
  113. "A value of 0 will zero out a shape's post-collision velocity, making it stop on contact. "
  114. "Larger values will remove less velocity after a collision, making it \'bounce\' with a greater force. "
  115. "Normal %restitution values range between 0 and 1.0."
  116. "@note Values near or equaling 1.0 are likely to cause undesirable results in the physics simulation."
  117. " Because of this it is reccomended to avoid values close to 1.0");
  118. addFieldV( "linearDamping", TypeRangedF32, Offset( linearDamping, PhysicsShapeData ), &CommonValidators::PositiveFloat,
  119. "@brief Value that reduces an object's linear velocity over time.\n\n"
  120. "Larger values will cause velocity to decay quicker.\n\n" );
  121. addFieldV( "angularDamping", TypeRangedF32, Offset( angularDamping, PhysicsShapeData ), &CommonValidators::PositiveFloat,
  122. "@brief Value that reduces an object's rotational velocity over time.\n\n"
  123. "Larger values will cause velocity to decay quicker.\n\n" );
  124. addFieldV( "linearSleepThreshold", TypeRangedF32, Offset( linearSleepThreshold, PhysicsShapeData ), &CommonValidators::PositiveFloat,
  125. "@brief Minimum linear velocity before the shape can be put to sleep.\n\n"
  126. "This should be a positive value. Shapes put to sleep will not be simulated in order to save system resources.\n\n"
  127. "@note The shape must be dynamic.");
  128. addFieldV( "angularSleepThreshold", TypeRangedF32, Offset( angularSleepThreshold, PhysicsShapeData ), &CommonValidators::PositiveFloat,
  129. "@brief Minimum rotational velocity before the shape can be put to sleep.\n\n"
  130. "This should be a positive value. Shapes put to sleep will not be simulated in order to save system resources.\n\n"
  131. "@note The shape must be dynamic.");
  132. addFieldV( "waterDampingScale", TypeRangedF32, Offset( waterDampingScale, PhysicsShapeData ), &CommonValidators::PositiveFloat,
  133. "@brief Scale to apply to linear and angular dampening while underwater.\n\n "
  134. "Used with the waterViscosity of the "
  135. "@see angularDamping linearDamping" );
  136. addFieldV( "buoyancyDensity", TypeRangedF32, Offset( buoyancyDensity, PhysicsShapeData ), &CommonValidators::PositiveFloat,
  137. "@brief The density of the shape for calculating buoyant forces.\n\n"
  138. "The result of the calculated buoyancy is relative to the density of the WaterObject the PhysicsShape is within.\n\n"
  139. "@see WaterObject::density");
  140. endGroup( "Physics" );
  141. addGroup( "Networking" );
  142. addField( "simType", TYPEID< PhysicsShapeData::SimType >(), Offset( simType, PhysicsShapeData ),
  143. "@brief Controls whether this shape is simulated on the server, client, or both physics simulations.\n\n" );
  144. endGroup( "Networking" );
  145. Parent::initPersistFields();
  146. }
  147. void PhysicsShapeData::packData( BitStream *stream )
  148. {
  149. Parent::packData( stream );
  150. PACKDATA_ASSET_REFACTOR(Shape);
  151. stream->write( mass );
  152. stream->write( dynamicFriction );
  153. stream->write( staticFriction );
  154. stream->write( restitution );
  155. stream->write( linearDamping );
  156. stream->write( angularDamping );
  157. stream->write( linearSleepThreshold );
  158. stream->write( angularSleepThreshold );
  159. stream->write( waterDampingScale );
  160. stream->write( buoyancyDensity );
  161. stream->writeInt( simType, SimType_Bits );
  162. stream->writeRangedU32( debris ? debris->getId() : 0, 0, DataBlockObjectIdLast );
  163. stream->writeRangedU32( explosion ? explosion->getId() : 0, 0, DataBlockObjectIdLast );
  164. stream->writeRangedU32( destroyedShape ? destroyedShape->getId() : 0, 0, DataBlockObjectIdLast );
  165. }
  166. void PhysicsShapeData::unpackData( BitStream *stream )
  167. {
  168. Parent::unpackData(stream);
  169. UNPACKDATA_ASSET_REFACTOR(Shape);
  170. stream->read( &mass );
  171. stream->read( &dynamicFriction );
  172. stream->read( &staticFriction );
  173. stream->read( &restitution );
  174. stream->read( &linearDamping );
  175. stream->read( &angularDamping );
  176. stream->read( &linearSleepThreshold );
  177. stream->read( &angularSleepThreshold );
  178. stream->read( &waterDampingScale );
  179. stream->read( &buoyancyDensity );
  180. simType = (SimType)stream->readInt( SimType_Bits );
  181. debris = stream->readRangedU32( 0, DataBlockObjectIdLast );
  182. explosion = stream->readRangedU32( 0, DataBlockObjectIdLast );
  183. destroyedShape = stream->readRangedU32( 0, DataBlockObjectIdLast );
  184. }
  185. bool PhysicsShapeData::onAdd()
  186. {
  187. if ( !Parent::onAdd() )
  188. return false;
  189. ResourceManager::get().getChangedSignal().notify( this, &PhysicsShapeData::_onResourceChanged );
  190. return true;
  191. }
  192. void PhysicsShapeData::onRemove()
  193. {
  194. ResourceManager::get().getChangedSignal().remove( this, &PhysicsShapeData::_onResourceChanged );
  195. Parent::onRemove();
  196. }
  197. void PhysicsShapeData::_onResourceChanged( const Torque::Path &path )
  198. {
  199. U32 assetStatus = ShapeAsset::getAssetErrCode(mShapeAsset);
  200. if (assetStatus != AssetBase::Ok && assetStatus != AssetBase::UsingFallback)
  201. {
  202. return;
  203. }
  204. if ( path != Path(mShapeAsset->getShapeFile()) )
  205. return;
  206. _setShape(_getShapeAssetId());
  207. // Reload the changed shape.
  208. PhysicsCollisionRef reloadcolShape;
  209. if ( !getShape())
  210. {
  211. Con::warnf( ConsoleLogEntry::General, "PhysicsShapeData::_onResourceChanged: Could not reload %s.", path.getFileName().c_str() );
  212. return;
  213. }
  214. // Reload the collision shape.
  215. reloadcolShape = getShape()->buildColShape( false, Point3F::One );
  216. if ( bool(reloadcolShape))
  217. colShape = reloadcolShape;
  218. mReloadSignal.trigger();
  219. }
  220. bool PhysicsShapeData::preload( bool server, String &errorBuffer )
  221. {
  222. if ( !Parent::preload( server, errorBuffer ) )
  223. return false;
  224. // If we don't have a physics plugin active then
  225. // we have to fail completely.
  226. if ( !PHYSICSMGR )
  227. {
  228. errorBuffer = "PhysicsShapeData::preload - No physics plugin is active!";
  229. return false;
  230. }
  231. bool shapeError = false;
  232. if (getShape())
  233. {
  234. if (!server && !getShape()->preloadMaterialList(getShapeFile()) && NetConnection::filesWereDownloaded())
  235. shapeError = true;
  236. }
  237. else
  238. {
  239. errorBuffer = String::ToString("PhysicsShapeData: Couldn't load shape \"%s\"", _getShapeAssetId());
  240. return false;
  241. }
  242. // Prepare the shared physics collision shape.
  243. if ( !colShape && getShape())
  244. {
  245. colShape = getShape()->buildColShape( false, Point3F::One );
  246. // If we got here and didn't get a collision shape then
  247. // we need to fail... can't have a shape without collision.
  248. if ( !colShape )
  249. {
  250. //no collision so we create a simple box collision shape from the shapes bounds and alert the user
  251. Con::warnf( "PhysicsShapeData::preload - No collision found for shape '%s', auto-creating one", _getShapeAssetId());
  252. Point3F halfWidth = getShape()->mBounds.getExtents() * 0.5f;
  253. colShape = PHYSICSMGR->createCollision();
  254. MatrixF centerXfm(true);
  255. centerXfm.setPosition(getShape()->mBounds.getCenter());
  256. colShape->addBox(halfWidth, centerXfm);
  257. return true;
  258. }
  259. }
  260. // My convex demcomposion test
  261. /*
  262. // Get the verts and triangles for the first visible detail.
  263. ConcretePolyList polyList;
  264. polyList.setTransform( &MatrixF::Identity, Point3F::One );
  265. TSShapeInstance shapeInst( shape, false );
  266. shapeInst.animate(0);
  267. if ( !shapeInst.buildPolyList( &polyList, 0 ) )
  268. return false;
  269. // Gah... Ratcliff's lib works on doubles... why, oh why?
  270. Vector<F64> doubleVerts;
  271. doubleVerts.setSize( polyList.mVertexList.size() * 3 );
  272. for ( U32 i=0; i < polyList.mVertexList.size(); i++ )
  273. {
  274. doubleVerts[ ( i * 3 ) + 0 ] = (F64)polyList.mVertexList[i].x;
  275. doubleVerts[ ( i * 3 ) + 1 ] = (F64)polyList.mVertexList[i].y;
  276. doubleVerts[ ( i * 3 ) + 2 ] = (F64)polyList.mVertexList[i].z;
  277. }
  278. using namespace ConvexDecomposition;
  279. class ConvexBuilder : public ConvexDecompInterface
  280. {
  281. public:
  282. ConvexBuilder() { }
  283. ~ConvexBuilder()
  284. {
  285. for ( U32 i=0; i < mHulls.size(); i++ )
  286. delete mHulls[i];
  287. }
  288. virtual void ConvexDecompResult( ConvexResult &result )
  289. {
  290. FConvexResult *hull = new FConvexResult( result );
  291. mHulls.push_back( hull );
  292. }
  293. Vector<FConvexResult*> mHulls;
  294. };
  295. DecompDesc d;
  296. d.mVcount = polyList.mVertexList.size();
  297. d.mVertices = doubleVerts.address();
  298. d.mTcount = polyList.mIndexList.size() / 3;
  299. d.mIndices = polyList.mIndexList.address();
  300. d.mDepth = 3;
  301. d.mCpercent = 20.0f;
  302. d.mPpercent = 30.0f;
  303. d.mMaxVertices = 32;
  304. d.mSkinWidth = 0.05f; // Need to expose this!
  305. ConvexBuilder builder;
  306. d.mCallback = &builder;
  307. if ( performConvexDecomposition( d ) < 1 || builder.mHulls.empty() )
  308. return false;
  309. // Add all the convex hull results into the collision shape.
  310. colShape = PHYSICSMGR->createCollision();
  311. for ( U32 i=0; i < builder.mHulls.size(); i++ )
  312. colShape->addConvex( (const Point3F*)builder.mHulls[i]->mHullVertices,
  313. builder.mHulls[i]->mHullVcount,
  314. MatrixF::Identity );
  315. */
  316. return !shapeError;
  317. }
  318. IMPLEMENT_CO_NETOBJECT_V1(PhysicsShape);
  319. ConsoleDocClass( PhysicsShape,
  320. "@brief Represents a destructible physical object simulated through the plugin system.\n\n"
  321. "@see PhysicsShapeData.\n"
  322. "@ingroup Physics"
  323. );
  324. PhysicsShape::PhysicsShape()
  325. : mPhysicsRep( NULL ),
  326. mWorld( NULL ),
  327. mResetPos( MatrixF::Identity ),
  328. mShapeInst( NULL ),
  329. mDestroyed( false ),
  330. mPlayAmbient( false ),
  331. mAmbientSeq( -1 ),
  332. mAmbientThread( NULL )
  333. {
  334. mNetFlags.set( Ghostable | ScopeAlways );
  335. mTypeMask |= DynamicShapeObjectType;
  336. }
  337. PhysicsShape::~PhysicsShape()
  338. {
  339. }
  340. void PhysicsShape::consoleInit()
  341. {
  342. Con::addVariable( "$PhysicsShape::noCorrections", TypeBool, &PhysicsShape::smNoCorrections,
  343. "@brief Determines if the shape will recieve corrections from the server or "
  344. "will instead be allowed to diverge.\n\n"
  345. "In the event that the client and server object positions/orientations "
  346. "differ and if this variable is true, the server will attempt to \'correct\' "
  347. "the client object to keep it in sync. Otherwise, client and server objects may fall out of sync.\n\n");
  348. Con::addVariable( "$PhysicsShape::noSmoothing", TypeBool, &PhysicsShape::smNoSmoothing,
  349. "@brief Determines if client-side shapes will attempt to smoothly transition to "
  350. "their new position after reciving a correction.\n\n"
  351. "If true, shapes will immediately render at the position they are corrected to.\n\n");
  352. Parent::consoleInit();
  353. }
  354. void PhysicsShape::initPersistFields()
  355. {
  356. docsURL;
  357. addGroup( "PhysicsShape" );
  358. addField( "playAmbient", TypeBool, Offset( mPlayAmbient, PhysicsShape ),
  359. "@brief Enables or disables playing of an ambient animation upon loading the shape.\n\n"
  360. "@note The ambient animation must be named \"ambient\"." );
  361. endGroup( "PhysicsShape" );
  362. Parent::initPersistFields();
  363. removeField( "scale" );
  364. }
  365. void PhysicsShape::inspectPostApply()
  366. {
  367. Parent::inspectPostApply();
  368. setMaskBits( InitialUpdateMask );
  369. }
  370. U32 PhysicsShape::packUpdate( NetConnection *con, U32 mask, BitStream *stream )
  371. {
  372. U32 retMask = Parent::packUpdate( con, mask, stream );
  373. if ( stream->writeFlag( mask & InitialUpdateMask ) )
  374. {
  375. stream->writeAffineTransform( getTransform() );
  376. stream->writeFlag( mPlayAmbient );
  377. stream->writeFlag( mDestroyed );
  378. return retMask;
  379. }
  380. // If we got here its not an initial update. So only send
  381. // the least amount of data possible.
  382. if ( stream->writeFlag( mask & StateMask ) )
  383. {
  384. // This will encode the position relative to the control
  385. // object position.
  386. //
  387. // This will compress the position to as little as 6.25
  388. // bytes if the position is within about 30 meters of the
  389. // control object.
  390. //
  391. // Worst case its a full 12 bytes + 2 bits if the position
  392. // is more than 500 meters from the control object.
  393. //
  394. stream->writeCompressedPoint( mState.position );
  395. // Use only 3.5 bytes to send the orientation.
  396. stream->writeQuat( mState.orientation, 9 );
  397. // If the server object has been set to sleep then
  398. // we don't need to send any velocity.
  399. if ( !stream->writeFlag( mState.sleeping ) )
  400. {
  401. // This gives me ~0.015f resolution in velocity magnitude
  402. // while only costing me 1 bit of the velocity is zero length,
  403. // <5 bytes in normal cases, and <8 bytes if the velocity is
  404. // greater than 1000.
  405. AssertWarn( mState.linVelocity.len() < 1000.0f,
  406. "PhysicsShape::packUpdate - The linVelocity is out of range!" );
  407. stream->writeVector( mState.linVelocity, 1000.0f, 16, 9 );
  408. // For angular velocity we get < 0.01f resolution in magnitude
  409. // with the most common case being under 4 bytes.
  410. AssertWarn( mState.angVelocity.len() < 10.0f,
  411. "PhysicsShape::packUpdate - The angVelocity is out of range!" );
  412. stream->writeVector( mState.angVelocity, 10.0f, 10, 9 );
  413. }
  414. }
  415. if ( stream->writeFlag( mask & DamageMask ) )
  416. stream->writeFlag( mDestroyed );
  417. return retMask;
  418. }
  419. void PhysicsShape::unpackUpdate( NetConnection *con, BitStream *stream )
  420. {
  421. Parent::unpackUpdate( con, stream );
  422. if ( stream->readFlag() ) // InitialUpdateMask
  423. {
  424. MatrixF mat;
  425. stream->readAffineTransform( &mat );
  426. setTransform( mat );
  427. mPlayAmbient = stream->readFlag();
  428. if ( isProperlyAdded() )
  429. _initAmbient();
  430. if ( stream->readFlag() )
  431. {
  432. if ( isProperlyAdded() )
  433. {
  434. // Destroy immediately if we've already been added
  435. // to the scene.
  436. destroy();
  437. }
  438. else
  439. {
  440. // Indicate the shape should be destroyed when the
  441. // shape is added.
  442. mDestroyed = true;
  443. }
  444. }
  445. return;
  446. }
  447. if ( stream->readFlag() ) // StateMask
  448. {
  449. PhysicsState state;
  450. // Read the encoded and compressed position... commonly only 6.25 bytes.
  451. stream->readCompressedPoint( &state.position );
  452. // Read the compressed quaternion... 3.5 bytes.
  453. stream->readQuat( &state.orientation, 9 );
  454. state.sleeping = stream->readFlag();
  455. if ( !state.sleeping )
  456. {
  457. stream->readVector( &state.linVelocity, 1000.0f, 16, 9 );
  458. stream->readVector( &state.angVelocity, 10.0f, 10, 9 );
  459. }
  460. if ( !smNoCorrections && mPhysicsRep && mPhysicsRep->isDynamic() && !mDestroyed )
  461. {
  462. // Set the new state on the physics object immediately.
  463. mPhysicsRep->applyCorrection( state.getTransform() );
  464. mPhysicsRep->setSleeping( state.sleeping );
  465. if ( !state.sleeping )
  466. {
  467. mPhysicsRep->setLinVelocity( state.linVelocity );
  468. mPhysicsRep->setAngVelocity( state.angVelocity );
  469. }
  470. mPhysicsRep->getState( &mState );
  471. }
  472. // If there is no physics object then just set the
  473. // new state... the tick will take care of the
  474. // interpolation and extrapolation.
  475. if ( !mPhysicsRep || !mPhysicsRep->isDynamic() )
  476. mState = state;
  477. }
  478. if ( stream->readFlag() ) // DamageMask
  479. {
  480. if ( stream->readFlag() )
  481. destroy();
  482. else
  483. restore();
  484. }
  485. }
  486. bool PhysicsShape::onAdd()
  487. {
  488. if ( !Parent::onAdd() )
  489. return false;
  490. // If we don't have a physics plugin active then
  491. // we have to fail completely.
  492. if ( !PHYSICSMGR )
  493. {
  494. Con::errorf( "PhysicsShape::onAdd - No physics plugin is active!" );
  495. return false;
  496. }
  497. //
  498. if ( !mPhysicsRep && !_createShape() )
  499. {
  500. Con::errorf( "PhysicsShape::onAdd() - Shape creation failed!" );
  501. return false;
  502. }
  503. // The reset position is the transform on the server
  504. // at creation time... its not used on the client.
  505. if ( isServerObject() )
  506. {
  507. storeRestorePos();
  508. PhysicsPlugin::getPhysicsResetSignal().notify( this, &PhysicsShape::_onPhysicsReset );
  509. }
  510. // Register for the resource change signal.
  511. //ResourceManager::get().getChangedSignal().notify( this, &PhysicsShape::_onResourceChanged );
  512. // Only add server objects and non-destroyed client objects to the scene.
  513. if ( isServerObject() || !mDestroyed)
  514. addToScene();
  515. if ( isClientObject() && mDestroyed )
  516. {
  517. // Disable all simulation of the body... no collision or dynamics.
  518. if ( mPhysicsRep )
  519. mPhysicsRep->setSimulationEnabled( false );
  520. // Stop doing tick processing for this SceneObject.
  521. setProcessTick( false );
  522. }
  523. return true;
  524. }
  525. void PhysicsShape::onRemove()
  526. {
  527. removeFromScene();
  528. SAFE_DELETE( mPhysicsRep );
  529. SAFE_DELETE( mShapeInst );
  530. mAmbientThread = NULL;
  531. mAmbientSeq = -1;
  532. mWorld = NULL;
  533. if ( isServerObject() )
  534. {
  535. PhysicsPlugin::getPhysicsResetSignal().remove( this, &PhysicsShape::_onPhysicsReset );
  536. if ( mDestroyedShape )
  537. mDestroyedShape->deleteObject();
  538. }
  539. // Remove the resource change signal.
  540. //ResourceManager::get().getChangedSignal().remove( this, &PhysicsShape::_onResourceChanged );
  541. Parent::onRemove();
  542. }
  543. bool PhysicsShape::onNewDataBlock( GameBaseData *dptr, bool reload )
  544. {
  545. if ( !Parent::onNewDataBlock( dptr, reload ) )
  546. return false;
  547. if ( !isProperlyAdded() )
  548. return true;
  549. // If we don't have a physics plugin active then
  550. // we have to fail completely.
  551. if ( !PHYSICSMGR )
  552. {
  553. Con::errorf( "PhysicsShape::onNewDataBlock - No physics plugin is active!" );
  554. return false;
  555. }
  556. //
  557. if ( !_createShape() )
  558. {
  559. Con::errorf( "PhysicsShape::onNewDataBlock() - Shape creation failed!" );
  560. return false;
  561. }
  562. return true;
  563. }
  564. bool PhysicsShape::_createShape()
  565. {
  566. SAFE_DELETE( mPhysicsRep );
  567. SAFE_DELETE( mShapeInst );
  568. mAmbientThread = NULL;
  569. mWorld = NULL;
  570. mAmbientSeq = -1;
  571. PhysicsShapeData *db = getDataBlock();
  572. if ( !db || !db->getShape())
  573. return false;
  574. // Set the world box.
  575. mObjBox = db->getShape()->mBounds;
  576. resetWorldBox();
  577. // If this is the server and its a client only simulation
  578. // object then disable our tick... the server doesn't do
  579. // any work for this shape.
  580. if ( isServerObject() &&
  581. db->simType == PhysicsShapeData::SimType_ClientOnly )
  582. {
  583. setProcessTick( false );
  584. return true;
  585. }
  586. // Create the shape instance.
  587. mShapeInst = new TSShapeInstance( db->getShape(), isClientObject() );
  588. if ( isClientObject() )
  589. {
  590. mAmbientSeq = db->getShape()->findSequence( "ambient" );
  591. _initAmbient();
  592. }
  593. // If the shape has a mass then its dynamic... else
  594. // its a kinematic shape.
  595. //
  596. // While a kinematic is less optimal than a static body
  597. // it allows for us to enable/disable collision and having
  598. // all dynamic actors react correctly... waking up.
  599. //
  600. const bool isDynamic = db->mass > 0.0f;
  601. // If we aren't dynamic we don't need to tick.
  602. setProcessTick( isDynamic || mPlayAmbient );
  603. // If this is the client and we're a server only object then
  604. // we don't need any physics representation... we're done.
  605. if ( isClientObject() &&
  606. db->simType == PhysicsShapeData::SimType_ServerOnly )
  607. return true;
  608. mWorld = PHYSICSMGR->getWorld( isServerObject() ? "server" : "client" );
  609. mPhysicsRep = PHYSICSMGR->createBody();
  610. mPhysicsRep->init( db->colShape,
  611. db->mass,
  612. isDynamic ? 0 : PhysicsBody::BF_KINEMATIC,
  613. this,
  614. mWorld );
  615. mPhysicsRep->setMaterial( db->restitution, db->dynamicFriction, db->staticFriction );
  616. if ( isDynamic )
  617. {
  618. mPhysicsRep->setDamping( db->linearDamping, db->angularDamping );
  619. mPhysicsRep->setSleepThreshold( db->linearSleepThreshold, db->angularSleepThreshold );
  620. }
  621. mPhysicsRep->setTransform( getTransform() );
  622. return true;
  623. }
  624. void PhysicsShape::_initAmbient()
  625. {
  626. if ( isServerObject() )
  627. return;
  628. bool willPlay = mPlayAmbient && mAmbientSeq != -1;
  629. if ( willPlay )
  630. {
  631. // Create thread if we dont already have.
  632. if ( mAmbientThread == NULL )
  633. mAmbientThread = mShapeInst->addThread();
  634. // Play the sequence.
  635. mShapeInst->setSequence( mAmbientThread, mAmbientSeq, 0);
  636. setProcessTick(true);
  637. }
  638. else
  639. {
  640. if ( mAmbientThread != NULL )
  641. {
  642. mShapeInst->destroyThread( mAmbientThread );
  643. mAmbientThread = NULL;
  644. }
  645. }
  646. }
  647. void PhysicsShape::_onPhysicsReset( PhysicsResetEvent reset )
  648. {
  649. if ( reset == PhysicsResetEvent_Store )
  650. mResetPos = getTransform();
  651. else if ( reset == PhysicsResetEvent_Restore )
  652. {
  653. setTransform( mResetPos );
  654. // Restore to un-destroyed state.
  655. restore();
  656. // Cheat and reset the client from here.
  657. if ( getClientObject() )
  658. {
  659. PhysicsShape *clientObj = (PhysicsShape*)getClientObject();
  660. clientObj->setTransform( mResetPos );
  661. clientObj->restore();
  662. }
  663. }
  664. }
  665. void PhysicsShape::setTransform( const MatrixF &newMat )
  666. {
  667. Parent::setTransform( newMat );
  668. // This is only called to set an absolute position
  669. // so we discard the delta state.
  670. mState.position = getPosition();
  671. mState.orientation.set( newMat );
  672. mRenderState[0] = mRenderState[1] = mState;
  673. setMaskBits( StateMask );
  674. if ( mPhysicsRep )
  675. mPhysicsRep->setTransform( newMat );
  676. }
  677. void PhysicsShape::setScale( const VectorF &scale )
  678. {
  679. // Cannot scale PhysicsShape.
  680. return;
  681. }
  682. void PhysicsShape::storeRestorePos()
  683. {
  684. mResetPos = getTransform();
  685. }
  686. F32 PhysicsShape::getMass() const
  687. {
  688. const PhysicsShapeData *db = const_cast<PhysicsShape*>( this )->getDataBlock();
  689. return db->mass;
  690. }
  691. void PhysicsShape::applyImpulse( const Point3F &pos, const VectorF &vec )
  692. {
  693. if ( mPhysicsRep && mPhysicsRep->isDynamic() )
  694. mPhysicsRep->applyImpulse( pos, vec );
  695. }
  696. void PhysicsShape::applyTorque( const Point3F &torque )
  697. {
  698. if (mPhysicsRep && mPhysicsRep->isDynamic())
  699. mPhysicsRep->applyTorque( torque );
  700. }
  701. void PhysicsShape::applyForce( const Point3F &force )
  702. {
  703. if (mPhysicsRep && mPhysicsRep->isDynamic())
  704. mPhysicsRep->applyForce( force );
  705. }
  706. void PhysicsShape::applyRadialImpulse( const Point3F &origin, F32 radius, F32 magnitude )
  707. {
  708. if ( !mPhysicsRep || !mPhysicsRep->isDynamic() )
  709. return;
  710. // TODO: Find a better approximation of the
  711. // force vector using the object box.
  712. VectorF force = getWorldBox().getCenter() - origin;
  713. F32 dist = force.magnitudeSafe();
  714. force.normalize();
  715. if ( dist == 0.0f )
  716. force *= magnitude;
  717. else
  718. force *= mClampF( radius / dist, 0.0f, 1.0f ) * magnitude;
  719. mPhysicsRep->applyImpulse( origin, force );
  720. // TODO: There is no simple way to really sync this sort of an
  721. // event with the client.
  722. //
  723. // The best is to send the current physics snapshot, calculate the
  724. // time difference from when this event occured and the time when the
  725. // client recieves it, and then extrapolate where it should be.
  726. //
  727. // Even then its impossible to be absolutely sure its synced.
  728. //
  729. // Bottom line... you shouldn't use physics over the network like this.
  730. //
  731. // Cheat for single player.
  732. //if ( getClientObject() )
  733. //((PhysicsShape*)getClientObject())->mPhysicsRep->applyImpulse( origin, force );
  734. }
  735. void PhysicsShape::interpolateTick( F32 delta )
  736. {
  737. AssertFatal( !mDestroyed, "PhysicsShape::interpolateTick - Shouldn't be processing a destroyed shape!" );
  738. if ( !mPhysicsRep->isDynamic() )
  739. return;
  740. // Interpolate the position and rotation based on the delta.
  741. PhysicsState state;
  742. state.interpolate( mRenderState[1], mRenderState[0], delta );
  743. // Set the transform to the interpolated transform.
  744. setRenderTransform( state.getTransform() );
  745. }
  746. void PhysicsShape::processTick( const Move *move )
  747. {
  748. AssertFatal( mPhysicsRep && !mDestroyed, "PhysicsShape::processTick - Shouldn't be processing a destroyed shape!" );
  749. // Note that unlike TSStatic, the serverside PhysicsShape does not
  750. // need to play the ambient animation because even if the animation were
  751. // to move collision shapes it would not affect the physx representation.
  752. if ( !mPhysicsRep->isDynamic() )
  753. return;
  754. // SINGLE PLAYER HACK!!!!
  755. if ( PHYSICSMGR->isSinglePlayer() && isClientObject() && getServerObject() )
  756. {
  757. PhysicsShape *servObj = (PhysicsShape*)getServerObject();
  758. setTransform( servObj->mState.getTransform() );
  759. mRenderState[0] = servObj->mRenderState[0];
  760. mRenderState[1] = servObj->mRenderState[1];
  761. return;
  762. }
  763. // Store the last render state.
  764. mRenderState[0] = mRenderState[1];
  765. // If the last render state doesn't match the last simulation
  766. // state then we got a correction and need to
  767. Point3F errorDelta = mRenderState[1].position - mState.position;
  768. const bool doSmoothing = !errorDelta.isZero() && !smNoSmoothing;
  769. const bool wasSleeping = mState.sleeping;
  770. // Get the new physics state.
  771. if ( mPhysicsRep )
  772. {
  773. mPhysicsRep->getState( &mState );
  774. _updateContainerForces();
  775. }
  776. else
  777. {
  778. // This is where we could extrapolate.
  779. }
  780. // Smooth the correction back into the render state.
  781. mRenderState[1] = mState;
  782. if ( doSmoothing )
  783. {
  784. F32 correction = mClampF( errorDelta.len() / 20.0f, 0.1f, 0.9f );
  785. mRenderState[1].position.interpolate( mState.position, mRenderState[0].position, correction );
  786. mRenderState[1].orientation.interpolate( mState.orientation, mRenderState[0].orientation, correction );
  787. }
  788. // If we haven't been sleeping then update our transform
  789. // and set ourselves as dirty for the next client update.
  790. if ( !wasSleeping || !mState.sleeping )
  791. {
  792. // Set the transform on the parent so that
  793. // the physics object isn't moved.
  794. Parent::setTransform( mState.getTransform() );
  795. // If we're doing server simulation then we need
  796. // to send the client a state update.
  797. if ( isServerObject() && mPhysicsRep && !smNoCorrections &&
  798. !PHYSICSMGR->isSinglePlayer() // SINGLE PLAYER HACK!!!!
  799. )
  800. setMaskBits( StateMask );
  801. }
  802. }
  803. void PhysicsShape::advanceTime( F32 timeDelta )
  804. {
  805. if ( isClientObject() && mPlayAmbient && mAmbientThread != NULL )
  806. mShapeInst->advanceTime( timeDelta, mAmbientThread );
  807. }
  808. void PhysicsShape::_updateContainerForces()
  809. {
  810. PROFILE_SCOPE( PhysicsShape_updateContainerForces );
  811. // If we're not simulating don't update forces.
  812. if ( !mWorld->isEnabled() )
  813. return;
  814. ContainerQueryInfo info;
  815. info.box = getWorldBox();
  816. info.mass = getDataBlock()->mass;
  817. // Find and retreive physics info from intersecting WaterObject(s)
  818. getContainer()->findObjects( getWorldBox(), WaterObjectType|PhysicalZoneObjectType, findRouter, &info );
  819. // Calculate buoyancy and drag
  820. F32 angDrag = getDataBlock()->angularDamping;
  821. F32 linDrag = getDataBlock()->linearDamping;
  822. F32 buoyancy = 0.0f;
  823. Point3F cmass = mPhysicsRep->getCMassPosition();
  824. F32 density = getDataBlock()->buoyancyDensity;
  825. if ( density > 0.0f )
  826. {
  827. if ( info.waterCoverage > 0.0f )
  828. {
  829. F32 waterDragScale = info.waterViscosity * getDataBlock()->waterDampingScale;
  830. F32 powCoverage = mPow( info.waterCoverage, 0.25f );
  831. angDrag = mLerp( angDrag, angDrag * waterDragScale, powCoverage );
  832. linDrag = mLerp( linDrag, linDrag * waterDragScale, powCoverage );
  833. }
  834. buoyancy = ( info.waterDensity / density ) * mPow( info.waterCoverage, 2.0f );
  835. // A little hackery to prevent oscillation
  836. // Based on this blog post:
  837. // (http://reinot.blogspot.com/2005/11/oh-yes-they-float-georgie-they-all.html)
  838. // JCF: disabled!
  839. Point3F buoyancyForce = buoyancy * -mWorld->getGravity() * TickSec * getDataBlock()->mass;
  840. mPhysicsRep->applyImpulse( cmass, buoyancyForce );
  841. }
  842. // Update the dampening as the container might have changed.
  843. mPhysicsRep->setDamping( linDrag, angDrag );
  844. // Apply physical zone forces.
  845. if ( !info.appliedForce.isZero() )
  846. mPhysicsRep->applyImpulse( cmass, info.appliedForce );
  847. }
  848. void PhysicsShape::prepRenderImage( SceneRenderState *state )
  849. {
  850. AssertFatal( !mDestroyed, "PhysicsShape::prepRenderImage - Shouldn't be processing a destroyed shape!" );
  851. PROFILE_SCOPE( PhysicsShape_prepRenderImage );
  852. if( !mShapeInst )
  853. return;
  854. Point3F cameraOffset;
  855. getRenderTransform().getColumn(3,&cameraOffset);
  856. cameraOffset -= state->getDiffuseCameraPosition();
  857. F32 dist = cameraOffset.len();
  858. if (dist < 0.01f)
  859. dist = 0.01f;
  860. F32 invScale = (1.0f/getMax(getMax(mObjScale.x,mObjScale.y),mObjScale.z));
  861. if ( mShapeInst->setDetailFromDistance( state, dist * invScale ) < 0 )
  862. return;
  863. GFXTransformSaver saver;
  864. // Set up our TS render state.
  865. TSRenderState rdata;
  866. rdata.setSceneState( state );
  867. rdata.setFadeOverride( 1.0f );
  868. // We might have some forward lit materials
  869. // so pass down a query to gather lights.
  870. LightQuery query;
  871. query.init( getWorldSphere() );
  872. rdata.setLightQuery( &query );
  873. MatrixF mat = getRenderTransform();
  874. mat.scale( mObjScale );
  875. GFX->setWorldMatrix( mat );
  876. mShapeInst->animate();
  877. mShapeInst->render( rdata );
  878. }
  879. void PhysicsShape::destroy()
  880. {
  881. if ( mDestroyed )
  882. return;
  883. mDestroyed = true;
  884. setMaskBits( DamageMask );
  885. const Point3F lastLinVel = mPhysicsRep->isDynamic() ? mPhysicsRep->getLinVelocity() : Point3F::Zero;
  886. // Disable all simulation of the body... no collision or dynamics.
  887. mPhysicsRep->setSimulationEnabled( false );
  888. // On the client side we remove it from the scene graph
  889. // to disable rendering and volume queries.
  890. if ( isClientObject() )
  891. removeFromScene();
  892. // Stop doing tick processing for this SceneObject.
  893. setProcessTick( false );
  894. PhysicsShapeData *db = getDataBlock();
  895. if ( !db )
  896. return;
  897. const MatrixF &mat = getTransform();
  898. if ( isServerObject() )
  899. {
  900. // We only create the destroyed object on the server
  901. // and let ghosting deal with updating the client.
  902. if ( db->destroyedShape )
  903. {
  904. mDestroyedShape = new PhysicsShape();
  905. mDestroyedShape->setDataBlock( db->destroyedShape );
  906. mDestroyedShape->setTransform( mat );
  907. if ( !mDestroyedShape->registerObject() )
  908. delete mDestroyedShape.getObject();
  909. }
  910. return;
  911. }
  912. // Let the physics debris create itself.
  913. PhysicsDebris::create( db->debris, mat, lastLinVel );
  914. if ( db->explosion )
  915. {
  916. Explosion *splod = new Explosion();
  917. splod->setDataBlock( db->explosion );
  918. splod->setTransform( mat );
  919. splod->setInitialState( getPosition(), mat.getUpVector(), 1.0f );
  920. if ( !splod->registerObject() )
  921. delete splod;
  922. }
  923. }
  924. void PhysicsShape::restore()
  925. {
  926. if ( !mDestroyed )
  927. return;
  928. PhysicsShapeData *db = getDataBlock();
  929. const bool isDynamic = db && db->mass > 0.0f;
  930. if ( mDestroyedShape )
  931. mDestroyedShape->deleteObject();
  932. // Restore tick processing, add it back to
  933. // the scene, and enable collision and simulation.
  934. setProcessTick( isDynamic || mPlayAmbient );
  935. if ( isClientObject() )
  936. addToScene();
  937. mPhysicsRep->setSimulationEnabled( true );
  938. mDestroyed = false;
  939. setMaskBits( DamageMask );
  940. }
  941. DefineEngineMethod( PhysicsShape, isDestroyed, bool, (),,
  942. "@brief Returns if a PhysicsShape has been destroyed or not.\n\n" )
  943. {
  944. return object->isDestroyed();
  945. }
  946. DefineEngineMethod( PhysicsShape, destroy, void, (),,
  947. "@brief Disables rendering and physical simulation.\n\n"
  948. "Calling destroy() will also spawn any explosions, debris, and/or destroyedShape "
  949. "defined for it, as well as remove it from the scene graph.\n\n"
  950. "Destroyed objects are only created on the server. Ghosting will later update the client.\n\n"
  951. "@note This does not actually delete the PhysicsShape." )
  952. {
  953. object->destroy();
  954. }
  955. DefineEngineMethod( PhysicsShape, restore, void, (),,
  956. "@brief Restores the shape to its state before being destroyed.\n\n"
  957. "Re-enables rendering and physical simulation on the object and "
  958. "adds it to the client's scene graph. "
  959. "Has no effect if the shape is not destroyed.\n\n")
  960. {
  961. object->restore();
  962. }
  963. DefineEngineMethod( PhysicsShape, applyTorque, void, (Point3F torque), ,
  964. "@brief Add a torque to a dynamic physics shape.\n\n"
  965. "@param torque to apply to the dynamic physics shape\n"
  966. "@note This value is ignored on physics shapes that are not dynamic. Wakes up the dynamic physics shape if it is sleeping.\n")
  967. {
  968. object->applyTorque( torque );
  969. }
  970. DefineEngineMethod(PhysicsShape, applyForce, void, (Point3F force), ,
  971. "@brief Add a force to a dynamic physics shape.\n\n"
  972. "@param force to apply to the dynamic physics shape\n"
  973. "@note This value is ignored on physics shapes that are not dynamic. Wakes up the dynamic physics shape if it is sleeping.\n")
  974. {
  975. object->applyForce( force );
  976. }