hoverVehicle.cpp 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985
  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. if (isServerObject())
  443. scriptOnAdd();
  444. return true;
  445. }
  446. void HoverVehicle::onRemove()
  447. {
  448. SFX_DELETE( mJetSound );
  449. SFX_DELETE( mEngineSound );
  450. SFX_DELETE( mFloatSound );
  451. scriptOnRemove();
  452. removeFromScene();
  453. Parent::onRemove();
  454. }
  455. bool HoverVehicle::onNewDataBlock(GameBaseData* dptr, bool reload)
  456. {
  457. mDataBlock = dynamic_cast<HoverVehicleData*>(dptr);
  458. if (!mDataBlock || !Parent::onNewDataBlock(dptr,reload))
  459. return false;
  460. if (isGhost())
  461. {
  462. // Create the sounds ahead of time. This reduces runtime
  463. // costs and makes the system easier to understand.
  464. SFX_DELETE( mEngineSound );
  465. SFX_DELETE( mFloatSound );
  466. SFX_DELETE( mJetSound );
  467. if ( mDataBlock->getHoverSounds(HoverVehicleData::EngineSound) )
  468. mEngineSound = SFX->createSource( mDataBlock->getHoverSoundProfile(HoverVehicleData::EngineSound), &getTransform() );
  469. if ( !mDataBlock->getHoverSounds(HoverVehicleData::FloatSound) )
  470. mFloatSound = SFX->createSource( mDataBlock->getHoverSoundProfile(HoverVehicleData::FloatSound), &getTransform() );
  471. if ( mDataBlock->getHoverSounds(HoverVehicleData::JetSound) )
  472. mJetSound = SFX->createSource( mDataBlock->getHoverSoundProfile(HoverVehicleData::JetSound), &getTransform() );
  473. }
  474. // Todo: Uncomment if this is a "leaf" class
  475. scriptOnNewDataBlock();
  476. return true;
  477. }
  478. //--------------------------------------------------------------------------
  479. void HoverVehicle::advanceTime(F32 dt)
  480. {
  481. Parent::advanceTime(dt);
  482. // Update jetsound...
  483. if ( mJetSound )
  484. {
  485. if ( mJetting )
  486. {
  487. if ( !mJetSound->isPlaying() )
  488. mJetSound->play();
  489. mJetSound->setTransform( getTransform() );
  490. }
  491. else
  492. mJetSound->stop();
  493. }
  494. // Update engine sound...
  495. if ( mEngineSound )
  496. {
  497. if ( !mEngineSound->isPlaying() )
  498. mEngineSound->play();
  499. mEngineSound->setTransform( getTransform() );
  500. F32 denom = mDataBlock->mainThrustForce + mDataBlock->strafeThrustForce;
  501. F32 factor = getMin(mThrustLevel, denom) / denom;
  502. F32 vol = 0.25 + factor * 0.75;
  503. mEngineSound->setVolume( vol );
  504. }
  505. // Are we floating? If so, start the floating sound...
  506. if ( mFloatSound )
  507. {
  508. if ( mFloating )
  509. {
  510. if ( !mFloatSound->isPlaying() )
  511. mFloatSound->play();
  512. mFloatSound->setTransform( getTransform() );
  513. }
  514. else
  515. mFloatSound->stop();
  516. }
  517. updateJet(dt);
  518. updateDustTrail( dt );
  519. }
  520. //--------------------------------------------------------------------------
  521. U32 HoverVehicle::packUpdate(NetConnection* con, U32 mask, BitStream* stream)
  522. {
  523. U32 retMask = Parent::packUpdate(con, mask, stream);
  524. //
  525. stream->writeInt(mThrustDirection,NumThrustBits);
  526. return retMask;
  527. }
  528. void HoverVehicle::unpackUpdate(NetConnection* con, BitStream* stream)
  529. {
  530. Parent::unpackUpdate(con, stream);
  531. mThrustDirection = ThrustDirection(stream->readInt(NumThrustBits));
  532. //
  533. }
  534. //--------------------------------------------------------------------------
  535. void HoverVehicle::updateMove(const Move* move)
  536. {
  537. Parent::updateMove(move);
  538. mForwardThrust = mThrottle > 0.0f ? mThrottle : 0.0f;
  539. mReverseThrust = mThrottle < 0.0f ? -mThrottle : 0.0f;
  540. mLeftThrust = move->x < 0.0f ? -move->x : 0.0f;
  541. mRightThrust = move->x > 0.0f ? move->x : 0.0f;
  542. mThrustDirection = (!move->y)? ThrustDown: (move->y > 0)? ThrustForward: ThrustBackward;
  543. }
  544. F32 HoverVehicle::getBaseStabilizerLength() const
  545. {
  546. F32 base = mDataBlock->stabLenMin;
  547. F32 lengthDiff = mDataBlock->stabLenMax - mDataBlock->stabLenMin;
  548. F32 velLength = mRigid.linVelocity.len();
  549. F32 minVel = getMin(velLength, mDataBlock->maxThrustSpeed);
  550. F32 velDiff = mDataBlock->maxThrustSpeed - minVel;
  551. // Protect against divide by zero.
  552. F32 velRatio = mDataBlock->maxThrustSpeed != 0.0f ? ( velDiff / mDataBlock->maxThrustSpeed ) : 0.0f;
  553. F32 inc = lengthDiff * ( 1.0 - velRatio );
  554. base += inc;
  555. return base;
  556. }
  557. struct StabPoint
  558. {
  559. Point3F osPoint; //
  560. Point3F wsPoint; //
  561. F32 extension;
  562. Point3F wsExtension; //
  563. Point3F wsVelocity; //
  564. };
  565. void HoverVehicle::updateForces(F32 /*dt*/)
  566. {
  567. PROFILE_SCOPE( HoverVehicle_UpdateForces );
  568. Point3F gravForce(0, 0, mRigid.mass * mNetGravity);
  569. MatrixF currTransform;
  570. mRigid.getTransform(&currTransform);
  571. mRigid.atRest = false;
  572. mThrustLevel = (mForwardThrust * mDataBlock->mainThrustForce +
  573. mReverseThrust * mDataBlock->reverseThrustForce +
  574. mLeftThrust * mDataBlock->strafeThrustForce +
  575. mRightThrust * mDataBlock->strafeThrustForce);
  576. Point3F thrustForce = ((Point3F( 0, 1, 0) * (mForwardThrust * mDataBlock->mainThrustForce)) +
  577. (Point3F( 0, -1, 0) * (mReverseThrust * mDataBlock->reverseThrustForce)) +
  578. (Point3F(-1, 0, 0) * (mLeftThrust * mDataBlock->strafeThrustForce)) +
  579. (Point3F( 1, 0, 0) * (mRightThrust * mDataBlock->strafeThrustForce)));
  580. currTransform.mulV(thrustForce);
  581. if (mJetting)
  582. thrustForce *= mDataBlock->turboFactor;
  583. Point3F torque(0, 0, 0);
  584. Point3F force(0, 0, 0);
  585. Point3F vel = mRigid.linVelocity;
  586. F32 baseStabLen = getBaseStabilizerLength();
  587. Point3F stabExtend(0, 0, -baseStabLen);
  588. currTransform.mulV(stabExtend);
  589. StabPoint stabPoints[2];
  590. stabPoints[0].osPoint = Point3F((mObjBox.minExtents.x + mObjBox.maxExtents.x) * 0.5,
  591. mObjBox.maxExtents.y,
  592. (mObjBox.minExtents.z + mObjBox.maxExtents.z) * 0.5);
  593. stabPoints[1].osPoint = Point3F((mObjBox.minExtents.x + mObjBox.maxExtents.x) * 0.5,
  594. mObjBox.minExtents.y,
  595. (mObjBox.minExtents.z + mObjBox.maxExtents.z) * 0.5);
  596. U32 j, i;
  597. for (i = 0; i < 2; i++) {
  598. currTransform.mulP(stabPoints[i].osPoint, &stabPoints[i].wsPoint);
  599. stabPoints[i].wsExtension = stabExtend;
  600. stabPoints[i].extension = baseStabLen;
  601. stabPoints[i].wsVelocity = mRigid.linVelocity;
  602. }
  603. RayInfo rinfo;
  604. mFloating = true;
  605. bool reallyFloating = true;
  606. F32 compression[2] = { 0.0f, 0.0f };
  607. F32 normalMod[2] = { 0.0f, 0.0f };
  608. bool normalSet[2] = { false, false };
  609. Point3F normal[2];
  610. for (j = 0; j < 2; j++) {
  611. if (getContainer()->castRay(stabPoints[j].wsPoint, stabPoints[j].wsPoint + stabPoints[j].wsExtension * 2.0,
  612. TerrainObjectType |
  613. WaterObjectType, &rinfo))
  614. {
  615. reallyFloating = false;
  616. if (rinfo.t <= 0.5) {
  617. // Ok, stab is in contact with the ground, let's calc the forces...
  618. compression[j] = (1.0 - (rinfo.t * 2.0)) * baseStabLen;
  619. }
  620. normalSet[j] = true;
  621. normalMod[j] = rinfo.t < 0.5 ? 1.0 : (1.0 - ((rinfo.t - 0.5) * 2.0));
  622. normal[j] = rinfo.normal;
  623. }
  624. if ( pointInWater( stabPoints[j].wsPoint ) )
  625. compression[j] = baseStabLen;
  626. }
  627. for (j = 0; j < 2; j++) {
  628. if (compression[j] != 0.0) {
  629. mFloating = false;
  630. // Spring force and damping
  631. Point3F springForce = -stabPoints[j].wsExtension;
  632. springForce.normalize();
  633. springForce *= compression[j] * mDataBlock->stabSpringConstant;
  634. Point3F springDamping = -stabPoints[j].wsExtension;
  635. springDamping.normalize();
  636. springDamping *= -getMin(mDot(springDamping, stabPoints[j].wsVelocity), 0.7f) * mDataBlock->stabDampingConstant;
  637. force += springForce + springDamping;
  638. }
  639. }
  640. // Gravity
  641. if (reallyFloating == false)
  642. force += gravForce;
  643. else
  644. force += gravForce * mDataBlock->floatingGravMag;
  645. // Braking
  646. F32 vellen = mRigid.linVelocity.len();
  647. if (mThrottle == 0.0f &&
  648. mLeftThrust == 0.0f &&
  649. mRightThrust == 0.0f &&
  650. vellen != 0.0f &&
  651. vellen < mDataBlock->brakingActivationSpeed)
  652. {
  653. Point3F dir = mRigid.linVelocity;
  654. dir.normalize();
  655. dir.neg();
  656. force += dir * mDataBlock->brakingForce;
  657. }
  658. // Gyro Drag
  659. torque = -mRigid.angMomentum * mDataBlock->gyroDrag;
  660. // Move to proper normal
  661. Point3F sn, r;
  662. currTransform.getColumn(2, &sn);
  663. if (normalSet[0] || normalSet[1]) {
  664. if (normalSet[0] && normalSet[1]) {
  665. F32 dot = mDot(normal[0], normal[1]);
  666. if (dot > 0.999) {
  667. // Just pick the first normal. They're too close to call
  668. if ((sn - normal[0]).lenSquared() > 0.00001) {
  669. mCross(sn, normal[0], &r);
  670. torque += r * mDataBlock->normalForce * normalMod[0];
  671. }
  672. } else {
  673. Point3F rotAxis;
  674. mCross(normal[0], normal[1], &rotAxis);
  675. rotAxis.normalize();
  676. F32 angle = mAcos(dot) * (normalMod[0] / (normalMod[0] + normalMod[1]));
  677. AngAxisF aa(rotAxis, angle);
  678. QuatF q(aa);
  679. MatrixF tempMat(true);
  680. q.setMatrix(&tempMat);
  681. Point3F newNormal;
  682. tempMat.mulV(normal[1], &newNormal);
  683. if ((sn - newNormal).lenSquared() > 0.00001) {
  684. mCross(sn, newNormal, &r);
  685. torque += r * (mDataBlock->normalForce * ((normalMod[0] + normalMod[1]) * 0.5));
  686. }
  687. }
  688. } else {
  689. Point3F useNormal;
  690. F32 useMod;
  691. if (normalSet[0]) {
  692. useNormal = normal[0];
  693. useMod = normalMod[0];
  694. } else {
  695. useNormal = normal[1];
  696. useMod = normalMod[1];
  697. }
  698. if ((sn - useNormal).lenSquared() > 0.00001) {
  699. mCross(sn, useNormal, &r);
  700. torque += r * mDataBlock->normalForce * useMod;
  701. }
  702. }
  703. } else {
  704. if ((sn - Point3F(0, 0, 1)).lenSquared() > 0.00001) {
  705. mCross(sn, Point3F(0, 0, 1), &r);
  706. torque += r * mDataBlock->restorativeForce;
  707. }
  708. }
  709. Point3F sn2;
  710. currTransform.getColumn(0, &sn);
  711. currTransform.getColumn(1, &sn2);
  712. mCross(sn, sn2, &r);
  713. r.normalize();
  714. torque -= r * (mSteering.x * mDataBlock->steeringForce);
  715. currTransform.getColumn(0, &sn);
  716. currTransform.getColumn(2, &sn2);
  717. mCross(sn, sn2, &r);
  718. r.normalize();
  719. torque -= r * (mSteering.x * mDataBlock->rollForce);
  720. currTransform.getColumn(1, &sn);
  721. currTransform.getColumn(2, &sn2);
  722. mCross(sn, sn2, &r);
  723. r.normalize();
  724. torque -= r * (mSteering.y * mDataBlock->pitchForce);
  725. // Apply drag
  726. Point3F vDrag = mRigid.linVelocity;
  727. if (!mFloating) {
  728. vDrag.convolve(Point3F(1, 1, mDataBlock->vertFactor));
  729. } else {
  730. vDrag.convolve(Point3F(0.25, 0.25, mDataBlock->vertFactor));
  731. }
  732. force -= vDrag * mDataBlock->dragForce;
  733. force += mFloating ? thrustForce * mDataBlock->floatingThrustFactor : thrustForce;
  734. // Add in physical zone force
  735. force += mAppliedForce;
  736. force -= mRigid.linVelocity * mDrag;
  737. torque -= mRigid.angMomentum * mDrag;
  738. mRigid.force = force;
  739. mRigid.torque = torque;
  740. }
  741. //--------------------------------------------------------------------------
  742. U32 HoverVehicle::getCollisionMask()
  743. {
  744. if (isServerObject())
  745. return sServerCollisionMask;
  746. else
  747. return sClientCollisionMask;
  748. }
  749. void HoverVehicle::updateDustTrail( F32 dt )
  750. {
  751. // Check to see if we're moving.
  752. VectorF velocityVector = getVelocity();
  753. F32 velocity = velocityVector.len();
  754. if( velocity > 2.0 )
  755. {
  756. velocityVector.normalize();
  757. emitDust( mDustTrailEmitter, mDataBlock->triggerTrailHeight, mDataBlock->dustTrailOffset,
  758. ( U32 )( dt * 1000 * ( velocity / mDataBlock->dustTrailFreqMod ) ),
  759. velocityVector );
  760. }
  761. }
  762. void HoverVehicle::updateJet(F32 dt)
  763. {
  764. if (mJetThread[BackActivate] == NULL)
  765. return;
  766. // Thrust Animation threads
  767. // Back
  768. if (mJetSeq[BackActivate] >=0 ) {
  769. if (!mBackMaintainOn || mThrustDirection != ThrustForward) {
  770. if (mBackMaintainOn) {
  771. mShapeInstance->setPos(mJetThread[BackActivate], 1);
  772. mShapeInstance->destroyThread(mJetThread[BackMaintain]);
  773. mBackMaintainOn = false;
  774. }
  775. mShapeInstance->setTimeScale(mJetThread[BackActivate],
  776. (mThrustDirection == ThrustForward)? 1.0f : -1.0f);
  777. mShapeInstance->advanceTime(dt,mJetThread[BackActivate]);
  778. }
  779. }
  780. if (mJetSeq[BackMaintain] >= 0 && !mBackMaintainOn &&
  781. mShapeInstance->getPos(mJetThread[BackActivate]) >= 1.0f)
  782. {
  783. mShapeInstance->setPos(mJetThread[BackActivate], 0);
  784. mShapeInstance->setTimeScale(mJetThread[BackActivate], 0);
  785. mJetThread[BackMaintain] = mShapeInstance->addThread();
  786. mShapeInstance->setSequence(mJetThread[BackMaintain],mJetSeq[BackMaintain],0);
  787. mShapeInstance->setTimeScale(mJetThread[BackMaintain],1);
  788. mBackMaintainOn = true;
  789. }
  790. if(mBackMaintainOn)
  791. mShapeInstance->advanceTime(dt,mJetThread[BackMaintain]);
  792. // Jet particles
  793. for (S32 j = 0; j < NumThrustDirections; j++) {
  794. JetActivation& jet = sJetActivation[j];
  795. updateEmitter(mJetting && j == mThrustDirection,dt,mDataBlock->jetEmitter[jet.emitter],
  796. jet.node,HoverVehicleData::MaxDirectionJets);
  797. }
  798. }
  799. void HoverVehicle::updateEmitter(bool active,F32 dt,ParticleEmitterData *emitter,S32 idx,S32 count)
  800. {
  801. if (!emitter)
  802. return;
  803. for (S32 j = idx; j < idx + count; j++)
  804. if (active) {
  805. if (mDataBlock->jetNode[j] != -1) {
  806. if (!bool(mJetEmitter[j])) {
  807. mJetEmitter[j] = new ParticleEmitter;
  808. mJetEmitter[j]->onNewDataBlock( emitter, false );
  809. mJetEmitter[j]->registerObject();
  810. }
  811. MatrixF mat;
  812. Point3F pos,axis;
  813. mat.mul(getRenderTransform(),
  814. mShapeInstance->mNodeTransforms[mDataBlock->jetNode[j]]);
  815. mat.getColumn(1,&axis);
  816. mat.getColumn(3,&pos);
  817. mJetEmitter[j]->emitParticles(pos,true,axis,getVelocity(),(U32)(dt * 1000.0f));
  818. }
  819. }
  820. else {
  821. for (S32 k = idx; k < idx + count; k++)
  822. if (bool(mJetEmitter[k])) {
  823. mJetEmitter[k]->deleteWhenEmpty();
  824. mJetEmitter[k] = 0;
  825. }
  826. }
  827. }