hoverVehicle.cpp 34 KB

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