afxMagicMissile.cpp 64 KB

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