afxMagicMissile.cpp 64 KB

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