rigidShape.cpp 55 KB

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