hoverVehicle.cpp 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977
  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/hoverVehicle.h"
  24. #include "core/stream/bitStream.h"
  25. #include "scene/sceneRenderState.h"
  26. #include "collision/clippedPolyList.h"
  27. #include "collision/planeExtractor.h"
  28. #include "T3D/gameBase/moveManager.h"
  29. #include "ts/tsShapeInstance.h"
  30. #include "console/consoleTypes.h"
  31. #include "scene/sceneManager.h"
  32. #include "sfx/sfxSystem.h"
  33. #include "sfx/sfxProfile.h"
  34. #include "sfx/sfxSource.h"
  35. #include "T3D/fx/particleEmitter.h"
  36. #include "math/mathIO.h"
  37. IMPLEMENT_CO_DATABLOCK_V1(HoverVehicleData);
  38. IMPLEMENT_CO_NETOBJECT_V1(HoverVehicle);
  39. ConsoleDocClass( HoverVehicleData,
  40. "@brief Defines the properties of a HoverVehicle.\n\n"
  41. "@ingroup Vehicles\n"
  42. );
  43. ConsoleDocClass( HoverVehicle,
  44. "@brief A hovering vehicle.\n\n"
  45. "A hover vehicle is a vehicle that maintains a specific distance between the "
  46. "vehicle and the ground at all times; unlike a flying vehicle which is free "
  47. "to ascend and descend at will."
  48. "The model used for the HoverVehicle has the following requirements:\n"
  49. "<dl>"
  50. "<dt>Collision mesh</dt><dd>A convex collision mesh at detail size -1.</dd>"
  51. "<dt>JetNozzle0-1 nodes</dt><dd>Particle emitter nodes used when thrusting "
  52. "forward.</dd>"
  53. "<dt>JetNozzle2-3 nodes</dt><dd>Particle emitter nodes used when thrusting "
  54. "downward.</dd>"
  55. "<dt>JetNozzleX node</dt><dd>Particle emitter node used when thrusting "
  56. "backward.</dd>"
  57. "<dt>activateBack animation</dt><dd>Non-cyclic animation sequence played "
  58. "when the vehicle begins thrusting forwards.</dd>"
  59. "<dt>maintainBack animation</dt><dd>Cyclic animation sequence played after "
  60. "activateBack when the vehicle continues thrusting forwards.</dd>"
  61. "</dl>"
  62. "@ingroup Vehicles\n"
  63. );
  64. namespace {
  65. const U32 sCollisionMoveMask = (TerrainObjectType | PlayerObjectType |
  66. StaticShapeObjectType | VehicleObjectType |
  67. VehicleBlockerObjectType);
  68. const U32 sServerCollisionMask = sCollisionMoveMask; // ItemObjectType
  69. const U32 sClientCollisionMask = sCollisionMoveMask;
  70. void nonFilter(SceneObject* object,void *key)
  71. {
  72. SceneContainer::CallbackInfo* info = reinterpret_cast<SceneContainer::CallbackInfo*>(key);
  73. object->buildPolyList(info->context,info->polyList,info->boundingBox,info->boundingSphere);
  74. }
  75. } // namespace {}
  76. const char* HoverVehicle::sJetSequence[HoverVehicle::JetAnimCount] =
  77. {
  78. "activateBack",
  79. "maintainBack",
  80. };
  81. const char* HoverVehicleData::sJetNode[HoverVehicleData::MaxJetNodes] =
  82. {
  83. "JetNozzle0", // Thrust Forward
  84. "JetNozzle1",
  85. "JetNozzleX", // Thrust Backward
  86. "JetNozzleX",
  87. "JetNozzle2", // Thrust Downward
  88. "JetNozzle3",
  89. };
  90. // Convert thrust direction into nodes & emitters
  91. HoverVehicle::JetActivation HoverVehicle::sJetActivation[NumThrustDirections] = {
  92. { HoverVehicleData::ForwardJetNode, HoverVehicleData::ForwardJetEmitter },
  93. { HoverVehicleData::BackwardJetNode, HoverVehicleData::BackwardJetEmitter },
  94. { HoverVehicleData::DownwardJetNode, HoverVehicleData::DownwardJetEmitter },
  95. };
  96. //--------------------------------------------------------------------------
  97. //--------------------------------------
  98. //
  99. HoverVehicleData::HoverVehicleData()
  100. {
  101. dragForce = 0;
  102. vertFactor = 0.25f;
  103. floatingThrustFactor = 0.15f;
  104. mainThrustForce = 0;
  105. reverseThrustForce = 0;
  106. strafeThrustForce = 0;
  107. turboFactor = 1.0f;
  108. stabLenMin = 0.5f;
  109. stabLenMax = 2.0f;
  110. stabSpringConstant = 30;
  111. stabDampingConstant = 10;
  112. gyroDrag = 10;
  113. normalForce = 30;
  114. restorativeForce = 10;
  115. steeringForce = 25;
  116. rollForce = 2.5f;
  117. pitchForce = 2.5f;
  118. dustTrailEmitter = NULL;
  119. dustTrailID = 0;
  120. dustTrailOffset.set( 0.0f, 0.0f, 0.0f );
  121. dustTrailFreqMod = 15.0f;
  122. maxThrustSpeed = 0;
  123. triggerTrailHeight = 2.5f;
  124. floatingGravMag = 1;
  125. brakingForce = 0;
  126. brakingActivationSpeed = 0;
  127. for (S32 k = 0; k < MaxJetNodes; k++)
  128. jetNode[k] = -1;
  129. for (S32 j = 0; j < MaxJetEmitters; j++)
  130. jetEmitter[j] = 0;
  131. for (S32 i = 0; i < MaxSounds; i++)
  132. sound[i] = 0;
  133. }
  134. HoverVehicleData::~HoverVehicleData()
  135. {
  136. }
  137. //--------------------------------------------------------------------------
  138. void HoverVehicleData::initPersistFields()
  139. {
  140. addField( "dragForce", TypeF32, Offset(dragForce, HoverVehicleData),
  141. "Drag force factor that acts opposite to the vehicle velocity.\nAlso "
  142. "used to determnine the vehicle's maxThrustSpeed.\n@see mainThrustForce" );
  143. addField( "vertFactor", TypeF32, Offset(vertFactor, HoverVehicleData),
  144. "Scalar applied to the vertical portion of the velocity drag acting on "
  145. "the vehicle.\nFor the horizontal (X and Y) components of velocity drag, "
  146. "a factor of 0.25 is applied when the vehicle is floating, and a factor "
  147. "of 1.0 is applied when the vehicle is not floating. This velocity drag "
  148. "is multiplied by the vehicle's dragForce, as defined above, and the "
  149. "result is subtracted from it's movement force.\n"
  150. "@note The vertFactor must be between 0.0 and 1.0 (inclusive)." );
  151. addField( "floatingThrustFactor", TypeF32, Offset(floatingThrustFactor, HoverVehicleData),
  152. "Scalar applied to the vehicle's thrust force when the vehicle is floating.\n"
  153. "@note The floatingThrustFactor must be between 0.0 and 1.0 (inclusive)." );
  154. addField( "mainThrustForce", TypeF32, Offset(mainThrustForce, HoverVehicleData),
  155. "Force generated by thrusting the vehicle forward.\nAlso used to determine "
  156. "the maxThrustSpeed:\n\n"
  157. "@tsexample\n"
  158. "maxThrustSpeed = (mainThrustForce + strafeThrustForce) / dragForce;\n"
  159. "@endtsexample\n" );
  160. addField( "reverseThrustForce", TypeF32, Offset(reverseThrustForce, HoverVehicleData),
  161. "Force generated by thrusting the vehicle backward." );
  162. addField( "strafeThrustForce", TypeF32, Offset(strafeThrustForce, HoverVehicleData),
  163. "Force generated by thrusting the vehicle to one side.\nAlso used to "
  164. "determine the vehicle's maxThrustSpeed.\n@see mainThrustForce" );
  165. addField( "turboFactor", TypeF32, Offset(turboFactor, HoverVehicleData),
  166. "Scale factor applied to the vehicle's thrust force when jetting." );
  167. addField( "stabLenMin", TypeF32, Offset(stabLenMin, HoverVehicleData),
  168. "Length of the base stabalizer when travelling at minimum speed (0).\n"
  169. "Each tick, the vehicle performs 2 raycasts (from the center back and "
  170. "center front of the vehicle) to check for contact with the ground. The "
  171. "base stabalizer length determines the length of that raycast; if "
  172. "neither raycast hit the ground, the vehicle is floating, stabalizer "
  173. "spring and ground normal forces are not applied.\n\n"
  174. "<img src=\"images/hoverVehicle_forces.png\">\n"
  175. "@see stabSpringConstant" );
  176. addField( "stabLenMax", TypeF32, Offset(stabLenMax, HoverVehicleData),
  177. "Length of the base stabalizer when travelling at maximum speed "
  178. "(maxThrustSpeed).\n\n@see stabLenMin\n\n@see mainThrustForce" );
  179. addField( "stabSpringConstant", TypeF32, Offset(stabSpringConstant, HoverVehicleData),
  180. "Value used to generate stabalizer spring force. The force generated "
  181. "depends on stabilizer compression, that is how close the vehicle is "
  182. "to the ground proportional to current stabalizer length.\n\n"
  183. "@see stabLenMin" );
  184. addField( "stabDampingConstant", TypeF32, Offset(stabDampingConstant, HoverVehicleData),
  185. "Damping spring force acting against changes in the stabalizer length.\n\n"
  186. "@see stabLenMin" );
  187. addField( "gyroDrag", TypeF32, Offset(gyroDrag, HoverVehicleData),
  188. "Damping torque that acts against the vehicle's current angular momentum." );
  189. addField( "normalForce", TypeF32, Offset(normalForce, HoverVehicleData),
  190. "Force generated in the ground normal direction when the vehicle is not "
  191. "floating (within stabalizer length from the ground).\n\n"
  192. "@see stabLenMin" );
  193. addField( "restorativeForce", TypeF32, Offset(restorativeForce, HoverVehicleData),
  194. "Force generated to stabalize the vehicle (return it to neutral pitch/roll) "
  195. "when the vehicle is floating (more than stabalizer length from the "
  196. "ground.\n\n@see stabLenMin" );
  197. addField( "steeringForce", TypeF32, Offset(steeringForce, HoverVehicleData),
  198. "Yaw (rotation about the Z-axis) force applied when steering in the x-axis direction."
  199. "about the vehicle's Z-axis)" );
  200. addField( "rollForce", TypeF32, Offset(rollForce, HoverVehicleData),
  201. "Roll (rotation about the Y-axis) force applied when steering in the x-axis direction." );
  202. addField( "pitchForce", TypeF32, Offset(pitchForce, HoverVehicleData),
  203. "Pitch (rotation about the X-axis) force applied when steering in the y-axis direction." );
  204. addField( "jetSound", TYPEID< SFXProfile >(), Offset(sound[JetSound], HoverVehicleData),
  205. "Looping sound played when the vehicle is jetting." );
  206. addField( "engineSound", TYPEID< SFXProfile >(), Offset(sound[EngineSound], HoverVehicleData),
  207. "Looping engine sound.\nThe volume is dynamically adjusted based on the "
  208. "current thrust level." );
  209. addField( "floatSound", TYPEID< SFXProfile >(), Offset(sound[FloatSound], HoverVehicleData),
  210. "Looping sound played while the vehicle is floating.\n\n@see stabMinLen" );
  211. addField( "dustTrailEmitter", TYPEID< ParticleEmitterData >(), Offset(dustTrailEmitter, HoverVehicleData),
  212. "Emitter to generate particles for the vehicle's dust trail.\nThe trail "
  213. "of dust particles is generated only while the vehicle is moving." );
  214. addField( "dustTrailOffset", TypePoint3F, Offset(dustTrailOffset, HoverVehicleData),
  215. "\"X Y Z\" offset from the vehicle's origin from which to generate dust "
  216. "trail particles.\nBy default particles are emitted directly beneath the "
  217. "origin of the vehicle model." );
  218. addField( "triggerTrailHeight", TypeF32, Offset(triggerTrailHeight, HoverVehicleData),
  219. "Maximum height above surface to emit dust trail particles.\nIf the vehicle "
  220. "is less than triggerTrailHeight above a static surface with a material that "
  221. "has 'showDust' set to true, the vehicle will emit particles from the "
  222. "dustTrailEmitter." );
  223. addField( "dustTrailFreqMod", TypeF32, Offset(dustTrailFreqMod, HoverVehicleData),
  224. "Number of dust trail particles to generate based on vehicle speed.\nThe "
  225. "vehicle's speed is divided by this value to determine how many particles "
  226. "to generate each frame. Lower values give a more dense trail, higher "
  227. "values a more sparse trail." );
  228. addField( "floatingGravMag", TypeF32, Offset(floatingGravMag, HoverVehicleData),
  229. "Scale factor applied to the vehicle gravitational force when the vehicle "
  230. "is floating.\n\n@see stabLenMin" );
  231. addField( "brakingForce", TypeF32, Offset(brakingForce, HoverVehicleData),
  232. "Force generated by braking.\nThe vehicle is considered to be braking if "
  233. "it is moving, but the throttle is off, and no left or right thrust is "
  234. "being applied. This force is only applied when the vehicle's velocity is "
  235. "less than brakingActivationSpeed." );
  236. addField( "brakingActivationSpeed", TypeF32, Offset(brakingActivationSpeed, HoverVehicleData),
  237. "Maximum speed below which a braking force is applied.\n\n@see brakingForce" );
  238. addField( "forwardJetEmitter", TYPEID< ParticleEmitterData >(), Offset(jetEmitter[ForwardJetEmitter], HoverVehicleData),
  239. "Emitter to generate particles for forward jet thrust.\nForward jet "
  240. "thrust particles are emitted from model nodes JetNozzle0 and JetNozzle1." );
  241. Parent::initPersistFields();
  242. }
  243. //--------------------------------------------------------------------------
  244. bool HoverVehicleData::onAdd()
  245. {
  246. if(!Parent::onAdd())
  247. return false;
  248. return true;
  249. }
  250. bool HoverVehicleData::preload(bool server, String &errorStr)
  251. {
  252. if (Parent::preload(server, errorStr) == false)
  253. return false;
  254. if (dragForce <= 0.01f) {
  255. Con::warnf("HoverVehicleData::preload: dragForce must be at least 0.01");
  256. dragForce = 0.01f;
  257. }
  258. if (vertFactor < 0.0f || vertFactor > 1.0f) {
  259. Con::warnf("HoverVehicleData::preload: vert factor must be [0, 1]");
  260. vertFactor = vertFactor < 0.0f ? 0.0f : 1.0f;
  261. }
  262. if (floatingThrustFactor < 0.0f || floatingThrustFactor > 1.0f) {
  263. Con::warnf("HoverVehicleData::preload: floatingThrustFactor must be [0, 1]");
  264. floatingThrustFactor = floatingThrustFactor < 0.0f ? 0.0f : 1.0f;
  265. }
  266. maxThrustSpeed = (mainThrustForce + strafeThrustForce) / dragForce;
  267. massCenter = Point3F(0, 0, 0);
  268. // Resolve objects transmitted from server
  269. if (!server) {
  270. for (S32 i = 0; i < MaxSounds; i++)
  271. if (sound[i])
  272. Sim::findObject(SimObjectId((uintptr_t)sound[i]),sound[i]);
  273. for (S32 j = 0; j < MaxJetEmitters; j++)
  274. if (jetEmitter[j])
  275. Sim::findObject(SimObjectId((uintptr_t)jetEmitter[j]),jetEmitter[j]);
  276. }
  277. if( !dustTrailEmitter && dustTrailID != 0 )
  278. {
  279. if( !Sim::findObject( dustTrailID, dustTrailEmitter ) )
  280. {
  281. Con::errorf( ConsoleLogEntry::General, "HoverVehicleData::preload Invalid packet, bad datablockId(dustTrailEmitter): 0x%x", dustTrailID );
  282. }
  283. }
  284. // Resolve jet nodes
  285. for (S32 j = 0; j < MaxJetNodes; j++)
  286. jetNode[j] = mShape->findNode(sJetNode[j]);
  287. return true;
  288. }
  289. //--------------------------------------------------------------------------
  290. void HoverVehicleData::packData(BitStream* stream)
  291. {
  292. Parent::packData(stream);
  293. stream->write(dragForce);
  294. stream->write(vertFactor);
  295. stream->write(floatingThrustFactor);
  296. stream->write(mainThrustForce);
  297. stream->write(reverseThrustForce);
  298. stream->write(strafeThrustForce);
  299. stream->write(turboFactor);
  300. stream->write(stabLenMin);
  301. stream->write(stabLenMax);
  302. stream->write(stabSpringConstant);
  303. stream->write(stabDampingConstant);
  304. stream->write(gyroDrag);
  305. stream->write(normalForce);
  306. stream->write(restorativeForce);
  307. stream->write(steeringForce);
  308. stream->write(rollForce);
  309. stream->write(pitchForce);
  310. mathWrite(*stream, dustTrailOffset);
  311. stream->write(triggerTrailHeight);
  312. stream->write(dustTrailFreqMod);
  313. for (S32 i = 0; i < MaxSounds; i++)
  314. if (stream->writeFlag(sound[i]))
  315. stream->writeRangedU32(mPacked ? SimObjectId((uintptr_t)sound[i]):
  316. sound[i]->getId(),DataBlockObjectIdFirst,DataBlockObjectIdLast);
  317. for (S32 j = 0; j < MaxJetEmitters; j++)
  318. {
  319. if (stream->writeFlag(jetEmitter[j]))
  320. {
  321. SimObjectId writtenId = mPacked ? SimObjectId((uintptr_t)jetEmitter[j]) : jetEmitter[j]->getId();
  322. stream->writeRangedU32(writtenId, DataBlockObjectIdFirst,DataBlockObjectIdLast);
  323. }
  324. }
  325. if (stream->writeFlag( dustTrailEmitter ))
  326. {
  327. stream->writeRangedU32( dustTrailEmitter->getId(), DataBlockObjectIdFirst, DataBlockObjectIdLast );
  328. }
  329. stream->write(floatingGravMag);
  330. stream->write(brakingForce);
  331. stream->write(brakingActivationSpeed);
  332. }
  333. void HoverVehicleData::unpackData(BitStream* stream)
  334. {
  335. Parent::unpackData(stream);
  336. stream->read(&dragForce);
  337. stream->read(&vertFactor);
  338. stream->read(&floatingThrustFactor);
  339. stream->read(&mainThrustForce);
  340. stream->read(&reverseThrustForce);
  341. stream->read(&strafeThrustForce);
  342. stream->read(&turboFactor);
  343. stream->read(&stabLenMin);
  344. stream->read(&stabLenMax);
  345. stream->read(&stabSpringConstant);
  346. stream->read(&stabDampingConstant);
  347. stream->read(&gyroDrag);
  348. stream->read(&normalForce);
  349. stream->read(&restorativeForce);
  350. stream->read(&steeringForce);
  351. stream->read(&rollForce);
  352. stream->read(&pitchForce);
  353. mathRead(*stream, &dustTrailOffset);
  354. stream->read(&triggerTrailHeight);
  355. stream->read(&dustTrailFreqMod);
  356. for (S32 i = 0; i < MaxSounds; i++)
  357. sound[i] = stream->readFlag()?
  358. (SFXProfile*)(uintptr_t)stream->readRangedU32(DataBlockObjectIdFirst,
  359. DataBlockObjectIdLast): 0;
  360. for (S32 j = 0; j < MaxJetEmitters; j++) {
  361. jetEmitter[j] = NULL;
  362. if (stream->readFlag())
  363. jetEmitter[j] = (ParticleEmitterData*)(uintptr_t)stream->readRangedU32(DataBlockObjectIdFirst,
  364. DataBlockObjectIdLast);
  365. }
  366. if( stream->readFlag() )
  367. {
  368. dustTrailID = (S32) stream->readRangedU32(DataBlockObjectIdFirst, DataBlockObjectIdLast);
  369. }
  370. stream->read(&floatingGravMag);
  371. stream->read(&brakingForce);
  372. stream->read(&brakingActivationSpeed);
  373. }
  374. //--------------------------------------------------------------------------
  375. //--------------------------------------
  376. //
  377. HoverVehicle::HoverVehicle()
  378. {
  379. mDataBlock = NULL;
  380. // Todo: ScopeAlways?
  381. mNetFlags.set(Ghostable);
  382. mFloating = false;
  383. mThrustLevel = 0.0f;
  384. mForwardThrust = 0.0f;
  385. mReverseThrust = 0.0f;
  386. mLeftThrust = 0.0f;
  387. mRightThrust = 0.0f;
  388. mJetSound = NULL;
  389. mEngineSound = NULL;
  390. mFloatSound = NULL;
  391. mThrustDirection = HoverVehicle::ThrustForward;
  392. mDustTrailEmitter = NULL;
  393. mBackMaintainOn = false;
  394. for (S32 i = 0; i < JetAnimCount; i++)
  395. {
  396. mJetSeq[i] = -1;
  397. mJetThread[i] = NULL;
  398. }
  399. }
  400. HoverVehicle::~HoverVehicle()
  401. {
  402. //
  403. }
  404. //--------------------------------------------------------------------------
  405. bool HoverVehicle::onAdd()
  406. {
  407. if(!Parent::onAdd())
  408. return false;
  409. addToScene();
  410. if( !isServerObject() )
  411. {
  412. if( mDataBlock->dustTrailEmitter )
  413. {
  414. mDustTrailEmitter = new ParticleEmitter;
  415. mDustTrailEmitter->onNewDataBlock( mDataBlock->dustTrailEmitter, false );
  416. if( !mDustTrailEmitter->registerObject() )
  417. {
  418. Con::warnf( ConsoleLogEntry::General, "Could not register dust emitter for class: %s", mDataBlock->getName() );
  419. delete mDustTrailEmitter;
  420. mDustTrailEmitter = NULL;
  421. }
  422. }
  423. // Jet Sequences
  424. for (S32 i = 0; i < JetAnimCount; i++) {
  425. TSShape const* shape = mShapeInstance->getShape();
  426. mJetSeq[i] = shape->findSequence(sJetSequence[i]);
  427. if (mJetSeq[i] != -1) {
  428. if (i == BackActivate) {
  429. mJetThread[i] = mShapeInstance->addThread();
  430. mShapeInstance->setSequence(mJetThread[i],mJetSeq[i],0);
  431. mShapeInstance->setTimeScale(mJetThread[i],0);
  432. }
  433. }
  434. else
  435. mJetThread[i] = 0;
  436. }
  437. }
  438. if (isServerObject())
  439. scriptOnAdd();
  440. return true;
  441. }
  442. void HoverVehicle::onRemove()
  443. {
  444. SFX_DELETE( mJetSound );
  445. SFX_DELETE( mEngineSound );
  446. SFX_DELETE( mFloatSound );
  447. scriptOnRemove();
  448. removeFromScene();
  449. Parent::onRemove();
  450. }
  451. bool HoverVehicle::onNewDataBlock(GameBaseData* dptr, bool reload)
  452. {
  453. mDataBlock = dynamic_cast<HoverVehicleData*>(dptr);
  454. if (!mDataBlock || !Parent::onNewDataBlock(dptr,reload))
  455. return false;
  456. if (isGhost())
  457. {
  458. // Create the sounds ahead of time. This reduces runtime
  459. // costs and makes the system easier to understand.
  460. SFX_DELETE( mEngineSound );
  461. SFX_DELETE( mFloatSound );
  462. SFX_DELETE( mJetSound );
  463. if ( mDataBlock->sound[HoverVehicleData::EngineSound] )
  464. mEngineSound = SFX->createSource( mDataBlock->sound[HoverVehicleData::EngineSound], &getTransform() );
  465. if ( !mDataBlock->sound[HoverVehicleData::FloatSound] )
  466. mFloatSound = SFX->createSource( mDataBlock->sound[HoverVehicleData::FloatSound], &getTransform() );
  467. if ( mDataBlock->sound[HoverVehicleData::JetSound] )
  468. mJetSound = SFX->createSource( mDataBlock->sound[HoverVehicleData::JetSound], &getTransform() );
  469. }
  470. // Todo: Uncomment if this is a "leaf" class
  471. scriptOnNewDataBlock();
  472. return true;
  473. }
  474. //--------------------------------------------------------------------------
  475. void HoverVehicle::advanceTime(F32 dt)
  476. {
  477. Parent::advanceTime(dt);
  478. // Update jetsound...
  479. if ( mJetSound )
  480. {
  481. if ( mJetting )
  482. {
  483. if ( !mJetSound->isPlaying() )
  484. mJetSound->play();
  485. mJetSound->setTransform( getTransform() );
  486. }
  487. else
  488. mJetSound->stop();
  489. }
  490. // Update engine sound...
  491. if ( mEngineSound )
  492. {
  493. if ( !mEngineSound->isPlaying() )
  494. mEngineSound->play();
  495. mEngineSound->setTransform( getTransform() );
  496. F32 denom = mDataBlock->mainThrustForce + mDataBlock->strafeThrustForce;
  497. F32 factor = getMin(mThrustLevel, denom) / denom;
  498. F32 vol = 0.25 + factor * 0.75;
  499. mEngineSound->setVolume( vol );
  500. }
  501. // Are we floating? If so, start the floating sound...
  502. if ( mFloatSound )
  503. {
  504. if ( mFloating )
  505. {
  506. if ( !mFloatSound->isPlaying() )
  507. mFloatSound->play();
  508. mFloatSound->setTransform( getTransform() );
  509. }
  510. else
  511. mFloatSound->stop();
  512. }
  513. updateJet(dt);
  514. updateDustTrail( dt );
  515. }
  516. //--------------------------------------------------------------------------
  517. U32 HoverVehicle::packUpdate(NetConnection* con, U32 mask, BitStream* stream)
  518. {
  519. U32 retMask = Parent::packUpdate(con, mask, stream);
  520. //
  521. stream->writeInt(mThrustDirection,NumThrustBits);
  522. return retMask;
  523. }
  524. void HoverVehicle::unpackUpdate(NetConnection* con, BitStream* stream)
  525. {
  526. Parent::unpackUpdate(con, stream);
  527. mThrustDirection = ThrustDirection(stream->readInt(NumThrustBits));
  528. //
  529. }
  530. //--------------------------------------------------------------------------
  531. void HoverVehicle::updateMove(const Move* move)
  532. {
  533. Parent::updateMove(move);
  534. mForwardThrust = mThrottle > 0.0f ? mThrottle : 0.0f;
  535. mReverseThrust = mThrottle < 0.0f ? -mThrottle : 0.0f;
  536. mLeftThrust = move->x < 0.0f ? -move->x : 0.0f;
  537. mRightThrust = move->x > 0.0f ? move->x : 0.0f;
  538. mThrustDirection = (!move->y)? ThrustDown: (move->y > 0)? ThrustForward: ThrustBackward;
  539. }
  540. F32 HoverVehicle::getBaseStabilizerLength() const
  541. {
  542. F32 base = mDataBlock->stabLenMin;
  543. F32 lengthDiff = mDataBlock->stabLenMax - mDataBlock->stabLenMin;
  544. F32 velLength = mRigid.linVelocity.len();
  545. F32 minVel = getMin(velLength, mDataBlock->maxThrustSpeed);
  546. F32 velDiff = mDataBlock->maxThrustSpeed - minVel;
  547. // Protect against divide by zero.
  548. F32 velRatio = mDataBlock->maxThrustSpeed != 0.0f ? ( velDiff / mDataBlock->maxThrustSpeed ) : 0.0f;
  549. F32 inc = lengthDiff * ( 1.0 - velRatio );
  550. base += inc;
  551. return base;
  552. }
  553. struct StabPoint
  554. {
  555. Point3F osPoint; //
  556. Point3F wsPoint; //
  557. F32 extension;
  558. Point3F wsExtension; //
  559. Point3F wsVelocity; //
  560. };
  561. void HoverVehicle::updateForces(F32 /*dt*/)
  562. {
  563. PROFILE_SCOPE( HoverVehicle_UpdateForces );
  564. Point3F gravForce(0, 0, mRigid.mass * mNetGravity);
  565. MatrixF currTransform;
  566. mRigid.getTransform(&currTransform);
  567. mRigid.atRest = false;
  568. mThrustLevel = (mForwardThrust * mDataBlock->mainThrustForce +
  569. mReverseThrust * mDataBlock->reverseThrustForce +
  570. mLeftThrust * mDataBlock->strafeThrustForce +
  571. mRightThrust * mDataBlock->strafeThrustForce);
  572. Point3F thrustForce = ((Point3F( 0, 1, 0) * (mForwardThrust * mDataBlock->mainThrustForce)) +
  573. (Point3F( 0, -1, 0) * (mReverseThrust * mDataBlock->reverseThrustForce)) +
  574. (Point3F(-1, 0, 0) * (mLeftThrust * mDataBlock->strafeThrustForce)) +
  575. (Point3F( 1, 0, 0) * (mRightThrust * mDataBlock->strafeThrustForce)));
  576. currTransform.mulV(thrustForce);
  577. if (mJetting)
  578. thrustForce *= mDataBlock->turboFactor;
  579. Point3F torque(0, 0, 0);
  580. Point3F force(0, 0, 0);
  581. Point3F vel = mRigid.linVelocity;
  582. F32 baseStabLen = getBaseStabilizerLength();
  583. Point3F stabExtend(0, 0, -baseStabLen);
  584. currTransform.mulV(stabExtend);
  585. StabPoint stabPoints[2];
  586. stabPoints[0].osPoint = Point3F((mObjBox.minExtents.x + mObjBox.maxExtents.x) * 0.5,
  587. mObjBox.maxExtents.y,
  588. (mObjBox.minExtents.z + mObjBox.maxExtents.z) * 0.5);
  589. stabPoints[1].osPoint = Point3F((mObjBox.minExtents.x + mObjBox.maxExtents.x) * 0.5,
  590. mObjBox.minExtents.y,
  591. (mObjBox.minExtents.z + mObjBox.maxExtents.z) * 0.5);
  592. U32 j, i;
  593. for (i = 0; i < 2; i++) {
  594. currTransform.mulP(stabPoints[i].osPoint, &stabPoints[i].wsPoint);
  595. stabPoints[i].wsExtension = stabExtend;
  596. stabPoints[i].extension = baseStabLen;
  597. stabPoints[i].wsVelocity = mRigid.linVelocity;
  598. }
  599. RayInfo rinfo;
  600. mFloating = true;
  601. bool reallyFloating = true;
  602. F32 compression[2] = { 0.0f, 0.0f };
  603. F32 normalMod[2] = { 0.0f, 0.0f };
  604. bool normalSet[2] = { false, false };
  605. Point3F normal[2];
  606. for (j = 0; j < 2; j++) {
  607. if (getContainer()->castRay(stabPoints[j].wsPoint, stabPoints[j].wsPoint + stabPoints[j].wsExtension * 2.0,
  608. TerrainObjectType |
  609. WaterObjectType, &rinfo))
  610. {
  611. reallyFloating = false;
  612. if (rinfo.t <= 0.5) {
  613. // Ok, stab is in contact with the ground, let's calc the forces...
  614. compression[j] = (1.0 - (rinfo.t * 2.0)) * baseStabLen;
  615. }
  616. normalSet[j] = true;
  617. normalMod[j] = rinfo.t < 0.5 ? 1.0 : (1.0 - ((rinfo.t - 0.5) * 2.0));
  618. normal[j] = rinfo.normal;
  619. }
  620. if ( pointInWater( stabPoints[j].wsPoint ) )
  621. compression[j] = baseStabLen;
  622. }
  623. for (j = 0; j < 2; j++) {
  624. if (compression[j] != 0.0) {
  625. mFloating = false;
  626. // Spring force and damping
  627. Point3F springForce = -stabPoints[j].wsExtension;
  628. springForce.normalize();
  629. springForce *= compression[j] * mDataBlock->stabSpringConstant;
  630. Point3F springDamping = -stabPoints[j].wsExtension;
  631. springDamping.normalize();
  632. springDamping *= -getMin(mDot(springDamping, stabPoints[j].wsVelocity), 0.7f) * mDataBlock->stabDampingConstant;
  633. force += springForce + springDamping;
  634. }
  635. }
  636. // Gravity
  637. if (reallyFloating == false)
  638. force += gravForce;
  639. else
  640. force += gravForce * mDataBlock->floatingGravMag;
  641. // Braking
  642. F32 vellen = mRigid.linVelocity.len();
  643. if (mThrottle == 0.0f &&
  644. mLeftThrust == 0.0f &&
  645. mRightThrust == 0.0f &&
  646. vellen != 0.0f &&
  647. vellen < mDataBlock->brakingActivationSpeed)
  648. {
  649. Point3F dir = mRigid.linVelocity;
  650. dir.normalize();
  651. dir.neg();
  652. force += dir * mDataBlock->brakingForce;
  653. }
  654. // Gyro Drag
  655. torque = -mRigid.angMomentum * mDataBlock->gyroDrag;
  656. // Move to proper normal
  657. Point3F sn, r;
  658. currTransform.getColumn(2, &sn);
  659. if (normalSet[0] || normalSet[1]) {
  660. if (normalSet[0] && normalSet[1]) {
  661. F32 dot = mDot(normal[0], normal[1]);
  662. if (dot > 0.999) {
  663. // Just pick the first normal. They're too close to call
  664. if ((sn - normal[0]).lenSquared() > 0.00001) {
  665. mCross(sn, normal[0], &r);
  666. torque += r * mDataBlock->normalForce * normalMod[0];
  667. }
  668. } else {
  669. Point3F rotAxis;
  670. mCross(normal[0], normal[1], &rotAxis);
  671. rotAxis.normalize();
  672. F32 angle = mAcos(dot) * (normalMod[0] / (normalMod[0] + normalMod[1]));
  673. AngAxisF aa(rotAxis, angle);
  674. QuatF q(aa);
  675. MatrixF tempMat(true);
  676. q.setMatrix(&tempMat);
  677. Point3F newNormal;
  678. tempMat.mulV(normal[1], &newNormal);
  679. if ((sn - newNormal).lenSquared() > 0.00001) {
  680. mCross(sn, newNormal, &r);
  681. torque += r * (mDataBlock->normalForce * ((normalMod[0] + normalMod[1]) * 0.5));
  682. }
  683. }
  684. } else {
  685. Point3F useNormal;
  686. F32 useMod;
  687. if (normalSet[0]) {
  688. useNormal = normal[0];
  689. useMod = normalMod[0];
  690. } else {
  691. useNormal = normal[1];
  692. useMod = normalMod[1];
  693. }
  694. if ((sn - useNormal).lenSquared() > 0.00001) {
  695. mCross(sn, useNormal, &r);
  696. torque += r * mDataBlock->normalForce * useMod;
  697. }
  698. }
  699. } else {
  700. if ((sn - Point3F(0, 0, 1)).lenSquared() > 0.00001) {
  701. mCross(sn, Point3F(0, 0, 1), &r);
  702. torque += r * mDataBlock->restorativeForce;
  703. }
  704. }
  705. Point3F sn2;
  706. currTransform.getColumn(0, &sn);
  707. currTransform.getColumn(1, &sn2);
  708. mCross(sn, sn2, &r);
  709. r.normalize();
  710. torque -= r * (mSteering.x * mDataBlock->steeringForce);
  711. currTransform.getColumn(0, &sn);
  712. currTransform.getColumn(2, &sn2);
  713. mCross(sn, sn2, &r);
  714. r.normalize();
  715. torque -= r * (mSteering.x * mDataBlock->rollForce);
  716. currTransform.getColumn(1, &sn);
  717. currTransform.getColumn(2, &sn2);
  718. mCross(sn, sn2, &r);
  719. r.normalize();
  720. torque -= r * (mSteering.y * mDataBlock->pitchForce);
  721. // Apply drag
  722. Point3F vDrag = mRigid.linVelocity;
  723. if (!mFloating) {
  724. vDrag.convolve(Point3F(1, 1, mDataBlock->vertFactor));
  725. } else {
  726. vDrag.convolve(Point3F(0.25, 0.25, mDataBlock->vertFactor));
  727. }
  728. force -= vDrag * mDataBlock->dragForce;
  729. force += mFloating ? thrustForce * mDataBlock->floatingThrustFactor : thrustForce;
  730. // Add in physical zone force
  731. force += mAppliedForce;
  732. force -= mRigid.linVelocity * mDrag;
  733. torque -= mRigid.angMomentum * mDrag;
  734. mRigid.force = force;
  735. mRigid.torque = torque;
  736. }
  737. //--------------------------------------------------------------------------
  738. U32 HoverVehicle::getCollisionMask()
  739. {
  740. if (isServerObject())
  741. return sServerCollisionMask;
  742. else
  743. return sClientCollisionMask;
  744. }
  745. void HoverVehicle::updateDustTrail( F32 dt )
  746. {
  747. // Check to see if we're moving.
  748. VectorF velocityVector = getVelocity();
  749. F32 velocity = velocityVector.len();
  750. if( velocity > 2.0 )
  751. {
  752. velocityVector.normalize();
  753. emitDust( mDustTrailEmitter, mDataBlock->triggerTrailHeight, mDataBlock->dustTrailOffset,
  754. ( U32 )( dt * 1000 * ( velocity / mDataBlock->dustTrailFreqMod ) ),
  755. velocityVector );
  756. }
  757. }
  758. void HoverVehicle::updateJet(F32 dt)
  759. {
  760. if (mJetThread[BackActivate] == NULL)
  761. return;
  762. // Thrust Animation threads
  763. // Back
  764. if (mJetSeq[BackActivate] >=0 ) {
  765. if (!mBackMaintainOn || mThrustDirection != ThrustForward) {
  766. if (mBackMaintainOn) {
  767. mShapeInstance->setPos(mJetThread[BackActivate], 1);
  768. mShapeInstance->destroyThread(mJetThread[BackMaintain]);
  769. mBackMaintainOn = false;
  770. }
  771. mShapeInstance->setTimeScale(mJetThread[BackActivate],
  772. (mThrustDirection == ThrustForward)? 1.0f : -1.0f);
  773. mShapeInstance->advanceTime(dt,mJetThread[BackActivate]);
  774. }
  775. }
  776. if (mJetSeq[BackMaintain] >= 0 && !mBackMaintainOn &&
  777. mShapeInstance->getPos(mJetThread[BackActivate]) >= 1.0f)
  778. {
  779. mShapeInstance->setPos(mJetThread[BackActivate], 0);
  780. mShapeInstance->setTimeScale(mJetThread[BackActivate], 0);
  781. mJetThread[BackMaintain] = mShapeInstance->addThread();
  782. mShapeInstance->setSequence(mJetThread[BackMaintain],mJetSeq[BackMaintain],0);
  783. mShapeInstance->setTimeScale(mJetThread[BackMaintain],1);
  784. mBackMaintainOn = true;
  785. }
  786. if(mBackMaintainOn)
  787. mShapeInstance->advanceTime(dt,mJetThread[BackMaintain]);
  788. // Jet particles
  789. for (S32 j = 0; j < NumThrustDirections; j++) {
  790. JetActivation& jet = sJetActivation[j];
  791. updateEmitter(mJetting && j == mThrustDirection,dt,mDataBlock->jetEmitter[jet.emitter],
  792. jet.node,HoverVehicleData::MaxDirectionJets);
  793. }
  794. }
  795. void HoverVehicle::updateEmitter(bool active,F32 dt,ParticleEmitterData *emitter,S32 idx,S32 count)
  796. {
  797. if (!emitter)
  798. return;
  799. for (S32 j = idx; j < idx + count; j++)
  800. if (active) {
  801. if (mDataBlock->jetNode[j] != -1) {
  802. if (!bool(mJetEmitter[j])) {
  803. mJetEmitter[j] = new ParticleEmitter;
  804. mJetEmitter[j]->onNewDataBlock( emitter, false );
  805. mJetEmitter[j]->registerObject();
  806. }
  807. MatrixF mat;
  808. Point3F pos,axis;
  809. mat.mul(getRenderTransform(),
  810. mShapeInstance->mNodeTransforms[mDataBlock->jetNode[j]]);
  811. mat.getColumn(1,&axis);
  812. mat.getColumn(3,&pos);
  813. mJetEmitter[j]->emitParticles(pos,true,axis,getVelocity(),(U32)(dt * 1000.0f));
  814. }
  815. }
  816. else {
  817. for (S32 k = idx; k < idx + count; k++)
  818. if (bool(mJetEmitter[k])) {
  819. mJetEmitter[k]->deleteWhenEmpty();
  820. mJetEmitter[k] = 0;
  821. }
  822. }
  823. }