rigidShape.cpp 60 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844
  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/rigidShape.h"
  24. #include "app/game.h"
  25. #include "math/mMath.h"
  26. #include "console/simBase.h"
  27. #include "console/console.h"
  28. #include "console/consoleTypes.h"
  29. #include "collision/clippedPolyList.h"
  30. #include "collision/planeExtractor.h"
  31. #include "T3D/gameBase/moveManager.h"
  32. #include "core/stream/bitStream.h"
  33. #include "core/dnet.h"
  34. #include "T3D/gameBase/gameConnection.h"
  35. #include "ts/tsShapeInstance.h"
  36. #include "math/mathIO.h"
  37. #include "scene/sceneRenderState.h"
  38. #include "scene/sceneManager.h"
  39. #include "T3D/fx/cameraFXMgr.h"
  40. #include "T3D/trigger.h"
  41. #include "T3D/item.h"
  42. #include "gfx/primBuilder.h"
  43. #include "gfx/gfxDrawUtil.h"
  44. #include "sfx/sfxTypes.h"
  45. #include "sfx/sfxSystem.h"
  46. #include "T3D/fx/particleEmitter.h"
  47. #include "console/engineAPI.h"
  48. #include "T3D/physics/physicsPlugin.h"
  49. #include "T3D/physics/physicsCollision.h"
  50. IMPLEMENT_CO_DATABLOCK_V1(RigidShapeData);
  51. ConsoleDocClass( RigidShapeData,
  52. "@brief Defines the physics properties for an individual RigidShapeData physics object.\n\n"
  53. "@tsexample\n"
  54. " datablock RigidShapeData( BouncingBoulder )\n"
  55. " {\n"
  56. " category = \"RigidShape\";\n"
  57. "\n"
  58. " shapeFile = \"~/data/shapes/boulder/boulder.dts\";\n"
  59. " emap = true;\n"
  60. "\n"
  61. " // Rigid Body\n"
  62. " mass = 500;\n"
  63. " massCenter = \"0 0 0\"; // Center of mass for rigid body\n"
  64. " massBox = \"0 0 0\"; // Size of box used for moment of inertia,\n"
  65. " // if zero it defaults to object bounding box\n"
  66. " drag = 0.2; // Drag coefficient\n"
  67. " bodyFriction = 0.2;\n"
  68. " bodyRestitution = 0.1;\n"
  69. " minImpactSpeed = 5; // Impacts over this invoke the script callback\n"
  70. " softImpactSpeed = 5; // Play SoftImpact Sound\n"
  71. " hardImpactSpeed = 15; // Play HardImpact Sound\n"
  72. " integration = 4; // Physics integration: TickSec/Rate\n"
  73. " collisionTol = 0.1; // Collision distance tolerance\n"
  74. " contactTol = 0.1; // Contact velocity tolerance\n"
  75. "\n"
  76. " minRollSpeed = 10;\n"
  77. "\n"
  78. " maxDrag = 0.5;\n"
  79. " minDrag = 0.01;\n"
  80. "\n"
  81. " dustHeight = 10;\n"
  82. "\n"
  83. " dragForce = 0.05;\n"
  84. " vertFactor = 0.05;\n"
  85. " };\n"
  86. "@endtsexample\n\n"
  87. "@see RigidShape\n"
  88. "@see ShapeBase\n\n"
  89. "@ingroup Physics\n"
  90. );
  91. IMPLEMENT_CO_NETOBJECT_V1(RigidShape);
  92. ConsoleDocClass( RigidShape,
  93. "@brief The RigidShape class implements rigid-body physics for DTS objects in the world.\n\n"
  94. "\"Rigid body physics\" refers to a system whereby objects are assumed to have a finite size,\n"
  95. "equally distributed masses, and where deformations of the objects themselves are not accounted for.\n"
  96. "Uses the RigidShape class to control its physics.\n\n"
  97. "@tsexample\n"
  98. " datablock RigidShapeData( BouncingBoulder )\n"
  99. " {\n"
  100. " category = \"RigidShape\";\n"
  101. "\n"
  102. " shapeFile = \"~/data/shapes/boulder/boulder.dts\";\n"
  103. " emap = true;\n"
  104. "\n"
  105. " // Rigid Body\n"
  106. " mass = 500;\n"
  107. " massCenter = \"0 0 0\"; // Center of mass for rigid body\n"
  108. " massBox = \"0 0 0\"; // Size of box used for moment of inertia,\n"
  109. " // if zero it defaults to object bounding box\n"
  110. " drag = 0.2; // Drag coefficient\n"
  111. " bodyFriction = 0.2;\n"
  112. " bodyRestitution = 0.1;\n"
  113. " minImpactSpeed = 5; // Impacts over this invoke the script callback\n"
  114. " softImpactSpeed = 5; // Play SoftImpact Sound\n"
  115. " hardImpactSpeed = 15; // Play HardImpact Sound\n"
  116. " integration = 4; // Physics integration: TickSec/Rate\n"
  117. " collisionTol = 0.1; // Collision distance tolerance\n"
  118. " contactTol = 0.1; // Contact velocity tolerance\n"
  119. "\n"
  120. " minRollSpeed = 10;\n"
  121. "\n"
  122. " maxDrag = 0.5;\n"
  123. " minDrag = 0.01;\n"
  124. "\n"
  125. " dustHeight = 10;\n"
  126. "\n"
  127. " dragForce = 0.05;\n"
  128. " vertFactor = 0.05;\n"
  129. " };\n"
  130. "\n"
  131. " new RigidShape()\n"
  132. " {\n"
  133. " dataBlock = \"BouncingBoulder\";\n"
  134. " parentGroup = EWCreatorWindow.objectGroup;\n"
  135. " };\n"
  136. "@endtsexample\n\n"
  137. "@see RigidShapeData\n"
  138. "@see ShapeBase\n\n"
  139. "@ingroup Physics\n"
  140. );
  141. IMPLEMENT_CALLBACK(RigidShapeData, onEnterLiquid, void, (RigidShape* obj, F32 coverage, const char* type), (obj, coverage, type),
  142. "Called when the vehicle enters liquid.\n"
  143. "@param obj the Vehicle object\n"
  144. "@param coverage percentage of the vehicle's bounding box covered by the liquid\n"
  145. "@param type type of liquid the vehicle has entered\n");
  146. IMPLEMENT_CALLBACK(RigidShapeData, onLeaveLiquid, void, (RigidShape* obj, const char* type), (obj, type),
  147. "Called when the vehicle leaves liquid.\n"
  148. "@param obj the Vehicle object\n"
  149. "@param type type of liquid the vehicle has left\n");
  150. //----------------------------------------------------------------------------
  151. namespace {
  152. static U32 sWorkingQueryBoxStaleThreshold = 10; // The maximum number of ticks that go by before
  153. // the mWorkingQueryBox is considered stale and
  154. // needs updating. Set to -1 to disable.
  155. static F32 sWorkingQueryBoxSizeMultiplier = 2.0f; // How much larger should the mWorkingQueryBox be
  156. // made when updating the working collision list.
  157. // The larger this number the less often the working list
  158. // will be updated due to motion, but any non-static shape
  159. // that moves into the query box will not be noticed.
  160. // Client prediction
  161. const S32 sMaxWarpTicks = 3; // Max warp duration in ticks
  162. const S32 sMaxPredictionTicks = 30; // Number of ticks to predict
  163. // Physics and collision constants
  164. static F32 sRestTol = 0.5; // % of gravity energy to be at rest
  165. static S32 sRestCount = 10; // Consecutive ticks before comming to rest
  166. const U32 sCollisionMoveMask = ( TerrainObjectType | PlayerObjectType |
  167. StaticShapeObjectType | VehicleObjectType |
  168. VehicleBlockerObjectType );
  169. const U32 sServerCollisionMask = sCollisionMoveMask; // ItemObjectType
  170. const U32 sClientCollisionMask = sCollisionMoveMask;
  171. void nonFilter(SceneObject* object,void *key)
  172. {
  173. SceneContainer::CallbackInfo* info = reinterpret_cast<SceneContainer::CallbackInfo*>(key);
  174. object->buildPolyList(info->context,info->polyList,info->boundingBox,info->boundingSphere);
  175. }
  176. } // namespace {}
  177. // Trigger objects that are not normally collided with.
  178. static U32 sTriggerMask = ItemObjectType |
  179. TriggerObjectType |
  180. CorpseObjectType;
  181. //----------------------------------------------------------------------------
  182. RigidShapeData::RigidShapeData()
  183. {
  184. shadowEnable = true;
  185. body.friction = 0;
  186. body.restitution = 1;
  187. minImpactSpeed = 25;
  188. softImpactSpeed = 25;
  189. hardImpactSpeed = 50;
  190. minRollSpeed = 0;
  191. cameraRoll = true;
  192. cameraLag = 0;
  193. cameraDecay = 0;
  194. cameraOffset = 0;
  195. minDrag = 0;
  196. maxDrag = 0;
  197. integration = 1;
  198. collisionTol = 0.1f;
  199. contactTol = 0.1f;
  200. massCenter.set(0,0,0);
  201. massBox.set(0,0,0);
  202. drag = 0.7f;
  203. density = 4;
  204. for (S32 i = 0; i < Body::MaxSounds; i++)
  205. INIT_ASSET_ARRAY(BodySounds, i);
  206. dustEmitter = NULL;
  207. dustID = 0;
  208. triggerDustHeight = 3.0;
  209. dustHeight = 1.0;
  210. dMemset( splashEmitterList, 0, sizeof( splashEmitterList ) );
  211. dMemset( splashEmitterIDList, 0, sizeof( splashEmitterIDList ) );
  212. splashFreqMod = 300.0;
  213. splashVelEpsilon = 0.50;
  214. exitSplashSoundVel = 2.0;
  215. softSplashSoundVel = 1.0;
  216. medSplashSoundVel = 2.0;
  217. hardSplashSoundVel = 3.0;
  218. enablePhysicsRep = true;
  219. for (S32 i = 0; i < Sounds::MaxSounds; i++)
  220. INIT_ASSET_ARRAY(WaterSounds, i);
  221. dragForce = 0;
  222. vertFactor = 0.25;
  223. dustTrailEmitter = NULL;
  224. dustTrailID = 0;
  225. _setShape(ShapeAsset::smNoShapeAssetFallback);
  226. }
  227. RigidShapeData::~RigidShapeData()
  228. {
  229. }
  230. //----------------------------------------------------------------------------
  231. bool RigidShapeData::onAdd()
  232. {
  233. if(!Parent::onAdd())
  234. return false;
  235. return true;
  236. }
  237. bool RigidShapeData::preload(bool server, String &errorStr)
  238. {
  239. if (!Parent::preload(server, errorStr))
  240. return false;
  241. // RigidShape objects must define a collision detail
  242. if (!collisionDetails.size() || collisionDetails[0] == -1)
  243. {
  244. Con::errorf("RigidShapeData::preload failed: Rigid shapes must define a collision-1 detail");
  245. errorStr = String::ToString("RigidShapeData: Couldn't load shape asset \"%s\"", mShapeAsset.getAssetId());
  246. return false;
  247. }
  248. // Resolve objects transmitted from server
  249. if (!server) {
  250. for (S32 i = 0; i < Body::MaxSounds; i++)
  251. {
  252. if (mBodySounds[i])
  253. {
  254. _setBodySounds(getBodySounds(i), i);
  255. }
  256. }
  257. for (S32 j = 0; j < Sounds::MaxSounds; j++)
  258. {
  259. if (mWaterSounds[j])
  260. {
  261. _setWaterSounds(getWaterSounds(j), j);
  262. }
  263. }
  264. }
  265. if( !dustEmitter && dustID != 0 )
  266. {
  267. if( !Sim::findObject( dustID, dustEmitter ) )
  268. {
  269. Con::errorf( ConsoleLogEntry::General, "RigidShapeData::preload Invalid packet, bad datablockId(dustEmitter): 0x%x", dustID );
  270. }
  271. }
  272. U32 i;
  273. for( i=0; i<VC_NUM_SPLASH_EMITTERS; i++ )
  274. {
  275. if( !splashEmitterList[i] && splashEmitterIDList[i] != 0 )
  276. {
  277. if( !Sim::findObject( splashEmitterIDList[i], splashEmitterList[i] ) )
  278. {
  279. Con::errorf( ConsoleLogEntry::General, "RigidShapeData::preload Invalid packet, bad datablockId(splashEmitter): 0x%x", splashEmitterIDList[i] );
  280. }
  281. }
  282. }
  283. if (dragForce <= 0.01f)
  284. {
  285. Con::warnf("RigidShapeData::preload: dragForce must be at least 0.01");
  286. dragForce = 0.01f;
  287. }
  288. if (vertFactor < 0.0f || vertFactor > 1.0f)
  289. {
  290. Con::warnf("RigidShapeData::preload: vert factor must be [0, 1]");
  291. vertFactor = vertFactor < 0.0f ? 0.0f : 1.0f;
  292. }
  293. if( !dustTrailEmitter && dustTrailID != 0 )
  294. {
  295. if( !Sim::findObject( dustTrailID, dustTrailEmitter ) )
  296. {
  297. Con::errorf( ConsoleLogEntry::General, "RigidShapeData::preload Invalid packet, bad datablockId(dustTrailEmitter): 0x%x", dustTrailID );
  298. }
  299. }
  300. return true;
  301. }
  302. //----------------------------------------------------------------------------
  303. void RigidShapeData::packData(BitStream* stream)
  304. {
  305. Parent::packData(stream);
  306. stream->write(body.restitution);
  307. stream->write(body.friction);
  308. for (U32 i = 0; i < Body::MaxSounds; ++i)
  309. {
  310. PACKDATA_ASSET_ARRAY(BodySounds, i);
  311. }
  312. stream->write(minImpactSpeed);
  313. stream->write(softImpactSpeed);
  314. stream->write(hardImpactSpeed);
  315. stream->write(minRollSpeed);
  316. stream->write(maxDrag);
  317. stream->write(minDrag);
  318. stream->write(integration);
  319. stream->write(collisionTol);
  320. stream->write(contactTol);
  321. mathWrite(*stream,massCenter);
  322. mathWrite(*stream,massBox);
  323. stream->writeFlag(cameraRoll);
  324. stream->write(cameraLag);
  325. stream->write(cameraDecay);
  326. stream->write(cameraOffset);
  327. stream->write( dustHeight );
  328. stream->write(exitSplashSoundVel);
  329. stream->write(softSplashSoundVel);
  330. stream->write(medSplashSoundVel);
  331. stream->write(hardSplashSoundVel);
  332. stream->write(enablePhysicsRep);
  333. // write the water sound profiles
  334. for (U32 i = 0; i < Sounds::MaxSounds; ++i)
  335. {
  336. PACKDATA_ASSET_ARRAY(WaterSounds, i);
  337. }
  338. if (stream->writeFlag( dustEmitter ))
  339. stream->writeRangedU32( dustEmitter->getId(), DataBlockObjectIdFirst, DataBlockObjectIdLast );
  340. for( U32 i = 0; i < VC_NUM_SPLASH_EMITTERS; ++ i )
  341. {
  342. if( stream->writeFlag( splashEmitterList[i] != NULL ) )
  343. stream->writeRangedU32( splashEmitterList[i]->getId(), DataBlockObjectIdFirst, DataBlockObjectIdLast );
  344. }
  345. stream->write(splashFreqMod);
  346. stream->write(splashVelEpsilon);
  347. stream->write(dragForce);
  348. stream->write(vertFactor);
  349. if (stream->writeFlag( dustTrailEmitter ))
  350. stream->writeRangedU32( dustTrailEmitter->getId(), DataBlockObjectIdFirst, DataBlockObjectIdLast );
  351. }
  352. void RigidShapeData::unpackData(BitStream* stream)
  353. {
  354. Parent::unpackData(stream);
  355. stream->read(&body.restitution);
  356. stream->read(&body.friction);
  357. for (U32 i = 0; i < Body::Sounds::MaxSounds; i++)
  358. {
  359. UNPACKDATA_ASSET_ARRAY(BodySounds, i);
  360. }
  361. stream->read(&minImpactSpeed);
  362. stream->read(&softImpactSpeed);
  363. stream->read(&hardImpactSpeed);
  364. stream->read(&minRollSpeed);
  365. stream->read(&maxDrag);
  366. stream->read(&minDrag);
  367. stream->read(&integration);
  368. stream->read(&collisionTol);
  369. stream->read(&contactTol);
  370. mathRead(*stream,&massCenter);
  371. mathRead(*stream,&massBox);
  372. cameraRoll = stream->readFlag();
  373. stream->read(&cameraLag);
  374. stream->read(&cameraDecay);
  375. stream->read(&cameraOffset);
  376. stream->read( &dustHeight );
  377. stream->read(&exitSplashSoundVel);
  378. stream->read(&softSplashSoundVel);
  379. stream->read(&medSplashSoundVel);
  380. stream->read(&hardSplashSoundVel);
  381. stream->read(&enablePhysicsRep);
  382. // write the water sound profiles
  383. for (U32 i = 0; i < Sounds::MaxSounds; ++i)
  384. {
  385. UNPACKDATA_ASSET_ARRAY(WaterSounds, i);
  386. }
  387. if( stream->readFlag() )
  388. dustID = (S32) stream->readRangedU32(DataBlockObjectIdFirst, DataBlockObjectIdLast);
  389. for( U32 i = 0; i < VC_NUM_SPLASH_EMITTERS; ++ i )
  390. {
  391. if( stream->readFlag() )
  392. splashEmitterIDList[i] = stream->readRangedU32( DataBlockObjectIdFirst, DataBlockObjectIdLast );
  393. }
  394. stream->read(&splashFreqMod);
  395. stream->read(&splashVelEpsilon);
  396. stream->read(&dragForce);
  397. stream->read(&vertFactor);
  398. if( stream->readFlag() )
  399. dustTrailID = (S32) stream->readRangedU32(DataBlockObjectIdFirst, DataBlockObjectIdLast);
  400. }
  401. //----------------------------------------------------------------------------
  402. void RigidShapeData::initPersistFields()
  403. {
  404. addGroup("Physics");
  405. addField("enablePhysicsRep", TypeBool, Offset(enablePhysicsRep, RigidShapeData),
  406. "@brief Creates a representation of the object in the physics plugin.\n");
  407. endGroup("Physics");
  408. addField("massCenter", TypePoint3F, Offset(massCenter, RigidShapeData), "Center of mass for rigid body.");
  409. addField("massBox", TypePoint3F, Offset(massBox, RigidShapeData), "Size of inertial box.");
  410. addField("bodyRestitution", TypeF32, Offset(body.restitution, RigidShapeData), "The percentage of kinetic energy kept by this object in a collision.");
  411. addField("bodyFriction", TypeF32, Offset(body.friction, RigidShapeData), "How much friction this object has. Lower values will cause the object to appear to be more slippery.");
  412. addField("minImpactSpeed", TypeF32, Offset(minImpactSpeed, RigidShapeData),
  413. "Minimum collision speed to classify collision as impact (triggers onImpact on server object)." );
  414. addField("softImpactSpeed", TypeF32, Offset(softImpactSpeed, RigidShapeData), "Minimum speed at which this object must be travelling for the soft impact sound to be played.");
  415. addField("hardImpactSpeed", TypeF32, Offset(hardImpactSpeed, RigidShapeData), "Minimum speed at which the object must be travelling for the hard impact sound to be played.");
  416. addField("minRollSpeed", TypeF32, Offset(minRollSpeed, RigidShapeData));
  417. addField("maxDrag", TypeF32, Offset(maxDrag, RigidShapeData), "Maximum drag available to this object.");
  418. addField("minDrag", TypeF32, Offset(minDrag, RigidShapeData), "Minimum drag available to this object.");
  419. addField("integration", TypeS32, Offset(integration, RigidShapeData), "Number of physics steps to process per tick.");
  420. addField("collisionTol", TypeF32, Offset(collisionTol, RigidShapeData), "Collision distance tolerance.");
  421. addField("contactTol", TypeF32, Offset(contactTol, RigidShapeData), "Contact velocity tolerance.");
  422. addGroup( "Forces" );
  423. addField("dragForce", TypeF32, Offset(dragForce, RigidShapeData), "Used to simulate the constant drag acting on the object");
  424. addField("vertFactor", TypeF32, Offset(vertFactor, RigidShapeData), "The scalar applied to the vertical portion of the velocity drag acting on a object.");
  425. endGroup( "Forces" );
  426. addGroup( "Particle Effects" );
  427. addField("dustEmitter", TYPEID< ParticleEmitterData >(), Offset(dustEmitter, RigidShapeData), "Array of pointers to ParticleEmitterData datablocks which will be used to emit particles at object/terrain contact point.\n");
  428. addField("triggerDustHeight", TypeF32, Offset(triggerDustHeight, RigidShapeData), "Maximum height from the ground at which the object will generate dust.\n");
  429. addField("dustHeight", TypeF32, Offset(dustHeight, RigidShapeData), "Height of dust effects.\n");
  430. addField("dustTrailEmitter", TYPEID< ParticleEmitterData >(), Offset(dustTrailEmitter, RigidShapeData), "Particle emitter used to create a dust trail for the moving object.\n");
  431. addField("splashEmitter", TYPEID< ParticleEmitterData >(), Offset(splashEmitterList, RigidShapeData), VC_NUM_SPLASH_EMITTERS, "Array of pointers to ParticleEmitterData datablocks which will generate splash effects.\n");
  432. addField("splashFreqMod", TypeF32, Offset(splashFreqMod, RigidShapeData), "The simulated frequency modulation of a splash generated by this object. Multiplied along with speed and time elapsed when determining splash emition rate.\n");
  433. addField("splashVelEpsilon", TypeF32, Offset(splashVelEpsilon, RigidShapeData), "The threshold speed at which we consider the object's movement to have stopped when updating splash effects.\n");
  434. endGroup( "Particle Effects" );
  435. addGroup( "Sounds" );
  436. INITPERSISTFIELD_SOUNDASSET_ARRAY(BodySounds, Body::Sounds::MaxSounds, RigidShapeData, "Sounds for body.");
  437. addField("exitSplashSoundVelocity", TypeF32, Offset(exitSplashSoundVel, RigidShapeData), "The minimum velocity at which the exit splash sound will be played when emerging from water.\n");
  438. addField("softSplashSoundVelocity", TypeF32, Offset(softSplashSoundVel, RigidShapeData),"The minimum velocity at which the soft splash sound will be played when impacting water.\n");
  439. addField("mediumSplashSoundVelocity", TypeF32, Offset(medSplashSoundVel, RigidShapeData), "The minimum velocity at which the medium splash sound will be played when impacting water.\n");
  440. addField("hardSplashSoundVelocity", TypeF32, Offset(hardSplashSoundVel, RigidShapeData), "The minimum velocity at which the hard splash sound will be played when impacting water.\n");
  441. INITPERSISTFIELD_SOUNDASSET_ARRAY(WaterSounds, Sounds::MaxSounds, RigidShapeData, "Sounds for interacting with water.");
  442. endGroup( "Sounds" );
  443. addGroup( "Camera" );
  444. addField("cameraRoll", TypeBool, Offset(cameraRoll, RigidShapeData), "Specifies whether the camera's rotation matrix, and the render eye transform are multiplied during camera updates.\n");
  445. addField("cameraLag", TypeF32, Offset(cameraLag, RigidShapeData), "Scalar amount by which the third person camera lags the object, relative to the object's linear velocity.\n");
  446. addField("cameraDecay", TypeF32, Offset(cameraDecay, RigidShapeData), "Scalar rate at which the third person camera offset decays, per tick.\n");
  447. addField("cameraOffset", TypeF32, Offset(cameraOffset, RigidShapeData), "The vertical offset of the object's camera.\n");
  448. endGroup( "Camera" );
  449. Parent::initPersistFields();
  450. }
  451. //----------------------------------------------------------------------------
  452. //----------------------------------------------------------------------------
  453. //----------------------------------------------------------------------------
  454. RigidShape::RigidShape()
  455. {
  456. mNetFlags.set(Ghostable);
  457. mDustTrailEmitter = NULL;
  458. mDataBlock = 0;
  459. // [rene, 27-Apr-11] WTH is a RigidShape a vehicle???
  460. mTypeMask |= VehicleObjectType | DynamicShapeObjectType;
  461. mDelta.pos = Point3F(0,0,0);
  462. mDelta.posVec = Point3F(0,0,0);
  463. mDelta.warpTicks = mDelta.warpCount = 0;
  464. mDelta.dt = 1;
  465. mDelta.move = NullMove;
  466. mPredictionCount = 0;
  467. mDelta.cameraOffset.set(0,0,0);
  468. mDelta.cameraVec.set(0,0,0);
  469. mDelta.cameraRot.set(0,0,0);
  470. mDelta.cameraRotVec.set(0,0,0);
  471. mRigid.linPosition.set(0, 0, 0);
  472. mRigid.linVelocity.set(0, 0, 0);
  473. mRigid.angPosition.identity();
  474. mRigid.angVelocity.set(0, 0, 0);
  475. mRigid.linMomentum.set(0, 0, 0);
  476. mRigid.angMomentum.set(0, 0, 0);
  477. mContacts.clear();
  478. mCameraOffset.set(0,0,0);
  479. dMemset( mDustEmitterList, 0, sizeof( mDustEmitterList ) );
  480. dMemset( mSplashEmitterList, 0, sizeof( mSplashEmitterList ) );
  481. mDisableMove = false; // start frozen by default
  482. restCount = 0;
  483. inLiquid = false;
  484. mWorkingQueryBox.minExtents.set(-1e9f, -1e9f, -1e9f);
  485. mWorkingQueryBox.maxExtents.set(-1e9f, -1e9f, -1e9f);
  486. mWorkingQueryBoxCountDown = sWorkingQueryBoxStaleThreshold;
  487. mPhysicsRep = NULL;
  488. }
  489. RigidShape::~RigidShape()
  490. {
  491. //
  492. }
  493. U32 RigidShape::getCollisionMask()
  494. {
  495. if (isServerObject())
  496. return sServerCollisionMask;
  497. else
  498. return sClientCollisionMask;
  499. }
  500. Point3F RigidShape::getVelocity() const
  501. {
  502. return mRigid.linVelocity;
  503. }
  504. //----------------------------------------------------------------------------
  505. bool RigidShape::onAdd()
  506. {
  507. if (!Parent::onAdd())
  508. return false;
  509. mWorkingQueryBox.minExtents.set(-1e9f, -1e9f, -1e9f);
  510. mWorkingQueryBox.maxExtents.set(-1e9f, -1e9f, -1e9f);
  511. // When loading from a mission script, the base SceneObject's transform
  512. // will have been set and needs to be transfered to the rigid body.
  513. mRigid.setTransform(mObjToWorld);
  514. // Initialize interpolation vars.
  515. mDelta.rot[1] = mDelta.rot[0] = mRigid.angPosition;
  516. mDelta.pos = mRigid.linPosition;
  517. mDelta.posVec = Point3F(0,0,0);
  518. // Create Emitters on the client
  519. if( isClientObject() )
  520. {
  521. if( mDataBlock->dustEmitter )
  522. {
  523. for( U32 i=0; i<RigidShapeData::VC_NUM_DUST_EMITTERS; i++ )
  524. {
  525. mDustEmitterList[i] = new ParticleEmitter;
  526. mDustEmitterList[i]->onNewDataBlock( mDataBlock->dustEmitter, false );
  527. if( !mDustEmitterList[i]->registerObject() )
  528. {
  529. Con::warnf( ConsoleLogEntry::General, "Could not register dust emitter for class: %s", mDataBlock->getName() );
  530. delete mDustEmitterList[i];
  531. mDustEmitterList[i] = NULL;
  532. }
  533. }
  534. }
  535. for( U32 j=0; j<RigidShapeData::VC_NUM_SPLASH_EMITTERS; j++ )
  536. {
  537. if( mDataBlock->splashEmitterList[j] )
  538. {
  539. mSplashEmitterList[j] = new ParticleEmitter;
  540. mSplashEmitterList[j]->onNewDataBlock( mDataBlock->splashEmitterList[j], false );
  541. if( !mSplashEmitterList[j]->registerObject() )
  542. {
  543. Con::warnf( ConsoleLogEntry::General, "Could not register splash emitter for class: %s", mDataBlock->getName() );
  544. delete mSplashEmitterList[j];
  545. mSplashEmitterList[j] = NULL;
  546. }
  547. }
  548. }
  549. }
  550. // Create a new convex.
  551. AssertFatal(mDataBlock->collisionDetails[0] != -1, "Error, a rigid shape must have a collision-1 detail!");
  552. mConvex.mObject = this;
  553. mConvex.pShapeBase = this;
  554. mConvex.hullId = 0;
  555. mConvex.box = mObjBox;
  556. mConvex.box.minExtents.convolve(mObjScale);
  557. mConvex.box.maxExtents.convolve(mObjScale);
  558. mConvex.findNodeTransform();
  559. _createPhysics();
  560. addToScene();
  561. if( !isServerObject() )
  562. {
  563. if( mDataBlock->dustTrailEmitter )
  564. {
  565. mDustTrailEmitter = new ParticleEmitter;
  566. mDustTrailEmitter->onNewDataBlock( mDataBlock->dustTrailEmitter, false );
  567. if( !mDustTrailEmitter->registerObject() )
  568. {
  569. Con::warnf( ConsoleLogEntry::General, "Could not register dust emitter for class: %s", mDataBlock->getName() );
  570. delete mDustTrailEmitter;
  571. mDustTrailEmitter = NULL;
  572. }
  573. }
  574. }
  575. if (isServerObject())
  576. scriptOnAdd();
  577. return true;
  578. }
  579. void RigidShape::onRemove()
  580. {
  581. scriptOnRemove();
  582. removeFromScene();
  583. U32 i=0;
  584. for( i=0; i<RigidShapeData::VC_NUM_DUST_EMITTERS; i++ )
  585. {
  586. if( mDustEmitterList[i] )
  587. {
  588. mDustEmitterList[i]->deleteWhenEmpty();
  589. mDustEmitterList[i] = NULL;
  590. }
  591. }
  592. for( i=0; i<RigidShapeData::VC_NUM_SPLASH_EMITTERS; i++ )
  593. {
  594. if( mSplashEmitterList[i] )
  595. {
  596. mSplashEmitterList[i]->deleteWhenEmpty();
  597. mSplashEmitterList[i] = NULL;
  598. }
  599. }
  600. mWorkingQueryBox.minExtents.set(-1e9f, -1e9f, -1e9f);
  601. mWorkingQueryBox.maxExtents.set(-1e9f, -1e9f, -1e9f);
  602. Parent::onRemove();
  603. }
  604. void RigidShape::_createPhysics()
  605. {
  606. SAFE_DELETE(mPhysicsRep);
  607. if (!PHYSICSMGR || !mDataBlock->enablePhysicsRep)
  608. return;
  609. TSShape* shape = mShapeInstance->getShape();
  610. PhysicsCollision* colShape = NULL;
  611. colShape = shape->buildColShape(false, getScale());
  612. if (colShape)
  613. {
  614. PhysicsWorld* world = PHYSICSMGR->getWorld(isServerObject() ? "server" : "client");
  615. mPhysicsRep = PHYSICSMGR->createBody();
  616. mPhysicsRep->init(colShape, 0, PhysicsBody::BF_KINEMATIC, this, world);
  617. mPhysicsRep->setTransform(getTransform());
  618. }
  619. }
  620. //----------------------------------------------------------------------------
  621. void RigidShape::processTick(const Move* move)
  622. {
  623. PROFILE_SCOPE(RigidShape_ProcessTick);
  624. Parent::processTick(move);
  625. if ( isMounted() )
  626. return;
  627. // Warp to catch up to server
  628. if (mDelta.warpCount < mDelta.warpTicks)
  629. {
  630. mDelta.warpCount++;
  631. // Set new pos.
  632. mObjToWorld.getColumn(3,&mDelta.pos);
  633. mDelta.pos += mDelta.warpOffset;
  634. mDelta.rot[0] = mDelta.rot[1];
  635. mDelta.rot[1].interpolate(mDelta.warpRot[0],mDelta.warpRot[1],F32(mDelta.warpCount)/mDelta.warpTicks);
  636. setPosition(mDelta.pos,mDelta.rot[1]);
  637. // Pos backstepping
  638. mDelta.posVec.x = -mDelta.warpOffset.x;
  639. mDelta.posVec.y = -mDelta.warpOffset.y;
  640. mDelta.posVec.z = -mDelta.warpOffset.z;
  641. }
  642. else
  643. {
  644. if (!move)
  645. {
  646. if (isGhost())
  647. {
  648. // If we haven't run out of prediction time,
  649. // predict using the last known move.
  650. if (mPredictionCount-- <= 0)
  651. return;
  652. move = &mDelta.move;
  653. }
  654. else
  655. move = &NullMove;
  656. }
  657. // Process input move
  658. updateMove(move);
  659. // Save current rigid state interpolation
  660. mDelta.posVec = mRigid.linPosition;
  661. mDelta.rot[0] = mRigid.angPosition;
  662. // Update the physics based on the integration rate
  663. S32 count = mDataBlock->integration;
  664. --mWorkingQueryBoxCountDown;
  665. if (!mDisableMove)
  666. updateWorkingCollisionSet(getCollisionMask());
  667. for (U32 i = 0; i < count; i++)
  668. updatePos(TickSec / count);
  669. // Wrap up interpolation info
  670. mDelta.pos = mRigid.linPosition;
  671. mDelta.posVec -= mRigid.linPosition;
  672. mDelta.rot[1] = mRigid.angPosition;
  673. // Update container database
  674. setPosition(mRigid.linPosition, mRigid.angPosition);
  675. setMaskBits(PositionMask);
  676. updateContainer();
  677. //TODO: Only update when position has actually changed
  678. //no need to check if mDataBlock->enablePhysicsRep is false as mPhysicsRep will be NULL if it is
  679. if (mPhysicsRep)
  680. mPhysicsRep->moveKinematicTo(getTransform());
  681. }
  682. }
  683. void RigidShape::interpolateTick(F32 dt)
  684. {
  685. Parent::interpolateTick(dt);
  686. if ( isMounted() )
  687. return;
  688. if(dt == 0.0f)
  689. setRenderPosition(mDelta.pos, mDelta.rot[1]);
  690. else
  691. {
  692. QuatF rot;
  693. rot.interpolate(mDelta.rot[1], mDelta.rot[0], dt);
  694. Point3F pos = mDelta.pos + mDelta.posVec * dt;
  695. setRenderPosition(pos,rot);
  696. }
  697. mDelta.dt = dt;
  698. }
  699. void RigidShape::advanceTime(F32 dt)
  700. {
  701. Parent::advanceTime(dt);
  702. updateFroth(dt);
  703. if ( isMounted() )
  704. return;
  705. // Update 3rd person camera offset. Camera update is done
  706. // here as it's a client side only animation.
  707. mCameraOffset -=
  708. (mCameraOffset * mDataBlock->cameraDecay +
  709. mRigid.linVelocity * mDataBlock->cameraLag) * dt;
  710. }
  711. //----------------------------------------------------------------------------
  712. bool RigidShape::onNewDataBlock(GameBaseData* dptr, bool reload)
  713. {
  714. mDataBlock = dynamic_cast<RigidShapeData*>(dptr);
  715. if (!mDataBlock || !Parent::onNewDataBlock(dptr, reload))
  716. return false;
  717. // Update Rigid Info
  718. mRigid.mass = mDataBlock->mass;
  719. mRigid.oneOverMass = 1 / mRigid.mass;
  720. mRigid.friction = mDataBlock->body.friction;
  721. mRigid.restitution = mDataBlock->body.restitution;
  722. mRigid.setCenterOfMass(mDataBlock->massCenter);
  723. // Ignores massBox, just set sphere for now. Derived objects
  724. // can set what they want.
  725. mRigid.setObjectInertia();
  726. scriptOnNewDataBlock();
  727. return true;
  728. }
  729. //----------------------------------------------------------------------------
  730. void RigidShape::getCameraParameters(F32 *min,F32* max,Point3F* off,MatrixF* rot)
  731. {
  732. *min = mDataBlock->cameraMinDist;
  733. *max = mDataBlock->cameraMaxDist;
  734. off->set(0,0,mDataBlock->cameraOffset);
  735. rot->identity();
  736. }
  737. //----------------------------------------------------------------------------
  738. void RigidShape::getCameraTransform(F32* pos,MatrixF* mat)
  739. {
  740. // Returns camera to world space transform
  741. // Handles first person / third person camera position
  742. if (isServerObject() && mShapeInstance)
  743. mShapeInstance->animateNodeSubtrees(true);
  744. if (*pos == 0)
  745. {
  746. getRenderEyeTransform(mat);
  747. return;
  748. }
  749. // Get the shape's camera parameters.
  750. F32 min,max;
  751. MatrixF rot;
  752. Point3F offset;
  753. getCameraParameters(&min,&max,&offset,&rot);
  754. // Start with the current eye position
  755. MatrixF eye;
  756. getRenderEyeTransform(&eye);
  757. // Build a transform that points along the eye axis
  758. // but where the Z axis is always up.
  759. if (mDataBlock->cameraRoll)
  760. mat->mul(eye,rot);
  761. else
  762. {
  763. MatrixF cam(1);
  764. VectorF x,y,z(0,0,1);
  765. eye.getColumn(1, &y);
  766. mCross(y, z, &x);
  767. x.normalize();
  768. mCross(x, y, &z);
  769. z.normalize();
  770. cam.setColumn(0,x);
  771. cam.setColumn(1,y);
  772. cam.setColumn(2,z);
  773. mat->mul(cam,rot);
  774. }
  775. // Camera is positioned straight back along the eye's -Y axis.
  776. // A ray is cast to make sure the camera doesn't go through
  777. // anything solid.
  778. VectorF vp,vec;
  779. vp.x = vp.z = 0;
  780. vp.y = -(max - min) * *pos;
  781. eye.mulV(vp,&vec);
  782. // Use the camera node as the starting position if it exists.
  783. Point3F osp,sp;
  784. if (mDataBlock->cameraNode != -1)
  785. {
  786. mShapeInstance->mNodeTransforms[mDataBlock->cameraNode].getColumn(3,&osp);
  787. getRenderTransform().mulP(osp,&sp);
  788. }
  789. else
  790. eye.getColumn(3,&sp);
  791. // Make sure we don't hit ourself...
  792. disableCollision();
  793. if (isMounted())
  794. getObjectMount()->disableCollision();
  795. // Cast the ray into the container database to see if we're going
  796. // to hit anything.
  797. RayInfo collision;
  798. Point3F ep = sp + vec + offset + mCameraOffset;
  799. if (mContainer->castRay(sp, ep,
  800. ~(WaterObjectType | GameBaseObjectType | DefaultObjectType),
  801. &collision) == true)
  802. {
  803. // Shift the collision point back a little to try and
  804. // avoid clipping against the front camera plane.
  805. F32 t = collision.t - (-mDot(vec, collision.normal) / vec.len()) * 0.1;
  806. if (t > 0.0f)
  807. ep = sp + offset + mCameraOffset + (vec * t);
  808. else
  809. eye.getColumn(3,&ep);
  810. }
  811. mat->setColumn(3,ep);
  812. // Re-enable our collision.
  813. if (isMounted())
  814. getObjectMount()->enableCollision();
  815. enableCollision();
  816. // Apply Camera FX.
  817. mat->mul( gCamFXMgr.getTrans() );
  818. }
  819. //----------------------------------------------------------------------------
  820. void RigidShape::getVelocity(const Point3F& r, Point3F* v)
  821. {
  822. mRigid.getVelocity(r, v);
  823. }
  824. void RigidShape::applyImpulse(const Point3F &pos, const Point3F &impulse)
  825. {
  826. Point3F r;
  827. mRigid.getOriginVector(pos,&r);
  828. mRigid.applyImpulse(r, impulse);
  829. }
  830. //----------------------------------------------------------------------------
  831. void RigidShape::updateMove(const Move* move)
  832. {
  833. mDelta.move = *move;
  834. }
  835. //----------------------------------------------------------------------------
  836. void RigidShape::setPosition(const Point3F& pos,const QuatF& rot)
  837. {
  838. MatrixF mat;
  839. rot.setMatrix(&mat);
  840. mat.setColumn(3,pos);
  841. Parent::setTransform(mat);
  842. }
  843. void RigidShape::setRenderPosition(const Point3F& pos, const QuatF& rot)
  844. {
  845. MatrixF mat;
  846. rot.setMatrix(&mat);
  847. mat.setColumn(3,pos);
  848. Parent::setRenderTransform(mat);
  849. }
  850. void RigidShape::setTransform(const MatrixF& newMat)
  851. {
  852. mRigid.setTransform(newMat);
  853. Parent::setTransform(newMat);
  854. mRigid.atRest = false;
  855. mContacts.clear();
  856. }
  857. void RigidShape::forceClientTransform()
  858. {
  859. setMaskBits(ForceMoveMask);
  860. }
  861. //-----------------------------------------------------------------------------
  862. void RigidShape::disableCollision()
  863. {
  864. Parent::disableCollision();
  865. }
  866. void RigidShape::enableCollision()
  867. {
  868. Parent::enableCollision();
  869. }
  870. //----------------------------------------------------------------------------
  871. /** Update the physics
  872. */
  873. void RigidShape::updatePos(F32 dt)
  874. {
  875. PROFILE_SCOPE(RigidShape_UpdatePos);
  876. Point3F origVelocity = mRigid.linVelocity;
  877. // Update internal forces acting on the body.
  878. mRigid.clearForces();
  879. updateForces(dt);
  880. // Update collision information based on our current pos.
  881. bool collided = false;
  882. if (!mRigid.atRest && !mDisableMove)
  883. {
  884. collided = updateCollision(dt);
  885. // Now that all the forces have been processed, lets
  886. // see if we're at rest. Basically, if the kinetic energy of
  887. // the rigid body is less than some percentage of the energy added
  888. // by gravity for a short period, we're considered at rest.
  889. // This should really be part of the rigid class...
  890. if (mCollisionList.getCount())
  891. {
  892. F32 k = mRigid.getKineticEnergy();
  893. F32 G = mNetGravity * dt;
  894. F32 Kg = 0.5 * mRigid.mass * G * G;
  895. if (k < sRestTol * Kg && ++restCount > sRestCount)
  896. mRigid.setAtRest();
  897. }
  898. else
  899. restCount = 0;
  900. }
  901. // Integrate forward
  902. if (!mRigid.atRest && !mDisableMove)
  903. mRigid.integrate(dt);
  904. // Deal with client and server scripting, sounds, etc.
  905. if (isServerObject())
  906. {
  907. // Check triggers and other objects that we normally don't
  908. // collide with. This function must be called before notifyCollision
  909. // as it will queue collision.
  910. checkTriggers();
  911. // Invoke the onCollision notify callback for all the objects
  912. // we've just hit.
  913. notifyCollision();
  914. // Server side impact script callback
  915. if (collided)
  916. {
  917. VectorF collVec = mRigid.linVelocity - origVelocity;
  918. F32 collSpeed = collVec.len();
  919. if (collSpeed > mDataBlock->minImpactSpeed)
  920. onImpact(collVec);
  921. }
  922. // Water script callbacks
  923. if (!inLiquid && mWaterCoverage != 0.0f)
  924. {
  925. mDataBlock->onEnterLiquid_callback(this, mWaterCoverage, mLiquidType.c_str());
  926. inLiquid = true;
  927. }
  928. else if (inLiquid && mWaterCoverage == 0.0f)
  929. {
  930. mDataBlock->onLeaveLiquid_callback(this, mLiquidType.c_str());
  931. inLiquid = false;
  932. }
  933. }
  934. else {
  935. // Play impact sounds on the client.
  936. if (collided) {
  937. F32 collSpeed = (mRigid.linVelocity - origVelocity).len();
  938. S32 impactSound = -1;
  939. if (collSpeed >= mDataBlock->hardImpactSpeed)
  940. impactSound = RigidShapeData::Body::HardImpactSound;
  941. else
  942. if (collSpeed >= mDataBlock->softImpactSpeed)
  943. impactSound = RigidShapeData::Body::SoftImpactSound;
  944. if (impactSound != -1 && mDataBlock->getBodySoundsProfile(impactSound))
  945. SFX->playOnce(mDataBlock->getBodySoundsProfile(impactSound), &getTransform());
  946. }
  947. // Water volume sounds
  948. F32 vSpeed = getVelocity().len();
  949. if (!inLiquid && mWaterCoverage >= 0.8f) {
  950. if (vSpeed >= mDataBlock->hardSplashSoundVel)
  951. SFX->playOnce(mDataBlock->getWaterSoundsProfile(RigidShapeData::ImpactHard), &getTransform());
  952. else
  953. if (vSpeed >= mDataBlock->medSplashSoundVel)
  954. SFX->playOnce(mDataBlock->getWaterSoundsProfile(RigidShapeData::ImpactMedium), &getTransform());
  955. else
  956. if (vSpeed >= mDataBlock->softSplashSoundVel)
  957. SFX->playOnce(mDataBlock->getWaterSoundsProfile(RigidShapeData::ImpactSoft), &getTransform());
  958. inLiquid = true;
  959. }
  960. else
  961. if (inLiquid && mWaterCoverage < 0.8f) {
  962. if (vSpeed >= mDataBlock->exitSplashSoundVel)
  963. SFX->playOnce(mDataBlock->getWaterSoundsProfile(RigidShapeData::ExitWater), &getTransform());
  964. inLiquid = false;
  965. }
  966. }
  967. }
  968. //----------------------------------------------------------------------------
  969. void RigidShape::updateForces(F32 dt)
  970. {
  971. if (mDisableMove) return;
  972. Point3F torque(0, 0, 0);
  973. Point3F force(0, 0, mRigid.mass * mNetGravity);
  974. // Apply drag
  975. Point3F vertDrag = mRigid.linVelocity*Point3F(1, 1, mDataBlock->vertFactor);
  976. force -= vertDrag * mDataBlock->dragForce;
  977. // Add in physical zone force
  978. force += mAppliedForce;
  979. force -= mRigid.linVelocity * mDrag;
  980. torque -= mRigid.angMomentum * mDrag;
  981. mRigid.force = force;
  982. mRigid.torque = torque;
  983. // If we're still atRest, make sure we're not accumulating anything
  984. if (mRigid.atRest)
  985. mRigid.setAtRest();
  986. }
  987. //-----------------------------------------------------------------------------
  988. /** Update collision information
  989. Update the convex state and check for collisions. If the object is in
  990. collision, impact and contact forces are generated.
  991. */
  992. bool RigidShape::updateCollision(F32 dt)
  993. {
  994. // Update collision information
  995. MatrixF mat,cmat;
  996. mConvex.transform = &mat;
  997. mRigid.getTransform(&mat);
  998. cmat = mConvex.getTransform();
  999. mCollisionList.clear();
  1000. CollisionState *state = mConvex.findClosestState(cmat, getScale(), mDataBlock->collisionTol);
  1001. if (state && state->mDist <= mDataBlock->collisionTol)
  1002. {
  1003. //resolveDisplacement(ns,state,dt);
  1004. mConvex.getCollisionInfo(cmat, getScale(), &mCollisionList, mDataBlock->collisionTol);
  1005. }
  1006. // Resolve collisions
  1007. bool collided = resolveCollision(mRigid,mCollisionList);
  1008. resolveContacts(mRigid,mCollisionList,dt);
  1009. return collided;
  1010. }
  1011. //----------------------------------------------------------------------------
  1012. /** Resolve collision impacts
  1013. Handle collision impacts, as opposed to contacts. Impulses are calculated based
  1014. on standard collision resolution formulas.
  1015. */
  1016. bool RigidShape::resolveCollision(Rigid& ns,CollisionList& cList)
  1017. {
  1018. // Apply impulses to resolve collision
  1019. bool collided = false;
  1020. for (S32 i = 0; i < cList.getCount(); i++)
  1021. {
  1022. Collision& c = cList[i];
  1023. if (c.distance < mDataBlock->collisionTol)
  1024. {
  1025. // Velocity into surface
  1026. Point3F v, r;
  1027. ns.getOriginVector(c.point, &r);
  1028. ns.getVelocity(r, &v);
  1029. F32 vn = mDot(v, c.normal);
  1030. // Only interested in velocities greater than sContactTol,
  1031. // velocities less than that will be dealt with as contacts
  1032. // "constraints".
  1033. if (vn < -mDataBlock->contactTol)
  1034. {
  1035. // Apply impulses to the rigid body to keep it from
  1036. // penetrating the surface.
  1037. if (c.object->getTypeMask() & VehicleObjectType)
  1038. {
  1039. RigidShape* otherRigid = dynamic_cast<RigidShape*>(c.object);
  1040. if (otherRigid)
  1041. ns.resolveCollision(cList[i].point, cList[i].normal, &otherRigid->mRigid);
  1042. else
  1043. ns.resolveCollision(cList[i].point, cList[i].normal);
  1044. }
  1045. else ns.resolveCollision(cList[i].point, cList[i].normal);
  1046. collided = true;
  1047. // Keep track of objects we collide with
  1048. if (!isGhost() && c.object->getTypeMask() & ShapeBaseObjectType)
  1049. {
  1050. ShapeBase* col = static_cast<ShapeBase*>(c.object);
  1051. queueCollision(col, v - col->getVelocity());
  1052. }
  1053. }
  1054. }
  1055. }
  1056. return collided;
  1057. }
  1058. //----------------------------------------------------------------------------
  1059. /** Resolve contact forces
  1060. Resolve contact forces using the "penalty" method. Forces are generated based
  1061. on the depth of penetration and the moment of inertia at the point of contact.
  1062. */
  1063. bool RigidShape::resolveContacts(Rigid& ns,CollisionList& cList,F32 dt)
  1064. {
  1065. // Use spring forces to manage contact constraints.
  1066. bool collided = false;
  1067. Point3F t,p(0,0,0),l(0,0,0);
  1068. for (S32 i = 0; i < cList.getCount(); i++)
  1069. {
  1070. const Collision& c = cList[i];
  1071. if (c.distance < mDataBlock->collisionTol)
  1072. {
  1073. // Velocity into the surface
  1074. Point3F v,r;
  1075. ns.getOriginVector(c.point,&r);
  1076. ns.getVelocity(r,&v);
  1077. F32 vn = mDot(v,c.normal);
  1078. // Only interested in velocities less than mDataBlock->contactTol,
  1079. // velocities greater than that are dealt with as collisions.
  1080. if (mFabs(vn) < mDataBlock->contactTol)
  1081. {
  1082. collided = true;
  1083. // Penetration force. This is actually a spring which
  1084. // will seperate the body from the collision surface.
  1085. F32 zi = 2 * mFabs(mRigid.getZeroImpulse(r,c.normal));
  1086. F32 s = (mDataBlock->collisionTol - c.distance) * zi - ((vn / mDataBlock->contactTol) * zi);
  1087. Point3F f = c.normal * s;
  1088. // Friction impulse, calculated as a function of the
  1089. // amount of force it would take to stop the motion
  1090. // perpendicular to the normal.
  1091. Point3F uv = v - (c.normal * vn);
  1092. F32 ul = uv.len();
  1093. if (s > 0 && ul)
  1094. {
  1095. uv /= -ul;
  1096. F32 u = ul * ns.getZeroImpulse(r,uv);
  1097. s *= mRigid.friction;
  1098. if (u > s)
  1099. u = s;
  1100. f += uv * u;
  1101. }
  1102. // Accumulate forces
  1103. p += f;
  1104. mCross(r,f,&t);
  1105. l += t;
  1106. }
  1107. }
  1108. }
  1109. // Contact constraint forces act over time...
  1110. ns.linMomentum += p * dt;
  1111. ns.angMomentum += l * dt;
  1112. ns.updateVelocity();
  1113. return true;
  1114. }
  1115. //----------------------------------------------------------------------------
  1116. bool RigidShape::resolveDisplacement(Rigid& ns,CollisionState *state, F32 dt)
  1117. {
  1118. SceneObject* obj = (state->mA->getObject() == this)?
  1119. state->mB->getObject(): state->mA->getObject();
  1120. if (obj->isDisplacable() && ((obj->getTypeMask() & ShapeBaseObjectType) != 0))
  1121. {
  1122. // Try to displace the object by the amount we're trying to move
  1123. Point3F objNewMom = ns.linVelocity * obj->getMass() * 1.1f;
  1124. Point3F objOldMom = obj->getMomentum();
  1125. Point3F objNewVel = objNewMom / obj->getMass();
  1126. Point3F myCenter;
  1127. Point3F theirCenter;
  1128. getWorldBox().getCenter(&myCenter);
  1129. obj->getWorldBox().getCenter(&theirCenter);
  1130. if (mDot(myCenter - theirCenter, objNewMom) >= 0.0f || objNewVel.len() < 0.01)
  1131. {
  1132. objNewMom = (theirCenter - myCenter);
  1133. objNewMom.normalize();
  1134. objNewMom *= 1.0f * obj->getMass();
  1135. objNewVel = objNewMom / obj->getMass();
  1136. }
  1137. obj->setMomentum(objNewMom);
  1138. if (obj->displaceObject(objNewVel * 1.1f * dt) == true)
  1139. {
  1140. // Queue collision and change in velocity
  1141. VectorF dv = (objOldMom - objNewMom) / obj->getMass();
  1142. queueCollision(static_cast<ShapeBase*>(obj), dv);
  1143. return true;
  1144. }
  1145. }
  1146. return false;
  1147. }
  1148. //----------------------------------------------------------------------------
  1149. void RigidShape::updateWorkingCollisionSet(const U32 mask)
  1150. {
  1151. PROFILE_SCOPE( Vehicle_UpdateWorkingCollisionSet );
  1152. // First, we need to adjust our velocity for possible acceleration. It is assumed
  1153. // that we will never accelerate more than 20 m/s for gravity, plus 30 m/s for
  1154. // jetting, and an equivalent 10 m/s for vehicle accel. We also assume that our
  1155. // working list is updated on a Tick basis, which means we only expand our box by
  1156. // the possible movement in that tick, plus some extra for caching purposes
  1157. Box3F convexBox = mConvex.getBoundingBox(getTransform(), getScale());
  1158. F32 len = (mRigid.linVelocity.len() + 50) * TickSec;
  1159. F32 l = (len * 1.1) + 0.1; // fudge factor
  1160. convexBox.minExtents -= Point3F(l, l, l);
  1161. convexBox.maxExtents += Point3F(l, l, l);
  1162. // Check to see if it is actually necessary to construct the new working list,
  1163. // or if we can use the cached version from the last query. We use the x
  1164. // component of the min member of the mWorkingQueryBox, which is lame, but
  1165. // it works ok.
  1166. bool updateSet = false;
  1167. // Check containment
  1168. if ((sWorkingQueryBoxStaleThreshold == -1 || mWorkingQueryBoxCountDown > 0) && mWorkingQueryBox.minExtents.x != -1e9f)
  1169. {
  1170. if (mWorkingQueryBox.isContained(convexBox) == false)
  1171. // Needed region is outside the cached region. Update it.
  1172. updateSet = true;
  1173. }
  1174. else
  1175. {
  1176. // Must update
  1177. updateSet = true;
  1178. }
  1179. // Actually perform the query, if necessary
  1180. if (updateSet == true)
  1181. {
  1182. mWorkingQueryBoxCountDown = sWorkingQueryBoxStaleThreshold;
  1183. const Point3F lPoint( sWorkingQueryBoxSizeMultiplier * l );
  1184. mWorkingQueryBox = convexBox;
  1185. mWorkingQueryBox.minExtents -= lPoint;
  1186. mWorkingQueryBox.maxExtents += lPoint;
  1187. disableCollision();
  1188. mConvex.updateWorkingList(mWorkingQueryBox, mask);
  1189. enableCollision();
  1190. }
  1191. }
  1192. //----------------------------------------------------------------------------
  1193. /** Check collisions with trigger and items
  1194. Perform a container search using the current bounding box
  1195. of the main body, wheels are not included. This method should
  1196. only be called on the server.
  1197. */
  1198. void RigidShape::checkTriggers()
  1199. {
  1200. Box3F bbox = mConvex.getBoundingBox(getTransform(), getScale());
  1201. gServerContainer.findObjects(bbox,sTriggerMask,findCallback,this);
  1202. }
  1203. /** The callback used in by the checkTriggers() method.
  1204. The checkTriggers method uses a container search which will
  1205. invoke this callback on each obj that matches.
  1206. */
  1207. void RigidShape::findCallback(SceneObject* obj,void *key)
  1208. {
  1209. RigidShape* shape = reinterpret_cast<RigidShape*>(key);
  1210. U32 objectMask = obj->getTypeMask();
  1211. // Check: triggers, corpses and items, basically the same things
  1212. // that the player class checks for
  1213. if (objectMask & TriggerObjectType) {
  1214. Trigger* pTrigger = static_cast<Trigger*>(obj);
  1215. pTrigger->potentialEnterObject(shape);
  1216. }
  1217. else if (objectMask & CorpseObjectType) {
  1218. ShapeBase* col = static_cast<ShapeBase*>(obj);
  1219. shape->queueCollision(col,shape->getVelocity() - col->getVelocity());
  1220. }
  1221. else if (objectMask & ItemObjectType) {
  1222. Item* item = static_cast<Item*>(obj);
  1223. if (shape != item->getCollisionObject())
  1224. shape->queueCollision(item,shape->getVelocity() - item->getVelocity());
  1225. }
  1226. }
  1227. //----------------------------------------------------------------------------
  1228. void RigidShape::writePacketData(GameConnection *connection, BitStream *stream)
  1229. {
  1230. Parent::writePacketData(connection, stream);
  1231. mathWrite(*stream, mRigid.linPosition);
  1232. mathWrite(*stream, mRigid.angPosition);
  1233. mathWrite(*stream, mRigid.linMomentum);
  1234. mathWrite(*stream, mRigid.angMomentum);
  1235. stream->writeFlag(mRigid.atRest);
  1236. stream->writeFlag(mContacts.getCount() == 0);
  1237. stream->writeFlag(mDisableMove);
  1238. stream->setCompressionPoint(mRigid.linPosition);
  1239. }
  1240. void RigidShape::readPacketData(GameConnection *connection, BitStream *stream)
  1241. {
  1242. Parent::readPacketData(connection, stream);
  1243. mathRead(*stream, &mRigid.linPosition);
  1244. mathRead(*stream, &mRigid.angPosition);
  1245. mathRead(*stream, &mRigid.linMomentum);
  1246. mathRead(*stream, &mRigid.angMomentum);
  1247. mRigid.atRest = stream->readFlag();
  1248. if (stream->readFlag())
  1249. mContacts.clear();
  1250. mRigid.updateInertialTensor();
  1251. mRigid.updateVelocity();
  1252. mDisableMove = stream->readFlag();
  1253. stream->setCompressionPoint(mRigid.linPosition);
  1254. }
  1255. //----------------------------------------------------------------------------
  1256. U32 RigidShape::packUpdate(NetConnection *con, U32 mask, BitStream *stream)
  1257. {
  1258. U32 retMask = Parent::packUpdate(con, mask, stream);
  1259. // The rest of the data is part of the control object packet update.
  1260. // If we're controlled by this client, we don't need to send it.
  1261. if (stream->writeFlag(getControllingClient() == con && !(mask & InitialUpdateMask)))
  1262. return retMask;
  1263. mDelta.move.pack(stream);
  1264. if (stream->writeFlag(mask & PositionMask))
  1265. {
  1266. stream->writeFlag(mask & ForceMoveMask);
  1267. stream->writeCompressedPoint(mRigid.linPosition);
  1268. mathWrite(*stream, mRigid.angPosition);
  1269. mathWrite(*stream, mRigid.linMomentum);
  1270. mathWrite(*stream, mRigid.angMomentum);
  1271. stream->writeFlag(mRigid.atRest);
  1272. }
  1273. if(stream->writeFlag(mask & FreezeMask))
  1274. stream->writeFlag(mDisableMove);
  1275. return retMask;
  1276. }
  1277. void RigidShape::unpackUpdate(NetConnection *con, BitStream *stream)
  1278. {
  1279. Parent::unpackUpdate(con,stream);
  1280. if (stream->readFlag())
  1281. return;
  1282. mDelta.move.unpack(stream);
  1283. if (stream->readFlag())
  1284. {
  1285. // Check if we need to jump to the given transform
  1286. // rather than interpolate to it.
  1287. bool forceUpdate = stream->readFlag();
  1288. mPredictionCount = sMaxPredictionTicks;
  1289. F32 speed = mRigid.linVelocity.len();
  1290. mDelta.warpRot[0] = mRigid.angPosition;
  1291. // Read in new position and momentum values
  1292. stream->readCompressedPoint(&mRigid.linPosition);
  1293. mathRead(*stream, &mRigid.angPosition);
  1294. mathRead(*stream, &mRigid.linMomentum);
  1295. mathRead(*stream, &mRigid.angMomentum);
  1296. mRigid.atRest = stream->readFlag();
  1297. mRigid.updateVelocity();
  1298. if (!forceUpdate && isProperlyAdded())
  1299. {
  1300. // Determine number of ticks to warp based on the average
  1301. // of the client and server velocities.
  1302. Point3F cp = mDelta.pos + mDelta.posVec * mDelta.dt;
  1303. mDelta.warpOffset = mRigid.linPosition - cp;
  1304. // Calc the distance covered in one tick as the average of
  1305. // the old speed and the new speed from the server.
  1306. F32 dt,as = (speed + mRigid.linVelocity.len()) * 0.5 * TickSec;
  1307. // Cal how many ticks it will take to cover the warp offset.
  1308. // If it's less than what's left in the current tick, we'll just
  1309. // warp in the remaining time.
  1310. if (!as || (dt = mDelta.warpOffset.len() / as) > sMaxWarpTicks)
  1311. dt = mDelta.dt + sMaxWarpTicks;
  1312. else
  1313. dt = (dt <= mDelta.dt)? mDelta.dt : mCeil(dt - mDelta.dt) + mDelta.dt;
  1314. // Adjust current frame interpolation
  1315. if (mDelta.dt)
  1316. {
  1317. mDelta.pos = cp + (mDelta.warpOffset * (mDelta.dt / dt));
  1318. mDelta.posVec = (cp - mDelta.pos) / mDelta.dt;
  1319. QuatF cr;
  1320. cr.interpolate(mDelta.rot[1],mDelta.rot[0],mDelta.dt);
  1321. mDelta.rot[1].interpolate(cr,mRigid.angPosition,mDelta.dt / dt);
  1322. mDelta.rot[0].extrapolate(mDelta.rot[1],cr,mDelta.dt);
  1323. }
  1324. // Calculated multi-tick warp
  1325. mDelta.warpCount = 0;
  1326. mDelta.warpTicks = (S32)(mFloor(dt));
  1327. if (mDelta.warpTicks)
  1328. {
  1329. mDelta.warpOffset = mRigid.linPosition - mDelta.pos;
  1330. mDelta.warpOffset /= mDelta.warpTicks;
  1331. mDelta.warpRot[0] = mDelta.rot[1];
  1332. mDelta.warpRot[1] = mRigid.angPosition;
  1333. }
  1334. }
  1335. else
  1336. {
  1337. // Set the shape to the server position
  1338. mDelta.dt = 0;
  1339. mDelta.pos = mRigid.linPosition;
  1340. mDelta.posVec.set(0,0,0);
  1341. mDelta.rot[1] = mDelta.rot[0] = mRigid.angPosition;
  1342. mDelta.warpCount = mDelta.warpTicks = 0;
  1343. setPosition(mRigid.linPosition, mRigid.angPosition);
  1344. }
  1345. }
  1346. if(stream->readFlag())
  1347. mDisableMove = stream->readFlag();
  1348. }
  1349. //----------------------------------------------------------------------------
  1350. //----------------------------------------------------------------------------
  1351. void RigidShape::consoleInit()
  1352. {
  1353. Con::addVariable("$rigidPhysics::workingQueryBoxStaleThreshold", TypeS32, &sWorkingQueryBoxStaleThreshold,
  1354. "@brief The maximum number of ticks that go by before the mWorkingQueryBox is considered stale and needs updating.\n\n"
  1355. "Other factors can cause the collision working query box to become invalidated, such as the rigid body moving far "
  1356. "enough outside of this cached box. The smaller this number, the more times the working list of triangles that are "
  1357. "considered for collision is refreshed. This has the greatest impact with colliding with high triangle count meshes.\n\n"
  1358. "@note Set to -1 to disable any time-based forced check.\n\n"
  1359. "@ingroup GameObjects\n");
  1360. Con::addVariable("$rigidPhysics::workingQueryBoxSizeMultiplier", TypeF32, &sWorkingQueryBoxSizeMultiplier,
  1361. "@brief How much larger the mWorkingQueryBox should be made when updating the working collision list.\n\n"
  1362. "The larger this number the less often the working list will be updated due to motion, but any non-static shape that "
  1363. "moves into the query box will not be noticed.\n\n"
  1364. "@ingroup GameObjects\n");
  1365. }
  1366. void RigidShape::initPersistFields()
  1367. {
  1368. Parent::initPersistFields();
  1369. }
  1370. //----------------------------------------------------------------------------
  1371. void RigidShape::updateLiftoffDust( F32 dt )
  1372. {
  1373. Point3F offset( 0.0, 0.0, mDataBlock->dustHeight );
  1374. emitDust( mDustEmitterList[ 0 ], mDataBlock->triggerDustHeight, offset,
  1375. ( U32 )( dt * 1000 ) );
  1376. }
  1377. //--------------------------------------------------------------------------
  1378. void RigidShape::updateFroth( F32 dt )
  1379. {
  1380. // update bubbles
  1381. Point3F moveDir = getVelocity();
  1382. Point3F contactPoint;
  1383. F32 speed = moveDir.len();
  1384. if( speed < mDataBlock->splashVelEpsilon ) speed = 0.0;
  1385. U32 emitRate = (U32)(speed * mDataBlock->splashFreqMod * dt);
  1386. U32 i;
  1387. for( i=0; i<RigidShapeData::VC_NUM_SPLASH_EMITTERS; i++ )
  1388. {
  1389. if( mSplashEmitterList[i] )
  1390. {
  1391. mSplashEmitterList[i]->emitParticles( contactPoint, contactPoint, Point3F( 0.0, 0.0, 1.0 ),
  1392. moveDir, emitRate );
  1393. }
  1394. }
  1395. }
  1396. //--------------------------------------------------------------------------
  1397. // Returns true if shape is intersecting a water surface (roughly)
  1398. //--------------------------------------------------------------------------
  1399. bool RigidShape::collidingWithWater( Point3F &waterHeight )
  1400. {
  1401. Point3F curPos = getPosition();
  1402. F32 height = mFabs( mObjBox.maxExtents.z - mObjBox.minExtents.z );
  1403. RayInfo rInfo;
  1404. if( gClientContainer.castRay( curPos + Point3F(0.0, 0.0, height), curPos, WaterObjectType, &rInfo) )
  1405. {
  1406. waterHeight = rInfo.point;
  1407. return true;
  1408. }
  1409. return false;
  1410. }
  1411. void RigidShape::setEnergyLevel(F32 energy)
  1412. {
  1413. Parent::setEnergyLevel(energy);
  1414. setMaskBits(EnergyMask);
  1415. }
  1416. void RigidShape::prepBatchRender( SceneRenderState *state, S32 mountedImageIndex )
  1417. {
  1418. Parent::prepBatchRender( state, mountedImageIndex );
  1419. if ( !gShowBoundingBox )
  1420. return;
  1421. ObjectRenderInst *ri = state->getRenderPass()->allocInst<ObjectRenderInst>();
  1422. ri->renderDelegate.bind( this, &RigidShape::_renderMassAndContacts );
  1423. ri->type = RenderPassManager::RIT_Editor;
  1424. state->getRenderPass()->addInst( ri );
  1425. }
  1426. void RigidShape::_renderMassAndContacts( ObjectRenderInst *ri, SceneRenderState *state, BaseMatInstance *overrideMat )
  1427. {
  1428. // Box for the center of Mass
  1429. GFXStateBlockDesc desc;
  1430. desc.setBlend(false, GFXBlendSrcAlpha, GFXBlendInvSrcAlpha);
  1431. desc.setZReadWrite(false);
  1432. desc.fillMode = GFXFillWireframe;
  1433. GFX->getDrawUtil()->drawCube( desc, Point3F(0.1f,0.1f,0.1f), mDataBlock->massCenter, ColorI(255, 255, 255), &mRenderObjToWorld );
  1434. // Collision points...
  1435. for (S32 i = 0; i < mCollisionList.getCount(); i++)
  1436. {
  1437. const Collision& collision = mCollisionList[i];
  1438. GFX->getDrawUtil()->drawCube( desc, Point3F(0.05f,0.05f,0.05f), collision.point, ColorI(0, 0, 255) );
  1439. }
  1440. // Render the normals as one big batch...
  1441. PrimBuild::begin(GFXLineList, mCollisionList.getCount() * 2);
  1442. for (S32 i = 0; i < mCollisionList.getCount(); i++)
  1443. {
  1444. const Collision& collision = mCollisionList[i];
  1445. PrimBuild::color3f(1, 1, 1);
  1446. PrimBuild::vertex3fv(collision.point);
  1447. PrimBuild::vertex3fv(collision.point + collision.normal * 0.05f);
  1448. }
  1449. PrimBuild::end();
  1450. // Build and render the collision polylist which is returned
  1451. // in the server's world space.
  1452. ClippedPolyList polyList;
  1453. polyList.mPlaneList.setSize(6);
  1454. polyList.mPlaneList[0].set(getWorldBox().minExtents,VectorF(-1,0,0));
  1455. polyList.mPlaneList[1].set(getWorldBox().minExtents,VectorF(0,-1,0));
  1456. polyList.mPlaneList[2].set(getWorldBox().minExtents,VectorF(0,0,-1));
  1457. polyList.mPlaneList[3].set(getWorldBox().maxExtents,VectorF(1,0,0));
  1458. polyList.mPlaneList[4].set(getWorldBox().maxExtents,VectorF(0,1,0));
  1459. polyList.mPlaneList[5].set(getWorldBox().maxExtents,VectorF(0,0,1));
  1460. Box3F dummyBox;
  1461. SphereF dummySphere;
  1462. buildPolyList(PLC_Collision, &polyList, dummyBox, dummySphere);
  1463. //polyList.render();
  1464. }
  1465. void RigidShape::reset()
  1466. {
  1467. mRigid.clearForces();
  1468. mRigid.setAtRest();
  1469. }
  1470. void RigidShape::freezeSim(bool frozen)
  1471. {
  1472. mDisableMove = frozen;
  1473. setMaskBits(FreezeMask);
  1474. }
  1475. DefineEngineMethod( RigidShape, reset, void, (),,
  1476. "@brief Clears physic forces from the shape and sets it at rest.\n\n"
  1477. "@tsexample\n"
  1478. "// Inform the RigidShape object to reset.\n"
  1479. "%thisRigidShape.reset();\n"
  1480. "@endtsexample\n\n"
  1481. "@see ShapeBaseData")
  1482. {
  1483. object->reset();
  1484. }
  1485. DefineEngineMethod( RigidShape, freezeSim, void, (bool isFrozen),,
  1486. "@brief Enables or disables the physics simulation on the RigidShape object.\n\n"
  1487. "@param isFrozen Boolean frozen state to set the object.\n"
  1488. "@tsexample\n"
  1489. "// Define the frozen state.\n"
  1490. "%isFrozen = \"true\";\n\n"
  1491. "// Inform the object of the defined frozen state\n"
  1492. "%thisRigidShape.freezeSim(%isFrozen);\n"
  1493. "@endtsexample\n\n"
  1494. "@see ShapeBaseData")
  1495. {
  1496. object->freezeSim(isFrozen);
  1497. }
  1498. DefineEngineMethod( RigidShape, forceClientTransform, void, (),,
  1499. "@brief Forces the client to jump to the RigidShape's transform rather then warp to it.\n\n")
  1500. {
  1501. if(object->isServerObject())
  1502. {
  1503. object->forceClientTransform();
  1504. }
  1505. }