afxMagicMissile.cpp 64 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106
  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. //~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~~//
  23. // Arcane-FX for MIT Licensed Open Source version of Torque 3D from GarageGames
  24. // Copyright (C) 2015 Faust Logic, Inc.
  25. //
  26. // afxMagicMissile is a heavily modified variation of the stock Projectile class. In
  27. // addition to numerous AFX customizations, it also incorporates functionality based on
  28. // the following TGE resources:
  29. //
  30. // Guided or Seeker Projectiles by Derk Adams
  31. // http://www.garagegames.com/index.php?sec=mg&mod=resource&page=view&qid=6778
  32. //
  33. // Projectile Ballistic Coefficients (drag factors) by Mark Owen
  34. // http://www.garagegames.com/index.php?sec=mg&mod=resource&page=view&qid=5128
  35. //
  36. //~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~~//
  37. #include "afx/arcaneFX.h"
  38. #include "scene/sceneRenderState.h"
  39. #include "scene/sceneManager.h"
  40. #include "core/resourceManager.h"
  41. #include "ts/tsShapeInstance.h"
  42. #include "sfx/sfxTrack.h"
  43. #include "sfx/sfxSource.h"
  44. #include "sfx/sfxSystem.h"
  45. #include "sfx/sfxTypes.h"
  46. #include "math/mathUtils.h"
  47. #include "math/mathIO.h"
  48. #include "sim/netConnection.h"
  49. #include "T3D/fx/particleEmitter.h"
  50. #include "T3D/fx/splash.h"
  51. #include "T3D/physics/physicsPlugin.h"
  52. #include "T3D/physics/physicsWorld.h"
  53. #include "gfx/gfxTransformSaver.h"
  54. #include "T3D/containerQuery.h"
  55. #include "T3D/lightDescription.h"
  56. #include "console/engineAPI.h"
  57. #include "lighting/lightManager.h"
  58. #include "afx/util/afxEase.h"
  59. #include "afx/afxMagicMissile.h"
  60. #include "afx/afxMagicSpell.h"
  61. #include "afx/afxChoreographer.h"
  62. class ObjectDeleteEvent : public SimEvent
  63. {
  64. public:
  65. void process(SimObject *object)
  66. {
  67. object->deleteObject();
  68. }
  69. };
  70. IMPLEMENT_CO_DATABLOCK_V1(afxMagicMissileData);
  71. ConsoleDocClass( afxMagicMissileData,
  72. "@brief Defines a particular magic-missile type. (Use with afxMagicSpellData.)\n"
  73. "@tsexample\n"
  74. "datablock afxMagicMissileData(Fireball_MM)\n"
  75. "{\n"
  76. " muzzleVelocity = 50;\n"
  77. " velInheritFactor = 0;\n"
  78. " lifetime = 20000;\n"
  79. " isBallistic = true;\n"
  80. " ballisticCoefficient = 0.85;\n"
  81. " gravityMod = 0.05;\n"
  82. " isGuided = true;\n"
  83. " precision = 30;\n"
  84. " trackDelay = 7;\n"
  85. " launchOffset = \"0 0 43.7965\";\n"
  86. " launchOnServerSignal = true;\n"
  87. "};\n"
  88. "@endtsexample\n"
  89. "@ingroup AFX\n"
  90. );
  91. IMPLEMENT_CO_NETOBJECT_V1(afxMagicMissile);
  92. ConsoleDocClass( afxMagicMissile,
  93. "@brief Magic-missile class used internally by afxMagicSpell. Properties of individual missile types are defined using afxMagicMissileData.\n"
  94. "@ingroup AFX\n"
  95. );
  96. /* From stock Projectile code...
  97. IMPLEMENT_CALLBACK( ProjectileData, onExplode, void, ( Projectile* proj, Point3F pos, F32 fade ),
  98. ( proj, pos, fade ),
  99. "Called when a projectile explodes.\n"
  100. "@param proj The projectile exploding.\n"
  101. "@param pos The position of the explosion.\n"
  102. "@param fade The currently fadeValue of the projectile, affects its visibility.\n"
  103. "@see Projectile, ProjectileData\n"
  104. );
  105. IMPLEMENT_CALLBACK( ProjectileData, onCollision, void, ( Projectile* proj, SceneObject* col, F32 fade, Point3F pos, Point3F normal ),
  106. ( proj, col, fade, pos, normal ),
  107. "Called when a projectile collides with another object.\n"
  108. "@param proj The projectile colliding.\n"
  109. "@param col The object hit by the projectile.\n"
  110. "@param fade The current fadeValue of the projectile, affects its visibility.\n"
  111. "@param pos The collision position.\n"
  112. "@param normal The collision normal.\n"
  113. "@see Projectile, ProjectileData\n"
  114. );
  115. const U32 Projectile::csmStaticCollisionMask = TerrainObjectType |
  116. InteriorObjectType |
  117. StaticObjectType;
  118. const U32 Projectile::csmDynamicCollisionMask = PlayerObjectType |
  119. VehicleObjectType |
  120. DamagableItemObjectType;
  121. const U32 Projectile::csmDamageableMask = Projectile::csmDynamicCollisionMask;
  122. U32 Projectile::smProjectileWarpTicks = 5;
  123. */
  124. //--------------------------------------------------------------------------
  125. //
  126. afxMagicMissileData::afxMagicMissileData()
  127. {
  128. INIT_ASSET(ProjectileShape);
  129. INIT_ASSET(ProjectileSound);
  130. /* From stock Projectile code...
  131. explosion = NULL;
  132. explosionId = 0;
  133. waterExplosion = NULL;
  134. waterExplosionId = 0;
  135. */
  136. /* From stock Projectile code...
  137. faceViewer = false;
  138. */
  139. scale.set( 1.0f, 1.0f, 1.0f );
  140. isBallistic = false;
  141. /* From stock Projectile code...
  142. velInheritFactor = 1.0f;
  143. */
  144. muzzleVelocity = 50;
  145. /* From stock Projectile code...
  146. impactForce = 0.0f;
  147. armingDelay = 0;
  148. activateSeq = -1;
  149. maintainSeq = -1;
  150. */
  151. lifetime = 20000 / 32;
  152. fadeDelay = 20000 / 32;
  153. gravityMod = 1.0;
  154. /* From stock Projectile code...
  155. bounceElasticity = 0.999f;
  156. bounceFriction = 0.3f;
  157. */
  158. particleEmitter = NULL;
  159. particleEmitterId = 0;
  160. particleWaterEmitter = NULL;
  161. particleWaterEmitterId = 0;
  162. splash = NULL;
  163. splashId = 0;
  164. /* From stock Projectile code...
  165. decal = NULL;
  166. decalId = 0;
  167. */
  168. lightDesc = NULL;
  169. lightDescId = 0;
  170. starting_vel_vec.zero();
  171. isGuided = false;
  172. precision = 0;
  173. trackDelay = 0;
  174. ballisticCoefficient = 1.0f;
  175. followTerrain = false;
  176. followTerrainHeight = 0.1f;
  177. followTerrainAdjustRate = 20.0f;
  178. followTerrainAdjustDelay = 0;
  179. lifetime = MaxLifetimeTicks;
  180. collision_mask = arcaneFX::sMissileCollisionMask;
  181. acceleration = 0;
  182. accelDelay = 0;
  183. accelLifetime = 0;
  184. launch_node = ST_NULLSTRING;
  185. launch_offset.zero();
  186. launch_offset_server.zero();
  187. launch_offset_client.zero();
  188. launch_node_offset.zero();
  189. launch_pitch = 0;
  190. launch_pan = 0;
  191. launch_cons_s_spec = ST_NULLSTRING;
  192. launch_cons_c_spec = ST_NULLSTRING;
  193. echo_launch_offset = false;
  194. wiggle_axis_string = ST_NULLSTRING;
  195. wiggle_num_axis = 0;
  196. wiggle_axis = 0;
  197. hover_altitude = 0;
  198. hover_attack_distance = 0;
  199. hover_attack_gradient = 0;
  200. hover_time = 0;
  201. reverse_targeting = false;
  202. caster_safety_time = U32_MAX;
  203. }
  204. afxMagicMissileData::afxMagicMissileData(const afxMagicMissileData& other, bool temp_clone) : GameBaseData(other, temp_clone)
  205. {
  206. CLONE_ASSET(ProjectileShape);
  207. projectileShape = other.projectileShape; // -- TSShape loads using projectileShapeName
  208. CLONE_ASSET(ProjectileSound);
  209. splash = other.splash;
  210. splashId = other.splashId; // -- for pack/unpack of splash ptr
  211. lightDesc = other.lightDesc;
  212. lightDescId = other.lightDescId; // -- for pack/unpack of lightDesc ptr
  213. scale = other.scale;
  214. isBallistic = other.isBallistic;
  215. muzzleVelocity = other.muzzleVelocity;
  216. gravityMod = other.gravityMod;
  217. particleEmitter = other.particleEmitter;
  218. particleEmitterId = other.particleEmitterId; // -- for pack/unpack of particleEmitter ptr
  219. particleWaterEmitter = other.particleWaterEmitter;
  220. particleWaterEmitterId = other.particleWaterEmitterId; // -- for pack/unpack of particleWaterEmitter ptr
  221. collision_mask = other.collision_mask;
  222. starting_vel_vec = other.starting_vel_vec;
  223. isGuided = other.isGuided;
  224. precision = other.precision;
  225. trackDelay = other.trackDelay;
  226. ballisticCoefficient = other.ballisticCoefficient;
  227. followTerrain = other.followTerrain;
  228. followTerrainHeight = other.followTerrainHeight;
  229. followTerrainAdjustRate = other.followTerrainAdjustRate;
  230. followTerrainAdjustDelay = other.followTerrainAdjustDelay;
  231. lifetime = other.lifetime;
  232. fadeDelay = other.fadeDelay;
  233. acceleration = other.acceleration;
  234. accelDelay = other.accelDelay;
  235. accelLifetime = other.accelLifetime;
  236. launch_node = other.launch_node;
  237. launch_offset = other.launch_offset;
  238. launch_offset_server = other.launch_offset_server;
  239. launch_offset_client = other.launch_offset_client;
  240. launch_node_offset = other.launch_node_offset;
  241. launch_pitch = other.launch_pitch;
  242. launch_pan = other.launch_pan;
  243. launch_cons_s_spec = other.launch_cons_s_spec;
  244. launch_cons_c_spec = other.launch_cons_c_spec;
  245. launch_cons_s_def = other.launch_cons_s_def;
  246. launch_cons_c_def = other.launch_cons_c_def;
  247. echo_launch_offset = other.echo_launch_offset;
  248. wiggle_magnitudes = other.wiggle_magnitudes;
  249. wiggle_speeds = other.wiggle_speeds;
  250. wiggle_axis_string = other.wiggle_axis_string;
  251. wiggle_num_axis = other.wiggle_num_axis;
  252. wiggle_axis = other.wiggle_axis;
  253. hover_altitude = other.hover_altitude;
  254. hover_attack_distance = other.hover_attack_distance;
  255. hover_attack_gradient = other.hover_attack_gradient;
  256. hover_time = other.hover_time;
  257. reverse_targeting = other.reverse_targeting;
  258. caster_safety_time = other.caster_safety_time;
  259. }
  260. afxMagicMissileData::~afxMagicMissileData()
  261. {
  262. if (wiggle_axis)
  263. delete [] wiggle_axis;
  264. }
  265. afxMagicMissileData* afxMagicMissileData::cloneAndPerformSubstitutions(const SimObject* owner, S32 index)
  266. {
  267. if (!owner || getSubstitutionCount() == 0)
  268. return this;
  269. afxMagicMissileData* sub_missile_db = new afxMagicMissileData(*this, true);
  270. performSubstitutions(sub_missile_db, owner, index);
  271. return sub_missile_db;
  272. }
  273. //--------------------------------------------------------------------------
  274. #define myOffset(field) Offset(field, afxMagicMissileData)
  275. FRangeValidator muzzleVelocityValidator(0, 10000);
  276. FRangeValidator missilePrecisionValidator(0.f, 100.f);
  277. FRangeValidator missileTrackDelayValidator(0, 100000);
  278. FRangeValidator missileBallisticCoefficientValidator(0, 1);
  279. void afxMagicMissileData::initPersistFields()
  280. {
  281. docsURL;
  282. static IRangeValidatorScaled ticksFromMS(TickMs, 0, MaxLifetimeTicks);
  283. addGroup("Shapes");
  284. INITPERSISTFIELD_SHAPEASSET(ProjectileShape, afxMagicMissileData, "Shape for the projectile");
  285. addField("scale", TypePoint3F, Offset(scale, afxMagicMissileData));
  286. addField("missileShapeScale", TypePoint3F, myOffset(scale));
  287. endGroup("Shapes");
  288. addGroup("Particle Effects");
  289. addField("particleEmitter", TYPEID<ParticleEmitterData>(), Offset(particleEmitter, afxMagicMissileData));
  290. addField("particleWaterEmitter", TYPEID<ParticleEmitterData>(), Offset(particleWaterEmitter, afxMagicMissileData));
  291. addField("splash", TYPEID<SplashData>(), Offset(splash, afxMagicMissileData));
  292. endGroup("Particle Effects");
  293. addGroup("Sounds");
  294. INITPERSISTFIELD_SOUNDASSET(ProjectileSound, afxMagicMissileData, "sound for the projectile");
  295. endGroup("Sounds");
  296. addGroup("Light Emitter");
  297. addField("lightDesc", TYPEID< LightDescription >(), Offset(lightDesc, afxMagicMissileData));
  298. endGroup("Light Emitter");
  299. addGroup("Physics");
  300. addNamedFieldV(lifetime, TypeS32, afxMagicMissileData, &ticksFromMS);
  301. addFieldV("casterSafetyTime", TypeS32, myOffset(caster_safety_time), &ticksFromMS);
  302. addField("isBallistic", TypeBool, Offset(isBallistic, afxMagicMissileData));
  303. addNamedFieldV(muzzleVelocity, TypeF32, afxMagicMissileData, &muzzleVelocityValidator);
  304. addNamedFieldV(ballisticCoefficient, TypeF32, afxMagicMissileData, &missileBallisticCoefficientValidator);
  305. addField("gravityMod", TypeF32, Offset(gravityMod, afxMagicMissileData));
  306. addField("collisionMask", TypeS32, myOffset(collision_mask));
  307. addField("startingVelocityVector",TypePoint3F, myOffset(starting_vel_vec));
  308. addNamedField(acceleration, TypeF32, afxMagicMissileData);
  309. addNamedFieldV(accelDelay, TypeS32, afxMagicMissileData, &ticksFromMS);
  310. addNamedFieldV(accelLifetime, TypeS32, afxMagicMissileData, &ticksFromMS);
  311. addField("reverseTargeting", TypeBool, myOffset(reverse_targeting));
  312. endGroup("Physics");
  313. addGroup("Physics-Tracking");
  314. addNamedField(isGuided, TypeBool, afxMagicMissileData);
  315. addNamedFieldV(precision, TypeF32, afxMagicMissileData, &missilePrecisionValidator);
  316. addNamedFieldV(trackDelay, TypeS32, afxMagicMissileData, &missileTrackDelayValidator);
  317. endGroup("Physics-Tracking");
  318. addGroup("Physics-Avoidance");
  319. addField("followTerrain", TypeBool, myOffset(followTerrain));
  320. addField("followTerrainHeight", TypeF32, myOffset(followTerrainHeight));
  321. addField("followTerrainAdjustRate", TypeF32, myOffset(followTerrainAdjustRate));
  322. addFieldV("followTerrainAdjustDelay", TypeS32, myOffset(followTerrainAdjustDelay), &ticksFromMS);
  323. addField("hoverAltitude", TypeF32, myOffset(hover_altitude));
  324. addField("hoverAttackDistance", TypeF32, myOffset(hover_attack_distance));
  325. addField("hoverAttackGradient", TypeF32, myOffset(hover_attack_gradient));
  326. addFieldV("hoverTime", TypeS32, myOffset(hover_time), &ticksFromMS);
  327. endGroup("Physics-Avoidance");
  328. addGroup("Physics-Launch");
  329. addField("launchNode", TypeString, myOffset(launch_node));
  330. addField("launchOffset", TypePoint3F, myOffset(launch_offset));
  331. addField("launchOffsetServer",TypePoint3F, myOffset(launch_offset_server));
  332. addField("launchOffsetClient",TypePoint3F, myOffset(launch_offset_client));
  333. addField("launchNodeOffset", TypePoint3F, myOffset(launch_node_offset));
  334. addField("launchAimPitch", TypeF32, myOffset(launch_pitch));
  335. addField("launchAimPan", TypeF32, myOffset(launch_pan));
  336. addField("launchConstraintServer", TypeString, myOffset(launch_cons_s_spec));
  337. addField("launchConstraintClient", TypeString, myOffset(launch_cons_c_spec));
  338. addField("echoLaunchOffset", TypeBool, myOffset(echo_launch_offset));
  339. endGroup("Physics-Launch");
  340. addGroup("Physics-Wiggle");
  341. addField("wiggleMagnitudes", TypeF32Vector, myOffset(wiggle_magnitudes));
  342. addField("wiggleSpeeds", TypeF32Vector, myOffset(wiggle_speeds));
  343. addField("wiggleAxis", TypeString, myOffset(wiggle_axis_string));
  344. endGroup("Physics-Wiggle");
  345. Parent::initPersistFields();
  346. // disallow some field substitutions
  347. onlyKeepClearSubstitutions("particleEmitter"); // subs resolving to "~~", or "~0" are OK
  348. onlyKeepClearSubstitutions("particleWaterEmitter");
  349. onlyKeepClearSubstitutions("sound");
  350. onlyKeepClearSubstitutions("splash");
  351. }
  352. //--------------------------------------------------------------------------
  353. bool afxMagicMissileData::onAdd()
  354. {
  355. if(!Parent::onAdd())
  356. return false;
  357. // ADDED BY MAGIC-MISSILE
  358. // Wiggle axes ////////////////////////////////////////////////////////////
  359. if (wiggle_axis_string != ST_NULLSTRING && wiggle_num_axis == 0)
  360. {
  361. // Tokenize input string and convert to Point3F array
  362. //
  363. Vector<String> dataBlocks(__FILE__, __LINE__);
  364. // make a copy of points_string
  365. dsize_t tokCopyLen = dStrlen(wiggle_axis_string) + 1;
  366. char* tokCopy = new char[tokCopyLen];
  367. dStrcpy(tokCopy, wiggle_axis_string, tokCopyLen);
  368. // extract tokens one by one, adding them to dataBlocks
  369. char* currTok = dStrtok(tokCopy, " \t");
  370. while (currTok != NULL)
  371. {
  372. dataBlocks.push_back(currTok);
  373. currTok = dStrtok(NULL, " \t");
  374. }
  375. // bail if there were no tokens in the string
  376. if (dataBlocks.size() == 0)
  377. {
  378. Con::warnf(ConsoleLogEntry::General, "afxMagicMissileData(%s) invalid wiggle axis string. No tokens found", getName());
  379. delete [] tokCopy;
  380. return false;
  381. }
  382. // Find wiggle_num_axis (round up to multiple of 3) // WARNING here if not multiple of 3?
  383. for (U32 i = 0; i < dataBlocks.size()%3; i++)
  384. {
  385. dataBlocks.push_back("0.0");
  386. }
  387. wiggle_num_axis = dataBlocks.size()/3;
  388. wiggle_axis = new Point3F[wiggle_num_axis];
  389. U32 p_i = 0;
  390. for (U32 i = 0; i < dataBlocks.size(); i+=3, p_i++)
  391. {
  392. F32 x,y,z;
  393. x = dAtof(dataBlocks[i]); // What about overflow?
  394. y = dAtof(dataBlocks[i+1]);
  395. z = dAtof(dataBlocks[i+2]);
  396. wiggle_axis[p_i].set(x,y,z);
  397. wiggle_axis[p_i].normalizeSafe(); // sufficient????
  398. }
  399. delete [] tokCopy;
  400. }
  401. launch_cons_s_def.parseSpec(launch_cons_s_spec, true, false);
  402. launch_cons_c_def.parseSpec(launch_cons_c_spec, false, true);
  403. return true;
  404. }
  405. bool afxMagicMissileData::preload(bool server, String &errorStr)
  406. {
  407. if (Parent::preload(server, errorStr) == false)
  408. return false;
  409. if( !server )
  410. {
  411. if (!particleEmitter && particleEmitterId != 0)
  412. if (Sim::findObject(particleEmitterId, particleEmitter) == false)
  413. Con::errorf(ConsoleLogEntry::General, "afxMagicMissileData::preload: Invalid packet, bad datablockId(particleEmitter): %d", particleEmitterId);
  414. if (!particleWaterEmitter && particleWaterEmitterId != 0)
  415. if (Sim::findObject(particleWaterEmitterId, particleWaterEmitter) == false)
  416. Con::errorf(ConsoleLogEntry::General, "afxMagicMissileData::preload: Invalid packet, bad datablockId(particleWaterEmitter): %d", particleWaterEmitterId);
  417. /* From stock Projectile code...
  418. if (!explosion && explosionId != 0)
  419. if (Sim::findObject(explosionId, explosion) == false)
  420. Con::errorf(ConsoleLogEntry::General, "ProjectileData::preload: Invalid packet, bad datablockId(explosion): %d", explosionId);
  421. if (!waterExplosion && waterExplosionId != 0)
  422. if (Sim::findObject(waterExplosionId, waterExplosion) == false)
  423. Con::errorf(ConsoleLogEntry::General, "ProjectileData::preload: Invalid packet, bad datablockId(waterExplosion): %d", waterExplosionId);
  424. */
  425. if (!splash && splashId != 0)
  426. if (Sim::findObject(splashId, splash) == false)
  427. Con::errorf(ConsoleLogEntry::General, "afxMagicMissileData::preload: Invalid packet, bad datablockId(splash): %d", splashId);
  428. /* From stock Projectile code...
  429. if (!decal && decalId != 0)
  430. if (Sim::findObject(decalId, decal) == false)
  431. Con::errorf(ConsoleLogEntry::General, "ProjectileData::preload: Invalid packet, bad datablockId(decal): %d", decalId);
  432. */
  433. if (getProjectileSound() != StringTable->EmptyString() && !isProjectileSoundValid())
  434. {
  435. Con::errorf(ConsoleLogEntry::General, "afxMagicMissileData::preload: Invalid ProjectileSound asset.");
  436. return false;
  437. }
  438. if (!lightDesc && lightDescId != 0)
  439. if (Sim::findObject(lightDescId, lightDesc) == false)
  440. Con::errorf(ConsoleLogEntry::General, "afxMagicMissileData::preload: Invalid packet, bad datablockid(lightDesc): %d", lightDescId);
  441. }
  442. if (!mProjectileShapeAsset.isNull())
  443. {
  444. projectileShape = mProjectileShapeAsset->getShapeResource();
  445. if (bool(projectileShape) == false)
  446. {
  447. errorStr = String::ToString("afxMagicMissileData::preload: Couldn't load shape \"%s\"", mProjectileShapeAssetId);
  448. return false;
  449. }
  450. /* From stock Projectile code...
  451. activateSeq = projectileShape->findSequence("activate");
  452. maintainSeq = projectileShape->findSequence("maintain");
  453. */
  454. }
  455. if (bool(projectileShape)) // create an instance to preload shape data
  456. {
  457. TSShapeInstance* pDummy = new TSShapeInstance(projectileShape, !server);
  458. delete pDummy;
  459. }
  460. return true;
  461. }
  462. //--------------------------------------------------------------------------
  463. // Modified from floorPlanRes.cc
  464. // Read a vector of items
  465. template <class T>
  466. bool readVector(Vector<T> & vec, Stream & stream, const char * msg)
  467. {
  468. U32 num, i;
  469. bool Ok = true;
  470. stream.read( & num );
  471. vec.setSize( num );
  472. for( i = 0; i < num && Ok; i++ ){
  473. Ok = stream.read(& vec[i]);
  474. AssertISV( Ok, avar("math vec read error (%s) on elem %d", msg, i) );
  475. }
  476. return Ok;
  477. }
  478. // Write a vector of items
  479. template <class T>
  480. bool writeVector(const Vector<T> & vec, Stream & stream, const char * msg)
  481. {
  482. bool Ok = true;
  483. stream.write( vec.size() );
  484. for( U32 i = 0; i < vec.size() && Ok; i++ ) {
  485. Ok = stream.write(vec[i]);
  486. AssertISV( Ok, avar("vec write error (%s) on elem %d", msg, i) );
  487. }
  488. return Ok;
  489. }
  490. //--------------------------------------------------------------------------
  491. void afxMagicMissileData::packData(BitStream* stream)
  492. {
  493. Parent::packData(stream);
  494. PACKDATA_ASSET(ProjectileShape);
  495. /* From stock Projectile code...
  496. stream->writeFlag(faceViewer);
  497. */
  498. if(stream->writeFlag(scale.x != 1 || scale.y != 1 || scale.z != 1))
  499. {
  500. stream->write(scale.x);
  501. stream->write(scale.y);
  502. stream->write(scale.z);
  503. }
  504. stream->write(collision_mask);
  505. if (stream->writeFlag(particleEmitter != NULL))
  506. stream->writeRangedU32(particleEmitter->getId(), DataBlockObjectIdFirst,
  507. DataBlockObjectIdLast);
  508. if (stream->writeFlag(particleWaterEmitter != NULL))
  509. stream->writeRangedU32(particleWaterEmitter->getId(), DataBlockObjectIdFirst,
  510. DataBlockObjectIdLast);
  511. /* From stock Projectile code...
  512. if (stream->writeFlag(explosion != NULL))
  513. stream->writeRangedU32(explosion->getId(), DataBlockObjectIdFirst,
  514. DataBlockObjectIdLast);
  515. if (stream->writeFlag(waterExplosion != NULL))
  516. stream->writeRangedU32(waterExplosion->getId(), DataBlockObjectIdFirst,
  517. DataBlockObjectIdLast);
  518. */
  519. if (stream->writeFlag(splash != NULL))
  520. stream->writeRangedU32(splash->getId(), DataBlockObjectIdFirst,
  521. DataBlockObjectIdLast);
  522. /* From stock Projectile code...
  523. if (stream->writeFlag(decal != NULL))
  524. stream->writeRangedU32(decal->getId(), DataBlockObjectIdFirst,
  525. DataBlockObjectIdLast);
  526. */
  527. PACKDATA_ASSET(ProjectileSound);
  528. if ( stream->writeFlag(lightDesc != NULL))
  529. stream->writeRangedU32(lightDesc->getId(), DataBlockObjectIdFirst,
  530. DataBlockObjectIdLast);
  531. /* From stock Projectile code...
  532. stream->write(impactForce);
  533. */
  534. stream->write(lifetime);
  535. /* From stock Projectile code...
  536. stream->write(armingDelay);
  537. stream->write(fadeDelay);
  538. */
  539. if(stream->writeFlag(isBallistic))
  540. {
  541. stream->write(gravityMod);
  542. /* From stock Projectile code...
  543. stream->write(bounceElasticity);
  544. stream->write(bounceFriction);
  545. */
  546. stream->write(ballisticCoefficient);
  547. }
  548. if(stream->writeFlag(isGuided))
  549. {
  550. stream->write(precision);
  551. stream->write(trackDelay);
  552. }
  553. stream->write(muzzleVelocity);
  554. mathWrite(*stream, starting_vel_vec);
  555. stream->write(acceleration);
  556. stream->write(accelDelay);
  557. stream->write(accelLifetime);
  558. stream->writeString(launch_node);
  559. mathWrite(*stream, launch_offset);
  560. mathWrite(*stream, launch_offset_server);
  561. mathWrite(*stream, launch_offset_client);
  562. mathWrite(*stream, launch_node_offset);
  563. stream->write(launch_pitch);
  564. stream->write(launch_pan);
  565. stream->writeString(launch_cons_c_spec);
  566. stream->writeFlag(echo_launch_offset);
  567. writeVector(wiggle_magnitudes, *stream, "afxMagicMissile: wiggle_magnitudes");
  568. writeVector(wiggle_speeds, *stream, "afxMagicMissile: wiggle_speeds");
  569. stream->write(wiggle_num_axis);
  570. for (U32 i = 0; i < wiggle_num_axis; i++)
  571. mathWrite(*stream, wiggle_axis[i]);
  572. stream->write(hover_altitude);
  573. stream->write(hover_attack_distance);
  574. stream->write(hover_attack_gradient);
  575. stream->writeRangedU32(hover_time, 0, MaxLifetimeTicks);
  576. stream->writeFlag(reverse_targeting);
  577. stream->write(caster_safety_time);
  578. }
  579. void afxMagicMissileData::unpackData(BitStream* stream)
  580. {
  581. Parent::unpackData(stream);
  582. UNPACKDATA_ASSET(ProjectileShape);
  583. /* From stock Projectile code...
  584. faceViewer = stream->readFlag();
  585. */
  586. if(stream->readFlag())
  587. {
  588. stream->read(&scale.x);
  589. stream->read(&scale.y);
  590. stream->read(&scale.z);
  591. }
  592. else
  593. scale.set(1,1,1);
  594. stream->read(&collision_mask);
  595. if (stream->readFlag())
  596. particleEmitterId = stream->readRangedU32(DataBlockObjectIdFirst, DataBlockObjectIdLast);
  597. if (stream->readFlag())
  598. particleWaterEmitterId = stream->readRangedU32(DataBlockObjectIdFirst, DataBlockObjectIdLast);
  599. /* From stock Projectile code...
  600. if (stream->readFlag())
  601. explosionId = stream->readRangedU32(DataBlockObjectIdFirst, DataBlockObjectIdLast);
  602. if (stream->readFlag())
  603. waterExplosionId = stream->readRangedU32(DataBlockObjectIdFirst, DataBlockObjectIdLast);
  604. */
  605. if (stream->readFlag())
  606. splashId = stream->readRangedU32(DataBlockObjectIdFirst, DataBlockObjectIdLast);
  607. /* From stock Projectile code...
  608. if (stream->readFlag())
  609. decalId = stream->readRangedU32(DataBlockObjectIdFirst, DataBlockObjectIdLast);
  610. */
  611. UNPACKDATA_ASSET(ProjectileSound);
  612. if (stream->readFlag())
  613. lightDescId = stream->readRangedU32(DataBlockObjectIdFirst, DataBlockObjectIdLast);
  614. /* From stock Projectile code...
  615. stream->read(&impactForce);
  616. */
  617. stream->read(&lifetime);
  618. /* From stock Projectile code...
  619. stream->read(&armingDelay);
  620. stream->read(&fadeDelay);
  621. */
  622. isBallistic = stream->readFlag();
  623. if(isBallistic)
  624. {
  625. stream->read(&gravityMod);
  626. /* From stock Projectile code...
  627. stream->read(&bounceElasticity);
  628. stream->read(&bounceFriction);
  629. */
  630. stream->read(&ballisticCoefficient);
  631. }
  632. isGuided = stream->readFlag();
  633. if(isGuided)
  634. {
  635. stream->read(&precision);
  636. stream->read(&trackDelay);
  637. }
  638. stream->read(&muzzleVelocity);
  639. mathRead(*stream, &starting_vel_vec);
  640. stream->read(&acceleration);
  641. stream->read(&accelDelay);
  642. stream->read(&accelLifetime);
  643. launch_node = stream->readSTString();
  644. mathRead(*stream, &launch_offset);
  645. mathRead(*stream, &launch_offset_server);
  646. mathRead(*stream, &launch_offset_client);
  647. mathRead(*stream, &launch_node_offset);
  648. stream->read(&launch_pitch);
  649. stream->read(&launch_pan);
  650. launch_cons_c_spec = stream->readSTString();
  651. echo_launch_offset = stream->readFlag();
  652. readVector(wiggle_magnitudes, *stream, "afxMagicMissile: wiggle_magnitudes");
  653. readVector(wiggle_speeds, *stream, "afxMagicMissile: wiggle_speeds");
  654. if (wiggle_axis)
  655. delete [] wiggle_axis;
  656. wiggle_axis = 0;
  657. wiggle_num_axis = 0;
  658. stream->read(&wiggle_num_axis);
  659. if (wiggle_num_axis > 0)
  660. {
  661. wiggle_axis = new Point3F[wiggle_num_axis];
  662. for (U32 i = 0; i < wiggle_num_axis; i++)
  663. mathRead(*stream, &wiggle_axis[i]);
  664. }
  665. stream->read(&hover_altitude);
  666. stream->read(&hover_attack_distance);
  667. stream->read(&hover_attack_gradient);
  668. hover_time = stream->readRangedU32(0, MaxLifetimeTicks);
  669. reverse_targeting = stream->readFlag();
  670. stream->read(&caster_safety_time);
  671. }
  672. /* From stock Projectile code...
  673. bool ProjectileData::setLifetime( void *obj, const char *index, const char *data )
  674. {
  675. S32 value = dAtoi(data);
  676. value = scaleValue(value);
  677. ProjectileData *object = static_cast<ProjectileData*>(obj);
  678. object->lifetime = value;
  679. return false;
  680. }
  681. bool ProjectileData::setArmingDelay( void *obj, const char *index, const char *data )
  682. {
  683. S32 value = dAtoi(data);
  684. value = scaleValue(value);
  685. ProjectileData *object = static_cast<ProjectileData*>(obj);
  686. object->armingDelay = value;
  687. return false;
  688. }
  689. bool ProjectileData::setFadeDelay( void *obj, const char *index, const char *data )
  690. {
  691. S32 value = dAtoi(data);
  692. value = scaleValue(value);
  693. ProjectileData *object = static_cast<ProjectileData*>(obj);
  694. object->fadeDelay = value;
  695. return false;
  696. }
  697. const char *ProjectileData::getScaledValue( void *obj, const char *data)
  698. {
  699. S32 value = dAtoi(data);
  700. value = scaleValue(value, false);
  701. String stringData = String::ToString(value);
  702. char *strBuffer = Con::getReturnBuffer(stringData.size());
  703. dMemcpy( strBuffer, stringData, stringData.size() );
  704. return strBuffer;
  705. }
  706. S32 ProjectileData::scaleValue( S32 value, bool down )
  707. {
  708. S32 minV = 0;
  709. S32 maxV = Projectile::MaxLivingTicks;
  710. // scale down to ticks before we validate
  711. if( down )
  712. value /= TickMs;
  713. if(value < minV || value > maxV)
  714. {
  715. Con::errorf("ProjectileData::scaleValue(S32 value = %d, bool down = %b) - Scaled value must be between %d and %d", value, down, minV, maxV);
  716. if(value < minV)
  717. value = minV;
  718. else if(value > maxV)
  719. value = maxV;
  720. }
  721. // scale up from ticks after we validate
  722. if( !down )
  723. value *= TickMs;
  724. return value;
  725. }
  726. */
  727. void afxMagicMissileData::gather_cons_defs(Vector<afxConstraintDef>& defs)
  728. {
  729. if (launch_cons_s_def.isDefined())
  730. defs.push_back(launch_cons_s_def);
  731. if (launch_cons_c_def.isDefined())
  732. defs.push_back(launch_cons_c_def);
  733. };
  734. //~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~~//
  735. //~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~~//
  736. // afxMagicMissile
  737. afxMagicMissile::afxMagicMissile()
  738. {
  739. init(true, true);
  740. }
  741. afxMagicMissile::afxMagicMissile(bool on_server, bool on_client)
  742. {
  743. init(on_server, on_client);
  744. }
  745. //--------------------------------------------------------------------------
  746. //--------------------------------------
  747. //
  748. void afxMagicMissile::init(bool on_server, bool on_client)
  749. {
  750. mPhysicsWorld = NULL;
  751. mTypeMask |= ProjectileObjectType | LightObjectType;
  752. mLight = LightManager::createLightInfo();
  753. mLight->setType( LightInfo::Point );
  754. mLightState.clear();
  755. mLightState.setLightInfo( mLight );
  756. mCurrPosition.zero();
  757. mCurrVelocity.set(0, 0, 1);
  758. mCurrTick = 0;
  759. mParticleEmitter = NULL;
  760. mParticleWaterEmitter = NULL;
  761. mSound = 0;
  762. mProjectileShape = NULL;
  763. mDataBlock = NULL;
  764. choreographer = NULL;
  765. if (on_server != on_client)
  766. {
  767. client_only = on_client;
  768. server_only = on_server;
  769. mNetFlags.clear(Ghostable | ScopeAlways);
  770. if (client_only)
  771. mNetFlags.set(IsGhost);
  772. }
  773. else
  774. {
  775. // note -- setting neither server or client makes no sense so we
  776. // treat as if both are set.
  777. mNetFlags.set(Ghostable | ScopeAlways);
  778. client_only = server_only = false;
  779. }
  780. mCurrDeltaBase.zero();
  781. mCurrBackDelta.zero();
  782. collision_mask = 0;
  783. prec_inc = 0.0f;
  784. did_launch = false;
  785. did_impact = false;
  786. missile_target = NULL;
  787. collide_exempt = NULL;
  788. use_accel = false;
  789. hover_attack_go = false;
  790. hover_attack_tick = 0;
  791. starting_velocity = 0.0;
  792. starting_vel_vec.zero();
  793. ss_object = 0;
  794. ss_index = 0;
  795. }
  796. afxMagicMissile::~afxMagicMissile()
  797. {
  798. SAFE_DELETE(mLight);
  799. delete mProjectileShape;
  800. mProjectileShape = NULL;
  801. }
  802. //--------------------------------------------------------------------------
  803. void afxMagicMissile::initPersistFields()
  804. {
  805. docsURL;
  806. addGroup("Physics");
  807. addField("initialPosition", TypePoint3F, Offset(mCurrPosition, afxMagicMissile) ,
  808. "Initial starting position for this missile.");
  809. addField("initialVelocity", TypePoint3F, Offset(mCurrVelocity, afxMagicMissile) ,
  810. "Initial starting velocity for this missile.");
  811. endGroup("Physics");
  812. /* From stock Projectile code...
  813. addGroup("Source");
  814. addField("sourceObject", TypeS32, Offset(mSourceObjectId, Projectile) ,"The object that fires this projectile. If this projectile was fired by a WeaponImage, it will be the object that owns the WeaponImage, usually the player.");
  815. addField("sourceSlot", TypeS32, Offset(mSourceObjectSlot, Projectile) ,"Which weapon slot on the sourceObject that this projectile originates from.");
  816. endGroup("Source");
  817. */
  818. Parent::initPersistFields();
  819. }
  820. /* From stock Projectile code...
  821. bool Projectile::calculateImpact(float,
  822. Point3F& pointOfImpact,
  823. float& impactTime)
  824. {
  825. Con::warnf(ConsoleLogEntry::General, "Projectile::calculateImpact: Should never be called");
  826. impactTime = 0;
  827. pointOfImpact.set(0, 0, 0);
  828. return false;
  829. }
  830. //--------------------------------------------------------------------------
  831. F32 Projectile::getUpdatePriority(CameraScopeQuery *camInfo, U32 updateMask, S32 updateSkips)
  832. {
  833. F32 ret = Parent::getUpdatePriority(camInfo, updateMask, updateSkips);
  834. // if the camera "owns" this object, it should have a slightly higher priority
  835. if(mSourceObject == camInfo->camera)
  836. return ret + 0.2;
  837. return ret;
  838. }
  839. */
  840. bool afxMagicMissile::onAdd()
  841. {
  842. if(!Parent::onAdd())
  843. return false;
  844. if (isServerObject())
  845. {
  846. /* From stock Projectile code...
  847. ShapeBase* ptr;
  848. if (Sim::findObject(mSourceObjectId, ptr))
  849. {
  850. mSourceObject = ptr;
  851. // Since we later do processAfter( mSourceObject ) we must clearProcessAfter
  852. // if it is deleted. SceneObject already handles this in onDeleteNotify so
  853. // all we need to do is register for the notification.
  854. deleteNotify( ptr );
  855. }
  856. else
  857. {
  858. if (mSourceObjectId != -1)
  859. Con::errorf(ConsoleLogEntry::General, "Projectile::onAdd: mSourceObjectId is invalid");
  860. mSourceObject = NULL;
  861. }
  862. // If we're on the server, we need to inherit some of our parent's velocity
  863. //
  864. mCurrTick = 0;
  865. */
  866. }
  867. else
  868. {
  869. if (bool(mDataBlock->projectileShape))
  870. {
  871. mProjectileShape = new TSShapeInstance(mDataBlock->projectileShape, true);
  872. /* From stock Projectile code...
  873. if (mDataBlock->activateSeq != -1)
  874. {
  875. mActivateThread = mProjectileShape->addThread();
  876. mProjectileShape->setTimeScale(mActivateThread, 1);
  877. mProjectileShape->setSequence(mActivateThread, mDataBlock->activateSeq, 0);
  878. }
  879. */
  880. }
  881. if (mDataBlock->particleEmitter != NULL)
  882. {
  883. ParticleEmitter* pEmitter = new ParticleEmitter;
  884. //pEmitter->setDataBlock(mDataBlock->particleEmitter->cloneAndPerformSubstitutions(ss_object, ss_index));
  885. pEmitter->onNewDataBlock(mDataBlock->particleEmitter->cloneAndPerformSubstitutions(ss_object, ss_index), false);
  886. if (pEmitter->registerObject() == false)
  887. {
  888. Con::warnf(ConsoleLogEntry::General, "Could not register particle emitter for particle of class: %s", mDataBlock->getName());
  889. delete pEmitter;
  890. pEmitter = NULL;
  891. }
  892. mParticleEmitter = pEmitter;
  893. }
  894. if (mDataBlock->particleWaterEmitter != NULL)
  895. {
  896. ParticleEmitter* pEmitter = new ParticleEmitter;
  897. pEmitter->onNewDataBlock(mDataBlock->particleWaterEmitter->cloneAndPerformSubstitutions(ss_object, ss_index), false);
  898. if (pEmitter->registerObject() == false)
  899. {
  900. Con::warnf(ConsoleLogEntry::General, "Could not register particle emitter for particle of class: %s", mDataBlock->getName());
  901. delete pEmitter;
  902. pEmitter = NULL;
  903. }
  904. mParticleWaterEmitter = pEmitter;
  905. }
  906. }
  907. /* From stock Projectile code...
  908. if (mSourceObject.isValid())
  909. processAfter(mSourceObject);
  910. */
  911. // detect for acceleration
  912. use_accel = (mDataBlock->acceleration != 0 && mDataBlock->accelLifetime > 0);
  913. // Setup our bounding box
  914. if (bool(mDataBlock->projectileShape) == true)
  915. mObjBox = mDataBlock->projectileShape->mBounds;
  916. else
  917. mObjBox = Box3F(Point3F(0, 0, 0), Point3F(0, 0, 0));
  918. resetWorldBox();
  919. addToScene();
  920. if ( PHYSICSMGR )
  921. mPhysicsWorld = PHYSICSMGR->getWorld( isServerObject() ? "server" : "client" );
  922. return true;
  923. }
  924. void afxMagicMissile::onRemove()
  925. {
  926. if(mParticleEmitter)
  927. {
  928. mParticleEmitter->deleteWhenEmpty();
  929. mParticleEmitter = NULL;
  930. }
  931. if(mParticleWaterEmitter)
  932. {
  933. mParticleWaterEmitter->deleteWhenEmpty();
  934. mParticleWaterEmitter = NULL;
  935. }
  936. SFX_DELETE( mSound );
  937. removeFromScene();
  938. Parent::onRemove();
  939. }
  940. bool afxMagicMissile::onNewDataBlock(GameBaseData* dptr, bool reload)
  941. {
  942. mDataBlock = dynamic_cast<afxMagicMissileData*>(dptr);
  943. if (!mDataBlock || !Parent::onNewDataBlock(dptr, reload))
  944. return false;
  945. starting_velocity = mDataBlock->muzzleVelocity;
  946. starting_vel_vec = mDataBlock->starting_vel_vec;
  947. collision_mask = mDataBlock->collision_mask;
  948. if ( isGhost() )
  949. {
  950. // Create the sound ahead of time. This reduces runtime
  951. // costs and makes the system easier to understand.
  952. SFX_DELETE( mSound );
  953. if (mDataBlock->getProjectileSound())
  954. mSound = SFX->createSource(mDataBlock->getProjectileSoundProfile());
  955. }
  956. return true;
  957. }
  958. //--------------------------------------------------------------------------
  959. void afxMagicMissile::submitLights( LightManager *lm, bool staticLighting )
  960. {
  961. if ( staticLighting || isHidden() || !mDataBlock->lightDesc )
  962. return;
  963. mDataBlock->lightDesc->submitLight( &mLightState, getRenderTransform(), lm, this );
  964. }
  965. bool afxMagicMissile::pointInWater(const Point3F &point)
  966. {
  967. // This is pretty much a hack so we can use the existing ContainerQueryInfo
  968. // and findObject router.
  969. // We only care if we intersect with water at all
  970. // so build a box at the point that has only 1 z extent.
  971. // And test if water coverage is anything other than zero.
  972. Box3F boundsBox( point, point );
  973. boundsBox.maxExtents.z += 1.0f;
  974. ContainerQueryInfo info;
  975. info.box = boundsBox;
  976. info.mass = 0.0f;
  977. // Find and retreive physics info from intersecting WaterObject(s)
  978. if(mContainer != NULL)
  979. {
  980. mContainer->findObjects( boundsBox, WaterObjectType, findRouter, &info );
  981. }
  982. else
  983. {
  984. // Handle special case where the projectile has exploded prior to having
  985. // called onAdd() on the client. This occurs when the projectile on the
  986. // server is created and then explodes in the same network update tick.
  987. // On the client end in NetConnection::ghostReadPacket() the ghost is
  988. // created and then Projectile::unpackUpdate() is called prior to the
  989. // projectile being registered. Within unpackUpdate() the explosion
  990. // is triggered, but without being registered onAdd() isn't called and
  991. // the container is not set. As all we're doing is checking if the
  992. // given explosion point is within water, we should be able to use the
  993. // global container here. We could likely always get away with this,
  994. // but using the actual defined container when possible is the right
  995. // thing to do. DAW
  996. AssertFatal(isClientObject(), "Server projectile has not been properly added");
  997. gClientContainer.findObjects( boundsBox, WaterObjectType, findRouter, &info );
  998. }
  999. return ( info.waterCoverage > 0.0f );
  1000. }
  1001. //----------------------------------------------------------------------------
  1002. void afxMagicMissile::emitParticles(const Point3F& from, const Point3F& to, const Point3F& vel, const U32 ms)
  1003. {
  1004. /* From stock Projectile code...
  1005. if ( isHidden() )
  1006. return;
  1007. */
  1008. Point3F axis = -vel;
  1009. if( axis.isZero() )
  1010. axis.set( 0.0, 0.0, 1.0 );
  1011. else
  1012. axis.normalize();
  1013. bool fromWater = pointInWater(from);
  1014. bool toWater = pointInWater(to);
  1015. if (!fromWater && !toWater && bool(mParticleEmitter)) // not in water
  1016. mParticleEmitter->emitParticles(from, to, axis, vel, ms);
  1017. else if (fromWater && toWater && bool(mParticleWaterEmitter)) // in water
  1018. mParticleWaterEmitter->emitParticles(from, to, axis, vel, ms);
  1019. else if (!fromWater && toWater) // entering water
  1020. {
  1021. // cast the ray to get the surface point of the water
  1022. RayInfo rInfo;
  1023. if (gClientContainer.castRay(from, to, WaterObjectType, &rInfo))
  1024. {
  1025. create_splash(rInfo.point);
  1026. // create an emitter for the particles out of water and the particles in water
  1027. if (mParticleEmitter)
  1028. mParticleEmitter->emitParticles(from, rInfo.point, axis, vel, ms);
  1029. if (mParticleWaterEmitter)
  1030. mParticleWaterEmitter->emitParticles(rInfo.point, to, axis, vel, ms);
  1031. }
  1032. }
  1033. else if (fromWater && !toWater) // leaving water
  1034. {
  1035. // cast the ray in the opposite direction since that point is out of the water, otherwise
  1036. // we hit water immediately and wont get the appropriate surface point
  1037. RayInfo rInfo;
  1038. if (gClientContainer.castRay(to, from, WaterObjectType, &rInfo))
  1039. {
  1040. create_splash(rInfo.point);
  1041. // create an emitter for the particles out of water and the particles in water
  1042. if (mParticleEmitter)
  1043. mParticleEmitter->emitParticles(rInfo.point, to, axis, vel, ms);
  1044. if (mParticleWaterEmitter)
  1045. mParticleWaterEmitter->emitParticles(from, rInfo.point, axis, vel, ms);
  1046. }
  1047. }
  1048. }
  1049. void afxMagicMissile::processTick(const Move* move)
  1050. {
  1051. Parent::processTick( move );
  1052. // only active from launch to impact
  1053. if (!is_active())
  1054. return;
  1055. mCurrTick++;
  1056. // missile fizzles out by exceeding lifetime
  1057. if ((isServerObject() || client_only) && mCurrTick >= mDataBlock->lifetime)
  1058. {
  1059. did_impact = true;
  1060. setMaskBits(ImpactMask);
  1061. if (choreographer)
  1062. {
  1063. Point3F n = mCurrVelocity; n.normalizeSafe();
  1064. choreographer->impactNotify(mCurrPosition, n, 0);
  1065. }
  1066. Sim::postEvent(this, new ObjectDeleteEvent, Sim::getCurrentTime() + 500);
  1067. return;
  1068. }
  1069. static F32 dT = F32(TickMs)*0.001f;
  1070. Point3F old_pos = mCurrPosition;
  1071. // adjust missile velocity from gravity and drag influences
  1072. if (mDataBlock->isBallistic)
  1073. {
  1074. F32 dV = (1 - mDataBlock->ballisticCoefficient)*dT;
  1075. Point3F d(mCurrVelocity.x*dV, mCurrVelocity.y*dV, 9.81f*mDataBlock->gravityMod*dT);
  1076. mCurrVelocity -= d;
  1077. }
  1078. // adjust missile velocity from acceleration
  1079. if (use_accel)
  1080. {
  1081. if (mCurrTick > mDataBlock->accelDelay &&
  1082. mCurrTick <= mDataBlock->accelDelay + mDataBlock->accelLifetime)
  1083. {
  1084. Point3F d = mCurrVelocity; d.normalizeSafe();
  1085. mCurrVelocity += d*mDataBlock->acceleration*dT;
  1086. }
  1087. }
  1088. // adjust mCurrVelocity from guidance system influences
  1089. if (mDataBlock->isGuided && missile_target && mCurrTick > mDataBlock->trackDelay)
  1090. {
  1091. // get the position tracked by the guidance system
  1092. Point3F target_pos = missile_target->getBoxCenter();
  1093. Point3F target_vec = target_pos - mCurrPosition;
  1094. F32 target_dist_sq = target_vec.lenSquared();
  1095. if (target_dist_sq < 4.0f)
  1096. prec_inc += 1.0f;
  1097. // hover
  1098. if (mDataBlock->hover_altitude > 0.0f)
  1099. {
  1100. Point3F target_vec_xy(target_vec.x, target_vec.y, 0);
  1101. F32 xy_dist = target_vec_xy.len();
  1102. if (xy_dist > mDataBlock->hover_attack_distance)
  1103. {
  1104. hover_attack_go = false;
  1105. if (xy_dist > mDataBlock->hover_attack_distance + mDataBlock->hover_attack_gradient)
  1106. {
  1107. target_pos.z += mDataBlock->hover_altitude;
  1108. }
  1109. else
  1110. {
  1111. target_pos.z += afxEase::eq( (xy_dist-mDataBlock->hover_attack_distance)/mDataBlock->hover_attack_gradient,
  1112. 0.0f, mDataBlock->hover_altitude,
  1113. 0.25f, 0.75f);
  1114. }
  1115. target_vec = target_pos - mCurrPosition;
  1116. }
  1117. else
  1118. {
  1119. if (!hover_attack_go)
  1120. {
  1121. hover_attack_go = true;
  1122. hover_attack_tick = 0;
  1123. }
  1124. hover_attack_tick++;
  1125. if (hover_attack_tick < mDataBlock->hover_time)
  1126. {
  1127. target_pos.z += mDataBlock->hover_altitude;
  1128. target_vec = target_pos - mCurrPosition;
  1129. }
  1130. }
  1131. }
  1132. // apply precision
  1133. // extract speed
  1134. F32 speed = mCurrVelocity.len();
  1135. // normalize vectors
  1136. target_vec.normalizeSafe();
  1137. mCurrVelocity.normalize();
  1138. F32 prec = mDataBlock->precision;
  1139. // fade in precision gradually to avoid sudden turn
  1140. if (mCurrTick < mDataBlock->trackDelay + 16)
  1141. prec *= (mCurrTick - mDataBlock->trackDelay)/16.0f;
  1142. prec += prec_inc;
  1143. if (prec > 100)
  1144. prec = 100;
  1145. // apply precision weighting
  1146. target_vec *= prec;
  1147. mCurrVelocity *= (100 - prec);
  1148. mCurrVelocity += target_vec;
  1149. mCurrVelocity.normalize();
  1150. mCurrVelocity *= speed;
  1151. }
  1152. // wiggle
  1153. for (U32 i = 0; i < mDataBlock->wiggle_num_axis; i++)
  1154. {
  1155. if (i >= mDataBlock->wiggle_magnitudes.size() || i >= mDataBlock->wiggle_speeds.size())
  1156. break;
  1157. F32 wiggle_mag = mDataBlock->wiggle_magnitudes[i];
  1158. F32 wiggle_speed = mDataBlock->wiggle_speeds[i];
  1159. Point3F wiggle_axis = mDataBlock->wiggle_axis[i];
  1160. //wiggle_axis.normalizeSafe(); // sufficient????
  1161. F32 theta = wiggle_mag * mSin(wiggle_speed*(mCurrTick*TickSec));
  1162. //Con::printf( "theta: %f", theta );
  1163. AngAxisF thetaRot(wiggle_axis, theta);
  1164. MatrixF temp(true);
  1165. thetaRot.setMatrix(&temp);
  1166. temp.mulP(mCurrVelocity);
  1167. }
  1168. Point3F new_pos = old_pos + mCurrVelocity*dT;
  1169. // conform to terrain
  1170. if (mDataBlock->followTerrain && mCurrTick >= mDataBlock->followTerrainAdjustDelay)
  1171. {
  1172. U32 mask = TerrainObjectType | TerrainLikeObjectType; // | InteriorObjectType;
  1173. F32 ht = mDataBlock->followTerrainHeight;
  1174. F32 ht_rate = mDataBlock->followTerrainAdjustRate;
  1175. F32 ht_min = 0.05f;
  1176. if (ht < ht_min)
  1177. ht = ht_min;
  1178. SceneContainer* container = (isServerObject()) ? &gServerContainer : &gClientContainer;
  1179. Point3F above_pos = new_pos; above_pos.z += 10000;
  1180. Point3F below_pos = new_pos; below_pos.z -= 10000;
  1181. RayInfo rInfo;
  1182. if (container && container->castRay(above_pos, below_pos, mask, &rInfo))
  1183. {
  1184. F32 terrain_z = rInfo.point.z;
  1185. F32 seek_z = terrain_z + ht;
  1186. if (new_pos.z < seek_z)
  1187. {
  1188. new_pos.z += ht_rate*dT;
  1189. if (new_pos.z > seek_z)
  1190. new_pos.z = seek_z;
  1191. }
  1192. else if (new_pos.z > seek_z)
  1193. {
  1194. new_pos.z -= ht_rate*dT;
  1195. if (new_pos.z < seek_z)
  1196. new_pos.z = seek_z;
  1197. }
  1198. if (new_pos.z < terrain_z + ht_min)
  1199. new_pos.z = terrain_z + ht_min;
  1200. }
  1201. }
  1202. // only check for impacts on server
  1203. if (isServerObject())
  1204. {
  1205. // avoid collision with the spellcaster
  1206. if (collide_exempt && mCurrTick <= mDataBlock->caster_safety_time)
  1207. collide_exempt->disableCollision();
  1208. // check for collision along ray from old to new position
  1209. RayInfo rInfo;
  1210. bool did_hit = false;
  1211. if (mPhysicsWorld)
  1212. {
  1213. // did_hit = mPhysicsWorld->castRay(old_pos, new_pos, &rInfo, Point3F(new_pos - old_pos) * mDataBlock->impactForce );
  1214. // Impulse currently hardcoded for testing purposes
  1215. did_hit = mPhysicsWorld->castRay(old_pos, new_pos, &rInfo, Point3F(new_pos - old_pos) * 1000.0f );
  1216. }
  1217. else
  1218. {
  1219. did_hit = getContainer()->castRay(old_pos, new_pos, collision_mask, &rInfo);
  1220. }
  1221. // restore collisions on spellcaster
  1222. if (collide_exempt && mCurrTick <= mDataBlock->caster_safety_time)
  1223. collide_exempt->enableCollision();
  1224. // process impact
  1225. if (did_hit)
  1226. {
  1227. MatrixF xform(true);
  1228. xform.setColumn(3, rInfo.point);
  1229. setTransform(xform);
  1230. mCurrPosition = rInfo.point;
  1231. mCurrVelocity = Point3F(0, 0, 0);
  1232. did_impact = true;
  1233. setMaskBits(ImpactMask);
  1234. if (choreographer)
  1235. {
  1236. choreographer->impactNotify(rInfo.point, rInfo.normal, rInfo.object);
  1237. Sim::postEvent(this, new ObjectDeleteEvent, Sim::getCurrentTime() + 500);
  1238. }
  1239. }
  1240. }
  1241. else // if (isClientObject())
  1242. {
  1243. emitParticles(mCurrPosition, new_pos, mCurrVelocity, TickMs);
  1244. updateSound();
  1245. }
  1246. // interp values used in interpolateTick()
  1247. mCurrDeltaBase = new_pos;
  1248. mCurrBackDelta = mCurrPosition - new_pos;
  1249. mCurrPosition = new_pos;
  1250. MatrixF xform(true);
  1251. xform.setColumn(3, mCurrPosition);
  1252. setTransform(xform);
  1253. }
  1254. void afxMagicMissile::interpolateTick(F32 delta)
  1255. {
  1256. Parent::interpolateTick(delta);
  1257. // only active from launch to impact
  1258. if (!is_active())
  1259. return;
  1260. Point3F interpPos = mCurrDeltaBase + mCurrBackDelta * delta;
  1261. Point3F dir = mCurrVelocity;
  1262. if(dir.isZero())
  1263. dir.set(0,0,1);
  1264. else
  1265. dir.normalize();
  1266. MatrixF xform(true);
  1267. xform = MathUtils::createOrientFromDir(dir);
  1268. xform.setPosition(interpPos);
  1269. setRenderTransform(xform);
  1270. updateSound();
  1271. }
  1272. //--------------------------------------------------------------------------
  1273. U32 afxMagicMissile::packUpdate(NetConnection* con, U32 mask, BitStream* stream)
  1274. {
  1275. U32 retMask = Parent::packUpdate( con, mask, stream );
  1276. const bool isInitalUpdate = mask & GameBase::InitialUpdateMask;
  1277. // InitialUpdateMask
  1278. if ( stream->writeFlag( isInitalUpdate ) )
  1279. {
  1280. Point3F pos;
  1281. getTransform().getColumn( 3, &pos );
  1282. stream->writeCompressedPoint( pos );
  1283. F32 len = mCurrVelocity.len();
  1284. if ( stream->writeFlag( len > 0.02 ) )
  1285. {
  1286. Point3F outVel = mCurrVelocity;
  1287. outVel *= 1 / len;
  1288. stream->writeNormalVector( outVel, 10 );
  1289. len *= 32.0; // 5 bits for fraction
  1290. if ( len > 8191 )
  1291. len = 8191;
  1292. stream->writeInt( (S32)len, 13 );
  1293. }
  1294. stream->writeRangedU32( mCurrTick, 0, afxMagicMissileData::MaxLifetimeTicks );
  1295. if (choreographer)
  1296. {
  1297. S32 ghostIndex = con->getGhostIndex( choreographer );
  1298. if ( stream->writeFlag( ghostIndex != -1 ) )
  1299. {
  1300. stream->writeRangedU32( U32(ghostIndex),
  1301. 0,
  1302. NetConnection::MaxGhostCount );
  1303. }
  1304. else
  1305. // have not recieved the ghost for the source object yet, try again later
  1306. retMask |= GameBase::InitialUpdateMask;
  1307. }
  1308. else
  1309. stream->writeFlag( false );
  1310. }
  1311. // impact update
  1312. if (stream->writeFlag(mask & ImpactMask))
  1313. {
  1314. mathWrite(*stream, mCurrPosition);
  1315. mathWrite(*stream, mCurrVelocity);
  1316. stream->writeFlag(did_impact);
  1317. }
  1318. // guided update
  1319. if (stream->writeFlag(mask & GuideMask))
  1320. {
  1321. mathWrite(*stream, mCurrPosition);
  1322. mathWrite(*stream, mCurrVelocity);
  1323. }
  1324. return retMask;
  1325. }
  1326. void afxMagicMissile::unpackUpdate(NetConnection* con, BitStream* stream)
  1327. {
  1328. Parent::unpackUpdate(con, stream);
  1329. if ( stream->readFlag() ) // InitialUpdateMask
  1330. {
  1331. Point3F pos;
  1332. stream->readCompressedPoint( &pos );
  1333. if ( stream->readFlag() )
  1334. {
  1335. stream->readNormalVector( &mCurrVelocity, 10 );
  1336. mCurrVelocity *= stream->readInt( 13 ) / 32.0f;
  1337. }
  1338. else
  1339. mCurrVelocity.zero();
  1340. mCurrDeltaBase = pos;
  1341. mCurrBackDelta = mCurrPosition - pos;
  1342. mCurrPosition = pos;
  1343. setPosition( mCurrPosition );
  1344. mCurrTick = stream->readRangedU32(0, afxMagicMissileData::MaxLifetimeTicks);
  1345. if ( stream->readFlag() )
  1346. {
  1347. U32 id = stream->readRangedU32(0, NetConnection::MaxGhostCount);
  1348. choreographer = dynamic_cast<afxChoreographer*>(con->resolveGhost(id));
  1349. if (choreographer)
  1350. {
  1351. deleteNotify(choreographer);
  1352. }
  1353. }
  1354. else
  1355. {
  1356. if (choreographer)
  1357. clearNotify(choreographer);
  1358. choreographer = 0;
  1359. }
  1360. }
  1361. // impact update
  1362. if (stream->readFlag())
  1363. {
  1364. mathRead(*stream, &mCurrPosition);
  1365. mathRead(*stream, &mCurrVelocity);
  1366. did_impact = stream->readFlag();
  1367. }
  1368. if (stream->readFlag()) // guided update
  1369. {
  1370. mathRead( *stream, &mCurrPosition );
  1371. mathRead( *stream, &mCurrVelocity );
  1372. }
  1373. }
  1374. //--------------------------------------------------------------------------
  1375. void afxMagicMissile::prepRenderImage(SceneRenderState* state)
  1376. {
  1377. if (!is_active())
  1378. return;
  1379. /*
  1380. if (isHidden() || mFadeValue <= (1.0/255.0))
  1381. return;
  1382. */
  1383. if ( mDataBlock->lightDesc )
  1384. {
  1385. mDataBlock->lightDesc->prepRender( state, &mLightState, getRenderTransform() );
  1386. }
  1387. /*
  1388. if ( mFlareData )
  1389. {
  1390. mFlareState.fullBrightness = mDataBlock->lightDesc->mBrightness;
  1391. mFlareState.scale = mFlareScale;
  1392. mFlareState.lightInfo = mLight;
  1393. mFlareState.lightMat = getTransform();
  1394. mFlareData->prepRender( state, &mFlareState );
  1395. }
  1396. */
  1397. prepBatchRender( state );
  1398. }
  1399. void afxMagicMissile::prepBatchRender(SceneRenderState* state)
  1400. {
  1401. if ( !mProjectileShape )
  1402. return;
  1403. GFXTransformSaver saver;
  1404. // Set up our TS render state.
  1405. TSRenderState rdata;
  1406. rdata.setSceneState( state );
  1407. // We might have some forward lit materials
  1408. // so pass down a query to gather lights.
  1409. LightQuery query;
  1410. query.init( getWorldSphere() );
  1411. rdata.setLightQuery( &query );
  1412. MatrixF mat = getRenderTransform();
  1413. mat.scale( mObjScale );
  1414. mat.scale( mDataBlock->scale );
  1415. GFX->setWorldMatrix( mat );
  1416. mProjectileShape->setDetailFromPosAndScale( state, mat.getPosition(), mObjScale );
  1417. mProjectileShape->animate();
  1418. mProjectileShape->render( rdata );
  1419. }
  1420. void afxMagicMissile::onDeleteNotify(SimObject* obj)
  1421. {
  1422. ShapeBase* shape_test = dynamic_cast<ShapeBase*>(obj);
  1423. if (shape_test == collide_exempt)
  1424. {
  1425. collide_exempt = NULL;
  1426. Parent::onDeleteNotify(obj);
  1427. return;
  1428. }
  1429. SceneObject* target_test = dynamic_cast<SceneObject*>(obj);
  1430. if (target_test == missile_target)
  1431. {
  1432. missile_target = NULL;
  1433. Parent::onDeleteNotify(obj);
  1434. return;
  1435. }
  1436. afxChoreographer* ch = dynamic_cast<afxChoreographer*>(obj);
  1437. if (ch == choreographer)
  1438. {
  1439. choreographer = NULL;
  1440. Parent::onDeleteNotify(obj);
  1441. return;
  1442. }
  1443. Parent::onDeleteNotify(obj);
  1444. }
  1445. //~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~~//
  1446. // private:
  1447. void afxMagicMissile::create_splash(const Point3F& pos)
  1448. {
  1449. if (!mDataBlock || !mDataBlock->splash)
  1450. return;
  1451. MatrixF xfm = getTransform();
  1452. xfm.setPosition(pos);
  1453. Splash* splash = new Splash();
  1454. splash->onNewDataBlock(mDataBlock->splash, false);
  1455. splash->setTransform(xfm);
  1456. splash->setInitialState(xfm.getPosition(), Point3F(0.0, 0.0, 1.0));
  1457. if (!splash->registerObject())
  1458. {
  1459. delete splash;
  1460. splash = NULL;
  1461. }
  1462. }
  1463. void afxMagicMissile::get_launch_constraint_data(Point3F& pos, Point3F& vel)
  1464. {
  1465. // need a choreographer
  1466. if (!choreographer)
  1467. {
  1468. Con::errorf("afxMagicMissile::get_launch_constraint_data(): missing choreographer.");
  1469. return;
  1470. }
  1471. // need a constraint manager
  1472. afxConstraintMgr* cons_mgr = choreographer->getConstraintMgr();
  1473. if (!cons_mgr)
  1474. {
  1475. Con::errorf("afxMagicMissile::get_launch_constraint_data(): missing constriant manager.");
  1476. return;
  1477. }
  1478. // need a valid constraint
  1479. afxConstraintID launch_cons_id;
  1480. if (isServerObject())
  1481. launch_cons_id = cons_mgr->getConstraintId(mDataBlock->launch_cons_s_def);
  1482. else
  1483. launch_cons_id = cons_mgr->getConstraintId(mDataBlock->launch_cons_c_def);
  1484. afxConstraint* launch_cons = cons_mgr->getConstraint(launch_cons_id);
  1485. if (!launch_cons)
  1486. {
  1487. Con::errorf("afxMagicMissile::get_launch_constraint_data(): constraint undefined.");
  1488. return;
  1489. }
  1490. MatrixF launch_xfm;
  1491. launch_cons->getTransform(launch_xfm);
  1492. Point3F launch_pos;
  1493. launch_cons->getPosition(launch_pos);
  1494. pos = launch_pos;
  1495. // echo the actual launch position to the console
  1496. if (mDataBlock->echo_launch_offset)
  1497. {
  1498. SceneObject* default_launcher = get_default_launcher();
  1499. if (default_launcher)
  1500. {
  1501. MatrixF launcher_xfm_inv = default_launcher->getWorldTransform();
  1502. VectorF offset = pos - default_launcher->getRenderPosition();
  1503. launcher_xfm_inv.mulV(offset);
  1504. if (isServerObject())
  1505. Con::printf("launchOffsetServer = \"%g %g %g\";", offset.x, offset.y, offset.z);
  1506. else
  1507. Con::printf("launchOffsetClient = \"%g %g %g\";", offset.x, offset.y, offset.z);
  1508. }
  1509. }
  1510. // setup aiming matrix to straight forward and level
  1511. MatrixF aim_mtx;
  1512. AngAxisF aim_aa(Point3F(0,1,0),0);
  1513. aim_aa.setMatrix(&aim_mtx);
  1514. // calculate final aiming vector
  1515. MatrixF aim2_mtx;
  1516. aim2_mtx.mul(launch_xfm, aim_mtx);
  1517. VectorF aim_vec;
  1518. aim2_mtx.getColumn(1,&aim_vec);
  1519. aim_vec.normalizeSafe();
  1520. // give velocity vector a magnitude
  1521. vel = aim_vec*mDataBlock->muzzleVelocity;
  1522. }
  1523. // resolve the launch constraint object. normally it's the caster, but for
  1524. // reverse_targeting the target object us used.
  1525. SceneObject* afxMagicMissile::get_default_launcher() const
  1526. {
  1527. SceneObject* launch_cons_obj = 0;
  1528. if (mDataBlock->reverse_targeting)
  1529. {
  1530. if (dynamic_cast<afxMagicSpell*>(choreographer))
  1531. launch_cons_obj = ((afxMagicSpell*)choreographer)->mTarget;
  1532. if (!launch_cons_obj)
  1533. {
  1534. Con::errorf("afxMagicMissile::get_launch_data(): missing target constraint object for reverse targeted missile.");
  1535. return 0;
  1536. }
  1537. }
  1538. else
  1539. {
  1540. if (dynamic_cast<afxMagicSpell*>(choreographer))
  1541. launch_cons_obj = ((afxMagicSpell*)choreographer)->mCaster;
  1542. if (!launch_cons_obj)
  1543. {
  1544. Con::errorf("afxMagicMissile::get_launch_data(): missing launch constraint object missile.");
  1545. return 0;
  1546. }
  1547. }
  1548. return launch_cons_obj;
  1549. }
  1550. void afxMagicMissile::get_launch_data(Point3F& pos, Point3F& vel)
  1551. {
  1552. bool use_constraint = (isServerObject()) ? mDataBlock->launch_cons_s_def.isDefined() : mDataBlock->launch_cons_c_def.isDefined();
  1553. if (use_constraint)
  1554. {
  1555. get_launch_constraint_data(pos, vel);
  1556. return;
  1557. }
  1558. // a choreographer pointer is required
  1559. if (!choreographer)
  1560. {
  1561. Con::errorf("afxMagicMissile::get_launch_data(): missing choreographer.");
  1562. return;
  1563. }
  1564. SceneObject* launch_cons_obj = get_default_launcher();
  1565. if (!launch_cons_obj)
  1566. return;
  1567. MatrixF launch_xfm = launch_cons_obj->getRenderTransform();
  1568. // calculate launch position
  1569. Point3F offset_override = (isClientObject()) ? mDataBlock->launch_offset_client :
  1570. mDataBlock->launch_offset_server;
  1571. // override
  1572. if (!offset_override.isZero())
  1573. {
  1574. launch_xfm.mulV(offset_override);
  1575. pos = launch_cons_obj->getRenderPosition() + offset_override;
  1576. }
  1577. // no override
  1578. else
  1579. {
  1580. // get transformed launch offset
  1581. VectorF launch_offset = mDataBlock->launch_offset;
  1582. launch_xfm.mulV(launch_offset);
  1583. StringTableEntry launch_node = mDataBlock->launch_node;
  1584. // calculate position of missile at launch
  1585. if (launch_node != ST_NULLSTRING)
  1586. {
  1587. ShapeBase* launch_cons_shape = dynamic_cast<ShapeBase*>(launch_cons_obj);
  1588. TSShapeInstance* shape_inst = (launch_cons_shape) ? launch_cons_shape->getShapeInstance() : 0;
  1589. if (!shape_inst || !shape_inst->getShape())
  1590. launch_node = ST_NULLSTRING;
  1591. else
  1592. {
  1593. S32 node_ID = shape_inst->getShape()->findNode(launch_node);
  1594. MatrixF node_xfm = launch_cons_obj->getRenderTransform();
  1595. node_xfm.scale(launch_cons_obj->getScale());
  1596. if (node_ID >= 0)
  1597. node_xfm.mul(shape_inst->mNodeTransforms[node_ID]);
  1598. VectorF node_offset = mDataBlock->launch_node_offset;
  1599. node_xfm.mulV(node_offset);
  1600. pos = node_xfm.getPosition() + launch_offset + node_offset;
  1601. }
  1602. }
  1603. // calculate launch position without launch node
  1604. else
  1605. pos = launch_cons_obj->getRenderPosition() + launch_offset;
  1606. }
  1607. // echo the actual launch position to the console
  1608. if (mDataBlock->echo_launch_offset)
  1609. {
  1610. VectorF offset = pos - launch_cons_obj->getRenderPosition();
  1611. MatrixF caster_xfm_inv = launch_xfm;
  1612. caster_xfm_inv.affineInverse();
  1613. caster_xfm_inv.mulV(offset);
  1614. if (isServerObject())
  1615. Con::printf("launchOffsetServer = \"%g %g %g\";", offset.x, offset.y, offset.z);
  1616. else
  1617. Con::printf("launchOffsetClient = \"%g %g %g\";", offset.x, offset.y, offset.z);
  1618. }
  1619. // calculate launch velocity vector
  1620. if (starting_vel_vec.isZero())
  1621. {
  1622. // setup aiming matrix to straight forward and level
  1623. MatrixF aim_mtx;
  1624. AngAxisF aim_aa(Point3F(0,1,0),0);
  1625. aim_aa.setMatrix(&aim_mtx);
  1626. // setup pitch matrix
  1627. MatrixF pitch_mtx;
  1628. AngAxisF pitch_aa(Point3F(1,0,0),mDegToRad(mDataBlock->launch_pitch));
  1629. pitch_aa.setMatrix(&pitch_mtx);
  1630. // setup pan matrix
  1631. MatrixF pan_mtx;
  1632. AngAxisF pan_aa(Point3F(0,0,1),mDegToRad(mDataBlock->launch_pan));
  1633. pan_aa.setMatrix(&pan_mtx);
  1634. // calculate adjusted aiming matrix
  1635. aim_mtx.mul(pitch_mtx);
  1636. aim_mtx.mul(pan_mtx);
  1637. // calculate final aiming vector
  1638. MatrixF aim2_mtx;
  1639. aim2_mtx.mul(launch_xfm, aim_mtx);
  1640. VectorF aim_vec;
  1641. aim2_mtx.getColumn(1,&aim_vec);
  1642. aim_vec.normalizeSafe();
  1643. // give velocity vector a magnitude
  1644. vel = aim_vec*mDataBlock->muzzleVelocity;
  1645. }
  1646. else
  1647. {
  1648. vel = starting_vel_vec*starting_velocity;
  1649. }
  1650. }
  1651. void afxMagicMissile::updateSound()
  1652. {
  1653. if (!mDataBlock->isProjectileSoundValid())
  1654. return;
  1655. if ( mSound )
  1656. {
  1657. if ( !mSound->isPlaying() )
  1658. mSound->play();
  1659. mSound->setVelocity( getVelocity() );
  1660. mSound->setTransform( getRenderTransform() );
  1661. }
  1662. }
  1663. //~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~~//
  1664. // public:
  1665. void afxMagicMissile::launch()
  1666. {
  1667. get_launch_data(mCurrPosition, mCurrVelocity);
  1668. mCurrDeltaBase = mCurrPosition;
  1669. mCurrBackDelta.zero();
  1670. did_launch = true;
  1671. setPosition(mCurrPosition);
  1672. afxMagicSpell* spell = dynamic_cast<afxMagicSpell*>(choreographer);
  1673. if (spell)
  1674. {
  1675. if (mDataBlock->reverse_targeting)
  1676. {
  1677. missile_target = spell->mCaster;
  1678. collide_exempt = spell->mTarget;
  1679. }
  1680. else
  1681. {
  1682. missile_target = spell->mTarget;
  1683. collide_exempt = spell->mCaster;
  1684. }
  1685. if (spell->mCaster)
  1686. processAfter(spell->mCaster);
  1687. if (missile_target)
  1688. deleteNotify(missile_target);
  1689. if (collide_exempt)
  1690. deleteNotify(collide_exempt);
  1691. }
  1692. else
  1693. {
  1694. missile_target = 0;
  1695. collide_exempt = 0;
  1696. }
  1697. }
  1698. void afxMagicMissile::setChoreographer(afxChoreographer* chor)
  1699. {
  1700. if (choreographer)
  1701. clearNotify(choreographer);
  1702. choreographer = chor;
  1703. if (choreographer)
  1704. deleteNotify(choreographer);
  1705. }
  1706. void afxMagicMissile::setStartingVelocityVector(const Point3F& vel_vec)
  1707. {
  1708. starting_vel_vec = vel_vec;
  1709. }
  1710. void afxMagicMissile::setStartingVelocity(const F32 vel)
  1711. {
  1712. starting_velocity = vel;
  1713. }
  1714. void afxMagicMissile::getStartingVelocityValues(F32& vel, Point3F& vel_vec)
  1715. {
  1716. vel = starting_velocity;
  1717. vel_vec = starting_vel_vec;
  1718. }
  1719. //~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~~//
  1720. /* From stock Projectile code...
  1721. DefineEngineMethod(Projectile, presimulate, void, (F32 seconds), (1.0f), "Updates velocity and position, and performs collision testing.\n"
  1722. "@param seconds Amount of time, in seconds, since the simulation began, to start the simulation at.\n"
  1723. "@tsexample\n"
  1724. "// Tell the projectile object to process a simulation event, and provide the amount of time\n"
  1725. " in seconds that has passed since the simulation began.\n"
  1726. "%seconds = 2000;\n"
  1727. "%projectile.presimulate(%seconds);\n"
  1728. "@endtsexample\n")
  1729. {
  1730. object->simulate( seconds );
  1731. }
  1732. */
  1733. DefineEngineMethod(afxMagicMissile, setStartingVelocityVector, void, (Point3F velocityVec),,
  1734. "Set the starting velocity-vector for a magic-missile.\n\n"
  1735. "@ingroup AFX")
  1736. {
  1737. object->setStartingVelocityVector(velocityVec);
  1738. }
  1739. DefineEngineMethod(afxMagicMissile, setStartingVelocity, void, (float velocity),,
  1740. "Set the starting velocity for a magic-missile.\n\n"
  1741. "@ingroup AFX")
  1742. {
  1743. object->setStartingVelocity(velocity);
  1744. }
  1745. //~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~~//