hoverVehicle.cpp 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974
  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 F32 sHoverVehicleGravity = -20;
  66. const U32 sCollisionMoveMask = (TerrainObjectType | PlayerObjectType |
  67. StaticShapeObjectType | VehicleObjectType |
  68. VehicleBlockerObjectType);
  69. const U32 sServerCollisionMask = sCollisionMoveMask; // ItemObjectType
  70. const U32 sClientCollisionMask = sCollisionMoveMask;
  71. void nonFilter(SceneObject* object,void *key)
  72. {
  73. SceneContainer::CallbackInfo* info = reinterpret_cast<SceneContainer::CallbackInfo*>(key);
  74. object->buildPolyList(info->context,info->polyList,info->boundingBox,info->boundingSphere);
  75. }
  76. } // namespace {}
  77. const char* HoverVehicle::sJetSequence[HoverVehicle::JetAnimCount] =
  78. {
  79. "activateBack",
  80. "maintainBack",
  81. };
  82. const char* HoverVehicleData::sJetNode[HoverVehicleData::MaxJetNodes] =
  83. {
  84. "JetNozzle0", // Thrust Forward
  85. "JetNozzle1",
  86. "JetNozzleX", // Thrust Backward
  87. "JetNozzleX",
  88. "JetNozzle2", // Thrust Downward
  89. "JetNozzle3",
  90. };
  91. // Convert thrust direction into nodes & emitters
  92. HoverVehicle::JetActivation HoverVehicle::sJetActivation[NumThrustDirections] = {
  93. { HoverVehicleData::ForwardJetNode, HoverVehicleData::ForwardJetEmitter },
  94. { HoverVehicleData::BackwardJetNode, HoverVehicleData::BackwardJetEmitter },
  95. { HoverVehicleData::DownwardJetNode, HoverVehicleData::DownwardJetEmitter },
  96. };
  97. //--------------------------------------------------------------------------
  98. //--------------------------------------
  99. //
  100. HoverVehicleData::HoverVehicleData()
  101. {
  102. dragForce = 0;
  103. vertFactor = 0.25f;
  104. floatingThrustFactor = 0.15f;
  105. mainThrustForce = 0;
  106. reverseThrustForce = 0;
  107. strafeThrustForce = 0;
  108. turboFactor = 1.0f;
  109. stabLenMin = 0.5f;
  110. stabLenMax = 2.0f;
  111. stabSpringConstant = 30;
  112. stabDampingConstant = 10;
  113. gyroDrag = 10;
  114. normalForce = 30;
  115. restorativeForce = 10;
  116. steeringForce = 25;
  117. rollForce = 2.5f;
  118. pitchForce = 2.5f;
  119. dustTrailEmitter = NULL;
  120. dustTrailID = 0;
  121. dustTrailOffset.set( 0.0f, 0.0f, 0.0f );
  122. dustTrailFreqMod = 15.0f;
  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(packed? 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 = packed ? 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*) 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*)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. // Todo: ScopeAlways?
  380. mNetFlags.set(Ghostable);
  381. mFloating = false;
  382. mForwardThrust = 0;
  383. mReverseThrust = 0;
  384. mLeftThrust = 0;
  385. mRightThrust = 0;
  386. mJetSound = NULL;
  387. mEngineSound = NULL;
  388. mFloatSound = NULL;
  389. mDustTrailEmitter = NULL;
  390. mBackMaintainOn = false;
  391. for (S32 i = 0; i < JetAnimCount; i++)
  392. mJetThread[i] = 0;
  393. }
  394. HoverVehicle::~HoverVehicle()
  395. {
  396. //
  397. }
  398. //--------------------------------------------------------------------------
  399. bool HoverVehicle::onAdd()
  400. {
  401. if(!Parent::onAdd())
  402. return false;
  403. addToScene();
  404. if( !isServerObject() )
  405. {
  406. if( mDataBlock->dustTrailEmitter )
  407. {
  408. mDustTrailEmitter = new ParticleEmitter;
  409. mDustTrailEmitter->onNewDataBlock( mDataBlock->dustTrailEmitter, false );
  410. if( !mDustTrailEmitter->registerObject() )
  411. {
  412. Con::warnf( ConsoleLogEntry::General, "Could not register dust emitter for class: %s", mDataBlock->getName() );
  413. delete mDustTrailEmitter;
  414. mDustTrailEmitter = NULL;
  415. }
  416. }
  417. // Jet Sequences
  418. for (S32 i = 0; i < JetAnimCount; i++) {
  419. TSShape const* shape = mShapeInstance->getShape();
  420. mJetSeq[i] = shape->findSequence(sJetSequence[i]);
  421. if (mJetSeq[i] != -1) {
  422. if (i == BackActivate) {
  423. mJetThread[i] = mShapeInstance->addThread();
  424. mShapeInstance->setSequence(mJetThread[i],mJetSeq[i],0);
  425. mShapeInstance->setTimeScale(mJetThread[i],0);
  426. }
  427. }
  428. else
  429. mJetThread[i] = 0;
  430. }
  431. }
  432. if (isServerObject())
  433. scriptOnAdd();
  434. return true;
  435. }
  436. void HoverVehicle::onRemove()
  437. {
  438. SFX_DELETE( mJetSound );
  439. SFX_DELETE( mEngineSound );
  440. SFX_DELETE( mFloatSound );
  441. scriptOnRemove();
  442. removeFromScene();
  443. Parent::onRemove();
  444. }
  445. bool HoverVehicle::onNewDataBlock(GameBaseData* dptr, bool reload)
  446. {
  447. mDataBlock = dynamic_cast<HoverVehicleData*>(dptr);
  448. if (!mDataBlock || !Parent::onNewDataBlock(dptr,reload))
  449. return false;
  450. if (isGhost())
  451. {
  452. // Create the sounds ahead of time. This reduces runtime
  453. // costs and makes the system easier to understand.
  454. SFX_DELETE( mEngineSound );
  455. SFX_DELETE( mFloatSound );
  456. SFX_DELETE( mJetSound );
  457. if ( mDataBlock->sound[HoverVehicleData::EngineSound] )
  458. mEngineSound = SFX->createSource( mDataBlock->sound[HoverVehicleData::EngineSound], &getTransform() );
  459. if ( !mDataBlock->sound[HoverVehicleData::FloatSound] )
  460. mFloatSound = SFX->createSource( mDataBlock->sound[HoverVehicleData::FloatSound], &getTransform() );
  461. if ( mDataBlock->sound[HoverVehicleData::JetSound] )
  462. mJetSound = SFX->createSource( mDataBlock->sound[HoverVehicleData::JetSound], &getTransform() );
  463. }
  464. // Todo: Uncomment if this is a "leaf" class
  465. scriptOnNewDataBlock();
  466. return true;
  467. }
  468. //--------------------------------------------------------------------------
  469. void HoverVehicle::advanceTime(F32 dt)
  470. {
  471. Parent::advanceTime(dt);
  472. // Update jetsound...
  473. if ( mJetSound )
  474. {
  475. if ( mJetting )
  476. {
  477. if ( !mJetSound->isPlaying() )
  478. mJetSound->play();
  479. mJetSound->setTransform( getTransform() );
  480. }
  481. else
  482. mJetSound->stop();
  483. }
  484. // Update engine sound...
  485. if ( mEngineSound )
  486. {
  487. if ( !mEngineSound->isPlaying() )
  488. mEngineSound->play();
  489. mEngineSound->setTransform( getTransform() );
  490. F32 denom = mDataBlock->mainThrustForce + mDataBlock->strafeThrustForce;
  491. F32 factor = getMin(mThrustLevel, denom) / denom;
  492. F32 vol = 0.25 + factor * 0.75;
  493. mEngineSound->setVolume( vol );
  494. }
  495. // Are we floating? If so, start the floating sound...
  496. if ( mFloatSound )
  497. {
  498. if ( mFloating )
  499. {
  500. if ( !mFloatSound->isPlaying() )
  501. mFloatSound->play();
  502. mFloatSound->setTransform( getTransform() );
  503. }
  504. else
  505. mFloatSound->stop();
  506. }
  507. updateJet(dt);
  508. updateDustTrail( dt );
  509. }
  510. //--------------------------------------------------------------------------
  511. U32 HoverVehicle::packUpdate(NetConnection* con, U32 mask, BitStream* stream)
  512. {
  513. U32 retMask = Parent::packUpdate(con, mask, stream);
  514. //
  515. stream->writeInt(mThrustDirection,NumThrustBits);
  516. return retMask;
  517. }
  518. void HoverVehicle::unpackUpdate(NetConnection* con, BitStream* stream)
  519. {
  520. Parent::unpackUpdate(con, stream);
  521. mThrustDirection = ThrustDirection(stream->readInt(NumThrustBits));
  522. //
  523. }
  524. //--------------------------------------------------------------------------
  525. void HoverVehicle::updateMove(const Move* move)
  526. {
  527. Parent::updateMove(move);
  528. mForwardThrust = mThrottle > 0.0f ? mThrottle : 0.0f;
  529. mReverseThrust = mThrottle < 0.0f ? -mThrottle : 0.0f;
  530. mLeftThrust = move->x < 0.0f ? -move->x : 0.0f;
  531. mRightThrust = move->x > 0.0f ? move->x : 0.0f;
  532. mThrustDirection = (!move->y)? ThrustDown: (move->y > 0)? ThrustForward: ThrustBackward;
  533. }
  534. F32 HoverVehicle::getBaseStabilizerLength() const
  535. {
  536. F32 base = mDataBlock->stabLenMin;
  537. F32 lengthDiff = mDataBlock->stabLenMax - mDataBlock->stabLenMin;
  538. F32 velLength = mRigid.linVelocity.len();
  539. F32 minVel = getMin(velLength, mDataBlock->maxThrustSpeed);
  540. F32 velDiff = mDataBlock->maxThrustSpeed - minVel;
  541. // Protect against divide by zero.
  542. F32 velRatio = mDataBlock->maxThrustSpeed != 0.0f ? ( velDiff / mDataBlock->maxThrustSpeed ) : 0.0f;
  543. F32 inc = lengthDiff * ( 1.0 - velRatio );
  544. base += inc;
  545. return base;
  546. }
  547. struct StabPoint
  548. {
  549. Point3F osPoint; //
  550. Point3F wsPoint; //
  551. F32 extension;
  552. Point3F wsExtension; //
  553. Point3F wsVelocity; //
  554. };
  555. void HoverVehicle::updateForces(F32 /*dt*/)
  556. {
  557. PROFILE_SCOPE( HoverVehicle_UpdateForces );
  558. Point3F gravForce(0, 0, sHoverVehicleGravity * mRigid.mass * mGravityMod);
  559. MatrixF currTransform;
  560. mRigid.getTransform(&currTransform);
  561. mRigid.atRest = false;
  562. mThrustLevel = (mForwardThrust * mDataBlock->mainThrustForce +
  563. mReverseThrust * mDataBlock->reverseThrustForce +
  564. mLeftThrust * mDataBlock->strafeThrustForce +
  565. mRightThrust * mDataBlock->strafeThrustForce);
  566. Point3F thrustForce = ((Point3F( 0, 1, 0) * (mForwardThrust * mDataBlock->mainThrustForce)) +
  567. (Point3F( 0, -1, 0) * (mReverseThrust * mDataBlock->reverseThrustForce)) +
  568. (Point3F(-1, 0, 0) * (mLeftThrust * mDataBlock->strafeThrustForce)) +
  569. (Point3F( 1, 0, 0) * (mRightThrust * mDataBlock->strafeThrustForce)));
  570. currTransform.mulV(thrustForce);
  571. if (mJetting)
  572. thrustForce *= mDataBlock->turboFactor;
  573. Point3F torque(0, 0, 0);
  574. Point3F force(0, 0, 0);
  575. Point3F vel = mRigid.linVelocity;
  576. F32 baseStabLen = getBaseStabilizerLength();
  577. Point3F stabExtend(0, 0, -baseStabLen);
  578. currTransform.mulV(stabExtend);
  579. StabPoint stabPoints[2];
  580. stabPoints[0].osPoint = Point3F((mObjBox.minExtents.x + mObjBox.maxExtents.x) * 0.5,
  581. mObjBox.maxExtents.y,
  582. (mObjBox.minExtents.z + mObjBox.maxExtents.z) * 0.5);
  583. stabPoints[1].osPoint = Point3F((mObjBox.minExtents.x + mObjBox.maxExtents.x) * 0.5,
  584. mObjBox.minExtents.y,
  585. (mObjBox.minExtents.z + mObjBox.maxExtents.z) * 0.5);
  586. U32 j, i;
  587. for (i = 0; i < 2; i++) {
  588. currTransform.mulP(stabPoints[i].osPoint, &stabPoints[i].wsPoint);
  589. stabPoints[i].wsExtension = stabExtend;
  590. stabPoints[i].extension = baseStabLen;
  591. stabPoints[i].wsVelocity = mRigid.linVelocity;
  592. }
  593. RayInfo rinfo;
  594. mFloating = true;
  595. bool reallyFloating = true;
  596. F32 compression[2] = { 0.0f, 0.0f };
  597. F32 normalMod[2] = { 0.0f, 0.0f };
  598. bool normalSet[2] = { false, false };
  599. Point3F normal[2];
  600. for (j = 0; j < 2; j++) {
  601. if (getContainer()->castRay(stabPoints[j].wsPoint, stabPoints[j].wsPoint + stabPoints[j].wsExtension * 2.0,
  602. TerrainObjectType |
  603. WaterObjectType, &rinfo))
  604. {
  605. reallyFloating = false;
  606. if (rinfo.t <= 0.5) {
  607. // Ok, stab is in contact with the ground, let's calc the forces...
  608. compression[j] = (1.0 - (rinfo.t * 2.0)) * baseStabLen;
  609. }
  610. normalSet[j] = true;
  611. normalMod[j] = rinfo.t < 0.5 ? 1.0 : (1.0 - ((rinfo.t - 0.5) * 2.0));
  612. normal[j] = rinfo.normal;
  613. }
  614. if ( pointInWater( stabPoints[j].wsPoint ) )
  615. compression[j] = baseStabLen;
  616. }
  617. for (j = 0; j < 2; j++) {
  618. if (compression[j] != 0.0) {
  619. mFloating = false;
  620. // Spring force and damping
  621. Point3F springForce = -stabPoints[j].wsExtension;
  622. springForce.normalize();
  623. springForce *= compression[j] * mDataBlock->stabSpringConstant;
  624. Point3F springDamping = -stabPoints[j].wsExtension;
  625. springDamping.normalize();
  626. springDamping *= -getMin(mDot(springDamping, stabPoints[j].wsVelocity), 0.7f) * mDataBlock->stabDampingConstant;
  627. force += springForce + springDamping;
  628. }
  629. }
  630. // Gravity
  631. if (reallyFloating == false)
  632. force += gravForce;
  633. else
  634. force += gravForce * mDataBlock->floatingGravMag;
  635. // Braking
  636. F32 vellen = mRigid.linVelocity.len();
  637. if (mThrottle == 0.0f &&
  638. mLeftThrust == 0.0f &&
  639. mRightThrust == 0.0f &&
  640. vellen != 0.0f &&
  641. vellen < mDataBlock->brakingActivationSpeed)
  642. {
  643. Point3F dir = mRigid.linVelocity;
  644. dir.normalize();
  645. dir.neg();
  646. force += dir * mDataBlock->brakingForce;
  647. }
  648. // Gyro Drag
  649. torque = -mRigid.angMomentum * mDataBlock->gyroDrag;
  650. // Move to proper normal
  651. Point3F sn, r;
  652. currTransform.getColumn(2, &sn);
  653. if (normalSet[0] || normalSet[1]) {
  654. if (normalSet[0] && normalSet[1]) {
  655. F32 dot = mDot(normal[0], normal[1]);
  656. if (dot > 0.999) {
  657. // Just pick the first normal. They're too close to call
  658. if ((sn - normal[0]).lenSquared() > 0.00001) {
  659. mCross(sn, normal[0], &r);
  660. torque += r * mDataBlock->normalForce * normalMod[0];
  661. }
  662. } else {
  663. Point3F rotAxis;
  664. mCross(normal[0], normal[1], &rotAxis);
  665. rotAxis.normalize();
  666. F32 angle = mAcos(dot) * (normalMod[0] / (normalMod[0] + normalMod[1]));
  667. AngAxisF aa(rotAxis, angle);
  668. QuatF q(aa);
  669. MatrixF tempMat(true);
  670. q.setMatrix(&tempMat);
  671. Point3F newNormal;
  672. tempMat.mulV(normal[1], &newNormal);
  673. if ((sn - newNormal).lenSquared() > 0.00001) {
  674. mCross(sn, newNormal, &r);
  675. torque += r * (mDataBlock->normalForce * ((normalMod[0] + normalMod[1]) * 0.5));
  676. }
  677. }
  678. } else {
  679. Point3F useNormal;
  680. F32 useMod;
  681. if (normalSet[0]) {
  682. useNormal = normal[0];
  683. useMod = normalMod[0];
  684. } else {
  685. useNormal = normal[1];
  686. useMod = normalMod[1];
  687. }
  688. if ((sn - useNormal).lenSquared() > 0.00001) {
  689. mCross(sn, useNormal, &r);
  690. torque += r * mDataBlock->normalForce * useMod;
  691. }
  692. }
  693. } else {
  694. if ((sn - Point3F(0, 0, 1)).lenSquared() > 0.00001) {
  695. mCross(sn, Point3F(0, 0, 1), &r);
  696. torque += r * mDataBlock->restorativeForce;
  697. }
  698. }
  699. Point3F sn2;
  700. currTransform.getColumn(0, &sn);
  701. currTransform.getColumn(1, &sn2);
  702. mCross(sn, sn2, &r);
  703. r.normalize();
  704. torque -= r * (mSteering.x * mDataBlock->steeringForce);
  705. currTransform.getColumn(0, &sn);
  706. currTransform.getColumn(2, &sn2);
  707. mCross(sn, sn2, &r);
  708. r.normalize();
  709. torque -= r * (mSteering.x * mDataBlock->rollForce);
  710. currTransform.getColumn(1, &sn);
  711. currTransform.getColumn(2, &sn2);
  712. mCross(sn, sn2, &r);
  713. r.normalize();
  714. torque -= r * (mSteering.y * mDataBlock->pitchForce);
  715. // Apply drag
  716. Point3F vDrag = mRigid.linVelocity;
  717. if (!mFloating) {
  718. vDrag.convolve(Point3F(1, 1, mDataBlock->vertFactor));
  719. } else {
  720. vDrag.convolve(Point3F(0.25, 0.25, mDataBlock->vertFactor));
  721. }
  722. force -= vDrag * mDataBlock->dragForce;
  723. force += mFloating ? thrustForce * mDataBlock->floatingThrustFactor : thrustForce;
  724. // Add in physical zone force
  725. force += mAppliedForce;
  726. // Container buoyancy & drag
  727. force += Point3F(0, 0,-mBuoyancy * sHoverVehicleGravity * mRigid.mass * mGravityMod);
  728. force -= mRigid.linVelocity * mDrag;
  729. torque -= mRigid.angMomentum * mDrag;
  730. mRigid.force = force;
  731. mRigid.torque = torque;
  732. }
  733. //--------------------------------------------------------------------------
  734. U32 HoverVehicle::getCollisionMask()
  735. {
  736. if (isServerObject())
  737. return sServerCollisionMask;
  738. else
  739. return sClientCollisionMask;
  740. }
  741. void HoverVehicle::updateDustTrail( F32 dt )
  742. {
  743. // Check to see if we're moving.
  744. VectorF velocityVector = getVelocity();
  745. F32 velocity = velocityVector.len();
  746. if( velocity > 2.0 )
  747. {
  748. velocityVector.normalize();
  749. emitDust( mDustTrailEmitter, mDataBlock->triggerTrailHeight, mDataBlock->dustTrailOffset,
  750. ( U32 )( dt * 1000 * ( velocity / mDataBlock->dustTrailFreqMod ) ),
  751. velocityVector );
  752. }
  753. }
  754. void HoverVehicle::updateJet(F32 dt)
  755. {
  756. if (mJetThread[BackActivate] == NULL)
  757. return;
  758. // Thrust Animation threads
  759. // Back
  760. if (mJetSeq[BackActivate] >=0 ) {
  761. if (!mBackMaintainOn || mThrustDirection != ThrustForward) {
  762. if (mBackMaintainOn) {
  763. mShapeInstance->setPos(mJetThread[BackActivate], 1);
  764. mShapeInstance->destroyThread(mJetThread[BackMaintain]);
  765. mBackMaintainOn = false;
  766. }
  767. mShapeInstance->setTimeScale(mJetThread[BackActivate],
  768. (mThrustDirection == ThrustForward)? 1.0f : -1.0f);
  769. mShapeInstance->advanceTime(dt,mJetThread[BackActivate]);
  770. }
  771. }
  772. if (mJetSeq[BackMaintain] >= 0 && !mBackMaintainOn &&
  773. mShapeInstance->getPos(mJetThread[BackActivate]) >= 1.0f)
  774. {
  775. mShapeInstance->setPos(mJetThread[BackActivate], 0);
  776. mShapeInstance->setTimeScale(mJetThread[BackActivate], 0);
  777. mJetThread[BackMaintain] = mShapeInstance->addThread();
  778. mShapeInstance->setSequence(mJetThread[BackMaintain],mJetSeq[BackMaintain],0);
  779. mShapeInstance->setTimeScale(mJetThread[BackMaintain],1);
  780. mBackMaintainOn = true;
  781. }
  782. if(mBackMaintainOn)
  783. mShapeInstance->advanceTime(dt,mJetThread[BackMaintain]);
  784. // Jet particles
  785. for (S32 j = 0; j < NumThrustDirections; j++) {
  786. JetActivation& jet = sJetActivation[j];
  787. updateEmitter(mJetting && j == mThrustDirection,dt,mDataBlock->jetEmitter[jet.emitter],
  788. jet.node,HoverVehicleData::MaxDirectionJets);
  789. }
  790. }
  791. void HoverVehicle::updateEmitter(bool active,F32 dt,ParticleEmitterData *emitter,S32 idx,S32 count)
  792. {
  793. if (!emitter)
  794. return;
  795. for (S32 j = idx; j < idx + count; j++)
  796. if (active) {
  797. if (mDataBlock->jetNode[j] != -1) {
  798. if (!bool(mJetEmitter[j])) {
  799. mJetEmitter[j] = new ParticleEmitter;
  800. mJetEmitter[j]->onNewDataBlock( emitter, false );
  801. mJetEmitter[j]->registerObject();
  802. }
  803. MatrixF mat;
  804. Point3F pos,axis;
  805. mat.mul(getRenderTransform(),
  806. mShapeInstance->mNodeTransforms[mDataBlock->jetNode[j]]);
  807. mat.getColumn(1,&axis);
  808. mat.getColumn(3,&pos);
  809. mJetEmitter[j]->emitParticles(pos,true,axis,getVelocity(),(U32)(dt * 1000.0f));
  810. }
  811. }
  812. else {
  813. for (S32 j = idx; j < idx + count; j++)
  814. if (bool(mJetEmitter[j])) {
  815. mJetEmitter[j]->deleteWhenEmpty();
  816. mJetEmitter[j] = 0;
  817. }
  818. }
  819. }