Weapon.cpp 128 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531
  1. /*
  2. ** Command & Conquer Generals Zero Hour(tm)
  3. ** Copyright 2025 Electronic Arts Inc.
  4. **
  5. ** This program is free software: you can redistribute it and/or modify
  6. ** it under the terms of the GNU General Public License as published by
  7. ** the Free Software Foundation, either version 3 of the License, or
  8. ** (at your option) any later version.
  9. **
  10. ** This program is distributed in the hope that it will be useful,
  11. ** but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. ** GNU General Public License for more details.
  14. **
  15. ** You should have received a copy of the GNU General Public License
  16. ** along with this program. If not, see <http://www.gnu.org/licenses/>.
  17. */
  18. ////////////////////////////////////////////////////////////////////////////////
  19. // //
  20. // (c) 2001-2003 Electronic Arts Inc. //
  21. // //
  22. ////////////////////////////////////////////////////////////////////////////////
  23. // FILE: Weapon.cpp ///////////////////////////////////////////////////////////////////////////////
  24. // Author: Colin Day, November 2001
  25. // Desc: Weapon descriptions
  26. ///////////////////////////////////////////////////////////////////////////////////////////////////
  27. // INCLUDES ///////////////////////////////////////////////////////////////////////////////////////
  28. #include "PreRTS.h" // This must go first in EVERY cpp file int the GameEngine
  29. #define DEFINE_DEATH_NAMES
  30. #define DEFINE_WEAPONBONUSCONDITION_NAMES
  31. #define DEFINE_WEAPONBONUSFIELD_NAMES
  32. #define DEFINE_WEAPONCOLLIDEMASK_NAMES
  33. #define DEFINE_WEAPONAFFECTSMASK_NAMES
  34. #define DEFINE_WEAPONRELOAD_NAMES
  35. #define DEFINE_WEAPONPREFIRE_NAMES
  36. #include "Common/CRC.h"
  37. #include "Common/CRCDebug.h"
  38. #include "Common/GameAudio.h"
  39. #include "Common/GameState.h"
  40. #include "Common/INI.h"
  41. #include "Common/PerfTimer.h"
  42. #include "Common/Player.h"
  43. #include "Common/ThingFactory.h"
  44. #include "Common/ThingTemplate.h"
  45. #include "Common/Xfer.h"
  46. #include "GameClient/Drawable.h"
  47. #include "GameClient/FXList.h"
  48. #include "GameClient/InGameUI.h"
  49. #include "GameClient/ParticleSys.h"
  50. #include "GameLogic/Damage.h"
  51. #include "GameLogic/ExperienceTracker.h"
  52. #include "GameLogic/GameLogic.h"
  53. #include "GameLogic/AIPathfind.h"
  54. #include "GameLogic/Module/BehaviorModule.h"
  55. #include "GameLogic/Module/BodyModule.h"
  56. #include "GameLogic/Module/ContainModule.h"
  57. #include "GameLogic/Module/LaserUpdate.h"
  58. #include "GameLogic/Module/UpdateModule.h"
  59. #include "GameLogic/Module/SpecialPowerCompletionDie.h"
  60. #include "GameLogic/Module/AssaultTransportAIUpdate.h"
  61. #include "GameLogic/Object.h"
  62. #include "GameLogic/ObjectCreationList.h"
  63. #include "GameLogic/PartitionManager.h"
  64. #include "GameLogic/Weapon.h"
  65. #include "GameLogic/Module/AIUpdate.h"
  66. #include "GameLogic/Module/AssistedTargetingUpdate.h"
  67. #include "GameLogic/Module/ProjectileStreamUpdate.h"
  68. #include "GameLogic/Module/PhysicsUpdate.h"
  69. #include "GameLogic/TerrainLogic.h"
  70. #define RATIONALIZE_ATTACK_RANGE
  71. #define ATTACK_RANGE_IS_2D
  72. #ifdef ATTACK_RANGE_IS_2D
  73. const DistanceCalculationType ATTACK_RANGE_CALC_TYPE = FROM_BOUNDINGSPHERE_2D;
  74. #else
  75. const DistanceCalculationType ATTACK_RANGE_CALC_TYPE = FROM_BOUNDINGSPHERE_3D;
  76. #endif
  77. #ifdef _INTERNAL
  78. // for occasional debugging...
  79. //#pragma optimize("", off)
  80. //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes")
  81. #endif
  82. // damage is ALWAYS 3d
  83. const DistanceCalculationType DAMAGE_RANGE_CALC_TYPE = FROM_BOUNDINGSPHERE_3D;
  84. //-------------------------------------------------------------------------------------------------
  85. static void parsePerVetLevelAsciiString( INI* ini, void* /*instance*/, void * store, const void* /*userData*/ )
  86. {
  87. AsciiString* s = (AsciiString*)store;
  88. VeterancyLevel v = (VeterancyLevel)INI::scanIndexList(ini->getNextToken(), TheVeterancyNames);
  89. s[v] = ini->getNextAsciiString();
  90. }
  91. //-------------------------------------------------------------------------------------------------
  92. static void parseAllVetLevelsAsciiString( INI* ini, void* /*instance*/, void * store, const void* /*userData*/ )
  93. {
  94. AsciiString* s = (AsciiString*)store;
  95. AsciiString a = ini->getNextAsciiString();
  96. for (Int i = LEVEL_FIRST; i <= LEVEL_LAST; ++i)
  97. s[i] = a;
  98. }
  99. //-------------------------------------------------------------------------------------------------
  100. static void parsePerVetLevelFXList( INI* ini, void* /*instance*/, void * store, const void* /*userData*/ )
  101. {
  102. typedef const FXList* ConstFXListPtr;
  103. ConstFXListPtr* s = (ConstFXListPtr*)store;
  104. VeterancyLevel v = (VeterancyLevel)INI::scanIndexList(ini->getNextToken(), TheVeterancyNames);
  105. const FXList* fx = NULL;
  106. INI::parseFXList(ini, NULL, &fx, NULL);
  107. s[v] = fx;
  108. }
  109. //-------------------------------------------------------------------------------------------------
  110. static void parseAllVetLevelsFXList( INI* ini, void* /*instance*/, void * store, const void* /*userData*/ )
  111. {
  112. typedef const FXList* ConstFXListPtr;
  113. ConstFXListPtr* s = (ConstFXListPtr*)store;
  114. const FXList* fx = NULL;
  115. INI::parseFXList(ini, NULL, &fx, NULL);
  116. for (Int i = LEVEL_FIRST; i <= LEVEL_LAST; ++i)
  117. s[i] = fx;
  118. }
  119. //-------------------------------------------------------------------------------------------------
  120. static void parsePerVetLevelPSys( INI* ini, void* /*instance*/, void * store, const void* /*userData*/ )
  121. {
  122. typedef const ParticleSystemTemplate* ConstParticleSystemTemplatePtr;
  123. ConstParticleSystemTemplatePtr* s = (ConstParticleSystemTemplatePtr*)store;
  124. VeterancyLevel v = (VeterancyLevel)INI::scanIndexList(ini->getNextToken(), TheVeterancyNames);
  125. ConstParticleSystemTemplatePtr pst = NULL;
  126. INI::parseParticleSystemTemplate(ini, NULL, &pst, NULL);
  127. s[v] = pst;
  128. }
  129. //-------------------------------------------------------------------------------------------------
  130. static void parseAllVetLevelsPSys( INI* ini, void* /*instance*/, void * store, const void* /*userData*/ )
  131. {
  132. typedef const ParticleSystemTemplate* ConstParticleSystemTemplatePtr;
  133. ConstParticleSystemTemplatePtr* s = (ConstParticleSystemTemplatePtr*)store;
  134. ConstParticleSystemTemplatePtr pst = NULL;
  135. INI::parseParticleSystemTemplate(ini, NULL, &pst, NULL);
  136. for (Int i = LEVEL_FIRST; i <= LEVEL_LAST; ++i)
  137. s[i] = pst;
  138. }
  139. ///////////////////////////////////////////////////////////////////////////////////////////////////
  140. // PUBLIC DATA ////////////////////////////////////////////////////////////////////////////////////
  141. ///////////////////////////////////////////////////////////////////////////////////////////////////
  142. WeaponStore *TheWeaponStore = NULL; ///< the weapon store definition
  143. ///////////////////////////////////////////////////////////////////////////////////////////////////
  144. // PRIVATE DATA ///////////////////////////////////////////////////////////////////////////////////
  145. ///////////////////////////////////////////////////////////////////////////////////////////////////
  146. const FieldParse WeaponTemplate::TheWeaponTemplateFieldParseTable[] =
  147. {
  148. { "PrimaryDamage", INI::parseReal, NULL, offsetof(WeaponTemplate, m_primaryDamage) },
  149. { "PrimaryDamageRadius", INI::parseReal, NULL, offsetof(WeaponTemplate, m_primaryDamageRadius) },
  150. { "SecondaryDamage", INI::parseReal, NULL, offsetof(WeaponTemplate, m_secondaryDamage) },
  151. { "SecondaryDamageRadius", INI::parseReal, NULL, offsetof(WeaponTemplate, m_secondaryDamageRadius) },
  152. { "ShockWaveAmount", INI::parseReal, NULL, offsetof(WeaponTemplate, m_shockWaveAmount) },
  153. { "ShockWaveRadius", INI::parseReal, NULL, offsetof(WeaponTemplate, m_shockWaveRadius) },
  154. { "ShockWaveTaperOff", INI::parseReal, NULL, offsetof(WeaponTemplate, m_shockWaveTaperOff) },
  155. { "AttackRange", INI::parseReal, NULL, offsetof(WeaponTemplate, m_attackRange) },
  156. { "MinimumAttackRange", INI::parseReal, NULL, offsetof(WeaponTemplate, m_minimumAttackRange) },
  157. { "RequestAssistRange", INI::parseReal, NULL, offsetof(WeaponTemplate, m_requestAssistRange) },
  158. { "AcceptableAimDelta", INI::parseAngleReal, NULL, offsetof(WeaponTemplate, m_aimDelta) },
  159. { "ScatterRadius", INI::parseReal, NULL, offsetof(WeaponTemplate, m_scatterRadius) },
  160. { "ScatterTargetScalar", INI::parseReal, NULL, offsetof(WeaponTemplate, m_scatterTargetScalar) },
  161. { "ScatterRadiusVsInfantry", INI::parseReal, NULL, offsetof( WeaponTemplate, m_infantryInaccuracyDist ) },
  162. { "DamageType", DamageTypeFlags::parseSingleBitFromINI, NULL, offsetof(WeaponTemplate, m_damageType) },
  163. { "DamageStatusType", ObjectStatusMaskType::parseSingleBitFromINI, NULL, offsetof(WeaponTemplate, m_damageStatusType) },
  164. { "DeathType", INI::parseIndexList, TheDeathNames, offsetof(WeaponTemplate, m_deathType) },
  165. { "WeaponSpeed", INI::parseVelocityReal, NULL, offsetof(WeaponTemplate, m_weaponSpeed) },
  166. { "MinWeaponSpeed", INI::parseVelocityReal, NULL, offsetof(WeaponTemplate, m_minWeaponSpeed) },
  167. { "ScaleWeaponSpeed", INI::parseBool, NULL, offsetof(WeaponTemplate, m_isScaleWeaponSpeed) },
  168. { "WeaponRecoil", INI::parseAngleReal, NULL, offsetof(WeaponTemplate, m_weaponRecoil) },
  169. { "MinTargetPitch", INI::parseAngleReal, NULL, offsetof(WeaponTemplate, m_minTargetPitch) },
  170. { "MaxTargetPitch", INI::parseAngleReal, NULL, offsetof(WeaponTemplate, m_maxTargetPitch) },
  171. { "RadiusDamageAngle", INI::parseAngleReal, NULL, offsetof(WeaponTemplate, m_radiusDamageAngle) },
  172. { "ProjectileObject", INI::parseAsciiString, NULL, offsetof(WeaponTemplate, m_projectileName) },
  173. { "FireSound", INI::parseAudioEventRTS, NULL, offsetof(WeaponTemplate, m_fireSound) },
  174. { "FireSoundLoopTime", INI::parseDurationUnsignedInt, NULL, offsetof(WeaponTemplate, m_fireSoundLoopTime) },
  175. { "FireFX", parseAllVetLevelsFXList, NULL, offsetof(WeaponTemplate, m_fireFXs) },
  176. { "ProjectileDetonationFX", parseAllVetLevelsFXList, NULL, offsetof(WeaponTemplate, m_projectileDetonateFXs) },
  177. { "FireOCL", parseAllVetLevelsAsciiString, NULL, offsetof(WeaponTemplate, m_fireOCLNames) },
  178. { "ProjectileDetonationOCL", parseAllVetLevelsAsciiString, NULL, offsetof(WeaponTemplate, m_projectileDetonationOCLNames) },
  179. { "ProjectileExhaust", parseAllVetLevelsPSys, NULL, offsetof(WeaponTemplate, m_projectileExhausts) },
  180. { "VeterancyFireFX", parsePerVetLevelFXList, NULL, offsetof(WeaponTemplate, m_fireFXs) },
  181. { "VeterancyProjectileDetonationFX", parsePerVetLevelFXList, NULL, offsetof(WeaponTemplate, m_projectileDetonateFXs) },
  182. { "VeterancyFireOCL", parsePerVetLevelAsciiString, NULL, offsetof(WeaponTemplate, m_fireOCLNames) },
  183. { "VeterancyProjectileDetonationOCL", parsePerVetLevelAsciiString, NULL, offsetof(WeaponTemplate, m_projectileDetonationOCLNames) },
  184. { "VeterancyProjectileExhaust", parsePerVetLevelPSys, NULL, offsetof(WeaponTemplate, m_projectileExhausts) },
  185. { "ClipSize", INI::parseInt, NULL, offsetof(WeaponTemplate, m_clipSize) },
  186. { "ContinuousFireOne", INI::parseInt, NULL, offsetof(WeaponTemplate, m_continuousFireOneShotsNeeded) },
  187. { "ContinuousFireTwo", INI::parseInt, NULL, offsetof(WeaponTemplate, m_continuousFireTwoShotsNeeded) },
  188. { "ContinuousFireCoast", INI::parseDurationUnsignedInt, NULL, offsetof(WeaponTemplate, m_continuousFireCoastFrames) },
  189. { "AutoReloadWhenIdle", INI::parseDurationUnsignedInt, NULL, offsetof(WeaponTemplate, m_autoReloadWhenIdleFrames) },
  190. { "ClipReloadTime", INI::parseDurationUnsignedInt, NULL, offsetof(WeaponTemplate, m_clipReloadTime) },
  191. { "DelayBetweenShots", WeaponTemplate::parseShotDelay, NULL, 0 },
  192. { "ShotsPerBarrel", INI::parseInt, NULL, offsetof(WeaponTemplate, m_shotsPerBarrel) },
  193. { "DamageDealtAtSelfPosition",INI::parseBool, NULL, offsetof(WeaponTemplate, m_damageDealtAtSelfPosition) },
  194. { "RadiusDamageAffects", INI::parseBitString32, TheWeaponAffectsMaskNames, offsetof(WeaponTemplate, m_affectsMask) },
  195. { "ProjectileCollidesWith", INI::parseBitString32, TheWeaponCollideMaskNames, offsetof(WeaponTemplate, m_collideMask) },
  196. { "AntiAirborneVehicle", INI::parseBitInInt32, (void*)WEAPON_ANTI_AIRBORNE_VEHICLE, offsetof(WeaponTemplate, m_antiMask) },
  197. { "AntiGround", INI::parseBitInInt32, (void*)WEAPON_ANTI_GROUND, offsetof(WeaponTemplate, m_antiMask) },
  198. { "AntiProjectile", INI::parseBitInInt32, (void*)WEAPON_ANTI_PROJECTILE, offsetof(WeaponTemplate, m_antiMask) },
  199. { "AntiSmallMissile", INI::parseBitInInt32, (void*)WEAPON_ANTI_SMALL_MISSILE, offsetof(WeaponTemplate, m_antiMask) },
  200. { "AntiMine", INI::parseBitInInt32, (void*)WEAPON_ANTI_MINE, offsetof(WeaponTemplate, m_antiMask) },
  201. { "AntiParachute", INI::parseBitInInt32, (void*)WEAPON_ANTI_PARACHUTE, offsetof(WeaponTemplate, m_antiMask) },
  202. { "AntiAirborneInfantry", INI::parseBitInInt32, (void*)WEAPON_ANTI_AIRBORNE_INFANTRY, offsetof(WeaponTemplate, m_antiMask) },
  203. { "AntiBallisticMissile", INI::parseBitInInt32, (void*)WEAPON_ANTI_BALLISTIC_MISSILE, offsetof(WeaponTemplate, m_antiMask) },
  204. { "AutoReloadsClip", INI::parseIndexList, TheWeaponReloadNames, offsetof(WeaponTemplate, m_reloadType) },
  205. { "ProjectileStreamName", INI::parseAsciiString, NULL, offsetof(WeaponTemplate, m_projectileStreamName) },
  206. { "LaserName", INI::parseAsciiString, NULL, offsetof(WeaponTemplate, m_laserName) },
  207. { "LaserBoneName", INI::parseAsciiString, NULL, offsetof(WeaponTemplate, m_laserBoneName) },
  208. { "WeaponBonus", WeaponTemplate::parseWeaponBonusSet, NULL, 0 },
  209. { "HistoricBonusTime", INI::parseDurationUnsignedInt, NULL, offsetof(WeaponTemplate, m_historicBonusTime) },
  210. { "HistoricBonusRadius", INI::parseReal, NULL, offsetof(WeaponTemplate, m_historicBonusRadius) },
  211. { "HistoricBonusCount", INI::parseInt, NULL, offsetof(WeaponTemplate, m_historicBonusCount) },
  212. { "HistoricBonusWeapon", INI::parseWeaponTemplate, NULL, offsetof(WeaponTemplate, m_historicBonusWeapon) },
  213. { "LeechRangeWeapon", INI::parseBool, NULL, offsetof(WeaponTemplate, m_leechRangeWeapon) },
  214. { "ScatterTarget", WeaponTemplate::parseScatterTarget, NULL, 0 },
  215. { "CapableOfFollowingWaypoints", INI::parseBool, NULL, offsetof(WeaponTemplate, m_capableOfFollowingWaypoint) },
  216. { "ShowsAmmoPips", INI::parseBool, NULL, offsetof(WeaponTemplate, m_isShowsAmmoPips) },
  217. { "AllowAttackGarrisonedBldgs", INI::parseBool, NULL, offsetof(WeaponTemplate, m_allowAttackGarrisonedBldgs) },
  218. { "PlayFXWhenStealthed", INI::parseBool, NULL, offsetof(WeaponTemplate, m_playFXWhenStealthed) },
  219. { "PreAttackDelay", INI::parseDurationUnsignedInt, NULL, offsetof( WeaponTemplate, m_preAttackDelay ) },
  220. { "PreAttackType", INI::parseIndexList, TheWeaponPrefireNames, offsetof(WeaponTemplate, m_prefireType) },
  221. { "ContinueAttackRange", INI::parseReal, NULL, offsetof(WeaponTemplate, m_continueAttackRange) },
  222. { "SuspendFXDelay", INI::parseDurationUnsignedInt, NULL, offsetof(WeaponTemplate, m_suspendFXDelay) },
  223. { "MissileCallsOnDie", INI::parseBool, NULL, offsetof(WeaponTemplate, m_dieOnDetonate) },
  224. { NULL, NULL, NULL, 0 } // keep this last
  225. };
  226. ///////////////////////////////////////////////////////////////////////////////////////////////////
  227. // PUBLIC FUNCTIONS ///////////////////////////////////////////////////////////////////////////////
  228. ///////////////////////////////////////////////////////////////////////////////////////////////////
  229. //-------------------------------------------------------------------------------------------------
  230. WeaponTemplate::WeaponTemplate() : m_nextTemplate(NULL)
  231. {
  232. m_name = "NoNameWeapon";
  233. m_nameKey = NAMEKEY_INVALID;
  234. m_primaryDamage = 0.0f;
  235. m_primaryDamageRadius = 0.0f;
  236. m_secondaryDamage = 0.0f;
  237. m_secondaryDamageRadius = 0.0f;
  238. m_attackRange = 0.0f;
  239. m_minimumAttackRange = 0.0f;
  240. m_requestAssistRange = 0.0f;
  241. m_aimDelta = 0.0f;
  242. m_scatterRadius = 0.0f;
  243. m_scatterTargetScalar = 0.0f;
  244. m_shockWaveAmount = 0.0f;
  245. m_shockWaveRadius = 0.0f;
  246. m_shockWaveTaperOff = 0.0f;
  247. m_damageType = DAMAGE_EXPLOSION;
  248. m_deathType = DEATH_NORMAL;
  249. m_weaponSpeed = 999999.0f; // effectively instant
  250. m_minWeaponSpeed = 999999.0f; // effectively instant
  251. m_isScaleWeaponSpeed = FALSE;
  252. m_weaponRecoil = 0.0f; // no recoil
  253. m_minTargetPitch = -PI;
  254. m_maxTargetPitch = PI;
  255. m_radiusDamageAngle = PI; // PI each way, so full circle
  256. m_projectileName.clear(); // no projectile
  257. m_projectileTmpl = NULL;
  258. for (Int i = LEVEL_FIRST; i <= LEVEL_LAST; ++i)
  259. {
  260. m_fireOCLNames[i].clear();
  261. m_projectileDetonationOCLNames[i].clear();
  262. m_projectileExhausts[i] = NULL;
  263. m_fireOCLs[i] = NULL;
  264. m_projectileDetonationOCLs[i] = NULL;
  265. m_fireFXs[i] = NULL;
  266. m_projectileDetonateFXs[i] = NULL;
  267. }
  268. m_damageDealtAtSelfPosition = false;
  269. m_affectsMask = (WEAPON_AFFECTS_ALLIES | WEAPON_AFFECTS_ENEMIES | WEAPON_AFFECTS_NEUTRALS);
  270. // most projectile weapons don't want to collide with nontargeted enemies/allies or trees...
  271. m_collideMask = (WEAPON_COLLIDE_STRUCTURES);
  272. m_reloadType = AUTO_RELOAD;
  273. m_prefireType = PREFIRE_PER_SHOT;
  274. m_clipSize = 0;
  275. m_continuousFireOneShotsNeeded = INT_MAX;
  276. m_continuousFireTwoShotsNeeded = INT_MAX;
  277. m_continuousFireCoastFrames = 0;
  278. m_autoReloadWhenIdleFrames = 0;
  279. m_clipReloadTime = 0;
  280. m_minDelayBetweenShots = 0;
  281. m_maxDelayBetweenShots = 0;
  282. m_fireSoundLoopTime = 0;
  283. m_extraBonus = NULL;
  284. m_shotsPerBarrel = 1;
  285. m_antiMask = WEAPON_ANTI_GROUND; // but not air or projectile.
  286. m_projectileStreamName.clear();
  287. m_laserName.clear();
  288. m_laserBoneName.clear();
  289. m_historicBonusTime = 0;
  290. m_historicBonusCount = 0;
  291. m_historicBonusRadius = 0;
  292. m_historicBonusWeapon = NULL;
  293. m_leechRangeWeapon = FALSE;
  294. m_capableOfFollowingWaypoint = FALSE;
  295. m_isShowsAmmoPips = FALSE;
  296. m_allowAttackGarrisonedBldgs = FALSE;
  297. m_playFXWhenStealthed = FALSE;
  298. m_preAttackDelay = 0;
  299. m_continueAttackRange = 0.0f;
  300. m_infantryInaccuracyDist = 0.0f;
  301. m_damageStatusType = OBJECT_STATUS_NONE;
  302. m_suspendFXDelay = 0;
  303. m_dieOnDetonate = FALSE;
  304. }
  305. //-------------------------------------------------------------------------------------------------
  306. WeaponTemplate::~WeaponTemplate()
  307. {
  308. if (m_nextTemplate) {
  309. m_nextTemplate->deleteInstance();
  310. }
  311. // delete any extra-bonus that's present
  312. if (m_extraBonus)
  313. m_extraBonus->deleteInstance();
  314. }
  315. // ------------------------------------------------------------------------------------------------
  316. void WeaponTemplate::reset( void )
  317. {
  318. m_historicDamage.clear();
  319. } // end reset
  320. //-------------------------------------------------------------------------------------------------
  321. /*static*/ void WeaponTemplate::parseWeaponBonusSet( INI* ini, void *instance, void * /*store*/, const void* /*userData*/ )
  322. {
  323. WeaponTemplate* self = (WeaponTemplate*)instance;
  324. if (!self->m_extraBonus)
  325. self->m_extraBonus = newInstance(WeaponBonusSet);
  326. self->m_extraBonus->parseWeaponBonusSet(ini);
  327. }
  328. //-------------------------------------------------------------------------------------------------
  329. /*static*/ void WeaponTemplate::parseScatterTarget( INI* ini, void *instance, void * /*store*/, const void* /*userData*/ )
  330. {
  331. // Accept multiple listings of Coord2D's.
  332. WeaponTemplate* self = (WeaponTemplate*)instance;
  333. Coord2D target;
  334. target.x = 0;
  335. target.y = 0;
  336. INI::parseCoord2D( ini, NULL, &target, NULL );
  337. self->m_scatterTargets.push_back(target);
  338. }
  339. //-------------------------------------------------------------------------------------------------
  340. /*static*/ void WeaponTemplate::parseShotDelay( INI* ini, void *instance, void * /*store*/, const void* /*userData*/ )
  341. {
  342. // This smart parser allows both a single number for traditional delay, and a labeled pair of numbers for a delay range
  343. WeaponTemplate* self = (WeaponTemplate*)instance;
  344. static const char *MIN_LABEL = "Min";
  345. static const char *MAX_LABEL = "Max";
  346. const char* token = ini->getNextTokenOrNull(ini->getSepsColon());
  347. if( stricmp(token, MIN_LABEL) == 0 )
  348. {
  349. // Two entry min/max
  350. self->m_minDelayBetweenShots = INI::scanInt(ini->getNextToken(ini->getSepsColon()));
  351. token = ini->getNextTokenOrNull(ini->getSepsColon());
  352. if( stricmp(token, MAX_LABEL) != 0 )
  353. {
  354. // Messed up double entry
  355. self->m_maxDelayBetweenShots = self->m_minDelayBetweenShots;
  356. }
  357. else
  358. self->m_maxDelayBetweenShots = INI::scanInt(ini->getNextToken(ini->getSepsColon()));
  359. }
  360. else
  361. {
  362. // single entry, as in no label so the first token is just a number
  363. self->m_minDelayBetweenShots = INI::scanInt(token);
  364. self->m_maxDelayBetweenShots = self->m_minDelayBetweenShots;
  365. }
  366. // No matter what we have now, we want to convert it to frames from msec.
  367. // ShotDelay used to use parseDurationUnsignedInt, and we are expanding on that.
  368. self->m_minDelayBetweenShots = ceilf(ConvertDurationFromMsecsToFrames((Real)self->m_minDelayBetweenShots));
  369. self->m_maxDelayBetweenShots = ceilf(ConvertDurationFromMsecsToFrames((Real)self->m_maxDelayBetweenShots));
  370. }
  371. //-------------------------------------------------------------------------------------------------
  372. void WeaponTemplate::postProcessLoad()
  373. {
  374. if (!TheThingFactory)
  375. {
  376. DEBUG_CRASH(("you must call this after TheThingFactory is inited"));
  377. return;
  378. }
  379. if (m_projectileName.isEmpty())
  380. {
  381. m_projectileTmpl = NULL;
  382. }
  383. else
  384. {
  385. m_projectileTmpl = TheThingFactory->findTemplate(m_projectileName);
  386. DEBUG_ASSERTCRASH(m_projectileTmpl, ("projectile %s not found!",m_projectileName.str()));
  387. }
  388. for (Int i = LEVEL_FIRST; i <= LEVEL_LAST; ++i)
  389. {
  390. // And the OCL if there is one
  391. if (m_fireOCLNames[i].isEmpty())
  392. {
  393. m_fireOCLs[i] = NULL;
  394. }
  395. else
  396. {
  397. m_fireOCLs[i] = TheObjectCreationListStore->findObjectCreationList(m_fireOCLNames[i].str() );
  398. DEBUG_ASSERTCRASH(m_fireOCLs[i], ("OCL %s not found in a weapon!",m_fireOCLNames[i].str()));
  399. }
  400. m_fireOCLNames[i].clear();
  401. // And the other OCL if there is one
  402. if (m_projectileDetonationOCLNames[i].isEmpty() )
  403. {
  404. m_projectileDetonationOCLs[i] = NULL;
  405. }
  406. else
  407. {
  408. m_projectileDetonationOCLs[i] = TheObjectCreationListStore->findObjectCreationList(m_projectileDetonationOCLNames[i].str() );
  409. DEBUG_ASSERTCRASH(m_projectileDetonationOCLs[i], ("OCL %s not found in a weapon!",m_projectileDetonationOCLNames[i].str()));
  410. }
  411. m_projectileDetonationOCLNames[i].clear();
  412. }
  413. } // end postProcessLoad
  414. //-------------------------------------------------------------------------------------------------
  415. Real WeaponTemplate::getAttackRange(const WeaponBonus& bonus) const
  416. {
  417. #ifdef RATIONALIZE_ATTACK_RANGE
  418. // Note - undersize by 1/4 of a pathfind cell, so that the goal is not teetering on the edge
  419. // of firing range. jba.
  420. const Real UNDERSIZE = PATHFIND_CELL_SIZE_F*0.25f;
  421. Real r = m_attackRange * bonus.getField(WeaponBonus::RANGE) - UNDERSIZE;
  422. if (r < 0.0f) r = 0.0f;
  423. return r;
  424. #else
  425. // fudge this a little to account for pathfinding roundoff & such
  426. const Real ATTACK_RANGE_FUDGE = 1.05f;
  427. return m_attackRange * bonus.getField(WeaponBonus::RANGE) * ATTACK_RANGE_FUDGE;
  428. #endif
  429. }
  430. //-------------------------------------------------------------------------------------------------
  431. Real WeaponTemplate::getMinimumAttackRange() const
  432. {
  433. #ifdef RATIONALIZE_ATTACK_RANGE
  434. // Note - undersize by 1/4 of a pathfind cell, so that the goal is not teetering on the edge
  435. // of firing range. jba.
  436. const Real UNDERSIZE = PATHFIND_CELL_SIZE_F*0.25f;
  437. Real r = m_minimumAttackRange - UNDERSIZE;
  438. if (r < 0.0f) r = 0.0f;
  439. return r;
  440. #else
  441. return m_minimumAttackRange;
  442. #endif
  443. }
  444. //-------------------------------------------------------------------------------------------------
  445. Real WeaponTemplate::getUnmodifiedAttackRange() const
  446. {
  447. return m_attackRange;
  448. }
  449. //-------------------------------------------------------------------------------------------------
  450. Int WeaponTemplate::getDelayBetweenShots(const WeaponBonus& bonus) const
  451. {
  452. // yes, divide, not multiply; the larger the rate-of-fire bonus, the shorter
  453. // we want the delay time to be.
  454. Int delayToUse;
  455. if( m_minDelayBetweenShots == m_maxDelayBetweenShots )
  456. delayToUse = m_minDelayBetweenShots; // Random number thing doesn't like this case
  457. else
  458. delayToUse = GameLogicRandomValue( m_minDelayBetweenShots, m_maxDelayBetweenShots );
  459. Real bonusROF = bonus.getField(WeaponBonus::RATE_OF_FIRE);
  460. //CRCDEBUG_LOG(("WeaponTemplate::getDelayBetweenShots() - min:%d max:%d val:%d, bonusROF=%g/%8.8X\n",
  461. //m_minDelayBetweenShots, m_maxDelayBetweenShots, delayToUse, bonusROF, AS_INT(bonusROF)));
  462. return REAL_TO_INT_FLOOR(delayToUse / bonusROF);
  463. }
  464. //-------------------------------------------------------------------------------------------------
  465. Int WeaponTemplate::getClipReloadTime(const WeaponBonus& bonus) const
  466. {
  467. // yes, divide, not multiply; the larger the rate-of-fire bonus, the shorter
  468. // we want the reload time to be.
  469. return REAL_TO_INT_FLOOR(m_clipReloadTime / bonus.getField(WeaponBonus::RATE_OF_FIRE));
  470. }
  471. //-------------------------------------------------------------------------------------------------
  472. Int WeaponTemplate::getPreAttackDelay( const WeaponBonus& bonus ) const
  473. {
  474. return m_preAttackDelay * bonus.getField( WeaponBonus::PRE_ATTACK );
  475. }
  476. //-------------------------------------------------------------------------------------------------
  477. Real WeaponTemplate::getPrimaryDamage(const WeaponBonus& bonus) const
  478. {
  479. return m_primaryDamage * bonus.getField(WeaponBonus::DAMAGE);
  480. }
  481. //-------------------------------------------------------------------------------------------------
  482. Real WeaponTemplate::getPrimaryDamageRadius(const WeaponBonus& bonus) const
  483. {
  484. return m_primaryDamageRadius * bonus.getField(WeaponBonus::RADIUS);
  485. }
  486. //-------------------------------------------------------------------------------------------------
  487. Real WeaponTemplate::getSecondaryDamage(const WeaponBonus& bonus) const
  488. {
  489. return m_secondaryDamage * bonus.getField(WeaponBonus::DAMAGE);
  490. }
  491. //-------------------------------------------------------------------------------------------------
  492. Real WeaponTemplate::getSecondaryDamageRadius(const WeaponBonus& bonus) const
  493. {
  494. return m_secondaryDamageRadius * bonus.getField(WeaponBonus::RADIUS);
  495. }
  496. //-------------------------------------------------------------------------------------------------
  497. Bool WeaponTemplate::isContactWeapon() const
  498. {
  499. #ifdef RATIONALIZE_ATTACK_RANGE
  500. // Note - undersize by 1/4 of a pathfind cell, so that the goal is not teetering on the edge
  501. // of firing range. jba.
  502. const Real UNDERSIZE = PATHFIND_CELL_SIZE_F*0.25f;
  503. return (m_attackRange - UNDERSIZE) < PATHFIND_CELL_SIZE_F;
  504. #else
  505. // fudge this a little to account for pathfinding roundoff & such
  506. const Real ATTACK_RANGE_FUDGE = 1.05f;
  507. return m_attackRange * ATTACK_RANGE_FUDGE < PATHFIND_CELL_SIZE_F;
  508. #endif
  509. }
  510. //-------------------------------------------------------------------------------------------------
  511. Real WeaponTemplate::estimateWeaponTemplateDamage(
  512. const Object *sourceObj,
  513. const Object *victimObj,
  514. const Coord3D* victimPos,
  515. const WeaponBonus& bonus
  516. ) const
  517. {
  518. if (sourceObj == NULL || (victimObj == NULL && victimPos == NULL))
  519. {
  520. DEBUG_CRASH(("bad args to estimate"));
  521. return 0.0f;
  522. }
  523. DamageType damageType = getDamageType();
  524. DeathType deathType = getDeathType();
  525. if (victimObj && victimObj->isKindOf(KINDOF_SHRUBBERY))
  526. {
  527. if (deathType == DEATH_BURNED)
  528. {
  529. // this is just a nonzero value, to ensure we can target shrubbery with flame weapons, regardless...
  530. return 1.0f;
  531. }
  532. else
  533. {
  534. return 0.0f;
  535. }
  536. }
  537. // hmm.. must be shooting a firebase or such, if there is noone home to take the bullet, return 0!
  538. if ( victimObj->isKindOf( KINDOF_STRUCTURE) && damageType == DAMAGE_SNIPER )
  539. {
  540. if ( victimObj->getContain() )
  541. {
  542. if ( victimObj->getContain()->getContainCount() == 0 )
  543. return 0.0f;
  544. }
  545. }
  546. if (damageType == DAMAGE_SURRENDER || m_allowAttackGarrisonedBldgs)
  547. {
  548. ContainModuleInterface* contain = victimObj->getContain();
  549. if( contain && contain->getContainCount() > 0 && contain->isGarrisonable() && !contain->isImmuneToClearBuildingAttacks() )
  550. {
  551. // this is just a nonzero value, to ensure we can target garrisoned things with surrender weapons, regardless...
  552. return 1.0f;
  553. }
  554. }
  555. if( victimObj )
  556. {
  557. if( damageType == DAMAGE_DISARM )
  558. {
  559. if( victimObj->isKindOf( KINDOF_MINE ) || victimObj->isKindOf( KINDOF_BOOBY_TRAP ) || victimObj->isKindOf( KINDOF_DEMOTRAP ) )
  560. {
  561. // this is just a nonzero value, to ensure we can target mines with disarm weapons, regardless...
  562. return 1.0f;
  563. }
  564. return 0.0f;
  565. }
  566. if( damageType == DAMAGE_DEPLOY && !victimObj->isAirborneTarget() )
  567. {
  568. return 1.0f;
  569. }
  570. }
  571. //@todo Kris need to examine the DAMAGE_HACK type for damage estimation purposes.
  572. //Likely this damage type will have threat implications that won't properly be dealt with until resolved.
  573. // const Coord3D* sourcePos = sourceObj->getPosition();
  574. if (victimPos == NULL)
  575. {
  576. victimPos = victimObj->getPosition();
  577. }
  578. Real damageAmount = getPrimaryDamage(bonus);
  579. if (victimObj == NULL)
  580. {
  581. return damageAmount;
  582. }
  583. else
  584. {
  585. DamageInfoInput damageInfo;
  586. damageInfo.m_damageType = damageType;
  587. damageInfo.m_deathType = deathType;
  588. damageInfo.m_sourceID = sourceObj->getID();
  589. damageInfo.m_amount = damageAmount;
  590. return victimObj->estimateDamage(damageInfo);
  591. }
  592. }
  593. //-------------------------------------------------------------------------------------------------
  594. Bool WeaponTemplate::shouldProjectileCollideWith(
  595. const Object* projectileLauncher,
  596. const Object* projectile,
  597. const Object* thingWeCollidedWith,
  598. ObjectID intendedVictimID // could be INVALID_ID for a position-shot
  599. ) const
  600. {
  601. if (!projectile || !thingWeCollidedWith)
  602. return false;
  603. // if it's our intended victim, we want to collide with it, regardless of any other considerations.
  604. if (intendedVictimID == thingWeCollidedWith->getID())
  605. return true;
  606. if (projectileLauncher != NULL)
  607. {
  608. // Don't hit your own launcher, ever.
  609. if (projectileLauncher == thingWeCollidedWith)
  610. return false;
  611. // If our launcher is inside something, and that something is 'thingWeCollidedWith' we won't collide
  612. const Object *launcherContainedBy = projectileLauncher->getContainedBy();
  613. if( launcherContainedBy == thingWeCollidedWith )
  614. return false;
  615. }
  616. // never bother burning already-burned things. (srj)
  617. if (getDamageType() == DAMAGE_FLAME || getDamageType() == DAMAGE_PARTICLE_BEAM)
  618. {
  619. if (thingWeCollidedWith->testStatus(OBJECT_STATUS_BURNED))
  620. {
  621. return false;
  622. }
  623. }
  624. // horrible special case for airplanes sitting on airfields: the projectile might
  625. // "collide" with the airfield's (invisible) collision geometry when a resting plane
  626. // is targeted. we don't want this. special case it:
  627. if (thingWeCollidedWith->isKindOf(KINDOF_FS_AIRFIELD))
  628. {
  629. //
  630. // ok, so if we are an airfield, and our intended victim has a reserved space
  631. // with us, it "belongs" to us and collisions intended for it should not detonate
  632. // as a result of colliding with us.
  633. //
  634. // notes:
  635. // -- we have already established that "thingWeCollidedWith" is not the intended victim (above)
  636. // -- this does NOT verify that the plane is actually parked at the airfield; it might be elsewhere
  637. // (but if it is, it's highly unlikely that this sort of collision could occur)
  638. //
  639. for (BehaviorModule** i = thingWeCollidedWith->getBehaviorModules(); *i; ++i)
  640. {
  641. ParkingPlaceBehaviorInterface* pp = (*i)->getParkingPlaceBehaviorInterface();
  642. if (pp != NULL && pp->hasReservedSpace(intendedVictimID))
  643. return false;
  644. }
  645. }
  646. // if something has a Sneaky Target offset, it is momentarily immune to being hit...
  647. // normally this shouldn't happen, but occasionally can by accident. so avoid it. (srj)
  648. const AIUpdateInterface* ai = thingWeCollidedWith->getAI();
  649. if (ai != NULL && ai->getSneakyTargetingOffset(NULL))
  650. {
  651. return false;
  652. }
  653. Int requiredMask = 0;
  654. Relationship r = projectile->getRelationship(thingWeCollidedWith);
  655. if (r == ALLIES) requiredMask = WEAPON_COLLIDE_ALLIES;
  656. else if (r == ENEMIES) requiredMask = WEAPON_COLLIDE_ENEMIES;
  657. if (thingWeCollidedWith->isKindOf(KINDOF_STRUCTURE))
  658. {
  659. if (thingWeCollidedWith->getControllingPlayer() == projectile->getControllingPlayer())
  660. requiredMask |= WEAPON_COLLIDE_CONTROLLED_STRUCTURES;
  661. else
  662. requiredMask |= WEAPON_COLLIDE_STRUCTURES;
  663. }
  664. if (thingWeCollidedWith->isKindOf(KINDOF_SHRUBBERY)) requiredMask |= WEAPON_COLLIDE_SHRUBBERY;
  665. if (thingWeCollidedWith->isKindOf(KINDOF_PROJECTILE)) requiredMask |= WEAPON_COLLIDE_PROJECTILE;
  666. if (thingWeCollidedWith->getTemplate()->getFenceWidth() > 0) requiredMask |= WEAPON_COLLIDE_WALLS;
  667. if (thingWeCollidedWith->isKindOf(KINDOF_SMALL_MISSILE)) requiredMask |= WEAPON_COLLIDE_SMALL_MISSILES; //All missiles are also projectiles!
  668. if (thingWeCollidedWith->isKindOf(KINDOF_BALLISTIC_MISSILE)) requiredMask |= WEAPON_COLLIDE_BALLISTIC_MISSILES; //All missiles are also projectiles!
  669. // if any in requiredMask are present in collidemask, do the collision. (srj)
  670. if ((getProjectileCollideMask() & requiredMask) != 0)
  671. return true;
  672. //DEBUG_LOG(("Rejecting projectile collision between %s and %s!\n",projectile->getTemplate()->getName().str(),thingWeCollidedWith->getTemplate()->getName().str()));
  673. return false;
  674. }
  675. //-------------------------------------------------------------------------------------------------
  676. UnsignedInt WeaponTemplate::fireWeaponTemplate
  677. (
  678. const Object *sourceObj,
  679. WeaponSlotType wslot,
  680. Int specificBarrelToUse,
  681. Object *victimObj,
  682. const Coord3D* victimPos,
  683. const WeaponBonus& bonus,
  684. Bool isProjectileDetonation,
  685. Bool ignoreRanges,
  686. Weapon *firingWeapon,
  687. ObjectID* projectileID,
  688. Bool inflictDamage
  689. ) const
  690. {
  691. //-extraLogging
  692. #if (defined(_DEBUG) || defined(_INTERNAL))
  693. AsciiString targetStr;
  694. if( TheGlobalData->m_extraLogging )
  695. {
  696. if( victimObj )
  697. targetStr.format( "%s", victimObj->getTemplate()->getName().str() );
  698. else if( victimPos )
  699. targetStr.format( "%d,%d,%d", victimPos->x, victimPos->y, victimPos->z );
  700. else
  701. targetStr.format( "SELF." );
  702. DEBUG_LOG( ("%d - WeaponTemplate::fireWeaponTemplate() begin - %s attacking %s - ",
  703. TheGameLogic->getFrame(), sourceObj->getTemplate()->getName().str(), targetStr.str() ) );
  704. }
  705. #endif
  706. //end -extraLogging
  707. //CRCDEBUG_LOG(("WeaponTemplate::fireWeaponTemplate() from %s\n", DescribeObject(sourceObj).str()));
  708. DEBUG_ASSERTCRASH(specificBarrelToUse >= 0, ("specificBarrelToUse should no longer be -1\n"));
  709. if (sourceObj == NULL || (victimObj == NULL && victimPos == NULL))
  710. {
  711. //-extraLogging
  712. #if (defined(_DEBUG) || defined(_INTERNAL))
  713. if( TheGlobalData->m_extraLogging )
  714. DEBUG_LOG( ("FAIL 1 (sourceObj %d == NULL || (victimObj %d == NULL && victimPos %d == NULL)\n", sourceObj != 0, victimObj != 0, victimPos != 0) );
  715. #endif
  716. //end -extraLogging
  717. return 0;
  718. }
  719. DEBUG_ASSERTCRASH((m_primaryDamage > 0) || (victimObj == NULL), ("You can't really shoot a zero damage weapon at an Object.") );
  720. ObjectID sourceID = sourceObj->getID();
  721. const Coord3D* sourcePos = sourceObj->getPosition();
  722. Real distSqr;
  723. ObjectID victimID;
  724. TBridgeAttackInfo info;
  725. Coord3D victimPosStorage;
  726. if (victimObj)
  727. {
  728. DEBUG_ASSERTLOG(sourceObj != victimObj, ("*** firing weapon at self -- is this really what you want?\n"));
  729. victimPos = victimObj->getPosition();
  730. victimID = victimObj->getID();
  731. Coord3D sneakyOffset;
  732. const AIUpdateInterface* ai = victimObj->getAI();
  733. if (ai != NULL && ai->getSneakyTargetingOffset(&sneakyOffset))
  734. {
  735. victimPosStorage = *victimPos;
  736. victimPosStorage.x += sneakyOffset.x;
  737. victimPosStorage.y += sneakyOffset.y;
  738. victimPosStorage.z += sneakyOffset.z;
  739. victimPos = &victimPosStorage;
  740. // for a sneaky offset, we always target a position rather than an object
  741. victimObj = NULL;
  742. victimID = INVALID_ID;
  743. distSqr = ThePartitionManager->getDistanceSquared(sourceObj, victimPos, ATTACK_RANGE_CALC_TYPE);
  744. }
  745. else
  746. {
  747. if (victimObj->isKindOf(KINDOF_BRIDGE))
  748. {
  749. // Bridges are kind of oddball - they have 2 target points at either end.
  750. TheTerrainLogic->getBridgeAttackPoints(victimObj, &info);
  751. distSqr = ThePartitionManager->getDistanceSquared( sourceObj, &info.attackPoint1, ATTACK_RANGE_CALC_TYPE );
  752. victimPos = &info.attackPoint1;
  753. Real distSqr2 = ThePartitionManager->getDistanceSquared( sourceObj, &info.attackPoint2, ATTACK_RANGE_CALC_TYPE );
  754. if (distSqr > distSqr2)
  755. {
  756. // Try the other one.
  757. distSqr = distSqr2;
  758. victimPos = &info.attackPoint2;
  759. }
  760. }
  761. else
  762. {
  763. distSqr = ThePartitionManager->getDistanceSquared(sourceObj, victimObj, ATTACK_RANGE_CALC_TYPE);
  764. }
  765. }
  766. }
  767. else
  768. {
  769. victimID = INVALID_ID;
  770. distSqr = ThePartitionManager->getDistanceSquared(sourceObj, victimPos, ATTACK_RANGE_CALC_TYPE);
  771. }
  772. // DEBUG_LOG(("WeaponTemplate::fireWeaponTemplate: firing weapon %s (source=%s, victim=%s)\n",
  773. // m_name.str(),sourceObj->getTemplate()->getName().str(),victimObj?victimObj->getTemplate()->getName().str():"NULL"));
  774. //Only perform this check if the weapon isn't a leech range weapon (which can have unlimited range!)
  775. if( !ignoreRanges && !isLeechRangeWeapon() )
  776. {
  777. Real attackRangeSqr = sqr(getAttackRange(bonus));
  778. if (distSqr > attackRangeSqr)
  779. {
  780. //DEBUG_ASSERTCRASH(distSqr < 5*5 || distSqr < attackRangeSqr*1.2f, ("*** victim is out of range (%f vs %f) of this weapon -- why did we attempt to fire?\n",sqrtf(distSqr),sqrtf(attackRangeSqr)));
  781. //-extraLogging
  782. #if (defined(_DEBUG) || defined(_INTERNAL))
  783. if( TheGlobalData->m_extraLogging )
  784. DEBUG_LOG( ("FAIL 2 (distSqr %.2f > attackRangeSqr %.2f)\n", distSqr, attackRangeSqr ) );
  785. #endif
  786. //end -extraLogging
  787. return 0;
  788. }
  789. }
  790. if (!ignoreRanges)
  791. {
  792. Real minAttackRangeSqr = sqr(getMinimumAttackRange());
  793. #ifdef RATIONALIZE_ATTACK_RANGE
  794. if (distSqr < minAttackRangeSqr && !isProjectileDetonation)
  795. #else
  796. if (distSqr < minAttackRangeSqr-0.5f && !isProjectileDetonation)
  797. #endif
  798. {
  799. DEBUG_ASSERTCRASH(distSqr > minAttackRangeSqr*0.8f, ("*** victim is closer than min attack range (%f vs %f) of this weapon -- why did we attempt to fire?\n",sqrtf(distSqr),sqrtf(minAttackRangeSqr)));
  800. //-extraLogging
  801. #if (defined(_DEBUG) || defined(_INTERNAL))
  802. if( TheGlobalData->m_extraLogging )
  803. DEBUG_LOG( ("FAIL 3 (distSqr %.2f< minAttackRangeSqr %.2f - 0.5f && !isProjectileDetonation %d)\n", distSqr, minAttackRangeSqr, isProjectileDetonation ) );
  804. #endif
  805. //end -extraLogging
  806. return 0;
  807. }
  808. }
  809. // call this even if FXList is null, because this also handles stuff like Gun Barrel Recoil
  810. if (sourceObj && sourceObj->getDrawable())
  811. {
  812. Coord3D targetPos;
  813. if( victimObj )
  814. {
  815. victimObj->getGeometryInfo().getCenterPosition( *victimObj->getPosition(), targetPos );
  816. }
  817. else
  818. {
  819. targetPos.set( victimPos );
  820. }
  821. Real reAngle = getWeaponRecoilAmount();
  822. Real reDir = reAngle != 0.0f ? (atan2(victimPos->y - sourcePos->y, victimPos->x - sourcePos->x)) : 0.0f;
  823. VeterancyLevel v = sourceObj->getVeterancyLevel();
  824. const FXList* fx = isProjectileDetonation ? getProjectileDetonateFX(v) : getFireFX(v);
  825. if ( TheGameLogic->getFrame() < firingWeapon->getSuspendFXFrame() )
  826. fx = NULL;
  827. Bool handled;
  828. if(!sourceObj->isLocallyControlled() // if user watching is not controller and
  829. && sourceObj->testStatus(OBJECT_STATUS_STEALTHED) // if unit is stealthed (like a Pathfinder)
  830. && !sourceObj->testStatus(OBJECT_STATUS_DETECTED) // but not detected...
  831. && !sourceObj->testStatus(OBJECT_STATUS_DISGUISED) // and not disguised...
  832. && !sourceObj->isKindOf(KINDOF_MINE) // and not a mine (which always do the FX, even if hidden)...
  833. && !isPlayFXWhenStealthed() // and not a weapon marked to playwhenstealthed
  834. )
  835. {
  836. handled = TRUE; // then let's just pretend like we did the fx by returning true
  837. }
  838. else
  839. {
  840. handled = sourceObj->getDrawable()->handleWeaponFireFX(wslot,
  841. specificBarrelToUse,
  842. fx,
  843. getWeaponSpeed(),
  844. reAngle,
  845. reDir,
  846. &targetPos,
  847. getPrimaryDamageRadius(bonus)
  848. );
  849. }
  850. if (handled == false && fx != NULL)
  851. {
  852. // bah. just play it at the drawable's pos.
  853. //DEBUG_LOG(("*** WeaponFireFX not fully handled by the client\n"));
  854. const Coord3D* where = isContactWeapon() ? &targetPos : sourceObj->getDrawable()->getPosition();
  855. FXList::doFXPos(fx, where, sourceObj->getDrawable()->getTransformMatrix(), getWeaponSpeed(), &targetPos, getPrimaryDamageRadius(bonus));
  856. }
  857. }
  858. // Now do the FireOCL if there is one
  859. if( sourceObj )
  860. {
  861. VeterancyLevel v = sourceObj->getVeterancyLevel();
  862. const ObjectCreationList *oclToUse = isProjectileDetonation ? getProjectileDetonationOCL(v) : getFireOCL(v);
  863. if( oclToUse )
  864. ObjectCreationList::create( oclToUse, sourceObj, NULL );
  865. }
  866. Coord3D projectileDestination = *victimPos; //Need to copy this, as we have a pointer to their actual position
  867. Real scatterRadius = 0.0f;
  868. if( m_scatterRadius > 0.0f || m_infantryInaccuracyDist > 0.0f && victimObj && victimObj->isKindOf( KINDOF_INFANTRY ) )
  869. {
  870. // This weapon scatters, so clear the victimObj, as we are no longer shooting it directly,
  871. // and find a random point within the radius to shoot at as victimPos
  872. scatterRadius = m_scatterRadius;
  873. // if it's an object, aim at the center, not the ground part (srj)
  874. PathfindLayerEnum targetLayer = LAYER_GROUND;
  875. if( victimObj )
  876. {
  877. if( victimObj->isKindOf( KINDOF_STRUCTURE ) )
  878. {
  879. victimObj->getGeometryInfo().getCenterPosition(*victimObj->getPosition(), projectileDestination);
  880. }
  881. if( m_infantryInaccuracyDist > 0.0f && victimObj->isKindOf( KINDOF_INFANTRY ) )
  882. {
  883. //If we are firing a weapon that is considered inaccurate against infantry, then add it to
  884. //the scatter radius!
  885. scatterRadius += m_infantryInaccuracyDist;
  886. }
  887. targetLayer = victimObj->getLayer();
  888. }
  889. //victimObj = NULL; // his position is already in victimPos, if he existed
  890. //Randomize the scatter radius (sometimes it can be more accurate than others)
  891. scatterRadius = GameLogicRandomValueReal( 0, scatterRadius );
  892. Real scatterAngleRadian = GameLogicRandomValueReal( 0, 2*PI );
  893. Coord3D firingOffset;
  894. firingOffset.zero();
  895. firingOffset.x = scatterRadius * Cos( scatterAngleRadian );
  896. firingOffset.y = scatterRadius * Sin( scatterAngleRadian );
  897. projectileDestination.x += firingOffset.x;
  898. projectileDestination.y += firingOffset.y;
  899. //What's suddenly become crucially important is to FIRE at the ground at this location!!!
  900. //If we aim for the center point of our target and miss, the shot will go much farther than
  901. //we expect!
  902. // srj sez: we should actually fire at the layer the victim is on, if possible, in case it is on a bridge...
  903. projectileDestination.z = TheTerrainLogic->getLayerHeight( projectileDestination.x, projectileDestination.y, targetLayer );
  904. }
  905. if (getProjectileTemplate() == NULL || isProjectileDetonation)
  906. {
  907. // see if we need to be called back at a later point to deal the damage.
  908. Coord3D v;
  909. v.x = victimPos->x - sourcePos->x;
  910. v.y = victimPos->y - sourcePos->y;
  911. v.z = victimPos->z - sourcePos->z;
  912. // don't round the result; we WANT a fractional-frame-delay in this case.
  913. Real delayInFrames = (v.length() / getWeaponSpeed());
  914. ObjectID damageID = getDamageDealtAtSelfPosition() ? INVALID_ID : victimID;
  915. if( firingWeapon->isLaser() )
  916. {
  917. if( scatterRadius <= getPrimaryDamageRadius( bonus ) || scatterRadius <= getSecondaryDamageRadius( bonus ) )
  918. {
  919. //The laser is close enough to damage the object, so just hit it directly. Some victim objects
  920. //adjust the laser's position to prevent it from hitting the ground.
  921. if( victimObj )
  922. {
  923. projectileDestination.set( victimObj->getPosition() );
  924. }
  925. firingWeapon->createLaser( sourceObj, victimObj, &projectileDestination );
  926. }
  927. else
  928. {
  929. //We are missing our intended target, so now we want to aim at the ground at the projectile offset.
  930. damageID = INVALID_ID;
  931. firingWeapon->createLaser( sourceObj, NULL, &projectileDestination );
  932. }
  933. if( inflictDamage )
  934. {
  935. dealDamageInternal( sourceID, damageID, &projectileDestination, bonus, isProjectileDetonation );
  936. }
  937. return TheGameLogic->getFrame();
  938. }
  939. const Coord3D* damagePos = getDamageDealtAtSelfPosition() ? sourcePos : victimPos;
  940. if (delayInFrames < 1.0f)
  941. {
  942. // go ahead and do it now
  943. //DEBUG_LOG(("WeaponTemplate::fireWeaponTemplate: firing weapon immediately!\n"));
  944. if( inflictDamage )
  945. {
  946. dealDamageInternal(sourceID, damageID, damagePos, bonus, isProjectileDetonation);
  947. }
  948. //-extraLogging
  949. #if (defined(_DEBUG) || defined(_INTERNAL))
  950. if( TheGlobalData->m_extraLogging )
  951. DEBUG_LOG( ("EARLY 4 (delayed damage applied now)\n") );
  952. #endif
  953. //end -extraLogging
  954. return TheGameLogic->getFrame();
  955. }
  956. else
  957. {
  958. UnsignedInt when = 0;
  959. if( TheWeaponStore && inflictDamage )
  960. {
  961. UnsignedInt delayInWholeFrames = REAL_TO_INT_CEIL(delayInFrames);
  962. when = TheGameLogic->getFrame() + delayInWholeFrames;
  963. //DEBUG_LOG(("WeaponTemplate::fireWeaponTemplate: firing weapon in %d frames (= %d)!\n", delayInWholeFrames,when));
  964. TheWeaponStore->setDelayedDamage(this, damagePos, when, sourceID, damageID, bonus);
  965. }
  966. //-extraLogging
  967. #if (defined(_DEBUG) || defined(_INTERNAL))
  968. if( TheGlobalData->m_extraLogging )
  969. DEBUG_LOG( ("EARLY 5 (delaying damage applied until frame %d)\n", when ) );
  970. #endif
  971. //end -extraLogging
  972. return when;
  973. }
  974. }
  975. else // must be a projectile
  976. {
  977. Player *owningPlayer = sourceObj->getControllingPlayer(); //Need to know so missiles don't collide with firer
  978. Object *projectile = TheThingFactory->newObject( getProjectileTemplate(), owningPlayer->getDefaultTeam() );
  979. projectile->setProducer(sourceObj);
  980. //If the player has battle plans (America Strategy Center), then apply those bonuses
  981. //to this object if applicable. Internally it validates certain kinds of objects.
  982. //When projectiles are created, weapon bonuses such as damage may get applied.
  983. if( owningPlayer->getNumBattlePlansActive() > 0 )
  984. {
  985. owningPlayer->applyBattlePlanBonusesForObject( projectile );
  986. }
  987. //Store the project ID in the object as the last projectile fired!
  988. if (projectileID)
  989. *projectileID = projectile->getID();
  990. // Notify special power tracking
  991. SpecialPowerCompletionDie *die = sourceObj->findSpecialPowerCompletionDie();
  992. if (die)
  993. {
  994. die->notifyScriptEngine();
  995. die = projectile->findSpecialPowerCompletionDie();
  996. if (die)
  997. {
  998. die->setCreator(INVALID_ID);
  999. }
  1000. }
  1001. else
  1002. {
  1003. die = projectile->findSpecialPowerCompletionDie();
  1004. if (die)
  1005. {
  1006. die->setCreator(sourceObj->getID());
  1007. }
  1008. }
  1009. firingWeapon->newProjectileFired( sourceObj, projectile, victimObj, victimPos );//The actual logic weapon needs to know this was created.
  1010. ProjectileUpdateInterface* pui = NULL;
  1011. for (BehaviorModule** u = projectile->getBehaviorModules(); *u; ++u)
  1012. {
  1013. if ((pui = (*u)->getProjectileUpdateInterface()) != NULL)
  1014. break;
  1015. }
  1016. if (pui)
  1017. {
  1018. VeterancyLevel v = sourceObj->getVeterancyLevel();
  1019. if( scatterRadius > 0.0f )
  1020. {
  1021. //With a scatter radius, don't follow the victim (overriding the intent).
  1022. pui->projectileLaunchAtObjectOrPosition( NULL, &projectileDestination, sourceObj, wslot, specificBarrelToUse, this, m_projectileExhausts[v] );
  1023. }
  1024. else
  1025. {
  1026. pui->projectileLaunchAtObjectOrPosition(victimObj, &projectileDestination, sourceObj, wslot, specificBarrelToUse, this, m_projectileExhausts[v]);
  1027. }
  1028. }
  1029. else
  1030. {
  1031. //DEBUG_CRASH(("Projectiles should implement ProjectileUpdateInterface!\n"));
  1032. // actually, this is ok, for things like Firestorm.... (srj)
  1033. projectile->setPosition(&projectileDestination);
  1034. }
  1035. //If we're launching a missile at a unit with valid countermeasures, then communicate it
  1036. if( projectile->isKindOf( KINDOF_SMALL_MISSILE ) && victimObj && victimObj->hasCountermeasures() )
  1037. {
  1038. const AIUpdateInterface *ai = victimObj->getAI();
  1039. //Only allow jets not currently supersonic to launch countermeasures
  1040. if( ai && ai->getCurLocomotorSetType() != LOCOMOTORSET_SUPERSONIC )
  1041. {
  1042. //This function will determine now whether or not the fired projectile will be diverted to
  1043. //an available decoy flare.
  1044. victimObj->reportMissileForCountermeasures( projectile );
  1045. }
  1046. }
  1047. //-extraLogging
  1048. #if (defined(_DEBUG) || defined(_INTERNAL))
  1049. if( TheGlobalData->m_extraLogging )
  1050. DEBUG_LOG( ("DONE\n") );
  1051. #endif
  1052. //end -extraLogging
  1053. return 0;
  1054. }
  1055. }
  1056. //-------------------------------------------------------------------------------------------------
  1057. void WeaponTemplate::trimOldHistoricDamage() const
  1058. {
  1059. UnsignedInt expirationDate = TheGameLogic->getFrame() - TheGlobalData->m_historicDamageLimit;
  1060. while (m_historicDamage.size() > 0)
  1061. {
  1062. HistoricWeaponDamageInfo& h = m_historicDamage.front();
  1063. if (h.frame <= expirationDate)
  1064. {
  1065. m_historicDamage.pop_front();
  1066. continue;
  1067. }
  1068. else
  1069. {
  1070. // since they are in strict chronological order,
  1071. // stop as soon as we get to a nonexpired one
  1072. break;
  1073. }
  1074. }
  1075. }
  1076. //-------------------------------------------------------------------------------------------------
  1077. static Bool is2DDistSquaredLessThan(const Coord3D& a, const Coord3D& b, Real distSqr)
  1078. {
  1079. Real da = sqr(a.x - b.x) + sqr(a.y - b.y);
  1080. return da <= distSqr;
  1081. }
  1082. //-------------------------------------------------------------------------------------------------
  1083. void WeaponTemplate::dealDamageInternal(ObjectID sourceID, ObjectID victimID, const Coord3D *pos, const WeaponBonus& bonus, Bool isProjectileDetonation) const
  1084. {
  1085. if (sourceID == 0) // must have a source
  1086. return;
  1087. if (victimID == 0 && pos == NULL) // must have some sort of destination
  1088. return;
  1089. Object *source = TheGameLogic->findObjectByID(sourceID); // might be null...
  1090. //
  1091. /** @todo We need to rewrite the historic stuff ... if you fire 5 missiles, and the 5th,
  1092. // one creates a firestorm ... and then half a second later another volley of 5 missiles
  1093. // come in, the second wave of 5 missiles would all do a historic weapon, making 5 more
  1094. // firestorms (CBD) */
  1095. //
  1096. trimOldHistoricDamage();
  1097. if( m_historicBonusCount > 0 && m_historicBonusWeapon != this )
  1098. {
  1099. Real radSqr = m_historicBonusRadius * m_historicBonusRadius;
  1100. Int count = 0;
  1101. UnsignedInt frameNow = TheGameLogic->getFrame();
  1102. UnsignedInt oldestThatWillCount = frameNow - m_historicBonusTime; // Anything before this frame is "more than two seconds ago" eg
  1103. for( HistoricWeaponDamageList::const_iterator it = m_historicDamage.begin(); it != m_historicDamage.end(); ++it )
  1104. {
  1105. if( it->frame >= oldestThatWillCount &&
  1106. is2DDistSquaredLessThan( *pos, it->location, radSqr ) )
  1107. {
  1108. // This one is close enough in time and distance, so count it. This is tracked by template since it applies
  1109. // across units, so don't try to clear historicDamage on success in here.
  1110. ++count;
  1111. }
  1112. }
  1113. if( count >= m_historicBonusCount - 1 ) // minus 1 since we include ourselves implicitly
  1114. {
  1115. TheWeaponStore->createAndFireTempWeapon(m_historicBonusWeapon, source, pos);
  1116. /** @todo E3 hack! Clear the list for now to make sure we don't have multiple firestorms
  1117. * remove this when the branches merge back into one. What is causing the
  1118. * multiple firestorms, who is to say ... this is a plug, not a fix! */
  1119. m_historicDamage.clear();
  1120. }
  1121. else
  1122. {
  1123. // add AFTER checking for historic stuff
  1124. m_historicDamage.push_back( HistoricWeaponDamageInfo(frameNow, *pos) );
  1125. } // end else
  1126. } // if historic bonuses
  1127. //DEBUG_LOG(("WeaponTemplate::dealDamageInternal: dealing damage %s at frame %d\n",m_name.str(),TheGameLogic->getFrame()));
  1128. // if there's a specific victim, use it's pos (overriding the value passed in)
  1129. Object *primaryVictim = victimID ? TheGameLogic->findObjectByID(victimID) : NULL; // might be null...
  1130. if (primaryVictim)
  1131. {
  1132. pos = primaryVictim->getPosition();
  1133. }
  1134. DamageType damageType = getDamageType();
  1135. DeathType deathType = getDeathType();
  1136. ObjectStatusTypes damageStatusType = getDamageStatusType();
  1137. if (getProjectileTemplate() == NULL || isProjectileDetonation)
  1138. {
  1139. SimpleObjectIterator *iter;
  1140. Object *curVictim;
  1141. Real curVictimDistSqr;
  1142. Real primaryRadius = getPrimaryDamageRadius(bonus);
  1143. Real secondaryRadius = getSecondaryDamageRadius(bonus);
  1144. Real primaryDamage = getPrimaryDamage(bonus);
  1145. Real secondaryDamage = getSecondaryDamage(bonus);
  1146. Int affects = getAffectsMask();
  1147. DEBUG_ASSERTCRASH(secondaryRadius >= primaryRadius || secondaryRadius == 0.0f, ("secondary radius should be >= primary radius (or zero)\n"));
  1148. Real primaryRadiusSqr = sqr(primaryRadius);
  1149. Real radius = max(primaryRadius, secondaryRadius);
  1150. if (radius > 0.0f)
  1151. {
  1152. iter = ThePartitionManager->iterateObjectsInRange(pos, radius, DAMAGE_RANGE_CALC_TYPE);
  1153. curVictim = iter->firstWithNumeric(&curVictimDistSqr);
  1154. }
  1155. else
  1156. {
  1157. //DEBUG_ASSERTCRASH(primaryVictim != NULL, ("weapons without radii should always pass in specific victims"));
  1158. // check against victimID rather than primaryVictim, since we may have targeted a legitimate victim
  1159. // that got killed before the damage was dealt... (srj)
  1160. //DEBUG_ASSERTCRASH(victimID != 0, ("weapons without radii should always pass in specific victims"));
  1161. iter = NULL;
  1162. curVictim = primaryVictim;
  1163. curVictimDistSqr = 0.0f;
  1164. if( affects & WEAPON_KILLS_SELF )
  1165. {
  1166. DamageInfo damageInfo;
  1167. damageInfo.in.m_damageType = damageType;
  1168. damageInfo.in.m_deathType = deathType;
  1169. damageInfo.in.m_sourceID = sourceID;
  1170. damageInfo.in.m_sourcePlayerMask = 0;
  1171. damageInfo.in.m_damageStatusType = damageStatusType;
  1172. damageInfo.in.m_amount = HUGE_DAMAGE_AMOUNT;
  1173. source->attemptDamage( &damageInfo );
  1174. return;
  1175. }
  1176. }
  1177. MemoryPoolObjectHolder hold(iter);
  1178. for (; curVictim != NULL; curVictim = iter ? iter->nextWithNumeric(&curVictimDistSqr) : NULL)
  1179. {
  1180. Bool killSelf = false;
  1181. if (source != NULL)
  1182. {
  1183. // anytime something is designated as the "primary victim" (ie, the direct target
  1184. // of the weapon), we ignore all the "affects" flags.
  1185. if (curVictim != primaryVictim)
  1186. {
  1187. if( (affects & WEAPON_KILLS_SELF) && source == curVictim )
  1188. {
  1189. killSelf = true;
  1190. }
  1191. else
  1192. {
  1193. // should object ever be allowed to damage themselves? methinks not...
  1194. // exception: a few weapons allow this (eg, for suicide bombers).
  1195. if( (affects & WEAPON_AFFECTS_SELF) == 0 )
  1196. {
  1197. // Remember that source is a missile for some units, and they don't want to injure them'selves' either
  1198. if( source == curVictim || source->getProducerID() == curVictim->getID() )
  1199. {
  1200. //DEBUG_LOG(("skipping damage done to SELF...\n"));
  1201. continue;
  1202. }
  1203. }
  1204. if( affects & WEAPON_DOESNT_AFFECT_SIMILAR )
  1205. {
  1206. //This means we probably are affecting allies, but don't want to kill nearby members that are the same type as us.
  1207. //A good example are a group of terrorists blowing themselves up. We don't want to cause a domino effect that kills
  1208. //all of them.
  1209. if( source->getTemplate()->isEquivalentTo(curVictim->getTemplate()) && source->getRelationship( curVictim ) == ALLIES )
  1210. {
  1211. continue;
  1212. }
  1213. }
  1214. if ((affects & WEAPON_DOESNT_AFFECT_AIRBORNE) != 0 && curVictim->isSignificantlyAboveTerrain())
  1215. {
  1216. continue;
  1217. }
  1218. /*
  1219. The idea here is: if its our ally(/enemies), AND it's not the direct target, AND the weapon doesn't
  1220. do radius-damage to allies(/enemies)... skip it.
  1221. */
  1222. Relationship r = curVictim->getRelationship(source);
  1223. Int requiredMask;
  1224. if (r == ALLIES)
  1225. requiredMask = WEAPON_AFFECTS_ALLIES;
  1226. else if (r == ENEMIES)
  1227. requiredMask = WEAPON_AFFECTS_ENEMIES;
  1228. else /* r == NEUTRAL */
  1229. requiredMask = WEAPON_AFFECTS_NEUTRALS;
  1230. if( !(affects & requiredMask) )
  1231. {
  1232. //Skip if we aren't affected by this weapon.
  1233. continue;
  1234. }
  1235. }
  1236. }
  1237. }
  1238. DamageInfo damageInfo;
  1239. damageInfo.in.m_damageType = damageType;
  1240. damageInfo.in.m_deathType = deathType;
  1241. damageInfo.in.m_sourceID = sourceID;
  1242. damageInfo.in.m_sourcePlayerMask = 0;
  1243. damageInfo.in.m_damageStatusType = damageStatusType;
  1244. Coord3D damageDirection;
  1245. damageDirection.zero();
  1246. if( curVictim && source )
  1247. {
  1248. damageDirection.set( curVictim->getPosition() );
  1249. damageDirection.sub( source->getPosition() );
  1250. }
  1251. Real allowedAngle = getRadiusDamageAngle();
  1252. if( allowedAngle < PI )
  1253. {
  1254. if( curVictim == NULL || source == NULL )
  1255. continue; // We are directional damage, but can't figure out our direction. Just bail.
  1256. // People can only be hit in a cone oriented as the firer is oriented
  1257. Vector3 sourceVector = source->getTransformMatrix()->Get_X_Vector();
  1258. Vector3 damageVector(damageDirection.x, damageDirection.y, damageDirection.z);
  1259. sourceVector.Normalize();
  1260. damageVector.Normalize();
  1261. // These are now normalized, so the dot productis actually the Cos of the angle they form
  1262. // A smaller Cos would mean a more obtuse angle
  1263. if( Vector3::Dot_Product(sourceVector, damageVector) < Cos(allowedAngle) )
  1264. continue;// Too far to the side, can't hurt them.
  1265. }
  1266. // Grab the vector between the source object causing the damage and the victim in order that we can
  1267. // simulate a shockwave pushing objects around
  1268. damageInfo.in.m_shockWaveAmount = m_shockWaveAmount;
  1269. if (damageInfo.in.m_shockWaveAmount > 0.0f)
  1270. {
  1271. // Calculate the vector of the shockwave
  1272. Coord3D shockWaveVector = damageDirection;
  1273. // Guard against zero vector. Make vector stright up if that is the case
  1274. if (fabs(shockWaveVector.x) < WWMATH_EPSILON &&
  1275. fabs(shockWaveVector.y) < WWMATH_EPSILON &&
  1276. fabs(shockWaveVector.z) < WWMATH_EPSILON)
  1277. {
  1278. shockWaveVector.z = 1.0f;
  1279. }
  1280. // Populate the damge information with the shockwave information
  1281. damageInfo.in.m_shockWaveVector = shockWaveVector;
  1282. damageInfo.in.m_shockWaveRadius = m_shockWaveRadius;
  1283. damageInfo.in.m_shockWaveTaperOff = m_shockWaveTaperOff;
  1284. }
  1285. if (source && source->getControllingPlayer()) {
  1286. damageInfo.in.m_sourcePlayerMask = source->getControllingPlayer()->getPlayerMask();
  1287. }
  1288. // note, don't bother with damage multipliers here...
  1289. // that's handled internally by the attemptDamage() method.
  1290. damageInfo.in.m_amount = (curVictimDistSqr <= primaryRadiusSqr) ? primaryDamage : secondaryDamage;
  1291. if( killSelf )
  1292. {
  1293. //Deal enough damage to kill yourself. I thought about getting the current health and applying
  1294. //enough unresistable damage to die... however it's possible that we have different types of
  1295. //deaths based on damage type and/or the possibility to resist certain damage types and
  1296. //surviving -- so instead, I'm blindly inflicting a very high value of the intended damage type.
  1297. damageInfo.in.m_amount = HUGE_DAMAGE_AMOUNT;
  1298. //BodyModuleInterface* body = curVictim->getBodyModule();
  1299. //if( body )
  1300. //{
  1301. // Real curVictimHealth = curVictim->getBodyModule()->getHealth();
  1302. // damageInfo.in.m_amount = __max( damageInfo.in.m_amount, curVictimHealth );
  1303. //}
  1304. }
  1305. // if the damage-dealer is a projectile, designate the damage as done by its launcher, not the projectile.
  1306. // this is much more useful for the AI...
  1307. if (source && source->isKindOf(KINDOF_PROJECTILE))
  1308. {
  1309. for (BehaviorModule** u = source->getBehaviorModules(); *u; ++u)
  1310. {
  1311. ProjectileUpdateInterface* pui = (*u)->getProjectileUpdateInterface();
  1312. if (pui != NULL)
  1313. {
  1314. damageInfo.in.m_sourceID = pui->projectileGetLauncherID();
  1315. break;
  1316. }
  1317. }
  1318. }
  1319. curVictim->attemptDamage(&damageInfo);
  1320. //DEBUG_ASSERTLOG(damageInfo.out.m_noEffect, ("WeaponTemplate::dealDamageInternal: dealt to %s %08lx: attempted %f, actual %f (%f)\n",
  1321. // curVictim->getTemplate()->getName().str(),curVictim,
  1322. // damageInfo.in.m_amount, damageInfo.out.m_actualDamageDealt, damageInfo.out.m_actualDamageClipped));
  1323. }
  1324. }
  1325. else
  1326. {
  1327. DEBUG_CRASH(("projectile weapons should never get dealDamage called directly\n"));
  1328. }
  1329. }
  1330. //-------------------------------------------------------------------------------------------------
  1331. //-------------------------------------------------------------------------------------------------
  1332. //-------------------------------------------------------------------------------------------------
  1333. WeaponStore::WeaponStore()
  1334. {
  1335. }
  1336. //-------------------------------------------------------------------------------------------------
  1337. WeaponStore::~WeaponStore()
  1338. {
  1339. deleteAllDelayedDamage();
  1340. for (Int i = 0; i < m_weaponTemplateVector.size(); i++)
  1341. {
  1342. WeaponTemplate* wt = m_weaponTemplateVector[i];
  1343. if (wt)
  1344. wt->deleteInstance();
  1345. }
  1346. m_weaponTemplateVector.clear();
  1347. }
  1348. //-------------------------------------------------------------------------------------------------
  1349. void WeaponStore::handleProjectileDetonation(const WeaponTemplate* wt, const Object *source, const Coord3D* pos, WeaponBonusConditionFlags extraBonusFlags, Bool inflictDamage )
  1350. {
  1351. Weapon* w = TheWeaponStore->allocateNewWeapon(wt, PRIMARY_WEAPON);
  1352. w->loadAmmoNow(source);
  1353. w->fireProjectileDetonationWeapon( source, pos, extraBonusFlags, inflictDamage );
  1354. w->deleteInstance();
  1355. }
  1356. //-------------------------------------------------------------------------------------------------
  1357. void WeaponStore::createAndFireTempWeapon(const WeaponTemplate* wt, const Object *source, const Coord3D* pos)
  1358. {
  1359. if (wt == NULL)
  1360. return;
  1361. Weapon* w = TheWeaponStore->allocateNewWeapon(wt, PRIMARY_WEAPON);
  1362. w->loadAmmoNow(source);
  1363. w->fireWeapon(source, pos);
  1364. w->deleteInstance();
  1365. }
  1366. //-------------------------------------------------------------------------------------------------
  1367. void WeaponStore::createAndFireTempWeapon(const WeaponTemplate* wt, const Object *source, Object *target)
  1368. {
  1369. //CRCDEBUG_LOG(("WeaponStore::createAndFireTempWeapon() for %s\n", DescribeObject(source)));
  1370. if (wt == NULL)
  1371. return;
  1372. Weapon* w = TheWeaponStore->allocateNewWeapon(wt, PRIMARY_WEAPON);
  1373. w->loadAmmoNow(source);
  1374. w->fireWeapon(source, target);
  1375. w->deleteInstance();
  1376. }
  1377. //-------------------------------------------------------------------------------------------------
  1378. const WeaponTemplate *WeaponStore::findWeaponTemplate( AsciiString name ) const
  1379. {
  1380. if (stricmp(name.str(), "None") == 0)
  1381. return NULL;
  1382. const WeaponTemplate * wt = findWeaponTemplatePrivate( TheNameKeyGenerator->nameToKey( name ) );
  1383. DEBUG_ASSERTCRASH(wt != NULL, ("Weapon %s not found!\n",name.str()));
  1384. return wt;
  1385. }
  1386. //-------------------------------------------------------------------------------------------------
  1387. WeaponTemplate *WeaponStore::findWeaponTemplatePrivate( NameKeyType key ) const
  1388. {
  1389. // search weapon list for name
  1390. for (Int i = 0; i < m_weaponTemplateVector.size(); i++)
  1391. if( m_weaponTemplateVector[ i ]->getNameKey() == key )
  1392. return m_weaponTemplateVector[i];
  1393. return NULL;
  1394. }
  1395. //-------------------------------------------------------------------------------------------------
  1396. WeaponTemplate *WeaponStore::newWeaponTemplate(AsciiString name)
  1397. {
  1398. // sanity
  1399. if(name.isEmpty())
  1400. return NULL;
  1401. // allocate a new weapon
  1402. WeaponTemplate *wt = newInstance(WeaponTemplate);
  1403. wt->m_name = name;
  1404. wt->m_nameKey = TheNameKeyGenerator->nameToKey( name );
  1405. m_weaponTemplateVector.push_back(wt);
  1406. return wt;
  1407. }
  1408. //-------------------------------------------------------------------------------------------------
  1409. WeaponTemplate *WeaponStore::newOverride(WeaponTemplate *weaponTemplate)
  1410. {
  1411. if (!weaponTemplate)
  1412. return NULL;
  1413. // allocate a new weapon
  1414. WeaponTemplate *wt = newInstance(WeaponTemplate);
  1415. (*wt) = (*weaponTemplate);
  1416. (wt)->friend_setNextTemplate(weaponTemplate);
  1417. return wt;
  1418. }
  1419. //-------------------------------------------------------------------------------------------------
  1420. void WeaponStore::update()
  1421. {
  1422. for (std::list<WeaponDelayedDamageInfo>::iterator ddi = m_weaponDDI.begin(); ddi != m_weaponDDI.end(); )
  1423. {
  1424. UnsignedInt curFrame = TheGameLogic->getFrame();
  1425. if (curFrame >= ddi->m_delayDamageFrame)
  1426. {
  1427. // we never do projectile-detonation-damage via this code path.
  1428. const isProjectileDetonation = false;
  1429. ddi->m_delayedWeapon->dealDamageInternal(ddi->m_delaySourceID, ddi->m_delayIntendedVictimID, &ddi->m_delayDamagePos, ddi->m_bonus, isProjectileDetonation);
  1430. ddi = m_weaponDDI.erase(ddi);
  1431. }
  1432. else
  1433. {
  1434. ++ddi;
  1435. }
  1436. }
  1437. }
  1438. //-------------------------------------------------------------------------------------------------
  1439. void WeaponStore::deleteAllDelayedDamage()
  1440. {
  1441. m_weaponDDI.clear();
  1442. }
  1443. // ------------------------------------------------------------------------------------------------
  1444. void WeaponStore::resetWeaponTemplates( void )
  1445. {
  1446. for (Int i = 0; i < m_weaponTemplateVector.size(); i++)
  1447. {
  1448. WeaponTemplate* wt = m_weaponTemplateVector[i];
  1449. wt->reset();
  1450. }
  1451. }
  1452. //-------------------------------------------------------------------------------------------------
  1453. void WeaponStore::reset()
  1454. {
  1455. // clean up any overriddes.
  1456. for (Int i = 0; i < m_weaponTemplateVector.size(); ++i)
  1457. {
  1458. WeaponTemplate *wt = m_weaponTemplateVector[i];
  1459. if (wt->isOverride())
  1460. {
  1461. WeaponTemplate *override = wt;
  1462. wt = wt->friend_clearNextTemplate();
  1463. override->deleteInstance();
  1464. }
  1465. }
  1466. deleteAllDelayedDamage();
  1467. resetWeaponTemplates();
  1468. }
  1469. //-------------------------------------------------------------------------------------------------
  1470. void WeaponStore::setDelayedDamage(const WeaponTemplate *weapon, const Coord3D* pos, UnsignedInt whichFrame, ObjectID sourceID, ObjectID victimID, const WeaponBonus& bonus)
  1471. {
  1472. WeaponDelayedDamageInfo wi;
  1473. wi.m_delayedWeapon = weapon;
  1474. wi.m_delayDamagePos = *pos;
  1475. wi.m_delayDamageFrame = whichFrame;
  1476. wi.m_delaySourceID = sourceID;
  1477. wi.m_delayIntendedVictimID = victimID;
  1478. wi.m_bonus = bonus;
  1479. m_weaponDDI.push_back(wi);
  1480. }
  1481. //-------------------------------------------------------------------------------------------------
  1482. void WeaponStore::postProcessLoad()
  1483. {
  1484. if (!TheThingFactory)
  1485. {
  1486. DEBUG_CRASH(("you must call this after TheThingFactory is inited"));
  1487. return;
  1488. }
  1489. for (Int i = 0; i < m_weaponTemplateVector.size(); i++)
  1490. {
  1491. WeaponTemplate* wt = m_weaponTemplateVector[i];
  1492. if (wt)
  1493. wt->postProcessLoad();
  1494. }
  1495. } // end postProcessLoad
  1496. //-------------------------------------------------------------------------------------------------
  1497. /*static*/ void WeaponStore::parseWeaponTemplateDefinition(INI* ini)
  1498. {
  1499. AsciiString name;
  1500. // read the weapon name
  1501. const char* c = ini->getNextToken();
  1502. name.set(c);
  1503. // find existing item if present
  1504. WeaponTemplate *weapon = TheWeaponStore->findWeaponTemplatePrivate( TheNameKeyGenerator->nameToKey( name ) );
  1505. if (weapon)
  1506. {
  1507. if (ini->getLoadType() == INI_LOAD_CREATE_OVERRIDES)
  1508. weapon = TheWeaponStore->newOverride(weapon);
  1509. else
  1510. {
  1511. DEBUG_CRASH(("Weapon '%s' already exists, but OVERRIDE not specified", c));
  1512. return;
  1513. }
  1514. }
  1515. else
  1516. {
  1517. // no item is present, create a new one
  1518. weapon = TheWeaponStore->newWeaponTemplate(name);
  1519. }
  1520. // parse the ini weapon definition
  1521. ini->initFromINI(weapon, weapon->getFieldParse());
  1522. if (weapon->m_projectileName.isNone())
  1523. weapon->m_projectileName.clear();
  1524. #if defined(_DEBUG) || defined(_INTERNAL)
  1525. if (!weapon->getFireSound().getEventName().isEmpty() && weapon->getFireSound().getEventName().compareNoCase("NoSound") != 0)
  1526. {
  1527. DEBUG_ASSERTCRASH(TheAudio->isValidAudioEvent(&weapon->getFireSound()), ("Invalid FireSound %s in Weapon '%s'.", weapon->getFireSound().getEventName().str(), weapon->getName().str()));
  1528. }
  1529. #endif
  1530. }
  1531. //-------------------------------------------------------------------------------------------------
  1532. //-------------------------------------------------------------------------------------------------
  1533. //-------------------------------------------------------------------------------------------------
  1534. //-------------------------------------------------------------------------------------------------
  1535. Weapon::Weapon(const WeaponTemplate* tmpl, WeaponSlotType wslot)
  1536. {
  1537. // Weapons start empty; you must reload before use.
  1538. // (however, there is no delay for reloading the first time.)
  1539. m_template = tmpl;
  1540. m_wslot = wslot;
  1541. m_status = OUT_OF_AMMO;
  1542. m_ammoInClip = 0;
  1543. m_whenWeCanFireAgain = 0;
  1544. m_whenPreAttackFinished = 0;
  1545. m_whenLastReloadStarted = 0;
  1546. m_projectileStreamID = INVALID_ID;
  1547. m_leechWeaponRangeActive = false;
  1548. m_pitchLimited = (m_template->getMinTargetPitch() > -PI || m_template->getMaxTargetPitch() < PI);
  1549. m_maxShotCount = NO_MAX_SHOTS_LIMIT;
  1550. m_curBarrel = 0;
  1551. m_numShotsForCurBarrel = m_template->getShotsPerBarrel();
  1552. m_lastFireFrame = 0;
  1553. m_suspendFXFrame = TheGameLogic->getFrame() + m_template->getSuspendFXDelay();
  1554. }
  1555. //-------------------------------------------------------------------------------------------------
  1556. Weapon::Weapon(const Weapon& that)
  1557. {
  1558. // Weapons lose all ammo when copied.
  1559. this->m_template = that.m_template;
  1560. this->m_wslot = that.m_wslot;
  1561. this->m_status = OUT_OF_AMMO;
  1562. this->m_ammoInClip = 0;
  1563. this->m_whenPreAttackFinished = 0;
  1564. this->m_whenLastReloadStarted = 0;
  1565. this->m_whenWeCanFireAgain = 0;
  1566. this->m_projectileStreamID = INVALID_ID;
  1567. this->m_leechWeaponRangeActive = false;
  1568. this->m_pitchLimited = (m_template->getMinTargetPitch() > -PI || m_template->getMaxTargetPitch() < PI);
  1569. this->m_maxShotCount = NO_MAX_SHOTS_LIMIT;
  1570. this->m_curBarrel = 0;
  1571. this->m_numShotsForCurBarrel = m_template->getShotsPerBarrel();
  1572. this->m_lastFireFrame = 0;
  1573. this->m_suspendFXFrame = that.getSuspendFXFrame();
  1574. }
  1575. //-------------------------------------------------------------------------------------------------
  1576. Weapon& Weapon::operator=(const Weapon& that)
  1577. {
  1578. if (this != &that)
  1579. {
  1580. // Weapons lose all ammo when copied.
  1581. this->m_template = that.m_template;
  1582. this->m_wslot = that.m_wslot;
  1583. this->m_status = OUT_OF_AMMO;
  1584. this->m_ammoInClip = 0;
  1585. this->m_whenPreAttackFinished = 0;
  1586. this->m_whenLastReloadStarted = 0;
  1587. this->m_whenWeCanFireAgain = 0;
  1588. this->m_leechWeaponRangeActive = false;
  1589. this->m_pitchLimited = (m_template->getMinTargetPitch() > -PI || m_template->getMaxTargetPitch() < PI);
  1590. this->m_maxShotCount = NO_MAX_SHOTS_LIMIT;
  1591. this->m_curBarrel = 0;
  1592. this->m_lastFireFrame = 0;
  1593. this->m_suspendFXFrame = that.getSuspendFXFrame();
  1594. this->m_numShotsForCurBarrel = m_template->getShotsPerBarrel();
  1595. this->m_projectileStreamID = INVALID_ID;
  1596. }
  1597. return *this;
  1598. }
  1599. //-------------------------------------------------------------------------------------------------
  1600. Weapon::~Weapon()
  1601. {
  1602. }
  1603. //-------------------------------------------------------------------------------------------------
  1604. void Weapon::computeBonus(const Object *source, WeaponBonusConditionFlags extraBonusFlags, WeaponBonus& bonus) const
  1605. {
  1606. bonus.clear();
  1607. WeaponBonusConditionFlags flags = source->getWeaponBonusCondition();
  1608. //CRCDEBUG_LOG(("Weapon::computeBonus() - flags are %X for %s\n", flags, DescribeObject(source).str()));
  1609. flags |= extraBonusFlags;
  1610. if( source->getContainedBy() )
  1611. {
  1612. // We may be able to add in our container's flags
  1613. const ContainModuleInterface *theirContain = source->getContainedBy()->getContain();
  1614. if( theirContain && theirContain->isWeaponBonusPassedToPassengers() )
  1615. flags |= theirContain->getWeaponBonusPassedToPassengers();
  1616. }
  1617. if (TheGlobalData->m_weaponBonusSet)
  1618. TheGlobalData->m_weaponBonusSet->appendBonuses(flags, bonus);
  1619. const WeaponBonusSet* extra = m_template->getExtraBonus();
  1620. if (extra)
  1621. extra->appendBonuses(flags, bonus);
  1622. }
  1623. //-------------------------------------------------------------------------------------------------
  1624. void Weapon::loadAmmoNow(const Object *sourceObj)
  1625. {
  1626. WeaponBonus bonus;
  1627. computeBonus(sourceObj, 0, bonus);
  1628. reloadWithBonus(sourceObj, bonus, true);
  1629. }
  1630. //-------------------------------------------------------------------------------------------------
  1631. void Weapon::reloadAmmo(const Object *sourceObj)
  1632. {
  1633. WeaponBonus bonus;
  1634. computeBonus(sourceObj, 0, bonus);
  1635. reloadWithBonus(sourceObj, bonus, false);
  1636. }
  1637. //-------------------------------------------------------------------------------------------------
  1638. Int Weapon::getClipReloadTime(const Object *source) const
  1639. {
  1640. WeaponBonus bonus;
  1641. computeBonus(source, 0, bonus);
  1642. return m_template->getClipReloadTime(bonus);
  1643. }
  1644. //-------------------------------------------------------------------------------------------------
  1645. void Weapon::setClipPercentFull(Real percent, Bool allowReduction)
  1646. {
  1647. if (m_template->getClipSize() == 0)
  1648. return;
  1649. Int ammo = REAL_TO_INT_FLOOR(m_template->getClipSize() * percent);
  1650. if (ammo > m_ammoInClip || (allowReduction && ammo < m_ammoInClip))
  1651. {
  1652. m_ammoInClip = ammo;
  1653. m_status = m_ammoInClip ? OUT_OF_AMMO : READY_TO_FIRE;
  1654. //CRCDEBUG_LOG(("Weapon::setClipPercentFull() just set m_status to %d (ammo in clip is %d)\n", m_status, m_ammoInClip));
  1655. m_whenLastReloadStarted = TheGameLogic->getFrame();
  1656. m_whenWeCanFireAgain = m_whenLastReloadStarted;
  1657. //CRCDEBUG_LOG(("Just set m_whenWeCanFireAgain to %d in Weapon::setClipPercentFull\n", m_whenWeCanFireAgain));
  1658. rebuildScatterTargets();
  1659. }
  1660. }
  1661. //-------------------------------------------------------------------------------------------------
  1662. void Weapon::rebuildScatterTargets()
  1663. {
  1664. m_scatterTargetsUnused.clear();
  1665. Int scatterTargetsCount = m_template->getScatterTargetsVector().size();
  1666. if (scatterTargetsCount)
  1667. {
  1668. // When I reload, I need to rebuild the list of ScatterTargets to shoot at.
  1669. for (Int targetIndex = 0; targetIndex < scatterTargetsCount; targetIndex++)
  1670. m_scatterTargetsUnused.push_back( targetIndex );
  1671. }
  1672. }
  1673. //-------------------------------------------------------------------------------------------------
  1674. void Weapon::reloadWithBonus(const Object *sourceObj, const WeaponBonus& bonus, Bool loadInstantly)
  1675. {
  1676. if (m_template->getClipSize() > 0
  1677. && m_ammoInClip == m_template->getClipSize()
  1678. && !sourceObj->isReloadTimeShared())
  1679. return; // don't restart our reload delay.
  1680. m_ammoInClip = m_template->getClipSize();
  1681. if (m_ammoInClip <= 0)
  1682. m_ammoInClip = 0x7fffffff; // 0 == unlimited (or effectively so)
  1683. m_status = RELOADING_CLIP;
  1684. Real reloadTime = loadInstantly ? 0 : m_template->getClipReloadTime(bonus);
  1685. m_whenLastReloadStarted = TheGameLogic->getFrame();
  1686. m_whenWeCanFireAgain = m_whenLastReloadStarted + reloadTime;
  1687. //CRCDEBUG_LOG(("Just set m_whenWeCanFireAgain to %d in Weapon::reloadWithBonus 1\n", m_whenWeCanFireAgain));
  1688. // if we are sharing reload times
  1689. // go through other weapons in weapon set
  1690. // set their m_whenWeCanFireAgain to this guy's delay
  1691. // set their m_status to this guy's status
  1692. if (sourceObj->isReloadTimeShared())
  1693. {
  1694. for (Int wt = 0; wt<WEAPONSLOT_COUNT; wt++)
  1695. {
  1696. Weapon *weapon = sourceObj->getWeaponInWeaponSlot((WeaponSlotType)wt);
  1697. if (weapon)
  1698. {
  1699. weapon->setPossibleNextShotFrame(m_whenWeCanFireAgain);
  1700. //CRCDEBUG_LOG(("Just set m_whenWeCanFireAgain to %d in Weapon::reloadWithBonus 2\n", m_whenWeCanFireAgain));
  1701. weapon->setStatus(RELOADING_CLIP);
  1702. }
  1703. }
  1704. }
  1705. rebuildScatterTargets();
  1706. }
  1707. //-------------------------------------------------------------------------------------------------
  1708. static void clipToTerrainExtent(Coord3D& approachTargetPos)
  1709. {
  1710. Region3D bounds;
  1711. TheTerrainLogic->getExtent(&bounds);
  1712. if (approachTargetPos.x < bounds.lo.x+PATHFIND_CELL_SIZE_F) {
  1713. approachTargetPos.x = bounds.lo.x+PATHFIND_CELL_SIZE_F;
  1714. }
  1715. if (approachTargetPos.y < bounds.lo.y+PATHFIND_CELL_SIZE_F) {
  1716. approachTargetPos.y = bounds.lo.y+PATHFIND_CELL_SIZE_F;
  1717. }
  1718. if (approachTargetPos.x > bounds.hi.x-PATHFIND_CELL_SIZE_F) {
  1719. approachTargetPos.x = bounds.hi.x-PATHFIND_CELL_SIZE_F;
  1720. }
  1721. if (approachTargetPos.y > bounds.hi.y-PATHFIND_CELL_SIZE_F) {
  1722. approachTargetPos.y = bounds.hi.y-PATHFIND_CELL_SIZE_F;
  1723. }
  1724. }
  1725. //-------------------------------------------------------------------------------------------------
  1726. void Weapon::onWeaponBonusChange(const Object *source)
  1727. {
  1728. // We are concerned with our reload times being off if our ROF just changed.
  1729. WeaponBonus bonus;
  1730. computeBonus(source, 0, bonus); // The middle arg is for projectiles to inherit damage bonus from launcher
  1731. Int newDelay;
  1732. Bool needUpdate = FALSE;
  1733. if( getStatus() == RELOADING_CLIP )
  1734. {
  1735. newDelay = m_template->getClipReloadTime(bonus);
  1736. needUpdate = TRUE;
  1737. }
  1738. else if( getStatus() == BETWEEN_FIRING_SHOTS )
  1739. {
  1740. newDelay = m_template->getDelayBetweenShots(bonus);
  1741. needUpdate = TRUE;
  1742. }
  1743. if( needUpdate )
  1744. {
  1745. m_whenLastReloadStarted = TheGameLogic->getFrame();
  1746. m_whenWeCanFireAgain = m_whenLastReloadStarted + newDelay;
  1747. if (source->isReloadTimeShared())
  1748. {
  1749. for (Int wt = 0; wt<WEAPONSLOT_COUNT; wt++)
  1750. {
  1751. Weapon *weapon = source->getWeaponInWeaponSlot((WeaponSlotType)wt);
  1752. if (weapon)
  1753. {
  1754. weapon->setPossibleNextShotFrame(m_whenWeCanFireAgain);
  1755. weapon->setStatus(RELOADING_CLIP);
  1756. }
  1757. }
  1758. }
  1759. }
  1760. }
  1761. //-------------------------------------------------------------------------------------------------
  1762. Bool Weapon::computeApproachTarget(const Object *source, const Object *target, const Coord3D *pos, Real angleOffset, Coord3D& approachTargetPos) const
  1763. {
  1764. // compute unit direction vector from us to our victim
  1765. const Coord3D *targetPos;
  1766. Coord3D dir;
  1767. if (target)
  1768. {
  1769. targetPos = target->getPosition();
  1770. ThePartitionManager->getVectorTo( target, source, ATTACK_RANGE_CALC_TYPE, dir );
  1771. }
  1772. else if (pos)
  1773. {
  1774. targetPos = pos;
  1775. ThePartitionManager->getVectorTo( source, pos, ATTACK_RANGE_CALC_TYPE, dir );
  1776. // Flip the vector to get from source to pos.
  1777. dir.x = -dir.x;
  1778. dir.y = -dir.y;
  1779. dir.z = -dir.z;
  1780. }
  1781. else
  1782. {
  1783. DEBUG_CRASH(("error"));
  1784. approachTargetPos.zero();
  1785. return false;
  1786. }
  1787. Real dist = dir.length();
  1788. Real minAttackRange = m_template->getMinimumAttackRange();
  1789. if (minAttackRange > PATHFIND_CELL_SIZE_F && dist < minAttackRange)
  1790. {
  1791. // We aret too close, so move away from the target.
  1792. DEBUG_ASSERTCRASH((minAttackRange<0.9f*getAttackRange(source)), ("Min attack range is too near attack range.\n"));
  1793. // Recompute dir, cause if the bounding spheres touch, it will be 0.
  1794. Coord3D srcPos = *source->getPosition();
  1795. dir.x = srcPos.x-targetPos->x;
  1796. dir.y = srcPos.y-targetPos->y;
  1797. #ifdef ATTACK_RANGE_IS_2D
  1798. dir.z = 0.0f;
  1799. #else
  1800. dir.z = srcPos.z-targetPos->z;
  1801. #endif
  1802. dir.normalize();
  1803. // if we're airborne and too close, just head for the opposite side.
  1804. if (source->isAboveTerrain())
  1805. {
  1806. // Don't do a 180 degree turn.
  1807. Real angle = atan2(-dir.y, -dir.x);
  1808. Real relAngle = source->getOrientation()- angle;
  1809. if (relAngle>2*PI) relAngle -= 2*PI;
  1810. if (relAngle<-2*PI) relAngle += 2*PI;
  1811. if (fabs(relAngle)<PI/2) {
  1812. dir.x = -dir.x;
  1813. dir.y = -dir.y;
  1814. dir.z = -dir.z;
  1815. }
  1816. }
  1817. if (angleOffset != 0.0f)
  1818. {
  1819. Real angle = atan2(dir.y, dir.x);
  1820. dir.x = (Real)Cos(angle + angleOffset);
  1821. dir.y = (Real)Sin(angle + angleOffset);
  1822. }
  1823. // select a spot along the line between us, halfway between the min & max range.
  1824. Real attackRange = (getAttackRange(source) + minAttackRange)/2.0f;
  1825. #ifdef ATTACK_RANGE_IS_2D
  1826. if (target)
  1827. attackRange += target->getGeometryInfo().getBoundingCircleRadius();
  1828. attackRange += source->getGeometryInfo().getBoundingCircleRadius();
  1829. #else
  1830. if (target)
  1831. attackRange += target->getGeometryInfo().getBoundingSphereRadius();
  1832. attackRange += source->getGeometryInfo().getBoundingSphereRadius();
  1833. #endif
  1834. approachTargetPos.x = attackRange * dir.x + targetPos->x;
  1835. approachTargetPos.y = attackRange * dir.y + targetPos->y;
  1836. approachTargetPos.z = attackRange * dir.z + targetPos->z;
  1837. ///@todo - make sure we can get to the approach position.
  1838. clipToTerrainExtent(approachTargetPos);
  1839. return false;
  1840. }
  1841. const Real FUDGE = 0.001f;
  1842. if (dist < FUDGE)
  1843. {
  1844. // we're close enough!
  1845. approachTargetPos = *source->getPosition();
  1846. return true;
  1847. }
  1848. else
  1849. {
  1850. if (isContactWeapon())
  1851. {
  1852. // Weapon is basically a contact weapon, like a car bomb. The approach target logic
  1853. // has been modified to let it approach the object, so just return the target position. jba.
  1854. approachTargetPos = *targetPos;
  1855. return false;
  1856. }
  1857. dir.x /= dist;
  1858. dir.y /= dist;
  1859. dir.z /= dist;
  1860. if (angleOffset != 0.0f)
  1861. {
  1862. Real angle = atan2(dir.y, dir.x);
  1863. dir.x = (Real)Cos(angle + angleOffset);
  1864. dir.y = (Real)Sin(angle + angleOffset);
  1865. }
  1866. // select a spot along the line between us, in range of our weapon
  1867. const Real ATTACK_RANGE_APPROACH_FUDGE = 0.9f;
  1868. Real attackRange = getAttackRange(source) * ATTACK_RANGE_APPROACH_FUDGE;
  1869. approachTargetPos.x = attackRange * dir.x + targetPos->x;
  1870. approachTargetPos.y = attackRange * dir.y + targetPos->y;
  1871. approachTargetPos.z = attackRange * dir.z + targetPos->z;
  1872. if (source->getAI() && source->getAI()->isAircraftThatAdjustsDestination()) {
  1873. // Adjust the target so that we are not stacked atop another aircraft.
  1874. TheAI->pathfinder()->adjustTargetDestination(source, target, pos, this, &approachTargetPos);
  1875. }
  1876. return false;
  1877. }
  1878. }
  1879. //-------------------------------------------------------------------------------------------------
  1880. //Special case attack range calculate that fakes moving the object (to a garrisoned point) without
  1881. //actually moving the object. This is used to help determine if a garrisoned unit not yet
  1882. //positioned can attack someone.
  1883. //-------------------------------------------------------------------------------------------------
  1884. Bool Weapon::isSourceObjectWithGoalPositionWithinAttackRange( const Object *source, const Coord3D *goalPos, const Object *target, const Coord3D *targetPos ) const
  1885. {
  1886. Real distSqr;
  1887. if( target )
  1888. distSqr = ThePartitionManager->getGoalDistanceSquared( source, goalPos, target, ATTACK_RANGE_CALC_TYPE );
  1889. else if( targetPos )
  1890. distSqr = ThePartitionManager->getGoalDistanceSquared( source, goalPos, targetPos, ATTACK_RANGE_CALC_TYPE );
  1891. else
  1892. return false;
  1893. Real attackRangeSqr = sqr( getAttackRange( source ) );
  1894. Real minAttackRangeSqr = sqr(m_template->getMinimumAttackRange());
  1895. #ifdef RATIONALIZE_ATTACK_RANGE
  1896. if (distSqr < minAttackRangeSqr)
  1897. #else
  1898. if (distSqr < minAttackRangeSqr-0.5f)
  1899. #endif
  1900. {
  1901. return false;
  1902. }
  1903. return (distSqr <= attackRangeSqr);
  1904. }
  1905. //-------------------------------------------------------------------------------------------------
  1906. Bool Weapon::isWithinAttackRange(const Object *source, const Coord3D* pos) const
  1907. {
  1908. Real distSqr = ThePartitionManager->getDistanceSquared( source, pos, ATTACK_RANGE_CALC_TYPE );
  1909. Real attackRangeSqr = sqr(getAttackRange(source));
  1910. Real minAttackRangeSqr = sqr(m_template->getMinimumAttackRange());
  1911. #ifdef RATIONALIZE_ATTACK_RANGE
  1912. if (distSqr < minAttackRangeSqr)
  1913. #else
  1914. if (distSqr < minAttackRangeSqr-0.5f)
  1915. #endif
  1916. {
  1917. return false;
  1918. }
  1919. return (distSqr <= attackRangeSqr);
  1920. }
  1921. //-------------------------------------------------------------------------------------------------
  1922. Bool Weapon::isWithinAttackRange(const Object *source, const Object *target) const
  1923. {
  1924. Real distSqr;
  1925. Real attackRangeSqr = sqr(getAttackRange(source));
  1926. if( !target->isKindOf(KINDOF_BRIDGE) )
  1927. {
  1928. distSqr = ThePartitionManager->getDistanceSquared( source, target, ATTACK_RANGE_CALC_TYPE );
  1929. }
  1930. else
  1931. {
  1932. // Special case - bridges have two attackable points at either end.
  1933. TBridgeAttackInfo info;
  1934. TheTerrainLogic->getBridgeAttackPoints(target, &info);
  1935. distSqr = ThePartitionManager->getDistanceSquared( source, &info.attackPoint1, ATTACK_RANGE_CALC_TYPE );
  1936. if (distSqr>attackRangeSqr)
  1937. {
  1938. // Try the other one.
  1939. distSqr = ThePartitionManager->getDistanceSquared( source, &info.attackPoint2, ATTACK_RANGE_CALC_TYPE );
  1940. }
  1941. }
  1942. Real minAttackRangeSqr = sqr(m_template->getMinimumAttackRange());
  1943. #ifdef RATIONALIZE_ATTACK_RANGE
  1944. if (distSqr < minAttackRangeSqr)
  1945. #else
  1946. if (distSqr < minAttackRangeSqr-0.5f)
  1947. #endif
  1948. {
  1949. // too close. can't attack.
  1950. return false;
  1951. }
  1952. if( distSqr <= attackRangeSqr )
  1953. {
  1954. // Note - only compare contact weapons with structures. If you do the collision check
  1955. // against vehicles, the attacker may get close enough to the vehicle to get crushed
  1956. // before it fires its weapon. jba.
  1957. if( isContactWeapon() && target->isKindOf(KINDOF_STRUCTURE))
  1958. {
  1959. //We're close enough to fire off ranged weapons -- but in the case of contact weapons
  1960. //we want to do a more detailed check to see if we're actually colliding with the target.
  1961. ObjectIterator *iter = ThePartitionManager->iteratePotentialCollisions( source->getPosition(), source->getGeometryInfo(), 0.0f );
  1962. MemoryPoolObjectHolder hold( iter );
  1963. for( Object *them = iter->first(); them; them = iter->next() )
  1964. {
  1965. if( target == them )
  1966. {
  1967. return true;
  1968. }
  1969. }
  1970. return false;
  1971. }
  1972. return true;
  1973. }
  1974. return false;
  1975. }
  1976. //-------------------------------------------------------------------------------------------------
  1977. Bool Weapon::isTooClose(const Object *source, const Object *target) const
  1978. {
  1979. Real minAttackRange = m_template->getMinimumAttackRange();
  1980. if (minAttackRange == 0.0f)
  1981. return false;
  1982. Real distSqr = ThePartitionManager->getDistanceSquared( source, target, ATTACK_RANGE_CALC_TYPE );
  1983. if (distSqr < sqr(minAttackRange))
  1984. {
  1985. return true;
  1986. }
  1987. return false;
  1988. }
  1989. //-------------------------------------------------------------------------------------------------
  1990. Bool Weapon::isTooClose( const Object *source, const Coord3D *pos ) const
  1991. {
  1992. Real minAttackRange = m_template->getMinimumAttackRange();
  1993. if (minAttackRange == 0.0f)
  1994. return false;
  1995. Real distSqr = ThePartitionManager->getDistanceSquared( source, pos, ATTACK_RANGE_CALC_TYPE );
  1996. if (distSqr < sqr(minAttackRange))
  1997. {
  1998. return true;
  1999. }
  2000. return false;
  2001. }
  2002. //-------------------------------------------------------------------------------------------------
  2003. Bool Weapon::isGoalPosWithinAttackRange(const Object *source, const Coord3D* goalPos, const Object *target, const Coord3D* targetPos) const
  2004. {
  2005. Real distSqr;
  2006. // Note - undersize by 1/4 of a pathfind cell, so that the goal is not teetering on the edge
  2007. // of firing range. jba.
  2008. // Note 2 - even with RATIONALIZE_ATTACK_RANGE, we still need to subtract 1/4 of a pathfind cell,
  2009. // otherwise if it teters on the edge, attacks can fail. jba.
  2010. Real attackRangeSqr = sqr(getAttackRange(source)-(PATHFIND_CELL_SIZE_F*0.25f));
  2011. if (target != NULL)
  2012. {
  2013. if (target->isKindOf(KINDOF_BRIDGE))
  2014. {
  2015. // Special case - bridges have two attackable points at either end.
  2016. TBridgeAttackInfo info;
  2017. TheTerrainLogic->getBridgeAttackPoints(target, &info);
  2018. distSqr = ThePartitionManager->getGoalDistanceSquared( source, goalPos, &info.attackPoint1, ATTACK_RANGE_CALC_TYPE );
  2019. if (distSqr>attackRangeSqr)
  2020. {
  2021. // Try the other one.
  2022. distSqr = ThePartitionManager->getGoalDistanceSquared( source, goalPos, &info.attackPoint2, ATTACK_RANGE_CALC_TYPE );
  2023. }
  2024. }
  2025. else
  2026. {
  2027. distSqr = ThePartitionManager->getGoalDistanceSquared( source, goalPos, target, ATTACK_RANGE_CALC_TYPE );
  2028. }
  2029. }
  2030. else
  2031. {
  2032. distSqr = ThePartitionManager->getGoalDistanceSquared( source, goalPos, targetPos, ATTACK_RANGE_CALC_TYPE );
  2033. }
  2034. // Note - oversize by 1/4 of a pathfind cell, so that the goal is not teetering on the edge
  2035. // of firing range. jba.
  2036. // Note 2 - even with RATIONALIZE_ATTACK_RANGE, we still need to add 1/4 of a pathfind cell,
  2037. // otherwise if it teters on the edge, attacks can fail. jba.
  2038. Real minAttackRangeSqr = sqr(m_template->getMinimumAttackRange()+(PATHFIND_CELL_SIZE_F*0.25f));
  2039. #ifdef RATIONALIZE_ATTACK_RANGE
  2040. if (distSqr < minAttackRangeSqr)
  2041. #else
  2042. if (distSqr < minAttackRangeSqr-0.5f)
  2043. #endif
  2044. {
  2045. return false;
  2046. }
  2047. return (distSqr <= attackRangeSqr);
  2048. }
  2049. //-------------------------------------------------------------------------------------------------
  2050. Real Weapon::getPercentReadyToFire() const
  2051. {
  2052. switch (getStatus())
  2053. {
  2054. case OUT_OF_AMMO:
  2055. case PRE_ATTACK:
  2056. return 0.0f;
  2057. case READY_TO_FIRE:
  2058. return 1.0f;
  2059. case BETWEEN_FIRING_SHOTS:
  2060. case RELOADING_CLIP:
  2061. {
  2062. UnsignedInt now = TheGameLogic->getFrame();
  2063. UnsignedInt nextShot = getPossibleNextShotFrame();
  2064. DEBUG_ASSERTCRASH(now >= m_whenLastReloadStarted, ("now >= m_whenLastReloadStarted"));
  2065. if (now >= nextShot)
  2066. return 1.0f;
  2067. DEBUG_ASSERTCRASH(nextShot >= m_whenLastReloadStarted, ("nextShot >= m_whenLastReloadStarted"));
  2068. UnsignedInt totalTime = nextShot - m_whenLastReloadStarted;
  2069. if (totalTime == 0)
  2070. {
  2071. return 1.0f;
  2072. }
  2073. UnsignedInt timeLeft = nextShot - now;
  2074. DEBUG_ASSERTCRASH(timeLeft <= totalTime, ("timeLeft <= totalTime"));
  2075. UnsignedInt timeSoFar = totalTime - timeLeft;
  2076. if (timeSoFar >= totalTime)
  2077. {
  2078. return 1.0f;
  2079. }
  2080. else
  2081. {
  2082. return (Real)timeSoFar / (Real)totalTime;
  2083. }
  2084. }
  2085. }
  2086. DEBUG_CRASH(("should not get here"));
  2087. return 0.0f;
  2088. }
  2089. //-------------------------------------------------------------------------------------------------
  2090. Real Weapon::getAttackRange(const Object *source) const
  2091. {
  2092. WeaponBonus bonus;
  2093. computeBonus(source, 0, bonus);
  2094. return m_template->getAttackRange(bonus);
  2095. //Contained objects have longer ranges.
  2096. //const Object *container = source->getContainedBy();
  2097. //if( container )
  2098. //{
  2099. // attackRange += container->getGeometryInfo().getBoundingCircleRadius();
  2100. //}
  2101. //return attackRange;
  2102. }
  2103. //-------------------------------------------------------------------------------------------------
  2104. Real Weapon::getAttackDistance(const Object *source, const Object *victimObj, const Coord3D* victimPos) const
  2105. {
  2106. Real range = getAttackRange(source);
  2107. if (victimObj != NULL)
  2108. {
  2109. #ifdef ATTACK_RANGE_IS_2D
  2110. range += source->getGeometryInfo().getBoundingCircleRadius();
  2111. range += victimObj->getGeometryInfo().getBoundingCircleRadius();
  2112. #else
  2113. range += source->getGeometryInfo().getBoundingSphereRadius();
  2114. range += victimObj->getGeometryInfo().getBoundingSphereRadius();
  2115. #endif
  2116. }
  2117. return range;
  2118. }
  2119. //-------------------------------------------------------------------------------------------------
  2120. Real Weapon::estimateWeaponDamage(const Object *sourceObj, const Object *victimObj, const Coord3D* victimPos)
  2121. {
  2122. if (!m_template)
  2123. return 0.0f;
  2124. // if the weapon is just reloading, it's ok. if it's out of ammo
  2125. // (and won't autoreload), then we aren't gonna do any damage.
  2126. if (getStatus() == OUT_OF_AMMO && !m_template->getAutoReloadsClip())
  2127. return 0.0f;
  2128. WeaponBonus bonus;
  2129. computeBonus(sourceObj, 0, bonus);
  2130. return m_template->estimateWeaponTemplateDamage(sourceObj, victimObj, victimPos, bonus);
  2131. }
  2132. //-------------------------------------------------------------------------------------------------
  2133. void Weapon::newProjectileFired(const Object *sourceObj, const Object *projectile, const Object *victimObj, const Coord3D *victimPos )
  2134. {
  2135. // If I have a stream, I need to tell it about this new guy
  2136. if( m_template->getProjectileStreamName().isEmpty() )
  2137. return; // nope, no streak logic to do
  2138. Object* projectileStream = TheGameLogic->findObjectByID(m_projectileStreamID);
  2139. if( projectileStream == NULL )
  2140. {
  2141. m_projectileStreamID = INVALID_ID; // reset, since it might have been "valid" but deleted out from under us
  2142. const ThingTemplate* pst = TheThingFactory->findTemplate(m_template->getProjectileStreamName());
  2143. projectileStream = TheThingFactory->newObject( pst, sourceObj->getControllingPlayer()->getDefaultTeam() );
  2144. if( projectileStream == NULL )
  2145. return;
  2146. m_projectileStreamID = projectileStream->getID();
  2147. }
  2148. //Check for projectile stream update
  2149. static NameKeyType key_ProjectileStreamUpdate = NAMEKEY("ProjectileStreamUpdate");
  2150. ProjectileStreamUpdate* update = (ProjectileStreamUpdate*)projectileStream->findUpdateModule(key_ProjectileStreamUpdate);
  2151. if( update )
  2152. {
  2153. update->setPosition( sourceObj->getPosition() );
  2154. update->addProjectile( sourceObj->getID(), projectile->getID(), victimObj ? victimObj->getID() : INVALID_ID, victimPos );
  2155. return;
  2156. }
  2157. }
  2158. //-------------------------------------------------------------------------------------------------
  2159. void Weapon::createLaser( const Object *sourceObj, const Object *victimObj, const Coord3D *victimPos )
  2160. {
  2161. const ThingTemplate* pst = TheThingFactory->findTemplate(m_template->getLaserName());
  2162. if( !pst )
  2163. {
  2164. DEBUG_CRASH( ("Weapon::createLaser(). %s could not find template for its laser %s.",
  2165. sourceObj->getTemplate()->getName().str(), m_template->getLaserName().str() ) );
  2166. return;
  2167. }
  2168. Object* laser = TheThingFactory->newObject( pst, sourceObj->getControllingPlayer()->getDefaultTeam() );
  2169. if( laser == NULL )
  2170. return;
  2171. // Give it a good basis in reality to ensure it can draw when on screen.
  2172. laser->setPosition(sourceObj->getPosition());
  2173. //Check for laser update
  2174. Drawable *draw = laser->getDrawable();
  2175. if( draw )
  2176. {
  2177. static NameKeyType key_LaserUpdate = NAMEKEY( "LaserUpdate" );
  2178. LaserUpdate *update = (LaserUpdate*)draw->findClientUpdateModule( key_LaserUpdate );
  2179. if( update )
  2180. {
  2181. Coord3D pos = *victimPos;
  2182. if( victimObj && !victimObj->isKindOf( KINDOF_PROJECTILE ) && !victimObj->isAirborneTarget() )
  2183. {
  2184. //Targets are positioned on the ground, so raise the beam up so we're not shooting their feet.
  2185. //Projectiles are a different story, target their exact position.
  2186. pos.z += 10.0f;
  2187. }
  2188. update->initLaser( sourceObj, victimObj, sourceObj->getPosition(), &pos, m_template->getLaserBoneName() );
  2189. }
  2190. }
  2191. }
  2192. //-------------------------------------------------------------------------------------------------
  2193. // return true if we auto-reloaded our clip after firing.
  2194. //DECLARE_PERF_TIMER(fireWeapon)
  2195. Bool Weapon::privateFireWeapon(
  2196. const Object *sourceObj,
  2197. Object *victimObj,
  2198. const Coord3D* victimPos,
  2199. Bool isProjectileDetonation,
  2200. Bool ignoreRanges,
  2201. WeaponBonusConditionFlags extraBonusFlags,
  2202. ObjectID* projectileID,
  2203. Bool inflictDamage
  2204. )
  2205. {
  2206. //CRCDEBUG_LOG(("Weapon::privateFireWeapon() for %s\n", DescribeObject(sourceObj).str()));
  2207. //USE_PERF_TIMER(fireWeapon)
  2208. if (projectileID)
  2209. *projectileID = INVALID_ID;
  2210. if (!m_template)
  2211. return false;
  2212. // If we are a networked weapon, tell everyone nearby they might want to get in on this shot
  2213. if( m_template->getRequestAssistRange() && victimObj )
  2214. processRequestAssistance( sourceObj, victimObj );
  2215. //For weapon templates that have the leech range weapon flag set, it essentially grants
  2216. //the weapon unlimited range for the remainder of the attack. While it's triggered here
  2217. //it's the AIAttackState machine that actually uses and resets this value.
  2218. //This makes the ASSUMPTION that it is IMPOSSIBLE TO FIRE A WEAPON WITHOUT BEING IN AN AIATTACKSTATE
  2219. //
  2220. // @todo srj -- this isn't a universally true assertion! eg, FireWeaponDie lets you do this easily.
  2221. //
  2222. if( m_template->isLeechRangeWeapon() )
  2223. {
  2224. setLeechRangeActive( TRUE );
  2225. }
  2226. //Special case damge type overrides requiring special handling.
  2227. switch( m_template->getDamageType() )
  2228. {
  2229. case DAMAGE_DEPLOY:
  2230. {
  2231. const AIUpdateInterface *ai = sourceObj->getAI();
  2232. if( ai )
  2233. {
  2234. const AssaultTransportAIInterface *atInterface = ai->getAssaultTransportAIInterface();
  2235. if( atInterface )
  2236. {
  2237. atInterface->beginAssault( victimObj );
  2238. }
  2239. }
  2240. break;
  2241. }
  2242. case DAMAGE_DISARM:
  2243. {
  2244. if (sourceObj && victimObj)
  2245. {
  2246. Bool found = false;
  2247. for (BehaviorModule** bmi = victimObj->getBehaviorModules(); *bmi; ++bmi)
  2248. {
  2249. LandMineInterface* lmi = (*bmi)->getLandMineInterface();
  2250. if (lmi)
  2251. {
  2252. VeterancyLevel v = sourceObj->getVeterancyLevel();
  2253. FXList::doFXPos(m_template->getFireFX(v), victimObj->getPosition(), victimObj->getTransformMatrix(), 0, victimObj->getPosition(), 0);
  2254. lmi->disarm();
  2255. found = true;
  2256. break;
  2257. }
  2258. }
  2259. // it's a mine, but doesn't have LandMineInterface...
  2260. if( !found && victimObj->isKindOf( KINDOF_MINE ) || victimObj->isKindOf( KINDOF_BOOBY_TRAP ) || victimObj->isKindOf( KINDOF_DEMOTRAP ) )
  2261. {
  2262. VeterancyLevel v = sourceObj->getVeterancyLevel();
  2263. FXList::doFXPos(m_template->getFireFX(v), victimObj->getPosition(), victimObj->getTransformMatrix(), 0, victimObj->getPosition(), 0);
  2264. TheGameLogic->destroyObject( victimObj );// douse this thing before somebody gets hurt!
  2265. found = true;
  2266. }
  2267. if( found )
  2268. {
  2269. sourceObj->getControllingPlayer()->getAcademyStats()->recordMineCleared();
  2270. }
  2271. }
  2272. --m_maxShotCount;
  2273. --m_ammoInClip; // so we can use the delay between shots on the mine clearing weapon
  2274. if (m_ammoInClip <= 0 && m_template->getAutoReloadsClip())
  2275. {
  2276. reloadAmmo(sourceObj);
  2277. return TRUE; // reloaded
  2278. }
  2279. else
  2280. {
  2281. return FALSE; // did not reload
  2282. }
  2283. }
  2284. case DAMAGE_HACK:
  2285. {
  2286. //We're using a hacker unit to hack a target. Hacking has various effects and
  2287. //instead of inflicting damage, we are waiting for a period of time until the hack takes effect.
  2288. //return FALSE;
  2289. }
  2290. }
  2291. WeaponBonus bonus;
  2292. computeBonus(sourceObj, extraBonusFlags, bonus);
  2293. DEBUG_ASSERTCRASH(getStatus() != OUT_OF_AMMO, ("Hmm, firing weapon that is OUT_OF_AMMO"));
  2294. DEBUG_ASSERTCRASH(getStatus() == READY_TO_FIRE, ("Hmm, Weapon is firing more often than should be possible"));
  2295. DEBUG_ASSERTCRASH(m_ammoInClip > 0, ("Hmm, firing an empty weapon"));
  2296. if (getStatus() != READY_TO_FIRE)
  2297. return false;
  2298. UnsignedInt now = TheGameLogic->getFrame();
  2299. Bool reloaded = false;
  2300. if (m_ammoInClip > 0)
  2301. {
  2302. Int barrelCount = sourceObj->getDrawable()->getBarrelCount(m_wslot);
  2303. if (m_curBarrel >= barrelCount)
  2304. {
  2305. m_curBarrel = 0;
  2306. m_numShotsForCurBarrel = m_template->getShotsPerBarrel();
  2307. }
  2308. if( m_scatterTargetsUnused.size() )
  2309. {
  2310. // If I have a set scatter pattern, I need to offset the target by a random pick from that pattern
  2311. if( victimObj )
  2312. {
  2313. victimPos = victimObj->getPosition();
  2314. victimObj = NULL;
  2315. }
  2316. Coord3D targetPos = *victimPos; // need to copy, as this pointer is actually inside somebody potentially
  2317. Int randomPick = GameLogicRandomValue( 0, m_scatterTargetsUnused.size() - 1 );
  2318. Int targetIndex = m_scatterTargetsUnused[randomPick];
  2319. Real scatterTargetScalar = getScatterTargetScalar();// essentially a radius, but operates only on this scatterTarget table
  2320. Coord2D scatterOffset = m_template->getScatterTargetsVector().at( targetIndex );
  2321. scatterOffset.x *= scatterTargetScalar;
  2322. scatterOffset.y *= scatterTargetScalar;
  2323. targetPos.x += scatterOffset.x;
  2324. targetPos.y += scatterOffset.y;
  2325. targetPos.z = TheTerrainLogic->getGroundHeight(targetPos.x, targetPos.y);
  2326. // To erase from a vector, put the last on the one you used and pop the back.
  2327. m_scatterTargetsUnused[randomPick] = m_scatterTargetsUnused.back();
  2328. m_scatterTargetsUnused.pop_back();
  2329. m_template->fireWeaponTemplate(sourceObj, m_wslot, m_curBarrel, victimObj, &targetPos, bonus, isProjectileDetonation, ignoreRanges, this, projectileID, inflictDamage );
  2330. }
  2331. else
  2332. {
  2333. m_template->fireWeaponTemplate(sourceObj, m_wslot, m_curBarrel, victimObj, victimPos, bonus, isProjectileDetonation, ignoreRanges, this, projectileID, inflictDamage );
  2334. }
  2335. m_lastFireFrame = now;
  2336. --m_ammoInClip;
  2337. --m_maxShotCount;
  2338. --m_numShotsForCurBarrel;
  2339. if (m_numShotsForCurBarrel <= 0)
  2340. {
  2341. ++m_curBarrel;
  2342. m_numShotsForCurBarrel = m_template->getShotsPerBarrel();
  2343. }
  2344. if (m_ammoInClip <= 0)
  2345. {
  2346. if (m_template->getAutoReloadsClip())
  2347. {
  2348. reloadAmmo(sourceObj);
  2349. reloaded = true;
  2350. }
  2351. else
  2352. {
  2353. m_status = OUT_OF_AMMO;
  2354. m_whenWeCanFireAgain = 0x7fffffff;
  2355. //CRCDEBUG_LOG(("Just set m_whenWeCanFireAgain to %d in Weapon::privateFireWeapon 1\n", m_whenWeCanFireAgain));
  2356. }
  2357. }
  2358. else
  2359. {
  2360. m_status = BETWEEN_FIRING_SHOTS;
  2361. //CRCDEBUG_LOG(("Weapon::privateFireWeapon() just set m_status to BETWEEN_FIRING_SHOTS\n"));
  2362. Int delay = m_template->getDelayBetweenShots(bonus);
  2363. m_whenLastReloadStarted = now;
  2364. m_whenWeCanFireAgain = now + delay;
  2365. //CRCDEBUG_LOG(("Just set m_whenWeCanFireAgain to %d (delay is %d) in Weapon::privateFireWeapon\n", m_whenWeCanFireAgain, delay));
  2366. // if we are sharing reload times
  2367. // go through other weapons in weapon set
  2368. // set their m_whenWeCanFireAgain to this guy's delay
  2369. // set their m_status to this guy's status
  2370. if ( sourceObj->isReloadTimeShared() )
  2371. {
  2372. for (Int wt = 0; wt<WEAPONSLOT_COUNT; wt++)
  2373. {
  2374. Weapon *weapon = sourceObj->getWeaponInWeaponSlot((WeaponSlotType)wt);
  2375. if (weapon)
  2376. {
  2377. weapon->setPossibleNextShotFrame(m_whenWeCanFireAgain);
  2378. //CRCDEBUG_LOG(("Just set m_whenWeCanFireAgain to %d in Weapon::privateFireWeapon 3\n", m_whenWeCanFireAgain));
  2379. weapon->setStatus(BETWEEN_FIRING_SHOTS);
  2380. }
  2381. }
  2382. }
  2383. }
  2384. }
  2385. return reloaded;
  2386. }
  2387. //-------------------------------------------------------------------------------------------------
  2388. void Weapon::preFireWeapon( const Object *source, const Object *victim )
  2389. {
  2390. Int delay = getPreAttackDelay( source, victim );
  2391. if( delay > 0 )
  2392. {
  2393. setStatus( PRE_ATTACK );
  2394. setPreAttackFinishedFrame( TheGameLogic->getFrame() + delay );
  2395. if( m_template->isLeechRangeWeapon() )
  2396. {
  2397. setLeechRangeActive( TRUE );
  2398. }
  2399. }
  2400. }
  2401. //-------------------------------------------------------------------------------------------------
  2402. Bool Weapon::fireWeapon(const Object *source, Object *target, ObjectID* projectileID)
  2403. {
  2404. //CRCDEBUG_LOG(("Weapon::fireWeapon() for %s at %s\n", DescribeObject(source).str(), DescribeObject(target).str()));
  2405. return privateFireWeapon( source, target, NULL, false, false, 0, projectileID, TRUE );
  2406. }
  2407. //-------------------------------------------------------------------------------------------------
  2408. // return true if we auto-reloaded our clip after firing.
  2409. Bool Weapon::fireWeapon(const Object *source, const Coord3D* pos, ObjectID* projectileID)
  2410. {
  2411. //CRCDEBUG_LOG(("Weapon::fireWeapon() for %s\n", DescribeObject(source).str()));
  2412. return privateFireWeapon( source, NULL, pos, false, false, 0, projectileID, TRUE );
  2413. }
  2414. //-------------------------------------------------------------------------------------------------
  2415. void Weapon::fireProjectileDetonationWeapon(const Object *source, Object *target, WeaponBonusConditionFlags extraBonusFlags, Bool inflictDamage )
  2416. {
  2417. //CRCDEBUG_LOG(("Weapon::fireProjectileDetonationWeapon() for %sat %s\n", DescribeObject(source).str(), DescribeObject(target).str()));
  2418. privateFireWeapon( source, target, NULL, true, false, extraBonusFlags, NULL, inflictDamage );
  2419. }
  2420. //-------------------------------------------------------------------------------------------------
  2421. void Weapon::fireProjectileDetonationWeapon(const Object *source, const Coord3D* pos, WeaponBonusConditionFlags extraBonusFlags, Bool inflictDamage )
  2422. {
  2423. //CRCDEBUG_LOG(("Weapon::fireProjectileDetonationWeapon() for %s\n", DescribeObject(source).str()));
  2424. privateFireWeapon( source, NULL, pos, true, false, extraBonusFlags, NULL, inflictDamage );
  2425. }
  2426. //-------------------------------------------------------------------------------------------------
  2427. //Currently, this function was added to allow a script to force fire a weapon,
  2428. //and immediately gain control of the weapon that was fired to give it special orders...
  2429. Object* Weapon::forceFireWeapon( const Object *source, const Coord3D *pos)
  2430. {
  2431. //CRCDEBUG_LOG(("Weapon::forceFireWeapon() for %s\n", DescribeObject(source).str()));
  2432. //Force the ammo to load instantly.
  2433. //loadAmmoNow( source );
  2434. //Fire the weapon at the position. Internally, it'll store the weapon projectile ID if so created.
  2435. ObjectID projectileID = INVALID_ID;
  2436. const Bool ignoreRange = true;
  2437. privateFireWeapon(source, NULL, pos, false, ignoreRange, NULL, &projectileID, TRUE );
  2438. return TheGameLogic->findObjectByID( projectileID );
  2439. }
  2440. //-------------------------------------------------------------------------------------------------
  2441. WeaponStatus Weapon::getStatus() const
  2442. {
  2443. UnsignedInt now = TheGameLogic->getFrame();
  2444. if( now < m_whenPreAttackFinished )
  2445. {
  2446. return PRE_ATTACK;
  2447. }
  2448. if( now >= m_whenWeCanFireAgain )
  2449. {
  2450. if (m_ammoInClip > 0)
  2451. m_status = READY_TO_FIRE;
  2452. else
  2453. m_status = OUT_OF_AMMO;
  2454. //CRCDEBUG_LOG(("Weapon::getStatus() just set m_status to %d (ammo in clip is %d)\n", m_status, m_ammoInClip));
  2455. }
  2456. return m_status;
  2457. }
  2458. //-------------------------------------------------------------------------------------------------
  2459. Bool Weapon::isWithinTargetPitch(const Object *source, const Object *victim) const
  2460. {
  2461. if (isContactWeapon() || !isPitchLimited())
  2462. return true;
  2463. const Coord3D* src = source->getPosition();
  2464. const Coord3D* dst = victim->getPosition();
  2465. const Real ACCCEPTABLE_DZ = 10.0f;
  2466. if (fabs(dst->z - src->z) < ACCCEPTABLE_DZ)
  2467. return true; // always good enough if dz is small, regardless of pitch
  2468. Real minPitch, maxPitch;
  2469. source->getGeometryInfo().calcPitches(*src, victim->getGeometryInfo(), *dst, minPitch, maxPitch);
  2470. // if there's any intersection between the the two pitch ranges, we're good to go.
  2471. if ((minPitch >= m_template->getMinTargetPitch() && minPitch <= m_template->getMaxTargetPitch()) ||
  2472. (maxPitch >= m_template->getMinTargetPitch() && maxPitch <= m_template->getMaxTargetPitch()) ||
  2473. (minPitch <= m_template->getMinTargetPitch() && maxPitch >= m_template->getMaxTargetPitch()))
  2474. return true;
  2475. //DEBUG_LOG(("pitch %f-%f is out of range\n",rad2deg(minPitch),rad2deg(maxPitch),rad2deg(m_template->getMinTargetPitch()),rad2deg(m_template->getMaxTargetPitch())));
  2476. return false;
  2477. }
  2478. //-------------------------------------------------------------------------------------------------
  2479. Real Weapon::getPrimaryDamageRadius(const Object *source) const
  2480. {
  2481. WeaponBonus bonus;
  2482. computeBonus(source, 0, bonus);
  2483. return m_template->getPrimaryDamageRadius(bonus);
  2484. }
  2485. //-------------------------------------------------------------------------------------------------
  2486. Bool Weapon::isDamageWeapon() const
  2487. {
  2488. //These damage types are special attacks that don't do damage directly, even
  2489. //if they can indirectly. These are here to prevent the UI from allowing the
  2490. //user to mouseover a target and think it can attack it using these types.
  2491. switch( m_template->getDamageType() )
  2492. {
  2493. case DAMAGE_DEPLOY:
  2494. //Kris @todo
  2495. //Evaluate a better way to handle this weapon type... doesn't fit being a damage weapon.
  2496. //May want to check if cargo can attack!
  2497. return TRUE;
  2498. case DAMAGE_DISARM:
  2499. return TRUE; // hmm, can only "damage" mines, but still...
  2500. case DAMAGE_HACK:
  2501. return FALSE;
  2502. }
  2503. //Use no bonus
  2504. WeaponBonus whoCares;
  2505. if( m_template->getPrimaryDamage( whoCares ) > 0.0f || m_template->getSecondaryDamage( whoCares ) > 0.0f )
  2506. {
  2507. return TRUE;
  2508. }
  2509. return FALSE;
  2510. }
  2511. //-------------------------------------------------------------------------------------------------
  2512. Int Weapon::getPreAttackDelay( const Object *source, const Object *victim ) const
  2513. {
  2514. // Look for a reason to return zero and have no delay.
  2515. WeaponPrefireType type = m_template->getPrefireType();
  2516. if( type == PREFIRE_PER_CLIP )
  2517. {
  2518. if( m_template->getClipSize() > 0 && m_ammoInClip < m_template->getClipSize() )
  2519. return 0;// I only delay once a clip, and this is not the first shot
  2520. }
  2521. else if( type == PREFIRE_PER_ATTACK )
  2522. {
  2523. if( source->getNumConsecutiveShotsFiredAtTarget( victim ) > 0 )
  2524. return 0;// I only delay once an attack, and I have already shot this guy
  2525. }
  2526. //else it is per shot, so it always applies
  2527. WeaponBonus bonus;
  2528. computeBonus(source, 0, bonus);
  2529. return m_template->getPreAttackDelay( bonus );
  2530. }
  2531. //-------------------------------------------------------------------------------------------------
  2532. //-------------------------------------------------------------------------------------------------
  2533. //-------------------------------------------------------------------------------------------------
  2534. //-------------------------------------------------------------------------------------------------
  2535. class AssistanceRequestData
  2536. {
  2537. public:
  2538. AssistanceRequestData();
  2539. const Object *m_requestingObject;
  2540. Object *m_victimObject;
  2541. Real m_requestDistanceSquared;
  2542. };
  2543. //-------------------------------------------------------------------------------------------------
  2544. AssistanceRequestData::AssistanceRequestData()
  2545. {
  2546. m_requestingObject = NULL;
  2547. m_victimObject = NULL;
  2548. m_requestDistanceSquared = 0.0f;
  2549. }
  2550. //-------------------------------------------------------------------------------------------------
  2551. static void makeAssistanceRequest( Object *requestOf, void *userData )
  2552. {
  2553. AssistanceRequestData *requestData = (AssistanceRequestData *)userData;
  2554. // Don't ask ourselves (can't believe I forgot this one)
  2555. if( requestOf == requestData->m_requestingObject )
  2556. return;
  2557. // Only request of our kind of people
  2558. if( !requestOf->getTemplate()->isEquivalentTo( requestData->m_requestingObject->getTemplate() ) )
  2559. return;
  2560. // Who are close enough
  2561. Real distSq = ThePartitionManager->getDistanceSquared( requestOf, requestData->m_requestingObject, FROM_CENTER_2D );
  2562. if( distSq > requestData->m_requestDistanceSquared )
  2563. return;
  2564. // and respond to requests
  2565. static const NameKeyType key_assistUpdate = NAMEKEY("AssistedTargetingUpdate");
  2566. AssistedTargetingUpdate *assistModule = (AssistedTargetingUpdate*)requestOf->findUpdateModule(key_assistUpdate);
  2567. if( assistModule == NULL )
  2568. return;
  2569. // and say yes
  2570. if( !assistModule->isFreeToAssist() )
  2571. return;
  2572. assistModule->assistAttack( requestData->m_requestingObject, requestData->m_victimObject );
  2573. }
  2574. //-------------------------------------------------------------------------------------------------
  2575. void Weapon::processRequestAssistance( const Object *requestingObject, Object *victimObject )
  2576. {
  2577. // Iterate through our player's objects, and tell everyone like us within our assistance range
  2578. // who is free to do so to assist us on this shot.
  2579. Player *ourPlayer = requestingObject->getControllingPlayer();
  2580. if( !ourPlayer )
  2581. return;
  2582. AssistanceRequestData requestData;
  2583. requestData.m_requestingObject = requestingObject;
  2584. requestData.m_victimObject = victimObject;
  2585. requestData.m_requestDistanceSquared = m_template->getRequestAssistRange() * m_template->getRequestAssistRange();
  2586. ourPlayer->iterateObjects( makeAssistanceRequest, &requestData );
  2587. }
  2588. //-------------------------------------------------------------------------------------------------
  2589. /*static*/ void Weapon::calcProjectileLaunchPosition(
  2590. const Object* launcher,
  2591. WeaponSlotType wslot,
  2592. Int specificBarrelToUse,
  2593. Matrix3D& worldTransform,
  2594. Coord3D& worldPos
  2595. )
  2596. {
  2597. if( launcher->getContainedBy() )
  2598. {
  2599. // If we are in an enclosing container, our launch position is our actual position. Yes, I am putting
  2600. // a minor case and an oft used function, but the major case is huge and full of math.
  2601. if(launcher->getContainedBy()->getContain()->isEnclosingContainerFor(launcher))
  2602. {
  2603. worldTransform = *launcher->getTransformMatrix();
  2604. Vector3 tmp = worldTransform.Get_Translation();
  2605. worldPos.x = tmp.X;
  2606. worldPos.y = tmp.Y;
  2607. worldPos.z = tmp.Z;
  2608. return;
  2609. }
  2610. }
  2611. Real turretAngle = 0.0f;
  2612. Real turretPitch = 0.0f;
  2613. const AIUpdateInterface* ai = launcher->getAIUpdateInterface();
  2614. WhichTurretType tur = ai ? ai->getWhichTurretForWeaponSlot(wslot, &turretAngle, &turretPitch) : TURRET_INVALID;
  2615. //CRCDEBUG_LOG(("calcProjectileLaunchPosition(): Turret %d, slot %d, barrel %d for %s\n", tur, wslot, specificBarrelToUse, DescribeObject(launcher).str()));
  2616. Matrix3D attachTransform(true);
  2617. Coord3D turretRotPos = {0.0f, 0.0f, 0.0f};
  2618. Coord3D turretPitchPos = {0.0f, 0.0f, 0.0f};
  2619. const Drawable* draw = launcher->getDrawable();
  2620. //CRCDEBUG_LOG(("Do we have a drawable? %d\n", (draw != NULL)));
  2621. if (!draw || !draw->getProjectileLaunchOffset(wslot, specificBarrelToUse, &attachTransform, tur, &turretRotPos, &turretPitchPos))
  2622. {
  2623. //CRCDEBUG_LOG(("ProjectileLaunchPos %d %d not found!\n",wslot, specificBarrelToUse));
  2624. DEBUG_CRASH(("ProjectileLaunchPos %d %d not found!\n",wslot, specificBarrelToUse));
  2625. attachTransform.Make_Identity();
  2626. turretRotPos.zero();
  2627. turretPitchPos.zero();
  2628. }
  2629. if (tur != TURRET_INVALID)
  2630. {
  2631. // The attach transform is the pristine front and center position of the fire point
  2632. // We can't read from the client, so we need to reproduce the actual point that
  2633. // takes turn and pitch into account.
  2634. Matrix3D turnAdjustment(1);
  2635. Matrix3D pitchAdjustment(1);
  2636. // To rotate about a point, move that point to 0,0, rotate, then move it back.
  2637. // Pre rotate will keep the first twist from screwing the angle of the second pitch
  2638. pitchAdjustment.Translate( turretPitchPos.x, turretPitchPos.y, turretPitchPos.z );
  2639. pitchAdjustment.In_Place_Pre_Rotate_Y(-turretPitch);
  2640. pitchAdjustment.Translate( -turretPitchPos.x, -turretPitchPos.y, -turretPitchPos.z );
  2641. turnAdjustment.Translate( turretRotPos.x, turretRotPos.y, turretRotPos.z );
  2642. turnAdjustment.In_Place_Pre_Rotate_Z(turretAngle);
  2643. turnAdjustment.Translate( -turretRotPos.x, -turretRotPos.y, -turretRotPos.z );
  2644. #ifdef ALLOW_TEMPORARIES
  2645. attachTransform = turnAdjustment * pitchAdjustment * attachTransform;
  2646. #else
  2647. Matrix3D tmp = attachTransform;
  2648. attachTransform.mul(turnAdjustment, pitchAdjustment);
  2649. attachTransform.postMul(tmp);
  2650. #endif
  2651. }
  2652. //#if defined(_DEBUG) || defined(_INTERNAL)
  2653. // Real muzzleHeight = attachTransform.Get_Z_Translation();
  2654. // DEBUG_ASSERTCRASH( muzzleHeight > 0.001f, ("YOUR TURRET HAS A VERY LOW PROJECTILE LAUNCH POSITION, BUT FOUND A VALID BONE. DID YOU PICK THE WRONG ONE? %s", launcher->getTemplate()->getName().str()));
  2655. //#endif
  2656. launcher->convertBonePosToWorldPos(NULL, &attachTransform, NULL, &worldTransform);
  2657. Vector3 tmp = worldTransform.Get_Translation();
  2658. worldPos.x = tmp.X;
  2659. worldPos.y = tmp.Y;
  2660. worldPos.z = tmp.Z;
  2661. }
  2662. //-------------------------------------------------------------------------------------------------
  2663. /*static*/ void Weapon::positionProjectileForLaunch(
  2664. Object* projectile,
  2665. const Object* launcher,
  2666. WeaponSlotType wslot,
  2667. Int specificBarrelToUse
  2668. )
  2669. {
  2670. //CRCDEBUG_LOG(("Weapon::positionProjectileForLaunch() for %s from %s\n",
  2671. //DescribeObject(projectile).str(), DescribeObject(launcher).str()));
  2672. // if our launch vehicle is gone, destroy ourselves
  2673. if (launcher == NULL)
  2674. {
  2675. TheGameLogic->destroyObject( projectile );
  2676. return;
  2677. }
  2678. Matrix3D worldTransform(true);
  2679. Coord3D worldPos;
  2680. Weapon::calcProjectileLaunchPosition(launcher, wslot, specificBarrelToUse, worldTransform, worldPos);
  2681. projectile->getDrawable()->setDrawableHidden(false);
  2682. projectile->setTransformMatrix(&worldTransform);
  2683. projectile->setPosition(&worldPos);
  2684. projectile->getExperienceTracker()->setExperienceSink( launcher->getID() );
  2685. const PhysicsBehavior* launcherPhys = launcher->getPhysics();
  2686. PhysicsBehavior* missilePhys = projectile->getPhysics();
  2687. if (launcherPhys && missilePhys)
  2688. {
  2689. launcherPhys->transferVelocityTo(missilePhys);
  2690. missilePhys->setIgnoreCollisionsWith(launcher);
  2691. }
  2692. }
  2693. //-------------------------------------------------------------------------------------------------
  2694. //-------------------------------------------------------------------------------------------------
  2695. void Weapon::getFiringLineOfSightOrigin(const Object* source, Coord3D& origin) const
  2696. {
  2697. //GS 1-6-03
  2698. // Sorry, but we have to simplify this. If we take the actual projectile launch pos, then
  2699. // that point can change. Take a Ranger with his gun on his shoulder. His point is very high so
  2700. // he clears this check and transitions to attacking. This puts his gun at waist level and
  2701. // now he fails this check so he transitions back. Our height won't change.
  2702. origin.z += source->getGeometryInfo().getMaxHeightAbovePosition();
  2703. /*
  2704. if (m_template->getProjectileTemplate() == NULL)
  2705. {
  2706. // note that we want to measure from the top of the collision
  2707. // shape, not the bottom! (most objects have eyes a lot closer
  2708. // to their head than their feet. if we have really odd critters
  2709. // with eye-feet, we'll need to change this assumption.)
  2710. origin.z += source->getGeometryInfo().getMaxHeightAbovePosition();
  2711. }
  2712. else
  2713. {
  2714. Matrix3D tmp(true);
  2715. Coord3D launchPos = {0.0f, 0.0f, 0.0f};
  2716. calcProjectileLaunchPosition(source, m_wslot, m_curBarrel, tmp, launchPos);
  2717. origin.x += launchPos.x - source->getPosition()->x;
  2718. origin.y += launchPos.y - source->getPosition()->y;
  2719. origin.z += launchPos.z - source->getPosition()->z;
  2720. }
  2721. */
  2722. }
  2723. //-------------------------------------------------------------------------------------------------
  2724. //-------------------------------------------------------------------------------------------------
  2725. Bool Weapon::isClearFiringLineOfSightTerrain(const Object* source, const Object* victim) const
  2726. {
  2727. Coord3D origin;
  2728. origin = *source->getPosition();
  2729. //CRCDEBUG_LOG(("Weapon::isClearFiringLineOfSightTerrain(Object) for %s\n", DescribeObject(source).str()));
  2730. //DUMPCOORD3D(&origin);
  2731. getFiringLineOfSightOrigin(source, origin);
  2732. Coord3D victimPos;
  2733. victim->getGeometryInfo().getCenterPosition( *victim->getPosition(), victimPos );
  2734. //CRCDEBUG_LOG(("Weapon::isClearFiringLineOfSightTerrain() - victimPos is (%g,%g,%g) (%X,%X,%X)\n",
  2735. // victimPos.x, victimPos.y, victimPos.z,
  2736. // AS_INT(victimPos.x),AS_INT(victimPos.y),AS_INT(victimPos.z)));
  2737. return ThePartitionManager->isClearLineOfSightTerrain(NULL, origin, NULL, victimPos);
  2738. }
  2739. //-------------------------------------------------------------------------------------------------
  2740. //-------------------------------------------------------------------------------------------------
  2741. Bool Weapon::isClearFiringLineOfSightTerrain(const Object* source, const Coord3D& victimPos) const
  2742. {
  2743. Coord3D origin;
  2744. origin = *source->getPosition();
  2745. //CRCDEBUG_LOG(("Weapon::isClearFiringLineOfSightTerrain(Coord3D) for %s\n", DescribeObject(source).str()));
  2746. //DUMPCOORD3D(&origin);
  2747. getFiringLineOfSightOrigin(source, origin);
  2748. return ThePartitionManager->isClearLineOfSightTerrain(NULL, origin, NULL, victimPos);
  2749. }
  2750. //-------------------------------------------------------------------------------------------------
  2751. //-------------------------------------------------------------------------------------------------
  2752. /** Determine whether if source was at goalPos whether it would have clear line of sight. */
  2753. Bool Weapon::isClearGoalFiringLineOfSightTerrain(const Object* source, const Coord3D& goalPos, const Object* victim) const
  2754. {
  2755. Coord3D origin=goalPos;
  2756. //CRCDEBUG_LOG(("Weapon::isClearGoalFiringLineOfSightTerrain(Object) for %s\n", DescribeObject(source).str()));
  2757. //DUMPCOORD3D(&origin);
  2758. getFiringLineOfSightOrigin(source, origin);
  2759. Coord3D victimPos;
  2760. victim->getGeometryInfo().getCenterPosition( *victim->getPosition(), victimPos );
  2761. return ThePartitionManager->isClearLineOfSightTerrain(NULL, origin, NULL, victimPos);
  2762. }
  2763. //-------------------------------------------------------------------------------------------------
  2764. //-------------------------------------------------------------------------------------------------
  2765. /** Determine whether if source was at goalPos whether it would have clear line of sight. */
  2766. Bool Weapon::isClearGoalFiringLineOfSightTerrain(const Object* source, const Coord3D& goalPos, const Coord3D& victimPos) const
  2767. {
  2768. Coord3D origin=goalPos;
  2769. //CRCDEBUG_LOG(("Weapon::isClearGoalFiringLineOfSightTerrain(Coord3D) for %s\n", DescribeObject(source).str()));
  2770. //DUMPCOORD3D(&origin);
  2771. getFiringLineOfSightOrigin(source, origin);
  2772. //CRCDEBUG_LOG(("Weapon::isClearFiringLineOfSightTerrain() - victimPos is (%g,%g,%g) (%X,%X,%X)\n",
  2773. // victimPos.x, victimPos.y, victimPos.z,
  2774. // AS_INT(victimPos.x),AS_INT(victimPos.y),AS_INT(victimPos.z)));
  2775. return ThePartitionManager->isClearLineOfSightTerrain(NULL, origin, NULL, victimPos);
  2776. }
  2777. //-------------------------------------------------------------------------------------------------
  2778. //Kris: Patch 1.01 - November 10, 2003
  2779. //This function was added to transfer key weapon stats for Jarmen Kell to and from the bike for
  2780. //the sniper attack, so he can share the stats.
  2781. //-------------------------------------------------------------------------------------------------
  2782. void Weapon::transferNextShotStatsFrom( const Weapon &weapon )
  2783. {
  2784. m_whenWeCanFireAgain = weapon.getPossibleNextShotFrame();
  2785. m_whenLastReloadStarted = weapon.getLastReloadStartedFrame();
  2786. m_status = weapon.getStatus();
  2787. }
  2788. // ------------------------------------------------------------------------------------------------
  2789. // ------------------------------------------------------------------------------------------------
  2790. void Weapon::crc( Xfer *xfer )
  2791. {
  2792. #ifdef DEBUG_CRC
  2793. AsciiString logString;
  2794. AsciiString tmp;
  2795. Bool doLogging = g_logObjectCRCs;
  2796. if (doLogging)
  2797. {
  2798. tmp.format("CRC of weapon %s: ", m_template->getName().str());
  2799. logString.concat(tmp);
  2800. }
  2801. #endif DEBUG_CRC
  2802. AsciiString tmplName = m_template->getName();
  2803. xfer->xferAsciiString(&tmplName);
  2804. // slot
  2805. xfer->xferUser( &m_wslot, sizeof( WeaponSlotType ) );
  2806. #ifdef DEBUG_CRC
  2807. if (doLogging)
  2808. {
  2809. tmp.format("m_wslot %d ", m_wslot);
  2810. logString.concat(tmp);
  2811. }
  2812. #endif // DEBUG_CRC
  2813. // status
  2814. /*
  2815. xfer->xferUser( &m_status, sizeof( WeaponStatus ) );
  2816. #ifdef DEBUG_CRC
  2817. if (doLogging)
  2818. {
  2819. tmp.format("m_status %d ", m_status);
  2820. logString.concat(tmp);
  2821. }
  2822. #endif // DEBUG_CRC
  2823. */
  2824. // ammo
  2825. xfer->xferUnsignedInt( &m_ammoInClip );
  2826. #ifdef DEBUG_CRC
  2827. if (doLogging)
  2828. {
  2829. tmp.format("m_ammoInClip %d ", m_ammoInClip);
  2830. logString.concat(tmp);
  2831. }
  2832. #endif // DEBUG_CRC
  2833. // when can fire again
  2834. xfer->xferUnsignedInt( &m_whenWeCanFireAgain );
  2835. #ifdef DEBUG_CRC
  2836. if (doLogging)
  2837. {
  2838. tmp.format("m_whenWeCanFireAgain %d ", m_whenWeCanFireAgain);
  2839. logString.concat(tmp);
  2840. }
  2841. #endif // DEBUG_CRC
  2842. // when pre attack finished
  2843. xfer->xferUnsignedInt( &m_whenPreAttackFinished );
  2844. #ifdef DEBUG_CRC
  2845. if (doLogging)
  2846. {
  2847. tmp.format("m_whenPreAttackFinished %d ", m_whenPreAttackFinished);
  2848. logString.concat(tmp);
  2849. }
  2850. #endif // DEBUG_CRC
  2851. // when last reload started
  2852. xfer->xferUnsignedInt( &m_whenLastReloadStarted );
  2853. #ifdef DEBUG_CRC
  2854. if (doLogging)
  2855. {
  2856. tmp.format("m_whenLastReloadStarted %d ", m_whenLastReloadStarted);
  2857. logString.concat(tmp);
  2858. }
  2859. #endif // DEBUG_CRC
  2860. // last fire frame
  2861. xfer->xferUnsignedInt( &m_lastFireFrame );
  2862. #ifdef DEBUG_CRC
  2863. if (doLogging)
  2864. {
  2865. tmp.format("m_lastFireFrame %d ", m_lastFireFrame);
  2866. logString.concat(tmp);
  2867. }
  2868. #endif // DEBUG_CRC
  2869. // projectile stream object
  2870. xfer->xferObjectID( &m_projectileStreamID );
  2871. #ifdef DEBUG_CRC
  2872. if (doLogging)
  2873. {
  2874. tmp.format("projectileStreamID %d ", m_projectileStreamID);
  2875. logString.concat(tmp);
  2876. }
  2877. #endif // DEBUG_CRC
  2878. // laser object (defunct)
  2879. ObjectID laserIDUnused = INVALID_ID;
  2880. xfer->xferObjectID( &laserIDUnused );
  2881. #ifdef DEBUG_CRC
  2882. if (doLogging)
  2883. {
  2884. tmp.format("laserID %d ", laserIDUnused);
  2885. logString.concat(tmp);
  2886. }
  2887. #endif // DEBUG_CRC
  2888. // max shot count
  2889. xfer->xferInt( &m_maxShotCount );
  2890. #ifdef DEBUG_CRC
  2891. if (doLogging)
  2892. {
  2893. tmp.format("m_maxShotCount %d ", m_maxShotCount);
  2894. logString.concat(tmp);
  2895. }
  2896. #endif // DEBUG_CRC
  2897. // current barrel
  2898. xfer->xferInt( &m_curBarrel );
  2899. #ifdef DEBUG_CRC
  2900. if (doLogging)
  2901. {
  2902. tmp.format("m_curBarrel %d ", m_curBarrel);
  2903. logString.concat(tmp);
  2904. }
  2905. #endif // DEBUG_CRC
  2906. // num shots for current barrel
  2907. xfer->xferInt( &m_numShotsForCurBarrel );
  2908. #ifdef DEBUG_CRC
  2909. if (doLogging)
  2910. {
  2911. tmp.format("m_numShotsForCurBarrel %d ", m_numShotsForCurBarrel);
  2912. logString.concat(tmp);
  2913. }
  2914. #endif // DEBUG_CRC
  2915. // scatter targets unused
  2916. UnsignedShort scatterCount = m_scatterTargetsUnused.size();
  2917. xfer->xferUnsignedShort( &scatterCount );
  2918. #ifdef DEBUG_CRC
  2919. if (doLogging)
  2920. {
  2921. tmp.format("scatterCount %d ", scatterCount);
  2922. logString.concat(tmp);
  2923. }
  2924. #endif // DEBUG_CRC
  2925. Int intData;
  2926. std::vector< Int >::const_iterator it;
  2927. for( it = m_scatterTargetsUnused.begin(); it != m_scatterTargetsUnused.end(); ++it )
  2928. {
  2929. intData = *it;
  2930. xfer->xferInt( &intData );
  2931. #ifdef DEBUG_CRC
  2932. if (doLogging)
  2933. {
  2934. tmp.format("%d ", intData);
  2935. logString.concat(tmp);
  2936. }
  2937. #endif // DEBUG_CRC
  2938. } // end for, it
  2939. // pitch limited
  2940. xfer->xferBool( &m_pitchLimited );
  2941. #ifdef DEBUG_CRC
  2942. if (doLogging)
  2943. {
  2944. tmp.format("m_pitchLimited %d ", m_pitchLimited);
  2945. logString.concat(tmp);
  2946. }
  2947. #endif // DEBUG_CRC
  2948. // leech weapon range active
  2949. xfer->xferBool( &m_leechWeaponRangeActive );
  2950. #ifdef DEBUG_CRC
  2951. if (doLogging)
  2952. {
  2953. tmp.format("m_leechWeaponRangeActive %d ", m_leechWeaponRangeActive);
  2954. logString.concat(tmp);
  2955. }
  2956. #endif // DEBUG_CRC
  2957. #ifdef DEBUG_CRC
  2958. if (doLogging)
  2959. {
  2960. CRCDEBUG_LOG(("%s\n", logString.str()));
  2961. }
  2962. #endif // DEBUG_CRC
  2963. } // end crc
  2964. // ------------------------------------------------------------------------------------------------
  2965. /** Xfer
  2966. * Version Info:
  2967. * 1: Initial version */
  2968. // ------------------------------------------------------------------------------------------------
  2969. void Weapon::xfer( Xfer *xfer )
  2970. {
  2971. // version
  2972. const XferVersion currentVersion = 3;
  2973. XferVersion version = currentVersion;
  2974. xfer->xferVersion( &version, currentVersion );
  2975. if (version >= 2)
  2976. {
  2977. AsciiString tmplName = m_template->getName();
  2978. xfer->xferAsciiString(&tmplName);
  2979. if (xfer->getXferMode() == XFER_LOAD)
  2980. {
  2981. m_template = TheWeaponStore->findWeaponTemplate(tmplName);
  2982. if (m_template == NULL)
  2983. throw INI_INVALID_DATA;
  2984. }
  2985. }
  2986. // slot
  2987. xfer->xferUser( &m_wslot, sizeof( WeaponSlotType ) );
  2988. // status
  2989. xfer->xferUser( &m_status, sizeof( WeaponStatus ) );
  2990. // ammo
  2991. xfer->xferUnsignedInt( &m_ammoInClip );
  2992. // when can fire again
  2993. xfer->xferUnsignedInt( &m_whenWeCanFireAgain );
  2994. // wehn pre attack finished
  2995. xfer->xferUnsignedInt( &m_whenPreAttackFinished );
  2996. // when last reload started
  2997. xfer->xferUnsignedInt( &m_whenLastReloadStarted );
  2998. // last fire frame
  2999. xfer->xferUnsignedInt( &m_lastFireFrame );
  3000. // suspendFXFrame, this affects client only
  3001. if ( version >= 3 )
  3002. xfer->xferUnsignedInt( &m_suspendFXFrame );
  3003. else
  3004. m_suspendFXFrame = 0;
  3005. // projectile stream object
  3006. xfer->xferObjectID( &m_projectileStreamID );
  3007. // laser object
  3008. ObjectID laserIDUnused = INVALID_ID;
  3009. xfer->xferObjectID( &laserIDUnused );
  3010. // max shot count
  3011. xfer->xferInt( &m_maxShotCount );
  3012. // current barrel
  3013. xfer->xferInt( &m_curBarrel );
  3014. // num shots for current barrel
  3015. xfer->xferInt( &m_numShotsForCurBarrel );
  3016. // scatter targets unused
  3017. UnsignedShort scatterCount = m_scatterTargetsUnused.size();
  3018. xfer->xferUnsignedShort( &scatterCount );
  3019. Int intData;
  3020. if( xfer->getXferMode() == XFER_SAVE )
  3021. {
  3022. std::vector< Int >::const_iterator it;
  3023. for( it = m_scatterTargetsUnused.begin(); it != m_scatterTargetsUnused.end(); ++it )
  3024. {
  3025. intData = *it;
  3026. xfer->xferInt( &intData );
  3027. } // end for, it
  3028. } // end if, save
  3029. else
  3030. {
  3031. // sanity, the scatter targets must be empty
  3032. m_scatterTargetsUnused.clear();
  3033. for( UnsignedShort i = 0; i < scatterCount; ++i )
  3034. {
  3035. xfer->xferInt( &intData );
  3036. m_scatterTargetsUnused.push_back( intData );
  3037. } // end for, i
  3038. } // end else, load
  3039. // pitch limited
  3040. xfer->xferBool( &m_pitchLimited );
  3041. // leech weapon range active
  3042. xfer->xferBool( &m_leechWeaponRangeActive );
  3043. } // end xfer
  3044. // ------------------------------------------------------------------------------------------------
  3045. /** Load post process */
  3046. // ------------------------------------------------------------------------------------------------
  3047. void Weapon::loadPostProcess( void )
  3048. {
  3049. if( m_projectileStreamID != INVALID_ID )
  3050. {
  3051. Object* projectileStream = TheGameLogic->findObjectByID( m_projectileStreamID );
  3052. if( projectileStream == NULL )
  3053. {
  3054. m_projectileStreamID = INVALID_ID;
  3055. }
  3056. }
  3057. }
  3058. //-------------------------------------------------------------------------------------------------
  3059. //-------------------------------------------------------------------------------------------------
  3060. //-------------------------------------------------------------------------------------------------
  3061. void WeaponBonus::appendBonuses(WeaponBonus& bonus) const
  3062. {
  3063. for (int f = 0; f < WeaponBonus::FIELD_COUNT; ++f)
  3064. {
  3065. bonus.m_field[f] += this->m_field[f] - 1.0f;
  3066. }
  3067. }
  3068. //-------------------------------------------------------------------------------------------------
  3069. /*static*/ void WeaponBonusSet::parseWeaponBonusSet(INI* ini, void* /*instance*/, void* store, const void* /*userData*/)
  3070. {
  3071. WeaponBonusSet* self = (WeaponBonusSet*)store;
  3072. self->parseWeaponBonusSet(ini);
  3073. }
  3074. //-------------------------------------------------------------------------------------------------
  3075. /*static*/ void WeaponBonusSet::parseWeaponBonusSetPtr(INI* ini, void* /*instance*/, void* store, const void* /*userData*/)
  3076. {
  3077. WeaponBonusSet** selfPtr = (WeaponBonusSet**)store;
  3078. (*selfPtr)->parseWeaponBonusSet(ini);
  3079. }
  3080. //-------------------------------------------------------------------------------------------------
  3081. void WeaponBonusSet::parseWeaponBonusSet(INI* ini)
  3082. {
  3083. WeaponBonusConditionType wb = (WeaponBonusConditionType)INI::scanIndexList(ini->getNextToken(), TheWeaponBonusNames);
  3084. WeaponBonus::Field wf = (WeaponBonus::Field)INI::scanIndexList(ini->getNextToken(), TheWeaponBonusFieldNames);
  3085. m_bonus[wb].setField(wf, INI::scanPercentToReal(ini->getNextToken()));
  3086. }
  3087. //-------------------------------------------------------------------------------------------------
  3088. void WeaponBonusSet::appendBonuses(WeaponBonusConditionFlags flags, WeaponBonus& bonus) const
  3089. {
  3090. if (flags == 0)
  3091. return; // my, that was easy
  3092. for (int i = 0; i < WEAPONBONUSCONDITION_COUNT; ++i)
  3093. {
  3094. if ((flags & (1 << i)) == 0)
  3095. continue;
  3096. this->m_bonus[i].appendBonuses(bonus);
  3097. }
  3098. }