afxMagicMissile.cpp 65 KB

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