hoverVehicle.cpp 33 KB

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