Drawable.cpp 186 KB

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