Weapon.cpp 117 KB

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