vehicle.cpp 55 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597
  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/vehicles/vehicle.h"
  24. #include "math/mMath.h"
  25. #include "console/simBase.h"
  26. #include "console/console.h"
  27. #include "console/consoleTypes.h"
  28. #include "console/engineAPI.h"
  29. #include "collision/clippedPolyList.h"
  30. #include "collision/planeExtractor.h"
  31. #include "core/stream/bitStream.h"
  32. #include "core/dnet.h"
  33. #include "T3D/gameBase/gameConnection.h"
  34. #include "T3D/fx/cameraFXMgr.h"
  35. #include "ts/tsShapeInstance.h"
  36. #include "T3D/fx/particleEmitter.h"
  37. #include "sfx/sfxSystem.h"
  38. #include "sfx/sfxProfile.h"
  39. #include "sfx/sfxSource.h"
  40. #include "math/mathIO.h"
  41. #include "scene/sceneRenderState.h"
  42. #include "T3D/trigger.h"
  43. #include "T3D/item.h"
  44. #include "gfx/primBuilder.h"
  45. #include "gfx/gfxDrawUtil.h"
  46. #include "materials/materialDefinition.h"
  47. #include "T3D/physics/physicsPlugin.h"
  48. #include "T3D/physics/physicsBody.h"
  49. #include "T3D/physics/physicsCollision.h"
  50. namespace {
  51. static U32 sWorkingQueryBoxStaleThreshold = 10; // The maximum number of ticks that go by before
  52. // the mWorkingQueryBox is considered stale and
  53. // needs updating. Set to -1 to disable.
  54. static F32 sWorkingQueryBoxSizeMultiplier = 2.0f; // How much larger should the mWorkingQueryBox be
  55. // made when updating the working collision list.
  56. // The larger this number the less often the working list
  57. // will be updated due to motion, but any non-static shape
  58. // that moves into the query box will not be noticed.
  59. // Client prediction
  60. const S32 sMaxWarpTicks = 3; // Max warp duration in ticks
  61. const S32 sMaxPredictionTicks = 30; // Number of ticks to predict
  62. // Physics and collision constants
  63. static F32 sRestTol = 0.5; // % of gravity energy to be at rest
  64. static S32 sRestCount = 10; // Consecutive ticks before comming to rest
  65. } // namespace {}
  66. // Trigger objects that are not normally collided with.
  67. static U32 sTriggerMask = ItemObjectType |
  68. TriggerObjectType |
  69. CorpseObjectType;
  70. IMPLEMENT_CONOBJECT(VehicleData);
  71. ConsoleDocClass( VehicleData,
  72. "@brief Base properties shared by all Vehicles (FlyingVehicle, HoverVehicle, "
  73. "WheeledVehicle).\n\n"
  74. "This datablock defines properties shared by all Vehicle types, but should "
  75. "not be instantiated directly. Instead, set the desired properties in the "
  76. "FlyingVehicleData, HoverVehicleData or WheeledVehicleData datablock.\n"
  77. "@section VehicleData_damage Damage\n\n"
  78. "The VehicleData class extends the basic energy/damage functionality provided "
  79. "by ShapeBaseData to include damage from collisions, as well as particle "
  80. "emitters activated automatically when damage levels reach user specified "
  81. "thresholds.\n\n"
  82. "The example below shows how to setup a Vehicle to:\n"
  83. "<ul>\n"
  84. " <li>take damage when colliding with another object\n"
  85. " <li>emit gray smoke particles from two locations on the Vehicle when damaged above 50%</li>\n"
  86. " <li>emit black smoke particles from two locations on the Vehicle when damaged above 85%</li>\n"
  87. " <li>emit bubbles when any active damage emitter point is underwater</li>\n"
  88. "</ul>\n\n"
  89. "@tsexample\n"
  90. "// damage from collisions\n"
  91. "collDamageMultiplier = 0.05;\n"
  92. "collDamageThresholdVel = 15;\n\n"
  93. "// damage levels\n"
  94. "damageLevelTolerance[0] = 0.5;\n"
  95. "damageEmitter[0] = GraySmokeEmitter; // emitter used when damage is >= 50%\n"
  96. "damageLevelTolerance[1] = 0.85;\n"
  97. "damageEmitter[1] = BlackSmokeEmitter; // emitter used when damage is >= 85%\n"
  98. "damageEmitter[2] = DamageBubbleEmitter; // emitter used instead of damageEmitter[0:1]\n"
  99. " // when offset point is underwater\n"
  100. "// emit offsets (used for all active damage level emitters)\n"
  101. "damageEmitterOffset[0] = \"0.5 3 1\";\n"
  102. "damageEmitterOffset[1] = \"-0.5 3 1\";\n"
  103. "numDmgEmitterAreas = 2;\n"
  104. "@endtsexample\n"
  105. "@ingroup Vehicles\n"
  106. );
  107. //----------------------------------------------------------------------------
  108. VehicleData::VehicleData()
  109. {
  110. shadowEnable = true;
  111. shadowSize = 256;
  112. shadowProjectionDistance = 14.0f;
  113. body.friction = 0;
  114. body.restitution = 1;
  115. minImpactSpeed = 25;
  116. softImpactSpeed = 25;
  117. hardImpactSpeed = 50;
  118. minRollSpeed = 0;
  119. maxSteeringAngle = M_PI_F/4.0f; // 45 deg.
  120. cameraRoll = true;
  121. cameraLag = 0;
  122. cameraDecay = 0;
  123. cameraOffset = 0;
  124. minDrag = 0;
  125. maxDrag = 0;
  126. integration = 1;
  127. collisionTol = 0.1f;
  128. contactTol = 0.1f;
  129. massCenter.set(0,0,0);
  130. massBox.set(0,0,0);
  131. drag = 0.7f;
  132. density = 4;
  133. jetForce = 500;
  134. jetEnergyDrain = 0.8f;
  135. minJetEnergy = 1;
  136. steeringReturn = 0.0f;
  137. steeringReturnSpeedScale = 0.01f;
  138. powerSteering = false;
  139. for (S32 i = 0; i < Body::MaxSounds; i++)
  140. body.sound[i] = 0;
  141. dustEmitter = NULL;
  142. dustID = 0;
  143. triggerDustHeight = 3.0;
  144. dustHeight = 1.0;
  145. dMemset( damageEmitterList, 0, sizeof( damageEmitterList ) );
  146. dMemset( damageEmitterOffset, 0, sizeof( damageEmitterOffset ) );
  147. dMemset( damageEmitterIDList, 0, sizeof( damageEmitterIDList ) );
  148. dMemset( damageLevelTolerance, 0, sizeof( damageLevelTolerance ) );
  149. dMemset( splashEmitterList, 0, sizeof( splashEmitterList ) );
  150. dMemset( splashEmitterIDList, 0, sizeof( splashEmitterIDList ) );
  151. numDmgEmitterAreas = 0;
  152. splashFreqMod = 300.0;
  153. splashVelEpsilon = 0.50;
  154. exitSplashSoundVel = 2.0;
  155. softSplashSoundVel = 1.0;
  156. medSplashSoundVel = 2.0;
  157. hardSplashSoundVel = 3.0;
  158. dMemset(waterSound, 0, sizeof(waterSound));
  159. collDamageThresholdVel = 20;
  160. collDamageMultiplier = 0.05f;
  161. enablePhysicsRep = true;
  162. }
  163. //----------------------------------------------------------------------------
  164. bool VehicleData::preload(bool server, String &errorStr)
  165. {
  166. if (!Parent::preload(server, errorStr))
  167. return false;
  168. // Vehicle objects must define a collision detail
  169. if (!collisionDetails.size() || collisionDetails[0] == -1)
  170. {
  171. Con::errorf("VehicleData::preload failed: Vehicle models must define a collision-1 detail");
  172. errorStr = String::ToString("VehicleData: Couldn't load shape \"%s\"",shapeName);
  173. return false;
  174. }
  175. // Resolve objects transmitted from server
  176. if (!server) {
  177. for (S32 i = 0; i < Body::MaxSounds; i++)
  178. if (body.sound[i])
  179. Sim::findObject(SimObjectId((uintptr_t)body.sound[i]),body.sound[i]);
  180. }
  181. if( !dustEmitter && dustID != 0 )
  182. {
  183. if( !Sim::findObject( dustID, dustEmitter ) )
  184. {
  185. Con::errorf( ConsoleLogEntry::General, "VehicleData::preload Invalid packet, bad datablockId(dustEmitter): 0x%x", dustID );
  186. }
  187. }
  188. U32 i;
  189. for( i=0; i<VC_NUM_DAMAGE_EMITTERS; i++ )
  190. {
  191. if( !damageEmitterList[i] && damageEmitterIDList[i] != 0 )
  192. {
  193. if( !Sim::findObject( damageEmitterIDList[i], damageEmitterList[i] ) )
  194. {
  195. Con::errorf( ConsoleLogEntry::General, "VehicleData::preload Invalid packet, bad datablockId(damageEmitter): 0x%x", damageEmitterIDList[i] );
  196. }
  197. }
  198. }
  199. for( i=0; i<VC_NUM_SPLASH_EMITTERS; i++ )
  200. {
  201. if( !splashEmitterList[i] && splashEmitterIDList[i] != 0 )
  202. {
  203. if( !Sim::findObject( splashEmitterIDList[i], splashEmitterList[i] ) )
  204. {
  205. Con::errorf( ConsoleLogEntry::General, "VehicleData::preload Invalid packet, bad datablockId(splashEmitter): 0x%x", splashEmitterIDList[i] );
  206. }
  207. }
  208. }
  209. return true;
  210. }
  211. //----------------------------------------------------------------------------
  212. void VehicleData::packData(BitStream* stream)
  213. {
  214. S32 i;
  215. Parent::packData(stream);
  216. stream->write(body.restitution);
  217. stream->write(body.friction);
  218. for (i = 0; i < Body::MaxSounds; i++)
  219. if (stream->writeFlag(body.sound[i]))
  220. stream->writeRangedU32(mPacked ? SimObjectId((uintptr_t)body.sound[i]):
  221. body.sound[i]->getId(),DataBlockObjectIdFirst,
  222. DataBlockObjectIdLast);
  223. stream->write(minImpactSpeed);
  224. stream->write(softImpactSpeed);
  225. stream->write(hardImpactSpeed);
  226. stream->write(minRollSpeed);
  227. stream->write(maxSteeringAngle);
  228. stream->write(maxDrag);
  229. stream->write(minDrag);
  230. stream->write(integration);
  231. stream->write(collisionTol);
  232. stream->write(contactTol);
  233. mathWrite(*stream,massCenter);
  234. mathWrite(*stream,massBox);
  235. stream->write(jetForce);
  236. stream->write(jetEnergyDrain);
  237. stream->write(minJetEnergy);
  238. stream->write(steeringReturn);
  239. stream->write(steeringReturnSpeedScale);
  240. stream->writeFlag(powerSteering);
  241. stream->writeFlag(cameraRoll);
  242. stream->write(cameraLag);
  243. stream->write(cameraDecay);
  244. stream->write(cameraOffset);
  245. stream->write( triggerDustHeight );
  246. stream->write( dustHeight );
  247. stream->write( numDmgEmitterAreas );
  248. stream->write(exitSplashSoundVel);
  249. stream->write(softSplashSoundVel);
  250. stream->write(medSplashSoundVel);
  251. stream->write(hardSplashSoundVel);
  252. stream->write(enablePhysicsRep);
  253. // write the water sound profiles
  254. for(i = 0; i < MaxSounds; i++)
  255. if(stream->writeFlag(waterSound[i]))
  256. stream->writeRangedU32(waterSound[i]->getId(), DataBlockObjectIdFirst, DataBlockObjectIdLast);
  257. if (stream->writeFlag( dustEmitter ))
  258. {
  259. stream->writeRangedU32( dustEmitter->getId(), DataBlockObjectIdFirst, DataBlockObjectIdLast );
  260. }
  261. for (i = 0; i < VC_NUM_DAMAGE_EMITTERS; i++)
  262. {
  263. if( stream->writeFlag( damageEmitterList[i] != NULL ) )
  264. {
  265. stream->writeRangedU32( damageEmitterList[i]->getId(), DataBlockObjectIdFirst, DataBlockObjectIdLast );
  266. }
  267. }
  268. for (i = 0; i < VC_NUM_SPLASH_EMITTERS; i++)
  269. {
  270. if( stream->writeFlag( splashEmitterList[i] != NULL ) )
  271. {
  272. stream->writeRangedU32( splashEmitterList[i]->getId(), DataBlockObjectIdFirst, DataBlockObjectIdLast );
  273. }
  274. }
  275. for (S32 j = 0; j < VC_NUM_DAMAGE_EMITTER_AREAS; j++)
  276. {
  277. stream->write( damageEmitterOffset[j].x );
  278. stream->write( damageEmitterOffset[j].y );
  279. stream->write( damageEmitterOffset[j].z );
  280. }
  281. for (S32 k = 0; k < VC_NUM_DAMAGE_LEVELS; k++)
  282. {
  283. stream->write( damageLevelTolerance[k] );
  284. }
  285. stream->write(splashFreqMod);
  286. stream->write(splashVelEpsilon);
  287. stream->write(collDamageThresholdVel);
  288. stream->write(collDamageMultiplier);
  289. }
  290. void VehicleData::unpackData(BitStream* stream)
  291. {
  292. Parent::unpackData(stream);
  293. stream->read(&body.restitution);
  294. stream->read(&body.friction);
  295. S32 i;
  296. for (i = 0; i < Body::MaxSounds; i++) {
  297. body.sound[i] = NULL;
  298. if (stream->readFlag())
  299. body.sound[i] = (SFXProfile*)(uintptr_t)stream->readRangedU32(DataBlockObjectIdFirst,
  300. DataBlockObjectIdLast);
  301. }
  302. stream->read(&minImpactSpeed);
  303. stream->read(&softImpactSpeed);
  304. stream->read(&hardImpactSpeed);
  305. stream->read(&minRollSpeed);
  306. stream->read(&maxSteeringAngle);
  307. stream->read(&maxDrag);
  308. stream->read(&minDrag);
  309. stream->read(&integration);
  310. stream->read(&collisionTol);
  311. stream->read(&contactTol);
  312. mathRead(*stream,&massCenter);
  313. mathRead(*stream,&massBox);
  314. stream->read(&jetForce);
  315. stream->read(&jetEnergyDrain);
  316. stream->read(&minJetEnergy);
  317. stream->read(&steeringReturn);
  318. stream->read(&steeringReturnSpeedScale);
  319. powerSteering = stream->readFlag();
  320. cameraRoll = stream->readFlag();
  321. stream->read(&cameraLag);
  322. stream->read(&cameraDecay);
  323. stream->read(&cameraOffset);
  324. stream->read( &triggerDustHeight );
  325. stream->read( &dustHeight );
  326. stream->read( &numDmgEmitterAreas );
  327. stream->read(&exitSplashSoundVel);
  328. stream->read(&softSplashSoundVel);
  329. stream->read(&medSplashSoundVel);
  330. stream->read(&hardSplashSoundVel);
  331. stream->read(&enablePhysicsRep);
  332. // write the water sound profiles
  333. for(i = 0; i < MaxSounds; i++)
  334. if(stream->readFlag())
  335. {
  336. U32 id = stream->readRangedU32(DataBlockObjectIdFirst, DataBlockObjectIdLast);
  337. waterSound[i] = dynamic_cast<SFXProfile*>( Sim::findObject(id) );
  338. }
  339. if( stream->readFlag() )
  340. {
  341. dustID = (S32) stream->readRangedU32(DataBlockObjectIdFirst, DataBlockObjectIdLast);
  342. }
  343. for (i = 0; i < VC_NUM_DAMAGE_EMITTERS; i++)
  344. {
  345. if( stream->readFlag() )
  346. {
  347. damageEmitterIDList[i] = stream->readRangedU32( DataBlockObjectIdFirst, DataBlockObjectIdLast );
  348. }
  349. }
  350. for (i = 0; i < VC_NUM_SPLASH_EMITTERS; i++)
  351. {
  352. if( stream->readFlag() )
  353. {
  354. splashEmitterIDList[i] = stream->readRangedU32( DataBlockObjectIdFirst, DataBlockObjectIdLast );
  355. }
  356. }
  357. for( S32 j=0; j<VC_NUM_DAMAGE_EMITTER_AREAS; j++ )
  358. {
  359. stream->read( &damageEmitterOffset[j].x );
  360. stream->read( &damageEmitterOffset[j].y );
  361. stream->read( &damageEmitterOffset[j].z );
  362. }
  363. for( S32 k=0; k<VC_NUM_DAMAGE_LEVELS; k++ )
  364. {
  365. stream->read( &damageLevelTolerance[k] );
  366. }
  367. stream->read(&splashFreqMod);
  368. stream->read(&splashVelEpsilon);
  369. stream->read(&collDamageThresholdVel);
  370. stream->read(&collDamageMultiplier);
  371. }
  372. //----------------------------------------------------------------------------
  373. void VehicleData::initPersistFields()
  374. {
  375. addGroup("Physics");
  376. addField("enablePhysicsRep", TypeBool, Offset(enablePhysicsRep, VehicleData),
  377. "@brief Creates a representation of the object in the physics plugin.\n");
  378. endGroup("Physics");
  379. addField( "jetForce", TypeF32, Offset(jetForce, VehicleData),
  380. "@brief Additional force applied to the vehicle when it is jetting.\n\n"
  381. "For WheeledVehicles, the force is applied in the forward direction. For "
  382. "FlyingVehicles, the force is applied in the thrust direction." );
  383. addField( "jetEnergyDrain", TypeF32, Offset(jetEnergyDrain, VehicleData),
  384. "@brief Energy amount to drain for each tick the vehicle is jetting.\n\n"
  385. "Once the vehicle's energy level reaches 0, it will no longer be able to jet." );
  386. addField( "minJetEnergy", TypeF32, Offset(minJetEnergy, VehicleData),
  387. "Minimum vehicle energy level to begin jetting." );
  388. addField( "steeringReturn", TypeF32, Offset(steeringReturn, VehicleData),
  389. "Rate at which the vehicle's steering returns to forwards when it is moving." );
  390. addField( "steeringReturnSpeedScale", TypeF32, Offset(steeringReturnSpeedScale, VehicleData),
  391. "Amount of effect the vehicle's speed has on its rate of steering return." );
  392. addField( "powerSteering", TypeBool, Offset(powerSteering, VehicleData),
  393. "If true, steering does not auto-centre while the vehicle is being steered by its driver." );
  394. addField( "massCenter", TypePoint3F, Offset(massCenter, VehicleData),
  395. "Defines the vehicle's center of mass (offset from the origin of the model)." );
  396. addField( "massBox", TypePoint3F, Offset(massBox, VehicleData),
  397. "@brief Define the box used to estimate the vehicle's moment of inertia.\n\n"
  398. "Currently only used by WheeledVehicle; other vehicle types use a "
  399. "unit sphere to compute inertia." );
  400. addField( "bodyRestitution", TypeF32, Offset(body.restitution, VehicleData),
  401. "Collision 'bounciness'.\nNormally in the range 0 (not bouncy at all) to "
  402. "1 (100% bounciness)." );
  403. addField( "bodyFriction", TypeF32, Offset(body.friction, VehicleData),
  404. "Collision friction coefficient.\nHow well this object will slide against "
  405. "objects it collides with." );
  406. addField( "softImpactSound", TYPEID< SFXProfile >(), Offset(body.sound[Body::SoftImpactSound], VehicleData),
  407. "@brief Sound to play on a 'soft' impact.\n\n"
  408. "This sound is played if the impact speed is < hardImpactSpeed and >= "
  409. "softImpactSpeed.\n\n"
  410. "@see softImpactSpeed" );
  411. addField( "hardImpactSound", TYPEID< SFXProfile >(), Offset(body.sound[Body::HardImpactSound], VehicleData),
  412. "@brief Sound to play on a 'hard' impact.\n\n"
  413. "This sound is played if the impact speed >= hardImpactSpeed.\n\n"
  414. "@see hardImpactSpeed" );
  415. addField( "minImpactSpeed", TypeF32, Offset(minImpactSpeed, VehicleData),
  416. "Minimum collision speed for the onImpact callback to be invoked." );
  417. addField( "softImpactSpeed", TypeF32, Offset(softImpactSpeed, VehicleData),
  418. "Minimum collision speed for the softImpactSound to be played." );
  419. addField( "hardImpactSpeed", TypeF32, Offset(hardImpactSpeed, VehicleData),
  420. "Minimum collision speed for the hardImpactSound to be played." );
  421. addField( "minRollSpeed", TypeF32, Offset(minRollSpeed, VehicleData),
  422. "Unused" );
  423. addField( "maxSteeringAngle", TypeF32, Offset(maxSteeringAngle, VehicleData),
  424. "Maximum yaw (horizontal) and pitch (vertical) steering angle in radians." );
  425. addField( "maxDrag", TypeF32, Offset(maxDrag, VehicleData),
  426. "Maximum drag coefficient.\nCurrently unused." );
  427. addField( "minDrag", TypeF32, Offset(minDrag, VehicleData),
  428. "Minimum drag coefficient.\nCurrently only used by FlyingVehicle." );
  429. addField( "integration", TypeS32, Offset(integration, VehicleData),
  430. "Number of integration steps per tick.\nIncrease this to improve simulation "
  431. "stability (also increases simulation processing time)." );
  432. addField( "collisionTol", TypeF32, Offset(collisionTol, VehicleData),
  433. "Minimum distance between objects for them to be considered as colliding." );
  434. addField( "contactTol", TypeF32, Offset(contactTol, VehicleData),
  435. "Maximum relative velocity between objects for collisions to be resolved "
  436. "as contacts.\nVelocities greater than this are handled as collisions." );
  437. addField( "cameraRoll", TypeBool, Offset(cameraRoll, VehicleData),
  438. "If true, the camera will roll with the vehicle. If false, the camera will "
  439. "always have the positive Z axis as up." );
  440. addField( "cameraLag", TypeF32, Offset(cameraLag, VehicleData),
  441. "@brief How much the camera lags behind the vehicle depending on vehicle speed.\n\n"
  442. "Increasing this value will make the camera fall further behind the vehicle "
  443. "as it accelerates away.\n\n@see cameraDecay." );
  444. addField("cameraDecay", TypeF32, Offset(cameraDecay, VehicleData),
  445. "How quickly the camera moves back towards the vehicle when stopped.\n\n"
  446. "@see cameraLag." );
  447. addField("cameraOffset", TypeF32, Offset(cameraOffset, VehicleData),
  448. "Vertical (Z axis) height of the camera above the vehicle." );
  449. addField( "dustEmitter", TYPEID< ParticleEmitterData >(), Offset(dustEmitter, VehicleData),
  450. "Dust particle emitter.\n\n@see triggerDustHeight\n\n@see dustHeight");
  451. addField( "triggerDustHeight", TypeF32, Offset(triggerDustHeight, VehicleData),
  452. "@brief Maximum height above surface to emit dust particles.\n\n"
  453. "If the vehicle is less than triggerDustHeight above a static surface "
  454. "with a material that has 'showDust' set to true, the vehicle will emit "
  455. "particles from the dustEmitter." );
  456. addField( "dustHeight", TypeF32, Offset(dustHeight, VehicleData),
  457. "Height above ground at which to emit particles from the dustEmitter." );
  458. addField( "damageEmitter", TYPEID< ParticleEmitterData >(), Offset(damageEmitterList, VehicleData), VC_NUM_DAMAGE_EMITTERS,
  459. "@brief Array of particle emitters used to generate damage (dust, smoke etc) "
  460. "effects.\n\n"
  461. "Currently, the first two emitters (indices 0 and 1) are used when the damage "
  462. "level exceeds the associated damageLevelTolerance. The 3rd emitter is used "
  463. "when the emitter point is underwater.\n\n"
  464. "@see damageEmitterOffset" );
  465. addField( "damageEmitterOffset", TypePoint3F, Offset(damageEmitterOffset, VehicleData), VC_NUM_DAMAGE_EMITTER_AREAS,
  466. "@brief Object space \"x y z\" offsets used to emit particles for the "
  467. "active damageEmitter.\n\n"
  468. "@tsexample\n"
  469. "// damage levels\n"
  470. "damageLevelTolerance[0] = 0.5;\n"
  471. "damageEmitter[0] = SmokeEmitter;\n"
  472. "// emit offsets (used for all active damage level emitters)\n"
  473. "damageEmitterOffset[0] = \"0.5 3 1\";\n"
  474. "damageEmitterOffset[1] = \"-0.5 3 1\";\n"
  475. "numDmgEmitterAreas = 2;\n"
  476. "@endtsexample\n" );
  477. addField( "damageLevelTolerance", TypeF32, Offset(damageLevelTolerance, VehicleData), VC_NUM_DAMAGE_LEVELS,
  478. "@brief Damage levels (as a percentage of maxDamage) above which to begin "
  479. "emitting particles from the associated damageEmitter.\n\n"
  480. "Levels should be in order of increasing damage.\n\n"
  481. "@see damageEmitterOffset" );
  482. addField( "numDmgEmitterAreas", TypeF32, Offset(numDmgEmitterAreas, VehicleData),
  483. "Number of damageEmitterOffset values to use for each damageEmitter.\n\n"
  484. "@see damageEmitterOffset" );
  485. addField( "splashEmitter", TYPEID< ParticleEmitterData >(), Offset(splashEmitterList, VehicleData), VC_NUM_SPLASH_EMITTERS,
  486. "Array of particle emitters used to generate splash effects." );
  487. addField( "splashFreqMod", TypeF32, Offset(splashFreqMod, VehicleData),
  488. "@brief Number of splash particles to generate based on vehicle speed.\n\n"
  489. "This value is multiplied by the current speed to determine how many "
  490. "particles to generate each frame." );
  491. addField( "splashVelEpsilon", TypeF32, Offset(splashVelEpsilon, VehicleData),
  492. "Minimum speed when moving through water to generate splash particles." );
  493. addField( "exitSplashSoundVelocity", TypeF32, Offset(exitSplashSoundVel, VehicleData),
  494. "Minimum velocity when leaving the water for the exitingWater sound to play." );
  495. addField( "softSplashSoundVelocity", TypeF32, Offset(softSplashSoundVel, VehicleData),
  496. "Minimum velocity when entering the water for the imapactWaterEasy sound "
  497. "to play.\n\n@see impactWaterEasy" );
  498. addField( "mediumSplashSoundVelocity", TypeF32, Offset(medSplashSoundVel, VehicleData),
  499. "Minimum velocity when entering the water for the imapactWaterMedium sound "
  500. "to play.\n\n@see impactWaterMedium" );
  501. addField( "hardSplashSoundVelocity", TypeF32, Offset(hardSplashSoundVel, VehicleData),
  502. "Minimum velocity when entering the water for the imapactWaterHard sound "
  503. "to play.\n\n@see impactWaterHard" );
  504. addField( "exitingWater", TYPEID< SFXProfile >(), Offset(waterSound[ExitWater], VehicleData),
  505. "Sound to play when exiting the water." );
  506. addField( "impactWaterEasy", TYPEID< SFXProfile >(), Offset(waterSound[ImpactSoft], VehicleData),
  507. "Sound to play when entering the water with speed >= softSplashSoundVelocity "
  508. "and < mediumSplashSoundVelocity." );
  509. addField( "impactWaterMedium", TYPEID< SFXProfile >(), Offset(waterSound[ImpactMedium], VehicleData),
  510. "Sound to play when entering the water with speed >= mediumSplashSoundVelocity "
  511. "and < hardSplashSoundVelocity." );
  512. addField( "impactWaterHard", TYPEID< SFXProfile >(), Offset(waterSound[ImpactHard], VehicleData),
  513. "Sound to play when entering the water with speed >= hardSplashSoundVelocity." );
  514. addField( "waterWakeSound", TYPEID< SFXProfile >(), Offset(waterSound[Wake], VehicleData),
  515. "Looping sound to play while moving through the water." );
  516. addField( "collDamageThresholdVel", TypeF32, Offset(collDamageThresholdVel, VehicleData),
  517. "Minimum collision velocity to cause damage to this vehicle.\nCurrently unused." );
  518. addField( "collDamageMultiplier", TypeF32, Offset(collDamageMultiplier, VehicleData),
  519. "@brief Damage to this vehicle after a collision (multiplied by collision "
  520. "velocity).\n\nCurrently unused." );
  521. Parent::initPersistFields();
  522. }
  523. //----------------------------------------------------------------------------
  524. //----------------------------------------------------------------------------
  525. //----------------------------------------------------------------------------
  526. IMPLEMENT_CONOBJECT(Vehicle);
  527. ConsoleDocClass( Vehicle,
  528. "@brief Base functionality shared by all Vehicles (FlyingVehicle, HoverVehicle, "
  529. "WheeledVehicle).\n\n"
  530. "This object implements functionality shared by all Vehicle types, but should "
  531. "not be instantiated directly. Create a FlyingVehicle, HoverVehicle, or "
  532. "WheeledVehicle instead.\n"
  533. "@note The model used for any Vehicle must include a collision mesh at detail "
  534. "size -1.\n"
  535. "@ingroup Vehicles\n"
  536. );
  537. Vehicle::Vehicle()
  538. {
  539. mDataBlock = 0;
  540. mTypeMask |= VehicleObjectType | DynamicShapeObjectType;
  541. mDelta.pos = Point3F(0,0,0);
  542. mDelta.posVec = Point3F(0,0,0);
  543. mDelta.warpTicks = mDelta.warpCount = 0;
  544. mDelta.dt = 1;
  545. mDelta.move = NullMove;
  546. mPredictionCount = 0;
  547. mDelta.cameraOffset.set(0,0,0);
  548. mDelta.cameraVec.set(0,0,0);
  549. mDelta.cameraRot.set(0,0,0);
  550. mDelta.cameraRotVec.set(0,0,0);
  551. mRigid.linPosition.set(0, 0, 0);
  552. mRigid.linVelocity.set(0, 0, 0);
  553. mRigid.angPosition.identity();
  554. mRigid.angVelocity.set(0, 0, 0);
  555. mRigid.linMomentum.set(0, 0, 0);
  556. mRigid.angMomentum.set(0, 0, 0);
  557. mContacts.clear();
  558. mSteering.set(0,0);
  559. mThrottle = 0;
  560. mJetting = false;
  561. mCameraOffset.set(0,0,0);
  562. dMemset( mDamageEmitterList, 0, sizeof( mDamageEmitterList ) );
  563. mDisableMove = false;
  564. restCount = 0;
  565. inLiquid = false;
  566. mWakeSound = NULL;
  567. mWorkingQueryBox.minExtents.set(-1e9f, -1e9f, -1e9f);
  568. mWorkingQueryBox.maxExtents.set(-1e9f, -1e9f, -1e9f);
  569. mWorkingQueryBoxCountDown = sWorkingQueryBoxStaleThreshold;
  570. mPhysicsRep = NULL;
  571. }
  572. U32 Vehicle::getCollisionMask()
  573. {
  574. AssertFatal(false, "Vehicle::getCollisionMask is pure virtual!");
  575. return 0;
  576. }
  577. //----------------------------------------------------------------------------
  578. bool Vehicle::onAdd()
  579. {
  580. if (!Parent::onAdd())
  581. return false;
  582. mWorkingQueryBox.minExtents.set(-1e9f, -1e9f, -1e9f);
  583. mWorkingQueryBox.maxExtents.set(-1e9f, -1e9f, -1e9f);
  584. // When loading from a mission script, the base SceneObject's transform
  585. // will have been set and needs to be transfered to the rigid body.
  586. mRigid.setTransform(mObjToWorld);
  587. // Initialize interpolation vars.
  588. mDelta.rot[1] = mDelta.rot[0] = mRigid.angPosition;
  589. mDelta.pos = mRigid.linPosition;
  590. mDelta.posVec = Point3F(0,0,0);
  591. // Create Emitters on the client
  592. if( isClientObject() )
  593. {
  594. U32 j;
  595. for( j=0; j<VehicleData::VC_NUM_DAMAGE_EMITTERS; j++ )
  596. {
  597. if( mDataBlock->damageEmitterList[j] )
  598. {
  599. mDamageEmitterList[j] = new ParticleEmitter;
  600. mDamageEmitterList[j]->onNewDataBlock( mDataBlock->damageEmitterList[j], false );
  601. if( !mDamageEmitterList[j]->registerObject() )
  602. {
  603. Con::warnf( ConsoleLogEntry::General, "Could not register damage emitter for class: %s", mDataBlock->getName() );
  604. delete mDamageEmitterList[j];
  605. mDamageEmitterList[j] = NULL;
  606. }
  607. }
  608. }
  609. }
  610. // Create a new convex.
  611. AssertFatal(mDataBlock->collisionDetails[0] != -1, "Error, a vehicle must have a collision-1 detail!");
  612. mConvex.mObject = this;
  613. mConvex.pShapeBase = this;
  614. mConvex.hullId = 0;
  615. mConvex.box = mObjBox;
  616. mConvex.box.minExtents.convolve(mObjScale);
  617. mConvex.box.maxExtents.convolve(mObjScale);
  618. mConvex.findNodeTransform();
  619. _createPhysics();
  620. return true;
  621. }
  622. void Vehicle::onRemove()
  623. {
  624. SAFE_DELETE(mPhysicsRep);
  625. U32 i=0;
  626. for( i=0; i<VehicleData::VC_NUM_DAMAGE_EMITTERS; i++ )
  627. {
  628. if( mDamageEmitterList[i] )
  629. {
  630. mDamageEmitterList[i]->deleteWhenEmpty();
  631. mDamageEmitterList[i] = NULL;
  632. }
  633. }
  634. mWorkingQueryBox.minExtents.set(-1e9f, -1e9f, -1e9f);
  635. mWorkingQueryBox.maxExtents.set(-1e9f, -1e9f, -1e9f);
  636. Parent::onRemove();
  637. }
  638. //----------------------------------------------------------------------------
  639. void Vehicle::processTick(const Move* move)
  640. {
  641. PROFILE_SCOPE( Vehicle_ProcessTick );
  642. ShapeBase::processTick(move);
  643. if ( isMounted() )
  644. return;
  645. // Warp to catch up to server
  646. if (mDelta.warpCount < mDelta.warpTicks)
  647. {
  648. mDelta.warpCount++;
  649. // Set new pos.
  650. mObjToWorld.getColumn(3,&mDelta.pos);
  651. mDelta.pos += mDelta.warpOffset;
  652. mDelta.rot[0] = mDelta.rot[1];
  653. mDelta.rot[1].interpolate(mDelta.warpRot[0],mDelta.warpRot[1],F32(mDelta.warpCount)/mDelta.warpTicks);
  654. setPosition(mDelta.pos,mDelta.rot[1]);
  655. // Pos backstepping
  656. mDelta.posVec.x = -mDelta.warpOffset.x;
  657. mDelta.posVec.y = -mDelta.warpOffset.y;
  658. mDelta.posVec.z = -mDelta.warpOffset.z;
  659. }
  660. else
  661. {
  662. if (!move)
  663. {
  664. if (isGhost())
  665. {
  666. // If we haven't run out of prediction time,
  667. // predict using the last known move.
  668. if (mPredictionCount-- <= 0)
  669. return;
  670. move = &mDelta.move;
  671. }
  672. else
  673. move = &NullMove;
  674. }
  675. // Process input move
  676. updateMove(move);
  677. // Save current rigid state interpolation
  678. mDelta.posVec = mRigid.linPosition;
  679. mDelta.rot[0] = mRigid.angPosition;
  680. // Update the physics based on the integration rate
  681. S32 count = mDataBlock->integration;
  682. --mWorkingQueryBoxCountDown;
  683. if (!mDisableMove)
  684. updateWorkingCollisionSet(getCollisionMask());
  685. for (U32 i = 0; i < count; i++)
  686. updatePos(TickSec / count);
  687. // Wrap up interpolation info
  688. mDelta.pos = mRigid.linPosition;
  689. mDelta.posVec -= mRigid.linPosition;
  690. mDelta.rot[1] = mRigid.angPosition;
  691. // Update container database
  692. setPosition(mRigid.linPosition, mRigid.angPosition);
  693. setMaskBits(PositionMask);
  694. updateContainer();
  695. //TODO: Only update when position has actually changed
  696. //no need to check if mDataBlock->enablePhysicsRep is false as mPhysicsRep will be NULL if it is
  697. if (mPhysicsRep)
  698. mPhysicsRep->moveKinematicTo(getTransform());
  699. }
  700. }
  701. void Vehicle::advanceTime(F32 dt)
  702. {
  703. PROFILE_SCOPE( Vehicle_AdvanceTime );
  704. Parent::advanceTime(dt);
  705. updateLiftoffDust( dt );
  706. updateDamageSmoke( dt );
  707. }
  708. //----------------------------------------------------------------------------
  709. bool Vehicle::onNewDataBlock(GameBaseData* dptr,bool reload)
  710. {
  711. mDataBlock = dynamic_cast<VehicleData*>(dptr);
  712. if (!mDataBlock || !Parent::onNewDataBlock(dptr, reload))
  713. return false;
  714. // Update Rigid Info
  715. mRigid.mass = mDataBlock->mass;
  716. mRigid.oneOverMass = 1 / mRigid.mass;
  717. mRigid.friction = mDataBlock->body.friction;
  718. mRigid.restitution = mDataBlock->body.restitution;
  719. mRigid.setCenterOfMass(mDataBlock->massCenter);
  720. // Ignores massBox, just set sphere for now. Derived objects
  721. // can set what they want.
  722. mRigid.setObjectInertia();
  723. if (isGhost())
  724. {
  725. // Create the sound ahead of time. This reduces runtime
  726. // costs and makes the system easier to understand.
  727. SFX_DELETE( mWakeSound );
  728. if ( mDataBlock->waterSound[VehicleData::Wake] )
  729. mWakeSound = SFX->createSource( mDataBlock->waterSound[VehicleData::Wake], &getTransform() );
  730. }
  731. return true;
  732. }
  733. //----------------------------------------------------------------------------
  734. void Vehicle::getCameraParameters(F32 *min,F32* max,Point3F* off,MatrixF* rot)
  735. {
  736. *min = mDataBlock->cameraMinDist;
  737. *max = mDataBlock->cameraMaxDist;
  738. off->set(0,0,mDataBlock->cameraOffset);
  739. rot->identity();
  740. }
  741. //----------------------------------------------------------------------------
  742. void Vehicle::getCameraTransform(F32* pos, MatrixF* mat)
  743. {
  744. // Returns camera to world space transform
  745. // Handles first person / third person camera position
  746. if (isServerObject() && mShapeInstance)
  747. mShapeInstance->animateNodeSubtrees(true);
  748. if (*pos == 0)
  749. {
  750. getRenderEyeTransform(mat);
  751. }
  752. else
  753. {
  754. // Get the shape's camera parameters.
  755. F32 min, max;
  756. MatrixF rot;
  757. Point3F offset;
  758. getCameraParameters(&min, &max, &offset, &rot);
  759. // Start with the current eye position
  760. MatrixF eye;
  761. getRenderEyeTransform(&eye);
  762. // Build a transform that points along the eye axis
  763. // but where the Z axis is always up.
  764. if (mDataBlock->cameraRoll)
  765. mat->mul(eye, rot);
  766. else
  767. {
  768. MatrixF cam(1);
  769. VectorF x, y, z(0, 0, 1);
  770. eye.getColumn(1, &y);
  771. mCross(y, z, &x);
  772. x.normalize();
  773. mCross(x, y, &z);
  774. z.normalize();
  775. cam.setColumn(0, x);
  776. cam.setColumn(1, y);
  777. cam.setColumn(2, z);
  778. mat->mul(cam, rot);
  779. }
  780. // Camera is positioned straight back along the eye's -Y axis.
  781. // A ray is cast to make sure the camera doesn't go through
  782. // anything solid.
  783. VectorF vp, vec;
  784. vp.x = vp.z = 0;
  785. vp.y = -(max - min) * *pos;
  786. eye.mulV(vp, &vec);
  787. // Use the camera node as the starting position if it exists.
  788. Point3F osp, sp;
  789. if (mDataBlock->cameraNode != -1)
  790. {
  791. mShapeInstance->mNodeTransforms[mDataBlock->cameraNode].getColumn(3, &osp);
  792. getRenderTransform().mulP(osp, &sp);
  793. }
  794. else
  795. eye.getColumn(3, &sp);
  796. // Make sure we don't hit ourself...
  797. disableCollision();
  798. if (isMounted())
  799. getObjectMount()->disableCollision();
  800. // Cast the ray into the container database to see if we're going
  801. // to hit anything.
  802. RayInfo collision;
  803. Point3F ep = sp + vec + offset + mCameraOffset;
  804. if (mContainer->castRay(sp, ep,
  805. ~(WaterObjectType | GameBaseObjectType | DefaultObjectType | sTriggerMask),
  806. &collision) == true) {
  807. // Shift the collision point back a little to try and
  808. // avoid clipping against the front camera plane.
  809. F32 t = collision.t - (-mDot(vec, collision.normal) / vec.len()) * 0.1;
  810. if (t > 0.0f)
  811. ep = sp + offset + mCameraOffset + (vec * t);
  812. else
  813. eye.getColumn(3, &ep);
  814. }
  815. mat->setColumn(3, ep);
  816. // Re-enable our collision.
  817. if (isMounted())
  818. getObjectMount()->enableCollision();
  819. enableCollision();
  820. }
  821. // Apply Camera FX.
  822. mat->mul( gCamFXMgr.getTrans() );
  823. }
  824. //----------------------------------------------------------------------------
  825. void Vehicle::updateMove(const Move* move)
  826. {
  827. PROFILE_SCOPE( Vehicle_UpdateMove );
  828. mDelta.move = *move;
  829. // Image Triggers
  830. if (mDamageState == Enabled) {
  831. setImageTriggerState(0,move->trigger[0]);
  832. setImageTriggerState(1,move->trigger[1]);
  833. }
  834. // Throttle
  835. if(!mDisableMove)
  836. mThrottle = move->y;
  837. // Steering
  838. if (move != &NullMove) {
  839. F32 y = move->yaw;
  840. mSteering.x = mClampF(mSteering.x + y,-mDataBlock->maxSteeringAngle,
  841. mDataBlock->maxSteeringAngle);
  842. F32 p = move->pitch;
  843. mSteering.y = mClampF(mSteering.y + p,-mDataBlock->maxSteeringAngle,
  844. mDataBlock->maxSteeringAngle);
  845. }
  846. else {
  847. mSteering.x = 0;
  848. mSteering.y = 0;
  849. }
  850. // Steering return
  851. if(mDataBlock->steeringReturn > 0.0f &&
  852. (!mDataBlock->powerSteering || (move->yaw == 0.0f && move->pitch == 0.0f)))
  853. {
  854. Point2F returnAmount(mSteering.x * mDataBlock->steeringReturn * TickSec,
  855. mSteering.y * mDataBlock->steeringReturn * TickSec);
  856. if(mDataBlock->steeringReturnSpeedScale > 0.0f)
  857. {
  858. Point3F vel;
  859. mWorldToObj.mulV(getVelocity(), &vel);
  860. returnAmount += Point2F(mSteering.x * vel.y * mDataBlock->steeringReturnSpeedScale * TickSec,
  861. mSteering.y * vel.y * mDataBlock->steeringReturnSpeedScale * TickSec);
  862. }
  863. mSteering -= returnAmount;
  864. }
  865. // Jetting flag
  866. if (move->trigger[3]) {
  867. if (!mJetting && getEnergyLevel() >= mDataBlock->minJetEnergy)
  868. mJetting = true;
  869. if (mJetting) {
  870. F32 newEnergy = getEnergyLevel() - mDataBlock->jetEnergyDrain;
  871. if (newEnergy < 0) {
  872. newEnergy = 0;
  873. mJetting = false;
  874. }
  875. setEnergyLevel(newEnergy);
  876. }
  877. }
  878. else
  879. mJetting = false;
  880. }
  881. //----------------------------------------------------------------------------
  882. /** Update the physics
  883. */
  884. void Vehicle::updatePos(F32 dt)
  885. {
  886. PROFILE_SCOPE( Vehicle_UpdatePos );
  887. Point3F origVelocity = mRigid.linVelocity;
  888. // Update internal forces acting on the body.
  889. mRigid.clearForces();
  890. updateForces(dt);
  891. // Update collision information based on our current pos.
  892. bool collided = false;
  893. if (!mRigid.atRest && !mDisableMove)
  894. {
  895. collided = updateCollision(dt);
  896. // Now that all the forces have been processed, lets
  897. // see if we're at rest. Basically, if the kinetic energy of
  898. // the vehicles is less than some percentage of the energy added
  899. // by gravity for a short period, we're considered at rest.
  900. // This should really be part of the rigid class...
  901. if (mCollisionList.getCount())
  902. {
  903. F32 k = mRigid.getKineticEnergy();
  904. F32 G = mNetGravity * dt;
  905. F32 Kg = 0.5 * mRigid.mass * G * G;
  906. if (k < sRestTol * Kg && ++restCount > sRestCount)
  907. mRigid.setAtRest();
  908. }
  909. else
  910. restCount = 0;
  911. }
  912. // Integrate forward
  913. if (!mRigid.atRest && !mDisableMove)
  914. mRigid.integrate(dt);
  915. // Deal with client and server scripting, sounds, etc.
  916. if (isServerObject()) {
  917. // Check triggers and other objects that we normally don't
  918. // collide with. This function must be called before notifyCollision
  919. // as it will queue collision.
  920. checkTriggers();
  921. // Invoke the onCollision notify callback for all the objects
  922. // we've just hit.
  923. notifyCollision();
  924. // Server side impact script callback
  925. if (collided) {
  926. VectorF collVec = mRigid.linVelocity - origVelocity;
  927. F32 collSpeed = collVec.len();
  928. if (collSpeed > mDataBlock->minImpactSpeed)
  929. onImpact(collVec);
  930. }
  931. // Water script callbacks
  932. if (!inLiquid && mWaterCoverage != 0.0f) {
  933. mDataBlock->onEnterLiquid_callback( this, mWaterCoverage, mLiquidType.c_str() );
  934. inLiquid = true;
  935. }
  936. else if (inLiquid && mWaterCoverage == 0.0f) {
  937. mDataBlock->onLeaveLiquid_callback( this, mLiquidType.c_str() );
  938. inLiquid = false;
  939. }
  940. }
  941. else {
  942. // Play impact sounds on the client.
  943. if (collided) {
  944. F32 collSpeed = (mRigid.linVelocity - origVelocity).len();
  945. S32 impactSound = -1;
  946. if (collSpeed >= mDataBlock->hardImpactSpeed)
  947. impactSound = VehicleData::Body::HardImpactSound;
  948. else
  949. if (collSpeed >= mDataBlock->softImpactSpeed)
  950. impactSound = VehicleData::Body::SoftImpactSound;
  951. if (impactSound != -1 && mDataBlock->body.sound[impactSound] != NULL)
  952. SFX->playOnce( mDataBlock->body.sound[impactSound], &getTransform() );
  953. }
  954. // Water volume sounds
  955. F32 vSpeed = getVelocity().len();
  956. if (!inLiquid && mWaterCoverage >= 0.8f) {
  957. if (vSpeed >= mDataBlock->hardSplashSoundVel)
  958. SFX->playOnce( mDataBlock->waterSound[VehicleData::ImpactHard], &getTransform() );
  959. else
  960. if (vSpeed >= mDataBlock->medSplashSoundVel)
  961. SFX->playOnce( mDataBlock->waterSound[VehicleData::ImpactMedium], &getTransform() );
  962. else
  963. if (vSpeed >= mDataBlock->softSplashSoundVel)
  964. SFX->playOnce( mDataBlock->waterSound[VehicleData::ImpactSoft], &getTransform() );
  965. inLiquid = true;
  966. }
  967. else
  968. if(inLiquid && mWaterCoverage < 0.8f) {
  969. if (vSpeed >= mDataBlock->exitSplashSoundVel)
  970. SFX->playOnce( mDataBlock->waterSound[VehicleData::ExitWater], &getTransform() );
  971. inLiquid = false;
  972. }
  973. }
  974. }
  975. //----------------------------------------------------------------------------
  976. void Vehicle::updateForces(F32 /*dt*/)
  977. {
  978. // Nothing here.
  979. }
  980. /** The callback used in by the checkTriggers() method.
  981. The checkTriggers method uses a container search which will
  982. invoke this callback on each obj that matches.
  983. */
  984. void Vehicle::findCallback(SceneObject* obj,void *key)
  985. {
  986. Vehicle* vehicle = reinterpret_cast<Vehicle*>(key);
  987. U32 objectMask = obj->getTypeMask();
  988. // Check: triggers, corpses and items, basically the same things
  989. // that the player class checks for
  990. if (objectMask & TriggerObjectType) {
  991. Trigger* pTrigger = static_cast<Trigger*>(obj);
  992. pTrigger->potentialEnterObject(vehicle);
  993. }
  994. else if (objectMask & CorpseObjectType) {
  995. ShapeBase* col = static_cast<ShapeBase*>(obj);
  996. vehicle->queueCollision(col,vehicle->getVelocity() - col->getVelocity());
  997. }
  998. else if (objectMask & ItemObjectType) {
  999. Item* item = static_cast<Item*>(obj);
  1000. if (vehicle != item->getCollisionObject())
  1001. vehicle->queueCollision(item,vehicle->getVelocity() - item->getVelocity());
  1002. }
  1003. }
  1004. //----------------------------------------------------------------------------
  1005. void Vehicle::writePacketData(GameConnection *connection, BitStream *stream)
  1006. {
  1007. Parent::writePacketData(connection, stream);
  1008. mathWrite(*stream, mSteering);
  1009. mathWrite(*stream, mRigid.linPosition);
  1010. mathWrite(*stream, mRigid.angPosition);
  1011. mathWrite(*stream, mRigid.linMomentum);
  1012. mathWrite(*stream, mRigid.angMomentum);
  1013. stream->writeFlag(mRigid.atRest);
  1014. stream->writeFlag(mContacts.getCount() == 0);
  1015. stream->writeFlag(mDisableMove);
  1016. stream->setCompressionPoint(mRigid.linPosition);
  1017. }
  1018. void Vehicle::readPacketData(GameConnection *connection, BitStream *stream)
  1019. {
  1020. Parent::readPacketData(connection, stream);
  1021. mathRead(*stream, &mSteering);
  1022. mathRead(*stream, &mRigid.linPosition);
  1023. mathRead(*stream, &mRigid.angPosition);
  1024. mathRead(*stream, &mRigid.linMomentum);
  1025. mathRead(*stream, &mRigid.angMomentum);
  1026. mRigid.atRest = stream->readFlag();
  1027. if (stream->readFlag())
  1028. mContacts.clear();
  1029. mRigid.updateInertialTensor();
  1030. mRigid.updateVelocity();
  1031. mRigid.updateCenterOfMass();
  1032. mDisableMove = stream->readFlag();
  1033. stream->setCompressionPoint(mRigid.linPosition);
  1034. }
  1035. //----------------------------------------------------------------------------
  1036. U32 Vehicle::packUpdate(NetConnection *con, U32 mask, BitStream *stream)
  1037. {
  1038. U32 retMask = Parent::packUpdate(con, mask, stream);
  1039. stream->writeFlag(mJetting);
  1040. // The rest of the data is part of the control object packet update.
  1041. // If we're controlled by this client, we don't need to send it.
  1042. if (stream->writeFlag(getControllingClient() == con && !(mask & InitialUpdateMask)))
  1043. return retMask;
  1044. F32 yaw = (mSteering.x + mDataBlock->maxSteeringAngle) / (2 * mDataBlock->maxSteeringAngle);
  1045. F32 pitch = (mSteering.y + mDataBlock->maxSteeringAngle) / (2 * mDataBlock->maxSteeringAngle);
  1046. stream->writeFloat(yaw,9);
  1047. stream->writeFloat(pitch,9);
  1048. mDelta.move.pack(stream);
  1049. if (stream->writeFlag(mask & PositionMask))
  1050. {
  1051. stream->writeCompressedPoint(mRigid.linPosition);
  1052. mathWrite(*stream, mRigid.angPosition);
  1053. mathWrite(*stream, mRigid.linMomentum);
  1054. mathWrite(*stream, mRigid.angMomentum);
  1055. stream->writeFlag(mRigid.atRest);
  1056. }
  1057. stream->writeFloat(mClampF(getEnergyValue(), 0.f, 1.f), 8);
  1058. return retMask;
  1059. }
  1060. void Vehicle::unpackUpdate(NetConnection *con, BitStream *stream)
  1061. {
  1062. Parent::unpackUpdate(con,stream);
  1063. mJetting = stream->readFlag();
  1064. if (stream->readFlag())
  1065. return;
  1066. F32 yaw = stream->readFloat(9);
  1067. F32 pitch = stream->readFloat(9);
  1068. mSteering.x = (2 * yaw * mDataBlock->maxSteeringAngle) - mDataBlock->maxSteeringAngle;
  1069. mSteering.y = (2 * pitch * mDataBlock->maxSteeringAngle) - mDataBlock->maxSteeringAngle;
  1070. mDelta.move.unpack(stream);
  1071. if (stream->readFlag())
  1072. {
  1073. mPredictionCount = sMaxPredictionTicks;
  1074. F32 speed = mRigid.linVelocity.len();
  1075. mDelta.warpRot[0] = mRigid.angPosition;
  1076. // Read in new position and momentum values
  1077. stream->readCompressedPoint(&mRigid.linPosition);
  1078. mathRead(*stream, &mRigid.angPosition);
  1079. mathRead(*stream, &mRigid.linMomentum);
  1080. mathRead(*stream, &mRigid.angMomentum);
  1081. mRigid.atRest = stream->readFlag();
  1082. mRigid.updateVelocity();
  1083. if (isProperlyAdded())
  1084. {
  1085. // Determine number of ticks to warp based on the average
  1086. // of the client and server velocities.
  1087. Point3F cp = mDelta.pos + mDelta.posVec * mDelta.dt;
  1088. mDelta.warpOffset = mRigid.linPosition - cp;
  1089. // Calc the distance covered in one tick as the average of
  1090. // the old speed and the new speed from the server.
  1091. F32 dt,as = (speed + mRigid.linVelocity.len()) * 0.5 * TickSec;
  1092. // Cal how many ticks it will take to cover the warp offset.
  1093. // If it's less than what's left in the current tick, we'll just
  1094. // warp in the remaining time.
  1095. if (!as || (dt = mDelta.warpOffset.len() / as) > sMaxWarpTicks)
  1096. dt = mDelta.dt + sMaxWarpTicks;
  1097. else
  1098. dt = (dt <= mDelta.dt)? mDelta.dt : mCeil(dt - mDelta.dt) + mDelta.dt;
  1099. // Adjust current frame interpolation
  1100. if (mDelta.dt) {
  1101. mDelta.pos = cp + (mDelta.warpOffset * (mDelta.dt / dt));
  1102. mDelta.posVec = (cp - mDelta.pos) / mDelta.dt;
  1103. QuatF cr;
  1104. cr.interpolate(mDelta.rot[1],mDelta.rot[0],mDelta.dt);
  1105. mDelta.rot[1].interpolate(cr,mRigid.angPosition,mDelta.dt / dt);
  1106. mDelta.rot[0].extrapolate(mDelta.rot[1],cr,mDelta.dt);
  1107. }
  1108. // Calculated multi-tick warp
  1109. mDelta.warpCount = 0;
  1110. mDelta.warpTicks = (S32)(mFloor(dt));
  1111. if (mDelta.warpTicks)
  1112. {
  1113. mDelta.warpOffset = mRigid.linPosition - mDelta.pos;
  1114. mDelta.warpOffset /= (F32)mDelta.warpTicks;
  1115. mDelta.warpRot[0] = mDelta.rot[1];
  1116. mDelta.warpRot[1] = mRigid.angPosition;
  1117. }
  1118. }
  1119. else
  1120. {
  1121. // Set the vehicle to the server position
  1122. mDelta.dt = 0;
  1123. mDelta.pos = mRigid.linPosition;
  1124. mDelta.posVec.set(0,0,0);
  1125. mDelta.rot[1] = mDelta.rot[0] = mRigid.angPosition;
  1126. mDelta.warpCount = mDelta.warpTicks = 0;
  1127. setPosition(mRigid.linPosition, mRigid.angPosition);
  1128. }
  1129. mRigid.updateCenterOfMass();
  1130. }
  1131. setEnergyLevel(stream->readFloat(8) * mDataBlock->maxEnergy);
  1132. }
  1133. //----------------------------------------------------------------------------
  1134. void Vehicle::consoleInit()
  1135. {
  1136. Con::addVariable("$vehicle::workingQueryBoxStaleThreshold",TypeS32,&sWorkingQueryBoxStaleThreshold,
  1137. "@brief The maximum number of ticks that go by before the mWorkingQueryBox is considered stale and needs updating.\n\n"
  1138. "Other factors can cause the collision working query box to become invalidated, such as the vehicle moving far "
  1139. "enough outside of this cached box. The smaller this number, the more times the working list of triangles that are "
  1140. "considered for collision is refreshed. This has the greatest impact with colliding with high triangle count meshes.\n\n"
  1141. "@note Set to -1 to disable any time-based forced check.\n\n"
  1142. "@ingroup GameObjects\n");
  1143. Con::addVariable("$vehicle::workingQueryBoxSizeMultiplier",TypeF32,&sWorkingQueryBoxSizeMultiplier,
  1144. "@brief How much larger the mWorkingQueryBox should be made when updating the working collision list.\n\n"
  1145. "The larger this number the less often the working list will be updated due to motion, but any non-static shape that "
  1146. "moves into the query box will not be noticed.\n\n"
  1147. "@ingroup GameObjects\n");
  1148. }
  1149. void Vehicle::initPersistFields()
  1150. {
  1151. addField( "disableMove", TypeBool, Offset(mDisableMove, Vehicle),
  1152. "When this flag is set, the vehicle will ignore throttle changes." );
  1153. Parent::initPersistFields();
  1154. }
  1155. void Vehicle::mountObject(SceneObject *obj, S32 node, const MatrixF &xfm )
  1156. {
  1157. Parent::mountObject( obj, node, xfm );
  1158. // Clear objects off the working list that are from objects mounted to us.
  1159. // (This applies mostly to players...)
  1160. for ( CollisionWorkingList* itr = mConvex.getWorkingList().wLink.mNext;
  1161. itr != &mConvex.getWorkingList();
  1162. itr = itr->wLink.mNext)
  1163. {
  1164. if (itr->mConvex->getObject() == obj)
  1165. {
  1166. CollisionWorkingList* cl = itr;
  1167. itr = itr->wLink.mPrev;
  1168. cl->free();
  1169. }
  1170. }
  1171. }
  1172. //----------------------------------------------------------------------------
  1173. void Vehicle::updateLiftoffDust( F32 dt )
  1174. {
  1175. Point3F offset( 0.0, 0.0, mDataBlock->dustHeight );
  1176. emitDust( mDustEmitterList[ 0 ], mDataBlock->triggerDustHeight, offset,
  1177. ( U32 )( dt * 1000 ) );
  1178. }
  1179. //----------------------------------------------------------------------------
  1180. void Vehicle::updateDamageSmoke( F32 dt )
  1181. {
  1182. for( S32 j=VehicleData::VC_NUM_DAMAGE_LEVELS-1; j>=0; j-- )
  1183. {
  1184. F32 damagePercent = mDamage / mDataBlock->maxDamage;
  1185. if( damagePercent >= mDataBlock->damageLevelTolerance[j] )
  1186. {
  1187. for( S32 i=0; i<mDataBlock->numDmgEmitterAreas; i++ )
  1188. {
  1189. MatrixF trans = getTransform();
  1190. Point3F offset = mDataBlock->damageEmitterOffset[i];
  1191. trans.mulP( offset );
  1192. Point3F emitterPoint = offset;
  1193. if( pointInWater(offset ) )
  1194. {
  1195. U32 emitterOffset = VehicleData::VC_BUBBLE_EMITTER;
  1196. if( mDamageEmitterList[emitterOffset] )
  1197. {
  1198. mDamageEmitterList[emitterOffset]->emitParticles( emitterPoint, emitterPoint, Point3F( 0.0, 0.0, 1.0 ), getVelocity(), (U32)( dt * 1000 ) );
  1199. }
  1200. }
  1201. else
  1202. {
  1203. if( mDamageEmitterList[j] )
  1204. {
  1205. mDamageEmitterList[j]->emitParticles( emitterPoint, emitterPoint, Point3F( 0.0, 0.0, 1.0 ), getVelocity(), (U32)(dt * 1000));
  1206. }
  1207. }
  1208. }
  1209. break;
  1210. }
  1211. }
  1212. }
  1213. //--------------------------------------------------------------------------
  1214. void Vehicle::updateFroth( F32 dt )
  1215. {
  1216. // update bubbles
  1217. Point3F moveDir = getVelocity();
  1218. Point3F contactPoint;
  1219. if( !collidingWithWater( contactPoint ) )
  1220. {
  1221. if ( mWakeSound )
  1222. mWakeSound->stop();
  1223. return;
  1224. }
  1225. F32 speed = moveDir.len();
  1226. if( speed < mDataBlock->splashVelEpsilon ) speed = 0.0;
  1227. U32 emitRate = (U32)(speed * mDataBlock->splashFreqMod * dt);
  1228. U32 i;
  1229. if ( mWakeSound )
  1230. {
  1231. if ( !mWakeSound->isPlaying() )
  1232. mWakeSound->play();
  1233. mWakeSound->setTransform( getTransform() );
  1234. mWakeSound->setVelocity( getVelocity() );
  1235. }
  1236. for( i=0; i<VehicleData::VC_NUM_SPLASH_EMITTERS; i++ )
  1237. {
  1238. if( mSplashEmitterList[i] )
  1239. {
  1240. mSplashEmitterList[i]->emitParticles( contactPoint, contactPoint, Point3F( 0.0, 0.0, 1.0 ),
  1241. moveDir, emitRate );
  1242. }
  1243. }
  1244. }
  1245. void Vehicle::prepBatchRender( SceneRenderState *state, S32 mountedImageIndex )
  1246. {
  1247. Parent::prepBatchRender( state, mountedImageIndex );
  1248. if ( !gShowBoundingBox )
  1249. return;
  1250. if ( mountedImageIndex != -1 )
  1251. {
  1252. ObjectRenderInst *ri = state->getRenderPass()->allocInst<ObjectRenderInst>();
  1253. ri->renderDelegate.bind( this, &Vehicle::_renderMuzzleVector );
  1254. ri->objectIndex = mountedImageIndex;
  1255. ri->type = RenderPassManager::RIT_Editor;
  1256. state->getRenderPass()->addInst( ri );
  1257. return;
  1258. }
  1259. ObjectRenderInst *ri = state->getRenderPass()->allocInst<ObjectRenderInst>();
  1260. ri->renderDelegate.bind( this, &Vehicle::_renderMassAndContacts );
  1261. ri->type = RenderPassManager::RIT_Editor;
  1262. state->getRenderPass()->addInst( ri );
  1263. }
  1264. void Vehicle::_renderMassAndContacts( ObjectRenderInst *ri, SceneRenderState *state, BaseMatInstance *overrideMat )
  1265. {
  1266. GFXStateBlockDesc desc;
  1267. desc.setBlend(false, GFXBlendSrcAlpha, GFXBlendInvSrcAlpha);
  1268. desc.setZReadWrite(false,true);
  1269. desc.fillMode = GFXFillWireframe;
  1270. // Render the mass center.
  1271. GFX->getDrawUtil()->drawCube(desc, Point3F(0.1f,0.1f,0.1f),mDataBlock->massCenter, ColorI(255, 255, 255), &mRenderObjToWorld);
  1272. // Now render all the contact points.
  1273. for (S32 i = 0; i < mCollisionList.getCount(); i++)
  1274. {
  1275. const Collision& collision = mCollisionList[i];
  1276. GFX->getDrawUtil()->drawCube(desc, Point3F(0.05f,0.05f,0.05f),collision.point, ColorI(0, 0, 255));
  1277. }
  1278. // Finally render the normals as one big batch.
  1279. PrimBuild::begin(GFXLineList, mCollisionList.getCount() * 2);
  1280. for (S32 i = 0; i < mCollisionList.getCount(); i++)
  1281. {
  1282. const Collision& collision = mCollisionList[i];
  1283. PrimBuild::color3f(1, 1, 1);
  1284. PrimBuild::vertex3fv(collision.point);
  1285. PrimBuild::vertex3fv(collision.point + collision.normal * 0.05f);
  1286. }
  1287. PrimBuild::end();
  1288. // Build and render the collision polylist which is returned
  1289. // in the server's world space.
  1290. ClippedPolyList polyList;
  1291. polyList.mPlaneList.setSize(6);
  1292. polyList.mPlaneList[0].set(getWorldBox().minExtents,VectorF(-1,0,0));
  1293. polyList.mPlaneList[1].set(getWorldBox().minExtents,VectorF(0,-1,0));
  1294. polyList.mPlaneList[2].set(getWorldBox().minExtents,VectorF(0,0,-1));
  1295. polyList.mPlaneList[3].set(getWorldBox().maxExtents,VectorF(1,0,0));
  1296. polyList.mPlaneList[4].set(getWorldBox().maxExtents,VectorF(0,1,0));
  1297. polyList.mPlaneList[5].set(getWorldBox().maxExtents,VectorF(0,0,1));
  1298. Box3F dummyBox;
  1299. SphereF dummySphere;
  1300. buildPolyList(PLC_Collision, &polyList, dummyBox, dummySphere);
  1301. //polyList.render();
  1302. }
  1303. void Vehicle::_renderMuzzleVector( ObjectRenderInst *ri, SceneRenderState *state, BaseMatInstance *overrideMat )
  1304. {
  1305. const U32 index = ri->objectIndex;
  1306. AssertFatal( index > 0 && index < MaxMountedImages, "Vehicle::_renderMuzzleVector() - Bad object index!" );
  1307. AssertFatal( mMountedImageList[index].dataBlock, "Vehicle::_renderMuzzleVector() - Bad object index!" );
  1308. Point3F muzzlePoint, muzzleVector, endpoint;
  1309. getMuzzlePoint(index, &muzzlePoint);
  1310. getMuzzleVector(index, &muzzleVector);
  1311. endpoint = muzzlePoint + muzzleVector * 250;
  1312. if (mSolidSB.isNull())
  1313. {
  1314. GFXStateBlockDesc desc;
  1315. desc.setBlend(false, GFXBlendSrcAlpha, GFXBlendInvSrcAlpha);
  1316. desc.setZReadWrite(false);
  1317. mSolidSB = GFX->createStateBlock(desc);
  1318. }
  1319. GFX->setStateBlock(mSolidSB);
  1320. PrimBuild::begin(GFXLineList, 2);
  1321. PrimBuild::color4f(0, 1, 0, 1);
  1322. PrimBuild::vertex3fv(muzzlePoint);
  1323. PrimBuild::vertex3fv(endpoint);
  1324. PrimBuild::end();
  1325. }