Drawable.cpp 158 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893
  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. // Drawable.cpp ///////////////////////////////////////////////////////////////////////////////////
  24. // "Drawables" - graphical GameClient entities bound to GameLogic objects
  25. // Author: Michael S. Booth, March 2001
  26. ///////////////////////////////////////////////////////////////////////////////////////////////////
  27. #include "PreRTS.h" // This must go first in EVERY cpp file int the GameEngine
  28. #include "Common/AudioEventInfo.h"
  29. #include "Common/AudioSettings.h"
  30. #include "Common/BitFlagsIO.h"
  31. #include "Common/BuildAssistant.h"
  32. #include "Common/ClientUpdateModule.h"
  33. #include "Common/DrawModule.h"
  34. #include "Common/GameAudio.h"
  35. #include "Common/GameEngine.h"
  36. #include "Common/GameLOD.h"
  37. #include "Common/GameState.h"
  38. #include "Common/GlobalData.h"
  39. #include "Common/ModuleFactory.h"
  40. #include "Common/PerfTimer.h"
  41. #include "Common/Player.h"
  42. #include "Common/PlayerList.h"
  43. #include "Common/ThingFactory.h"
  44. #include "Common/ThingTemplate.h"
  45. #include "Common/Xfer.h"
  46. #include "GameLogic/ExperienceTracker.h"
  47. #include "GameLogic/GameLogic.h" // for logic frame count
  48. #include "GameLogic/Object.h"
  49. #include "GameLogic/Locomotor.h"
  50. #include "GameLogic/Module/AIUpdate.h"
  51. #include "GameLogic/Module/BodyModule.h"
  52. #include "GameLogic/Module/ContainModule.h"
  53. #include "GameLogic/Module/PhysicsUpdate.h"
  54. #include "GameLogic/Module/StealthUpdate.h"
  55. #include "GameLogic/Module/StickyBombUpdate.h"
  56. #include "GameLogic/Module/BattlePlanUpdate.h"
  57. #include "GameLogic/ScriptEngine.h"
  58. #include "GameLogic/Weapon.h"
  59. #include "GameClient/Anim2D.h"
  60. #include "GameClient/Display.h"
  61. #include "GameClient/DisplayStringManager.h"
  62. #include "GameClient/Drawable.h"
  63. #include "GameClient/DrawGroupInfo.h"
  64. #include "GameClient/GameClient.h"
  65. #include "GameClient/GlobalLanguage.h"
  66. #include "GameClient/InGameUI.h"
  67. #include "GameClient/Image.h"
  68. #include "GameClient/ParticleSys.h"
  69. #include "GameClient/LanguageFilter.h"
  70. #include "GameClient/Shadow.h"
  71. #include "GameClient/GameText.h"
  72. #ifdef _INTERNAL
  73. // for occasional debugging...
  74. //#pragma optimize("", off)
  75. //#pragma MESSAGE("************************************** WARNING, optimization disabled for debugging purposes")
  76. #endif
  77. #define VERY_TRANSPARENT_HEATVISION (0.001f)
  78. #define HEATVISION_FADE_SCALAR (0.8f)
  79. static const char *TheDrawableIconNames[] =
  80. {
  81. "DefaultHeal",
  82. "StructureHeal",
  83. "VehicleHeal",
  84. #ifdef ALLOW_DEMORALIZE
  85. "Demoralized",
  86. #else
  87. "Demoralized_OBSOLETE",
  88. #endif
  89. "BombTimed",
  90. "BombRemote",
  91. "Disabled",
  92. "BattlePlanIcon_Bombard",
  93. "BattlePlanIcon_HoldTheLine",
  94. "BattlePlanIcon_SeekAndDestroy",
  95. "Emoticon",
  96. "Enthusiastic",//a red cross? // soon to replace?
  97. "Subliminal", //with the gold border! replace?
  98. "CarBomb",
  99. NULL
  100. };
  101. // ------------------------------------------------------------------------------------------------
  102. // ------------------------------------------------------------------------------------------------
  103. DrawableIconInfo::DrawableIconInfo()
  104. {
  105. for (int i = 0; i < MAX_ICONS; ++i)
  106. {
  107. m_icon[i] = NULL;
  108. m_keepTillFrame[i] = 0;
  109. }
  110. }
  111. // ------------------------------------------------------------------------------------------------
  112. // ------------------------------------------------------------------------------------------------
  113. DrawableIconInfo::~DrawableIconInfo()
  114. {
  115. clear();
  116. }
  117. // ------------------------------------------------------------------------------------------------
  118. // ------------------------------------------------------------------------------------------------
  119. void DrawableIconInfo::clear()
  120. {
  121. for (int i = 0; i < MAX_ICONS; ++i)
  122. {
  123. if (m_icon[i])
  124. m_icon[i]->deleteInstance();
  125. m_icon[i] = NULL;
  126. m_keepTillFrame[i] = 0;
  127. }
  128. }
  129. // ------------------------------------------------------------------------------------------------
  130. // ------------------------------------------------------------------------------------------------
  131. void DrawableIconInfo::killIcon(DrawableIconType t)
  132. {
  133. if (m_icon[t])
  134. {
  135. m_icon[t]->deleteInstance();
  136. m_icon[t] = NULL;
  137. m_keepTillFrame[t] = 0;
  138. }
  139. }
  140. // ------------------------------------------------------------------------------------------------
  141. // ------------------------------------------------------------------------------------------------
  142. DrawableLocoInfo::DrawableLocoInfo()
  143. {
  144. m_pitch = 0.0f;
  145. m_pitchRate = 0.0f;
  146. m_roll = 0.0f;
  147. m_rollRate = 0.0f;
  148. m_yaw = 0.0f;
  149. m_accelerationPitch = 0.0f;
  150. m_accelerationPitchRate = 0.0f;
  151. m_accelerationRoll = 0.0f;
  152. m_accelerationRollRate = 0.0f;
  153. m_overlapZVel = 0.0f;
  154. m_overlapZ = 0.0f;
  155. m_wobble = 1.0f;
  156. m_wheelInfo.m_frontLeftHeightOffset = 0;
  157. m_wheelInfo.m_frontRightHeightOffset = 0;
  158. m_wheelInfo.m_rearLeftHeightOffset = 0;
  159. m_wheelInfo.m_rearRightHeightOffset = 0;
  160. m_wheelInfo.m_framesAirborneCounter = 0;
  161. m_wheelInfo.m_framesAirborne = 0;
  162. m_wheelInfo.m_wheelAngle = 0;
  163. }
  164. // ------------------------------------------------------------------------------------------------
  165. // ------------------------------------------------------------------------------------------------
  166. DrawableLocoInfo::~DrawableLocoInfo()
  167. {
  168. }
  169. // ------------------------------------------------------------------------------------------------
  170. // ------------------------------------------------------------------------------------------------
  171. static const char *drawableIconIndexToName( DrawableIconType iconIndex )
  172. {
  173. DEBUG_ASSERTCRASH( iconIndex >= ICON_FIRST && iconIndex < MAX_ICONS,
  174. ("drawableIconIndexToName - Illegal index '%d'\n", iconIndex) );
  175. return TheDrawableIconNames[ iconIndex ];
  176. } // end drawableIconIndexToName
  177. // ------------------------------------------------------------------------------------------------
  178. // ------------------------------------------------------------------------------------------------
  179. static DrawableIconType drawableIconNameToIndex( const char *iconName )
  180. {
  181. DEBUG_ASSERTCRASH( iconName != NULL, ("drawableIconNameToIndex - Illegal name\n") );
  182. for( Int i = ICON_FIRST; i < MAX_ICONS; ++i )
  183. if( stricmp( TheDrawableIconNames[ i ], iconName ) == 0 )
  184. return (DrawableIconType)i;
  185. return ICON_INVALID;
  186. } // end drawableIconNameToIndex
  187. // ------------------------------------------------------------------------------------------------
  188. // constants
  189. const UnsignedInt HEALING_ICON_DISPLAY_TIME = LOGICFRAMES_PER_SECOND * 3;
  190. const UnsignedInt DEFAULT_HEAL_ICON_WIDTH = 32;
  191. const UnsignedInt DEFAULT_HEAL_ICON_HEIGHT = 32;
  192. const RGBColor SICKLY_GREEN_POISONED_COLOR = {-1.0f, 1.0f, -1.0f};
  193. const RGBColor DARK_GRAY_DISABLED_COLOR = {-0.5f, -0.5f, -0.5f};
  194. const RGBColor RED_IRRADIATED_COLOR = { 1.0f, -1.0f, -1.0f};
  195. const Int MAX_ENABLED_MODULES = 16;
  196. // ------------------------------------------------------------------------------------------------
  197. // ------------------------------------------------------------------------------------------------
  198. /*static*/ Bool Drawable::s_staticImagesInited = false;
  199. /*static*/ const Image* Drawable::s_veterancyImage[LEVEL_COUNT] = { NULL };
  200. /*static*/ const Image* Drawable::s_fullAmmo = NULL;
  201. /*static*/ const Image* Drawable::s_emptyAmmo = NULL;
  202. /*static*/ const Image* Drawable::s_fullContainer = NULL;
  203. /*static*/ const Image* Drawable::s_emptyContainer = NULL;
  204. /*static*/ Anim2DTemplate** Drawable::s_animationTemplates = NULL;
  205. #ifdef DIRTY_CONDITION_FLAGS
  206. /*static*/ Int Drawable::s_modelLockCount = 0;
  207. #endif
  208. // ------------------------------------------------------------------------------------------------
  209. /*static*/ void Drawable::initStaticImages()
  210. {
  211. if (s_staticImagesInited)
  212. return;
  213. s_veterancyImage[0] = NULL;
  214. s_veterancyImage[1] = TheMappedImageCollection->findImageByName("SCVeter1");
  215. s_veterancyImage[2] = TheMappedImageCollection->findImageByName("SCVeter2");
  216. s_veterancyImage[3] = TheMappedImageCollection->findImageByName("SCVeter3");
  217. s_fullAmmo = TheMappedImageCollection->findImageByName("SCPAmmoFull");
  218. s_emptyAmmo = TheMappedImageCollection->findImageByName("SCPAmmoEmpty");
  219. s_fullContainer = TheMappedImageCollection->findImageByName("SCPPipFull");
  220. s_emptyContainer = TheMappedImageCollection->findImageByName("SCPPipEmpty");
  221. s_animationTemplates = NEW Anim2DTemplate* [ MAX_ICONS ];
  222. s_animationTemplates[ICON_DEFAULT_HEAL] = TheAnim2DCollection->findTemplate(TheDrawableIconNames[ICON_DEFAULT_HEAL]);
  223. s_animationTemplates[ICON_STRUCTURE_HEAL] = TheAnim2DCollection->findTemplate(TheDrawableIconNames[ICON_STRUCTURE_HEAL]);
  224. s_animationTemplates[ICON_VEHICLE_HEAL] = TheAnim2DCollection->findTemplate(TheDrawableIconNames[ICON_VEHICLE_HEAL]);
  225. #ifdef ALLOW_DEMORALIZE
  226. s_animationTemplates[ICON_DEMORALIZED] = TheAnim2DCollection->findTemplate(TheDrawableIconNames[ICON_DEMORALIZED]);
  227. #endif
  228. s_animationTemplates[ICON_BOMB_TIMED] = TheAnim2DCollection->findTemplate(TheDrawableIconNames[ICON_BOMB_TIMED]);
  229. s_animationTemplates[ICON_BOMB_REMOTE] = TheAnim2DCollection->findTemplate(TheDrawableIconNames[ICON_BOMB_REMOTE]);
  230. s_animationTemplates[ICON_DISABLED] = TheAnim2DCollection->findTemplate(TheDrawableIconNames[ICON_DISABLED]);
  231. s_animationTemplates[ICON_BATTLEPLAN_BOMBARD] = TheAnim2DCollection->findTemplate(TheDrawableIconNames[ICON_BATTLEPLAN_BOMBARD]);
  232. s_animationTemplates[ICON_BATTLEPLAN_HOLDTHELINE] = TheAnim2DCollection->findTemplate(TheDrawableIconNames[ICON_BATTLEPLAN_HOLDTHELINE]);
  233. s_animationTemplates[ICON_BATTLEPLAN_SEARCHANDDESTROY] = TheAnim2DCollection->findTemplate(TheDrawableIconNames[ICON_BATTLEPLAN_SEARCHANDDESTROY]);
  234. s_animationTemplates[ICON_EMOTICON] = NULL; //Emoticons can be anything, so we'll need to handle it dynamically.
  235. s_animationTemplates[ICON_ENTHUSIASTIC] = TheAnim2DCollection->findTemplate(TheDrawableIconNames[ICON_ENTHUSIASTIC]);
  236. s_animationTemplates[ICON_ENTHUSIASTIC_SUBLIMINAL] = TheAnim2DCollection->findTemplate(TheDrawableIconNames[ICON_ENTHUSIASTIC_SUBLIMINAL]);
  237. s_animationTemplates[ICON_CARBOMB] = TheAnim2DCollection->findTemplate(TheDrawableIconNames[ICON_CARBOMB]);
  238. s_staticImagesInited = true;
  239. }
  240. //-------------------------------------------------------------------------------------------------
  241. /*static*/ void Drawable::killStaticImages()
  242. {
  243. if( s_animationTemplates )
  244. {
  245. delete s_animationTemplates;
  246. s_animationTemplates = NULL;
  247. }
  248. }
  249. //-------------------------------------------------------------------------------------------------
  250. void Drawable::saturateRGB(RGBColor& color, Real factor)
  251. {
  252. color.red *= factor;
  253. color.green *= factor;
  254. color.blue *= factor;
  255. Real halfFactor = factor * 0.5f;
  256. color.red -= halfFactor;
  257. color.green -= halfFactor;
  258. color.blue -= halfFactor;
  259. }
  260. //--- A MACRO TO APPLY TO TheTacticalView->getZoom() ------ To Clamp the return to a visually pleasing size
  261. //--- so that icons, emoticons, health bars, pips, etc, look reasonably solid and don't shimmer or tweed
  262. //#define CLAMP_ICON_ZOOM_FACTOR(n) (MAX(0.80f, MIN(1.00f, n)))
  263. #define CLAMP_ICON_ZOOM_FACTOR(n) (n)//nothing
  264. //-------------------------------------------------------------------------------------------------
  265. /** Drawables are lightweight, graphical entities which live on the GameClient,
  266. * and are usually bound to GameLogic objects. In other words, they are the
  267. * graphical side of a logical object, whereas GameLogic objects encapsulate
  268. * behaviors and physics. */
  269. //-------------------------------------------------------------------------------------------------
  270. Drawable::Drawable( const ThingTemplate *thingTemplate, DrawableStatus statusBits )
  271. : Thing( thingTemplate )
  272. {
  273. // assign status bits before anything else can be done
  274. m_status = statusBits;
  275. // Added By Sadullah Nader
  276. // Initialization missing and needed
  277. m_nextDrawable = NULL;
  278. m_prevDrawable = NULL;
  279. //
  280. // register drawable with the GameClient ... do this first before we start doing anything
  281. // complex that uses any of the drawable data so that we have and ID!! It's ok to initialize
  282. // members of the drawable before this registration happens
  283. //
  284. TheGameClient->registerDrawable( this );
  285. Int i;
  286. // Added By Sadullah Nader
  287. // Initialization missing and needed
  288. m_flashColor = 0;
  289. m_selected = '\0';
  290. //
  291. m_expirationDate = 0; // 0 == never expires
  292. m_lastConstructDisplayed = -1.0f;
  293. //Added By Sadullah Nader
  294. //Fix for the building percent
  295. m_constructDisplayString = TheDisplayStringManager->newDisplayString();
  296. m_constructDisplayString->setFont(TheFontLibrary->getFont(TheInGameUI->getDrawableCaptionFontName(),
  297. TheGlobalLanguageData->adjustFontSize(TheInGameUI->getDrawableCaptionPointSize()),
  298. TheInGameUI->isDrawableCaptionBold() ));
  299. m_ambientSound = NULL;
  300. m_decalOpacityFadeTarget = 0;
  301. m_decalOpacityFadeRate = 0;
  302. m_decalOpacity = 0;
  303. m_explicitOpacity = 1.0f;
  304. m_stealthOpacity = 1.0f;
  305. m_effectiveStealthOpacity = 1.0f;
  306. m_terrainDecalType = TERRAIN_DECAL_NONE;
  307. m_fadeMode = FADING_NONE;
  308. m_timeElapsedFade = 0;
  309. m_timeToFade = 0;
  310. m_shroudClearFrame = 0;
  311. for (i = 0; i < NUM_DRAWABLE_MODULE_TYPES; ++i)
  312. m_modules[i] = NULL;
  313. m_stealthLook = STEALTHLOOK_NONE;
  314. m_flashCount = 0;
  315. m_locoInfo = NULL;
  316. // sanity
  317. if( TheGameClient == NULL || thingTemplate == NULL )
  318. {
  319. assert( 0 );
  320. return;
  321. } // end if
  322. m_instance.Make_Identity();
  323. m_instanceIsIdentity = true;
  324. //Real scaleFuzziness = thingTemplate->getInstanceScaleFuzziness();
  325. //Real fuzzyScale = ( 1.0f + GameClientRandomValueReal( -scaleFuzziness, scaleFuzziness ));
  326. m_instanceScale = thingTemplate->getAssetScale();// * fuzzyScale;
  327. // initially not bound to an object
  328. m_object = NULL;
  329. m_particle = NULL;
  330. // tintStatusTracking
  331. m_tintStatus = 0;
  332. m_prevTintStatus = 0;
  333. #ifdef DIRTY_CONDITION_FLAGS
  334. m_isModelDirty = true;
  335. #endif
  336. m_hidden = false;
  337. m_hiddenByStealth = false;
  338. m_heatVisionOpacity = 0.0f;
  339. m_drawableFullyObscuredByShroud = false;
  340. m_ambientSoundEnabled = TRUE;
  341. //
  342. // allocate any modules we need to, we should keep
  343. // this at or near the end of the drawable construction so that we have
  344. // all the valid data about the thing when we create the module
  345. //
  346. //Filter out drawable modules which have been disabled because of game LOD.
  347. Int modIdx;
  348. Module** m;
  349. const ModuleInfo& drawMI = thingTemplate->getDrawModuleInfo();
  350. m_modules[MODULETYPE_DRAW - FIRST_DRAWABLE_MODULE_TYPE] = MSGNEW("ModulePtrs") Module*[drawMI.getCount()+1]; // pool[]ify
  351. m = m_modules[MODULETYPE_DRAW - FIRST_DRAWABLE_MODULE_TYPE];
  352. for (modIdx = 0; modIdx < drawMI.getCount(); ++modIdx)
  353. {
  354. const ModuleData* newModData = drawMI.getNthData(modIdx);
  355. if (TheGlobalData->m_useDrawModuleLOD &&
  356. newModData->getMinimumRequiredGameLOD() > TheGameLODManager->getStaticLODLevel())
  357. continue;
  358. *m++ = TheModuleFactory->newModule(this, drawMI.getNthName(modIdx), newModData, MODULETYPE_DRAW);
  359. }
  360. *m = NULL;
  361. const ModuleInfo& cuMI = thingTemplate->getClientUpdateModuleInfo();
  362. if (cuMI.getCount())
  363. {
  364. // since most things don't have CU modules, we allow this to be null!
  365. m_modules[MODULETYPE_CLIENT_UPDATE - FIRST_DRAWABLE_MODULE_TYPE] = MSGNEW("ModulePtrs") Module*[cuMI.getCount()+1]; // pool[]ify
  366. m = m_modules[MODULETYPE_CLIENT_UPDATE - FIRST_DRAWABLE_MODULE_TYPE];
  367. for (modIdx = 0; modIdx < cuMI.getCount(); ++modIdx)
  368. {
  369. const ModuleData* newModData = cuMI.getNthData(modIdx);
  370. /// @todo srj -- this is evil, we shouldn't look at the module name directly!
  371. if (thingTemplate->isKindOf(KINDOF_SHRUBBERY) &&
  372. !TheGlobalData->m_useTreeSway &&
  373. cuMI.getNthName(modIdx).compareNoCase("SwayClientUpdate") == 0)
  374. continue;
  375. *m++ = TheModuleFactory->newModule(this, cuMI.getNthName(modIdx), newModData, MODULETYPE_CLIENT_UPDATE);
  376. }
  377. *m = NULL;
  378. }
  379. /// allow for inter-Module resolution
  380. for (i = 0; i < NUM_DRAWABLE_MODULE_TYPES; ++i)
  381. {
  382. for (Module** m = m_modules[i]; m && *m; ++m)
  383. (*m)->onObjectCreated();
  384. }
  385. m_groupNumber = NULL;
  386. m_captionDisplayString = NULL;
  387. m_drawableInfo.m_drawable = this;
  388. m_drawableInfo.m_ghostObject = NULL;
  389. m_iconInfo = NULL; // lazily allocate!
  390. m_selectionFlashEnvelope = NULL; // lazily allocate!
  391. m_colorTintEnvelope = NULL; // lazily allocate!
  392. initStaticImages();
  393. startAmbientSound();
  394. } // end Drawable
  395. //-------------------------------------------------------------------------------------------------
  396. //-------------------------------------------------------------------------------------------------
  397. Drawable::~Drawable()
  398. {
  399. Int i;
  400. if( m_constructDisplayString )
  401. TheDisplayStringManager->freeDisplayString( m_constructDisplayString );
  402. m_constructDisplayString = NULL;
  403. if ( m_captionDisplayString )
  404. TheDisplayStringManager->freeDisplayString( m_captionDisplayString );
  405. m_captionDisplayString = NULL;
  406. m_groupNumber = NULL;
  407. // delete any modules callbacks
  408. for (i = 0; i < NUM_DRAWABLE_MODULE_TYPES; ++i)
  409. {
  410. for (Module** m = m_modules[i]; m && *m; ++m)
  411. {
  412. (*m)->deleteInstance();
  413. *m = NULL; // in case other modules call findModule from their dtor!
  414. }
  415. delete [] m_modules[i];
  416. m_modules[i] = NULL;
  417. }
  418. stopAmbientSound();
  419. if (m_ambientSound)
  420. {
  421. m_ambientSound->deleteInstance();
  422. m_ambientSound = NULL;
  423. }
  424. /// @todo this is nasty, we need a real general effects system
  425. // remove any entries that might be present from the ray effect system
  426. TheGameClient->removeFromRayEffects( this );
  427. // reset object to NULL so we never mistaken grab "dead" objects
  428. m_object = NULL;
  429. m_particle = NULL;
  430. // delete any icons present
  431. if (m_iconInfo)
  432. m_iconInfo->deleteInstance();
  433. if (m_selectionFlashEnvelope)
  434. m_selectionFlashEnvelope->deleteInstance();
  435. if (m_colorTintEnvelope)
  436. m_colorTintEnvelope->deleteInstance();
  437. if (m_locoInfo)
  438. {
  439. m_locoInfo->deleteInstance();
  440. m_locoInfo = NULL;
  441. }
  442. }
  443. //-------------------------------------------------------------------------------------------------
  444. /** Run from GameClient::destroyDrawable */
  445. //-------------------------------------------------------------------------------------------------
  446. void Drawable::onDestroy( void )
  447. {
  448. //
  449. // run the onDelete on all modules present so they each have an opportunity to cleanup
  450. // anything they need to ... including talking to any other modules
  451. //
  452. for( Int i = 0; i < NUM_DRAWABLE_MODULE_TYPES; i++ )
  453. {
  454. for( Module** m = m_modules[ i ]; m && *m; ++m )
  455. (*m)->onDelete();
  456. } // end for i
  457. } // end onDestroy
  458. //-------------------------------------------------------------------------------------------------
  459. Bool Drawable::isVisible()
  460. {
  461. for (DrawModule** dm = getDrawModules(); *dm; ++dm)
  462. {
  463. if ((*dm)->isVisible())
  464. {
  465. return TRUE;
  466. }
  467. }
  468. return FALSE;
  469. }
  470. //-------------------------------------------------------------------------------------------------
  471. Bool Drawable::getShouldAnimate( Bool considerPower ) const
  472. {
  473. const Object *obj = getObject();
  474. if (obj)
  475. {
  476. if (considerPower && obj->testScriptStatusBit(OBJECT_STATUS_SCRIPT_UNPOWERED))
  477. return FALSE;
  478. if (obj->isDisabled())
  479. {
  480. if( obj->isDisabledByType( DISABLED_HACKED )
  481. || obj->isDisabledByType( DISABLED_PARALYZED )
  482. || obj->isDisabledByType( DISABLED_EMP )
  483. // srj sez: unmanned things also should not animate. (eg, gattling tanks,
  484. // which have a slight barrel animation even when at rest). if this causes
  485. // a problem, we will need to fix gattling tanks in another way.
  486. || obj->isDisabledByType( DISABLED_UNMANNED )
  487. )
  488. return FALSE;
  489. if (considerPower && obj->isDisabledByType(DISABLED_UNDERPOWERED))
  490. {
  491. // We only pause animations if this draw module says so
  492. // By checking for the others first, we prevent underpower from allowing a True on an addition disable type
  493. return FALSE;
  494. }
  495. }
  496. }
  497. return TRUE;
  498. }
  499. //-------------------------------------------------------------------------------------------------
  500. // this method must ONLY be called from the client, NEVER From the logic, not even indirectly.
  501. Bool Drawable::clientOnly_getFirstRenderObjInfo(Coord3D* pos, Real* boundingSphereRadius, Matrix3D* transform)
  502. {
  503. DrawModule** dm = getDrawModules();
  504. const ObjectDrawInterface* di = (dm && *dm) ? (*dm)->getObjectDrawInterface() : NULL;
  505. if (di)
  506. {
  507. return di->clientOnly_getRenderObjInfo(pos, boundingSphereRadius, transform);
  508. }
  509. return false;
  510. }
  511. //-------------------------------------------------------------------------------------------------
  512. Bool Drawable::getProjectileLaunchOffset(WeaponSlotType wslot, Int specificBarrelToUse, Matrix3D* launchPos, WhichTurretType tur, Coord3D* turretRotPos, Coord3D* turretPitchPos) const
  513. {
  514. for (const DrawModule** dm = getDrawModules(); *dm; ++dm)
  515. {
  516. const ObjectDrawInterface* di = (*dm)->getObjectDrawInterface();
  517. if (di && di->getProjectileLaunchOffset(m_conditionState, wslot, specificBarrelToUse, launchPos, tur, turretRotPos, turretPitchPos))
  518. return true;
  519. }
  520. return false;
  521. }
  522. //-------------------------------------------------------------------------------------------------
  523. void Drawable::setAnimationLoopDuration(UnsignedInt numFrames)
  524. {
  525. for (DrawModule** dm = getDrawModules(); *dm; ++dm)
  526. {
  527. ObjectDrawInterface* di = (*dm)->getObjectDrawInterface();
  528. if (di)
  529. di->setAnimationLoopDuration(numFrames);
  530. }
  531. }
  532. //-------------------------------------------------------------------------------------------------
  533. void Drawable::setAnimationCompletionTime(UnsignedInt numFrames)
  534. {
  535. for (DrawModule** dm = getDrawModules(); *dm; ++dm)
  536. {
  537. ObjectDrawInterface* di = (*dm)->getObjectDrawInterface();
  538. if (di)
  539. di->setAnimationCompletionTime(numFrames);
  540. }
  541. }
  542. //-------------------------------------------------------------------------------------------------
  543. void Drawable::updateSubObjects()
  544. {
  545. for (DrawModule** dm = getDrawModules(); *dm; ++dm)
  546. {
  547. ObjectDrawInterface* di = (*dm)->getObjectDrawInterface();
  548. if (di)
  549. di->updateSubObjects();
  550. }
  551. }
  552. //-------------------------------------------------------------------------------------------------
  553. void Drawable::showSubObject( const AsciiString& name, Bool show )
  554. {
  555. for (DrawModule** dm = getDrawModules(); *dm; ++dm)
  556. {
  557. ObjectDrawInterface* di = (*dm)->getObjectDrawInterface();
  558. if (di)
  559. {
  560. di->showSubObject( name, show );
  561. }
  562. }
  563. }
  564. #ifdef ALLOW_ANIM_INQUIRIES
  565. // srj sez: not sure if this is a good idea, for net sync reasons...
  566. //-------------------------------------------------------------------------------------------------
  567. /**
  568. This call asks, "In the current animation (if any) how far along are you, from 0.0f to 1.0f".
  569. */
  570. Real Drawable::getAnimationScrubScalar( void ) const // lorenzen
  571. {
  572. for (const DrawModule** dm = getDrawModules(); *dm; ++dm)
  573. {
  574. const ObjectDrawInterface* di = (*dm)->getObjectDrawInterface();
  575. if (di)
  576. {
  577. return di->getAnimationScrubScalar();
  578. }
  579. }
  580. return 0.0f;
  581. }
  582. #endif
  583. //-------------------------------------------------------------------------------------------------
  584. Int Drawable::getPristineBonePositions(const char* boneNamePrefix, Int startIndex, Coord3D* positions, Matrix3D* transforms, Int maxBones) const
  585. {
  586. Int count = 0;
  587. for (const DrawModule** dm = getDrawModules(); *dm; ++dm)
  588. {
  589. if (maxBones <= 0)
  590. break;
  591. const ObjectDrawInterface* di = (*dm)->getObjectDrawInterface();
  592. if (di)
  593. {
  594. Int subcount =
  595. di->getPristineBonePositionsForConditionState(m_conditionState, boneNamePrefix, startIndex, positions, transforms, maxBones);
  596. if (subcount > 0)
  597. {
  598. count += subcount;
  599. if (positions)
  600. positions += subcount;
  601. if (transforms)
  602. transforms += subcount;
  603. maxBones -= subcount;
  604. }
  605. }
  606. }
  607. return count;
  608. }
  609. //-------------------------------------------------------------------------------------------------
  610. Int Drawable::getCurrentClientBonePositions(const char* boneNamePrefix, Int startIndex, Coord3D* positions, Matrix3D* transforms, Int maxBones) const
  611. {
  612. Int count = 0;
  613. for (const DrawModule** dm = getDrawModules(); *dm; ++dm)
  614. {
  615. if (maxBones <= 0)
  616. break;
  617. const ObjectDrawInterface* di = (*dm)->getObjectDrawInterface();
  618. if (di)
  619. {
  620. Int subcount =
  621. di->getCurrentBonePositions(boneNamePrefix, startIndex, positions, transforms, maxBones);
  622. if (subcount > 0)
  623. {
  624. count += subcount;
  625. if (positions)
  626. positions += subcount;
  627. if (transforms)
  628. transforms += subcount;
  629. maxBones -= subcount;
  630. }
  631. }
  632. }
  633. return count;
  634. }
  635. //-------------------------------------------------------------------------------------------------
  636. Bool Drawable::getCurrentWorldspaceClientBonePositions(const char* boneName, Matrix3D& transform) const
  637. {
  638. for (const DrawModule** dm = getDrawModules(); *dm; ++dm)
  639. {
  640. const ObjectDrawInterface* di = (*dm)->getObjectDrawInterface();
  641. if (di && di->getCurrentWorldspaceClientBonePositions(boneName, transform))
  642. return true;
  643. }
  644. return false;
  645. }
  646. //-------------------------------------------------------------------------------------------------
  647. /** Attach to a particle system */
  648. //-------------------------------------------------------------------------------------------------
  649. void Drawable::attachToParticleSystem( Particle *p )
  650. {
  651. m_particle = p;
  652. }
  653. //-------------------------------------------------------------------------------------------------
  654. /** Detach from a particle system, if attached */
  655. //-------------------------------------------------------------------------------------------------
  656. void Drawable::detachFromParticleSystem( void )
  657. {
  658. if (m_particle)
  659. {
  660. m_particle->detachDrawable();
  661. m_particle = NULL;
  662. }
  663. }
  664. //-------------------------------------------------------------------------------------------------
  665. void Drawable::setTerrainDecal(TerrainDecalType type)
  666. {
  667. if (m_terrainDecalType == type)
  668. return;
  669. m_terrainDecalType=type;
  670. DrawModule** dm = getDrawModules();
  671. //Only the first draw module gets a decal to prevent stacking.
  672. //Should be okay as long as we keep the primary object in the
  673. //first module.
  674. if (*dm)
  675. (*dm)->setTerrainDecal(type);
  676. }
  677. //-------------------------------------------------------------------------------------------------
  678. void Drawable::setTerrainDecalSize(Real x, Real y)
  679. {
  680. DrawModule** dm = getDrawModules();
  681. if (*dm)
  682. (*dm)->setTerrainDecalSize(x,y);
  683. }
  684. //-------------------------------------------------------------------------------------------------
  685. void Drawable::setTerrainDecalFadeTarget(Real target, Real rate)
  686. {
  687. if (m_decalOpacityFadeTarget != target)
  688. {
  689. m_decalOpacityFadeTarget = target;
  690. m_decalOpacityFadeRate = rate;
  691. }
  692. //else
  693. // m_decalOpacityFadeRate = 0;
  694. }
  695. //-------------------------------------------------------------------------------------------------
  696. void Drawable::setShadowsEnabled(Bool enable)
  697. {
  698. // set status bit
  699. if( enable )
  700. setDrawableStatus( DRAWABLE_STATUS_SHADOWS );
  701. else
  702. clearDrawableStatus( DRAWABLE_STATUS_SHADOWS );
  703. for (DrawModule** dm = getDrawModules(); *dm; ++dm)
  704. {
  705. (*dm)->setShadowsEnabled(enable);
  706. }
  707. }
  708. //-------------------------------------------------------------------------------------------------
  709. /**frees all shadow resources used by this module - used by Options screen.*/
  710. void Drawable::releaseShadows(void)
  711. {
  712. for (DrawModule** dm = getDrawModules(); *dm; ++dm)
  713. {
  714. (*dm)->releaseShadows();
  715. }
  716. }
  717. //-------------------------------------------------------------------------------------------------
  718. /**create shadow resources if not already present. Used by Options screen.*/
  719. void Drawable::allocateShadows(void)
  720. {
  721. for (DrawModule** dm = getDrawModules(); *dm; ++dm)
  722. {
  723. (*dm)->allocateShadows();
  724. }
  725. }
  726. //-------------------------------------------------------------------------------------------------
  727. void Drawable::setFullyObscuredByShroud(Bool fullyObscured)
  728. {
  729. if (m_drawableFullyObscuredByShroud != fullyObscured)
  730. {
  731. for (DrawModule** dm = getDrawModules(); *dm; ++dm)
  732. {
  733. (*dm)->setFullyObscuredByShroud(fullyObscured);
  734. }
  735. m_drawableFullyObscuredByShroud = fullyObscured;
  736. }
  737. }
  738. //-------------------------------------------------------------------------------------------------
  739. /** Set drawable's "selected" status, if not already set. Also update running
  740. * total count of selected drawables. */
  741. //-------------------------------------------------------------------------------------------------
  742. void Drawable::friend_setSelected( void )
  743. {
  744. if(isSelected() == false)
  745. {
  746. m_selected = TRUE;
  747. onSelected();
  748. }
  749. }
  750. //-------------------------------------------------------------------------------------------------
  751. /** Clear drawable's "selected" status, if not already clear. Also update running
  752. * total count of selected drawables. */
  753. //-------------------------------------------------------------------------------------------------
  754. void Drawable::friend_clearSelected( void )
  755. {
  756. if(isSelected())
  757. {
  758. m_selected = FALSE;
  759. onUnselected();
  760. }
  761. }
  762. // ------------------------------------------------------------------------------------------------
  763. /** Flash the drawable with the color */
  764. // ------------------------------------------------------------------------------------------------
  765. void Drawable::colorFlash( const RGBColor* color, UnsignedInt decayFrames, UnsignedInt attackFrames, UnsignedInt sustainAtPeak )
  766. {
  767. if (m_colorTintEnvelope == NULL)
  768. m_colorTintEnvelope = newInstance(TintEnvelope);
  769. if( color )
  770. {
  771. m_colorTintEnvelope->play( color, attackFrames, decayFrames, sustainAtPeak);
  772. }
  773. else
  774. {
  775. RGBColor white;
  776. white.setFromInt(0xffffffff);
  777. m_colorTintEnvelope->play( &white );
  778. }
  779. // make sure the tint color is unlocked so we "fade back down" to normal
  780. clearDrawableStatus( DRAWABLE_STATUS_TINT_COLOR_LOCKED );
  781. }
  782. // ------------------------------------------------------------------------------------------------
  783. /** Tint a drawable a specified color */
  784. // ------------------------------------------------------------------------------------------------
  785. void Drawable::colorTint( const RGBColor* color )
  786. {
  787. if( color )
  788. {
  789. // set the color via color flash
  790. colorFlash( color, 0, 0, TRUE );
  791. // lock the tint color so the flash never "fades back down"
  792. setDrawableStatus( DRAWABLE_STATUS_TINT_COLOR_LOCKED );
  793. }
  794. else
  795. {
  796. if (m_colorTintEnvelope == NULL)
  797. m_colorTintEnvelope = newInstance(TintEnvelope);
  798. // remove the tint applied to the object
  799. m_colorTintEnvelope->rest();
  800. // set the tint as unlocked so we can flash and stuff again
  801. clearDrawableStatus( DRAWABLE_STATUS_TINT_COLOR_LOCKED );
  802. }
  803. }
  804. //-------------------------------------------------------------------------------------------------
  805. /** Gathering point for all things besides actual selection that must happen on selection */
  806. //-------------------------------------------------------------------------------------------------
  807. void Drawable::onSelected()
  808. {
  809. flashAsSelected();//much simpler
  810. Object* obj = getObject();
  811. if ( obj )
  812. {
  813. ContainModuleInterface* contain = obj->getContain();
  814. if ( contain )
  815. {
  816. contain->clientVisibleContainedFlashAsSelected();
  817. }
  818. }
  819. } // end onSelected
  820. //-------------------------------------------------------------------------------------------------
  821. /** Gathering point for all things besides actual selection that must happen on deselection */
  822. //-------------------------------------------------------------------------------------------------
  823. void Drawable::onUnselected()
  824. {
  825. // nothing
  826. }
  827. //-------------------------------------------------------------------------------------------------
  828. /** get FX color value to add to ALL LIGHTS when drawing */
  829. //-------------------------------------------------------------------------------------------------
  830. const Vector3 * Drawable::getTintColor( void ) const
  831. {
  832. if ( m_colorTintEnvelope )
  833. {
  834. if (m_colorTintEnvelope->isEffective())
  835. {
  836. return m_colorTintEnvelope->getColor();
  837. }
  838. }
  839. return NULL;
  840. }
  841. //-------------------------------------------------------------------------------------------------
  842. /** get SELECTION color value to add to ALL LIGHTS when drawing */
  843. //-------------------------------------------------------------------------------------------------
  844. const Vector3 * Drawable::getSelectionColor( void ) const
  845. {
  846. if (m_selectionFlashEnvelope)
  847. {
  848. if (m_selectionFlashEnvelope->isEffective())
  849. {
  850. return m_selectionFlashEnvelope->getColor();
  851. }
  852. }
  853. return NULL;
  854. }
  855. //-------------------------------------------------------------------------------------------------
  856. /** fades the object out gradually...how gradually is determined by number of frames */
  857. //-------------------------------------------------------------------------------------------------
  858. void Drawable::fadeOut( UnsignedInt frames ) ///< cloak object
  859. {
  860. setDrawableOpacity(1.0);
  861. m_fadeMode = FADING_OUT;
  862. m_timeToFade = frames;
  863. m_timeElapsedFade = 0;
  864. }
  865. //-------------------------------------------------------------------------------------------------
  866. /** fades the object in gradually...how gradually is determined by number of frames */
  867. //-------------------------------------------------------------------------------------------------
  868. void Drawable::fadeIn( UnsignedInt frames ) ///< decloak object
  869. {
  870. setDrawableOpacity(0.0);
  871. m_fadeMode = FADING_IN;
  872. m_timeToFade = frames;
  873. m_timeElapsedFade = 0;
  874. }
  875. //-------------------------------------------------------------------------------------------------
  876. const Real Drawable::getScale (void) const
  877. {
  878. return m_instanceScale;
  879. // return getTemplate()->getAssetScale();
  880. }
  881. //-------------------------------------------------------------------------------------------------
  882. //-------------------------------------------------------------------------------------------------
  883. void Drawable::reactToBodyDamageStateChange(BodyDamageType newState)
  884. {
  885. static const ModelConditionFlagType TheDamageMap[BODYDAMAGETYPE_COUNT] =
  886. {
  887. MODELCONDITION_INVALID,
  888. MODELCONDITION_DAMAGED,
  889. MODELCONDITION_REALLY_DAMAGED,
  890. MODELCONDITION_RUBBLE,
  891. };
  892. ModelConditionFlags newDamage;
  893. if (TheDamageMap[newState] != MODELCONDITION_INVALID)
  894. newDamage.set(TheDamageMap[newState]);
  895. clearAndSetModelConditionFlags(
  896. MAKE_MODELCONDITION_MASK3(MODELCONDITION_DAMAGED, MODELCONDITION_REALLY_DAMAGED, MODELCONDITION_RUBBLE),
  897. newDamage);
  898. startAmbientSound(newState, TheGlobalData->m_timeOfDay);
  899. }
  900. //-------------------------------------------------------------------------------------------------
  901. void Drawable::setEffectiveOpacity( Real pulseFactor, Real explicitOpacity /* = -1.0f */)
  902. {
  903. if( explicitOpacity != -1.0f )
  904. {
  905. m_stealthOpacity = MIN( 1.0f, MAX( 0.0f, explicitOpacity ) );
  906. }
  907. Real pf = MIN(1.0f, MAX(0.0f, pulseFactor));
  908. Real pulseMargin = (1.0f - m_stealthOpacity);
  909. Real pulseAmount = pulseMargin * pf;
  910. m_effectiveStealthOpacity = m_stealthOpacity + pulseAmount;
  911. } ///< get alpha/opacity value used to override defaults when drawing.
  912. //-------------------------------------------------------------------------------------------------
  913. /** update is called once per frame */
  914. //-------------------------------------------------------------------------------------------------
  915. //DECLARE_PERF_TIMER(updateDrawable)
  916. void Drawable::updateDrawable( void )
  917. {
  918. //USE_PERF_TIMER(updateDrawable)
  919. UnsignedInt now = TheGameLogic->getFrame();
  920. Object *obj = getObject();
  921. {
  922. for (ClientUpdateModule** cu = getClientUpdateModules(); cu && *cu; ++cu)
  923. {
  924. (*cu)->clientUpdate();
  925. }
  926. }
  927. {
  928. // handle fading in or out
  929. if (m_fadeMode != FADING_NONE)
  930. {
  931. Real numer = (m_fadeMode == FADING_IN) ? (m_timeElapsedFade) : (m_timeToFade-m_timeElapsedFade);
  932. setDrawableOpacity(numer/(Real)m_timeToFade);
  933. ++m_timeElapsedFade;
  934. if (m_timeElapsedFade > m_timeToFade)
  935. m_fadeMode = FADING_NONE;
  936. }
  937. }
  938. if ( getTerrainDecalType() != TERRAIN_DECAL_NONE )
  939. {
  940. DrawModule** dm = getDrawModules();
  941. if (*dm)
  942. {
  943. if (m_decalOpacityFadeRate != 0)
  944. {
  945. //LERP
  946. (*dm)->setTerrainDecalOpacity(m_decalOpacity);
  947. m_decalOpacity += m_decalOpacityFadeRate;
  948. }
  949. //---------------
  950. if (m_decalOpacityFadeRate < 0 && m_decalOpacity <= 0 )
  951. {
  952. m_decalOpacityFadeRate = 0.0f;
  953. m_decalOpacity = 0.0f;
  954. this->setTerrainDecal(TERRAIN_DECAL_NONE);
  955. }
  956. else if (m_decalOpacityFadeRate > 0 && m_decalOpacity >= 1.0f)
  957. {
  958. m_decalOpacity = 1.0f;
  959. m_decalOpacityFadeRate = 0.0f;
  960. (*dm)->setTerrainDecalOpacity(m_decalOpacity);
  961. }
  962. }//end if (*dm)
  963. }
  964. else
  965. m_decalOpacity = 0;
  966. {
  967. if (m_expirationDate != 0 && now >= m_expirationDate)
  968. {
  969. DEBUG_ASSERTCRASH(obj == NULL, ("Drawables with Objects should not have expiration dates!"));
  970. TheGameClient->destroyDrawable(this);
  971. return;
  972. }
  973. }
  974. {
  975. if (m_flashCount > 0 && (TheGameClient->getFrame() % DRAWABLE_FRAMES_PER_FLASH) == 0)
  976. {
  977. RGBColor tmp;
  978. tmp.setFromInt(m_flashColor);
  979. colorFlash(&tmp);
  980. m_flashCount--;
  981. }
  982. }
  983. //Lets figure out whether we should be changing colors right about now
  984. // we'll use an ifelseif ladder since we are scanning bits
  985. if( m_prevTintStatus != m_tintStatus )// edge test
  986. {
  987. if ( testTintStatus( TINT_STATUS_DISABLED ) )
  988. {
  989. if (m_colorTintEnvelope == NULL)
  990. m_colorTintEnvelope = newInstance(TintEnvelope);
  991. m_colorTintEnvelope->play( &DARK_GRAY_DISABLED_COLOR, 30, 30, SUSTAIN_INDEFINITELY);
  992. }
  993. // else if ( testTintStatus( TINT_STATUS_POISONED) )
  994. // {
  995. // if (m_colorTintEnvelope == NULL)
  996. // m_colorTintEnvelope = newInstance(TintEnvelope);
  997. // m_colorTintEnvelope->play( &SICKLY_GREEN_POISONED_COLOR, 30, 30, SUSTAIN_INDEFINITELY);
  998. // }
  999. // else if ( testTintStatus( TINT_STATUS_IRRADIATED) )
  1000. // {
  1001. // if (m_colorTintEnvelope == NULL)
  1002. // m_colorTintEnvelope = newInstance(TintEnvelope);
  1003. // m_colorTintEnvelope->play( &RED_IRRADIATED_COLOR, 30, 30, SUSTAIN_INDEFINITELY);
  1004. // }
  1005. else
  1006. {
  1007. // NO TINTING SHOULD BE PRESENT
  1008. if (m_colorTintEnvelope == NULL)
  1009. m_colorTintEnvelope = newInstance(TintEnvelope);
  1010. m_colorTintEnvelope->release(); // head on back to normal, now
  1011. }
  1012. }
  1013. m_prevTintStatus = m_tintStatus;//for next frame
  1014. if ( obj )
  1015. {
  1016. if ( ! obj->isEffectivelyDead() )
  1017. clearTintStatus( TINT_STATUS_IRRADIATED); // so the res glow stops when not exposed
  1018. }
  1019. if (m_colorTintEnvelope)
  1020. m_colorTintEnvelope->update(); // defector fx, disable fx, etc...
  1021. if (m_selectionFlashEnvelope)
  1022. m_selectionFlashEnvelope->update(); // selection flashing
  1023. //If we have an ambient sound, and we aren't currently playing it, attempt to play it now
  1024. if( m_ambientSound && m_ambientSoundEnabled && !m_ambientSound->m_event.getEventName().isEmpty() && !m_ambientSound->m_event.isCurrentlyPlaying() )
  1025. {
  1026. startAmbientSound();
  1027. }
  1028. }
  1029. //-------------------------------------------------------------------------------------------------
  1030. void Drawable::flashAsSelected( const RGBColor *color ) ///< drawable takes care of the details if you spec no color
  1031. {
  1032. if (m_selectionFlashEnvelope == NULL)
  1033. m_selectionFlashEnvelope = newInstance(TintEnvelope);
  1034. if ( color )
  1035. {
  1036. m_selectionFlashEnvelope->play( color, 0, 4 );
  1037. }
  1038. else
  1039. {
  1040. Object *obj = getObject();
  1041. if (obj)
  1042. {
  1043. RGBColor tempColor;
  1044. if (TheGlobalData->m_selectionFlashHouseColor)
  1045. tempColor.setFromInt(obj->getIndicatorColor());
  1046. else
  1047. tempColor.setFromInt(0xffffffff);//white
  1048. Real saturation = TheGlobalData->m_selectionFlashSaturationFactor;
  1049. saturateRGB( tempColor, saturation );
  1050. m_selectionFlashEnvelope->play( &tempColor, 0, 4 );
  1051. }
  1052. }
  1053. }
  1054. //-------------------------------------------------------------------------------------------------
  1055. void Drawable::applyPhysicsXform(Matrix3D* mtx)
  1056. {
  1057. const Object *obj = getObject();
  1058. if( !obj || obj->isDisabledByType( DISABLED_HELD ) || !TheGlobalData->m_showClientPhysics )
  1059. {
  1060. return;
  1061. }
  1062. Bool frozen = TheTacticalView->isTimeFrozen() && !TheTacticalView->isCameraMovementFinished();
  1063. frozen = frozen || TheScriptEngine->isTimeFrozenDebug() || TheScriptEngine->isTimeFrozenScript();
  1064. if (frozen)
  1065. return;
  1066. PhysicsXformInfo info;
  1067. if (calcPhysicsXform(info))
  1068. {
  1069. mtx->Translate(0.0f, 0.0f, info.m_totalZ);
  1070. mtx->Rotate_Y( info.m_totalPitch );
  1071. mtx->Rotate_X( -info.m_totalRoll );
  1072. mtx->Rotate_Z( info.m_totalYaw );
  1073. }
  1074. }
  1075. //-------------------------------------------------------------------------------------------------
  1076. //-------------------------------------------------------------------------------------------------
  1077. Bool Drawable::calcPhysicsXform(PhysicsXformInfo& info)
  1078. {
  1079. const Object* obj = getObject();
  1080. const AIUpdateInterface *ai = obj ? obj->getAIUpdateInterface() : NULL;
  1081. Bool hasPhysicsXform = false;
  1082. if (ai)
  1083. {
  1084. const Locomotor *locomotor = ai->getCurLocomotor();
  1085. if (locomotor)
  1086. {
  1087. switch (locomotor->getAppearance())
  1088. {
  1089. case LOCO_WHEELS_FOUR:
  1090. calcPhysicsXformWheels(locomotor, info);
  1091. hasPhysicsXform = true;
  1092. break;
  1093. case LOCO_TREADS:
  1094. calcPhysicsXformTreads(locomotor, info);
  1095. hasPhysicsXform = true;
  1096. break;
  1097. case LOCO_HOVER:
  1098. case LOCO_WINGS:
  1099. calcPhysicsXformHoverOrWings(locomotor, info);
  1100. hasPhysicsXform = true;
  1101. break;
  1102. case LOCO_THRUST:
  1103. calcPhysicsXformThrust(locomotor, info);
  1104. hasPhysicsXform = true;
  1105. break;
  1106. }
  1107. }
  1108. }
  1109. if (hasPhysicsXform)
  1110. {
  1111. // HOTFIX: Ensure that we are not passing denormalized values back to caller
  1112. // @todo remove hotfix
  1113. if (info.m_totalPitch>-1e-20f&&info.m_totalPitch<1e-20f)
  1114. info.m_totalPitch=0.f;
  1115. if (info.m_totalRoll>-1e-20f&&info.m_totalRoll<1e-20f)
  1116. info.m_totalRoll=0.f;
  1117. if (info.m_totalYaw>-1e-20f&&info.m_totalYaw<1e-20f)
  1118. info.m_totalYaw=0.f;
  1119. if (info.m_totalZ>-1e-20f&&info.m_totalZ<1e-20f)
  1120. info.m_totalZ=0.f;
  1121. }
  1122. return hasPhysicsXform;
  1123. }
  1124. // ------------------------------------------------------------------------------------------------
  1125. // ------------------------------------------------------------------------------------------------
  1126. void Drawable::calcPhysicsXformThrust( const Locomotor *locomotor, PhysicsXformInfo& info )
  1127. {
  1128. if (m_locoInfo == NULL)
  1129. m_locoInfo = newInstance(DrawableLocoInfo);
  1130. Real THRUST_ROLL = locomotor->getThrustRoll();
  1131. Real WOBBLE_RATE = locomotor->getWobbleRate();
  1132. Real MAX_WOBBLE = locomotor->getMaxWobble();
  1133. Real MIN_WOBBLE = locomotor->getMinWobble();
  1134. //
  1135. // this is a kind of quick thrust implementation cause we need scud missiles to wobble *now*,
  1136. // we deal with just adjusting pitch, yaw, and roll just a little bit
  1137. //
  1138. if( WOBBLE_RATE )
  1139. {
  1140. if( m_locoInfo->m_wobble >= 1.0f )
  1141. {
  1142. if( m_locoInfo->m_pitch < MAX_WOBBLE - WOBBLE_RATE * 2 )
  1143. {
  1144. m_locoInfo->m_pitch += WOBBLE_RATE;
  1145. m_locoInfo->m_yaw += WOBBLE_RATE;
  1146. } // end if
  1147. else
  1148. {
  1149. m_locoInfo->m_pitch += (WOBBLE_RATE / 2.0f);
  1150. m_locoInfo->m_yaw += (WOBBLE_RATE / 2.0f);
  1151. } // end else
  1152. if( m_locoInfo->m_pitch >= MAX_WOBBLE )
  1153. m_locoInfo->m_wobble = -1.0f;
  1154. } // end if
  1155. else
  1156. {
  1157. if( m_locoInfo->m_pitch >= MIN_WOBBLE + WOBBLE_RATE * 2.0f )
  1158. {
  1159. m_locoInfo->m_pitch -= WOBBLE_RATE;
  1160. m_locoInfo->m_yaw -= WOBBLE_RATE;
  1161. } // end if
  1162. else
  1163. {
  1164. m_locoInfo->m_pitch -= (WOBBLE_RATE / 2.0f);
  1165. m_locoInfo->m_yaw -= (WOBBLE_RATE / 2.0f);
  1166. } // end else
  1167. if( m_locoInfo->m_pitch <= MIN_WOBBLE )
  1168. m_locoInfo->m_wobble = 1.0f;
  1169. } // end else
  1170. info.m_totalPitch = m_locoInfo->m_pitch;
  1171. info.m_totalYaw = m_locoInfo->m_yaw;
  1172. } // end if, wobble exists
  1173. if( THRUST_ROLL )
  1174. {
  1175. m_locoInfo->m_roll += THRUST_ROLL;
  1176. info.m_totalRoll = m_locoInfo->m_roll;
  1177. } // end if
  1178. }
  1179. //-------------------------------------------------------------------------------------------------
  1180. //-------------------------------------------------------------------------------------------------
  1181. void Drawable::calcPhysicsXformHoverOrWings( const Locomotor *locomotor, PhysicsXformInfo& info )
  1182. {
  1183. if (m_locoInfo == NULL)
  1184. m_locoInfo = newInstance(DrawableLocoInfo);
  1185. const Real ACCEL_PITCH_LIMIT = locomotor->getAccelPitchLimit();
  1186. const Real PITCH_STIFFNESS = locomotor->getPitchStiffness();
  1187. const Real ROLL_STIFFNESS = locomotor->getRollStiffness();
  1188. const Real PITCH_DAMPING = locomotor->getPitchDamping();
  1189. const Real ROLL_DAMPING = locomotor->getRollDamping();
  1190. const Real Z_VEL_PITCH_COEFF = locomotor->getPitchByZVelCoef();
  1191. const Real FORWARD_VEL_COEFF = locomotor->getForwardVelCoef();
  1192. const Real LATERAL_VEL_COEFF = locomotor->getLateralVelCoef();
  1193. const Real FORWARD_ACCEL_COEFF = locomotor->getForwardAccelCoef();
  1194. const Real LATERAL_ACCEL_COEFF = locomotor->getLateralAccelCoef();
  1195. const Real UNIFORM_AXIAL_DAMPING = locomotor->getUniformAxialDamping();
  1196. // get object from logic
  1197. Object *obj = getObject();
  1198. if (obj == NULL)
  1199. return;
  1200. AIUpdateInterface *ai = obj->getAIUpdateInterface();
  1201. if (ai == NULL)
  1202. return;
  1203. // get object physics state
  1204. PhysicsBehavior *physics = obj->getPhysics();
  1205. if (physics == NULL)
  1206. return;
  1207. // get our position and direction vector
  1208. //const Coord3D *pos = getPosition();
  1209. const Coord3D* dir = getUnitDirectionVector2D();
  1210. const Coord3D* accel = physics->getAcceleration();
  1211. const Coord3D* vel = physics->getVelocity();
  1212. m_locoInfo->m_pitchRate += ((-PITCH_STIFFNESS * m_locoInfo->m_pitch) + (-PITCH_DAMPING * m_locoInfo->m_pitchRate)); // spring/damper
  1213. m_locoInfo->m_rollRate += ((-ROLL_STIFFNESS * m_locoInfo->m_roll) + (-ROLL_DAMPING * m_locoInfo->m_rollRate)); // spring/damper
  1214. m_locoInfo->m_pitch += m_locoInfo->m_pitchRate * UNIFORM_AXIAL_DAMPING;
  1215. m_locoInfo->m_roll += m_locoInfo->m_rollRate * UNIFORM_AXIAL_DAMPING;
  1216. // process chassis acceleration dynamics - damp back towards zero
  1217. m_locoInfo->m_accelerationPitchRate += ((-PITCH_STIFFNESS * (m_locoInfo->m_accelerationPitch)) + (-PITCH_DAMPING * m_locoInfo->m_accelerationPitchRate)); // spring/damper
  1218. m_locoInfo->m_accelerationPitch += m_locoInfo->m_accelerationPitchRate;
  1219. m_locoInfo->m_accelerationRollRate += ((-ROLL_STIFFNESS * m_locoInfo->m_accelerationRoll) + (-ROLL_DAMPING * m_locoInfo->m_accelerationRollRate)); // spring/damper
  1220. m_locoInfo->m_accelerationRoll += m_locoInfo->m_accelerationRollRate;
  1221. // compute total pitch and roll of tank
  1222. info.m_totalPitch = m_locoInfo->m_pitch + m_locoInfo->m_accelerationPitch;
  1223. info.m_totalRoll = m_locoInfo->m_roll + m_locoInfo->m_accelerationRoll;
  1224. if (physics->isMotive())
  1225. {
  1226. if (Z_VEL_PITCH_COEFF != 0.0f)
  1227. {
  1228. const Real TINY_DZ = 0.001f;
  1229. if (fabs(vel->z) > TINY_DZ)
  1230. {
  1231. Real pitch = atan2(vel->z, sqrt(sqr(vel->x)+sqr(vel->y)));
  1232. m_locoInfo->m_pitch -= Z_VEL_PITCH_COEFF * pitch;
  1233. }
  1234. }
  1235. // cause the chassis to pitch & roll in reaction to current speed
  1236. Real forwardVel = dir->x * vel->x + dir->y * vel->y;
  1237. m_locoInfo->m_pitch += -(FORWARD_VEL_COEFF * forwardVel);
  1238. Real lateralVel = -dir->y * vel->x + dir->x * vel->y;
  1239. m_locoInfo->m_roll += -(LATERAL_VEL_COEFF * lateralVel);
  1240. // cause the chassis to pitch & roll in reaction to acceleration/deceleration
  1241. Real forwardAccel = dir->x * accel->x + dir->y * accel->y;
  1242. m_locoInfo->m_accelerationPitchRate += -(FORWARD_ACCEL_COEFF * forwardAccel);
  1243. Real lateralAccel = -dir->y * accel->x + dir->x * accel->y;
  1244. m_locoInfo->m_accelerationRollRate += -(LATERAL_ACCEL_COEFF * lateralAccel);
  1245. }
  1246. // limit acceleration pitch and roll
  1247. if (m_locoInfo->m_accelerationPitch > ACCEL_PITCH_LIMIT)
  1248. m_locoInfo->m_accelerationPitch = ACCEL_PITCH_LIMIT;
  1249. else if (m_locoInfo->m_accelerationPitch < -ACCEL_PITCH_LIMIT)
  1250. m_locoInfo->m_accelerationPitch = -ACCEL_PITCH_LIMIT;
  1251. if (m_locoInfo->m_accelerationRoll > ACCEL_PITCH_LIMIT)
  1252. m_locoInfo->m_accelerationRoll = ACCEL_PITCH_LIMIT;
  1253. else if (m_locoInfo->m_accelerationRoll < -ACCEL_PITCH_LIMIT)
  1254. m_locoInfo->m_accelerationRoll = -ACCEL_PITCH_LIMIT;
  1255. info.m_totalZ = 0.0f;
  1256. }
  1257. //-------------------------------------------------------------------------------------------------
  1258. //-------------------------------------------------------------------------------------------------
  1259. void Drawable::calcPhysicsXformTreads( const Locomotor *locomotor, PhysicsXformInfo& info )
  1260. {
  1261. if (m_locoInfo == NULL)
  1262. m_locoInfo = newInstance(DrawableLocoInfo);
  1263. const Real OVERLAP_SHRINK_FACTOR = 0.8f;
  1264. const Real FLATTENED_OBJECT_HEIGHT = 0.5f;
  1265. const Real LEAVE_OVERLAP_PITCH_KICK = PI/128;
  1266. const Real OVERLAP_ROUGH_VIBRATION_FACTOR = 5.0f;
  1267. const Real MAX_ROUGH_VIBRATION = 0.5f;
  1268. const Real ACCEL_PITCH_LIMIT = locomotor->getAccelPitchLimit();
  1269. const Real PITCH_STIFFNESS = locomotor->getPitchStiffness();
  1270. const Real ROLL_STIFFNESS = locomotor->getRollStiffness();
  1271. const Real PITCH_DAMPING = locomotor->getPitchDamping();
  1272. const Real ROLL_DAMPING = locomotor->getRollDamping();
  1273. const Real FORWARD_ACCEL_COEFF = locomotor->getForwardAccelCoef();
  1274. const Real LATERAL_ACCEL_COEFF = locomotor->getLateralAccelCoef();
  1275. const Real UNIFORM_AXIAL_DAMPING = locomotor->getUniformAxialDamping();
  1276. // get object from logic
  1277. Object *obj = getObject();
  1278. if (obj == NULL)
  1279. return;
  1280. AIUpdateInterface *ai = obj->getAIUpdateInterface();
  1281. if (ai == NULL)
  1282. return ;
  1283. // get object physics state
  1284. PhysicsBehavior *physics = obj->getPhysics();
  1285. if (physics == NULL)
  1286. return;
  1287. // get our position and direction vector
  1288. const Coord3D *pos = getPosition();
  1289. const Coord3D *dir = getUnitDirectionVector2D();
  1290. const Coord3D *accel = physics->getAcceleration();
  1291. const Coord3D *vel = physics->getVelocity();
  1292. // compute perpendicular (2d)
  1293. Coord3D perp;
  1294. perp.x = -dir->y;
  1295. perp.y = dir->x;
  1296. perp.z = 0.0f;
  1297. // find pitch and roll of terrain under chassis
  1298. Coord3D normal;
  1299. /* Real hheight = */ TheTerrainLogic->getLayerHeight( pos->x, pos->y, obj->getLayer(), &normal );
  1300. // override surface normal if we are overlapping another object - crushing it
  1301. Real overlapZ = 0.0f;
  1302. // get object we are currently overlapping, if any
  1303. Object* overlapped = TheGameLogic->findObjectByID(physics->getCurrentOverlap());
  1304. if (overlapped && overlapped->isKindOf(KINDOF_SHRUBBERY)) {
  1305. overlapped = NULL; // We just smash through shrubbery. jba.
  1306. }
  1307. if (overlapped)
  1308. {
  1309. const Coord3D *overPos = overlapped->getPosition();
  1310. Real dx = overPos->x - pos->x;
  1311. Real dy = overPos->y - pos->y;
  1312. Real centerDistSqr = sqr(dx) + sqr(dy);
  1313. // compute maximum distance between objects, if their edges just touched
  1314. Real ourSize = getDrawableGeometryInfo().getBoundingCircleRadius();
  1315. Real otherSize = overlapped->getGeometryInfo().getBoundingCircleRadius();
  1316. Real maxCenterDist = otherSize + ourSize;
  1317. // shrink the overlap distance a bit to avoid floating
  1318. maxCenterDist *= OVERLAP_SHRINK_FACTOR;
  1319. if (centerDistSqr < sqr(maxCenterDist))
  1320. {
  1321. Real centerDist = sqrtf(centerDistSqr);
  1322. Real amount = 1.0f - centerDist/maxCenterDist;
  1323. if (amount < 0.0f)
  1324. amount = 0.0f;
  1325. else if (amount > 1.0f)
  1326. amount = 1.0f;
  1327. // rough vibrations proportional to speed when we drive over something
  1328. Real rough = (vel->x*vel->x + vel->y*vel->y) * OVERLAP_ROUGH_VIBRATION_FACTOR;
  1329. if (rough > MAX_ROUGH_VIBRATION)
  1330. rough = MAX_ROUGH_VIBRATION;
  1331. Real height = overlapped->getGeometryInfo().getMaxHeightAbovePosition();
  1332. // do not "go up" flattened crushed things
  1333. Bool flat = false;
  1334. if (overlapped->isKindOf(KINDOF_LOW_OVERLAPPABLE) ||
  1335. overlapped->isKindOf(KINDOF_INFANTRY) ||
  1336. (overlapped->getBodyModule()->getFrontCrushed() && overlapped->getBodyModule()->getBackCrushed()))
  1337. {
  1338. flat = true;
  1339. height = FLATTENED_OBJECT_HEIGHT;
  1340. }
  1341. if (amount < FLATTENED_OBJECT_HEIGHT && flat == false)
  1342. {
  1343. overlapZ = height * 2.0f * amount;
  1344. // compute vector along "surface"
  1345. // not proportional to actual geometry to avoid overlay steep inclines, etc
  1346. Coord3D v;
  1347. v.x = dx/centerDist;
  1348. v.y = dy/centerDist;
  1349. v.z = 0.2f; // 0.25
  1350. Coord3D up;
  1351. up.x = GameClientRandomValueReal( -rough, rough );
  1352. up.y = GameClientRandomValueReal( -rough, rough );
  1353. up.z = 1.0f;
  1354. up.normalize();
  1355. Coord3D prp;
  1356. prp.crossProduct( &v, &up, &prp );
  1357. normal.crossProduct( &prp, &v, &normal );
  1358. // compute unit normal
  1359. normal.normalize();
  1360. }
  1361. else
  1362. {
  1363. // sitting on top of object
  1364. overlapZ = height;
  1365. normal.x = GameClientRandomValueReal( -rough, rough );
  1366. normal.y = GameClientRandomValueReal( -rough, rough );
  1367. normal.z = 1.0f;
  1368. normal.normalize();
  1369. }
  1370. }
  1371. }
  1372. else // no overlap this frame
  1373. {
  1374. // if we had an overlap last frame, and we're now in the air, give a
  1375. // kick to the pitch for effect
  1376. if (physics->getPreviousOverlap() != INVALID_ID && m_locoInfo->m_overlapZ > 0.0f)
  1377. m_locoInfo->m_pitchRate += LEAVE_OVERLAP_PITCH_KICK;
  1378. }
  1379. Real dot = normal.x * dir->x + normal.y * dir->y;
  1380. Real groundPitch = dot * (PI/2.0f);
  1381. dot = normal.x * perp.x + normal.y * perp.y;
  1382. Real groundRoll = dot * (PI/2.0f);
  1383. // process chassis suspension dynamics - damp back towards groundPitch
  1384. // the ground can only push back if we're touching it
  1385. if (overlapped || m_locoInfo->m_overlapZ <= 0.0f)
  1386. {
  1387. m_locoInfo->m_pitchRate += ((-PITCH_STIFFNESS * (m_locoInfo->m_pitch - groundPitch)) + (-PITCH_DAMPING * m_locoInfo->m_pitchRate)); // spring/damper
  1388. if (m_locoInfo->m_pitchRate > 0.0f)
  1389. m_locoInfo->m_pitchRate *= 0.5f;
  1390. m_locoInfo->m_rollRate += ((-ROLL_STIFFNESS * (m_locoInfo->m_roll - groundRoll)) + (-ROLL_DAMPING * m_locoInfo->m_rollRate)); // spring/damper
  1391. }
  1392. m_locoInfo->m_pitch += m_locoInfo->m_pitchRate * UNIFORM_AXIAL_DAMPING;
  1393. m_locoInfo->m_roll += m_locoInfo->m_rollRate * UNIFORM_AXIAL_DAMPING;
  1394. // process chassis recoil dynamics - damp back towards zero
  1395. m_locoInfo->m_accelerationPitchRate += ((-PITCH_STIFFNESS * (m_locoInfo->m_accelerationPitch)) + (-PITCH_DAMPING * m_locoInfo->m_accelerationPitchRate)); // spring/damper
  1396. m_locoInfo->m_accelerationPitch += m_locoInfo->m_accelerationPitchRate;
  1397. m_locoInfo->m_accelerationRollRate += ((-ROLL_STIFFNESS * m_locoInfo->m_accelerationRoll) + (-ROLL_DAMPING * m_locoInfo->m_accelerationRollRate)); // spring/damper
  1398. m_locoInfo->m_accelerationRoll += m_locoInfo->m_accelerationRollRate;
  1399. // compute total pitch and roll of tank
  1400. info.m_totalPitch = m_locoInfo->m_pitch + m_locoInfo->m_accelerationPitch;
  1401. info.m_totalRoll = m_locoInfo->m_roll + m_locoInfo->m_accelerationRoll;
  1402. if (physics->isMotive())
  1403. {
  1404. // cause the chassis to pitch & roll in reaction to acceleration/deceleration
  1405. Real forwardAccel = dir->x * accel->x + dir->y * accel->y;
  1406. m_locoInfo->m_accelerationPitchRate += -(FORWARD_ACCEL_COEFF * forwardAccel);
  1407. Real lateralAccel = -dir->y * accel->x + dir->x * accel->y;
  1408. m_locoInfo->m_accelerationRollRate += -(LATERAL_ACCEL_COEFF * lateralAccel);
  1409. }
  1410. #ifdef RECOIL_FROM_BEING_DAMAGED
  1411. // recoil from being hit
  1412. /// @todo Recoil needs to be based on sane damage amounts (MSB)
  1413. const DamageInfo *damageInfo = obj->getBodyModule()->getLastDamageInfo();
  1414. if (damageInfo)
  1415. {
  1416. if (obj->getBodyModule()->getLastDamageTimestamp() > m_lastDamageTimestamp && damageInfo->in.m_amount > RECOIL_DAMAGE)
  1417. {
  1418. Object *attacker = TheGameLogic->getObject( damageInfo->in.m_sourceID );
  1419. if (attacker)
  1420. {
  1421. Coord3D to;
  1422. ThePartitionManager->getVectorTo( obj, attacker, FROM_CENTER_2D, &to );
  1423. to.normalize();
  1424. Real forward = dir->x * to.x + dir->y * to.y;
  1425. Real lateral = perp.x * to.x + perp.y * to.y;
  1426. Real recoil = PI/16.0f * GameClientRandomValueReal( 0.5f, 1.0f );
  1427. m_locoInfo->m_accelerationPitchRate -= recoil * forward;
  1428. m_locoInfo->m_accelerationRollRate -= recoil * lateral;
  1429. }
  1430. m_lastDamageTimestamp = obj->getBodyModule()->getLastDamageTimestamp();
  1431. }
  1432. }
  1433. #endif
  1434. // limit recoil pitch and roll
  1435. if (m_locoInfo->m_accelerationPitch > ACCEL_PITCH_LIMIT)
  1436. m_locoInfo->m_accelerationPitch = ACCEL_PITCH_LIMIT;
  1437. else if (m_locoInfo->m_accelerationPitch < -ACCEL_PITCH_LIMIT)
  1438. m_locoInfo->m_accelerationPitch = -ACCEL_PITCH_LIMIT;
  1439. if (m_locoInfo->m_accelerationRoll > ACCEL_PITCH_LIMIT)
  1440. m_locoInfo->m_accelerationRoll = ACCEL_PITCH_LIMIT;
  1441. else if (m_locoInfo->m_accelerationRoll < -ACCEL_PITCH_LIMIT)
  1442. m_locoInfo->m_accelerationRoll = -ACCEL_PITCH_LIMIT;
  1443. // adjust z
  1444. if (overlapZ > m_locoInfo->m_overlapZ)
  1445. {
  1446. m_locoInfo->m_overlapZ = overlapZ;
  1447. /// @todo Z needs to accelerate/decelerate, not be directly set (MSB)
  1448. // m_locoInfo->m_overlapZ += 0.4f;
  1449. m_locoInfo->m_overlapZVel = 0.0f;
  1450. }
  1451. Real ztmp = m_locoInfo->m_overlapZ/2.0f;
  1452. // do fake Z physics
  1453. if (m_locoInfo->m_overlapZ > 0.0f)
  1454. {
  1455. m_locoInfo->m_overlapZVel -= 0.2f;
  1456. m_locoInfo->m_overlapZ += m_locoInfo->m_overlapZVel;
  1457. }
  1458. if (m_locoInfo->m_overlapZ <= 0.0f)
  1459. {
  1460. m_locoInfo->m_overlapZ = 0.0f;
  1461. m_locoInfo->m_overlapZVel = 0.0f;
  1462. }
  1463. info.m_totalZ = ztmp;
  1464. }
  1465. //-------------------------------------------------------------------------------------------------
  1466. //-------------------------------------------------------------------------------------------------
  1467. void Drawable::calcPhysicsXformWheels( const Locomotor *locomotor, PhysicsXformInfo& info )
  1468. {
  1469. if (m_locoInfo == NULL)
  1470. m_locoInfo = newInstance(DrawableLocoInfo);
  1471. const Real ACCEL_PITCH_LIMIT = locomotor->getAccelPitchLimit();
  1472. const Real BOUNCE_ANGLE_KICK = locomotor->getBounceKick();
  1473. const Real PITCH_STIFFNESS = locomotor->getPitchStiffness();
  1474. const Real ROLL_STIFFNESS = locomotor->getRollStiffness();
  1475. const Real PITCH_DAMPING = locomotor->getPitchDamping();
  1476. const Real ROLL_DAMPING = locomotor->getRollDamping();
  1477. const Real FORWARD_ACCEL_COEFF = locomotor->getForwardAccelCoef();
  1478. const Real LATERAL_ACCEL_COEFF = locomotor->getLateralAccelCoef();
  1479. const Real UNIFORM_AXIAL_DAMPING = locomotor->getUniformAxialDamping();
  1480. const Real MAX_SUSPENSION_EXTENSION = locomotor->getMaxWheelExtension(); //-2.3f;
  1481. // const Real MAX_SUSPENSION_COMPRESSION = locomotor->getMaxWheelCompression(); //1.4f;
  1482. const Real WHEEL_ANGLE = locomotor->getWheelTurnAngle(); //PI/8;
  1483. const Bool DO_WHEELS = locomotor->hasSuspension();
  1484. // get object from logic
  1485. Object *obj = getObject();
  1486. if (obj == NULL)
  1487. return;
  1488. AIUpdateInterface *ai = obj->getAIUpdateInterface();
  1489. if (ai == NULL)
  1490. return ;
  1491. // get object physics state
  1492. PhysicsBehavior *physics = obj->getPhysics();
  1493. if (physics == NULL)
  1494. return ;
  1495. // get our position and direction vector
  1496. const Coord3D *pos = getPosition();
  1497. const Coord3D *dir = getUnitDirectionVector2D();
  1498. const Coord3D *accel = physics->getAcceleration();
  1499. // compute perpendicular (2d)
  1500. Coord3D perp;
  1501. perp.x = -dir->y;
  1502. perp.y = dir->x;
  1503. perp.z = 0.0f;
  1504. // find pitch and roll of terrain under chassis
  1505. Coord3D normal;
  1506. Real hheight = TheTerrainLogic->getLayerHeight( pos->x, pos->y, obj->getLayer(), &normal );
  1507. Real dot = normal.x * dir->x + normal.y * dir->y;
  1508. Real groundPitch = dot * (PI/2.0f);
  1509. dot = normal.x * perp.x + normal.y * perp.y;
  1510. Real groundRoll = dot * (PI/2.0f);
  1511. Bool airborne = obj->isSignificantlyAboveTerrain();
  1512. if (airborne)
  1513. {
  1514. if (DO_WHEELS)
  1515. {
  1516. // Wheels extend when airborne.
  1517. m_locoInfo->m_wheelInfo.m_framesAirborne = 0;
  1518. m_locoInfo->m_wheelInfo.m_framesAirborneCounter++;
  1519. if (pos->z - hheight > -MAX_SUSPENSION_EXTENSION)
  1520. {
  1521. m_locoInfo->m_wheelInfo.m_rearLeftHeightOffset += (MAX_SUSPENSION_EXTENSION - m_locoInfo->m_wheelInfo.m_rearLeftHeightOffset)/2.0f;
  1522. m_locoInfo->m_wheelInfo.m_rearRightHeightOffset += (MAX_SUSPENSION_EXTENSION - m_locoInfo->m_wheelInfo.m_rearRightHeightOffset)/2.0f;
  1523. }
  1524. else
  1525. {
  1526. m_locoInfo->m_wheelInfo.m_rearLeftHeightOffset += (0 - m_locoInfo->m_wheelInfo.m_rearLeftHeightOffset)/2.0f;
  1527. m_locoInfo->m_wheelInfo.m_rearRightHeightOffset += (0 - m_locoInfo->m_wheelInfo.m_rearRightHeightOffset)/2.0f;
  1528. }
  1529. }
  1530. // Calculate suspension info.
  1531. Real length = obj->getGeometryInfo().getMajorRadius();
  1532. Real width = obj->getGeometryInfo().getMinorRadius();
  1533. Real pitchHeight = length*Sin(m_locoInfo->m_pitch + m_locoInfo->m_accelerationPitch - groundPitch);
  1534. Real rollHeight = width*Sin(m_locoInfo->m_roll + m_locoInfo->m_accelerationRoll - groundRoll);
  1535. info.m_totalZ = fabs(pitchHeight)/4 + fabs(rollHeight)/4;
  1536. return; // maintain the same orientation while we fly through the air.
  1537. }
  1538. // Bouncy.
  1539. Real curSpeed = physics->getVelocityMagnitude();
  1540. #if 1
  1541. Real maxSpeed = ai->getCurLocomotorSpeed();
  1542. if (!airborne && curSpeed > maxSpeed/10)
  1543. {
  1544. Real factor = curSpeed/maxSpeed;
  1545. if (fabs(m_locoInfo->m_pitchRate)<factor*BOUNCE_ANGLE_KICK/4 && fabs(m_locoInfo->m_rollRate)<factor*BOUNCE_ANGLE_KICK/8)
  1546. {
  1547. // do the bouncy.
  1548. switch (GameClientRandomValue(0,3))
  1549. {
  1550. case 0:
  1551. m_locoInfo->m_pitchRate -= BOUNCE_ANGLE_KICK*factor;
  1552. m_locoInfo->m_rollRate -= BOUNCE_ANGLE_KICK*factor/2;
  1553. break;
  1554. case 1:
  1555. m_locoInfo->m_pitchRate += BOUNCE_ANGLE_KICK*factor;
  1556. m_locoInfo->m_rollRate -= BOUNCE_ANGLE_KICK*factor/2;
  1557. break;
  1558. case 2:
  1559. m_locoInfo->m_pitchRate -= BOUNCE_ANGLE_KICK*factor;
  1560. m_locoInfo->m_rollRate += BOUNCE_ANGLE_KICK*factor/2;
  1561. break;
  1562. case 3:
  1563. m_locoInfo->m_pitchRate += BOUNCE_ANGLE_KICK*factor;
  1564. m_locoInfo->m_rollRate += BOUNCE_ANGLE_KICK*factor/2;
  1565. break;
  1566. }
  1567. }
  1568. }
  1569. #endif
  1570. // process chassis suspension dynamics - damp back towards groundPitch
  1571. // the ground can only push back if we're touching it
  1572. if (!airborne)
  1573. {
  1574. m_locoInfo->m_pitchRate += ((-PITCH_STIFFNESS * (m_locoInfo->m_pitch - groundPitch)) + (-PITCH_DAMPING * m_locoInfo->m_pitchRate)); // spring/damper
  1575. if (m_locoInfo->m_pitchRate > 0.0f)
  1576. m_locoInfo->m_pitchRate *= 0.5f;
  1577. m_locoInfo->m_rollRate += ((-ROLL_STIFFNESS * (m_locoInfo->m_roll - groundRoll)) + (-ROLL_DAMPING * m_locoInfo->m_rollRate)); // spring/damper
  1578. }
  1579. m_locoInfo->m_pitch += m_locoInfo->m_pitchRate * UNIFORM_AXIAL_DAMPING;
  1580. m_locoInfo->m_roll += m_locoInfo->m_rollRate * UNIFORM_AXIAL_DAMPING;
  1581. // process chassis acceleration dynamics - damp back towards zero
  1582. m_locoInfo->m_accelerationPitchRate += ((-PITCH_STIFFNESS * (m_locoInfo->m_accelerationPitch)) + (-PITCH_DAMPING * m_locoInfo->m_accelerationPitchRate)); // spring/damper
  1583. m_locoInfo->m_accelerationPitch += m_locoInfo->m_accelerationPitchRate;
  1584. m_locoInfo->m_accelerationRollRate += ((-ROLL_STIFFNESS * m_locoInfo->m_accelerationRoll) + (-ROLL_DAMPING * m_locoInfo->m_accelerationRollRate)); // spring/damper
  1585. m_locoInfo->m_accelerationRoll += m_locoInfo->m_accelerationRollRate;
  1586. // compute total pitch and roll of tank
  1587. info.m_totalPitch = m_locoInfo->m_pitch + m_locoInfo->m_accelerationPitch;
  1588. info.m_totalRoll = m_locoInfo->m_roll + m_locoInfo->m_accelerationRoll;
  1589. if (physics->isMotive())
  1590. {
  1591. // cause the chassis to pitch & roll in reaction to acceleration/deceleration
  1592. Real forwardAccel = dir->x * accel->x + dir->y * accel->y;
  1593. m_locoInfo->m_accelerationPitchRate += -(FORWARD_ACCEL_COEFF * forwardAccel);
  1594. Real lateralAccel = -dir->y * accel->x + dir->x * accel->y;
  1595. m_locoInfo->m_accelerationRollRate += -(LATERAL_ACCEL_COEFF * lateralAccel);
  1596. }
  1597. // limit acceleration pitch and roll
  1598. if (m_locoInfo->m_accelerationPitch > ACCEL_PITCH_LIMIT)
  1599. m_locoInfo->m_accelerationPitch = ACCEL_PITCH_LIMIT;
  1600. else if (m_locoInfo->m_accelerationPitch < -ACCEL_PITCH_LIMIT)
  1601. m_locoInfo->m_accelerationPitch = -ACCEL_PITCH_LIMIT;
  1602. if (m_locoInfo->m_accelerationRoll > ACCEL_PITCH_LIMIT)
  1603. m_locoInfo->m_accelerationRoll = ACCEL_PITCH_LIMIT;
  1604. else if (m_locoInfo->m_accelerationRoll < -ACCEL_PITCH_LIMIT)
  1605. m_locoInfo->m_accelerationRoll = -ACCEL_PITCH_LIMIT;
  1606. info.m_totalZ = 0;
  1607. // Calculate suspension info.
  1608. Real length = obj->getGeometryInfo().getMajorRadius();
  1609. Real width = obj->getGeometryInfo().getMinorRadius();
  1610. Real pitchHeight = length*Sin(info.m_totalPitch-groundPitch);
  1611. Real rollHeight = width*Sin(info.m_totalRoll-groundRoll);
  1612. if (DO_WHEELS)
  1613. {
  1614. // calculate each wheel position
  1615. m_locoInfo->m_wheelInfo.m_framesAirborne = m_locoInfo->m_wheelInfo.m_framesAirborneCounter;
  1616. m_locoInfo->m_wheelInfo.m_framesAirborneCounter = 0;
  1617. TWheelInfo newInfo = m_locoInfo->m_wheelInfo;
  1618. PhysicsTurningType rotation = physics->getTurning();
  1619. if (rotation == TURN_NEGATIVE) {
  1620. newInfo.m_wheelAngle = -WHEEL_ANGLE;
  1621. } else if (rotation == TURN_POSITIVE) {
  1622. newInfo.m_wheelAngle = WHEEL_ANGLE;
  1623. } else {
  1624. newInfo.m_wheelAngle = 0;
  1625. }
  1626. if (physics->getForwardSpeed2D() < 0.0f) {
  1627. // if we're moving backwards, the wheels rotate in the opposite direction.
  1628. newInfo.m_wheelAngle = -newInfo.m_wheelAngle;
  1629. }
  1630. //
  1631. ///@todo Steven/John ... please review this and make sure it makes sense (CBD)
  1632. // we're going to add the angle to the current wheel rotation ... but we're going to
  1633. // divide that number to add small angles. This allows for "smoother" wheel turning
  1634. // transitions ... and when the AI has things move in a straight line, since it's
  1635. // constantly telling the object to go left, go straight, go right, go straight,
  1636. // etc, this smaller angle we'll be adding covers the constant wheel shifting
  1637. // left and right when moving in a relatively straight line
  1638. //
  1639. #define WHEEL_SMOOTHNESS 10.0f // higher numbers add smaller angles, make it more "smooth"
  1640. m_locoInfo->m_wheelInfo.m_wheelAngle += (newInfo.m_wheelAngle - m_locoInfo->m_wheelInfo.m_wheelAngle)/WHEEL_SMOOTHNESS;
  1641. const Real SPRING_FACTOR = 0.9f;
  1642. if (pitchHeight<0) { // Front raising up
  1643. newInfo.m_frontLeftHeightOffset = SPRING_FACTOR*(pitchHeight/3+pitchHeight/2);
  1644. newInfo.m_frontRightHeightOffset = SPRING_FACTOR*(pitchHeight/3+pitchHeight/2);
  1645. newInfo.m_rearLeftHeightOffset = -pitchHeight/2 + pitchHeight/4;
  1646. newInfo.m_rearRightHeightOffset = -pitchHeight/2 + pitchHeight/4;
  1647. } else { // Back rasing up.
  1648. newInfo.m_frontLeftHeightOffset = (-pitchHeight/4+pitchHeight/2);
  1649. newInfo.m_frontRightHeightOffset = (-pitchHeight/4+pitchHeight/2);
  1650. newInfo.m_rearLeftHeightOffset = SPRING_FACTOR*(-pitchHeight/2 + -pitchHeight/3);
  1651. newInfo.m_rearRightHeightOffset = SPRING_FACTOR*(-pitchHeight/2 + -pitchHeight/3);
  1652. }
  1653. if (rollHeight>0) { // Right raising up
  1654. newInfo.m_frontRightHeightOffset += -SPRING_FACTOR*(rollHeight/3+rollHeight/2);
  1655. newInfo.m_rearRightHeightOffset += -SPRING_FACTOR*(rollHeight/3+rollHeight/2);
  1656. newInfo.m_rearLeftHeightOffset += rollHeight/2 - rollHeight/4;
  1657. newInfo.m_frontLeftHeightOffset += rollHeight/2 - rollHeight/4;
  1658. } else { // Left rasing up.
  1659. newInfo.m_frontRightHeightOffset += -rollHeight/2 + rollHeight/4;
  1660. newInfo.m_rearRightHeightOffset += -rollHeight/2 + rollHeight/4;
  1661. newInfo.m_rearLeftHeightOffset += SPRING_FACTOR*(rollHeight/3+rollHeight/2);
  1662. newInfo.m_frontLeftHeightOffset += SPRING_FACTOR*(rollHeight/3+rollHeight/2);
  1663. }
  1664. if (newInfo.m_frontLeftHeightOffset < m_locoInfo->m_wheelInfo.m_frontLeftHeightOffset) {
  1665. // If it's going down, dampen the movement a bit
  1666. m_locoInfo->m_wheelInfo.m_frontLeftHeightOffset += (newInfo.m_frontLeftHeightOffset - m_locoInfo->m_wheelInfo.m_frontLeftHeightOffset)/2.0f;
  1667. } else {
  1668. m_locoInfo->m_wheelInfo.m_frontLeftHeightOffset = newInfo.m_frontLeftHeightOffset;
  1669. }
  1670. if (newInfo.m_frontRightHeightOffset < m_locoInfo->m_wheelInfo.m_frontRightHeightOffset) {
  1671. // If it's going down, dampen the movement a bit
  1672. m_locoInfo->m_wheelInfo.m_frontRightHeightOffset += (newInfo.m_frontRightHeightOffset - m_locoInfo->m_wheelInfo.m_frontRightHeightOffset)/2.0f;
  1673. } else {
  1674. m_locoInfo->m_wheelInfo.m_frontRightHeightOffset = newInfo.m_frontRightHeightOffset;
  1675. }
  1676. if (newInfo.m_rearLeftHeightOffset < m_locoInfo->m_wheelInfo.m_rearLeftHeightOffset) {
  1677. // If it's going down, dampen the movement a bit
  1678. m_locoInfo->m_wheelInfo.m_rearLeftHeightOffset += (newInfo.m_rearLeftHeightOffset - m_locoInfo->m_wheelInfo.m_rearLeftHeightOffset)/2.0f;
  1679. } else {
  1680. m_locoInfo->m_wheelInfo.m_rearLeftHeightOffset = newInfo.m_rearLeftHeightOffset;
  1681. }
  1682. if (newInfo.m_rearRightHeightOffset < m_locoInfo->m_wheelInfo.m_rearRightHeightOffset) {
  1683. // If it's going down, dampen the movement a bit
  1684. m_locoInfo->m_wheelInfo.m_rearRightHeightOffset += (newInfo.m_rearRightHeightOffset - m_locoInfo->m_wheelInfo.m_rearRightHeightOffset)/2.0f;
  1685. } else {
  1686. m_locoInfo->m_wheelInfo.m_rearRightHeightOffset = newInfo.m_rearRightHeightOffset;
  1687. }
  1688. //m_locoInfo->m_wheelInfo = newInfo;
  1689. if (m_locoInfo->m_wheelInfo.m_frontLeftHeightOffset<MAX_SUSPENSION_EXTENSION) {
  1690. m_locoInfo->m_wheelInfo.m_frontLeftHeightOffset=MAX_SUSPENSION_EXTENSION;
  1691. }
  1692. if (m_locoInfo->m_wheelInfo.m_frontRightHeightOffset<MAX_SUSPENSION_EXTENSION) {
  1693. m_locoInfo->m_wheelInfo.m_frontRightHeightOffset=MAX_SUSPENSION_EXTENSION;
  1694. }
  1695. if (m_locoInfo->m_wheelInfo.m_rearLeftHeightOffset<MAX_SUSPENSION_EXTENSION) {
  1696. m_locoInfo->m_wheelInfo.m_rearLeftHeightOffset=MAX_SUSPENSION_EXTENSION;
  1697. }
  1698. if (m_locoInfo->m_wheelInfo.m_rearRightHeightOffset<MAX_SUSPENSION_EXTENSION) {
  1699. m_locoInfo->m_wheelInfo.m_rearRightHeightOffset=MAX_SUSPENSION_EXTENSION;
  1700. }
  1701. /*
  1702. if (m_locoInfo->m_wheelInfo.m_frontLeftHeightOffset>MAX_SUSPENSION_COMPRESSION) {
  1703. m_locoInfo->m_wheelInfo.m_frontLeftHeightOffset=MAX_SUSPENSION_COMPRESSION;
  1704. }
  1705. if (m_locoInfo->m_wheelInfo.m_frontRightHeightOffset>MAX_SUSPENSION_COMPRESSION) {
  1706. m_locoInfo->m_wheelInfo.m_frontRightHeightOffset=MAX_SUSPENSION_COMPRESSION;
  1707. }
  1708. if (m_locoInfo->m_wheelInfo.m_rearLeftHeightOffset>MAX_SUSPENSION_COMPRESSION) {
  1709. m_locoInfo->m_wheelInfo.m_rearLeftHeightOffset=MAX_SUSPENSION_COMPRESSION;
  1710. }
  1711. if (m_locoInfo->m_wheelInfo.m_rearRightHeightOffset>MAX_SUSPENSION_COMPRESSION) {
  1712. m_locoInfo->m_wheelInfo.m_rearRightHeightOffset=MAX_SUSPENSION_COMPRESSION;
  1713. }
  1714. */
  1715. }
  1716. // If we are > 22 degrees, need to raise height;
  1717. Real divisor = 4;
  1718. Real pitch = fabs(info.m_totalPitch-groundPitch);
  1719. if (pitch>PI/8) {
  1720. divisor = ((4*PI/8) + (1*(pitch-PI/8)))/pitch;
  1721. }
  1722. info.m_totalZ += fabs(pitchHeight)/divisor;
  1723. info.m_totalZ += fabs(rollHeight)/divisor;
  1724. }
  1725. //-------------------------------------------------------------------------------------------------
  1726. /** decodes the current previous damage type and sets the ambient sound set from that. */
  1727. //-------------------------------------------------------------------------------------------------
  1728. const AudioEventRTS& Drawable::getAmbientSoundByDamage(BodyDamageType dt)
  1729. {
  1730. switch (dt)
  1731. {
  1732. case BODY_DAMAGED:
  1733. return *getTemplate()->getSoundAmbientDamaged();
  1734. case BODY_REALLYDAMAGED:
  1735. return *getTemplate()->getSoundAmbientReallyDamaged();
  1736. case BODY_RUBBLE:
  1737. return *getTemplate()->getSoundAmbientRubble();
  1738. case BODY_PRISTINE:
  1739. default:
  1740. return *getTemplate()->getSoundAmbient();
  1741. }
  1742. }
  1743. //-------------------------------------------------------------------------------------------------
  1744. //-------------------------------------------------------------------------------------------------
  1745. #ifdef _DEBUG
  1746. void Drawable::validatePos() const
  1747. {
  1748. const Coord3D* ourPos = getPosition();
  1749. if (_isnan(ourPos->x) || _isnan(ourPos->y) || _isnan(ourPos->z))
  1750. {
  1751. DEBUG_CRASH(("Drawable/Object position NAN! '%s'\n", getTemplate()->getName().str()));
  1752. }
  1753. if (getObject())
  1754. {
  1755. const Coord3D* objPos = getObject()->getPosition();
  1756. if (ourPos->x != objPos->x || ourPos->y != objPos->y || ourPos->z != objPos->z)
  1757. {
  1758. DEBUG_CRASH(("Drawable/Object position mismatch! '%s'\n", getTemplate()->getName().str()));
  1759. }
  1760. }
  1761. }
  1762. #endif
  1763. //=============================================================================
  1764. void Drawable::setStealthLook(StealthLookType look)
  1765. {
  1766. if (look != m_stealthLook)
  1767. {
  1768. m_stealthOpacity = 1.0f; //assume not transparent
  1769. switch (look)
  1770. {
  1771. case STEALTHLOOK_NONE:
  1772. m_hiddenByStealth = false;
  1773. m_heatVisionOpacity = 0.0f;
  1774. break;
  1775. case STEALTHLOOK_VISIBLE_FRIENDLY:
  1776. case STEALTHLOOK_VISIBLE_FRIENDLY_DETECTED:
  1777. {
  1778. Real opacity = TheGlobalData->m_stealthFriendlyOpacity;
  1779. Object *obj = getObject();
  1780. if( obj )
  1781. {
  1782. //Try to get the stealthupdate module and see if the opacity value is overriden.
  1783. static NameKeyType key_StealthUpdate = NAMEKEY("StealthUpdate");
  1784. StealthUpdate* stealth = (StealthUpdate *)obj->findUpdateModule(key_StealthUpdate);
  1785. if( stealth )
  1786. {
  1787. if( stealth->isDisguised() )
  1788. {
  1789. //Disguised objects drive the opacity level directly, hence the break.
  1790. m_hiddenByStealth = false;
  1791. break;
  1792. }
  1793. else
  1794. {
  1795. Real friendlyOpacity = stealth->getFriendlyOpacity();
  1796. if( friendlyOpacity != INVALID_OPACITY )
  1797. {
  1798. opacity = friendlyOpacity;
  1799. }
  1800. }
  1801. }
  1802. }
  1803. m_stealthOpacity = opacity; // make as partially transparent as this while pulsing
  1804. m_hiddenByStealth = false;
  1805. /** @todo srj -- evil hack here... this whole heat-vision thing is fucked.
  1806. don't want it on mines but no good way to do that. hack for now. */
  1807. if (look == STEALTHLOOK_VISIBLE_FRIENDLY_DETECTED && !isKindOf(KINDOF_MINE))
  1808. m_heatVisionOpacity = 1.0f;
  1809. else
  1810. m_heatVisionOpacity = 0.0f;
  1811. break;
  1812. }
  1813. case STEALTHLOOK_DISGUISED_ENEMY:
  1814. m_hiddenByStealth = false;
  1815. m_heatVisionOpacity = 0.0f;
  1816. break;
  1817. // this is for the non-controllingplayer that can see me anyway
  1818. case STEALTHLOOK_VISIBLE_DETECTED:
  1819. m_hiddenByStealth = false;// let the scene omit the first drawing pass
  1820. /** @todo srj -- evil hack here... this whole heat-vision thing is fucked.
  1821. don't want it on mines but no good way to do that. hack for now. */
  1822. if (isKindOf(KINDOF_MINE))
  1823. m_heatVisionOpacity = 0.0f;
  1824. else
  1825. m_heatVisionOpacity = 1.0f;// Draw() will fade until it is set to 1 again
  1826. break;
  1827. case STEALTHLOOK_INVISIBLE:
  1828. m_hiddenByStealth = true;
  1829. m_heatVisionOpacity = 0.0f;
  1830. break;
  1831. }
  1832. m_stealthLook = look;
  1833. updateHiddenStatus();
  1834. }
  1835. }
  1836. //-------------------------------------------------------------------------------------------------
  1837. /** default draw is to just call the database defined draw */
  1838. //-------------------------------------------------------------------------------------------------
  1839. void Drawable::draw( View *view )
  1840. {
  1841. if ( getObject() && getObject()->isEffectivelyDead() )
  1842. m_heatVisionOpacity = 0.0f;//dead folks don't stealth anyway
  1843. else if ( m_heatVisionOpacity > VERY_TRANSPARENT_HEATVISION )// keep fading any heatvision unless something has set it to zero
  1844. m_heatVisionOpacity *= HEATVISION_FADE_SCALAR;
  1845. else
  1846. m_heatVisionOpacity = 0.0f;
  1847. if (m_hidden || m_hiddenByStealth || getFullyObscuredByShroud())
  1848. return; // my, that was easy
  1849. if ( getObject() && !getObject()->isEffectivelyDead() )
  1850. setShadowsEnabled( m_stealthLook != STEALTHLOOK_VISIBLE_DETECTED );
  1851. #ifdef _DEBUG
  1852. validatePos();
  1853. #endif
  1854. // call the database defined draw action method
  1855. Matrix3D transformMtx = *getTransformMatrix();
  1856. if (!isInstanceIdentity())
  1857. {
  1858. #ifdef ALLOW_TEMPORARIES
  1859. transformMtx = transformMtx * (*getInstanceMatrix());
  1860. #else
  1861. transformMtx.postMul(*getInstanceMatrix());
  1862. #endif
  1863. }
  1864. applyPhysicsXform(&transformMtx);
  1865. for (DrawModule** dm = getDrawModules(); *dm; ++dm)
  1866. {
  1867. (*dm)->doDrawModule(&transformMtx);
  1868. }
  1869. }
  1870. // ------------------------------------------------------------------------------------------------
  1871. /** Compute the health bar region based on the health of the object and the
  1872. * zoom level of the camera */
  1873. // ------------------------------------------------------------------------------------------------
  1874. static Bool computeHealthRegion( const Drawable *draw, IRegion2D& region )
  1875. {
  1876. // sanity
  1877. if( draw == NULL )
  1878. return FALSE;
  1879. const Object *obj = draw->getObject();
  1880. if( obj == NULL )
  1881. return FALSE;
  1882. Coord3D p;
  1883. obj->getHealthBoxPosition(p);
  1884. ICoord2D screenCenter;
  1885. if( !TheTacticalView->worldToScreen( &p, &screenCenter ) )
  1886. return FALSE;
  1887. Real healthBoxWidth, healthBoxHeight;
  1888. if (!obj->getHealthBoxDimensions(healthBoxHeight, healthBoxWidth))
  1889. return FALSE;
  1890. // scale the health bars according to the zoom
  1891. Real zoom = TheTacticalView->getZoom();
  1892. //Real widthScale = 1.3f / zoom;
  1893. Real widthScale = 1.0f / zoom;
  1894. //Real heightScale = 0.8f / zoom;
  1895. Real heightScale = 1.0f;
  1896. healthBoxWidth *= widthScale;
  1897. healthBoxHeight *= heightScale;
  1898. // do this so health bar doesn't get too skinny or fat after scaling
  1899. //healthBoxHeight = max(3.0f, healthBoxHeight);
  1900. healthBoxHeight = 3.0f;
  1901. // figure out the final region for the health box
  1902. region.lo.x = screenCenter.x - healthBoxWidth * 0.45f;
  1903. region.lo.y = screenCenter.y - healthBoxHeight * 0.5f;
  1904. region.hi.x = region.lo.x + healthBoxWidth;
  1905. region.hi.y = region.lo.y + healthBoxHeight;
  1906. return TRUE;
  1907. } // end computeHealthRegion
  1908. // ------------------------------------------------------------------------------------------------
  1909. Bool Drawable::drawsAnyUIText( void )
  1910. {
  1911. if (!isSelected())
  1912. return FALSE;
  1913. const Object *obj = getObject();
  1914. if ( !obj || !obj->isLocallyControlled() )
  1915. return FALSE;
  1916. Player *owner = obj->getControllingPlayer();
  1917. Int groupNum = owner->getSquadNumberForObject(obj);
  1918. if (groupNum > NO_HOTKEY_SQUAD && groupNum < NUM_HOTKEY_SQUADS )
  1919. return TRUE;
  1920. else
  1921. m_groupNumber = NULL;
  1922. if ( obj->getFormationID() != NO_FORMATION_ID )
  1923. return TRUE;
  1924. return FALSE;
  1925. }
  1926. // ------------------------------------------------------------------------------------------------
  1927. /** This is called as part of the "post draw" phase when drawable a drawable. It is there
  1928. * that we should overlay on the screen any 2D elements for purposes of user interface
  1929. * information (such as a heatlh bar, veterency levels, etc.) */
  1930. // ------------------------------------------------------------------------------------------------
  1931. void Drawable::drawIconUI( void )
  1932. {
  1933. if( TheGameLogic->getDrawIconUI() && (TheScriptEngine->getFade()==ScriptEngine::FADE_NONE) )
  1934. {
  1935. IRegion2D healthBarRegionStorage;
  1936. const IRegion2D* healthBarRegion = NULL;
  1937. if (computeHealthRegion(this, healthBarRegionStorage))
  1938. healthBarRegion = &healthBarRegionStorage; //both data and a PointerAsFlag for logic in the methods below
  1939. Object *obj = getObject();
  1940. // we only draw icons drawables with objects, so one bail here -------------------------
  1941. if ( ! obj )
  1942. return;
  1943. //Icons that can be drawn on dead things
  1944. drawHealthBar( healthBarRegion );
  1945. drawEmoticon( healthBarRegion );
  1946. drawCaption( healthBarRegion );
  1947. drawConstructPercent( healthBarRegion );
  1948. //All Icons Below only draw on ALIVE things, so bail here -------------------------
  1949. if( obj->isEffectivelyDead() || obj->isKindOf( KINDOF_IGNORED_IN_GUI )) // object explicitly wants nothing to do with these icons, so...
  1950. return;
  1951. drawHealing( healthBarRegion );//call so dead things can kill their healing icons
  1952. drawBombed( healthBarRegion );
  1953. //Disabled for multiplay!
  1954. //drawBattlePlans( healthBarRegion );
  1955. if ( drawsAnyUIText() )
  1956. TheGameClient->addTextBearingDrawable( this );
  1957. drawEnthusiastic( healthBarRegion );
  1958. #ifdef ALLOW_DEMORALIZE
  1959. drawDemoralized( healthBarRegion );
  1960. #endif
  1961. drawDisabled( healthBarRegion );
  1962. drawAmmo( healthBarRegion );
  1963. drawContained( healthBarRegion );
  1964. //Moved this to last so that it shows up over contained and ammo icons.
  1965. drawVeterancy( healthBarRegion );
  1966. }
  1967. }
  1968. //------------------------------------------------------------------------------------------------
  1969. DrawableIconInfo* Drawable::getIconInfo()
  1970. {
  1971. if (m_iconInfo == NULL)
  1972. m_iconInfo = newInstance(DrawableIconInfo);
  1973. return m_iconInfo;
  1974. }
  1975. //------------------------------------------------------------------------------------------------
  1976. void Drawable::clearEmoticon()
  1977. {
  1978. if (!hasIconInfo())
  1979. return;
  1980. killIcon(ICON_EMOTICON);
  1981. }
  1982. //------------------------------------------------------------------------------------------------
  1983. void Drawable::setEmoticon( const AsciiString &name, Int duration )
  1984. {
  1985. //A duration of -1 means FOREVER
  1986. clearEmoticon();
  1987. Anim2DTemplate *animTemplate = TheAnim2DCollection->findTemplate( name );
  1988. if( animTemplate )
  1989. {
  1990. DEBUG_ASSERTCRASH( getIconInfo()->m_icon[ ICON_EMOTICON ] == NULL, ("Drawable::setEmoticon - Emoticon isn't empty, need to refuse to set or destroy the old one in favor of the new one\n") );
  1991. if( getIconInfo()->m_icon[ ICON_EMOTICON ] == NULL )
  1992. {
  1993. getIconInfo()->m_icon[ ICON_EMOTICON ] = newInstance(Anim2D)( animTemplate, TheAnim2DCollection );
  1994. getIconInfo()->m_keepTillFrame[ ICON_EMOTICON ] = duration >= 0 ? TheGameLogic->getFrame() + duration : FOREVER;
  1995. }
  1996. }
  1997. }
  1998. //------------------------------------------------------------------------------------------------
  1999. void Drawable::drawEmoticon( const IRegion2D *healthBarRegion )
  2000. {
  2001. if( hasIconInfo() && getIconInfo()->m_icon[ ICON_EMOTICON ] )
  2002. {
  2003. UnsignedInt now = TheGameLogic->getFrame();
  2004. if( healthBarRegion && getIconInfo()->m_keepTillFrame[ ICON_EMOTICON ] >= now )
  2005. {
  2006. //Draw the emoticon.
  2007. Int barWidth = healthBarRegion->hi.x - healthBarRegion->lo.x;
  2008. //Int barHeight = healthBarRegion.hi.y - healthBarRegion.lo.y;
  2009. Int frameWidth = getIconInfo()->m_icon[ ICON_EMOTICON ]->getCurrentFrameWidth();
  2010. Int frameHeight = getIconInfo()->m_icon[ ICON_EMOTICON ]->getCurrentFrameHeight();
  2011. #ifdef SCALE_ICONS_WITH_ZOOM_ML
  2012. // adjust the width to be a % of the health bar region size
  2013. Int size = REAL_TO_INT( barWidth * 0.3f );
  2014. frameHeight = REAL_TO_INT((INT_TO_REAL(size) / INT_TO_REAL(frameWidth)) * frameHeight);
  2015. frameWidth = size;
  2016. #endif
  2017. // given our scaled width and height we need to find the top left point to draw the image at
  2018. ICoord2D screen;
  2019. screen.x = (Int)(healthBarRegion->lo.x + (barWidth * 0.5f) - (frameWidth * 0.5f));
  2020. screen.y = healthBarRegion->hi.y - frameHeight;
  2021. getIconInfo()->m_icon[ ICON_EMOTICON ]->draw( screen.x, screen.y, frameWidth, frameHeight );
  2022. }
  2023. else
  2024. {
  2025. //Get rid of the emoticon.
  2026. clearEmoticon();
  2027. }
  2028. }
  2029. }
  2030. // ------------------------------------------------------------------------------------------------
  2031. // ------------------------------------------------------------------------------------------------
  2032. void Drawable::drawAmmo( const IRegion2D *healthBarRegion )
  2033. {
  2034. const Object *obj = getObject();
  2035. if (!(
  2036. TheGlobalData->m_showObjectHealth &&
  2037. (isSelected() || (TheInGameUI && (TheInGameUI->getMousedOverDrawableID() == getID()))) &&
  2038. obj->getControllingPlayer() == ThePlayerList->getLocalPlayer()
  2039. ))
  2040. return;
  2041. Int numTotal;
  2042. Int numFull;
  2043. if (!obj->getAmmoPipShowingInfo(numTotal, numFull))
  2044. return;
  2045. if (!s_fullAmmo || !s_emptyAmmo)
  2046. return;
  2047. #ifdef SCALE_ICONS_WITH_ZOOM_ML
  2048. Real scale = TheGlobalData->m_ammoPipScaleFactor / CLAMP_ICON_ZOOM_FACTOR( TheTacticalView->getZoom() );
  2049. #else
  2050. Real scale = 1.0f;
  2051. #endif
  2052. Int boxWidth = REAL_TO_INT(s_emptyAmmo->getImageWidth() * scale);
  2053. Int boxHeight = REAL_TO_INT(s_emptyAmmo->getImageHeight() * scale);
  2054. const Int SPACING = 1;
  2055. //Int totalWidth = (boxWidth+SPACING)*numTotal;
  2056. ICoord2D screenCenter;
  2057. Coord3D pos = *obj->getPosition();
  2058. pos.x += TheGlobalData->m_ammoPipWorldOffset.x;
  2059. pos.y += TheGlobalData->m_ammoPipWorldOffset.y;
  2060. pos.z += TheGlobalData->m_ammoPipWorldOffset.z + obj->getGeometryInfo().getMaxHeightAbovePosition();
  2061. if( !TheTacticalView->worldToScreen( &pos, &screenCenter ) )
  2062. return;
  2063. Real bounding = obj->getGeometryInfo().getBoundingSphereRadius() * scale;
  2064. //Int posx = screenCenter.x + REAL_TO_INT(TheGlobalData->m_ammoPipScreenOffset.x*bounding) - totalWidth;
  2065. //**CHANGING CODE: Left justify with health bar min
  2066. Int posx = healthBarRegion->lo.x;
  2067. Int posy = screenCenter.y + REAL_TO_INT(TheGlobalData->m_ammoPipScreenOffset.y*bounding);
  2068. for (Int i = 0; i < numTotal; ++i)
  2069. {
  2070. TheDisplay->drawImage(i < numFull ? s_fullAmmo : s_emptyAmmo, posx, posy + 1, posx + boxWidth, posy + 1 + boxHeight);
  2071. posx += boxWidth + SPACING;
  2072. }
  2073. }
  2074. // ------------------------------------------------------------------------------------------------
  2075. // ------------------------------------------------------------------------------------------------
  2076. void Drawable::drawContained( const IRegion2D *healthBarRegion )
  2077. {
  2078. const Object *obj = getObject();
  2079. ContainModuleInterface* container = obj->getContain();
  2080. if (!container)
  2081. return;
  2082. if (!(
  2083. TheGlobalData->m_showObjectHealth &&
  2084. (isSelected() || (TheInGameUI && (TheInGameUI->getMousedOverDrawableID() == getID()))) &&
  2085. obj->getControllingPlayer() == ThePlayerList->getLocalPlayer()
  2086. ))
  2087. return;
  2088. Int numTotal;
  2089. Int numFull;
  2090. if (!container->getContainerPipsToShow(numTotal, numFull))
  2091. return;
  2092. // if empty, don't show nothin'
  2093. if (numFull == 0)
  2094. return;
  2095. Int numInfantry = 0;
  2096. const ContainedItemsList* contained = container->getContainedItemsList();
  2097. if (contained)
  2098. {
  2099. for (ContainedItemsList::const_iterator it = contained->begin(); it != contained->end(); ++it)
  2100. {
  2101. if ((*it)->isKindOf(KINDOF_INFANTRY))
  2102. ++numInfantry;
  2103. }
  2104. }
  2105. #ifdef SCALE_ICONS_WITH_ZOOM_ML
  2106. Real scale = TheGlobalData->m_ammoPipScaleFactor / CLAMP_ICON_ZOOM_FACTOR( TheTacticalView->getZoom() );
  2107. #else
  2108. Real scale = 1.0f;
  2109. #endif
  2110. Int boxWidth = REAL_TO_INT(s_emptyContainer->getImageWidth() * scale);
  2111. Int boxHeight = REAL_TO_INT(s_emptyContainer->getImageHeight() * scale);
  2112. const Int SPACING = 1;
  2113. //Int totalWidth = (boxWidth+SPACING)*numTotal;
  2114. ICoord2D screenCenter;
  2115. Coord3D pos = *obj->getPosition();
  2116. pos.x += TheGlobalData->m_containerPipWorldOffset.x;
  2117. pos.y += TheGlobalData->m_containerPipWorldOffset.y;
  2118. pos.z += TheGlobalData->m_containerPipWorldOffset.z + obj->getGeometryInfo().getMaxHeightAbovePosition();
  2119. if( !TheTacticalView->worldToScreen( &pos, &screenCenter ) )
  2120. return;
  2121. Real bounding = obj->getGeometryInfo().getBoundingSphereRadius() * scale;
  2122. //Int posx = screenCenter.x + REAL_TO_INT(TheGlobalData->m_containerPipScreenOffset.x*bounding) - totalWidth;
  2123. //**CHANGING CODE: Left justify with health bar min
  2124. Int posx = healthBarRegion->lo.x;
  2125. Int posy = screenCenter.y + REAL_TO_INT(TheGlobalData->m_containerPipScreenOffset.y*bounding);
  2126. for (Int i = 0; i < numTotal; ++i)
  2127. {
  2128. const Color INFANTRY_COLOR = GameMakeColor(0, 255, 0, 255);
  2129. const Color NON_INFANTRY_COLOR = GameMakeColor(0, 0, 255, 255);
  2130. if (i < numFull)
  2131. TheDisplay->drawImage(s_fullContainer, posx, posy, posx + boxWidth, posy + boxHeight,
  2132. (i < numInfantry) ? INFANTRY_COLOR : NON_INFANTRY_COLOR);
  2133. else
  2134. TheDisplay->drawImage(s_emptyContainer, posx, posy + 1, posx + boxWidth, posy + 1 + boxHeight);
  2135. posx += boxWidth + SPACING;
  2136. }
  2137. }
  2138. //-------------------------------------------------------------------------------------------------
  2139. void Drawable::drawBattlePlans( const IRegion2D *healthBarRegion )
  2140. {
  2141. Object *obj = getObject();
  2142. if( !obj || !healthBarRegion )
  2143. {
  2144. return;
  2145. }
  2146. Player *player = obj->getControllingPlayer();
  2147. if( player && player->getNumBattlePlansActive() > 0 && player->doesObjectQualifyForBattlePlan( obj ) )
  2148. {
  2149. if( player->getBattlePlansActiveSpecific( PLANSTATUS_BOMBARDMENT ) )
  2150. {
  2151. if( !getIconInfo()->m_icon[ ICON_BATTLEPLAN_BOMBARD ] )
  2152. {
  2153. getIconInfo()->m_icon[ ICON_BATTLEPLAN_BOMBARD ] = newInstance(Anim2D)( s_animationTemplates[ ICON_BATTLEPLAN_BOMBARD ], TheAnim2DCollection );
  2154. }
  2155. //Int barHeight = healthBarRegion.hi.y - healthBarRegion.lo.y;
  2156. Int frameWidth = getIconInfo()->m_icon[ ICON_BATTLEPLAN_BOMBARD ]->getCurrentFrameWidth();
  2157. Int frameHeight = getIconInfo()->m_icon[ ICON_BATTLEPLAN_BOMBARD ]->getCurrentFrameHeight();
  2158. #ifdef SCALE_ICONS_WITH_ZOOM_ML
  2159. // adjust the width to be a % of the health bar region size
  2160. Int barWidth = healthBarRegion->hi.x - healthBarRegion->lo.x;
  2161. Int size = REAL_TO_INT( barWidth * 0.3f );
  2162. frameHeight = REAL_TO_INT((INT_TO_REAL(size) / INT_TO_REAL(frameWidth)) * frameHeight);
  2163. frameWidth = size;
  2164. #endif
  2165. // given our scaled width and height we need to find the top left point to draw the image at
  2166. ICoord2D screen;
  2167. screen.x = healthBarRegion->lo.x;
  2168. screen.y = healthBarRegion->lo.y + frameHeight;
  2169. getIconInfo()->m_icon[ ICON_BATTLEPLAN_BOMBARD ]->draw( screen.x, screen.y, frameWidth, frameHeight );
  2170. }
  2171. else
  2172. {
  2173. killIcon(ICON_BATTLEPLAN_BOMBARD);
  2174. }
  2175. if( player->getBattlePlansActiveSpecific( PLANSTATUS_HOLDTHELINE ) )
  2176. {
  2177. if( !getIconInfo()->m_icon[ ICON_BATTLEPLAN_HOLDTHELINE ] )
  2178. {
  2179. getIconInfo()->m_icon[ ICON_BATTLEPLAN_HOLDTHELINE ] = newInstance(Anim2D)( s_animationTemplates[ ICON_BATTLEPLAN_HOLDTHELINE ], TheAnim2DCollection );
  2180. }
  2181. // draw the icon
  2182. Int frameWidth = getIconInfo()->m_icon[ ICON_BATTLEPLAN_HOLDTHELINE ]->getCurrentFrameWidth();
  2183. Int frameHeight = getIconInfo()->m_icon[ ICON_BATTLEPLAN_HOLDTHELINE ]->getCurrentFrameHeight();
  2184. #ifdef SCALE_ICONS_WITH_ZOOM_ML
  2185. // adjust the width to be a % of the health bar region size
  2186. Int barWidth = healthBarRegion->hi.x - healthBarRegion->lo.x;
  2187. Int size = REAL_TO_INT( barWidth * 0.3f );
  2188. frameHeight = REAL_TO_INT((INT_TO_REAL(size) / INT_TO_REAL(frameWidth)) * frameHeight);
  2189. frameWidth = size;
  2190. #endif
  2191. // given our scaled width and height we need to find the top left point to draw the image at
  2192. ICoord2D screen;
  2193. screen.x = healthBarRegion->lo.x;
  2194. screen.y = healthBarRegion->lo.y + frameHeight;
  2195. getIconInfo()->m_icon[ ICON_BATTLEPLAN_HOLDTHELINE ]->draw( screen.x + frameWidth, screen.y, frameWidth, frameHeight );
  2196. }
  2197. else
  2198. {
  2199. killIcon(ICON_BATTLEPLAN_HOLDTHELINE);
  2200. }
  2201. if( player->getBattlePlansActiveSpecific( PLANSTATUS_SEARCHANDDESTROY ) )
  2202. {
  2203. if( !getIconInfo()->m_icon[ ICON_BATTLEPLAN_SEARCHANDDESTROY ] )
  2204. {
  2205. getIconInfo()->m_icon[ ICON_BATTLEPLAN_SEARCHANDDESTROY ] = newInstance(Anim2D)( s_animationTemplates[ ICON_BATTLEPLAN_SEARCHANDDESTROY ], TheAnim2DCollection );
  2206. }
  2207. // draw the icon
  2208. Int frameWidth = getIconInfo()->m_icon[ ICON_BATTLEPLAN_SEARCHANDDESTROY ]->getCurrentFrameWidth();
  2209. Int frameHeight = getIconInfo()->m_icon[ ICON_BATTLEPLAN_SEARCHANDDESTROY ]->getCurrentFrameHeight();
  2210. #ifdef SCALE_ICONS_WITH_ZOOM_ML
  2211. // adjust the width to be a % of the health bar region size
  2212. Int barWidth = healthBarRegion->hi.x - healthBarRegion->lo.x;
  2213. Int size = REAL_TO_INT( barWidth * 0.3f );
  2214. frameHeight = REAL_TO_INT((INT_TO_REAL(size) / INT_TO_REAL(frameWidth)) * frameHeight);
  2215. frameWidth = size;
  2216. #endif
  2217. // given our scaled width and height we need to find the top left point to draw the image at
  2218. ICoord2D screen;
  2219. screen.x = healthBarRegion->lo.x;
  2220. screen.y = healthBarRegion->lo.y + frameHeight;
  2221. getIconInfo()->m_icon[ ICON_BATTLEPLAN_SEARCHANDDESTROY ]->draw( screen.x + (frameWidth * 2), screen.y, frameWidth, frameHeight );
  2222. }
  2223. else
  2224. {
  2225. killIcon(ICON_BATTLEPLAN_SEARCHANDDESTROY);
  2226. }
  2227. }
  2228. }
  2229. // ------------------------------------------------------------------------------------------------
  2230. // ------------------------------------------------------------------------------------------------
  2231. void Drawable::drawUIText()
  2232. {
  2233. // This gets called by GameClient now
  2234. // GameClient caches a list of us drawables during Drawablepostdraw()
  2235. // then our group numbers get spit out last, so they draw in front
  2236. const IRegion2D* healthBarRegion = NULL;
  2237. IRegion2D healthBarRegionStorage;
  2238. if (computeHealthRegion(this, healthBarRegionStorage))
  2239. healthBarRegion = &healthBarRegionStorage; //both data and a PointerAsFlag for logic in the methods below
  2240. if (!healthBarRegion)
  2241. return;
  2242. const Object *obj = getObject();
  2243. Player *owner = obj->getControllingPlayer();
  2244. Int groupNum = owner->getSquadNumberForObject(obj);
  2245. Color color = TheDrawGroupInfo->m_usePlayerColor ? owner->getPlayerColor() : TheDrawGroupInfo->m_colorForText;
  2246. if (groupNum > NO_HOTKEY_SQUAD && groupNum < NUM_HOTKEY_SQUADS )
  2247. {
  2248. Int xPos = healthBarRegion->lo.x;
  2249. Int yPos = healthBarRegion->lo.y;
  2250. if (TheDrawGroupInfo->m_usingPixelOffsetX) {
  2251. xPos += TheDrawGroupInfo->m_pixelOffsetX;
  2252. } else {
  2253. xPos += (healthBarRegion->width() * TheDrawGroupInfo->m_percentOffsetX);
  2254. }
  2255. if (TheDrawGroupInfo->m_usingPixelOffsetY) {
  2256. yPos += TheDrawGroupInfo->m_pixelOffsetY;
  2257. } else {
  2258. yPos += (healthBarRegion->width() * TheDrawGroupInfo->m_percentOffsetY);
  2259. }
  2260. m_groupNumber = TheDisplayStringManager->getGroupNumeralString(groupNum);
  2261. m_groupNumber->draw(xPos, yPos, color,
  2262. TheDrawGroupInfo->m_colorForTextDropShadow,
  2263. TheDrawGroupInfo->m_dropShadowOffsetX,
  2264. TheDrawGroupInfo->m_dropShadowOffsetY);
  2265. }
  2266. if ( obj->getFormationID() != NO_FORMATION_ID )
  2267. {
  2268. //draw an F, here
  2269. Coord3D p;
  2270. ICoord2D screenCenter;
  2271. obj->getHealthBoxPosition(p);
  2272. if( ! TheTacticalView->worldToScreen( &p, &screenCenter ) )
  2273. return;
  2274. Real healthBoxWidth, healthBoxHeight;
  2275. if ( ! obj->getHealthBoxDimensions(healthBoxHeight, healthBoxWidth))
  2276. return;
  2277. Real scale = 1.3f/CLAMP_ICON_ZOOM_FACTOR( TheTacticalView->getZoom() );
  2278. screenCenter.x += (healthBoxWidth * scale * 0.5f) + 10 ;
  2279. DisplayString *formationMarker = TheDisplayStringManager->getFormationLetterString();
  2280. //static DisplayString *formationMarker = TheDisplayStringManager->getGroupNumeralString( 5 );
  2281. if ( formationMarker )
  2282. formationMarker->draw(screenCenter.x, screenCenter.y, color,
  2283. TheDrawGroupInfo->m_colorForTextDropShadow,
  2284. TheDrawGroupInfo->m_dropShadowOffsetX,
  2285. TheDrawGroupInfo->m_dropShadowOffsetY);
  2286. }
  2287. }
  2288. // ------------------------------------------------------------------------------------------------
  2289. // ------------------------------------------------------------------------------------------------
  2290. void Drawable::drawHealing(const IRegion2D* healthBarRegion)
  2291. {
  2292. const Object *obj = getObject();
  2293. // we do show show icons for things that explicitly forbid it
  2294. if( obj->isKindOf( KINDOF_NO_HEAL_ICON ) || BitTest( obj->getStatusBits(), OBJECT_STATUS_SOLD ))
  2295. return;
  2296. // see if healing has been done to us recently
  2297. Bool showHealing = FALSE;
  2298. BodyModuleInterface *body = obj->getBodyModule();
  2299. if( body->getHealth() != body->getMaxHealth() )
  2300. {
  2301. // const DamageInfo* lastDamage = body->getLastDamageInfo();
  2302. // if( lastDamage != NULL && lastDamage->in.m_damageType == DAMAGE_HEALING
  2303. // &&(TheGameLogic->getFrame() - body->getLastHealingTimestamp()) <= HEALING_ICON_DISPLAY_TIME
  2304. // )
  2305. if ( TheGameLogic->getFrame() > HEALING_ICON_DISPLAY_TIME && // because so many things init health early in game
  2306. (TheGameLogic->getFrame() - body->getLastHealingTimestamp() <= HEALING_ICON_DISPLAY_TIME) )
  2307. showHealing = TRUE;
  2308. }
  2309. // based on our own kind of we have certain icons to display at a size scale
  2310. Real scale;
  2311. DrawableIconType typeIndex;
  2312. if( isKindOf( KINDOF_STRUCTURE ) )
  2313. {
  2314. typeIndex = ICON_STRUCTURE_HEAL;
  2315. scale = 0.33f;
  2316. }
  2317. else if( isKindOf( KINDOF_VEHICLE ) )
  2318. {
  2319. typeIndex = ICON_VEHICLE_HEAL;
  2320. scale = 0.7f;
  2321. }
  2322. else
  2323. {
  2324. typeIndex = ICON_DEFAULT_HEAL;
  2325. scale = 0.7f;
  2326. }
  2327. //
  2328. // if we are to show healing make sure we have the animation for it allocated, otherwise
  2329. // free any animation we may have allocated back to the animation memory pool
  2330. //
  2331. if( showHealing ) /// @todo HERE, WE NEED TO LEAVE STUFF ALONE, IF WE ARE ALREADY SHOWING HEALING
  2332. {
  2333. if (healthBarRegion != NULL)
  2334. {
  2335. if( getIconInfo()->m_icon[ typeIndex ] == NULL )
  2336. getIconInfo()->m_icon[ typeIndex ] = newInstance(Anim2D)( s_animationTemplates[ typeIndex ], TheAnim2DCollection );
  2337. // draw the animation if present
  2338. if( getIconInfo()->m_icon[ typeIndex ] != NULL)
  2339. {
  2340. //
  2341. // we are going to draw the healing icon relative to the size of the health bar region
  2342. // since that region takes into account hit point size and zoom factor of the camera too
  2343. //
  2344. Int barWidth = healthBarRegion->hi.x - healthBarRegion->lo.x;
  2345. Int frameWidth = getIconInfo()->m_icon[ typeIndex ]->getCurrentFrameWidth();
  2346. Int frameHeight = getIconInfo()->m_icon[ typeIndex ]->getCurrentFrameHeight();
  2347. #ifdef SCALE_ICONS_WITH_ZOOM_ML
  2348. // adjust the width to be a % of the health bar region size
  2349. Int size = REAL_TO_INT( barWidth * scale );
  2350. frameHeight = REAL_TO_INT((INT_TO_REAL(size) / INT_TO_REAL(frameWidth)) * frameHeight);
  2351. frameWidth = size;
  2352. #endif
  2353. // given our scaled width and height we need to find the top left point to draw the image at
  2354. ICoord2D screen;
  2355. screen.x = REAL_TO_INT( healthBarRegion->lo.x + (barWidth * 0.75f) - (frameWidth * 0.5f) );
  2356. screen.y = REAL_TO_INT( healthBarRegion->lo.y - frameHeight );
  2357. getIconInfo()->m_icon[ typeIndex ]->draw( screen.x, screen.y, frameWidth, frameHeight );
  2358. }
  2359. }
  2360. }
  2361. else
  2362. {
  2363. killIcon(typeIndex);
  2364. }
  2365. }
  2366. // ------------------------------------------------------------------------------------------------
  2367. /** This enthusiastic effect is TEMPORARY for the multiplayer test */
  2368. // ------------------------------------------------------------------------------------------------
  2369. void Drawable::drawEnthusiastic(const IRegion2D* healthBarRegion)
  2370. {
  2371. const Object *obj = getObject();
  2372. //
  2373. // if we are to show effect make sure we have the animation for it allocated, otherwise
  2374. // free any animation we may have allocated back to the animation memory pool
  2375. //
  2376. // only display if have enthusiasm
  2377. if( obj->testWeaponBonusCondition( WEAPONBONUSCONDITION_ENTHUSIASTIC ) == TRUE &&
  2378. healthBarRegion != NULL )
  2379. {
  2380. DrawableIconType iconIndex = ICON_ENTHUSIASTIC;
  2381. if (obj->testWeaponBonusCondition( WEAPONBONUSCONDITION_SUBLIMINAL ) == TRUE )// unless...
  2382. iconIndex = ICON_ENTHUSIASTIC_SUBLIMINAL;
  2383. if( getIconInfo()->m_icon[ iconIndex ] == NULL )
  2384. getIconInfo()->m_icon[ iconIndex ] = newInstance(Anim2D)( s_animationTemplates[ iconIndex ], TheAnim2DCollection );
  2385. // draw the animation if present
  2386. if( getIconInfo()->m_icon[ iconIndex ] != NULL)
  2387. {
  2388. //
  2389. // we are going to draw the healing icon relative to the size of the health bar region
  2390. // since that region takes into account hit point size and zoom factor of the camera too
  2391. //
  2392. Int barWidth = healthBarRegion->hi.x - healthBarRegion->lo.x;// used for position
  2393. // based on our own kind of we have certain icons to display at a size scale
  2394. Real scale;
  2395. if( isKindOf( KINDOF_STRUCTURE ) || isKindOf( KINDOF_HUGE_VEHICLE ) )
  2396. scale = 1.00f;
  2397. else if( isKindOf( KINDOF_VEHICLE ) )
  2398. scale = 0.75f;
  2399. else
  2400. scale = 0.5f;
  2401. Int frameWidth = getIconInfo()->m_icon[ iconIndex ]->getCurrentFrameWidth() * scale;
  2402. Int frameHeight = getIconInfo()->m_icon[ iconIndex ]->getCurrentFrameHeight() * scale;
  2403. #ifdef SCALE_ICONS_WITH_ZOOM_ML
  2404. // adjust the width to be a % of the health bar region size
  2405. Int size = REAL_TO_INT( barWidth * scale );
  2406. frameHeight = REAL_TO_INT((INT_TO_REAL(size) / INT_TO_REAL(frameWidth)) * frameHeight);
  2407. frameWidth = size;
  2408. #endif
  2409. // given our scaled width and height we need to find the bottom left point to draw the image at
  2410. ICoord2D screen;
  2411. screen.x = REAL_TO_INT( healthBarRegion->lo.x + (barWidth * 0.25f) - (frameWidth * 0.5f) );
  2412. screen.y = healthBarRegion->hi.y;
  2413. getIconInfo()->m_icon[ iconIndex ]->draw( screen.x, screen.y, frameWidth, frameHeight );
  2414. }
  2415. }
  2416. else
  2417. {
  2418. killIcon(ICON_ENTHUSIASTIC);
  2419. killIcon(ICON_ENTHUSIASTIC_SUBLIMINAL);
  2420. }
  2421. }
  2422. #ifdef ALLOW_DEMORALIZE
  2423. // ------------------------------------------------------------------------------------------------
  2424. // ------------------------------------------------------------------------------------------------
  2425. void Drawable::drawDemoralized(const IRegion2D* healthBarRegion)
  2426. {
  2427. const Object *obj = getObject();
  2428. //
  2429. // Demoralized
  2430. //
  2431. const AIUpdateInterface *ai = obj->getAIUpdateInterface();
  2432. if (!ai)
  2433. return;
  2434. if( ai->isDemoralized() )
  2435. {
  2436. // draw the icon
  2437. if( healthBarRegion )
  2438. {
  2439. // create icon if necessary
  2440. if( getIconInfo()->m_icon[ ICON_DEMORALIZED ] == NULL )
  2441. getIconInfo()->m_icon[ ICON_DEMORALIZED ] = newInstance(Anim2D)( s_animationTemplates[ ICON_DEMORALIZED ], TheAnim2DCollection );
  2442. if (getIconInfo()->m_icon[ ICON_DEMORALIZED ])
  2443. {
  2444. Int frameWidth = getIconInfo()->m_icon[ ICON_DEMORALIZED ]->getCurrentFrameWidth();
  2445. Int frameHeight = getIconInfo()->m_icon[ ICON_DEMORALIZED ]->getCurrentFrameHeight();
  2446. #ifdef SCALE_ICONS_WITH_ZOOM_ML
  2447. // adjust the width to be a % of the health bar region size
  2448. Int barWidth = healthBarRegion->hi.x - healthBarRegion->lo.x;
  2449. Int size = REAL_TO_INT( barWidth * 0.3f );
  2450. frameHeight = REAL_TO_INT((INT_TO_REAL(size) / INT_TO_REAL(frameWidth)) * frameHeight);
  2451. frameWidth = size;
  2452. #endif
  2453. // given our scaled width and height we need to find the top left point to draw the image at
  2454. ICoord2D screen;
  2455. screen.x = healthBarRegion->lo.x;
  2456. screen.y = healthBarRegion->hi.y;
  2457. getIconInfo()->m_icon[ ICON_DEMORALIZED ]->draw( screen.x, screen.y, frameWidth, frameHeight );
  2458. }
  2459. }
  2460. }
  2461. else
  2462. {
  2463. killIcon(ICON_DEMORALIZED);
  2464. }
  2465. }
  2466. #endif
  2467. // ------------------------------------------------------------------------------------------------
  2468. // ------------------------------------------------------------------------------------------------
  2469. void Drawable::drawBombed(const IRegion2D* healthBarRegion)
  2470. {
  2471. const Object *obj = getObject();
  2472. UnsignedInt now = TheGameLogic->getFrame();
  2473. if( obj->testWeaponSetFlag( WEAPONSET_CARBOMB ) &&
  2474. obj->getControllingPlayer() == ThePlayerList->getLocalPlayer())
  2475. {
  2476. if( !getIconInfo()->m_icon[ ICON_CARBOMB ] )
  2477. getIconInfo()->m_icon[ ICON_CARBOMB ] = newInstance(Anim2D)( s_animationTemplates[ ICON_CARBOMB ], TheAnim2DCollection );
  2478. if( getIconInfo()->m_icon[ ICON_CARBOMB ] )
  2479. {
  2480. //
  2481. // we are going to draw the healing icon relative to the size of the health bar region
  2482. // since that region takes into account hit point size and zoom factor of the camera too
  2483. //
  2484. if( healthBarRegion )
  2485. {
  2486. Int barWidth = healthBarRegion->hi.x - healthBarRegion->lo.x;
  2487. Int barHeight = healthBarRegion->hi.y - healthBarRegion->lo.y;
  2488. Int frameWidth = getIconInfo()->m_icon[ ICON_CARBOMB ]->getCurrentFrameWidth();
  2489. Int frameHeight = getIconInfo()->m_icon[ ICON_CARBOMB ]->getCurrentFrameHeight();
  2490. // adjust the width to be a % of the health bar region size
  2491. Int size = REAL_TO_INT( barWidth * 0.5f );
  2492. frameHeight = REAL_TO_INT((INT_TO_REAL(size) / INT_TO_REAL(frameWidth)) * frameHeight);
  2493. frameWidth = size;
  2494. // given our scaled width and height we need to find the top left point to draw the image at
  2495. ICoord2D screen;
  2496. screen.x = REAL_TO_INT( healthBarRegion->lo.x + (barWidth * 0.5f) - (frameWidth * 0.5f) );
  2497. screen.y = REAL_TO_INT( healthBarRegion->lo.y + barHeight * 0.5f );
  2498. getIconInfo()->m_icon[ ICON_CARBOMB ]->draw( screen.x, screen.y, frameWidth, frameHeight );
  2499. getIconInfo()->m_keepTillFrame[ ICON_CARBOMB ] = FOREVER;
  2500. }
  2501. }
  2502. }
  2503. else
  2504. {
  2505. killIcon(ICON_CARBOMB);
  2506. }
  2507. //
  2508. // Bombed?
  2509. //
  2510. static NameKeyType key_StickyBombUpdate = NAMEKEY( "StickyBombUpdate" );
  2511. StickyBombUpdate *update = (StickyBombUpdate*)obj->findUpdateModule( key_StickyBombUpdate );
  2512. if( update )
  2513. {
  2514. //This case is tricky. The object that is bombed doesn't know it... but the bomb itself does.
  2515. //So what we do is get it's target, then determine if the target has the icon or not.
  2516. Object *target = update->getTargetObject();
  2517. if( target )
  2518. {
  2519. if( update->isTimedBomb() )
  2520. {
  2521. //Timed bomb
  2522. if( !getIconInfo()->m_icon[ ICON_BOMB_TIMED ] )
  2523. {
  2524. getIconInfo()->m_icon[ ICON_BOMB_REMOTE ] = newInstance(Anim2D)( s_animationTemplates[ ICON_BOMB_REMOTE ], TheAnim2DCollection );
  2525. getIconInfo()->m_icon[ ICON_BOMB_TIMED ] = newInstance(Anim2D)( s_animationTemplates[ ICON_BOMB_TIMED ], TheAnim2DCollection );
  2526. //Because this is a counter icon that ranges from 0-60 seconds, we need to calculate which frame to
  2527. //start the animation from. Because timers are second based -- 1000 ms equal 1 frame. So we simply
  2528. //calculate the time via detonation frame.
  2529. //
  2530. // srj sez: this may sound familiar somehow, but let me reiterate, just in case you missed it:
  2531. //
  2532. // hardcoding is bad.
  2533. //
  2534. // the anim got changed and now is only 20 seconds max, so the previous code was wrong.
  2535. //
  2536. // hey, I've got an idea! why don't we ASK the anim how long it is?
  2537. //
  2538. UnsignedInt dieFrame = update->getDetonationFrame();
  2539. UnsignedInt seconds = REAL_TO_INT_CEIL( (dieFrame - now) * SECONDS_PER_LOGICFRAME_REAL);
  2540. UnsignedInt numFrames = getIconInfo()->m_icon[ ICON_BOMB_TIMED ]->getAnimTemplate()->getNumFrames();
  2541. // this anim goes from "N" seconds down to zero, so the max seconds we can use is N-1.
  2542. if (seconds > numFrames - 1)
  2543. seconds = numFrames - 1;
  2544. getIconInfo()->m_icon[ ICON_BOMB_TIMED ]->setMinFrame(numFrames - seconds - 1);
  2545. getIconInfo()->m_icon[ ICON_BOMB_TIMED ]->reset();
  2546. }
  2547. if( getIconInfo()->m_icon[ ICON_BOMB_TIMED ] )
  2548. {
  2549. //
  2550. // we are going to draw the healing icon relative to the size of the health bar region
  2551. // since that region takes into account hit point size and zoom factor of the camera too
  2552. //
  2553. if( healthBarRegion )
  2554. {
  2555. Int barWidth = healthBarRegion->hi.x - healthBarRegion->lo.x;
  2556. Int barHeight = healthBarRegion->hi.y - healthBarRegion->lo.y;
  2557. Int frameWidth = getIconInfo()->m_icon[ ICON_BOMB_TIMED ]->getCurrentFrameWidth();
  2558. Int frameHeight = getIconInfo()->m_icon[ ICON_BOMB_TIMED ]->getCurrentFrameHeight();
  2559. // adjust the width to be a % of the health bar region size
  2560. Int size = REAL_TO_INT( barWidth * 0.65f );
  2561. frameHeight = REAL_TO_INT((INT_TO_REAL(size) / INT_TO_REAL(frameWidth)) * frameHeight);
  2562. frameWidth = size;
  2563. // given our scaled width and height we need to find the top left point to draw the image at
  2564. ICoord2D screen;
  2565. screen.x = REAL_TO_INT( healthBarRegion->lo.x + (barWidth * 0.5f) - (frameWidth * 0.5f) );
  2566. screen.y = REAL_TO_INT( healthBarRegion->lo.y + barHeight * 0.5f );
  2567. getIconInfo()->m_icon[ ICON_BOMB_REMOTE ]->draw( screen.x, screen.y, frameWidth, frameHeight );
  2568. getIconInfo()->m_keepTillFrame[ ICON_BOMB_REMOTE ] = now + 1;
  2569. getIconInfo()->m_icon[ ICON_BOMB_TIMED ]->draw( screen.x, screen.y, frameWidth, frameHeight );
  2570. getIconInfo()->m_keepTillFrame[ ICON_BOMB_TIMED ] = now + 1;
  2571. }
  2572. }
  2573. }
  2574. else
  2575. {
  2576. //Remote charge
  2577. //Timed bomb
  2578. if( !getIconInfo()->m_icon[ ICON_BOMB_REMOTE ] )
  2579. {
  2580. getIconInfo()->m_icon[ ICON_BOMB_REMOTE ] = newInstance(Anim2D)( s_animationTemplates[ ICON_BOMB_REMOTE ], TheAnim2DCollection );
  2581. }
  2582. if( getIconInfo()->m_icon[ ICON_BOMB_REMOTE ] )
  2583. {
  2584. //
  2585. // we are going to draw the healing icon relative to the size of the health bar region
  2586. // since that region takes into account hit point size and zoom factor of the camera too
  2587. //
  2588. if( healthBarRegion )
  2589. {
  2590. Int barWidth = healthBarRegion->hi.x - healthBarRegion->lo.x;
  2591. Int barHeight = healthBarRegion->hi.y - healthBarRegion->lo.y;
  2592. Int frameWidth = getIconInfo()->m_icon[ ICON_BOMB_REMOTE ]->getCurrentFrameWidth();
  2593. Int frameHeight = getIconInfo()->m_icon[ ICON_BOMB_REMOTE ]->getCurrentFrameHeight();
  2594. // adjust the width to be a % of the health bar region size
  2595. Int size = REAL_TO_INT( barWidth * 0.65f );
  2596. frameHeight = REAL_TO_INT((INT_TO_REAL(size) / INT_TO_REAL(frameWidth)) * frameHeight);
  2597. frameWidth = size;
  2598. // given our scaled width and height we need to find the top left point to draw the image at
  2599. ICoord2D screen;
  2600. screen.x = REAL_TO_INT( healthBarRegion->lo.x + (barWidth * 0.5f) - (frameWidth * 0.5f) );
  2601. screen.y = REAL_TO_INT( healthBarRegion->lo.y + barHeight * 0.5f );
  2602. getIconInfo()->m_icon[ ICON_BOMB_REMOTE ]->draw( screen.x, screen.y, frameWidth, frameHeight );
  2603. getIconInfo()->m_keepTillFrame[ ICON_BOMB_REMOTE ] = now + 1;
  2604. }
  2605. }
  2606. }
  2607. }
  2608. }
  2609. if (hasIconInfo())
  2610. {
  2611. if(getIconInfo()->m_keepTillFrame[ ICON_BOMB_TIMED ] <= now )
  2612. {
  2613. killIcon(ICON_BOMB_TIMED);
  2614. }
  2615. if(getIconInfo()->m_keepTillFrame[ ICON_BOMB_REMOTE ] <= now )
  2616. {
  2617. killIcon(ICON_BOMB_REMOTE);
  2618. }
  2619. }
  2620. }
  2621. // ------------------------------------------------------------------------------------------------
  2622. /** Draw any icon information that needs to be drawn */
  2623. // ------------------------------------------------------------------------------------------------
  2624. void Drawable::drawDisabled(const IRegion2D* healthBarRegion)
  2625. {
  2626. const Object *obj = getObject();
  2627. //
  2628. // Disabled Emoticon /Lightning
  2629. // 7/
  2630. if( obj->isDisabledByType( DISABLED_HACKED )
  2631. || obj->isDisabledByType( DISABLED_PARALYZED )
  2632. || obj->isDisabledByType( DISABLED_EMP )
  2633. || obj->isDisabledByType( DISABLED_UNDERPOWERED )
  2634. )
  2635. {
  2636. // create icon if necessary
  2637. if( getIconInfo()->m_icon[ ICON_DISABLED ] == NULL )
  2638. {
  2639. getIconInfo()->m_icon[ ICON_DISABLED ] = newInstance(Anim2D)
  2640. ( s_animationTemplates[ ICON_DISABLED ], TheAnim2DCollection );
  2641. }
  2642. // draw the icon
  2643. if( healthBarRegion )
  2644. {
  2645. Int barHeight = healthBarRegion->hi.y - healthBarRegion->lo.y;
  2646. Int frameWidth = getIconInfo()->m_icon[ ICON_DISABLED ]->getCurrentFrameWidth();
  2647. Int frameHeight = getIconInfo()->m_icon[ ICON_DISABLED ]->getCurrentFrameHeight();
  2648. #ifdef SCALE_ICONS_WITH_ZOOM_ML
  2649. // adjust the width to be a % of the health bar region size
  2650. Int barWidth = healthBarRegion->hi.x - healthBarRegion->lo.x;
  2651. Int size = REAL_TO_INT( barWidth * 0.3f );
  2652. frameHeight = REAL_TO_INT((INT_TO_REAL(size) / INT_TO_REAL(frameWidth)) * frameHeight);
  2653. frameWidth = size;
  2654. #endif
  2655. // given our scaled width and height we need to find the top left point to draw the image at
  2656. ICoord2D screen;
  2657. screen.x = healthBarRegion->lo.x;
  2658. screen.y = healthBarRegion->hi.y - (frameHeight + barHeight);
  2659. getIconInfo()->m_icon[ ICON_DISABLED ]->draw( screen.x, screen.y, frameWidth, frameHeight );
  2660. } // end if
  2661. } // end if
  2662. else
  2663. {
  2664. // delete icon if necessary
  2665. killIcon(ICON_DISABLED);
  2666. } // end if
  2667. }
  2668. //-------------------------------------------------------------------------------------------------
  2669. /** Draw construction percent for drawables that have objects that are "under construction" */
  2670. //-------------------------------------------------------------------------------------------------
  2671. void Drawable::drawConstructPercent( const IRegion2D *healthBarRegion )
  2672. {
  2673. // this data is in an attached object
  2674. Object *obj = getObject();
  2675. if( obj == NULL || BitTest( obj->getStatusBits(), OBJECT_STATUS_UNDER_CONSTRUCTION ) == FALSE ||
  2676. BitTest( obj->getStatusBits(), OBJECT_STATUS_SOLD ) == TRUE )
  2677. {
  2678. // no object, or we are now complete get rid of the string if we have one
  2679. if( m_constructDisplayString )
  2680. {
  2681. TheDisplayStringManager->freeDisplayString( m_constructDisplayString );
  2682. m_constructDisplayString = NULL;
  2683. }
  2684. return;
  2685. }
  2686. //if( obj->isEffectivelyDead() )
  2687. //{
  2688. //Don't render icons for dead things.
  2689. // return;
  2690. //}
  2691. // construction is partially complete, allocate a display string if we need one
  2692. if( m_constructDisplayString == NULL )
  2693. m_constructDisplayString = TheDisplayStringManager->newDisplayString();
  2694. // set the string if the value has changed
  2695. if( m_lastConstructDisplayed != obj->getConstructionPercent() )
  2696. {
  2697. UnicodeString buffer;
  2698. buffer.format( TheGameText->fetch("CONTROLBAR:UnderConstructionDesc"), obj->getConstructionPercent());
  2699. m_constructDisplayString->setText( buffer );
  2700. // record this percent as our last displayed so we don't un-necessarily rebuild the string
  2701. m_lastConstructDisplayed = obj->getConstructionPercent();
  2702. } // end if
  2703. // get center position in drawable
  2704. ICoord2D screen;
  2705. Coord3D pos;
  2706. getDrawableGeometryInfo().getCenterPosition(*getPosition(), pos);
  2707. // convert drawable center position to screen coords
  2708. TheTacticalView->worldToScreen( &pos, &screen );
  2709. // draw the text
  2710. Color color = GameMakeColor( 255, 255, 255, 255 );
  2711. Color dropColor = GameMakeColor( 0, 0, 0, 255 );
  2712. screen.x -= (m_constructDisplayString->getWidth() / 2);
  2713. m_constructDisplayString->draw( screen.x, screen.y, color, dropColor );
  2714. } // end drawConstructPercent
  2715. //-------------------------------------------------------------------------------------------------
  2716. /** Draw caption */
  2717. //-------------------------------------------------------------------------------------------------
  2718. void Drawable::drawCaption( const IRegion2D *healthBarRegion )
  2719. {
  2720. if (!m_captionDisplayString)
  2721. return;
  2722. // get center position in drawable
  2723. ICoord2D screen;
  2724. Coord3D pos;
  2725. getDrawableGeometryInfo().getCenterPosition(*getPosition(), pos);
  2726. // convert drawable center position to screen coords
  2727. TheTacticalView->worldToScreen( &pos, &screen );
  2728. screen.x -= (m_captionDisplayString->getWidth() / 2);
  2729. // draw background
  2730. {
  2731. Int width, xPos;
  2732. Int height, yPos;
  2733. m_captionDisplayString->getSize(&width,&height);
  2734. xPos = screen.x - 1;
  2735. yPos = screen.y - 1;
  2736. TheDisplay->drawFillRect(xPos, yPos, width + 2,height + 2, GameMakeColor(0,0,0,125));
  2737. TheDisplay->drawOpenRect(xPos, yPos, width + 2,height + 2, 1.0, GameMakeColor(20,20,20,255));
  2738. }
  2739. // draw the text
  2740. Color color = TheInGameUI->getDrawableCaptionColor();
  2741. Color dropColor = GameMakeColor( 0, 0, 0, 255 );
  2742. m_captionDisplayString->draw( screen.x, screen.y, color, dropColor );
  2743. } // end drawCaption
  2744. // ------------------------------------------------------------------------------------------------
  2745. /** Draw any veterency markers that should be displayed */
  2746. // ------------------------------------------------------------------------------------------------
  2747. void Drawable::drawVeterancy( const IRegion2D *healthBarRegion )
  2748. {
  2749. // get object from drawble
  2750. Object* obj = getObject();
  2751. if( obj->getExperienceTracker() == NULL )
  2752. {
  2753. //Only objects with experience trackers can possibly have veterancy.
  2754. return;
  2755. }
  2756. VeterancyLevel level = obj->getVeterancyLevel();
  2757. const Image* image = s_veterancyImage[level];
  2758. if (!image)
  2759. return;
  2760. Real scale = 1.3f/CLAMP_ICON_ZOOM_FACTOR( TheTacticalView->getZoom() );
  2761. #ifdef SCALE_ICONS_WITH_ZOOM_ML
  2762. Real objScale = scale * 1.55f;
  2763. #else
  2764. Real objScale = 1.0f;
  2765. #endif
  2766. Real vetBoxWidth = image->getImageWidth()*objScale;
  2767. Real vetBoxHeight = image->getImageHeight()*objScale;
  2768. //
  2769. // take the center position of the object, go down to it's bottom extent, and project
  2770. // that point to the screen, that will be the "center" of our veterancy box
  2771. //
  2772. Coord3D p;
  2773. ICoord2D screenCenter;
  2774. obj->getHealthBoxPosition(p);
  2775. if( !TheTacticalView->worldToScreen( &p, &screenCenter ) )
  2776. return;
  2777. Real healthBoxWidth, healthBoxHeight;
  2778. if (!obj->getHealthBoxDimensions(healthBoxHeight, healthBoxWidth))
  2779. return;
  2780. screenCenter.x += healthBoxWidth * scale * 0.5f;
  2781. // draw the image
  2782. TheDisplay->drawImage(image, screenCenter.x + 1, screenCenter.y + 1, screenCenter.x + 1 + vetBoxWidth, screenCenter.y + 1 + vetBoxHeight);
  2783. } // end drawVeterancy
  2784. // ------------------------------------------------------------------------------------------------
  2785. /** Draw health bar information for drawable */
  2786. // ------------------------------------------------------------------------------------------------
  2787. void Drawable::drawHealthBar(const IRegion2D* healthBarRegion)
  2788. {
  2789. if (!healthBarRegion)
  2790. return;
  2791. //
  2792. // only draw health for selected drawbles and drawables that have been moused over
  2793. // by the cursor
  2794. //
  2795. if( TheGlobalData->m_showObjectHealth &&
  2796. (isSelected() || (TheInGameUI && (TheInGameUI->getMousedOverDrawableID() == getID()))) )
  2797. {
  2798. Object *obj = getObject();
  2799. // if no object, nothing to do
  2800. if( obj == NULL )
  2801. return;
  2802. if( obj->isKindOf( KINDOF_FORCEATTACKABLE ) )
  2803. {
  2804. //Currently (Nov 2002), everything that is forceattackable are civ fences, and they all have a
  2805. //single hit point and they aren't selectable. However, a bug is when you force attack it, it shows
  2806. //the healthbar. Well, this stops it, however, should force attackable kindofs change, then this
  2807. //will require reevaluation.
  2808. return;
  2809. }
  2810. // get body module of object
  2811. BodyModuleInterface *body = obj->getBodyModule();
  2812. // get the health and max health
  2813. Real health = body->getHealth();
  2814. Real maxHealth = body->getMaxHealth();
  2815. // if no max health or health at all we will draw nothing
  2816. if( maxHealth == 0.0f || health == 0.0f )
  2817. return;
  2818. // what is our health ratio
  2819. Real healthRatio = health / maxHealth;
  2820. //
  2821. // what color will we use for the health bar based on our ratio, this makes it
  2822. // slowly go from green to red, (or from blue to cyan if under construction, or disabled)
  2823. //
  2824. Color color, outlineColor;
  2825. if( BitTest( obj->getStatusBits(), OBJECT_STATUS_UNDER_CONSTRUCTION ) || (obj->isDisabled() && !obj->isDisabledByType(DISABLED_HELD)) )
  2826. {
  2827. color = GameMakeColor( 0, healthRatio * 255.0f, 255, 255 );//blue to cyan
  2828. outlineColor = GameMakeColor( 0, healthRatio * 128.0f, 128, 255 );//dark blue to dark cyan
  2829. }
  2830. else //red to green
  2831. {
  2832. RGBColor inColor, outColor;
  2833. inColor.blue = 0; // health bars do not display blue...
  2834. outColor.blue = 0; // health bars do not display blue...
  2835. if( healthRatio >= 0.5f )
  2836. {
  2837. inColor.red = 1.0f - ((healthRatio - 0.5f) / 0.5f);
  2838. inColor.green = 1.0f;
  2839. // color = GameMakeColor ( 255 - ((healthRatio - 0.5f) / 0.5f) * 255, 255, 0, 255 );
  2840. // outlineColor = GameMakeColor( (255 - ((healthRatio - 0.5f) / 0.5f) * 255) * 0.5, 255 * 0.5, 0, 255 );
  2841. }
  2842. else
  2843. {
  2844. inColor.red = 1.0f;
  2845. inColor.green = 1.0f - ((0.5f - healthRatio) / 0.5f);
  2846. // color = GameMakeColor( 255, 255 - ((0.5f - healthRatio) / 0.5f) * 255, 0, 255 );
  2847. // outlineColor = GameMakeColor( 255 * 0.5, (255 - ((0.5f - healthRatio) / 0.5f) * 255) * 0.5, 0, 255 );
  2848. }
  2849. outColor.red = inColor.red * 0.5f;
  2850. outColor.green =inColor.green * 0.5f;
  2851. if( m_conditionState.test( MODELCONDITION_REALLY_DAMAGED ) == TRUE )
  2852. {//average the above color with red
  2853. inColor.red = (1.0f + inColor.red) * 0.5f;
  2854. inColor.green *= 0.5f;
  2855. }
  2856. else if ( m_conditionState.test( MODELCONDITION_DAMAGED ) == FALSE )
  2857. {//average the above color with green
  2858. inColor.green = (1.0f + inColor.green) * 0.5f;
  2859. inColor.red *= 0.5f;
  2860. }
  2861. color = GameMakeColor( 255.0 * inColor.red, 255.0 * inColor.green, 255.0 * inColor.blue, 255);
  2862. outlineColor = GameMakeColor( 255.0 * outColor.red, 255.0 * outColor.green, 255.0 * outColor.blue, 255);
  2863. }
  2864. /// Real scale = 1.3f / TheTacticalView->getZoom();
  2865. Real healthBoxWidth = healthBarRegion->hi.x - healthBarRegion->lo.x;
  2866. Real healthBoxHeight = max(3, healthBarRegion->hi.y - healthBarRegion->lo.y);
  2867. Real healthBoxOutlineSize = 1.0f;
  2868. // draw the health box outline
  2869. TheDisplay->drawOpenRect( healthBarRegion->lo.x, healthBarRegion->lo.y, healthBoxWidth, healthBoxHeight,
  2870. healthBoxOutlineSize, outlineColor );
  2871. // draw a filled bar for the health
  2872. TheDisplay->drawFillRect( healthBarRegion->lo.x + 1, healthBarRegion->lo.y + 1,
  2873. (healthBoxWidth - 2) * healthRatio, healthBoxHeight - 2,
  2874. color );
  2875. } // end if
  2876. } // end drawHealthBar
  2877. //-------------------------------------------------------------------------------------------------
  2878. //-------------------------------------------------------------------------------------------------
  2879. void Drawable::clearAndSetModelConditionState( ModelConditionFlagType clr, ModelConditionFlagType set )
  2880. {
  2881. ModelConditionFlags c, s;
  2882. if (clr != MODELCONDITION_INVALID)
  2883. c.set(clr);
  2884. if (set != MODELCONDITION_INVALID)
  2885. s.set(set);
  2886. clearAndSetModelConditionFlags(c, s);
  2887. }
  2888. //-------------------------------------------------------------------------------------------------
  2889. DrawModule** Drawable::getDrawModules()
  2890. {
  2891. DrawModule** dm = (DrawModule**)getModuleList(MODULETYPE_DRAW);
  2892. #ifdef DIRTY_CONDITION_FLAGS
  2893. if (m_isModelDirty)
  2894. {
  2895. if (s_modelLockCount > 0)
  2896. {
  2897. DEBUG_CRASH(("Should not need to update dirty stuff while locked-for-iteration. Ignoring."));
  2898. // this shouldn't happen, but if it does, just return the current (dirty) scenario.
  2899. // we must NOT update the condition state, as someone is relying on the current
  2900. // list of W3D render objects not being munged. (srj)
  2901. }
  2902. else
  2903. {
  2904. for (DrawModule** dm2 = dm; *dm2; ++dm2)
  2905. {
  2906. ObjectDrawInterface* di = (*dm2)->getObjectDrawInterface();
  2907. if (di)
  2908. di->replaceModelConditionState( m_conditionState );
  2909. }
  2910. m_isModelDirty = false;
  2911. }
  2912. }
  2913. #endif
  2914. return dm;
  2915. }
  2916. //-------------------------------------------------------------------------------------------------
  2917. DrawModule const** Drawable::getDrawModules() const
  2918. {
  2919. DrawModule const** dm = (DrawModule const**)getModuleList(MODULETYPE_DRAW);
  2920. #ifdef DIRTY_CONDITION_FLAGS
  2921. if (m_isModelDirty)
  2922. {
  2923. if (s_modelLockCount > 0)
  2924. {
  2925. DEBUG_CRASH(("Should not need to update dirty stuff while locked-for-iteration. Ignoring."));
  2926. // this shouldn't happen, but if it does, just return the current (dirty) scenario.
  2927. // we must NOT update the condition state, as someone is relying on the current
  2928. // list of W3D render objects not being munged. (srj)
  2929. }
  2930. else
  2931. {
  2932. // yeah, yeah, yeah... I know (srj)
  2933. for (DrawModule** dm2 = (DrawModule**)dm; *dm2; ++dm2)
  2934. {
  2935. ObjectDrawInterface* di = (*dm2)->getObjectDrawInterface();
  2936. if (di)
  2937. di->replaceModelConditionState( m_conditionState );
  2938. }
  2939. m_isModelDirty = false;
  2940. }
  2941. }
  2942. #endif
  2943. return dm;
  2944. }
  2945. //-------------------------------------------------------------------------------------------------
  2946. //-------------------------------------------------------------------------------------------------
  2947. void Drawable::clearAndSetModelConditionFlags(const ModelConditionFlags& clr, const ModelConditionFlags& setf)
  2948. {
  2949. ModelConditionFlags oldFlags = m_conditionState;
  2950. m_conditionState.clearAndSet(clr, setf);
  2951. if (m_conditionState == oldFlags)
  2952. return;
  2953. #ifdef DIRTY_CONDITION_FLAGS
  2954. m_isModelDirty = true;
  2955. #else
  2956. for (DrawModule** dm = getDrawModules(); *dm; ++dm)
  2957. {
  2958. ObjectDrawInterface* di = (*dm)->getObjectDrawInterface();
  2959. if (di)
  2960. di->replaceModelConditionState( m_conditionState );
  2961. }
  2962. #endif
  2963. }
  2964. // ------------------------------------------------------------------------------------------------
  2965. // ------------------------------------------------------------------------------------------------
  2966. void Drawable::replaceModelConditionFlags( const ModelConditionFlags &flags, Bool forceReplace )
  2967. {
  2968. //
  2969. // this is a no-op if the new flags are the same as our existing flags (unless we
  2970. // have the forceReplace parameter set, in which case we will force the setting of the
  2971. // new flags)
  2972. //
  2973. if( forceReplace == FALSE && m_conditionState == flags )
  2974. return;
  2975. m_conditionState = flags;
  2976. #ifdef DIRTY_CONDITION_FLAGS
  2977. // when forcing a replace we won't use dirty flags, we will immediately do an update now
  2978. if( forceReplace == TRUE )
  2979. {
  2980. for (DrawModule** dm = getDrawModules(); *dm; ++dm)
  2981. {
  2982. ObjectDrawInterface* di = (*dm)->getObjectDrawInterface();
  2983. if (di)
  2984. di->replaceModelConditionState( m_conditionState );
  2985. }
  2986. m_isModelDirty = false;
  2987. }
  2988. else
  2989. m_isModelDirty = true;
  2990. #else
  2991. for (DrawModule** dm = getDrawModules(); *dm; ++dm)
  2992. {
  2993. ObjectDrawInterface* di = (*dm)->getObjectDrawInterface();
  2994. if (di)
  2995. di->replaceModelConditionState( m_conditionState );
  2996. }
  2997. #endif
  2998. }
  2999. //-------------------------------------------------------------------------------------------------
  3000. void Drawable::setIndicatorColor(Color color)
  3001. {
  3002. for (DrawModule** dm = getDrawModules(); *dm; ++dm)
  3003. {
  3004. ObjectDrawInterface* di = (*dm)->getObjectDrawInterface();
  3005. if (di)
  3006. di->replaceIndicatorColor(color);
  3007. }
  3008. }
  3009. // ------------------------------------------------------------------------------------------------
  3010. const GeometryInfo& Drawable::getDrawableGeometryInfo() const
  3011. {
  3012. return getObject() ? getObject()->getGeometryInfo() : getTemplate()->getTemplateGeometryInfo();
  3013. }
  3014. // ------------------------------------------------------------------------------------------------
  3015. /** Set the id for this drawable */
  3016. // ------------------------------------------------------------------------------------------------
  3017. void Drawable::setID( DrawableID id )
  3018. {
  3019. // if id hasn't changed do nothing
  3020. if( m_id == id )
  3021. return;
  3022. // remove this objects previous id from the lookup table
  3023. if( m_id != INVALID_DRAWABLE_ID )
  3024. TheGameClient->removeDrawableFromLookupTable( this );
  3025. // assign new id
  3026. m_id = id;
  3027. // add new id to lookup table
  3028. if( m_id != INVALID_DRAWABLE_ID )
  3029. {
  3030. TheGameClient->addDrawableToLookupTable( this );
  3031. if (m_ambientSound)
  3032. m_ambientSound->m_event.setDrawableID(m_id);
  3033. }
  3034. } // end setID
  3035. // ------------------------------------------------------------------------------------------------
  3036. /** Return drawable ID, this ID is only good on the client */
  3037. // ------------------------------------------------------------------------------------------------
  3038. DrawableID Drawable::getID( void ) const
  3039. {
  3040. // we should never be getting the ID of a drawable who doesn't yet have and ID assigned to it
  3041. DEBUG_ASSERTCRASH( m_id != 0, ("Drawable::getID - Using ID before it was assigned!!!!\n") );
  3042. return m_id;
  3043. } // end get ID
  3044. //-------------------------------------------------------------------------------------------------
  3045. void Drawable::friend_bindToObject( Object *obj ) ///< bind this drawable to an object ID
  3046. {
  3047. m_object = obj;
  3048. if (getObject())
  3049. {
  3050. if (TheGlobalData->m_timeOfDay == TIME_OF_DAY_NIGHT)
  3051. setIndicatorColor(getObject()->getNightIndicatorColor());
  3052. else
  3053. setIndicatorColor(getObject()->getIndicatorColor());
  3054. }
  3055. for (DrawModule** dm = getDrawModules(); *dm; ++dm)
  3056. {
  3057. (*dm)->onDrawableBoundToObject();
  3058. }
  3059. }
  3060. //-------------------------------------------------------------------------------------------------
  3061. // when our Object changes teams, it calls us to let us know, so
  3062. // we can update our model, etc., if necessary. NOTE, we don't guarantee
  3063. // that the new team is different from the old team, nor do we guarantee
  3064. // that the team is nonnull.
  3065. void Drawable::changedTeam()
  3066. {
  3067. Object *object = getObject();
  3068. if( object )
  3069. {
  3070. if (TheGlobalData->m_timeOfDay == TIME_OF_DAY_NIGHT)
  3071. setIndicatorColor( object->getNightIndicatorColor() );
  3072. else
  3073. setIndicatorColor( object->getIndicatorColor() );
  3074. }
  3075. }
  3076. //-------------------------------------------------------------------------------------------------
  3077. void Drawable::setPosition(const Coord3D *pos)
  3078. {
  3079. // extend
  3080. Thing::setPosition(pos);
  3081. }
  3082. //-------------------------------------------------------------------------------------------------
  3083. void Drawable::reactToTransformChange(const Matrix3D* oldMtx, const Coord3D* oldPos, Real oldAngle)
  3084. {
  3085. for (DrawModule** dm = getDrawModules(); *dm; ++dm)
  3086. {
  3087. (*dm)->reactToTransformChange(oldMtx, oldPos, oldAngle);
  3088. }
  3089. }
  3090. //-------------------------------------------------------------------------------------------------
  3091. void Drawable::reactToGeometryChange()
  3092. {
  3093. for (DrawModule** dm = getDrawModules(); *dm; ++dm)
  3094. {
  3095. (*dm)->reactToGeometryChange();
  3096. }
  3097. }
  3098. //-------------------------------------------------------------------------------------------------
  3099. Bool Drawable::handleWeaponFireFX(WeaponSlotType wslot, Int specificBarrelToUse, const FXList* fxl, Real weaponSpeed, Real recoilAmount, Real recoilAngle, const Coord3D* victimPos, Real damageRadius)
  3100. {
  3101. if (recoilAmount != 0.0f)
  3102. {
  3103. // adjust recoil from absolute to relative.
  3104. if (getObject())
  3105. recoilAngle -= getObject()->getOrientation();
  3106. // flip direction 180 degrees.
  3107. recoilAngle += PI;
  3108. if (m_locoInfo)
  3109. {
  3110. m_locoInfo->m_accelerationPitchRate += recoilAmount * Cos(recoilAngle);
  3111. m_locoInfo->m_accelerationRollRate += recoilAmount * Sin(recoilAngle);
  3112. }
  3113. }
  3114. for (DrawModule** dm = getDrawModules(); *dm; ++dm)
  3115. {
  3116. ObjectDrawInterface* di = (*dm)->getObjectDrawInterface();
  3117. if (di && di->handleWeaponFireFX(wslot, specificBarrelToUse, fxl, weaponSpeed, victimPos, damageRadius))
  3118. return true;
  3119. }
  3120. return false;
  3121. }
  3122. //-------------------------------------------------------------------------------------------------
  3123. Int Drawable::getBarrelCount(WeaponSlotType wslot) const
  3124. {
  3125. for (const DrawModule** dm = getDrawModules(); *dm; ++dm)
  3126. {
  3127. const ObjectDrawInterface* di = (*dm)->getObjectDrawInterface();
  3128. Int count = di ? di->getBarrelCount(wslot) : 0;
  3129. if (count != 0)
  3130. return count;
  3131. }
  3132. return 0;
  3133. }
  3134. //-------------------------------------------------------------------------------------------------
  3135. /** Set the Drawable's instance transform */
  3136. //-------------------------------------------------------------------------------------------------
  3137. void Drawable::setInstanceMatrix( const Matrix3D *instance )
  3138. {
  3139. if (instance)
  3140. {
  3141. m_instance = *instance;
  3142. m_instanceIsIdentity = false;
  3143. }
  3144. else
  3145. {
  3146. m_instance.Make_Identity();
  3147. m_instanceIsIdentity = true;
  3148. }
  3149. }
  3150. //-------------------------------------------------------------------------------------------------
  3151. /**
  3152. * Return the Drawable's world transform.
  3153. * If this Drawable is attached to an Object, return the Object's transform instead.
  3154. */
  3155. //-------------------------------------------------------------------------------------------------
  3156. const Matrix3D *Drawable::getTransformMatrix( void ) const
  3157. {
  3158. const Object *obj = getObject();
  3159. if (obj)
  3160. return obj->getTransformMatrix();
  3161. else
  3162. return Thing::getTransformMatrix();
  3163. }
  3164. //-------------------------------------------------------------------------------------------------
  3165. /**
  3166. * Set and clear the drawable's caption text
  3167. */
  3168. //-------------------------------------------------------------------------------------------------
  3169. void Drawable::setCaptionText( const UnicodeString& captionText )
  3170. {
  3171. if (captionText.isEmpty())
  3172. {
  3173. clearCaptionText();
  3174. return;
  3175. }
  3176. UnicodeString sanitizedString = captionText;
  3177. TheLanguageFilter->filterLine(sanitizedString);
  3178. if( m_captionDisplayString == NULL )
  3179. {
  3180. m_captionDisplayString = TheDisplayStringManager->newDisplayString();
  3181. GameFont *font = TheFontLibrary->getFont(
  3182. TheInGameUI->getDrawableCaptionFontName(),
  3183. TheGlobalLanguageData->adjustFontSize(TheInGameUI->getDrawableCaptionPointSize()),
  3184. TheInGameUI->isDrawableCaptionBold() );
  3185. m_captionDisplayString->setFont( font );
  3186. m_captionDisplayString->setText( sanitizedString );
  3187. }
  3188. else
  3189. {
  3190. // set the string if the value has changed
  3191. if( m_captionDisplayString->getText().compare(sanitizedString) != 0 )
  3192. {
  3193. m_captionDisplayString->setText( sanitizedString );
  3194. }
  3195. }
  3196. }
  3197. //-------------------------------------------------------------------------------------------------
  3198. void Drawable::clearCaptionText( void )
  3199. {
  3200. if (m_captionDisplayString)
  3201. TheDisplayStringManager->freeDisplayString(m_captionDisplayString);
  3202. m_captionDisplayString = NULL;
  3203. }
  3204. //-------------------------------------------------------------------------------------------------
  3205. UnicodeString Drawable::getCaptionText( void )
  3206. {
  3207. if (m_captionDisplayString)
  3208. return m_captionDisplayString->getText();
  3209. return UnicodeString::TheEmptyString;
  3210. }
  3211. //-------------------------------------------------------------------------------------------------
  3212. /** Attach and start playing an ambient sound to this drawable */
  3213. //-------------------------------------------------------------------------------------------------
  3214. void Drawable::setTimeOfDay(TimeOfDay tod)
  3215. {
  3216. BodyDamageType dt = BODY_PRISTINE;
  3217. if (getObject() && getObject()->getBodyModule())
  3218. dt = getObject()->getBodyModule()->getDamageState();
  3219. startAmbientSound(dt, tod);
  3220. ModelConditionFlags c = m_conditionState;
  3221. c.set(MODELCONDITION_NIGHT, (tod == TIME_OF_DAY_NIGHT) ? 1 : 0);
  3222. replaceModelConditionFlags(c);
  3223. }
  3224. //-------------------------------------------------------------------------------------------------
  3225. /** Attach and start playing an ambient sound to this drawable */
  3226. //-------------------------------------------------------------------------------------------------
  3227. void Drawable::startAmbientSound(BodyDamageType dt, TimeOfDay tod)
  3228. {
  3229. stopAmbientSound();
  3230. //Get the specific ambient sound for the damage type.
  3231. const AudioEventRTS& audio = getAmbientSoundByDamage(dt);
  3232. Bool trySound = FALSE;
  3233. if( audio.getEventName().isNotEmpty() )
  3234. {
  3235. if (m_ambientSound == NULL)
  3236. m_ambientSound = newInstance(DynamicAudioEventRTS);
  3237. (m_ambientSound->m_event) = audio;
  3238. trySound = TRUE;
  3239. }
  3240. else if( dt != BODY_PRISTINE && dt != BODY_RUBBLE )
  3241. {
  3242. //If the ambient sound was absent in the case of non-pristine damage types,
  3243. //try getting the pristine one. Most of our cases actually specify just the
  3244. //pristine sound and want to use it for all states (except dead/rubble).
  3245. const AudioEventRTS& pristineAudio = getAmbientSoundByDamage( BODY_PRISTINE );
  3246. if( pristineAudio.getEventName().isNotEmpty() )
  3247. {
  3248. if (m_ambientSound == NULL)
  3249. m_ambientSound = newInstance(DynamicAudioEventRTS);
  3250. (m_ambientSound->m_event) = pristineAudio;
  3251. trySound = TRUE;
  3252. }
  3253. }
  3254. if( trySound && m_ambientSound )
  3255. {
  3256. const AudioEventInfo *info = m_ambientSound->m_event.getAudioEventInfo();
  3257. if( info )
  3258. {
  3259. if( BitTest( info->m_type, ST_GLOBAL) || info->m_priority == AP_CRITICAL )
  3260. {
  3261. //Play it anyways.
  3262. m_ambientSound->m_event.setDrawableID(getID());
  3263. m_ambientSound->m_event.setTimeOfDay(tod);
  3264. m_ambientSound->m_event.setPlayingHandle(TheAudio->addAudioEvent( &m_ambientSound->m_event ));
  3265. }
  3266. else
  3267. {
  3268. //Check if it's close enough to try playing (optimization)
  3269. Coord3D vector = *getPosition();
  3270. vector.sub( TheAudio->getListenerPosition() );
  3271. Real distSqr = vector.lengthSqr();
  3272. if( distSqr < sqr( info->m_maxDistance ) )
  3273. {
  3274. m_ambientSound->m_event.setDrawableID(getID());
  3275. m_ambientSound->m_event.setTimeOfDay(tod);
  3276. m_ambientSound->m_event.setPlayingHandle(TheAudio->addAudioEvent( &m_ambientSound->m_event ));
  3277. }
  3278. }
  3279. }
  3280. else
  3281. {
  3282. DEBUG_CRASH( ("Ambient sound %s missing! Skipping...", m_ambientSound->m_event.getEventName().str() ) );
  3283. m_ambientSound->deleteInstance();
  3284. m_ambientSound = NULL;
  3285. }
  3286. }
  3287. }
  3288. //-------------------------------------------------------------------------------------------------
  3289. // Attach and start playing an ambient sound to this drawable. Calculates states automatically.
  3290. //-------------------------------------------------------------------------------------------------
  3291. void Drawable::startAmbientSound()
  3292. {
  3293. stopAmbientSound();
  3294. BodyDamageType bodyCondition = BODY_PRISTINE;
  3295. Object *obj = getObject();
  3296. if( obj )
  3297. {
  3298. bodyCondition = obj->getBodyModule()->getDamageState();
  3299. }
  3300. startAmbientSound( bodyCondition, TheGlobalData->m_timeOfDay );
  3301. }
  3302. //-------------------------------------------------------------------------------------------------
  3303. /** Stop playing the drawables ambient sound if it has one */
  3304. //-------------------------------------------------------------------------------------------------
  3305. void Drawable::stopAmbientSound( void )
  3306. {
  3307. if (m_ambientSound)
  3308. TheAudio->removeAudioEvent(m_ambientSound->m_event.getPlayingHandle());
  3309. }
  3310. //-------------------------------------------------------------------------------------------------
  3311. void Drawable::enableAmbientSound( Bool enable )
  3312. {
  3313. if( m_ambientSoundEnabled == enable )
  3314. {
  3315. return;
  3316. }
  3317. m_ambientSoundEnabled = enable;
  3318. if( enable )
  3319. {
  3320. startAmbientSound();
  3321. }
  3322. else
  3323. {
  3324. stopAmbientSound();
  3325. }
  3326. }
  3327. //-------------------------------------------------------------------------------------------------
  3328. /** add self to the linked list */
  3329. //-------------------------------------------------------------------------------------------------
  3330. void Drawable::prependToList(Drawable **pListHead)
  3331. {
  3332. // add the object to the global list
  3333. m_prevDrawable = NULL;
  3334. m_nextDrawable = *pListHead;
  3335. if (*pListHead)
  3336. (*pListHead)->m_prevDrawable = this;
  3337. *pListHead = this;
  3338. }
  3339. //-------------------------------------------------------------------------------------------------
  3340. /** remove self from the linked list */
  3341. //-------------------------------------------------------------------------------------------------
  3342. void Drawable::removeFromList(Drawable **pListHead)
  3343. {
  3344. if (m_nextDrawable)
  3345. m_nextDrawable->m_prevDrawable = m_prevDrawable;
  3346. if (m_prevDrawable)
  3347. m_prevDrawable->m_nextDrawable = m_nextDrawable;
  3348. else
  3349. *pListHead = m_nextDrawable;
  3350. }
  3351. //-------------------------------------------------------------------------------------------------
  3352. //-------------------------------------------------------------------------------------------------
  3353. void Drawable::updateHiddenStatus()
  3354. {
  3355. Bool hidden = m_hidden || m_hiddenByStealth;
  3356. if( hidden )
  3357. TheInGameUI->deselectDrawable( this );
  3358. for (DrawModule** dm = getDrawModules(); *dm; ++dm)
  3359. {
  3360. ObjectDrawInterface* di = (*dm)->getObjectDrawInterface();
  3361. if (di)
  3362. di->setHidden(hidden != 0);
  3363. }
  3364. }
  3365. //-------------------------------------------------------------------------------------------------
  3366. /** Hide or un-hide drawable */
  3367. //-------------------------------------------------------------------------------------------------
  3368. void Drawable::setDrawableHidden( Bool hidden )
  3369. {
  3370. if (hidden != m_hidden)
  3371. {
  3372. m_hidden = hidden;
  3373. updateHiddenStatus();
  3374. }
  3375. }
  3376. //-------------------------------------------------------------------------------------------------
  3377. void Drawable::updateDrawableClipStatus( UnsignedInt shotsRemaining, UnsignedInt maxShots, WeaponSlotType slot )
  3378. {
  3379. for (DrawModule** dm = getDrawModules(); *dm; ++dm)
  3380. {
  3381. ObjectDrawInterface* di = (*dm)->getObjectDrawInterface();
  3382. if (di)
  3383. di->updateProjectileClipStatus(shotsRemaining, maxShots, slot);
  3384. }
  3385. }
  3386. //-------------------------------------------------------------------------------------------------
  3387. void Drawable::updateDrawableSupplyStatus( Int maxSupply, Int currentSupply )
  3388. {
  3389. for (DrawModule** dm = getDrawModules(); *dm; ++dm)
  3390. {
  3391. ObjectDrawInterface* di = (*dm)->getObjectDrawInterface();
  3392. if (di)
  3393. di->updateDrawModuleSupplyStatus( maxSupply, currentSupply );
  3394. }
  3395. }
  3396. //-------------------------------------------------------------------------------------------------
  3397. void Drawable::notifyDrawableDependencyCleared()
  3398. {
  3399. for (DrawModule** dm = getDrawModules(); *dm; ++dm)
  3400. {
  3401. ObjectDrawInterface* di = (*dm)->getObjectDrawInterface();
  3402. if (di)
  3403. di->notifyDrawModuleDependencyCleared();
  3404. }
  3405. }
  3406. //-------------------------------------------------------------------------------------------------
  3407. /** Set as selectable or not. */
  3408. //-------------------------------------------------------------------------------------------------
  3409. void Drawable::setSelectable( Bool selectable )
  3410. {
  3411. // unselct drawable if it is no longer selectable.
  3412. if( !selectable )
  3413. TheInGameUI->deselectDrawable( this );
  3414. for (DrawModule** dm = getDrawModules(); *dm; ++dm)
  3415. {
  3416. ObjectDrawInterface* di = (*dm)->getObjectDrawInterface();
  3417. if (di)
  3418. di->setSelectable(selectable);
  3419. }
  3420. }
  3421. //-------------------------------------------------------------------------------------------------
  3422. /** Return whether or not this Drawable is selectable. */
  3423. //-------------------------------------------------------------------------------------------------
  3424. Bool Drawable::isSelectable( void ) const
  3425. {
  3426. return getObject() && getObject()->isSelectable();
  3427. }
  3428. //-------------------------------------------------------------------------------------------------
  3429. /** Return whether or not this Drawable is selectable as part of a group. */
  3430. //-------------------------------------------------------------------------------------------------
  3431. Bool Drawable::isMassSelectable( void ) const
  3432. {
  3433. return getObject() && getObject()->isMassSelectable();
  3434. }
  3435. //-------------------------------------------------------------------------------------------------
  3436. /** Preload all our assets that we can for all our possible states in this time of day */
  3437. //-------------------------------------------------------------------------------------------------
  3438. void Drawable::preloadAssets( TimeOfDay timeOfDay )
  3439. {
  3440. /// walk all our modules and preload any assets we need to
  3441. for( Int i = 0; i < NUM_DRAWABLE_MODULE_TYPES; ++i )
  3442. for( Module** m = m_modules[i]; m && *m; ++m )
  3443. (*m)->preloadAssets( timeOfDay );
  3444. } // end preloadAssets
  3445. //-------------------------------------------------------------------------------------------------
  3446. // Simply searches for the first occurrence of a specified client update module.
  3447. //-------------------------------------------------------------------------------------------------
  3448. ClientUpdateModule* Drawable::findClientUpdateModule( NameKeyType key )
  3449. {
  3450. ClientUpdateModule **clientModules = getClientUpdateModules();
  3451. if( clientModules )
  3452. {
  3453. while( *clientModules )
  3454. {
  3455. if( (*clientModules)->getModuleNameKey() == key )
  3456. {
  3457. return *clientModules;
  3458. }
  3459. }
  3460. }
  3461. return NULL;
  3462. }
  3463. // ------------------------------------------------------------------------------------------------
  3464. /** CRC */
  3465. // ------------------------------------------------------------------------------------------------
  3466. void Drawable::crc( Xfer *xfer )
  3467. {
  3468. } // end crc
  3469. // ------------------------------------------------------------------------------------------------
  3470. /** Xfer the drawable modules
  3471. * Version Info:
  3472. * 1: Initial version */
  3473. // ------------------------------------------------------------------------------------------------
  3474. void Drawable::xferDrawableModules( Xfer *xfer )
  3475. {
  3476. // version
  3477. const XferVersion currentVersion = 1;
  3478. XferVersion version = currentVersion;
  3479. xfer->xferVersion( &version, currentVersion );
  3480. //
  3481. // when using dirty condition flags ... we want to make sure that the modules are updated to
  3482. // the current state of the drawable
  3483. //
  3484. #ifdef DIRTY_CONDITION_FLAGS
  3485. if( xfer->getXferMode() == XFER_SAVE )
  3486. getDrawModules(); // will re-evaluate modules that are dirty and update them
  3487. #endif
  3488. // xfer number of module types
  3489. UnsignedShort moduleTypes = NUM_DRAWABLE_MODULE_TYPES;
  3490. xfer->xferUnsignedShort( &moduleTypes );
  3491. // xfer each set of modules for each type
  3492. AsciiString moduleIdentifier;
  3493. for( UnsignedShort curModuleType = 0; curModuleType < moduleTypes; ++curModuleType )
  3494. {
  3495. // how many modules are here for this type
  3496. Module **m;
  3497. UnsignedShort moduleCount = 0;
  3498. for( m = m_modules[ curModuleType ]; m && *m; ++m )
  3499. moduleCount++;
  3500. xfer->xferUnsignedShort( &moduleCount );
  3501. // xfer each module data
  3502. if( xfer->getXferMode() == XFER_SAVE )
  3503. {
  3504. // save each module
  3505. for( m = m_modules[ curModuleType ]; m && *m; ++m )
  3506. {
  3507. // write module identifier
  3508. moduleIdentifier = TheNameKeyGenerator->keyToName( (*m)->getModuleTagNameKey() );
  3509. DEBUG_ASSERTCRASH( moduleIdentifier != AsciiString::TheEmptyString,
  3510. ("Drawable::xferDrawableModules - module name key does not translate to a string!\n") );
  3511. xfer->xferAsciiString( &moduleIdentifier );
  3512. // begin data block
  3513. xfer->beginBlock();
  3514. // xfer data
  3515. xfer->xferSnapshot( *m );
  3516. // end data block
  3517. xfer->endBlock();
  3518. } // end for, m
  3519. } // end if, save
  3520. else
  3521. {
  3522. // read each module
  3523. for( UnsignedShort j = 0; j < moduleCount; ++j )
  3524. {
  3525. // read module identifier
  3526. xfer->xferAsciiString( &moduleIdentifier );
  3527. NameKeyType moduleIdentifierKey = TheNameKeyGenerator->nameToKey(moduleIdentifier);
  3528. // find module in the drawable module list
  3529. Module* module = NULL;
  3530. for( Module **m = m_modules[curModuleType]; m && *m; ++m )
  3531. {
  3532. if (moduleIdentifierKey == (*m)->getModuleTagNameKey())
  3533. {
  3534. module = *m;
  3535. break; // exit for m
  3536. } // end if
  3537. } // end for, m
  3538. // new block of data
  3539. Int dataSize = xfer->beginBlock();
  3540. //
  3541. // if we didn't find the module, it's quite possible that we have removed
  3542. // it from the object definition in a future patch, if that is so, we need to
  3543. // skip the module data in the file
  3544. //
  3545. if( module == NULL )
  3546. {
  3547. // for testing purposes, this module better be found
  3548. DEBUG_CRASH(( "Drawable::xferDrawableModules - Module '%s' was indicated in file, but not found on Drawable %s %d\n",
  3549. moduleIdentifier.str(), getTemplate()->getName().str(),getID() ));
  3550. // skip this data in the file
  3551. xfer->skip( dataSize );
  3552. } // end if
  3553. else
  3554. {
  3555. // xfer the data into this module
  3556. xfer->xferSnapshot( module );
  3557. } // end else
  3558. // end of data block
  3559. xfer->endBlock();
  3560. } // end for j
  3561. } // end else, load
  3562. } // end for curModuleType
  3563. } // end xferDrawableModules
  3564. // ------------------------------------------------------------------------------------------------
  3565. /** Xfer method
  3566. * Version Info;
  3567. * 1: Initial version
  3568. * 2: Moved condition state xfer before module xfer so we can restore anim frame
  3569. * during the module xfer (CBD)
  3570. * 4: Added m_ambientSoundEnabled flag
  3571. * 5: save full mtx, not pos+orient.
  3572. */
  3573. // ------------------------------------------------------------------------------------------------
  3574. void Drawable::xfer( Xfer *xfer )
  3575. {
  3576. // version
  3577. const XferVersion currentVersion = 5;
  3578. XferVersion version = currentVersion;
  3579. xfer->xferVersion( &version, currentVersion );
  3580. //Wow, because the constructor creates the ambient sound, the xfer can
  3581. //change the ID the sound points to, therefore, we must remove it now
  3582. //and restore it in loadPostProcess().
  3583. if( xfer->getXferMode() == XFER_LOAD && m_ambientSound )
  3584. {
  3585. TheAudio->killAudioEventImmediately( m_ambientSound->m_event.getPlayingHandle() );
  3586. m_ambientSound->deleteInstance();
  3587. m_ambientSound = NULL;
  3588. }
  3589. // drawable id
  3590. DrawableID id = getID();
  3591. xfer->xferDrawableID( &id );
  3592. setID( id );
  3593. // condition state, note that when we're loading we need to force a replace of these flags
  3594. if( version >= 2 )
  3595. {
  3596. m_conditionState.xfer( xfer );
  3597. if( xfer->getXferMode() == XFER_LOAD )
  3598. replaceModelConditionFlags( m_conditionState, TRUE );
  3599. } // end if
  3600. if( version >= 3 )
  3601. {
  3602. if (version >= 5)
  3603. {
  3604. Matrix3D mtx = *getTransformMatrix();
  3605. xfer->xferMatrix3D(&mtx);
  3606. setTransformMatrix(&mtx);
  3607. }
  3608. else
  3609. {
  3610. // position
  3611. Coord3D pos = *getPosition();
  3612. xfer->xferCoord3D( &pos );
  3613. setPosition( &pos );
  3614. // orientation
  3615. Real orientation = getOrientation();
  3616. xfer->xferReal( &orientation );
  3617. setOrientation( orientation );
  3618. }
  3619. }
  3620. // selection flash envelope
  3621. Bool selFlash = (m_selectionFlashEnvelope != NULL);
  3622. xfer->xferBool( &selFlash );
  3623. if( selFlash )
  3624. {
  3625. // allocate selection flash envelope if we need to
  3626. if( m_selectionFlashEnvelope == NULL )
  3627. m_selectionFlashEnvelope = newInstance( TintEnvelope );
  3628. // xfer
  3629. xfer->xferSnapshot( m_selectionFlashEnvelope );
  3630. } // end if
  3631. // color tint envelope
  3632. Bool colFlash = (m_colorTintEnvelope != NULL);
  3633. xfer->xferBool( &colFlash );
  3634. if( colFlash )
  3635. {
  3636. // allocate envelope if we need to
  3637. if( m_colorTintEnvelope == NULL )
  3638. m_colorTintEnvelope = newInstance( TintEnvelope );
  3639. // xfer
  3640. xfer->xferSnapshot( m_colorTintEnvelope );
  3641. } // end if
  3642. // terrain decal type
  3643. TerrainDecalType decal = getTerrainDecalType();
  3644. xfer->xferUser( &decal, sizeof( TerrainDecalType ) );
  3645. if( xfer->getXferMode() == XFER_LOAD )
  3646. setTerrainDecal( decal );
  3647. // explicit opacity
  3648. xfer->xferReal( &m_explicitOpacity );
  3649. // stealth opacity
  3650. xfer->xferReal( &m_stealthOpacity );
  3651. // effective stealth opacity
  3652. xfer->xferReal( &m_effectiveStealthOpacity );
  3653. // decalOpacityFadeTarget
  3654. xfer->xferReal( &m_decalOpacityFadeTarget );
  3655. // decalOpacityFadeRate
  3656. xfer->xferReal( &m_decalOpacityFadeRate );
  3657. // decalOpacityFadeRate
  3658. xfer->xferReal( &m_decalOpacity );
  3659. // object (if present)
  3660. ObjectID objectID = m_object ? m_object->getID() : INVALID_ID;
  3661. xfer->xferObjectID( &objectID );
  3662. // sanity
  3663. if( xfer->getXferMode() == XFER_LOAD )
  3664. {
  3665. if( m_object )
  3666. {
  3667. if( objectID != m_object->getID() )
  3668. {
  3669. DEBUG_CRASH(( "Drawable::xfer - Drawable '%s' is attached to wrong object '%s'\n",
  3670. getTemplate()->getName().str(), m_object->getTemplate()->getName().str() ));
  3671. throw SC_INVALID_DATA;
  3672. } // end if
  3673. } // end if
  3674. else
  3675. {
  3676. if( objectID != INVALID_ID )
  3677. {
  3678. #ifdef DEBUG_CRASHING
  3679. Object *obj = TheGameLogic->findObjectByID( objectID );
  3680. DEBUG_CRASH(( "Drawable::xfer - Drawable '%s' is not attached to an object but should be attached to object '%s' with id '%d'\n",
  3681. getTemplate()->getName().str(),
  3682. obj ? obj->getTemplate()->getName().str() : "Unknown",
  3683. objectID ));
  3684. #endif
  3685. throw SC_INVALID_DATA;
  3686. } // end if
  3687. } // end else
  3688. } // end if
  3689. // particle
  3690. // we don't need to worry about this, the particle itself will set it upon loading
  3691. // selected
  3692. // we won't worry about selection, we'll let TheInGameUI take care of it all
  3693. // status
  3694. xfer->xferUnsignedInt( &m_status );
  3695. // tint status
  3696. xfer->xferUnsignedInt( &m_tintStatus );
  3697. // prev tint status
  3698. xfer->xferUnsignedInt( &m_prevTintStatus );
  3699. // fading mode
  3700. xfer->xferUser( &m_fadeMode, sizeof( FadingMode ) );
  3701. // time elapsed fade
  3702. xfer->xferUnsignedInt( &m_timeElapsedFade );
  3703. // time to fade
  3704. xfer->xferUnsignedInt( &m_timeToFade );
  3705. Bool hasLocoInfo = (m_locoInfo != NULL);
  3706. xfer->xferBool( &hasLocoInfo );
  3707. if (hasLocoInfo)
  3708. {
  3709. if( xfer->getXferMode() == XFER_LOAD && m_locoInfo == NULL )
  3710. m_locoInfo = newInstance(DrawableLocoInfo);
  3711. // pitch
  3712. xfer->xferReal( &m_locoInfo->m_pitch );
  3713. // pitch rate
  3714. xfer->xferReal( &m_locoInfo->m_pitchRate );
  3715. // roll
  3716. xfer->xferReal( &m_locoInfo->m_roll );
  3717. // roll rate
  3718. xfer->xferReal( &m_locoInfo->m_rollRate );
  3719. // yaw
  3720. xfer->xferReal( &m_locoInfo->m_yaw );
  3721. // acceleration pitch
  3722. xfer->xferReal( &m_locoInfo->m_accelerationPitch );
  3723. // acceleration pitch rate
  3724. xfer->xferReal( &m_locoInfo->m_accelerationPitchRate );
  3725. // acceleration roll
  3726. xfer->xferReal( &m_locoInfo->m_accelerationRoll );
  3727. // acceleration roll rate
  3728. xfer->xferReal( &m_locoInfo->m_accelerationRollRate );
  3729. // overlap z vel
  3730. xfer->xferReal( &m_locoInfo->m_overlapZVel );
  3731. // overlap z
  3732. xfer->xferReal( &m_locoInfo->m_overlapZ );
  3733. // wobble
  3734. xfer->xferReal( &m_locoInfo->m_wobble );
  3735. // wheel info
  3736. xfer->xferReal( &m_locoInfo->m_wheelInfo.m_frontLeftHeightOffset );
  3737. xfer->xferReal( &m_locoInfo->m_wheelInfo.m_frontRightHeightOffset );
  3738. xfer->xferReal( &m_locoInfo->m_wheelInfo.m_rearLeftHeightOffset );
  3739. xfer->xferReal( &m_locoInfo->m_wheelInfo.m_rearRightHeightOffset );
  3740. xfer->xferReal( &m_locoInfo->m_wheelInfo.m_wheelAngle );
  3741. xfer->xferInt( &m_locoInfo->m_wheelInfo.m_framesAirborneCounter );
  3742. xfer->xferInt( &m_locoInfo->m_wheelInfo.m_framesAirborne );
  3743. }
  3744. // modules
  3745. xferDrawableModules( xfer );
  3746. // stealth look
  3747. xfer->xferUser( &m_stealthLook, sizeof( StealthLookType ) );
  3748. // flash count
  3749. xfer->xferInt( &m_flashCount );
  3750. // flash color
  3751. xfer->xferColor( &m_flashColor );
  3752. // hidden
  3753. xfer->xferBool( &m_hidden );
  3754. // hidden by stealth
  3755. xfer->xferBool( &m_hiddenByStealth );
  3756. // heat vision opacity
  3757. xfer->xferReal( &m_heatVisionOpacity );
  3758. // instance is identity
  3759. xfer->xferBool( &m_instanceIsIdentity );
  3760. // instance matrix
  3761. xfer->xferUser( &m_instance, sizeof( Matrix3D ) );
  3762. // instance scale
  3763. xfer->xferReal( &m_instanceScale );
  3764. // drawable Info - mostly hold FOW related data.
  3765. xfer->xferObjectID(&m_drawableInfo.m_shroudStatusObjectID);
  3766. // we do not need to save m_drawableInfo
  3767. // m_drawableInfo <--- do nothing with this
  3768. // condition state used to be here so we must keep it here for compatibility
  3769. if( version < 2 )
  3770. {
  3771. // sanity, we don't write old versions we can only read them
  3772. DEBUG_ASSERTCRASH( xfer->getXferMode() == XFER_LOAD,
  3773. ("Drawable::xfer - Writing an old format!!!\n") );
  3774. // condition state, note that when we're loading we need to force a replace of these flags
  3775. m_conditionState.xfer( xfer );
  3776. if( xfer->getXferMode() == XFER_LOAD )
  3777. replaceModelConditionFlags( m_conditionState, TRUE );
  3778. } // end if
  3779. // expiration date
  3780. xfer->xferUnsignedInt( &m_expirationDate );
  3781. // icon count
  3782. UnsignedByte iconCount = 0;
  3783. if (hasIconInfo())
  3784. {
  3785. for( UnsignedByte i = 0; i < MAX_ICONS; ++i )
  3786. if( getIconInfo()->m_icon[ i ] )
  3787. iconCount++;
  3788. }
  3789. xfer->xferUnsignedByte( &iconCount );
  3790. // icon data
  3791. AsciiString iconIndexName;
  3792. AsciiString iconTemplateName;
  3793. UnsignedInt iconKeepFrame;
  3794. if( xfer->getXferMode() == XFER_SAVE )
  3795. {
  3796. for( UnsignedByte i = 0; i < MAX_ICONS; ++i )
  3797. {
  3798. // skip empty icon slots
  3799. if( !hasIconInfo() || getIconInfo()->m_icon[ i ] == NULL )
  3800. continue;
  3801. // icon index name
  3802. iconIndexName.set( drawableIconIndexToName( (DrawableIconType)i ) );
  3803. xfer->xferAsciiString( &iconIndexName );
  3804. // keep till frame
  3805. iconKeepFrame = getIconInfo()->m_keepTillFrame[ i ];
  3806. xfer->xferUnsignedInt( &iconKeepFrame );
  3807. // icon template name
  3808. iconTemplateName = getIconInfo()->m_icon[ i ]->getAnimTemplate()->getName();
  3809. xfer->xferAsciiString( &iconTemplateName );
  3810. // icon data
  3811. xfer->xferSnapshot( getIconInfo()->m_icon[ i ] );
  3812. } // end for, i
  3813. } // end if, save
  3814. else
  3815. {
  3816. Int i;
  3817. // destroy any icons that might be present right now in favor of what we'll load from the file
  3818. if (hasIconInfo())
  3819. getIconInfo()->clear();
  3820. // read each data segment from the file
  3821. DrawableIconType iconIndex;
  3822. Anim2DTemplate *animTemplate;
  3823. for( i = 0; i < iconCount; ++i )
  3824. {
  3825. // icon index name
  3826. xfer->xferAsciiString( &iconIndexName );
  3827. iconIndex = drawableIconNameToIndex( iconIndexName.str() );
  3828. // keep till frame
  3829. xfer->xferUnsignedInt( &iconKeepFrame );
  3830. getIconInfo()->m_keepTillFrame[ iconIndex ] = iconKeepFrame;
  3831. // icon template name
  3832. xfer->xferAsciiString( &iconTemplateName );
  3833. animTemplate = TheAnim2DCollection->findTemplate( iconTemplateName );
  3834. if( animTemplate == NULL )
  3835. {
  3836. DEBUG_CRASH(( "Drawable::xfer - Unknown icon template '%s'\n", iconTemplateName.str() ));
  3837. throw SC_INVALID_DATA;
  3838. } // end if
  3839. // create icon
  3840. getIconInfo()->m_icon[ iconIndex ] = newInstance(Anim2D)( animTemplate, TheAnim2DCollection );
  3841. // icon data
  3842. xfer->xferSnapshot( getIconInfo()->m_icon[ iconIndex ] );
  3843. } // end for, i
  3844. } // end else, load
  3845. if( xfer->getXferMode() == XFER_LOAD )
  3846. {
  3847. // On load, we want to set it to none, because stealthlook updates
  3848. // when it changes. So in the next stealth update, it will be set to
  3849. // it's correct value, and the drawable updated (hide shadows and such). jba.
  3850. m_stealthLook = STEALTHLOOK_NONE;
  3851. // Also, need to update the hidden status for all sub-modules.
  3852. if (m_hidden || m_hiddenByStealth) {
  3853. updateHiddenStatus();
  3854. }
  3855. }
  3856. //
  3857. // when saving we should never have dirty modules, but when loading we will force the modules
  3858. // to be dirty just to be sure that they get re-evaluated after the load
  3859. //
  3860. #ifdef DIRTY_CONDITION_FLAGS
  3861. if( xfer->getXferMode() == XFER_SAVE )
  3862. DEBUG_ASSERTCRASH( m_isModelDirty == FALSE, ("Drawble::xfer - m_isModelDirty is not FALSE!\n") );
  3863. else
  3864. m_isModelDirty = TRUE;
  3865. #endif
  3866. if( version >= 4 )
  3867. {
  3868. xfer->xferBool( &m_ambientSoundEnabled );
  3869. }
  3870. } // end xfer
  3871. // ------------------------------------------------------------------------------------------------
  3872. /** Load post process */
  3873. // ------------------------------------------------------------------------------------------------
  3874. void Drawable::loadPostProcess( void )
  3875. {
  3876. // if we have an object, we don't need to save/load the pos, just restore it.
  3877. // if we don't, we'd better save it!
  3878. if (m_object != NULL)
  3879. {
  3880. setTransformMatrix(m_object->getTransformMatrix());
  3881. }
  3882. if( m_ambientSoundEnabled )
  3883. {
  3884. startAmbientSound();
  3885. }
  3886. else
  3887. {
  3888. stopAmbientSound();
  3889. }
  3890. } // end loadPostProcess
  3891. //=================================================================================================
  3892. //=================================================================================================
  3893. #ifdef DIRTY_CONDITION_FLAGS
  3894. /*static*/ void Drawable::friend_lockDirtyStuffForIteration()
  3895. {
  3896. if (s_modelLockCount == 0)
  3897. {
  3898. if (TheGameClient) // WB has no GameClient!
  3899. {
  3900. for (Drawable* d = TheGameClient->firstDrawable(); d != NULL; d = d->getNextDrawable())
  3901. {
  3902. // this will force us to update stuff.
  3903. d->getDrawModules();
  3904. }
  3905. }
  3906. }
  3907. ++s_modelLockCount;
  3908. }
  3909. #endif
  3910. //=================================================================================================
  3911. //=================================================================================================
  3912. #ifdef DIRTY_CONDITION_FLAGS
  3913. /*static*/ void Drawable::friend_unlockDirtyStuffForIteration()
  3914. {
  3915. if (s_modelLockCount > 0)
  3916. --s_modelLockCount;
  3917. }
  3918. #endif
  3919. //=================================================================================================
  3920. //=================================================================================================
  3921. TintEnvelope::TintEnvelope(void)
  3922. {
  3923. m_attackRate.Set(0,0,0);
  3924. m_decayRate.Set(0,0,0);
  3925. m_peakColor.Set(0,0,0);
  3926. m_currentColor.Set(0,0,0);
  3927. m_envState = ENVELOPE_STATE_REST;
  3928. m_sustainCounter = 0;
  3929. m_affect = FALSE;
  3930. }
  3931. //-------------------------------------------------------------------------------------------------
  3932. const Real FADE_RATE_EPSILON = (0.001f);
  3933. //-------------------------------------------------------------------------------------------------
  3934. void TintEnvelope::play(const RGBColor *peak, UnsignedInt atackFrames, UnsignedInt decayFrames, UnsignedInt sustainAtPeak )
  3935. {
  3936. setPeakColor( peak );
  3937. setAttackFrames( atackFrames );
  3938. setDecayFrames( decayFrames );
  3939. m_envState = ENVELOPE_STATE_ATTACK;
  3940. m_sustainCounter = sustainAtPeak;
  3941. m_affect = TRUE;
  3942. Vector3 delta;
  3943. Vector3::Subtract(m_currentColor, m_peakColor, &delta);
  3944. if ( delta.Length() <= FADE_RATE_EPSILON ) // we are practically already at this color
  3945. m_envState = ENVELOPE_STATE_SUSTAIN;
  3946. }
  3947. //-------------------------------------------------------------------------------------------------
  3948. void TintEnvelope::setAttackFrames(UnsignedInt frames)
  3949. {
  3950. Real recipFrames = 1.0f / (Real)MAX(1,frames);
  3951. m_attackRate.Set( m_currentColor );
  3952. Vector3::Subtract( m_peakColor, m_attackRate, &m_attackRate);
  3953. m_attackRate.Scale( Vector3(recipFrames, recipFrames, recipFrames) );
  3954. }
  3955. //-------------------------------------------------------------------------------------------------
  3956. void TintEnvelope::setDecayFrames( UnsignedInt frames )
  3957. {
  3958. Real recipFrames = ( -1.0f ) / (Real)MAX(1,frames);
  3959. m_decayRate.Set( m_peakColor );
  3960. m_decayRate.Scale( Vector3(recipFrames, recipFrames, recipFrames) );
  3961. }
  3962. //-------------------------------------------------------------------------------------------------
  3963. void TintEnvelope::update(void)
  3964. {
  3965. switch ( m_envState )
  3966. {
  3967. case ( ENVELOPE_STATE_REST ) : //most likely case
  3968. {
  3969. m_currentColor.Set(0,0,0);
  3970. m_affect = FALSE;
  3971. break;
  3972. }
  3973. case ( ENVELOPE_STATE_DECAY ) : // much more likely than attack
  3974. {
  3975. if (m_decayRate.Length() > m_currentColor.Length() || m_currentColor.Length() <= FADE_RATE_EPSILON) //we are at rest
  3976. {
  3977. m_envState = ENVELOPE_STATE_REST;
  3978. m_affect = FALSE;
  3979. }
  3980. else
  3981. {
  3982. Vector3::Add( m_decayRate, m_currentColor, &m_currentColor );//Add the decayRate to the current color;
  3983. m_affect = TRUE;
  3984. }
  3985. break;
  3986. }
  3987. case ( ENVELOPE_STATE_ATTACK ) :
  3988. {
  3989. Vector3 delta;
  3990. Vector3::Subtract(m_currentColor, m_peakColor, &delta);
  3991. if (m_attackRate.Length() > delta.Length() || delta.Length() <= FADE_RATE_EPSILON) //we are at the peak
  3992. {
  3993. if ( m_sustainCounter )
  3994. {
  3995. m_envState = ENVELOPE_STATE_SUSTAIN;
  3996. }
  3997. else
  3998. {
  3999. m_envState = ENVELOPE_STATE_DECAY;
  4000. }
  4001. }
  4002. else
  4003. {
  4004. Vector3::Add( m_attackRate, m_currentColor, &m_currentColor );//Add the attackRate to the current color;
  4005. m_affect = TRUE;
  4006. }
  4007. break;
  4008. }
  4009. case ( ENVELOPE_STATE_SUSTAIN ) :
  4010. {
  4011. if ( m_sustainCounter > 0 )
  4012. --m_sustainCounter;
  4013. else
  4014. release();
  4015. break;
  4016. }
  4017. default:
  4018. {
  4019. //do nothing, we are sustaining until externally triggered to release (decay)
  4020. break;
  4021. }
  4022. }
  4023. // here we transition the color from current to peak to release, according to
  4024. }
  4025. // ------------------------------------------------------------------------------------------------
  4026. /** CRC */
  4027. // ------------------------------------------------------------------------------------------------
  4028. void TintEnvelope::crc( Xfer *xfer )
  4029. {
  4030. } // end crc
  4031. // ------------------------------------------------------------------------------------------------
  4032. /** Xfer Method
  4033. * Version Info;
  4034. * 1: Initial version */
  4035. // ------------------------------------------------------------------------------------------------
  4036. void TintEnvelope::xfer( Xfer *xfer )
  4037. {
  4038. // version
  4039. XferVersion currentVersion = 1;
  4040. XferVersion version = currentVersion;
  4041. xfer->xferVersion( &version, currentVersion );
  4042. // attack rate
  4043. xfer->xferUser( &m_attackRate, sizeof( Vector3 ) );
  4044. // decay rate
  4045. xfer->xferUser( &m_decayRate, sizeof( Vector3 ) );
  4046. // peak color
  4047. xfer->xferUser( &m_peakColor, sizeof( Vector3 ) );
  4048. // current color
  4049. xfer->xferUser( &m_currentColor, sizeof( Vector3 ) );
  4050. // sustain counter
  4051. xfer->xferUnsignedInt( &m_sustainCounter );
  4052. // affect
  4053. xfer->xferBool( &m_affect );
  4054. // state
  4055. xfer->xferByte( &m_envState );
  4056. } // end xfer
  4057. // ------------------------------------------------------------------------------------------------
  4058. /** Load Post Process */
  4059. // ------------------------------------------------------------------------------------------------
  4060. void TintEnvelope::loadPostProcess( void )
  4061. {
  4062. } // end loadPostProcess