hoverVehicle.cpp 33 KB

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