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