afxMagicMissile.cpp 65 KB

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