Spawn.cpp 155 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244
  1. /*
  2. EQ2Emulator: Everquest II Server Emulator
  3. Copyright (C) 2007 EQ2EMulator Development Team (http://www.eq2emulator.net)
  4. This file is part of EQ2Emulator.
  5. EQ2Emulator 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. EQ2Emulator is distributed in the hope that it will be useful,
  10. but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. GNU General Public License for more details.
  13. You should have received a copy of the GNU General Public License
  14. along with EQ2Emulator. If not, see <http://www.gnu.org/licenses/>.
  15. */
  16. #include "Spawn.h"
  17. #include <stdio.h>
  18. #include "../common/timer.h"
  19. #include <time.h>
  20. #include <math.h>
  21. #include "Entity.h"
  22. #include "Widget.h"
  23. #include "Sign.h"
  24. #include "../common/MiscFunctions.h"
  25. #include "../common/Log.h"
  26. #include "Rules/Rules.h"
  27. #include "World.h"
  28. #include "LuaInterface.h"
  29. #include "Bots/Bot.h"
  30. #include "Zone/raycast_mesh.h"
  31. #include "RaceTypes/RaceTypes.h"
  32. #include "VisualStates.h"
  33. extern ConfigReader configReader;
  34. extern RuleManager rule_manager;
  35. extern World world;
  36. extern ZoneList zone_list;
  37. extern MasterRaceTypeList race_types_list;
  38. extern LuaInterface* lua_interface;
  39. extern VisualStates visual_states;
  40. Spawn::Spawn(){
  41. loot_coins = 0;
  42. trap_triggered = false;
  43. trap_state = 0;
  44. chest_drop_time = 0;
  45. trap_opened_time = 0;
  46. group_id = 0;
  47. size_offset = 0;
  48. merchant_id = 0;
  49. merchant_type = 0;
  50. merchant_min_level = 0;
  51. merchant_max_level = 0;
  52. memset(&appearance, 0, sizeof(AppearanceData));
  53. memset(&basic_info, 0, sizeof(BasicInfoStruct));
  54. appearance.pos.state = 0x4080;
  55. appearance.difficulty = 6;
  56. size = 32;
  57. appearance.pos.collision_radius = 32;
  58. id = Spawn::NextID();
  59. oversized_packet = 0xFF;
  60. zone = 0;
  61. spawn_location_id = 0;
  62. spawn_entry_id = 0;
  63. spawn_location_spawns_id = 0;
  64. respawn = 0;
  65. expire_time = 0;
  66. expire_offset = 0;
  67. x_offset = 0;
  68. y_offset = 0;
  69. z_offset = 0;
  70. database_id = 0;
  71. packet_num = 1;
  72. changed = false;
  73. vis_changed = false;
  74. position_changed = false;
  75. send_spawn_changes = true;
  76. info_changed = false;
  77. appearance.pos.Speed1 = 0;
  78. last_attacker = 0;
  79. faction_id = 0;
  80. running_to = 0;
  81. tmp_visual_state = -1;
  82. tmp_action_state = -1;
  83. transporter_id = 0;
  84. invulnerable = false;
  85. spawn_group_list = 0;
  86. MSpawnGroup = 0;
  87. movement_locations = 0;
  88. target = 0;
  89. primary_command_list_id = 0;
  90. secondary_command_list_id = 0;
  91. is_pet = false;
  92. m_followTarget = 0;
  93. following = false;
  94. req_quests_continued_access = false;
  95. req_quests_override = 0;
  96. req_quests_private = false;
  97. m_illusionModel = 0;
  98. Cell_Info.CurrentCell = nullptr;
  99. Cell_Info.CellListIndex = -1;
  100. m_addedToWorldTimestamp = 0;
  101. m_spawnAnim = 0;
  102. m_spawnAnimLeeway = 0;
  103. m_Update.SetName("Spawn::m_Update");
  104. m_requiredHistory.SetName("Spawn::m_requiredHistory");
  105. m_requiredQuests.SetName("Spawn::m_requiredQuests");
  106. last_heading_angle = 0.0;
  107. last_grid_update = 0;
  108. last_location_update = 0.0;
  109. last_movement_update = Timer::GetCurrentTime2();
  110. forceMapCheck = false;
  111. m_followDistance = 0;
  112. MCommandMutex.SetName("Entity::MCommandMutex");
  113. has_spawn_proximities = false;
  114. pickup_item_id = 0;
  115. pickup_unique_item_id = 0;
  116. disable_sounds = false;
  117. has_quests_required = false;
  118. has_history_required = false;
  119. is_flying_creature = false;
  120. is_water_creature = false;
  121. region_map = nullptr;
  122. current_map = nullptr;
  123. RegionMutex.SetName("Spawn::RegionMutex");
  124. pause_timer.Disable();
  125. m_SpawnMutex.SetName("Spawn::SpawnMutex");
  126. appearance_equipment_list.SetAppearanceType(1);
  127. is_transport_spawn = false;
  128. rail_id = 0;
  129. is_omitted_by_db_flag = false;
  130. loot_tier = 0;
  131. loot_drop_type = 0;
  132. deleted_spawn = false;
  133. is_collector = false;
  134. trigger_widget_id = 0;
  135. scared_by_strong_players = false;
  136. is_alive = true;
  137. SetLockedNoLoot(ENCOUNTER_STATE_AVAILABLE);
  138. loot_method = GroupLootMethod::METHOD_FFA;
  139. loot_rarity = 0;
  140. loot_group_id = 0;
  141. looter_spawn_id = 0;
  142. is_loot_complete = false;
  143. is_loot_dispensed = false;
  144. reset_movement = false;
  145. ResetKnockedBack();
  146. }
  147. Spawn::~Spawn(){
  148. is_running = false;
  149. vector<Item*>::iterator itr;
  150. for (itr = loot_items.begin(); itr != loot_items.end(); itr++)
  151. safe_delete(*itr);
  152. loot_items.clear();
  153. RemovePrimaryCommands();
  154. for(int32 i=0;i<secondary_command_list.size();i++){
  155. safe_delete(secondary_command_list[i]);
  156. }
  157. secondary_command_list.clear();
  158. RemoveSpawnFromGroup();
  159. MMovementLocations.lock();
  160. if(movement_locations){
  161. while(movement_locations->size()){
  162. safe_delete(movement_locations->front());
  163. movement_locations->pop_front();
  164. }
  165. safe_delete(movement_locations);
  166. }
  167. MMovementLocations.unlock();
  168. MMovementLoop.lock();
  169. for (int32 i = 0; i < movement_loop.size(); i++)
  170. safe_delete(movement_loop.at(i));
  171. movement_loop.clear();
  172. MMovementLoop.unlock();
  173. m_requiredHistory.writelock(__FUNCTION__, __LINE__);
  174. map<int32, LUAHistory*>::iterator lua_itr;
  175. for (lua_itr = required_history.begin(); lua_itr != required_history.end(); lua_itr++) {
  176. safe_delete(lua_itr->second);
  177. }
  178. required_history.clear();
  179. m_requiredHistory.releasewritelock(__FUNCTION__, __LINE__);
  180. m_requiredQuests.writelock(__FUNCTION__, __LINE__);
  181. map<int32, vector<int16>* >::iterator rq_itr;
  182. for (rq_itr = required_quests.begin(); rq_itr != required_quests.end(); rq_itr++){
  183. safe_delete(rq_itr->second);
  184. }
  185. required_quests.clear();
  186. m_requiredQuests.releasewritelock(__FUNCTION__, __LINE__);
  187. // just in case to make sure data is destroyed
  188. RemoveSpawnProximities();
  189. Regions.clear();
  190. }
  191. void Spawn::RemovePrimaryCommands()
  192. {
  193. for (int32 i = 0; i < primary_command_list.size(); i++) {
  194. safe_delete(primary_command_list[i]);
  195. }
  196. primary_command_list.clear();
  197. }
  198. void Spawn::InitializeHeaderPacketData(Player* player, PacketStruct* header, int16 index) {
  199. header->setDataByName("index", index);
  200. if (GetSpawnAnim() > 0 && Timer::GetCurrentTime2() < (GetAddedToWorldTimestamp() + GetSpawnAnimLeeway())) {
  201. if (header->GetVersion() >= 57080)
  202. header->setDataByName("spawn_anim", GetSpawnAnim());
  203. else
  204. header->setDataByName("spawn_anim", (int16)GetSpawnAnim());
  205. }
  206. else {
  207. if (header->GetVersion() >= 57080)
  208. header->setDataByName("spawn_anim", 0xFFFFFFFF);
  209. else
  210. header->setDataByName("spawn_anim", 0xFFFF);
  211. }
  212. if (primary_command_list.size() > 0){
  213. if (primary_command_list.size() > 1) {
  214. header->setArrayLengthByName("command_list", primary_command_list.size());
  215. for (int32 i = 0; i < primary_command_list.size(); i++) {
  216. header->setArrayDataByName("command_list_name", primary_command_list[i]->name.c_str(), i);
  217. header->setArrayDataByName("command_list_max_distance", primary_command_list[i]->distance, i);
  218. header->setArrayDataByName("command_list_error", primary_command_list[i]->error_text.c_str(), i);
  219. header->setArrayDataByName("command_list_command", primary_command_list[i]->command.c_str(), i);
  220. }
  221. }
  222. if (header->GetVersion() <= 561) {
  223. header->setMediumStringByName("default_command", primary_command_list[0]->name.c_str());
  224. }
  225. else
  226. header->setMediumStringByName("default_command", primary_command_list[0]->command.c_str());
  227. header->setDataByName("max_distance", primary_command_list[0]->distance);
  228. }
  229. if (spawn_group_list && MSpawnGroup){
  230. MSpawnGroup->readlock(__FUNCTION__, __LINE__);
  231. header->setArrayLengthByName("group_size", spawn_group_list->size());
  232. vector<Spawn*>::iterator itr;
  233. int i = 0;
  234. for (itr = spawn_group_list->begin(); itr != spawn_group_list->end(); itr++, i++){
  235. int32 idx = 0;
  236. idx = player->GetIDWithPlayerSpawn((*itr));
  237. header->setArrayDataByName("group_spawn_id", idx, i);
  238. }
  239. MSpawnGroup->releasereadlock(__FUNCTION__, __LINE__);
  240. }
  241. header->setDataByName("spawn_id", player->GetIDWithPlayerSpawn(this));
  242. header->setDataByName("crc", 1);
  243. header->setDataByName("time_stamp", Timer::GetCurrentTime2());
  244. }
  245. void Spawn::InitializeVisPacketData(Player* player, PacketStruct* vis_packet) {
  246. int16 version = vis_packet->GetVersion();
  247. //why?
  248. /*if (IsPlayer()) {
  249. appearance.pos.grid_id = 0xFFFFFFFF;
  250. }*/
  251. int8 tag_icon = 0;
  252. int32 tmp_id = 0;
  253. if(faction_id && (tag_icon = player->MatchGMVisualFilter(GMTagFilterType::GMFILTERTYPE_FACTION, faction_id, "", true)) > 0);
  254. else if(IsGroundSpawn() && (tag_icon = player->MatchGMVisualFilter(GMTagFilterType::GMFILTERTYPE_GROUNDSPAWN, 1, "", true)) > 0);
  255. else if((this->GetSpawnGroupID() && (tag_icon = player->MatchGMVisualFilter(GMTagFilterType::GMFILTERTYPE_SPAWNGROUP, 1, "", true)) > 0) ||
  256. (!this->GetSpawnGroupID() && (tag_icon = player->MatchGMVisualFilter(GMTagFilterType::GMFILTERTYPE_SPAWNGROUP, 0, "", true)) > 0));
  257. else if((this->GetRace() && (tag_icon = player->MatchGMVisualFilter(GMTagFilterType::GMFILTERTYPE_RACE, GetRace(), "", true)) > 0));
  258. else if(((tmp_id = race_types_list.GetRaceType(GetModelType()) > 0) && (tag_icon = player->MatchGMVisualFilter(GMTagFilterType::GMFILTERTYPE_RACE, tmp_id, "", true)) > 0));
  259. else if(((tmp_id = race_types_list.GetRaceBaseType(GetModelType()) > 0) && (tag_icon = player->MatchGMVisualFilter(GMTagFilterType::GMFILTERTYPE_RACE, tmp_id, "", true)) > 0));
  260. else if(IsEntity() && (tag_icon = ((Entity*)this)->GetInfoStruct()->get_tag1()) > 0);
  261. vis_packet->setDataByName("tag1", tag_icon);
  262. if (IsPlayer())
  263. vis_packet->setDataByName("player", 1);
  264. if (version <= 561) {
  265. vis_packet->setDataByName("targetable", appearance.targetable);
  266. vis_packet->setDataByName("show_name", appearance.display_name);
  267. vis_packet->setDataByName("attackable", appearance.attackable);
  268. if(appearance.attackable == 1)
  269. vis_packet->setDataByName("attackable_icon", 1);
  270. if (IsPlayer()) {
  271. if (((Player*)this)->IsGroupMember(player))
  272. vis_packet->setDataByName("group_member", 1);
  273. }
  274. }
  275. if (appearance.targetable == 1 || appearance.show_level == 1 || appearance.display_name == 1) {
  276. if (!IsGroundSpawn()) {
  277. int8 arrow_color = ARROW_COLOR_WHITE;
  278. sint8 npc_con = player->GetFactions()->GetCon(faction_id);
  279. if (IsPlayer() && !((Player*)this)->CanSeeInvis(player))
  280. npc_con = 0;
  281. else if (!IsPlayer() && IsEntity() && !((Entity*)this)->CanSeeInvis(player))
  282. npc_con = 0;
  283. if (appearance.attackable == 1)
  284. arrow_color = player->GetArrowColor(GetLevel());
  285. if (version <= 283) {
  286. if (GetMerchantID() > 0)
  287. arrow_color += 7;
  288. else {
  289. if (primary_command_list.size() > 0) {
  290. int16 len = strlen(primary_command_list[0]->command.c_str());
  291. if(len >= 4 && strncmp(primary_command_list[0]->command.c_str(), "bank", 4) == 0)
  292. arrow_color += 14;
  293. else if (len >= 4 && strncmp(primary_command_list[0]->command.c_str(), "hail", 4) == 0)
  294. arrow_color += 21;
  295. else if (len >= 6 && strncmp(primary_command_list[0]->command.c_str(), "attack", 6) == 0) {
  296. if (arrow_color > 5)
  297. arrow_color = 34;
  298. else
  299. arrow_color += 29;
  300. }
  301. }
  302. }
  303. }
  304. if(IsNPC() && (((Entity*)this)->GetLockedNoLoot() == ENCOUNTER_STATE_BROKEN ||
  305. (((Entity*)this)->GetLockedNoLoot() == ENCOUNTER_STATE_OVERMATCHED) ||
  306. ((Entity*)this)->GetLockedNoLoot() == ENCOUNTER_STATE_LOCKED && !((NPC*)this)->Brain()->IsEntityInEncounter(player->GetID()))) {
  307. vis_packet->setDataByName("arrow_color", ARROW_COLOR_GRAY);
  308. }
  309. else {
  310. vis_packet->setDataByName("arrow_color", arrow_color);
  311. }
  312. if (appearance.attackable == 0 || IsPlayer() || IsBot() || (IsEntity() && ((Entity*)this)->GetOwner() &&
  313. (((Entity*)this)->GetOwner()->IsPlayer() || ((Entity*)this)->GetOwner()->IsBot()))) {
  314. vis_packet->setDataByName("locked_no_loot", 1);
  315. }
  316. else {
  317. vis_packet->setDataByName("locked_no_loot", appearance.locked_no_loot);
  318. }
  319. if (player->GetArrowColor(GetLevel()) == ARROW_COLOR_GRAY)
  320. if (npc_con == -4)
  321. npc_con = -3;
  322. vis_packet->setDataByName("npc_con", npc_con);
  323. if (appearance.attackable == 1 && IsNPC() && (player->GetFactions()->GetCon(faction_id) <= -4 || ((NPC*)this)->Brain()->GetHate(player) > 1)) {
  324. vis_packet->setDataByName("npc_hate", ((NPC*)this)->Brain()->GetHatePercentage(player));
  325. vis_packet->setDataByName("show_difficulty_arrows", 1);
  326. }
  327. int8 quest_flag = player->CheckQuestFlag(this);
  328. if (version < 1188 && quest_flag >= 16)
  329. quest_flag = 1;
  330. vis_packet->setDataByName("quest_flag", quest_flag);
  331. if (player->HasQuestUpdateRequirement(this)) {
  332. vis_packet->setDataByName("name_quest_icon", 1);
  333. }
  334. }
  335. }
  336. int8 vis_flags = 0;
  337. if (MeetsSpawnAccessRequirements(player)) {
  338. if (appearance.attackable == 1)
  339. vis_flags += 64; //attackable icon
  340. if (appearance.show_level == 1)
  341. vis_flags += 32;
  342. if (appearance.display_name == 1)
  343. vis_flags += 16;
  344. if (IsPlayer() || appearance.targetable == 1)
  345. vis_flags += 4;
  346. if (appearance.show_command_icon == 1)
  347. vis_flags += 2;
  348. if (this == player) {
  349. //if (version <= 283) {
  350. // vis_flags = 1;
  351. //}
  352. //else
  353. vis_flags += 1;
  354. }
  355. }
  356. else if (req_quests_override > 0)
  357. {
  358. //Check to see if there's an override value set
  359. vis_flags = req_quests_override & 0xFF;
  360. }
  361. if (player->HasGMVision())
  362. {
  363. if ((vis_flags & 16) == 0 && appearance.display_name == 0)
  364. vis_flags += 16;
  365. if ((vis_flags & 4) == 0)
  366. vis_flags += 4;
  367. }
  368. if (version <= 546 && (vis_flags > 1 || appearance.display_hand_icon > 0)) //interactable
  369. vis_flags = 1;
  370. vis_packet->setDataByName("vis_flags", vis_flags);
  371. if (MeetsSpawnAccessRequirements(player)) {
  372. vis_packet->setDataByName("hand_flag", appearance.display_hand_icon);
  373. }
  374. else {
  375. if ((req_quests_override & 256) > 0)
  376. vis_packet->setDataByName("hand_flag", 1);
  377. }
  378. if ((version == 546 || version == 561) && GetMerchantID() > 0) {
  379. vis_packet->setDataByName("guild", "<Merchant>");
  380. }
  381. }
  382. void Spawn::InitializeFooterPacketData(Player* player, PacketStruct* footer) {
  383. if (IsWidget()){
  384. Widget* widget = (Widget*)this;
  385. if (widget->GetMultiFloorLift()) {
  386. footer->setDataByName("widget_x", widget->GetX());
  387. footer->setDataByName("widget_y", widget->GetY());
  388. footer->setDataByName("widget_z", widget->GetZ());
  389. }
  390. else {
  391. footer->setDataByName("widget_x", widget->GetWidgetX());
  392. footer->setDataByName("widget_y", widget->GetWidgetY());
  393. footer->setDataByName("widget_z", widget->GetWidgetZ());
  394. }
  395. footer->setDataByName("widget_id", widget->GetWidgetID());
  396. }
  397. else if (IsSign()){
  398. Sign* sign = (Sign*)this;
  399. footer->setDataByName("widget_id", sign->GetWidgetID());
  400. footer->setDataByName("widget_x", sign->GetWidgetX());
  401. footer->setDataByName("widget_y", sign->GetWidgetY());
  402. footer->setDataByName("widget_z", sign->GetWidgetZ());
  403. int8 showSignText = 1;
  404. if((HasQuestsRequired() || HasHistoryRequired()) && !MeetsSpawnAccessRequirements(player)) {
  405. showSignText = 0;
  406. }
  407. if (sign->GetSignTitle())
  408. footer->setMediumStringByName("title", sign->GetSignTitle());
  409. if (sign->GetSignDescription())
  410. footer->setMediumStringByName("description", sign->GetSignDescription());
  411. footer->setDataByName("sign_distance", sign->GetSignDistance());
  412. footer->setDataByName("show", showSignText);
  413. // in live we see that the language is set when the player does not have it, otherwise its left as 00's.
  414. if(!player->HasLanguage(sign->GetLanguage())) {
  415. footer->setDataByName("language", sign->GetLanguage());
  416. }
  417. }
  418. if ( IsPlayer())
  419. footer->setDataByName("is_player", 1);
  420. if (strlen(appearance.name) < 1)
  421. strncpy(appearance.name,to_string(GetID()).c_str(),128);
  422. footer->setMediumStringByName("name", appearance.name);
  423. footer->setMediumStringByName("guild", appearance.sub_title);
  424. footer->setMediumStringByName("prefix", appearance.prefix_title);
  425. footer->setMediumStringByName("suffix", appearance.suffix_title);
  426. footer->setMediumStringByName("last_name", appearance.last_name);
  427. if (appearance.attackable == 0 && GetLevel() > 0)
  428. footer->setDataByName("spawn_type", 1);
  429. else if (appearance.attackable == 0)
  430. footer->setDataByName("spawn_type", 6);
  431. else
  432. footer->setDataByName("spawn_type", 3);
  433. }
  434. EQ2Packet* Spawn::spawn_serialize(Player* player, int16 version, int16 offset, int32 value, int16 offset2, int16 offset3, int16 offset4, int32 value2) {
  435. // If spawn is NPC AND is pet && owner is a player && owner is the player passed to this function && player's char sheet pet id is 0
  436. m_Update.writelock(__FUNCTION__, __LINE__);
  437. int16 index = 0;
  438. if ((index = player->GetIndexForSpawn(this)) > 0) {
  439. player->SetSpawnMapIndex(this, index);
  440. }
  441. else {
  442. index = player->SetSpawnMapAndIndex(this);
  443. }
  444. // Jabantiz - [Bug] Client Crash on Revive
  445. if (player->GetIDWithPlayerSpawn(this) == 0) {
  446. player->SetSpawnMap(this);
  447. }
  448. PacketStruct* header = player->GetSpawnHeaderStruct();
  449. header->ResetData();
  450. InitializeHeaderPacketData(player, header, index);
  451. PacketStruct* footer = 0;
  452. if (IsWidget())
  453. footer = player->GetWidgetFooterStruct();
  454. else if (IsSign())
  455. footer = player->GetSignFooterStruct();
  456. else if (version > 561)
  457. footer = player->GetSpawnFooterStruct();
  458. if (footer) {
  459. footer->ResetData();
  460. InitializeFooterPacketData(player, footer);
  461. }
  462. PacketStruct* vis_struct = player->GetSpawnVisStruct();
  463. PacketStruct* info_struct = player->GetSpawnInfoStruct();
  464. PacketStruct* pos_struct = player->GetSpawnPosStruct();
  465. player->info_mutex.writelock(__FUNCTION__, __LINE__);
  466. player->vis_mutex.writelock(__FUNCTION__, __LINE__);
  467. player->pos_mutex.writelock(__FUNCTION__, __LINE__);
  468. info_struct->ResetData();
  469. InitializeInfoPacketData(player, info_struct);
  470. vis_struct->ResetData();
  471. InitializeVisPacketData(player, vis_struct);
  472. pos_struct->ResetData();
  473. InitializePosPacketData(player, pos_struct);
  474. if (version <= 283) {
  475. if (offset == 777) {
  476. info_struct->setDataByName("name", "This is a really long name\n");
  477. info_struct->setDataByName("last_name", "This is a really long LAST name\n");
  478. info_struct->setDataByName("name_suffix", "This is a really long SUFFIX\n");
  479. info_struct->setDataByName("name_prefix", "This is a really long PREFIX\n");
  480. info_struct->setDataByName("unknown", "This is a really long UNKNOWN\n");
  481. info_struct->setDataByName("second_suffix", "This is a really long 2nd SUFFIX\n");
  482. }
  483. //info_struct->setDataByName("unknown2", 3, 0); // level
  484. //info_struct->setDataByName("unknown2", 1, 1); //unknown, two down arrows
  485. //info_struct->setDataByName("unknown2", 1, 2); //unknown
  486. //info_struct->setDataByName("unknown2", 1, 3); //unknown
  487. //info_struct->setDataByName("unknown2", 1, 4); //solo fight
  488. //info_struct->setDataByName("unknown2", 1, 5); //unknown
  489. //info_struct->setDataByName("unknown2", 1, 6); //unknown
  490. //info_struct->setDataByName("unknown2", 1, 7); //merchant
  491. //info_struct->setDataByName("unknown2", 1, 8); //unknown
  492. //info_struct->setDataByName("unknown2", 1, 9); //unknown
  493. //info_struct->setDataByName("unknown2", 1, 10);
  494. //112: 00 00 00 01 02 03 04 05 - 06 07 08 09 0A 00 00 00 | ................ merchant, x4
  495. //112: 00 00 00 01 02 03 04 05 - 00 00 00 00 00 00 00 00 | ................ x4, epic, indifferent
  496. //info_struct->setDataByName("body_size", 42);
  497. //for(int i=0;i<8;i++)
  498. // info_struct->setDataByName("persistent_spell_visuals", 329, i);
  499. //info_struct->setDataByName("persistent_spell_levels", 20);
  500. }
  501. string* vis_data = vis_struct->serializeString();
  502. string* pos_data = pos_struct->serializeString();
  503. string* info_data = info_struct->serializeString();
  504. int16 part2_size = pos_data->length() + vis_data->length() + info_data->length();
  505. uchar* part2 = new uchar[part2_size];
  506. player->AddSpawnPosPacketForXOR(id, (uchar*)pos_data->c_str(), pos_data->length());
  507. player->AddSpawnVisPacketForXOR(id, (uchar*)vis_data->c_str(), vis_data->length());
  508. player->AddSpawnInfoPacketForXOR(id, (uchar*)info_data->c_str(), info_data->length());
  509. int32 vislength = vis_data->length();
  510. int32 poslength = pos_data->length();
  511. int32 infolength = info_data->length();
  512. uchar* ptr = part2;
  513. memcpy(ptr, pos_data->c_str(), pos_data->length());
  514. ptr += pos_data->length();
  515. memcpy(ptr, vis_data->c_str(), vis_data->length());
  516. ptr += vis_data->length();
  517. memcpy(ptr, info_data->c_str(), info_data->length());
  518. player->pos_mutex.releasewritelock(__FUNCTION__, __LINE__);
  519. player->info_mutex.releasewritelock(__FUNCTION__, __LINE__);
  520. player->vis_mutex.releasewritelock(__FUNCTION__, __LINE__);
  521. string* part1 = header->serializeString();
  522. string* part3 = 0;
  523. if (footer)
  524. part3 = footer->serializeString();
  525. //uchar blah7[] = {0x01,0x01,0x00,0x00,0x01,0x01,0x00,0x01,0x01,0x00 };
  526. //uchar blah7[] = { 0x03,0x01,0x00,0x01,0x01,0x01,0x00,0x01,0x01,0x00 }; base
  527. //uchar blah7[] = { 0x03,0x00,0x00,0x01,0x01,0x01,0x00,0x01,0x01,0x00 }; //no change
  528. //uchar blah7[] = { 0x03,0x00,0x00,0x00,0x01,0x01,0x00,0x01,0x01,0x00 }; //blue instead of green
  529. //uchar blah7[] = { 0x03,0x00,0x00,0x00,0x00,0x01,0x00,0x01,0x01,0x00 }; //no change
  530. //uchar blah7[] = { 0x03,0x00,0x00,0x00,0x00,0x00,0x00,0x01,0x01,0x00 }; //not selectable
  531. //uchar blah7[] = { 0x03,0x00,0x00,0x00,0x00,0x01,0x00,0x00,0x01,0x00 }; //no change
  532. //uchar blah7[] = { 0x03,0x00,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x00 }; //no longer have the two down arrows
  533. //uchar blah7[] = { 0x01,0x00,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x00 }; //arrow color green instead of white/gray
  534. //memcpy(part2 + 77, blah7, sizeof(blah7));
  535. //DumpPacket(part2, 885);
  536. if (offset > 0) {
  537. if (offset4 > 0 && offset4 >= offset3) {
  538. uchar* ptr2 = (uchar*)part2;
  539. ptr2 += offset3;
  540. while (offset4 >= offset3) {
  541. int8 jumpsize = 1;
  542. if (value2 > 0xFFFF) {
  543. memcpy(ptr2, (uchar*)&value2, 4);
  544. jumpsize = 4;
  545. }
  546. else if (value2 > 0xFF) {
  547. memcpy(ptr2, (uchar*)&value2, 2);
  548. jumpsize = 2;
  549. }
  550. else {
  551. memcpy(ptr2, (uchar*)&value2, 1);
  552. jumpsize = 1;
  553. }
  554. ptr2 += jumpsize;
  555. offset4 -= jumpsize;
  556. }
  557. }
  558. if (offset2 > 0 && offset2 >= offset) {
  559. uchar* ptr2 = (uchar*)part2;
  560. ptr2 += offset;
  561. while (offset2 >= offset) {
  562. int8 jumpsize = 1;
  563. if (value > 0xFFFF) {
  564. memcpy(ptr2, (uchar*)&value, 4);
  565. jumpsize = 4;
  566. }
  567. else if (value > 0xFF) {
  568. memcpy(ptr2, (uchar*)&value, 2);
  569. jumpsize = 2;
  570. }
  571. else
  572. memcpy(ptr2, (uchar*)&value, 1);
  573. ptr2 += jumpsize;
  574. offset2 -= jumpsize;
  575. }
  576. }
  577. else {
  578. uchar* ptr2 = (uchar*)part2;
  579. ptr2 += offset;
  580. if (value > 0xFFFF)
  581. memcpy(ptr2, (uchar*)&value, 4);
  582. else if (value > 0xFF)
  583. memcpy(ptr2, (uchar*)&value, 2);
  584. else
  585. memcpy(ptr2, (uchar*)&value, 1);
  586. }
  587. cout << "setting offset: " << offset << " to: " << value << endl;
  588. }
  589. //if (offset > 0)
  590. // DumpPacket(part2, part2_size);
  591. uchar tmp[4000];
  592. bool reverse = (version > 283);
  593. part2_size = Pack(tmp, part2, part2_size, 4000, version, reverse);
  594. int32 total_size = part1->length() + part2_size + 3;
  595. if (part3)
  596. total_size += part3->length();
  597. int32 final_packet_size = total_size + 1;
  598. if (version > 283)
  599. final_packet_size += 3;
  600. else {
  601. if (final_packet_size >= 255) {
  602. final_packet_size += 2;
  603. }
  604. }
  605. uchar* final_packet = new uchar[final_packet_size];
  606. ptr = final_packet;
  607. if (version <= 283) {
  608. if ((final_packet_size - total_size) > 1) {
  609. memcpy(ptr, &oversized_packet, sizeof(oversized_packet));
  610. ptr += sizeof(oversized_packet);
  611. memcpy(ptr, &total_size, 2);
  612. ptr += 2;
  613. }
  614. else {
  615. memcpy(ptr, &total_size, 1);
  616. ptr += 1;
  617. }
  618. }
  619. else {
  620. memcpy(ptr, &total_size, sizeof(total_size));
  621. ptr += sizeof(total_size);
  622. }
  623. memcpy(ptr, &oversized_packet, sizeof(oversized_packet));
  624. ptr += sizeof(oversized_packet);
  625. int16 opcode = 0;
  626. if (EQOpcodeManager.count(GetOpcodeVersion(version)) != 0) {
  627. if(IsWidget())
  628. opcode = EQOpcodeManager[GetOpcodeVersion(version)]->EmuToEQ(OP_EqCreateWidgetCmd);
  629. else if(IsSign())
  630. opcode = EQOpcodeManager[GetOpcodeVersion(version)]->EmuToEQ(OP_EqCreateSignWidgetCmd);
  631. else
  632. opcode = EQOpcodeManager[GetOpcodeVersion(version)]->EmuToEQ(OP_EqCreateGhostCmd);
  633. }
  634. memcpy(ptr, &opcode, sizeof(opcode));
  635. ptr += sizeof(opcode);
  636. memcpy(ptr, part1->c_str(), part1->length());
  637. ptr += part1->length();
  638. memcpy(ptr, tmp, part2_size);
  639. ptr += part2_size;
  640. if (part3)
  641. memcpy(ptr, part3->c_str(), part3->length());
  642. delete[] part2;
  643. //printf("SpawnPacket %s (id: %u, index: %u) to %s: p1: %i, p2: %i, p3: %i, ts: %i. poslength: %u, infolength: %u, vislength: %u\n", GetName(), GetID(), index, player->GetName(), part1->length(), part2_size, (part3 != nullptr) ? part3->length() : -1, total_size, poslength, infolength, vislength);
  644. EQ2Packet* ret = new EQ2Packet(OP_ClientCmdMsg, final_packet, final_packet_size);
  645. delete[] final_packet;
  646. m_Update.releasewritelock(__FUNCTION__, __LINE__);
  647. return ret;
  648. }
  649. uchar* Spawn::spawn_info_changes(Player* player, int16 version, int16* info_packet_size){
  650. int16 index = player->GetIndexForSpawn(this);
  651. PacketStruct* packet = player->GetSpawnInfoStruct();
  652. player->info_mutex.writelock(__FUNCTION__, __LINE__);
  653. packet->ResetData();
  654. InitializeInfoPacketData(player, packet);
  655. string* data = packet->serializeString();
  656. int32 size = data->length();
  657. uchar* xor_info_packet = player->GetTempInfoPacketForXOR();
  658. if (!xor_info_packet || size != player->GetTempInfoXorSize())
  659. {
  660. LogWrite(ZONE__DEBUG, 0, "Zone", "InstantiateInfoPacket: %i, %i", size, player->GetTempInfoXorSize());
  661. safe_delete(xor_info_packet);
  662. xor_info_packet = player->SetTempInfoPacketForXOR(size);
  663. }
  664. uchar* orig_packet = player->GetSpawnInfoPacketForXOR(id);
  665. if(orig_packet){
  666. memcpy(xor_info_packet, (uchar*)data->c_str(), size);
  667. Encode(xor_info_packet, orig_packet, size);
  668. }
  669. bool changed = false;
  670. for (int i = 0; i < size; ++i) {
  671. if (xor_info_packet[i]) {
  672. changed = true;
  673. break;
  674. }
  675. }
  676. if (!changed) {
  677. player->info_mutex.releasewritelock(__FUNCTION__, __LINE__);
  678. return nullptr;
  679. }
  680. uchar* tmp = new uchar[size + 1000];
  681. size = Pack(tmp, xor_info_packet, size, size+1000, version);
  682. player->info_mutex.releasewritelock(__FUNCTION__, __LINE__);
  683. int32 orig_size = size;
  684. size-=sizeof(int32);
  685. size+=CheckOverLoadSize(index);
  686. *info_packet_size = size + CheckOverLoadSize(size);
  687. uchar* tmp2 = new uchar[*info_packet_size];
  688. uchar* ptr = tmp2;
  689. ptr += DoOverLoad(size, ptr);
  690. ptr += DoOverLoad(index, ptr);
  691. memcpy(ptr, tmp+sizeof(int32), orig_size - sizeof(int32));
  692. delete[] tmp;
  693. return tmp2;
  694. }
  695. uchar* Spawn::spawn_vis_changes(Player* player, int16 version, int16* vis_packet_size){
  696. PacketStruct* vis_struct = player->GetSpawnVisStruct();
  697. int16 index = player->GetIndexForSpawn(this);
  698. player->vis_mutex.writelock(__FUNCTION__, __LINE__);
  699. uchar* orig_packet = player->GetSpawnVisPacketForXOR(id);
  700. vis_struct->ResetData();
  701. InitializeVisPacketData(player, vis_struct);
  702. string* data = vis_struct->serializeString();
  703. int32 size = data->length();
  704. uchar* xor_vis_packet = player->GetTempVisPacketForXOR();
  705. if (!xor_vis_packet || size != player->GetTempVisXorSize())
  706. {
  707. LogWrite(ZONE__DEBUG, 0, "Zone", "InstantiateVisPacket: %i, %i", size, player->GetTempVisXorSize());
  708. safe_delete(xor_vis_packet);
  709. xor_vis_packet = player->SetTempVisPacketForXOR(size);
  710. }
  711. if(orig_packet){
  712. memcpy(xor_vis_packet, (uchar*)data->c_str(), size);
  713. Encode(xor_vis_packet, orig_packet, size);
  714. }
  715. bool changed = false;
  716. for (int i = 0; i < size; ++i) {
  717. if (xor_vis_packet[i]) {
  718. changed = true;
  719. break;
  720. }
  721. }
  722. if (!changed) {
  723. player->vis_mutex.releasewritelock(__FUNCTION__, __LINE__);
  724. return nullptr;
  725. }
  726. uchar* tmp = new uchar[size + 1000];
  727. size = Pack(tmp, xor_vis_packet, size, size+1000, version);
  728. player->vis_mutex.releasewritelock(__FUNCTION__, __LINE__);
  729. int32 orig_size = size;
  730. size-=sizeof(int32);
  731. size+=CheckOverLoadSize(index);
  732. *vis_packet_size = size + CheckOverLoadSize(size);
  733. uchar* tmp2 = new uchar[*vis_packet_size];
  734. uchar* ptr = tmp2;
  735. ptr += DoOverLoad(size, ptr);
  736. ptr += DoOverLoad(index, ptr);
  737. memcpy(ptr, tmp+sizeof(int32), orig_size - sizeof(int32));
  738. delete[] tmp;
  739. return tmp2;
  740. }
  741. uchar* Spawn::spawn_pos_changes(Player* player, int16 version, int16* pos_packet_size) {
  742. int16 index = player->GetIndexForSpawn(this);
  743. PacketStruct* packet = player->GetSpawnPosStruct();
  744. player->pos_mutex.writelock(__FUNCTION__, __LINE__);
  745. uchar* orig_packet = player->GetSpawnPosPacketForXOR(id);
  746. packet->ResetData();
  747. InitializePosPacketData(player, packet, true);
  748. string* data = packet->serializeString();
  749. int32 size = data->length();
  750. uchar* xor_pos_packet = player->GetTempPosPacketForXOR();
  751. if (!xor_pos_packet || size != player->GetTempPosXorSize())
  752. {
  753. LogWrite(ZONE__DEBUG, 0, "Zone", "InstantiatePosPacket: %i, %i", size, player->GetTempPosXorSize());
  754. safe_delete(xor_pos_packet);
  755. xor_pos_packet = player->SetTempPosPacketForXOR(size);
  756. }
  757. if(orig_packet){
  758. memcpy(xor_pos_packet, (uchar*)data->c_str(), size);
  759. Encode(xor_pos_packet, orig_packet, size);
  760. }
  761. bool changed = false;
  762. for (int i = 0; i < size; ++i) {
  763. if (xor_pos_packet[i]) {
  764. changed = true;
  765. break;
  766. }
  767. }
  768. if (!changed) {
  769. player->pos_mutex.releasewritelock(__FUNCTION__, __LINE__);
  770. return nullptr;
  771. }
  772. int16 newSize = size + 1000;
  773. uchar* tmp = new uchar[newSize];
  774. size = Pack(tmp, xor_pos_packet, size, newSize, version);
  775. player->pos_mutex.releasewritelock(__FUNCTION__, __LINE__);
  776. int32 orig_size = size;
  777. // Needed for CoE+ clients
  778. if (version >= 1188)
  779. size += 1;
  780. if(IsPlayer() && version > 561)
  781. size += 4;
  782. size-=sizeof(int32);
  783. size+=CheckOverLoadSize(index);
  784. *pos_packet_size = size + CheckOverLoadSize(size);
  785. uchar* tmp2 = new uchar[*pos_packet_size];
  786. uchar* ptr = tmp2;
  787. ptr += DoOverLoad(size, ptr);
  788. ptr += DoOverLoad(index, ptr);
  789. // extra byte in coe+ clients, 0 for NPC's 1 for Players
  790. int8 x = 0;
  791. if (IsPlayer() && version > 561) {
  792. if (version >= 1188) {
  793. // set x to 1 and add it to the packet
  794. x = 1;
  795. memcpy(ptr, &x, sizeof(int8));
  796. ptr += sizeof(int8);
  797. }
  798. int32 now = Timer::GetCurrentTime2();
  799. memcpy(ptr, &now, sizeof(int32));
  800. ptr += sizeof(int32);
  801. }
  802. else if (version >= 1188) {
  803. // add x to packet
  804. memcpy(ptr, &x, sizeof(int8));
  805. ptr += sizeof(int8);
  806. }
  807. memcpy(ptr, tmp+sizeof(int32), orig_size - sizeof(int32));
  808. delete[] tmp;
  809. return tmp2;
  810. }
  811. EQ2Packet* Spawn::player_position_update_packet(Player* player, int16 version){
  812. if(!player || player->IsPlayer() == false){
  813. LogWrite(SPAWN__ERROR, 0, "Spawn", "Error: Called player_position_update_packet without player!");
  814. return 0;
  815. }
  816. else if(IsPlayer() == false){
  817. LogWrite(SPAWN__ERROR, 0, "Spawn", "Error: Called player_position_update_packet from spawn!");
  818. return 0;
  819. }
  820. static const int8 info_size = 1;
  821. static const int8 vis_size = 1;
  822. int16 pos_packet_size = 0;
  823. m_Update.writelock(__FUNCTION__, __LINE__);
  824. uchar* pos_changes = spawn_pos_changes(player, version, &pos_packet_size);
  825. if (pos_changes == NULL )
  826. {
  827. m_Update.releasewritelock(__FUNCTION__, __LINE__);
  828. return NULL;
  829. }
  830. int32 size = info_size + pos_packet_size + vis_size + 8;
  831. if (version >= 284)
  832. size += 3;
  833. else if (version <= 283 && size >= 255) {//1 byte to 3 for overloaded val
  834. size += 2;
  835. }
  836. static const int8 oversized = 255;
  837. int16 opcode_val = 0;
  838. if (EQOpcodeManager.count(GetOpcodeVersion(version)) != 0) {
  839. opcode_val = EQOpcodeManager[GetOpcodeVersion(version)]->EmuToEQ(OP_EqUpdateGhostCmd);
  840. }
  841. uchar* tmp = new uchar[size];
  842. memset(tmp, 0, size);
  843. uchar* ptr = tmp;
  844. if (version >= 284) {
  845. size -= 4;
  846. memcpy(ptr, &size, sizeof(int32));
  847. size += 4;
  848. ptr += sizeof(int32);
  849. }
  850. else {
  851. if (size >= 255) {
  852. memcpy(ptr, &oversized, sizeof(int8));
  853. ptr += sizeof(int8);
  854. size -= 3;
  855. memcpy(ptr, &size, sizeof(int16));
  856. size += 3;
  857. ptr += 3;
  858. }
  859. else {
  860. size -= 1;
  861. memcpy(ptr, &size, sizeof(int8));
  862. ptr += sizeof(int8);
  863. size += 1;
  864. ptr += 1;
  865. }
  866. }
  867. memcpy(ptr, &oversized, sizeof(int8));
  868. ptr += sizeof(int8);
  869. memcpy(ptr, &opcode_val, sizeof(int16));
  870. ptr += sizeof(int16);
  871. if (version <= 283) {
  872. int32 timestamp = Timer::GetCurrentTime2();
  873. memcpy(ptr, &timestamp, sizeof(int32));
  874. }
  875. ptr += sizeof(int32);
  876. ptr += info_size;
  877. memcpy(ptr, pos_changes, pos_packet_size);
  878. delete[] pos_changes;
  879. m_Update.releasewritelock(__FUNCTION__, __LINE__);
  880. EQ2Packet* ret_packet = new EQ2Packet(OP_ClientCmdMsg, tmp, size);
  881. // DumpPacket(ret_packet);
  882. delete[] tmp;
  883. return ret_packet;
  884. }
  885. EQ2Packet* Spawn::spawn_update_packet(Player* player, int16 version, bool override_changes, bool override_vis_changes){
  886. if(!player || player->IsPlayer() == false){
  887. LogWrite(SPAWN__ERROR, 0, "Spawn", "Error: Called spawn_update_packet without player!");
  888. return 0;
  889. }
  890. else if((IsPlayer() && info_changed == false && vis_changed == false) || (info_changed == false && vis_changed == false && position_changed == false)){
  891. if(!override_changes && !override_vis_changes)
  892. return 0;
  893. }
  894. uchar* info_changes = 0;
  895. uchar* pos_changes = 0;
  896. uchar* vis_changes = 0;
  897. static const int8 oversized = 255;
  898. int16 opcode_val = 0;
  899. if (EQOpcodeManager.count(GetOpcodeVersion(version)) != 0) {
  900. opcode_val = EQOpcodeManager[GetOpcodeVersion(version)]->EmuToEQ(OP_EqUpdateGhostCmd);
  901. }
  902. //We need to lock these variables up to make this thread safe
  903. m_Update.writelock(__FUNCTION__, __LINE__);
  904. //These variables are set in the spawn_info_changes, pos and vis changes functions
  905. int16 info_packet_size = 1;
  906. int16 pos_packet_size = 1;
  907. int16 vis_packet_size = 1;
  908. if (info_changed || override_changes)
  909. info_changes = spawn_info_changes(player, version, &info_packet_size);
  910. if ((position_changed || override_changes) && IsPlayer() == false)
  911. pos_changes = spawn_pos_changes(player, version, &pos_packet_size);
  912. if (vis_changed || override_changes || override_vis_changes)
  913. vis_changes = spawn_vis_changes(player, version, &vis_packet_size);
  914. int32 size = info_packet_size + pos_packet_size + vis_packet_size + 8;
  915. if (version >= 284)
  916. size += 3;
  917. else if (version <= 283 && size >= 255) {//1 byte to 3 for overloaded val
  918. size += 2;
  919. }
  920. uchar* tmp = new uchar[size];
  921. memset(tmp, 0, size);
  922. uchar* ptr = tmp;
  923. if (version >= 284) {
  924. size -= 4;
  925. memcpy(ptr, &size, sizeof(int32));
  926. size += 4;
  927. ptr += sizeof(int32);
  928. }
  929. else {
  930. if (size >= 255) {
  931. memcpy(ptr, &oversized, sizeof(int8));
  932. ptr += sizeof(int8);
  933. size -= 3;
  934. memcpy(ptr, &size, sizeof(int16));
  935. size += 3;
  936. ptr += 3;
  937. }
  938. else {
  939. size -= 1;
  940. memcpy(ptr, &size, sizeof(int8));
  941. ptr += sizeof(int8);
  942. size += 1;
  943. }
  944. }
  945. memcpy(ptr, &oversized, sizeof(int8));
  946. ptr += sizeof(int8);
  947. memcpy(ptr, &opcode_val, sizeof(int16));
  948. ptr += sizeof(int16);
  949. if (IsPlayer() == false || version <= 546) { //this isnt sent for player updates, it is sent on position update
  950. //int32 time = Timer::GetCurrentTime2();
  951. packet_num = Timer::GetCurrentTime2();
  952. memcpy(ptr, &packet_num, sizeof(int32));
  953. }
  954. ptr += sizeof(int32);
  955. if(info_changes)
  956. memcpy(ptr, info_changes, info_packet_size);
  957. ptr += info_packet_size;
  958. if(pos_changes)
  959. memcpy(ptr, pos_changes, pos_packet_size);
  960. ptr += pos_packet_size;
  961. if(vis_changes)
  962. memcpy(ptr, vis_changes, vis_packet_size);
  963. EQ2Packet* ret_packet = 0;
  964. if(info_packet_size + pos_packet_size + vis_packet_size > 0)
  965. ret_packet = new EQ2Packet(OP_ClientCmdMsg, tmp, size);
  966. delete[] tmp;
  967. safe_delete_array(info_changes);
  968. safe_delete_array(vis_changes);
  969. safe_delete_array(pos_changes);
  970. m_Update.releasewritelock(__FUNCTION__, __LINE__);
  971. return ret_packet;
  972. }
  973. uchar* Spawn::spawn_info_changes_ex(Player* player, int16 version, int16* info_packet_size) {
  974. int16 index = player->GetIndexForSpawn(this);
  975. PacketStruct* packet = player->GetSpawnInfoStruct();
  976. player->info_mutex.writelock(__FUNCTION__, __LINE__);
  977. packet->ResetData();
  978. InitializeInfoPacketData(player, packet);
  979. string* data = packet->serializeString();
  980. int32 size = data->length();
  981. uchar* xor_info_packet = player->GetTempInfoPacketForXOR();
  982. if (!xor_info_packet || size != player->GetTempInfoXorSize()) {
  983. LogWrite(ZONE__DEBUG, 0, "Zone", "InstantiateInfoExPacket: %i, %i", size, player->GetTempInfoXorSize());
  984. safe_delete(xor_info_packet);
  985. xor_info_packet = player->SetTempInfoPacketForXOR(size);
  986. }
  987. uchar* orig_packet = player->GetSpawnInfoPacketForXOR(id);
  988. if (orig_packet) {
  989. //if (!IsPlayer() && this->EngagedInCombat())
  990. //packet->PrintPacket();
  991. memcpy(xor_info_packet, (uchar*)data->c_str(), size);
  992. Encode(xor_info_packet, orig_packet, size);
  993. }
  994. bool changed = false;
  995. for (int i = 0; i < size; ++i) {
  996. if (xor_info_packet[i]) {
  997. changed = true;
  998. break;
  999. }
  1000. }
  1001. if (!changed) {
  1002. player->info_mutex.releasewritelock(__FUNCTION__, __LINE__);
  1003. return nullptr;
  1004. }
  1005. uchar* tmp = new uchar[size + 1000];
  1006. size = Pack(tmp, xor_info_packet, size, size+1000, version);
  1007. player->info_mutex.releasewritelock(__FUNCTION__, __LINE__);
  1008. int32 orig_size = size;
  1009. size -= sizeof(int32);
  1010. size += CheckOverLoadSize(index);
  1011. *info_packet_size = size;
  1012. uchar* tmp2 = new uchar[size];
  1013. uchar* ptr = tmp2;
  1014. ptr += DoOverLoad(index, ptr);
  1015. memcpy(ptr, tmp + sizeof(int32), orig_size - sizeof(int32));
  1016. delete[] tmp;
  1017. return move(tmp2);
  1018. }
  1019. uchar* Spawn::spawn_vis_changes_ex(Player* player, int16 version, int16* vis_packet_size) {
  1020. PacketStruct* vis_struct = player->GetSpawnVisStruct();
  1021. int16 index = player->GetIndexForSpawn(this);
  1022. player->vis_mutex.writelock(__FUNCTION__, __LINE__);
  1023. uchar* orig_packet = player->GetSpawnVisPacketForXOR(id);
  1024. vis_struct->ResetData();
  1025. InitializeVisPacketData(player, vis_struct);
  1026. string* data = vis_struct->serializeString();
  1027. int32 size = data->length();
  1028. uchar* xor_vis_packet = player->GetTempVisPacketForXOR();
  1029. if (!xor_vis_packet || size != player->GetTempVisXorSize()) {
  1030. LogWrite(ZONE__DEBUG, 0, "Zone", "InstantiateVisExPacket: %i, %i", size, player->GetTempVisXorSize());
  1031. safe_delete(xor_vis_packet);
  1032. xor_vis_packet = player->SetTempVisPacketForXOR(size);
  1033. }
  1034. if (orig_packet) {
  1035. //if (!IsPlayer() && this->EngagedInCombat())
  1036. // vis_struct->PrintPacket();
  1037. memcpy(xor_vis_packet, (uchar*)data->c_str(), size);
  1038. Encode(xor_vis_packet, orig_packet, size);
  1039. }
  1040. bool changed = false;
  1041. for (int i = 0; i < size; ++i) {
  1042. if (xor_vis_packet[i]) {
  1043. changed = true;
  1044. break;
  1045. }
  1046. }
  1047. if (!changed) {
  1048. player->vis_mutex.releasewritelock(__FUNCTION__, __LINE__);
  1049. return nullptr;
  1050. }
  1051. uchar* tmp = new uchar[size + 1000];
  1052. size = Pack(tmp, xor_vis_packet, size, size+1000, version);
  1053. player->vis_mutex.releasewritelock(__FUNCTION__, __LINE__);
  1054. int32 orig_size = size;
  1055. size -= sizeof(int32);
  1056. size += CheckOverLoadSize(index);
  1057. *vis_packet_size = size;
  1058. uchar* tmp2 = new uchar[size];
  1059. uchar* ptr = tmp2;
  1060. ptr += DoOverLoad(index, ptr);
  1061. memcpy(ptr, tmp + sizeof(int32), orig_size - sizeof(int32));
  1062. delete[] tmp;
  1063. return move(tmp2);
  1064. }
  1065. uchar* Spawn::spawn_pos_changes_ex(Player* player, int16 version, int16* pos_packet_size) {
  1066. int16 index = player->GetIndexForSpawn(this);
  1067. PacketStruct* packet = player->GetSpawnPosStruct();
  1068. player->pos_mutex.writelock(__FUNCTION__, __LINE__);
  1069. uchar* orig_packet = player->GetSpawnPosPacketForXOR(id);
  1070. packet->ResetData();
  1071. InitializePosPacketData(player, packet);
  1072. string* data = packet->serializeString();
  1073. int32 size = data->length();
  1074. uchar* xor_pos_packet = player->GetTempPosPacketForXOR();
  1075. if (!xor_pos_packet || size != player->GetTempPosXorSize()) {
  1076. LogWrite(ZONE__DEBUG, 0, "Zone", "InstantiatePosExPacket: %i, %i", size, player->GetTempPosXorSize());
  1077. safe_delete(xor_pos_packet);
  1078. xor_pos_packet = player->SetTempPosPacketForXOR(size);
  1079. }
  1080. if (orig_packet) {
  1081. //if (!IsPlayer() && this->EngagedInCombat())
  1082. // packet->PrintPacket();
  1083. memcpy(xor_pos_packet, (uchar*)data->c_str(), size);
  1084. Encode(xor_pos_packet, orig_packet, size);
  1085. }
  1086. bool changed = false;
  1087. for (int i = 0; i < size; ++i) {
  1088. if (xor_pos_packet[i]) {
  1089. changed = true;
  1090. break;
  1091. }
  1092. }
  1093. if (!changed) {
  1094. player->pos_mutex.releasewritelock(__FUNCTION__, __LINE__);
  1095. return nullptr;
  1096. }
  1097. int16 newSize = size + 1000;
  1098. uchar* tmp = new uchar[newSize];
  1099. size = Pack(tmp, xor_pos_packet, size, newSize, version);
  1100. player->pos_mutex.releasewritelock(__FUNCTION__, __LINE__);
  1101. int32 orig_size = size;
  1102. if (version >= 1188) {
  1103. size += 1;
  1104. }
  1105. if (IsPlayer() && version > 561) {
  1106. size += 4;
  1107. }
  1108. size -= sizeof(int32);
  1109. size += CheckOverLoadSize(index);
  1110. *pos_packet_size = size;
  1111. uchar* tmp2 = new uchar[size];
  1112. uchar* ptr = tmp2;
  1113. ptr += DoOverLoad(index, ptr);
  1114. // extra byte in coe+ clients, 0 for NPC's 1 for Players
  1115. int8 x = 0;
  1116. if (version > 561) {
  1117. if (IsPlayer()) {
  1118. if (version >= 1188) {
  1119. x = 1;
  1120. memcpy(ptr, &x, sizeof(int8));
  1121. ptr += sizeof(int8);
  1122. }
  1123. int32 now = Timer::GetCurrentTime2();
  1124. memcpy(ptr, &now, sizeof(int32));
  1125. ptr += sizeof(int32);
  1126. }
  1127. else if (version >= 1188) {
  1128. memcpy(ptr, &x, sizeof(int8));
  1129. ptr += sizeof(int8);
  1130. }
  1131. }
  1132. memcpy(ptr, tmp + sizeof(int32), orig_size - sizeof(int32));
  1133. delete[] tmp;
  1134. return move(tmp2);
  1135. }
  1136. EQ2Packet* Spawn::serialize(Player* player, int16 version){
  1137. return 0;
  1138. }
  1139. Spawn* Spawn::GetTarget(){
  1140. Spawn* ret = 0;
  1141. // only attempt to get a spawn if we had a target stored
  1142. if (target != 0)
  1143. {
  1144. ret = GetZone()->GetSpawnByID(target);
  1145. if (!ret)
  1146. target = 0;
  1147. }
  1148. return ret;
  1149. }
  1150. void Spawn::SetTarget(Spawn* spawn){
  1151. SetInfo(&target, spawn ? spawn->GetID() : 0);
  1152. }
  1153. Spawn* Spawn::GetLastAttacker() {
  1154. Spawn* ret = 0;
  1155. ret = GetZone()->GetSpawnByID(last_attacker);
  1156. if (!ret)
  1157. last_attacker = 0;
  1158. return ret;
  1159. }
  1160. void Spawn::SetLastAttacker(Spawn* spawn){
  1161. last_attacker = spawn->GetID();
  1162. }
  1163. void Spawn::SetInvulnerable(bool val){
  1164. invulnerable = val;
  1165. }
  1166. bool Spawn::GetInvulnerable(){
  1167. return invulnerable;
  1168. }
  1169. bool Spawn::TakeDamage(int32 damage){
  1170. if(invulnerable)
  1171. return false;
  1172. if (IsEntity()) {
  1173. if (((Entity*)this)->IsMezzed())
  1174. ((Entity*)this)->RemoveAllMezSpells();
  1175. if (damage == 0)
  1176. return true;
  1177. }
  1178. int32 hp = GetHP();
  1179. if(damage >= hp) {
  1180. SetHP(0);
  1181. if (IsPlayer()) {
  1182. ((Player*)this)->InCombat(false);
  1183. ((Player*)this)->SetRangeAttack(false);
  1184. GetZone()->TriggerCharSheetTimer(); // force char sheet updates now
  1185. }
  1186. }
  1187. else {
  1188. SetHP(hp - damage);
  1189. // if player flag the char sheet as changed so the ui updates properly
  1190. if (IsPlayer())
  1191. ((Player*)this)->SetCharSheetChanged(true);
  1192. }
  1193. return true;
  1194. }
  1195. ZoneServer* Spawn::GetZone(){
  1196. return zone;
  1197. }
  1198. void Spawn::SetZone(ZoneServer* in_zone, int32 version){
  1199. zone = in_zone;
  1200. if(in_zone)
  1201. {
  1202. region_map = world.GetRegionMap(std::string(in_zone->GetZoneFile()), version);
  1203. current_map = world.GetMap(std::string(in_zone->GetZoneFile()), version);
  1204. }
  1205. else
  1206. {
  1207. region_map = nullptr;
  1208. current_map = nullptr;
  1209. }
  1210. }
  1211. /*** HIT POINT ***/
  1212. void Spawn::SetHP(sint32 new_val, bool setUpdateFlags){
  1213. if(new_val == 0){
  1214. ClearRunningLocations();
  1215. CalculateRunningLocation(true);
  1216. if(IsEntity()) {
  1217. is_alive = false;
  1218. }
  1219. }
  1220. if(IsNPC() && new_val > 0 && !is_alive) {
  1221. is_alive = true;
  1222. }
  1223. else if(IsPlayer() && new_val > 0 && !is_alive) {
  1224. LogWrite(SPAWN__ERROR, 0, "Spawn", "Cannot change player HP > 0 while dead (%s)! Player must revive.", GetName());
  1225. return;
  1226. }
  1227. if(new_val > basic_info.max_hp)
  1228. SetInfo(&basic_info.max_hp, new_val, setUpdateFlags);
  1229. SetInfo(&basic_info.cur_hp, new_val, setUpdateFlags);
  1230. if(/*IsPlayer() &&*/ GetZone() && basic_info.cur_hp > 0 && basic_info.cur_hp < basic_info.max_hp)
  1231. GetZone()->AddDamagedSpawn(this);
  1232. SendGroupUpdate();
  1233. if ( IsPlayer() && new_val == 0 ) // fixes on death not showing hp update for players
  1234. ((Player*)this)->SetCharSheetChanged(true);
  1235. if (IsNPC() && ((NPC*)this)->IsPet() && ((NPC*)this)->GetOwner() && ((NPC*)this)->GetOwner()->IsPlayer()) {
  1236. Player* player = (Player*)((NPC*)this)->GetOwner();
  1237. if (player->GetPet() && player->GetCharmedPet()) {
  1238. if (this == player->GetPet()) {
  1239. player->GetInfoStruct()->set_pet_health_pct((float)basic_info.cur_hp / (float)basic_info.max_hp);
  1240. player->SetCharSheetChanged(true);
  1241. }
  1242. }
  1243. else {
  1244. player->GetInfoStruct()->set_pet_health_pct((float)basic_info.cur_hp / (float)basic_info.max_hp);
  1245. player->SetCharSheetChanged(true);
  1246. }
  1247. }
  1248. }
  1249. void Spawn::SetTotalHP(sint32 new_val){
  1250. if(basic_info.hp_base == 0) {
  1251. SetTotalHPBase(new_val);
  1252. SetTotalHPBaseInstance(new_val);
  1253. }
  1254. SetInfo(&basic_info.max_hp, new_val);
  1255. if(GetZone() && basic_info.cur_hp > 0 && basic_info.cur_hp < basic_info.max_hp)
  1256. GetZone()->AddDamagedSpawn(this);
  1257. SendGroupUpdate();
  1258. if (IsNPC() && ((NPC*)this)->IsPet() && ((NPC*)this)->GetOwner() != nullptr && ((NPC*)this)->GetOwner()->IsPlayer()) {
  1259. Player* player = (Player*)((NPC*)this)->GetOwner();
  1260. if (basic_info.max_hp && player->GetPet() && player->GetCharmedPet()) {
  1261. if (this == player->GetPet()) {
  1262. player->GetInfoStruct()->set_pet_health_pct((float)basic_info.cur_hp / (float)basic_info.max_hp);
  1263. player->SetCharSheetChanged(true);
  1264. }
  1265. }
  1266. else if(basic_info.max_hp) {
  1267. player->GetInfoStruct()->set_pet_health_pct((float)basic_info.cur_hp / (float)basic_info.max_hp);
  1268. player->SetCharSheetChanged(true);
  1269. }
  1270. }
  1271. }
  1272. void Spawn::SetTotalHPBase(sint32 new_val)
  1273. {
  1274. SetInfo(&basic_info.hp_base, new_val);
  1275. if(GetZone() && basic_info.cur_hp > 0 && basic_info.cur_hp < basic_info.max_hp)
  1276. GetZone()->AddDamagedSpawn(this);
  1277. SendGroupUpdate();
  1278. }
  1279. void Spawn::SetTotalHPBaseInstance(sint32 new_val)
  1280. {
  1281. SetInfo(&basic_info.hp_base_instance, new_val);
  1282. }
  1283. sint32 Spawn::GetHP()
  1284. {
  1285. return basic_info.cur_hp;
  1286. }
  1287. sint32 Spawn::GetTotalHP()
  1288. {
  1289. return basic_info.max_hp;
  1290. }
  1291. sint32 Spawn::GetTotalHPBase()
  1292. {
  1293. return basic_info.hp_base;
  1294. }
  1295. sint32 Spawn::GetTotalHPBaseInstance()
  1296. {
  1297. return basic_info.hp_base_instance;
  1298. }
  1299. sint32 Spawn::GetTotalPowerBaseInstance()
  1300. {
  1301. return basic_info.power_base_instance;
  1302. }
  1303. /*** POWER ***/
  1304. void Spawn::SetPower(sint32 power, bool setUpdateFlags){
  1305. if(power > basic_info.max_power)
  1306. SetInfo(&basic_info.max_power, power, setUpdateFlags);
  1307. SetInfo(&basic_info.cur_power, power, setUpdateFlags);
  1308. if(/*IsPlayer() &&*/ GetZone() && basic_info.cur_power < basic_info.max_power)
  1309. GetZone()->AddDamagedSpawn(this);
  1310. SendGroupUpdate();
  1311. if (IsNPC() && ((NPC*)this)->IsPet() && ((NPC*)this)->GetOwner() != nullptr && ((NPC*)this)->GetOwner()->IsPlayer()) {
  1312. Player* player = (Player*)((NPC*)this)->GetOwner();
  1313. if (player->GetPet() && player->GetCharmedPet()) {
  1314. if (this == player->GetPet()) {
  1315. player->GetInfoStruct()->set_pet_power_pct((float)basic_info.cur_power / (float)basic_info.max_power);
  1316. player->SetCharSheetChanged(true);
  1317. }
  1318. }
  1319. else {
  1320. player->GetInfoStruct()->set_pet_power_pct((float)basic_info.cur_power / (float)basic_info.max_power);
  1321. player->SetCharSheetChanged(true);
  1322. }
  1323. }
  1324. }
  1325. void Spawn::SetTotalPower(sint32 new_val)
  1326. {
  1327. if(basic_info.power_base == 0) {
  1328. SetTotalPowerBase(new_val);
  1329. SetTotalPowerBaseInstance(new_val);
  1330. }
  1331. SetInfo(&basic_info.max_power, new_val);
  1332. if(GetZone() && basic_info.cur_power < basic_info.max_power)
  1333. GetZone()->AddDamagedSpawn(this);
  1334. SendGroupUpdate();
  1335. if (IsNPC() && ((NPC*)this)->IsPet() && ((NPC*)this)->GetOwner() != nullptr && ((NPC*)this)->GetOwner()->IsPlayer()) {
  1336. Player* player = (Player*)((NPC*)this)->GetOwner();
  1337. if (player->GetPet() && player->GetCharmedPet()) {
  1338. if (this == player->GetPet()) {
  1339. player->GetInfoStruct()->set_pet_power_pct((float)basic_info.cur_power / (float)basic_info.max_power);
  1340. player->SetCharSheetChanged(true);
  1341. }
  1342. }
  1343. else {
  1344. player->GetInfoStruct()->set_pet_power_pct((float)basic_info.cur_power / (float)basic_info.max_power);
  1345. player->SetCharSheetChanged(true);
  1346. }
  1347. }
  1348. }
  1349. void Spawn::SetTotalPowerBase(sint32 new_val)
  1350. {
  1351. SetInfo(&basic_info.power_base, new_val);
  1352. if(GetZone() && basic_info.cur_power < basic_info.max_power)
  1353. GetZone()->AddDamagedSpawn(this);
  1354. SendGroupUpdate();
  1355. }
  1356. void Spawn::SetTotalPowerBaseInstance(sint32 new_val)
  1357. {
  1358. SetInfo(&basic_info.power_base_instance, new_val);
  1359. }
  1360. sint32 Spawn::GetPower()
  1361. {
  1362. return basic_info.cur_power;
  1363. }
  1364. sint32 Spawn::GetTotalPower(){
  1365. return basic_info.max_power;
  1366. }
  1367. sint32 Spawn::GetTotalPowerBase()
  1368. {
  1369. return basic_info.power_base;
  1370. }
  1371. /*** SAVAGERY ***/
  1372. void Spawn::SetSavagery(sint32 savagery, bool setUpdateFlags)
  1373. {
  1374. /* JA: extremely limited functionality until we better understand Savagery */
  1375. if(savagery > basic_info.max_savagery)
  1376. SetInfo(&basic_info.max_savagery, savagery, setUpdateFlags);
  1377. SetInfo(&basic_info.cur_savagery, savagery, setUpdateFlags);
  1378. }
  1379. void Spawn::SetTotalSavagery(sint32 new_val)
  1380. {
  1381. /* JA: extremely limited functionality until we better understand Savagery */
  1382. if(basic_info.savagery_base == 0)
  1383. SetTotalSavageryBase(new_val);
  1384. SetInfo(&basic_info.max_savagery, new_val);
  1385. }
  1386. void Spawn::SetTotalSavageryBase(sint32 new_val){
  1387. SetInfo(&basic_info.savagery_base, new_val);
  1388. SendGroupUpdate();
  1389. }
  1390. sint32 Spawn::GetTotalSavagery()
  1391. {
  1392. return basic_info.max_savagery;
  1393. }
  1394. sint32 Spawn::GetSavagery()
  1395. {
  1396. return basic_info.cur_savagery;
  1397. }
  1398. /*** DISSONANCE ***/
  1399. void Spawn::SetDissonance(sint32 dissonance, bool setUpdateFlags)
  1400. {
  1401. /* JA: extremely limited functionality until we better understand Dissonance */
  1402. if(dissonance > basic_info.max_dissonance)
  1403. SetInfo(&basic_info.max_dissonance, dissonance, setUpdateFlags);
  1404. SetInfo(&basic_info.cur_dissonance, dissonance, setUpdateFlags);
  1405. }
  1406. void Spawn::SetTotalDissonance(sint32 new_val)
  1407. {
  1408. /* JA: extremely limited functionality until we better understand Dissonance */
  1409. if(basic_info.dissonance_base == 0)
  1410. SetTotalDissonanceBase(new_val);
  1411. SetInfo(&basic_info.max_dissonance, new_val);
  1412. }
  1413. void Spawn::SetTotalDissonanceBase(sint32 new_val)
  1414. {
  1415. SetInfo(&basic_info.dissonance_base, new_val);
  1416. SendGroupUpdate();
  1417. }
  1418. sint32 Spawn::GetTotalDissonance()
  1419. {
  1420. return basic_info.max_dissonance;
  1421. }
  1422. sint32 Spawn::GetDissonance()
  1423. {
  1424. return basic_info.cur_dissonance;
  1425. }
  1426. /* --< Alternate Advancement Points >-- */
  1427. void Spawn::SetAssignedAA(sint16 new_val)
  1428. {
  1429. SetInfo(&basic_info.assigned_aa, new_val);
  1430. }
  1431. void Spawn::SetUnassignedAA(sint16 new_val)
  1432. {
  1433. SetInfo(&basic_info.unassigned_aa, new_val);
  1434. }
  1435. void Spawn::SetTradeskillAA(sint16 new_val)
  1436. {
  1437. SetInfo(&basic_info.tradeskill_aa, new_val);
  1438. }
  1439. void Spawn::SetUnassignedTradeskillAA(sint16 new_val)
  1440. {
  1441. SetInfo(&basic_info.unassigned_tradeskill_aa, new_val);
  1442. }
  1443. void Spawn::SetPrestigeAA(sint16 new_val)
  1444. {
  1445. SetInfo(&basic_info.prestige_aa, new_val);
  1446. }
  1447. void Spawn::SetUnassignedPrestigeAA(sint16 new_val)
  1448. {
  1449. SetInfo(&basic_info.unassigned_prestige_aa, new_val);
  1450. }
  1451. void Spawn::SetTradeskillPrestigeAA(sint16 new_val)
  1452. {
  1453. SetInfo(&basic_info.tradeskill_prestige_aa, new_val);
  1454. }
  1455. void Spawn::SetUnassignedTradeskillPrestigeAA(sint16 new_val)
  1456. {
  1457. SetInfo(&basic_info.unassigned_tradeskill_prestige_aa, new_val);
  1458. }
  1459. void Spawn::SetAAXPRewards(int32 value)
  1460. {
  1461. SetInfo(&basic_info.aaxp_rewards, value, false);
  1462. }
  1463. sint16 Spawn::GetAssignedAA()
  1464. {
  1465. return basic_info.assigned_aa;
  1466. }
  1467. sint16 Spawn::GetUnassignedAA()
  1468. {
  1469. return basic_info.unassigned_aa;
  1470. }
  1471. sint16 Spawn::GetTradeskillAA()
  1472. {
  1473. return basic_info.tradeskill_aa;
  1474. }
  1475. sint16 Spawn::GetUnassignedTradeskillAA()
  1476. {
  1477. return basic_info.unassigned_tradeskill_aa;
  1478. }
  1479. sint16 Spawn::GetPrestigeAA()
  1480. {
  1481. return basic_info.prestige_aa;
  1482. }
  1483. sint16 Spawn::GetUnassignedPretigeAA()
  1484. {
  1485. return basic_info.unassigned_prestige_aa;
  1486. }
  1487. sint16 Spawn::GetTradeskillPrestigeAA()
  1488. {
  1489. return basic_info.tradeskill_prestige_aa;
  1490. }
  1491. sint16 Spawn::GetUnassignedTradeskillPrestigeAA()
  1492. {
  1493. return basic_info.unassigned_tradeskill_prestige_aa;
  1494. }
  1495. int32 Spawn::GetAAXPRewards()
  1496. {
  1497. return basic_info.aaxp_rewards;
  1498. }
  1499. float Spawn::GetDistance(float x1, float y1, float z1, float x2, float y2, float z2){
  1500. x1 = x1 - x2;
  1501. y1 = y1 - y2;
  1502. z1 = z1 - z2;
  1503. return sqrt(x1*x1 + y1*y1 + z1*z1);
  1504. }
  1505. float Spawn::GetDistance(float x, float y, float z, float radius, bool ignore_y) {
  1506. if (ignore_y)
  1507. return GetDistance(x, y, z, GetX(), y, GetZ()) - radius;
  1508. else
  1509. return GetDistance(x, y, z, GetX(), GetY(), GetZ()) - radius;
  1510. }
  1511. float Spawn::GetDistance(float x, float y, float z, bool ignore_y) {
  1512. return GetDistance(x, y, z, 0.0f, ignore_y);
  1513. }
  1514. float Spawn::GetDistance(Spawn* spawn, bool ignore_y, bool includeRadius){
  1515. float ret = 0;
  1516. if (spawn)
  1517. {
  1518. float radius = 0.0f;
  1519. if (includeRadius)
  1520. radius = CalculateRadius(spawn);
  1521. ret = GetDistance(spawn->GetX(), spawn->GetY(), spawn->GetZ(), radius, ignore_y);
  1522. }
  1523. // maybe distance against ourselves, in that case we want to nullify the radius check
  1524. if (ret < 0)
  1525. ret = 0.0f;
  1526. return ret;
  1527. }
  1528. float Spawn::GetDistance(Spawn* spawn, float x1, float y1, float z1, bool includeRadius) {
  1529. float ret = 0;
  1530. if (spawn)
  1531. {
  1532. float radius = 0.0f;
  1533. if (includeRadius)
  1534. radius = CalculateRadius(spawn);
  1535. ret = GetDistance(x1, y1, z1, spawn->GetX(), spawn->GetY(), spawn->GetZ()) - radius;
  1536. }
  1537. // maybe distance against ourselves, in that case we want to nullify the radius check
  1538. if (ret < 0)
  1539. ret = 0.0f;
  1540. return ret;
  1541. }
  1542. float Spawn::CalculateRadius(Spawn* target)
  1543. {
  1544. float srcRadius = short_to_float(appearance.pos.collision_radius);
  1545. if (target)
  1546. {
  1547. float targRadius = short_to_float(target->appearance.pos.collision_radius);
  1548. return (targRadius / 32.0f) + (srcRadius / 32.0f);
  1549. }
  1550. else
  1551. return (srcRadius / 32.0f);
  1552. }
  1553. int32 Spawn::GetRespawnTime(){
  1554. return respawn;
  1555. }
  1556. void Spawn::SetRespawnTime(int32 time){
  1557. respawn = time;
  1558. }
  1559. int32 Spawn::GetExpireOffsetTime(){
  1560. return expire_offset;
  1561. }
  1562. void Spawn::SetExpireOffsetTime(int32 time){
  1563. expire_offset = time;
  1564. }
  1565. int32 Spawn::GetSpawnLocationID(){
  1566. return spawn_location_id;
  1567. }
  1568. void Spawn::SetSpawnLocationID(int32 id){
  1569. spawn_location_id = id;
  1570. }
  1571. int32 Spawn::GetSpawnEntryID(){
  1572. return spawn_entry_id;
  1573. }
  1574. void Spawn::SetSpawnEntryID(int32 id){
  1575. spawn_entry_id = id;
  1576. }
  1577. int32 Spawn::GetSpawnLocationPlacementID(){
  1578. return spawn_location_spawns_id;
  1579. }
  1580. void Spawn::SetSpawnLocationPlacementID(int32 id){
  1581. spawn_location_spawns_id = id;
  1582. }
  1583. const char* Spawn::GetSpawnScript(){
  1584. if(spawn_script.length() > 0)
  1585. return spawn_script.c_str();
  1586. else
  1587. return 0;
  1588. }
  1589. void Spawn::SetSpawnScript(string name){
  1590. spawn_script = name;
  1591. }
  1592. void Spawn::SetPrimaryCommand(const char* name, const char* command, float distance){
  1593. EntityCommand* entity_command = CreateEntityCommand(name, distance, command, "", 0, 0);
  1594. if(primary_command_list.size() > 0 && primary_command_list[0]){
  1595. safe_delete(primary_command_list[0]);
  1596. primary_command_list[0] = entity_command;
  1597. }
  1598. else
  1599. primary_command_list.push_back(entity_command);
  1600. }
  1601. void Spawn::SetSecondaryCommands(vector<EntityCommand*>* commands){
  1602. if(commands && commands->size() > 0){
  1603. vector<EntityCommand*>::iterator itr;
  1604. if(secondary_command_list.size() > 0){
  1605. for(itr = secondary_command_list.begin(); itr != secondary_command_list.end(); itr++){
  1606. safe_delete(*itr);
  1607. }
  1608. secondary_command_list.clear();
  1609. }
  1610. EntityCommand* command = 0;
  1611. for(itr = commands->begin(); itr != commands->end(); itr++){
  1612. command = CreateEntityCommand(*itr);
  1613. secondary_command_list.push_back(command);
  1614. }
  1615. }
  1616. }
  1617. void Spawn::SetPrimaryCommands(vector<EntityCommand*>* commands){
  1618. if(commands && commands->size() > 0){
  1619. vector<EntityCommand*>::iterator itr;
  1620. if(primary_command_list.size() > 0){
  1621. for(itr = primary_command_list.begin(); itr != primary_command_list.end(); itr++){
  1622. safe_delete(*itr);
  1623. }
  1624. primary_command_list.clear();
  1625. }
  1626. EntityCommand* command = 0;
  1627. for(itr = commands->begin(); itr != commands->end(); itr++){
  1628. command = CreateEntityCommand(*itr);
  1629. primary_command_list.push_back(command);
  1630. }
  1631. }
  1632. }
  1633. EntityCommand* Spawn::FindEntityCommand(string command, bool primaryOnly) {
  1634. EntityCommand* entity_command = 0;
  1635. if (primary_command_list.size() > 0) {
  1636. vector<EntityCommand*>::iterator itr;
  1637. for (itr = primary_command_list.begin(); itr != primary_command_list.end(); itr++) {
  1638. if ((*itr)->command.compare(command) == 0) {
  1639. entity_command = *itr;
  1640. break;
  1641. }
  1642. }
  1643. }
  1644. if (primaryOnly)
  1645. return entity_command;
  1646. if (!entity_command && secondary_command_list.size() > 0) {
  1647. vector<EntityCommand*>::iterator itr;
  1648. for (itr = secondary_command_list.begin(); itr != secondary_command_list.end(); itr++) {
  1649. if ((*itr)->command == command) {
  1650. entity_command = *itr;
  1651. break;
  1652. }
  1653. }
  1654. }
  1655. return entity_command;
  1656. }
  1657. void Spawn::SetSizeOffset(int8 offset){
  1658. size_offset = offset;
  1659. }
  1660. int8 Spawn::GetSizeOffset(){
  1661. return size_offset;
  1662. }
  1663. void Spawn::SetMerchantID(int32 val){
  1664. merchant_id = val;
  1665. }
  1666. int32 Spawn::GetMerchantID(){
  1667. return merchant_id;
  1668. }
  1669. void Spawn::SetMerchantType(int8 val) {
  1670. merchant_type = val;
  1671. }
  1672. int8 Spawn::GetMerchantType() {
  1673. return merchant_type;
  1674. }
  1675. void Spawn::SetMerchantLevelRange(int32 minLvl, int32 maxLvl) {
  1676. merchant_min_level = minLvl;
  1677. merchant_max_level = maxLvl;
  1678. }
  1679. int32 Spawn::GetMerchantMinLevel() {
  1680. return merchant_min_level;
  1681. }
  1682. int32 Spawn::GetMerchantMaxLevel() {
  1683. return merchant_max_level;
  1684. }
  1685. bool Spawn::IsClientInMerchantLevelRange(Client* client, bool sendMessageIfDenied)
  1686. {
  1687. if (!client)
  1688. return false;
  1689. if (GetMerchantMinLevel() && client->GetPlayer()->GetLevel() < GetMerchantMinLevel())
  1690. {
  1691. client->Message(CHANNEL_COLOR_RED, "You are unable to interact with this merchant due to a minimum level %u allowed.", GetMerchantMinLevel());
  1692. return false;
  1693. }
  1694. else if (GetMerchantMaxLevel() && client->GetPlayer()->GetLevel() > GetMerchantMaxLevel())
  1695. {
  1696. client->Message(CHANNEL_COLOR_RED, "You are unable to interact with this merchant due to a maximum level %u allowed.", GetMerchantMaxLevel());
  1697. return false;
  1698. }
  1699. return true;
  1700. }
  1701. void Spawn::SetQuestsRequired(Spawn* new_spawn){
  1702. m_requiredQuests.writelock(__FUNCTION__, __LINE__);
  1703. if(required_quests.size() > 0){
  1704. map<int32, vector<int16>* >::iterator itr;
  1705. for(itr = required_quests.begin(); itr != required_quests.end(); itr++){
  1706. vector<int16>* quest_steps = itr->second;
  1707. for (int32 i = 0; i < quest_steps->size(); i++)
  1708. new_spawn->SetQuestsRequired(itr->first, quest_steps->at(i));
  1709. }
  1710. }
  1711. m_requiredQuests.releasewritelock(__FUNCTION__, __LINE__);
  1712. }
  1713. void Spawn::SetQuestsRequired(int32 quest_id, int16 quest_step){
  1714. m_requiredQuests.writelock(__FUNCTION__, __LINE__);
  1715. if (required_quests.count(quest_id) == 0)
  1716. required_quests.insert(make_pair(quest_id, new vector<int16>));
  1717. else{
  1718. for (int32 i = 0; i < required_quests[quest_id]->size(); i++){
  1719. if (required_quests[quest_id]->at(i) == quest_step){
  1720. m_requiredQuests.releasewritelock(__FUNCTION__, __LINE__);
  1721. return;
  1722. }
  1723. }
  1724. }
  1725. has_quests_required = true;
  1726. required_quests[quest_id]->push_back(quest_step);
  1727. m_requiredQuests.releasewritelock(__FUNCTION__, __LINE__);
  1728. }
  1729. bool Spawn::HasQuestsRequired(){
  1730. return has_quests_required;
  1731. }
  1732. bool Spawn::HasHistoryRequired(){
  1733. return has_history_required;
  1734. }
  1735. void Spawn::SetRequiredHistory(int32 event_id, int32 value1, int32 value2){
  1736. LUAHistory* set_value = new LUAHistory();
  1737. set_value->Value = value1;
  1738. set_value->Value2 = value2;
  1739. set_value->SaveNeeded = false;
  1740. m_requiredHistory.writelock(__FUNCTION__, __LINE__);
  1741. if (required_history.count(event_id) == 0)
  1742. required_history.insert(make_pair(event_id, set_value));
  1743. else
  1744. {
  1745. LUAHistory* tmp_value = required_history[event_id];
  1746. required_history[event_id] = set_value;
  1747. safe_delete(tmp_value);
  1748. }
  1749. has_history_required = true;
  1750. m_requiredHistory.releasewritelock(__FUNCTION__, __LINE__);
  1751. }
  1752. void Spawn::SetTransporterID(int32 id){
  1753. transporter_id = id;
  1754. }
  1755. int32 Spawn::GetTransporterID(){
  1756. return transporter_id;
  1757. }
  1758. void Spawn::InitializePosPacketData(Player* player, PacketStruct* packet, bool bSpawnUpdate) {
  1759. int16 version = packet->GetVersion();
  1760. int32 new_grid_id = 0;
  1761. int32 new_widget_id = 0;
  1762. if(player->GetMap() != nullptr && player->GetMap()->IsMapLoaded())
  1763. {
  1764. m_GridMutex.writelock(__FUNCTION__, __LINE__);
  1765. std::map<int32,TimedGridData>::iterator itr = established_grid_id.find(version);
  1766. if ( itr == established_grid_id.end() || itr->second.timestamp <= (Timer::GetCurrentTime2()))
  1767. {
  1768. if(itr != established_grid_id.end() && itr->second.x == GetX() && itr->second.z == GetZ() && !itr->second.npc_save) {
  1769. itr->second.timestamp = Timer::GetCurrentTime2()+100;
  1770. itr->second.npc_save = false;
  1771. new_grid_id = itr->second.grid_id;
  1772. new_widget_id = itr->second.widget_id;
  1773. }
  1774. else {
  1775. auto loc = glm::vec3(GetX(), GetZ(), GetY());
  1776. float new_z = player->FindBestZ(loc, nullptr, &new_grid_id, &new_widget_id);
  1777. TimedGridData data;
  1778. data.grid_id = new_grid_id;
  1779. data.widget_id = new_widget_id;
  1780. data.x = GetX();
  1781. data.y = GetY();
  1782. data.z = GetZ();
  1783. data.npc_save = false;
  1784. data.timestamp = Timer::GetCurrentTime2()+100;
  1785. established_grid_id.insert(make_pair(packet->GetVersion(), data));
  1786. }
  1787. }
  1788. else {
  1789. new_grid_id = itr->second.grid_id;
  1790. new_widget_id = itr->second.widget_id;
  1791. }
  1792. m_GridMutex.releasewritelock(__FUNCTION__, __LINE__);
  1793. }
  1794. if(IsKnockedBack()) {
  1795. packet->setDataByName("pos_grid_id", 0);
  1796. }
  1797. else {
  1798. packet->setDataByName("pos_grid_id", new_grid_id != 0 ? new_grid_id : GetLocation());
  1799. }
  1800. bool include_heading = true;
  1801. if (IsWidget() && ((Widget*)this)->GetIncludeHeading() == false)
  1802. include_heading = false;
  1803. else if (IsSign() && ((Sign*)this)->GetIncludeHeading() == false)
  1804. include_heading = false;
  1805. if (include_heading){
  1806. packet->setDataByName("pos_heading1", appearance.pos.Dir1);
  1807. packet->setDataByName("pos_heading2", appearance.pos.Dir2);
  1808. }
  1809. if (version <= 910) {
  1810. packet->setDataByName("pos_collision_radius", appearance.pos.collision_radius > 0 ? appearance.pos.collision_radius : 32);
  1811. packet->setDataByName("pos_size", size > 0 ? size : 32);
  1812. packet->setDataByName("pos_size_multiplier", 32); //32 is normal
  1813. }
  1814. else {
  1815. if (size == 0)
  1816. size = 32;
  1817. packet->setDataByName("pos_collision_radius", appearance.pos.collision_radius > 0 ? appearance.pos.collision_radius : 32);
  1818. packet->setDataByName("pos_size", 1.0f);
  1819. if (!IsPlayer())
  1820. packet->setDataByName("pos_size", size > 0 ? (((float)size) / 32.0f) : 1.0f); // float not an integer
  1821. else
  1822. packet->setDataByName("pos_size", 1.0f);
  1823. // please do not remove! This makes it so NPCs for example do not resize large/small when you are in combat with them!
  1824. packet->setDataByName("pos_size_ratio", 1.0f);
  1825. }
  1826. packet->setDataByName("pos_state", appearance.pos.state);
  1827. bool include_location = true;
  1828. if (IsWidget() && ((Widget*)this)->GetIncludeLocation() == false)
  1829. include_location = false;
  1830. else if (IsSign() && ((Sign*)this)->GetIncludeLocation() == false)
  1831. include_location = false;
  1832. if (include_location){
  1833. if (IsWidget() && ((Widget*)this)->GetMultiFloorLift()) {
  1834. Widget* widget = (Widget*)this;
  1835. float x = appearance.pos.X - widget->GetWidgetX();
  1836. float y = appearance.pos.Y - widget->GetWidgetY();
  1837. float z = appearance.pos.Z - widget->GetWidgetZ();
  1838. packet->setDataByName("pos_x", x);
  1839. packet->setDataByName("pos_y", y);
  1840. packet->setDataByName("pos_z", z);
  1841. }
  1842. else {
  1843. packet->setDataByName("pos_x", appearance.pos.X);
  1844. packet->setDataByName("pos_y", appearance.pos.Y);
  1845. packet->setDataByName("pos_z", appearance.pos.Z);
  1846. }
  1847. if (IsSign())
  1848. packet->setDataByName("pos_unknown6", 3, 2);
  1849. }
  1850. if (IsPlayer()) {
  1851. Skill* skill = ((Player*)this)->GetSkillByName("Swimming", false);
  1852. sint16 swim_modifier = rule_manager.GetGlobalRule(R_Player, SwimmingSkillMinSpeed)->GetSInt16();
  1853. if(skill) {
  1854. sint16 max_val = 450;
  1855. if(skill->max_val > 0)
  1856. max_val = skill->max_val;
  1857. sint16 max_swim_mod = rule_manager.GetGlobalRule(R_Player, SwimmingSkillMaxSpeed)->GetSInt16();
  1858. float diff = (float)(skill->current_val + ((Player*)this)->GetStat(ITEM_STAT_SWIMMING)) / (float)max_val;
  1859. sint16 diff_mod = (sint16)(float)max_swim_mod * diff;
  1860. if(diff_mod > max_swim_mod)
  1861. swim_modifier = max_swim_mod;
  1862. else if(diff_mod > swim_modifier)
  1863. swim_modifier = diff_mod;
  1864. }
  1865. packet->setDataByName("pos_swim_speed_modifier", swim_modifier);
  1866. packet->setDataByName("pos_x_velocity", TransformFromFloat(GetSpeedX(), 5));
  1867. packet->setDataByName("pos_y_velocity", TransformFromFloat(GetSpeedY(), 5));
  1868. packet->setDataByName("pos_z_velocity", TransformFromFloat(GetSpeedZ(), 5));
  1869. }
  1870. if (appearance.pos.X2 == 0 && appearance.pos.Y2 == 0 && appearance.pos.Z2 && (appearance.pos.X != 0 || appearance.pos.Y != 0 || appearance.pos.Z != 0)) {
  1871. appearance.pos.X2 = appearance.pos.X;
  1872. appearance.pos.Y2 = appearance.pos.Y;
  1873. appearance.pos.Z2 = appearance.pos.Z;
  1874. }
  1875. if (appearance.pos.X3 == 0 && appearance.pos.Y3 == 0 && appearance.pos.Z3 && (appearance.pos.X != 0 || appearance.pos.Y != 0 || appearance.pos.Z != 0)) {
  1876. appearance.pos.X3 = appearance.pos.X;
  1877. appearance.pos.Y3 = appearance.pos.Y;
  1878. appearance.pos.Z3 = appearance.pos.Z;
  1879. }
  1880. //Transform To/From Float bits (original client)
  1881. //pos_loc_offset[3]: 5
  1882. //pos_x_velocity: 5
  1883. //pos_y_velocity: 5
  1884. //pos_z_velocity: 5
  1885. //pos_heading1: 6
  1886. //pos_heading2: 6
  1887. //pos_speed: 8
  1888. //pos_dest_loc_offset[3]: 5
  1889. //pos_dest_loc_offset2[3]: 5
  1890. //pos_heading_speed: 5
  1891. //pos_move_type: 5 (speed_modifier)
  1892. //pos_swim_speed_modifier: 5
  1893. //pos_side_speed: 8
  1894. //pos_vert_speed: 8
  1895. //pos_requested_pitch: 6
  1896. //pos_requested_pitch_speed: 5
  1897. //pos_pitch: 6
  1898. //pos_collision_radius: 5
  1899. //pos_size: 5
  1900. //actor_stop_range: 5
  1901. //this is for original box client, destinations used to be offsets
  1902. if (appearance.pos.X2 != 0 || appearance.pos.Y2 != 0 || appearance.pos.Z2 != 0) {
  1903. packet->setDataByName("pos_dest_loc_offset", TransformFromFloat(appearance.pos.X2 - appearance.pos.X, 5));
  1904. packet->setDataByName("pos_dest_loc_offset", TransformFromFloat(appearance.pos.Y2 - appearance.pos.Y, 5), 1);
  1905. packet->setDataByName("pos_dest_loc_offset", TransformFromFloat(appearance.pos.Z2 - appearance.pos.Z, 5), 2);
  1906. }
  1907. if (appearance.pos.X3 != 0 || appearance.pos.Y3 != 0 || appearance.pos.Z3 != 0) {
  1908. packet->setDataByName("pos_dest_loc_offset2", TransformFromFloat(appearance.pos.X3 - appearance.pos.X, 5));
  1909. packet->setDataByName("pos_dest_loc_offset2", TransformFromFloat(appearance.pos.Y3 - appearance.pos.Y, 5), 1);
  1910. packet->setDataByName("pos_dest_loc_offset2", TransformFromFloat(appearance.pos.Z3 - appearance.pos.Z, 5), 2);
  1911. }
  1912. bool bSendSpeed = true;
  1913. if (IsWidget() && ((Widget*)this)->GetMultiFloorLift()) {
  1914. Widget* widget = (Widget*)this;
  1915. float x;
  1916. float y;
  1917. float z;
  1918. if (IsRunning()){
  1919. x = appearance.pos.X2 - widget->GetWidgetX();
  1920. y = appearance.pos.Y2 - widget->GetWidgetY();
  1921. z = appearance.pos.Z2- widget->GetWidgetZ();
  1922. }
  1923. else {
  1924. x = appearance.pos.X - widget->GetWidgetX();
  1925. y = appearance.pos.Y - widget->GetWidgetY();
  1926. z = appearance.pos.Z - widget->GetWidgetZ();
  1927. }
  1928. packet->setDataByName("pos_next_x", x);
  1929. packet->setDataByName("pos_next_y", y);
  1930. packet->setDataByName("pos_next_z", z);
  1931. packet->setDataByName("pos_x3", x);
  1932. packet->setDataByName("pos_y3", y);
  1933. packet->setDataByName("pos_z3", z);
  1934. }
  1935. //If this is a spawn update or this spawn is currently moving we can send these values, otherwise set speed and next_xyz to 0
  1936. //This fixes the bug where spawns with movement scripts face south when initially spawning if they are at their target location.
  1937. else if (bSpawnUpdate || memcmp(&appearance.pos.X, &appearance.pos.X2, sizeof(float) * 3) != 0) {
  1938. packet->setDataByName("pos_next_x", appearance.pos.X2);
  1939. packet->setDataByName("pos_next_y", appearance.pos.Y2);
  1940. packet->setDataByName("pos_next_z", appearance.pos.Z2);
  1941. packet->setDataByName("pos_x3", appearance.pos.X3);
  1942. packet->setDataByName("pos_y3", appearance.pos.Y3);
  1943. packet->setDataByName("pos_z3", appearance.pos.Z3);
  1944. }
  1945. else
  1946. {
  1947. bSendSpeed = false;
  1948. }
  1949. //packet->setDataByName("pos_unknown2", 4, 2);
  1950. int16 speed_multiplier = rule_manager.GetGlobalRule(R_Spawn, SpeedMultiplier)->GetInt16(); // was 1280, 600 and now 300... investigating why
  1951. if (IsPlayer()) {
  1952. Player* player = static_cast<Player*>(this);
  1953. packet->setDataByName("pos_speed", player->GetPosPacketSpeed() * speed_multiplier);
  1954. packet->setDataByName("pos_side_speed", player->GetSideSpeed() * speed_multiplier);
  1955. }
  1956. else if (bSendSpeed) {
  1957. packet->setDataByName("pos_speed", GetSpeed() * speed_multiplier);
  1958. }
  1959. if (IsNPC() || IsPlayer()) {
  1960. packet->setDataByName("pos_move_type", 25);
  1961. }
  1962. else if (IsWidget() || IsSign()) {
  1963. packet->setDataByName("pos_move_type", 11);
  1964. }
  1965. else if(IsGroundSpawn()) {
  1966. packet->setDataByName("pos_move_type", 16);
  1967. }
  1968. if (!IsPlayer()) // has to be 2 or NPC's warp around when moving
  1969. packet->setDataByName("pos_movement_mode", 2);
  1970. packet->setDataByName("face_actor_id", 0xFFFFFFFF);
  1971. packet->setDataByName("pos_pitch1", appearance.pos.Pitch1);
  1972. packet->setDataByName("pos_pitch2", appearance.pos.Pitch2);
  1973. packet->setDataByName("pos_roll", appearance.pos.Roll);
  1974. }
  1975. void Spawn::InitializeInfoPacketData(Player* spawn, PacketStruct* packet) {
  1976. int16 version = packet->GetVersion();
  1977. bool spawnHiddenFromClient = false;
  1978. int8 classicFlags = 0;
  1979. // radius of 0 is always seen, -1 is never seen (unless items/spells override), larger than 0 is a defined radius to restrict visibility
  1980. sint32 radius = rule_manager.GetGlobalRule(R_PVP, InvisPlayerDiscoveryRange)->GetSInt32();
  1981. if (radius != 0 && (Spawn*)spawn != this && this->IsPlayer() && !spawn->CanSeeInvis((Entity*)this))
  1982. spawnHiddenFromClient = true;
  1983. if (!spawnHiddenFromClient && (appearance.targetable == 1 || appearance.show_level == 1 || appearance.display_name == 1)) {
  1984. if (!IsObject() && !IsGroundSpawn() && !IsWidget() && !IsSign()) {
  1985. int8 percent = 0;
  1986. if (GetHP() > 0)
  1987. percent = (int8)(((float)GetHP() / GetTotalHP()) * 100);
  1988. if (version >= 284) {
  1989. if (percent < 100) {
  1990. packet->setDataByName("hp_remaining", 100 ^ percent);
  1991. }
  1992. else
  1993. packet->setDataByName("hp_remaining", 0);
  1994. }
  1995. else {
  1996. if (percent > 100)
  1997. percent = 100;
  1998. packet->setDataByName("hp_remaining", percent);
  1999. }
  2000. if (GetTotalPower() > 0) {
  2001. percent = (int8)(((float)GetPower() / GetTotalPower()) * 100);
  2002. if (percent > 0)
  2003. packet->setDataByName("power_percent", percent);
  2004. else
  2005. packet->setDataByName("power_percent", 0);
  2006. }
  2007. }
  2008. }
  2009. if (version <= 561) {
  2010. packet->setDataByName("name", appearance.name);
  2011. for (int8 i = 0; i < 8; i++)
  2012. packet->setDataByName("unknown1", 0xFF, i);
  2013. if (appearance.show_level == 0)
  2014. packet->setDataByName("hide_health", 1);
  2015. }
  2016. if (GetHP() <= 0 && IsEntity()) {
  2017. packet->setDataByName("corpse", 1);
  2018. if(HasLoot())
  2019. packet->setDataByName("loot_icon", 1);
  2020. }
  2021. if (!IsPlayer())
  2022. packet->setDataByName("npc", 1);
  2023. if (GetMerchantID() > 0)
  2024. packet->setDataByName("merchant", 1);
  2025. packet->setDataByName("effective_level", IsEntity() && ((Entity*)this)->GetInfoStruct()->get_effective_level() != 0 ? (int8)((Entity*)this)->GetInfoStruct()->get_effective_level() : (int8)GetLevel());
  2026. packet->setDataByName("level", (int8)GetLevel());
  2027. packet->setDataByName("unknown4", (int8)GetLevel());
  2028. packet->setDataByName("difficulty", GetDifficulty()); //6);
  2029. packet->setDataByName("unknown6", 1);
  2030. packet->setDataByName("heroic_flag", appearance.heroic_flag);
  2031. packet->setDataByName("class", appearance.adventure_class);
  2032. int16 model_type = appearance.model_type;
  2033. if (GetIllusionModel() != 0) {
  2034. if (IsPlayer()) {
  2035. if (((Player*)this)->get_character_flag(CF_SHOW_ILLUSION)) {
  2036. model_type = GetIllusionModel();
  2037. }
  2038. }
  2039. else
  2040. model_type = GetIllusionModel();
  2041. }
  2042. int16 sogaModelType = appearance.soga_model_type;
  2043. if (spawnHiddenFromClient)
  2044. {
  2045. model_type = 0;
  2046. sogaModelType = 0;
  2047. }
  2048. packet->setDataByName("model_type", model_type);
  2049. if (appearance.soga_model_type == 0)
  2050. packet->setDataByName("soga_model_type", model_type);
  2051. else
  2052. packet->setDataByName("soga_model_type", sogaModelType);
  2053. int16 action_state = appearance.action_state;
  2054. if(IsEntity()) {
  2055. std::string actionState = "";
  2056. if (GetTempActionState() >= 0) {
  2057. action_state = GetTempActionState();
  2058. actionState = ((Entity*)this)->GetInfoStruct()->get_combat_action_state();
  2059. }
  2060. else {
  2061. actionState = ((Entity*)this)->GetInfoStruct()->get_action_state();
  2062. }
  2063. Client* client = spawn->GetClient();
  2064. if(IsEntity() && client) {
  2065. if(actionState.size() > 0) {
  2066. Emote* emote = visual_states.FindEmote(actionState, client->GetVersion());
  2067. if(emote != NULL)
  2068. action_state = emote->GetVisualState();
  2069. }
  2070. }
  2071. }
  2072. packet->setDataByName("action_state", action_state);
  2073. bool scaredOfPlayer = false;
  2074. if(IsCollector() && spawn->GetCollectionList()->HasCollectionsToHandIn())
  2075. packet->setDataByName("visual_state", VISUAL_STATE_COLLECTION_TURN_IN);
  2076. else if(!IsRunning() && IsNPC() && IsScaredByStrongPlayers() && spawn->GetArrowColor(GetLevel()) == ARROW_COLOR_GRAY &&
  2077. (GetDistance(spawn)) <= ((NPC*)this)->GetAggroRadius() && CheckLoS(spawn)) {
  2078. packet->setDataByName("visual_state", VISUAL_STATE_IDLE_AFRAID);
  2079. scaredOfPlayer = true;
  2080. }
  2081. else if (GetTempVisualState() >= 0)
  2082. packet->setDataByName("visual_state", GetTempVisualState());
  2083. else
  2084. packet->setDataByName("visual_state", appearance.visual_state);
  2085. if (IsNPC() && !IsPet() && !scaredOfPlayer)
  2086. {
  2087. if(((Entity*)this)->GetInfoStruct()->get_interaction_flag()) {
  2088. if(((Entity*)this)->GetInfoStruct()->get_interaction_flag() == 255) {
  2089. packet->setDataByName("interaction_flag", 0);
  2090. classicFlags += INFO_CLASSIC_FLAG_NOLOOK;
  2091. }
  2092. else {
  2093. packet->setDataByName("interaction_flag", ((Entity*)this)->GetInfoStruct()->get_interaction_flag()); //this makes NPCs head turn to look at you (12)
  2094. }
  2095. }
  2096. else {
  2097. packet->setDataByName("interaction_flag", 12); //turn head since no other value is set
  2098. }
  2099. }
  2100. packet->setDataByName("emote_state", appearance.emote_state);
  2101. packet->setDataByName("mood_state", appearance.mood_state);
  2102. packet->setDataByName("gender", appearance.gender);
  2103. packet->setDataByName("race", appearance.race);
  2104. if (IsEntity()) {
  2105. Entity* entity = ((Entity*)this);
  2106. packet->setDataByName("combat_voice", entity->GetCombatVoice());
  2107. packet->setDataByName("emote_voice", entity->GetEmoteVoice());
  2108. for (int i = 0; i < 25; i++) {
  2109. if (i == 2) { //don't send helm if hidden flag
  2110. if (IsPlayer()) {
  2111. if (((Player*)this)->get_character_flag(CF_HIDE_HELM)) {
  2112. packet->setDataByName("equipment_types", 0, i);
  2113. packet->setColorByName("equipment_colors", 0, i);
  2114. packet->setColorByName("equipment_highlights", 0, i);
  2115. continue;
  2116. }
  2117. }
  2118. if (IsBot()) {
  2119. if (!((Bot*)this)->ShowHelm) {
  2120. packet->setDataByName("equipment_types", 0, i);
  2121. packet->setColorByName("equipment_colors", 0, i);
  2122. packet->setColorByName("equipment_highlights", 0, i);
  2123. continue;
  2124. }
  2125. }
  2126. }
  2127. else if (i == 19) { //don't send cloak if hidden
  2128. if (IsPlayer()) {
  2129. if (!((Player*)this)->get_character_flag(CF_SHOW_CLOAK)) {
  2130. packet->setDataByName("equipment_types", 0, i);
  2131. packet->setColorByName("equipment_colors", 0, i);
  2132. packet->setColorByName("equipment_highlights", 0, i);
  2133. continue;
  2134. }
  2135. }
  2136. if (IsBot()) {
  2137. if (!((Bot*)this)->ShowCloak) {
  2138. packet->setDataByName("equipment_types", 0, i);
  2139. packet->setColorByName("equipment_colors", 0, i);
  2140. packet->setColorByName("equipment_highlights", 0, i);
  2141. continue;
  2142. }
  2143. }
  2144. }
  2145. entity->MEquipment.lock();
  2146. packet->setDataByName("equipment_types", entity->equipment.equip_id[i], i);
  2147. packet->setColorByName("equipment_colors", entity->equipment.color[i], i);
  2148. packet->setColorByName("equipment_highlights", entity->equipment.highlight[i], i);
  2149. entity->MEquipment.unlock();
  2150. }
  2151. packet->setDataByName("mount_type", entity->GetMount());
  2152. // find the visual flags
  2153. int8 vis_flag = 0;
  2154. //Invis + crouch flag check
  2155. if (entity->IsStealthed()) {
  2156. vis_flag += (INFO_VIS_FLAG_INVIS + INFO_VIS_FLAG_CROUCH);
  2157. classicFlags += INFO_VIS_FLAG_INVIS + INFO_VIS_FLAG_CROUCH;
  2158. }
  2159. //Invis flag check
  2160. else if (entity->IsInvis()) {
  2161. vis_flag += INFO_VIS_FLAG_INVIS;
  2162. classicFlags += INFO_VIS_FLAG_INVIS;
  2163. }
  2164. //Mount flag check
  2165. if (entity->GetMount() > 0) {
  2166. vis_flag += INFO_VIS_FLAG_MOUNTED;
  2167. }
  2168. //Hide hood check
  2169. bool vis_hide_hood = false;
  2170. if (IsPlayer() && ((Player*)this)->get_character_flag(CF_HIDE_HOOD)) {
  2171. if(version > 561) {
  2172. vis_flag += INFO_VIS_FLAG_HIDE_HOOD;
  2173. }
  2174. vis_hide_hood = true;
  2175. }
  2176. else if(IsPlayer()) {
  2177. classicFlags += INFO_CLASSIC_FLAG_SHOW_HOOD;
  2178. }
  2179. if(!vis_hide_hood && appearance.hide_hood && version > 561) {
  2180. vis_flag += INFO_VIS_FLAG_HIDE_HOOD;
  2181. }
  2182. if(version <= 561) {
  2183. packet->setDataByName("flags", classicFlags);
  2184. }
  2185. packet->setDataByName("visual_flag", vis_flag);
  2186. packet->setColorByName("mount_saddle_color", entity->GetMountSaddleColor());
  2187. packet->setColorByName("mount_color", entity->GetMountColor());
  2188. packet->setDataByName("hair_type_id", entity->features.hair_type);
  2189. packet->setDataByName("chest_type_id", entity->features.chest_type);
  2190. packet->setDataByName("wing_type_id", entity->features.wing_type);
  2191. packet->setDataByName("legs_type_id", entity->features.legs_type);
  2192. packet->setDataByName("soga_hair_type_id", entity->features.soga_hair_type);
  2193. packet->setDataByName("facial_hair_type_id", entity->features.hair_face_type);
  2194. packet->setDataByName("soga_facial_hair_type_id", entity->features.soga_hair_face_type);
  2195. for (int i = 0; i < 3; i++) {
  2196. packet->setDataByName("eye_type", entity->features.eye_type[i], i);
  2197. packet->setDataByName("ear_type", entity->features.ear_type[i], i);
  2198. packet->setDataByName("eye_brow_type", entity->features.eye_brow_type[i], i);
  2199. packet->setDataByName("cheek_type", entity->features.cheek_type[i], i);
  2200. packet->setDataByName("lip_type", entity->features.lip_type[i], i);
  2201. packet->setDataByName("chin_type", entity->features.chin_type[i], i);
  2202. packet->setDataByName("nose_type", entity->features.nose_type[i], i);
  2203. packet->setDataByName("soga_eye_type", entity->features.soga_eye_type[i], i);
  2204. packet->setDataByName("soga_ear_type", entity->features.soga_ear_type[i], i);
  2205. packet->setDataByName("soga_eye_brow_type", entity->features.soga_eye_brow_type[i], i);
  2206. packet->setDataByName("soga_cheek_type", entity->features.soga_cheek_type[i], i);
  2207. packet->setDataByName("soga_lip_type", entity->features.soga_lip_type[i], i);
  2208. packet->setDataByName("soga_chin_type", entity->features.soga_chin_type[i], i);
  2209. packet->setDataByName("soga_nose_type", entity->features.soga_nose_type[i], i);
  2210. }
  2211. packet->setColorByName("skin_color", entity->features.skin_color);
  2212. packet->setColorByName("model_color", entity->features.model_color);
  2213. packet->setColorByName("eye_color", entity->features.eye_color);
  2214. packet->setColorByName("hair_type_color", entity->features.hair_type_color);
  2215. packet->setColorByName("hair_type_highlight_color", entity->features.hair_type_highlight_color);
  2216. packet->setColorByName("hair_face_color", entity->features.hair_face_color);
  2217. packet->setColorByName("hair_face_highlight_color", entity->features.hair_face_highlight_color);
  2218. packet->setColorByName("hair_highlight", entity->features.hair_highlight_color);
  2219. packet->setColorByName("wing_color1", entity->features.wing_color1);
  2220. packet->setColorByName("wing_color2", entity->features.wing_color2);
  2221. packet->setColorByName("hair_color1", entity->features.hair_color1);
  2222. packet->setColorByName("hair_color2", entity->features.hair_color2);
  2223. packet->setColorByName("soga_skin_color", entity->features.soga_skin_color);
  2224. packet->setColorByName("soga_model_color", entity->features.soga_model_color);
  2225. packet->setColorByName("soga_eye_color", entity->features.soga_eye_color);
  2226. packet->setColorByName("soga_hair_color1", entity->features.soga_hair_color1);
  2227. packet->setColorByName("soga_hair_color2", entity->features.soga_hair_color2);
  2228. packet->setColorByName("soga_hair_type_color", entity->features.soga_hair_type_color);
  2229. packet->setColorByName("soga_hair_type_highlight_color", entity->features.soga_hair_type_highlight_color);
  2230. packet->setColorByName("soga_hair_face_color", entity->features.soga_hair_face_color);
  2231. packet->setColorByName("soga_hair_face_highlight_color", entity->features.soga_hair_face_highlight_color);
  2232. packet->setColorByName("soga_hair_highlight", entity->features.soga_hair_highlight_color);
  2233. packet->setDataByName("body_size", entity->features.body_size);
  2234. packet->setDataByName("body_age", entity->features.body_age);
  2235. packet->setDataByName("soga_body_size", entity->features.soga_body_size);
  2236. packet->setDataByName("soga_body_age", entity->features.soga_body_age);
  2237. }
  2238. else {
  2239. EQ2_Color empty;
  2240. empty.red = 255;
  2241. empty.blue = 255;
  2242. empty.green = 255;
  2243. packet->setColorByName("skin_color", empty);
  2244. packet->setColorByName("model_color", empty);
  2245. packet->setColorByName("eye_color", empty);
  2246. packet->setColorByName("soga_skin_color", empty);
  2247. packet->setColorByName("soga_model_color", empty);
  2248. packet->setColorByName("soga_eye_color", empty);
  2249. }
  2250. if (appearance.icon == 0) {
  2251. if (appearance.attackable == 1)
  2252. appearance.icon = 0;
  2253. else if (GetDifficulty() > 0)
  2254. appearance.icon = 4;
  2255. else
  2256. appearance.icon = 6;
  2257. }
  2258. // If Coe+ clients modify the values before we send
  2259. // if not then just send the value we have.
  2260. int8 temp_icon = appearance.icon;
  2261. //Check if we need to add the hand icon..
  2262. if ((temp_icon & 6) != 6 && appearance.display_hand_icon) {
  2263. temp_icon |= 6;
  2264. }
  2265. //Icon value 28 for boats, set this without modifying the value
  2266. if (version >= 1188 && temp_icon != 28) {
  2267. if ((temp_icon & 64) > 0) {
  2268. temp_icon -= 64; // remove the DoV value;
  2269. temp_icon += 128; // add the CoE value
  2270. }
  2271. if ((temp_icon & 32) > 0) {
  2272. temp_icon -= 32; // remove the DoV value;
  2273. temp_icon += 64; // add the CoE value
  2274. }
  2275. if ((temp_icon & 4) > 0) {
  2276. temp_icon -= 4; // remove DoV value
  2277. temp_icon += 8; // add the CoE icon
  2278. }
  2279. if ((temp_icon & 6) > 0) {
  2280. temp_icon -= 10; // remove DoV value
  2281. temp_icon += 12; // add the CoE icon
  2282. }
  2283. }
  2284. packet->setDataByName("icon", temp_icon);//appearance.icon);
  2285. int32 temp_activity_status = 0;
  2286. if (!Alive() && GetTotalHP() > 0 && !IsObject() && !IsGroundSpawn())
  2287. temp_activity_status = 1;
  2288. if(version >= 1188 && GetChestDropTime()) {
  2289. temp_activity_status = 0;
  2290. }
  2291. temp_activity_status += (IsNPC() || IsObject() || IsGroundSpawn()) ? 1 << 1 : 0;
  2292. if (version > 561) {
  2293. // Fix widget or sign having 'Play Legends of Norrath' or 'Tell' options in right click (client hard-coded entity commands)
  2294. if(IsWidget() || IsSign())
  2295. temp_activity_status = 2;
  2296. if (IsGroundSpawn() || GetShowHandIcon())
  2297. temp_activity_status += ACTIVITY_STATUS_INTERACTABLE_1188;
  2298. if ((appearance.activity_status & ACTIVITY_STATUS_ROLEPLAYING) > 0)
  2299. temp_activity_status += ACTIVITY_STATUS_ROLEPLAYING_1188;
  2300. if ((appearance.activity_status & ACTIVITY_STATUS_ANONYMOUS) > 0)
  2301. temp_activity_status += ACTIVITY_STATUS_ANONYMOUS_1188;
  2302. if ((appearance.activity_status & ACTIVITY_STATUS_LINKDEAD) > 0)
  2303. temp_activity_status += ACTIVITY_STATUS_LINKDEAD_1188;
  2304. if ((appearance.activity_status & ACTIVITY_STATUS_CAMPING) > 0)
  2305. temp_activity_status += ACTIVITY_STATUS_CAMPING_1188;
  2306. if ((appearance.activity_status & ACTIVITY_STATUS_LFG) > 0)
  2307. temp_activity_status += ACTIVITY_STATUS_LFG_1188;
  2308. if ((appearance.activity_status & ACTIVITY_STATUS_LFW) > 0)
  2309. temp_activity_status += ACTIVITY_STATUS_LFW_1188;
  2310. if ((appearance.activity_status & ACTIVITY_STATUS_SOLID) > 0)
  2311. temp_activity_status += ACTIVITY_STATUS_SOLID_1188;
  2312. if ((appearance.activity_status & ACTIVITY_STATUS_IMMUNITY_GAINED) > 0)
  2313. temp_activity_status += ACTIVITY_STATUS_IMMUNITY_GAINED_1188;
  2314. if ((appearance.activity_status & ACTIVITY_STATUS_IMMUNITY_REMAINING) > 0)
  2315. temp_activity_status += ACTIVITY_STATUS_IMMUNITY_REMAINING_1188;
  2316. if ((appearance.activity_status & ACTIVITY_STATUS_AFK) > 0)
  2317. temp_activity_status += ACTIVITY_STATUS_AFK_1188;
  2318. if (EngagedInCombat())
  2319. temp_activity_status += ACTIVITY_STATUS_INCOMBAT_1188;
  2320. // if this is either a boat or lift let the client be manipulated by the object
  2321. // doesn't work for DoF client version 546
  2322. if (appearance.icon == 28 || appearance.icon == 12 || IsTransportSpawn())
  2323. {
  2324. // there is some other flags that setting with a transport breaks their solidity/ability to properly transport
  2325. // thus we just consider the following flags for now as all necessary
  2326. temp_activity_status = ACTIVITY_STATUS_SOLID_1188;
  2327. temp_activity_status += ACTIVITY_STATUS_ISTRANSPORT_1188;
  2328. }
  2329. }
  2330. else if (version == 561) {
  2331. // Fix widget or sign having 'Play Legends of Norrath' or 'Tell' options in right click (client hard-coded entity commands)
  2332. if(IsWidget() || IsSign())
  2333. temp_activity_status = 2;
  2334. if (IsGroundSpawn() || GetShowHandIcon())
  2335. temp_activity_status += ACTIVITY_STATUS_INTERACTABLE_561;
  2336. if ((appearance.activity_status & ACTIVITY_STATUS_ROLEPLAYING) > 0)
  2337. temp_activity_status += ACTIVITY_STATUS_ROLEPLAYING_561;
  2338. if ((appearance.activity_status & ACTIVITY_STATUS_ANONYMOUS) > 0)
  2339. temp_activity_status += ACTIVITY_STATUS_ANONYMOUS_561;
  2340. if ((appearance.activity_status & ACTIVITY_STATUS_LINKDEAD) > 0)
  2341. temp_activity_status += ACTIVITY_STATUS_LINKDEAD_561;
  2342. if ((appearance.activity_status & ACTIVITY_STATUS_CAMPING) > 0)
  2343. temp_activity_status += ACTIVITY_STATUS_CAMPING_561;
  2344. if ((appearance.activity_status & ACTIVITY_STATUS_LFG) > 0)
  2345. temp_activity_status += ACTIVITY_STATUS_LFG_561;
  2346. if ((appearance.activity_status & ACTIVITY_STATUS_LFW) > 0)
  2347. temp_activity_status += ACTIVITY_STATUS_LFW_561;
  2348. if ((appearance.activity_status & ACTIVITY_STATUS_SOLID) > 0)
  2349. temp_activity_status += ACTIVITY_STATUS_SOLID_561;
  2350. if ((appearance.activity_status & ACTIVITY_STATUS_IMMUNITY_GAINED) > 0)
  2351. temp_activity_status += ACTIVITY_STATUS_IMMUNITY_GAINED_561;
  2352. if ((appearance.activity_status & ACTIVITY_STATUS_IMMUNITY_REMAINING) > 0)
  2353. temp_activity_status += ACTIVITY_STATUS_IMMUNITY_REMAINING_561;
  2354. if ((appearance.activity_status & ACTIVITY_STATUS_AFK) > 0)
  2355. temp_activity_status += ACTIVITY_STATUS_AFK_561;
  2356. if (EngagedInCombat())
  2357. temp_activity_status += ACTIVITY_STATUS_INCOMBAT_561;
  2358. // if this is either a boat or lift let the client be manipulated by the object
  2359. // doesn't work for DoF client version 546
  2360. if (appearance.icon == 28 || appearance.icon == 12 || IsTransportSpawn())
  2361. {
  2362. // there is some other flags that setting with a transport breaks their solidity/ability to properly transport
  2363. // thus we just consider the following flags for now as all necessary
  2364. temp_activity_status = ACTIVITY_STATUS_SOLID_561;
  2365. temp_activity_status += ACTIVITY_STATUS_ISTRANSPORT_561;
  2366. }
  2367. }
  2368. else
  2369. {
  2370. temp_activity_status = appearance.activity_status;
  2371. if(IsNPC())
  2372. temp_activity_status = 0xFF;
  2373. // this only partially fixes lifts in classic 283 client if you move just as the lift starts to move
  2374. if (appearance.icon == 28 || appearance.icon == 12)
  2375. packet->setDataByName("is_transport", 1);
  2376. if (MeetsSpawnAccessRequirements(spawn))
  2377. packet->setDataByName("hand_icon", appearance.display_hand_icon);
  2378. else {
  2379. if ((req_quests_override & 256) > 0)
  2380. packet->setDataByName("hand_icon", 1);
  2381. }
  2382. if (IsPlayer()) {
  2383. if (((Player*)this)->get_character_flag(CF_AFK))
  2384. packet->setDataByName("afk", 1);
  2385. if ((appearance.activity_status & ACTIVITY_STATUS_ROLEPLAYING) > 0)
  2386. packet->setDataByName("roleplaying", 1);
  2387. if ((appearance.activity_status & ACTIVITY_STATUS_ANONYMOUS) > 0)
  2388. packet->setDataByName("anonymous", 1);
  2389. if ((appearance.activity_status & ACTIVITY_STATUS_LINKDEAD) > 0)
  2390. packet->setDataByName("linkdead", 1);
  2391. if ((appearance.activity_status & ACTIVITY_STATUS_CAMPING) > 0)
  2392. packet->setDataByName("camping", 1);
  2393. if ((appearance.activity_status & ACTIVITY_STATUS_LFG) > 0)
  2394. packet->setDataByName("lfg", 1);
  2395. }
  2396. if (EngagedInCombat()) {
  2397. packet->setDataByName("auto_attack", 1);
  2398. }
  2399. if ((appearance.activity_status & ACTIVITY_STATUS_SOLID) > 0)
  2400. packet->setDataByName("solid_object", 1);
  2401. }
  2402. packet->setDataByName("activity_status", temp_activity_status); //appearance.activity_status);
  2403. // If player and player has a follow target
  2404. /* Jan 2021 Note!! Setting follow_target 0xFFFFFFFF has the result in causing strange behavior in swimming. Targetting a mob makes you focus down to its swim level, unable to swim above it.
  2405. ** in the same respect the player will drop like a rock to the bottom of the ocean (seems to be when self set to that flag?)
  2406. ** for now disabling this, if DoF needs it enabled for whatever reason then we need a version check added.
  2407. */
  2408. if (IsPlayer()) {
  2409. if (((Player*)this)->GetFollowTarget())
  2410. packet->setDataByName("follow_target", version <= 561 ? (((Player*)this)->GetIDWithPlayerSpawn(((Player*)this)->GetFollowTarget())) : ((((Player*)this)->GetIDWithPlayerSpawn(((Player*)this)->GetFollowTarget()) * -1) - 1));
  2411. else if(version <= 561) {
  2412. packet->setDataByName("follow_target", 0xFFFFFFFF);
  2413. }
  2414. //else
  2415. // packet->setDataByName("follow_target", 0xFFFFFFFF);
  2416. }
  2417. //else if (!IsPet()) {
  2418. // packet->setDataByName("follow_target", 0xFFFFFFFF);
  2419. //}
  2420. // i think this is used in DoF as a way to make a client say they are in combat with this target and cannot camp, it forces you to stand up if self spawn sends this data
  2421. if ((version > 561 || spawn != this) && GetTarget() && GetTarget()->GetTargetable())
  2422. packet->setDataByName("target_id", ((spawn->GetIDWithPlayerSpawn(GetTarget()) * -1) - 1));
  2423. else
  2424. packet->setDataByName("target_id", 0xFFFFFFFF);
  2425. //Send spell effects for target window
  2426. if(IsEntity()){
  2427. InfoStruct* info = ((Entity*)this)->GetInfoStruct();
  2428. int8 i = 0;
  2429. int16 backdrop = 0;
  2430. int16 spell_icon = 0;
  2431. int32 spell_id = 0;
  2432. LuaSpell* spell = 0;
  2433. ((Entity*)this)->GetSpellEffectMutex()->readlock(__FUNCTION__, __LINE__);
  2434. while(i < 30){
  2435. //Change value of spell id for this packet if spell exists
  2436. spell_id = info->spell_effects[i].spell_id;
  2437. if(spell_id > 0)
  2438. spell_id = 0xFFFFFFFF - spell_id;
  2439. else
  2440. spell_id = 0;
  2441. packet->setSubstructDataByName("spell_effects", "spell_id", spell_id, i);
  2442. //Change value of spell icon for this packet if spell exists
  2443. spell_icon = info->spell_effects[i].icon;
  2444. if(spell_icon > 0){
  2445. if(!(spell_icon == 0xFFFF))
  2446. spell_icon = 0xFFFF - spell_icon;
  2447. }
  2448. else
  2449. spell_icon = 0;
  2450. packet->setSubstructDataByName("spell_effects", "spell_icon", spell_icon, i);
  2451. //Change backdrop values to match values in this packet
  2452. backdrop = info->spell_effects[i].icon_backdrop;
  2453. switch(backdrop){
  2454. case 312:
  2455. backdrop = 33080;
  2456. break;
  2457. case 313:
  2458. backdrop = 33081;
  2459. break;
  2460. case 314:
  2461. backdrop = 33082;
  2462. break;
  2463. case 315:
  2464. backdrop = 33083;
  2465. break;
  2466. case 316:
  2467. backdrop = 33084;
  2468. break;
  2469. case 317:
  2470. backdrop = 33085;
  2471. break;
  2472. case (318 || 319):
  2473. backdrop = 33086;
  2474. break;
  2475. default:
  2476. break;
  2477. }
  2478. packet->setSubstructDataByName("spell_effects", "spell_icon_backdrop", backdrop, i);
  2479. spell = info->spell_effects[i].spell;
  2480. if (spell)
  2481. packet->setSubstructDataByName("spell_effects", "spell_triggercount", spell->num_triggers, i);
  2482. i++;
  2483. }
  2484. ((Entity*)this)->GetSpellEffectMutex()->releasereadlock(__FUNCTION__, __LINE__);
  2485. }
  2486. }
  2487. void Spawn::MoveToLocation(Spawn* spawn, float distance, bool immediate, bool mapped){
  2488. if(!spawn)
  2489. return;
  2490. SetRunningTo(spawn);
  2491. FaceTarget(spawn, false);
  2492. if (!IsPlayer() && distance > 0.0f)
  2493. {
  2494. if ((IsFlyingCreature() || IsWaterCreature() || InWater()) && CheckLoS(spawn))
  2495. {
  2496. if (immediate)
  2497. ClearRunningLocations();
  2498. AddRunningLocation(spawn->GetX(), spawn->GetY(), spawn->GetZ(), GetSpeed(), distance, true, true, "", true);
  2499. }
  2500. else if (/*!mapped && */GetZone())
  2501. {
  2502. GetZone()->movementMgr->NavigateTo((Entity*)this, spawn->GetX(), spawn->GetY(), spawn->GetZ());
  2503. last_grid_update = Timer::GetCurrentTime2();
  2504. }
  2505. else
  2506. {
  2507. if (immediate)
  2508. ClearRunningLocations();
  2509. AddRunningLocation(spawn->GetX(), spawn->GetY(), spawn->GetZ(), GetSpeed(), distance, true, true, "", mapped);
  2510. }
  2511. }
  2512. }
  2513. void Spawn::ProcessMovement(bool isSpawnListLocked){
  2514. CheckProximities();
  2515. if(IsBot() && ((Bot*)this)->IsCamping()) {
  2516. ((Bot*)this)->Begin_Camp();
  2517. }
  2518. if(IsPlayer()){
  2519. //Check if player is riding a boat, if so update pos (boat's current location + XYZ offsets)
  2520. Player* player = ((Player*)this);
  2521. int32 boat_id = player->GetBoatSpawn();
  2522. Spawn* boat = 0;
  2523. if(boat_id > 0)
  2524. boat = GetZone()->GetSpawnByID(boat_id, isSpawnListLocked);
  2525. //TODO: MAYBE do this for real boats, not lifts... GetWidgetTypeNameByTypeID
  2526. /*if(boat){
  2527. SetX(boat->GetX() + player->GetBoatX());
  2528. SetY(boat->GetY() + player->GetBoatY());
  2529. SetZ(boat->GetZ() + player->GetBoatZ());
  2530. }*/
  2531. return;
  2532. }
  2533. if(IsKnockedBack()) {
  2534. if(CalculateSpawnProjectilePosition(GetX(), GetY(), GetZ()))
  2535. return; // being launched!
  2536. }
  2537. if(reset_movement) {
  2538. ResetMovement();
  2539. reset_movement = false;
  2540. }
  2541. if (forceMapCheck && GetZone() != nullptr && GetMap() != nullptr && GetMap()->IsMapLoaded())
  2542. {
  2543. FixZ(true);
  2544. forceMapCheck = false;
  2545. }
  2546. if (GetHP() <= 0 && !IsWidget())
  2547. return;
  2548. if (EngagedInCombat())
  2549. {
  2550. if(IsEntity() && (((Entity*)this)->IsMezzedOrStunned() || ((Entity*)this)->IsRooted())) {
  2551. SetAppearancePosition(GetX(),GetY(),GetZ());
  2552. if ( IsEntity() )
  2553. ((Entity*)this)->SetSpeed(0.0f);
  2554. SetSpeed(0.0f);
  2555. position_changed = true;
  2556. changed = true;
  2557. GetZone()->AddChangedSpawn(this);
  2558. StopMovement();
  2559. return;
  2560. }
  2561. int locations = 0;
  2562. MMovementLocations.lock_shared();
  2563. if (movement_locations) {
  2564. locations = movement_locations->size();
  2565. }
  2566. MMovementLocations.unlock_shared();
  2567. if (locations < 1 && GetZone() && ((Entity*)this)->IsFeared())
  2568. {
  2569. CalculateNewFearpoint();
  2570. ValidateRunning(true, true);
  2571. }
  2572. }
  2573. Spawn* followTarget = GetZone()->GetSpawnByID(m_followTarget, isSpawnListLocked);
  2574. if (!followTarget && m_followTarget > 0)
  2575. m_followTarget = 0;
  2576. if (following && !IsPauseMovementTimerActive() && followTarget && !((Entity*)this)->IsFeared()) {
  2577. // Need to clear m_followTarget before the zoneserver deletes it
  2578. if (followTarget->GetHP() <= 0) {
  2579. followTarget = 0;
  2580. return;
  2581. }
  2582. if (!IsEntity() || (!((Entity*)this)->IsCasting() && !((Entity*)this)->IsMezzedOrStunned() && !((Entity*)this)->IsRooted())) {
  2583. if (GetBaseSpeed() > 0) {
  2584. CalculateRunningLocation();
  2585. }
  2586. else {
  2587. float speed = 4.0f;
  2588. if (IsEntity())
  2589. speed = ((Entity*)this)->GetMaxSpeed();
  2590. if (IsEntity())
  2591. ((Entity*)this)->SetSpeed(speed);
  2592. SetSpeed(speed);
  2593. }
  2594. MovementLocation tmpLoc;
  2595. MovementLocation* loc = 0;
  2596. MMovementLocations.lock_shared();
  2597. if(movement_locations && movement_locations->size() > 0){
  2598. loc = movement_locations->front();
  2599. if(loc) {
  2600. tmpLoc.attackable = loc->attackable;
  2601. tmpLoc.gridid = loc->gridid;
  2602. tmpLoc.lua_function = string(loc->lua_function);
  2603. tmpLoc.mapped = loc->mapped;
  2604. tmpLoc.reset_hp_on_runback = loc->reset_hp_on_runback;
  2605. tmpLoc.speed = loc->speed;
  2606. tmpLoc.stage = loc->stage;
  2607. tmpLoc.x = loc->x;
  2608. tmpLoc.y = loc->y;
  2609. tmpLoc.z = loc->z;
  2610. loc = &tmpLoc;
  2611. }
  2612. }
  2613. MMovementLocations.unlock_shared();
  2614. float dist = GetDistance(followTarget, true);
  2615. if ((!EngagedInCombat() && m_followDistance > 0 && dist <= m_followDistance) ||
  2616. (dist <= rule_manager.GetGlobalRule(R_Combat, MaxCombatRange)->GetFloat())) {
  2617. ClearRunningLocations();
  2618. CalculateRunningLocation(true);
  2619. }
  2620. else if (loc) {
  2621. float distance = GetDistance(followTarget, loc->x, loc->y, loc->z);
  2622. if ( (!EngagedInCombat() && m_followDistance > 0 && distance > m_followDistance) ||
  2623. ( EngagedInCombat() && distance > rule_manager.GetGlobalRule(R_Combat, MaxCombatRange)->GetFloat())) {
  2624. MoveToLocation(followTarget, rule_manager.GetGlobalRule(R_Combat, MaxCombatRange)->GetFloat(), true, loc->mapped);
  2625. CalculateRunningLocation();
  2626. }
  2627. }
  2628. else {
  2629. MoveToLocation(followTarget, rule_manager.GetGlobalRule(R_Combat, MaxCombatRange)->GetFloat(), false);
  2630. CalculateRunningLocation();
  2631. }
  2632. }
  2633. }
  2634. bool movementCase = false;
  2635. // Movement loop is only for scripted paths
  2636. if(!EngagedInCombat() && !IsPauseMovementTimerActive() && !NeedsToResumeMovement() && (!IsNPC() || !((NPC*)this)->m_runningBack)){
  2637. MMovementLoop.writelock();
  2638. if(movement_loop.size() > 0 && movement_index < movement_loop.size())
  2639. {
  2640. movementCase = true;
  2641. // Get the target location
  2642. MovementData* data = movement_loop[movement_index];
  2643. // need to resume our movement
  2644. if(resume_movement){
  2645. MMovementLocations.lock();
  2646. if (movement_locations){
  2647. while (movement_locations->size()){
  2648. safe_delete(movement_locations->front());
  2649. movement_locations->pop_front();
  2650. }
  2651. movement_locations->clear();
  2652. }
  2653. MMovementLocations.unlock();
  2654. data = movement_loop[movement_index];
  2655. if(data)
  2656. {
  2657. if(IsEntity()) {
  2658. ((Entity*)this)->SetSpeed(data->speed);
  2659. }
  2660. SetSpeed(data->speed);
  2661. if(data->use_movement_location_heading)
  2662. SetHeading(data->heading);
  2663. else if(!IsWidget())
  2664. FaceTarget(data->x, data->z);
  2665. // 0 delay at target location, need to set multiple locations
  2666. if(data->delay == 0 && movement_loop.size() > 0) {
  2667. int16 tmp_index = movement_index+1;
  2668. MovementData* data2 = 0;
  2669. if(tmp_index < movement_loop.size())
  2670. data2 = movement_loop[tmp_index];
  2671. else
  2672. data2 = movement_loop[0];
  2673. AddRunningLocation(data->x, data->y, data->z, data->speed, 0, true, false, "", true);
  2674. AddRunningLocation(data2->x, data2->y, data2->z, data2->speed, 0, true, true, "", true);
  2675. }
  2676. // delay at target location, only need to set 1 location
  2677. else
  2678. AddRunningLocation(data->x, data->y, data->z, data->speed);
  2679. }
  2680. movement_start_time = 0;
  2681. resume_movement = false;
  2682. }
  2683. // If we are not moving or we have arrived at our destination
  2684. else if(!IsRunning() || (data && data->x == GetX() && data->y == GetY() && data->z == GetZ())){
  2685. // If we were moving remove the last running location (the point we just arrived at)
  2686. if(IsRunning())
  2687. RemoveRunningLocation();
  2688. // If this waypoint has a delay and we just arrived here (movement_start_time == 0)
  2689. if(data && data->delay > 0 && movement_start_time == 0){
  2690. // Set the current time
  2691. movement_start_time = Timer::GetCurrentTime2();
  2692. // If this waypoint had a lua function then call it
  2693. if(data->lua_function.length() > 0)
  2694. GetZone()->CallSpawnScript(this, SPAWN_SCRIPT_CUSTOM, 0, data->lua_function.c_str());
  2695. int16 nextMove;
  2696. if ((int16)(movement_index + 1) < movement_loop.size())
  2697. nextMove = movement_index + 1;
  2698. else
  2699. nextMove = 0;
  2700. // Get the next target location
  2701. data = movement_loop[nextMove];
  2702. //Go ahead and face the next location
  2703. if(data)
  2704. FaceTarget(data->x, data->z);
  2705. }
  2706. // If this waypoint has no delay or we have waited the required time (current time >= delay + movement_start_time)
  2707. else if(data && data->delay == 0 || (data && data->delay > 0 && Timer::GetCurrentTime2() >= (data->delay+movement_start_time))) {
  2708. // if no delay at this waypoint but a lua function for it then call the function
  2709. if(data->delay == 0 && data->lua_function.length() > 0)
  2710. GetZone()->CallSpawnScript(this, SPAWN_SCRIPT_CUSTOM, 0, data->lua_function.c_str());
  2711. // since we ran a lua function make sure the movement loop is still alive and accurate
  2712. if(movement_loop.size() > 0)
  2713. {
  2714. // Advance the current movement loop index
  2715. if((int16)(movement_index+1) < movement_loop.size())
  2716. movement_index++;
  2717. else
  2718. movement_index = 0;
  2719. // Get the next target location
  2720. data = movement_loop[movement_index];
  2721. // set the speed for that location
  2722. SetSpeed(data->speed);
  2723. if(!IsWidget())
  2724. // turn towards the location
  2725. FaceTarget(data->x, data->z);
  2726. // If 0 delay at location get and set data for the point after it
  2727. if(data->delay == 0 && movement_loop.size() > 0){
  2728. MMovementLocations.lock();
  2729. if(movement_locations)
  2730. {
  2731. while (movement_locations->size()){
  2732. safe_delete(movement_locations->front());
  2733. movement_locations->pop_front();
  2734. }
  2735. // clear current target locations
  2736. movement_locations->clear();
  2737. }
  2738. MMovementLocations.unlock();
  2739. // get the data for the location after out new location
  2740. int16 tmp_index = movement_index+1;
  2741. MovementData* data2 = 0;
  2742. if(tmp_index < movement_loop.size())
  2743. data2 = movement_loop[tmp_index];
  2744. else
  2745. data2 = movement_loop[0];
  2746. // set the first location (adds it to movement_locations that we just cleared)
  2747. AddRunningLocation(data->x, data->y, data->z, data->speed, 0, true, false, "", true);
  2748. // set the location after that
  2749. AddRunningLocation(data2->x, data2->y, data2->z, data2->speed, 0, true, true, "", true);
  2750. }
  2751. // there is a delay at the next location so we only need to set it
  2752. else
  2753. AddRunningLocation(data->x, data->y, data->z, data->speed, 0, true, true, "", true);
  2754. // reset this timer to 0 now that we are moving again
  2755. movement_start_time = 0;
  2756. }
  2757. }
  2758. }
  2759. // moving and not at target location yet
  2760. else if(GetBaseSpeed() > 0)
  2761. CalculateRunningLocation();
  2762. // not moving, have a target location but not at it yet
  2763. else if (data) {
  2764. SetSpeed(data->speed);
  2765. AddRunningLocation(data->x, data->y, data->z, data->speed);
  2766. }
  2767. }
  2768. MMovementLoop.releasewritelock();
  2769. }
  2770. if (!movementCase && IsRunning() && !IsPauseMovementTimerActive()) {
  2771. CalculateRunningLocation();
  2772. //last_movement_update = Timer::GetCurrentTime2();
  2773. }
  2774. else if(movementCase)
  2775. {
  2776. //last_movement_update = Timer::GetCurrentTime2();
  2777. }
  2778. /*else if (IsNPC() && !IsRunning() && !EngagedInCombat() && ((NPC*)this)->GetRunbackLocation()) {
  2779. // Is an npc that is not moving and not engaged in combat but has a run back location set then clear the runback location
  2780. LogWrite(NPC_AI__DEBUG, 7, "NPC_AI", "Clear runback location for %s", GetName());
  2781. ((NPC*)this)->ClearRunback();
  2782. resume_movement = true;
  2783. NeedsToResumeMovement(false);
  2784. }*/
  2785. }
  2786. void Spawn::ResetMovement(){
  2787. MMovementLoop.writelock();
  2788. vector<MovementData*>::iterator itr;
  2789. for(itr = movement_loop.begin(); itr != movement_loop.end(); itr++){
  2790. safe_delete(*itr);
  2791. }
  2792. movement_loop.clear();
  2793. movement_index = 0;
  2794. resume_movement = true;
  2795. ClearRunningLocations();
  2796. MMovementLoop.releasewritelock();
  2797. ValidateRunning(true, true);
  2798. }
  2799. void Spawn::AddMovementLocation(float x, float y, float z, float speed, int16 delay, const char* lua_function, float heading, bool include_heading){
  2800. LogWrite(LUA__DEBUG, 5, "LUA", "AddMovementLocation: x: %.2f, y: %.2f, z: %.2f, speed: %.2f, delay: %i, lua: %s",
  2801. x, y, z, speed, delay, string(lua_function).c_str());
  2802. MovementData* data = new MovementData;
  2803. data->x = x;
  2804. data->y = y;
  2805. data->z = z;
  2806. data->speed = speed;
  2807. data->delay = delay*1000;
  2808. if(lua_function)
  2809. data->lua_function = string(lua_function);
  2810. data->heading = heading;
  2811. data->use_movement_location_heading = include_heading;
  2812. MMovementLoop.lock();
  2813. movement_loop.push_back(data);
  2814. MMovementLoop.unlock();
  2815. }
  2816. bool Spawn::ValidateRunning(bool lockMovementLocation, bool lockMovementLoop) {
  2817. bool movement = false;
  2818. if(lockMovementLocation) {
  2819. MMovementLocations.lock_shared();
  2820. }
  2821. if(movement_locations) {
  2822. movement = movement_locations->size() > 0;
  2823. }
  2824. if(lockMovementLocation) {
  2825. MMovementLocations.unlock_shared();
  2826. }
  2827. if(IsPauseMovementTimerActive() || (IsEntity() && (((Entity*)this)->IsMezzedOrStunned() || ((Entity*)this)->IsRooted()))) {
  2828. is_running = false;
  2829. return false;
  2830. }
  2831. if(movement) {
  2832. is_running = true;
  2833. return true;
  2834. }
  2835. if(lockMovementLoop) {
  2836. MMovementLoop.lock();
  2837. }
  2838. movement = movement_loop.size() > 0;
  2839. if(movement) {
  2840. is_running = true;
  2841. }
  2842. else {
  2843. is_running = false;
  2844. }
  2845. if(lockMovementLoop) {
  2846. MMovementLoop.unlock();
  2847. }
  2848. return movement;
  2849. }
  2850. bool Spawn::IsRunning(){
  2851. return is_running;
  2852. }
  2853. void Spawn::RunToLocation(float x, float y, float z, float following_x, float following_y, float following_z){
  2854. if(IsPauseMovementTimerActive() || (IsEntity() && (((Entity*)this)->IsMezzedOrStunned() || ((Entity*)this)->IsRooted()))) {
  2855. is_running = false;
  2856. return;
  2857. }
  2858. if(!IsWidget())
  2859. FaceTarget(x, z);
  2860. SetPos(&appearance.pos.X2, x, false);
  2861. SetPos(&appearance.pos.Z2, z, false);
  2862. SetPos(&appearance.pos.Y2, y, false);
  2863. if(following_x == 0 && following_y == 0 && following_z == 0){
  2864. SetPos(&appearance.pos.X3, x, false);
  2865. SetPos(&appearance.pos.Z3, z, false);
  2866. SetPos(&appearance.pos.Y3, y, false);
  2867. }
  2868. else{
  2869. SetPos(&appearance.pos.X3, following_x, false);
  2870. SetPos(&appearance.pos.Y3, following_y, false);
  2871. SetPos(&appearance.pos.Z3, following_z, false);
  2872. }
  2873. is_running = true;
  2874. position_changed = true;
  2875. changed = true;
  2876. GetZone()->AddChangedSpawn(this);
  2877. }
  2878. MovementLocation* Spawn::GetCurrentRunningLocation(){
  2879. MovementLocation* ret = 0;
  2880. MMovementLocations.lock_shared();
  2881. if(movement_locations && movement_locations->size() > 0){
  2882. ret = movement_locations->front();
  2883. }
  2884. MMovementLocations.unlock_shared();
  2885. return ret;
  2886. }
  2887. MovementLocation* Spawn::GetLastRunningLocation(){
  2888. MovementLocation* ret = 0;
  2889. MMovementLocations.lock_shared();
  2890. if(movement_locations && movement_locations->size() > 0){
  2891. ret = movement_locations->back();
  2892. }
  2893. MMovementLocations.unlock_shared();
  2894. return ret;
  2895. }
  2896. void Spawn::AddRunningLocation(float x, float y, float z, float speed, float distance_away, bool attackable, bool finished_adding_locations, string lua_function, bool isMapped){
  2897. if(speed == 0)
  2898. return;
  2899. if ( IsEntity() )
  2900. ((Entity*)this)->SetSpeed(speed);
  2901. else
  2902. this->SetSpeed(speed);
  2903. MovementLocation* current_location = 0;
  2904. float distance = GetDistance(x, y, z, distance_away != 0);
  2905. if(distance_away != 0){
  2906. distance -= distance_away;
  2907. x = x - (GetX() - x)*distance_away/distance;
  2908. z = z - (GetZ() - z)*distance_away/distance;
  2909. }
  2910. MMovementLocations.lock();
  2911. if(!movement_locations){
  2912. movement_locations = new deque<MovementLocation*>();
  2913. }
  2914. MMovementLocations.unlock();
  2915. MovementLocation* data = new MovementLocation;
  2916. data->mapped = isMapped;
  2917. data->x = x;
  2918. data->y = y;
  2919. data->z = z;
  2920. data->speed = speed;
  2921. data->attackable = attackable;
  2922. data->lua_function = lua_function;
  2923. data->gridid = 0; // used for runback defaults
  2924. data->reset_hp_on_runback = false;
  2925. MMovementLocations.lock_shared();
  2926. if(movement_locations->size() > 0)
  2927. current_location = movement_locations->back();
  2928. MMovementLocations.unlock_shared();
  2929. if(!current_location){
  2930. SetSpawnOrigX(GetX());
  2931. SetSpawnOrigY(GetY());
  2932. SetSpawnOrigZ(GetZ());
  2933. SetSpawnOrigHeading(GetHeading());
  2934. }
  2935. is_running = true;
  2936. MMovementLocations.lock();
  2937. movement_locations->push_back(data);
  2938. MMovementLocations.unlock();
  2939. if(!IsPauseMovementTimerActive() && finished_adding_locations){
  2940. MMovementLocations.lock();
  2941. current_location = movement_locations->front();
  2942. SetSpeed(current_location->speed);
  2943. if(movement_locations->size() > 1){
  2944. data = movement_locations->at(1);
  2945. RunToLocation(current_location->x, current_location->y, current_location->z, data->x, data->y, data->z);
  2946. }
  2947. else
  2948. RunToLocation(current_location->x, current_location->y, current_location->z, 0, 0, 0);
  2949. MMovementLocations.unlock();
  2950. }
  2951. }
  2952. bool Spawn::RemoveRunningLocation(){
  2953. bool ret = false;
  2954. MMovementLocations.lock();
  2955. if(movement_locations && movement_locations->size() > 0){
  2956. delete movement_locations->front();
  2957. movement_locations->pop_front();
  2958. ret = true;
  2959. }
  2960. MMovementLocations.unlock();
  2961. ValidateRunning(true, false);
  2962. return ret;
  2963. }
  2964. void Spawn::ClearRunningLocations(){
  2965. while(RemoveRunningLocation()){}
  2966. }
  2967. void Spawn::NewWaypointChange(MovementLocation* data){
  2968. if(data){
  2969. if(NeedsToResumeMovement()){
  2970. resume_movement = true;
  2971. NeedsToResumeMovement(false);
  2972. }
  2973. if(!data->attackable)
  2974. SetHeading(GetSpawnOrigHeading());
  2975. }
  2976. if (data && data->lua_function.length() > 0)
  2977. GetZone()->CallSpawnScript(this, SPAWN_SCRIPT_CUSTOM, 0, data->lua_function.c_str());
  2978. RemoveRunningLocation();
  2979. }
  2980. bool Spawn::CalculateChange(){
  2981. bool remove_needed = false;
  2982. MovementLocation* data = 0;
  2983. MovementLocation tmpLoc;
  2984. MMovementLocations.lock_shared();
  2985. if(movement_locations){
  2986. if(movement_locations->size() > 0){
  2987. // Target location
  2988. data = movement_locations->front();
  2989. if(data) {
  2990. tmpLoc.attackable = data->attackable;
  2991. tmpLoc.gridid = data->gridid;
  2992. tmpLoc.lua_function = string(data->lua_function);
  2993. tmpLoc.mapped = data->mapped;
  2994. tmpLoc.reset_hp_on_runback = data->reset_hp_on_runback;
  2995. tmpLoc.speed = data->speed;
  2996. tmpLoc.stage = data->stage;
  2997. tmpLoc.x = data->x;
  2998. tmpLoc.y = data->y;
  2999. tmpLoc.z = data->z;
  3000. data = &tmpLoc;
  3001. }
  3002. // If no target or we are at the target location need to remove this point
  3003. if(!data || (data->x == GetX() && data->y == GetY() && data->z == GetZ()))
  3004. remove_needed = true;
  3005. }
  3006. }
  3007. MMovementLocations.unlock_shared();
  3008. if(remove_needed){
  3009. NewWaypointChange(data);
  3010. }
  3011. else if(data){
  3012. // Speed is per second so we need a time_step (amount of time since the last update) to modify movement by
  3013. float time_step = (Timer::GetCurrentTime2() - last_movement_update) * 0.001; // * 0.001 is the same as / 1000, float muliplications is suppose to be faster though
  3014. // Get current location
  3015. float nx = GetX();
  3016. float ny = GetY();
  3017. float nz = GetZ();
  3018. // Get Forward vecotr
  3019. float tar_vx = data->x - nx;
  3020. float tar_vy = data->y - ny;
  3021. float tar_vz = data->z - nz;
  3022. // Multiply speed by the time_step to get how much should have changed over the last tick
  3023. float speed = GetSpeed() * time_step;
  3024. // Normalize the forward vector and multiply by speed, this gives us our change in coords, just need to add them to our current coords
  3025. float len = sqrtf(tar_vx * tar_vx + tar_vy * tar_vy + tar_vz * tar_vz);
  3026. tar_vx = (tar_vx / len) * speed;
  3027. tar_vy = (tar_vy / len) * speed;
  3028. tar_vz = (tar_vz / len) * speed;
  3029. // Distance less then 0.5 just set the npc to the target location
  3030. if (GetDistance(data->x, data->y, data->z, IsWidget() ? false : true) <= speed) {
  3031. SetX(data->x, false);
  3032. SetZ(data->z, false);
  3033. SetY(data->y, false, true);
  3034. remove_needed = true;
  3035. NewWaypointChange(data);
  3036. }
  3037. else {
  3038. SetX(nx + tar_vx, false);
  3039. SetZ(nz + tar_vz, false);
  3040. if ( IsWidget() )
  3041. SetY(ny + tar_vy, false, true);
  3042. else
  3043. SetY(ny + tar_vy, false);
  3044. }
  3045. int32 newGrid = GetLocation();
  3046. if (GetMap() != nullptr) {
  3047. m_GridMutex.writelock(__FUNCTION__, __LINE__);
  3048. std::map<int32,TimedGridData>::iterator itr = established_grid_id.begin();
  3049. if ( itr == established_grid_id.end() || itr->second.timestamp <= (Timer::GetCurrentTime2()))
  3050. {
  3051. if(itr != established_grid_id.end() && itr->second.x == GetX() && itr->second.z == GetZ()) {
  3052. itr->second.timestamp = Timer::GetCurrentTime2()+1000;
  3053. itr->second.npc_save = true;
  3054. newGrid = itr->second.grid_id;
  3055. }
  3056. else {
  3057. auto loc = glm::vec3(GetX(), GetZ(), GetY());
  3058. float new_z = FindBestZ(loc, nullptr, &newGrid);
  3059. TimedGridData data;
  3060. data.grid_id = newGrid;
  3061. data.x = GetX();
  3062. data.y = GetY();
  3063. data.z = GetZ();
  3064. data.npc_save = true;
  3065. data.timestamp = Timer::GetCurrentTime2()+1000;
  3066. established_grid_id.insert(make_pair(0, data));
  3067. }
  3068. }
  3069. else
  3070. newGrid = itr->second.grid_id;
  3071. m_GridMutex.releasewritelock(__FUNCTION__, __LINE__);
  3072. }
  3073. if ((!IsFlyingCreature() || IsTransportSpawn()) && newGrid != 0 && newGrid != GetLocation())
  3074. SetLocation(newGrid);
  3075. }
  3076. return remove_needed;
  3077. }
  3078. void Spawn::CalculateRunningLocation(bool stop){
  3079. bool pauseTimerEnabled = IsPauseMovementTimerActive();
  3080. if (!pauseTimerEnabled && !stop && (last_location_update + 100) > Timer::GetCurrentTime2())
  3081. return;
  3082. else if (!pauseTimerEnabled && !stop)
  3083. last_location_update = Timer::GetCurrentTime2();
  3084. bool continueElseIf = true;
  3085. bool removed = CalculateChange();
  3086. if (stop || pauseTimerEnabled) {
  3087. //following = false;
  3088. SetPos(&appearance.pos.X2, GetX(), false);
  3089. SetPos(&appearance.pos.Y2, GetY(), false);
  3090. SetPos(&appearance.pos.Z2, GetZ(), false);
  3091. SetPos(&appearance.pos.X3, GetX(), false);
  3092. SetPos(&appearance.pos.Y3, GetY(), false);
  3093. SetPos(&appearance.pos.Z3, GetZ(), false);
  3094. continueElseIf = false;
  3095. }
  3096. else if (removed) {
  3097. MMovementLocations.lock_shared();
  3098. if(movement_locations) {
  3099. if(movement_locations->size() > 0) {
  3100. MovementLocation* current_location = movement_locations->at(0);
  3101. if (movement_locations->size() > 1) {
  3102. MovementLocation* data = movement_locations->at(1);
  3103. RunToLocation(current_location->x, current_location->y, current_location->z, data->x, data->y, data->z);
  3104. }
  3105. else
  3106. RunToLocation(current_location->x, current_location->y, current_location->z, 0, 0, 0);
  3107. continueElseIf = false;
  3108. }
  3109. }
  3110. MMovementLocations.unlock_shared();
  3111. }
  3112. if (continueElseIf && GetZone() && GetTarget() != NULL && EngagedInCombat())
  3113. {
  3114. if (GetDistance(GetTarget()) > rule_manager.GetGlobalRule(R_Combat, MaxCombatRange)->GetFloat())
  3115. {
  3116. if ((IsFlyingCreature() || IsWaterCreature() || InWater()) && CheckLoS(GetTarget()))
  3117. AddRunningLocation(GetTarget()->GetX(), GetTarget()->GetY(), GetTarget()->GetZ(), GetSpeed(), 0, false);
  3118. else
  3119. GetZone()->movementMgr->NavigateTo((Entity*)this, GetTarget()->GetX(), GetTarget()->GetY(), GetTarget()->GetZ());
  3120. }
  3121. else
  3122. ((Entity*)this)->HaltMovement();
  3123. }
  3124. else if (continueElseIf && !following)
  3125. {
  3126. position_changed = true;
  3127. changed = true;
  3128. GetZone()->AddChangedSpawn(this);
  3129. }
  3130. }
  3131. float Spawn::GetFaceTarget(float x, float z) {
  3132. float angle;
  3133. double diff_x = x - GetX();
  3134. double diff_z = z - GetZ();
  3135. //If we're very close to the same spot don't bother changing heading
  3136. if (sqrt(diff_x * diff_x * diff_z * diff_z) < .1) {
  3137. return GetHeading();
  3138. }
  3139. if (diff_z == 0) {
  3140. if (diff_x > 0)
  3141. angle = 90;
  3142. else
  3143. angle = 270;
  3144. }
  3145. else
  3146. angle = ((atan(diff_x / diff_z)) * 180) / 3.14159265358979323846;
  3147. if (angle < 0)
  3148. angle = angle + 360;
  3149. else
  3150. angle = angle + 180;
  3151. if (diff_x < 0)
  3152. angle = angle + 180;
  3153. if (last_heading_angle == angle) return angle;
  3154. return angle;
  3155. }
  3156. void Spawn::FaceTarget(float x, float z){
  3157. float angle;
  3158. double diff_x = x - GetX();
  3159. double diff_z = z - GetZ();
  3160. //If we're very close to the same spot don't bother changing heading
  3161. if (sqrt(diff_x * diff_x * diff_z * diff_z) < .1) {
  3162. return;
  3163. }
  3164. if(diff_z==0){
  3165. if(diff_x > 0)
  3166. angle = 90;
  3167. else
  3168. angle = 270;
  3169. }
  3170. else
  3171. angle = ((atan(diff_x / diff_z)) * 180) / 3.14159265358979323846;
  3172. if(angle < 0)
  3173. angle = angle + 360;
  3174. else
  3175. angle = angle + 180;
  3176. if(diff_x < 0)
  3177. angle = angle + 180;
  3178. if (last_heading_angle == angle) return;
  3179. SetHeading(angle);
  3180. }
  3181. void Spawn::FaceTarget(Spawn* target, bool disable_action_state){
  3182. if(!target)
  3183. return;
  3184. if(GetHP() > 0 && target->IsPlayer() && !EngagedInCombat()){
  3185. if(!IsPet() && disable_action_state) {
  3186. if(IsNPC()) {
  3187. ((NPC*)this)->StartRunback();
  3188. ((NPC*)this)->PauseMovement(30000);
  3189. }
  3190. SetTempActionState(0);
  3191. }
  3192. }
  3193. FaceTarget(target->GetX(), target->GetZ());
  3194. }
  3195. bool Spawn::MeetsSpawnAccessRequirements(Player* player){
  3196. bool ret = false;
  3197. Quest* quest = 0;
  3198. //Check if we meet all quest requirements first..
  3199. m_requiredQuests.readlock(__FUNCTION__, __LINE__);
  3200. if (player && required_quests.size() > 0) {
  3201. map<int32, vector<int16>* >::iterator itr;
  3202. for (itr = required_quests.begin(); itr != required_quests.end(); itr++) {
  3203. player->AddQuestRequiredSpawn(this, itr->first);
  3204. vector<int16>* quest_steps = itr->second;
  3205. for (int32 i = 0; i < quest_steps->size(); i++) {
  3206. quest = player->GetQuest(itr->first);
  3207. if (req_quests_continued_access) {
  3208. if (quest) {
  3209. if (quest->GetQuestStepCompleted(quest_steps->at(i))) {
  3210. ret = true;
  3211. break;
  3212. }
  3213. }
  3214. else if (player->HasQuestBeenCompleted(itr->first)) {
  3215. ret = true;
  3216. break;
  3217. }
  3218. }
  3219. if (quest && quest->QuestStepIsActive(quest_steps->at(i))) {
  3220. ret = true;
  3221. break;
  3222. }
  3223. }
  3224. }
  3225. }
  3226. else
  3227. ret = true;
  3228. m_requiredQuests.releasereadlock(__FUNCTION__, __LINE__);
  3229. if (!ret)
  3230. return ret;
  3231. //Now check if the player meets all history requirements
  3232. m_requiredHistory.readlock(__FUNCTION__, __LINE__);
  3233. if (required_history.size() > 0){
  3234. map<int32, LUAHistory*>::iterator itr;
  3235. for (itr = required_history.begin(); itr != required_history.end(); itr++){
  3236. player->AddHistoryRequiredSpawn(this, itr->first);
  3237. LUAHistory* player_history = player->GetLUAHistory(itr->first);
  3238. if (player_history){
  3239. if (player_history->Value != itr->second->Value || player_history->Value2 != itr->second->Value2)
  3240. ret = false;
  3241. }
  3242. else
  3243. ret = false;
  3244. if (!ret)
  3245. break;
  3246. }
  3247. }
  3248. m_requiredHistory.releasereadlock(__FUNCTION__, __LINE__);
  3249. return ret;
  3250. }
  3251. vector<Spawn*>* Spawn::GetSpawnGroup(){
  3252. vector<Spawn*>* ret_list = 0;
  3253. if(spawn_group_list){
  3254. ret_list = new vector<Spawn*>();
  3255. if(MSpawnGroup)
  3256. MSpawnGroup->readlock(__FUNCTION__, __LINE__);
  3257. ret_list->insert(ret_list->begin(), spawn_group_list->begin(), spawn_group_list->end());
  3258. if(MSpawnGroup)
  3259. MSpawnGroup->releasereadlock(__FUNCTION__, __LINE__);
  3260. }
  3261. return ret_list;
  3262. }
  3263. bool Spawn::HasSpawnGroup() {
  3264. return spawn_group_list && spawn_group_list->size() > 0;
  3265. }
  3266. bool Spawn::IsInSpawnGroup(Spawn* spawn) {
  3267. bool ret = false;
  3268. if (HasSpawnGroup() && spawn) {
  3269. vector<Spawn*>::iterator itr;
  3270. for (itr = spawn_group_list->begin(); itr != spawn_group_list->end(); itr++) {
  3271. if ((*itr) == spawn) {
  3272. ret = true;
  3273. break;
  3274. }
  3275. }
  3276. }
  3277. return ret;
  3278. }
  3279. Spawn* Spawn::IsSpawnGroupMembersAlive(Spawn* ignore_spawn, bool npc_only) {
  3280. Spawn* ret = nullptr;
  3281. if (MSpawnGroup && HasSpawnGroup()) {
  3282. MSpawnGroup->readlock(__FUNCTION__, __LINE__);
  3283. vector<Spawn*>::iterator itr;
  3284. for (itr = spawn_group_list->begin(); itr != spawn_group_list->end(); itr++) {
  3285. if ((*itr) != ignore_spawn && (*itr)->Alive() && (!npc_only || (npc_only && (*itr)->IsNPC()))) {
  3286. ret = (*itr);
  3287. break;
  3288. }
  3289. }
  3290. MSpawnGroup->releasereadlock(__FUNCTION__, __LINE__);
  3291. }
  3292. return ret;
  3293. }
  3294. void Spawn::UpdateEncounterState(int8 new_state) {
  3295. if (MSpawnGroup && HasSpawnGroup()) {
  3296. MSpawnGroup->readlock(__FUNCTION__, __LINE__);
  3297. vector<Spawn*>::iterator itr;
  3298. for (itr = spawn_group_list->begin(); itr != spawn_group_list->end(); itr++) {
  3299. if ((*itr)->Alive() && (*itr)->IsNPC()) {
  3300. NPC* npc = (NPC*)(*itr);
  3301. (*itr)->SetLockedNoLoot(new_state);
  3302. if(new_state == ENCOUNTER_STATE_BROKEN && npc->Brain()) {
  3303. npc->Brain()->ClearEncounter();
  3304. }
  3305. }
  3306. }
  3307. MSpawnGroup->releasereadlock(__FUNCTION__, __LINE__);
  3308. }
  3309. }
  3310. void Spawn::CheckEncounterState(Entity* victim, bool test_auto_lock) {
  3311. if (!IsEntity() || !victim->IsNPC())
  3312. return;
  3313. Entity* ent = ((Entity*)this);
  3314. if (victim->GetLockedNoLoot() == ENCOUNTER_STATE_AVAILABLE) {
  3315. Entity* attacker = nullptr;
  3316. if (ent->GetOwner())
  3317. attacker = ent->GetOwner();
  3318. else
  3319. attacker = ent;
  3320. bool matchedAutoLock = false;
  3321. if (attacker->IsEntity() && ((Entity*)attacker)->GetGroupMemberInfo()) {
  3322. world.GetGroupManager()->GroupLock(__FUNCTION__, __LINE__);
  3323. GroupMemberInfo* gmi = ((Entity*)attacker)->GetGroupMemberInfo();
  3324. if (gmi && gmi->group_id)
  3325. {
  3326. PlayerGroup* group = world.GetGroupManager()->GetGroup(gmi->group_id);
  3327. if (group && ((group->GetGroupOptions()->group_lock_method && group->GetGroupOptions()->group_autolock == 1) || attacker->GetGroupMemberInfo()->leader))
  3328. {
  3329. matchedAutoLock = true;
  3330. group->MGroupMembers.readlock(__FUNCTION__, __LINE__);
  3331. deque<GroupMemberInfo*>* members = group->GetMembers();
  3332. for (int8 i = 0; i < members->size(); i++) {
  3333. Entity* member = members->at(i)->member;
  3334. if (!member || member->GetZone() != attacker->GetZone())
  3335. continue;
  3336. if (member->IsEntity()) {
  3337. if (!member->GetInfoStruct()->get_engaged_encounter()) {
  3338. member->GetInfoStruct()->set_engaged_encounter(1);
  3339. }
  3340. if (((NPC*)victim)->Brain()) {
  3341. ((NPC*)victim)->Brain()->AddHate(member, 0);
  3342. ((NPC*)victim)->Brain()->AddToEncounter(member);
  3343. victim->AddTargetToEncounter(member);
  3344. }
  3345. }
  3346. }
  3347. group->MGroupMembers.releasereadlock(__FUNCTION__, __LINE__);
  3348. }
  3349. }
  3350. world.GetGroupManager()->ReleaseGroupLock(__FUNCTION__, __LINE__);
  3351. }
  3352. else if (attacker->GetInfoStruct()->get_group_solo_autolock()) {
  3353. matchedAutoLock = true;
  3354. if (((NPC*)victim)->Brain()) {
  3355. ((NPC*)victim)->Brain()->AddHate(attacker, 0);
  3356. ((NPC*)victim)->Brain()->AddToEncounter(attacker);
  3357. victim->AddTargetToEncounter(attacker);
  3358. }
  3359. }
  3360. if (test_auto_lock && !matchedAutoLock) {
  3361. return;
  3362. }
  3363. if (!ent->GetInfoStruct()->get_engaged_encounter()) {
  3364. ent->GetInfoStruct()->set_engaged_encounter(1);
  3365. }
  3366. if (!attacker->GetInfoStruct()->get_engaged_encounter()) {
  3367. attacker->GetInfoStruct()->set_engaged_encounter(1);
  3368. }
  3369. int8 skip_loot_gray_mob_flag = rule_manager.GetGlobalRule(R_Loot, SkipLootGrayMob)->GetInt8();
  3370. int8 difficulty = attacker->GetArrowColor(victim->GetLevel());
  3371. int8 new_enc_state = ENCOUNTER_STATE_AVAILABLE;
  3372. if (skip_loot_gray_mob_flag && difficulty == ARROW_COLOR_GRAY) {
  3373. if (!attacker->IsPlayer() && !attacker->IsBot()) {
  3374. new_enc_state = ENCOUNTER_STATE_BROKEN;
  3375. }
  3376. else {
  3377. new_enc_state = ENCOUNTER_STATE_OVERMATCHED;
  3378. }
  3379. }
  3380. else {
  3381. if (attacker->IsPlayer() || attacker->IsBot()) {
  3382. new_enc_state = ENCOUNTER_STATE_LOCKED;
  3383. }
  3384. else {
  3385. new_enc_state = ENCOUNTER_STATE_BROKEN;
  3386. }
  3387. }
  3388. victim->SetLockedNoLoot(new_enc_state);
  3389. victim->UpdateEncounterState(new_enc_state);
  3390. }
  3391. }
  3392. void Spawn::AddTargetToEncounter(Entity* entity) {
  3393. if (MSpawnGroup && HasSpawnGroup()) {
  3394. MSpawnGroup->readlock(__FUNCTION__, __LINE__);
  3395. vector<Spawn*>::iterator itr;
  3396. for (itr = spawn_group_list->begin(); itr != spawn_group_list->end(); itr++) {
  3397. if ((*itr) != this && (*itr)->Alive() && (*itr)->IsNPC()) {
  3398. ((NPC*)(*itr))->Brain()->AddToEncounter(entity);
  3399. }
  3400. }
  3401. MSpawnGroup->releasereadlock(__FUNCTION__, __LINE__);
  3402. }
  3403. }
  3404. void Spawn::AddSpawnToGroup(Spawn* spawn){
  3405. if(!spawn)
  3406. return;
  3407. if(!spawn_group_list){
  3408. spawn_group_list = new vector<Spawn*>();
  3409. spawn_group_list->push_back(this);
  3410. safe_delete(MSpawnGroup);
  3411. MSpawnGroup = new Mutex();
  3412. MSpawnGroup->SetName("Spawn::MSpawnGroup");
  3413. }
  3414. vector<Spawn*>::iterator itr;
  3415. MSpawnGroup->writelock(__FUNCTION__, __LINE__);
  3416. for(itr = spawn_group_list->begin(); itr != spawn_group_list->end(); itr++){
  3417. if((*itr) == spawn){
  3418. MSpawnGroup->releasewritelock(__FUNCTION__, __LINE__);
  3419. return;
  3420. }
  3421. }
  3422. spawn_group_list->push_back(spawn);
  3423. spawn->SetSpawnGroupList(spawn_group_list, MSpawnGroup);
  3424. MSpawnGroup->releasewritelock(__FUNCTION__, __LINE__);
  3425. }
  3426. void Spawn::SetSpawnGroupList(vector<Spawn*>* list, Mutex* mutex){
  3427. spawn_group_list = list;
  3428. MSpawnGroup = mutex;
  3429. }
  3430. void Spawn::RemoveSpawnFromGroup(bool erase_all){
  3431. SetSpawnGroupID(0);
  3432. bool del = false;
  3433. if(MSpawnGroup){
  3434. MSpawnGroup->writelock(__FUNCTION__, __LINE__);
  3435. if(spawn_group_list){
  3436. vector<Spawn*>::iterator itr;
  3437. Spawn* spawn = 0;
  3438. if(spawn_group_list->size() == 1)
  3439. erase_all = true;
  3440. for(itr = spawn_group_list->begin(); itr != spawn_group_list->end(); itr++){
  3441. spawn = *itr;
  3442. if (spawn) {
  3443. if(!erase_all){
  3444. if(spawn == this){
  3445. spawn_group_list->erase(itr);
  3446. MSpawnGroup->releasewritelock(__FUNCTION__, __LINE__);
  3447. spawn_group_list = 0;
  3448. MSpawnGroup = 0;
  3449. return;
  3450. }
  3451. }
  3452. else{
  3453. if (spawn != this)
  3454. spawn->SetSpawnGroupList(0, 0);
  3455. }
  3456. }
  3457. }
  3458. if (erase_all)
  3459. spawn_group_list->clear();
  3460. del = (spawn_group_list->size() == 0);
  3461. }
  3462. MSpawnGroup->releasewritelock(__FUNCTION__, __LINE__);
  3463. if (del){
  3464. safe_delete(MSpawnGroup);
  3465. safe_delete(spawn_group_list);
  3466. }
  3467. }
  3468. }
  3469. void Spawn::SetSpawnGroupID(int32 id){
  3470. m_SpawnMutex.writelock();
  3471. group_id = id;
  3472. m_SpawnMutex.releasewritelock();
  3473. }
  3474. int32 Spawn::GetSpawnGroupID(){
  3475. int32 groupid = 0;
  3476. m_SpawnMutex.readlock();
  3477. groupid = group_id;
  3478. m_SpawnMutex.releasereadlock();
  3479. return groupid;
  3480. }
  3481. void Spawn::AddChangedZoneSpawn(){
  3482. if(send_spawn_changes && GetZone())
  3483. GetZone()->AddChangedSpawn(this);
  3484. }
  3485. void Spawn::RemoveSpawnAccess(Spawn* spawn) {
  3486. if (allowed_access.count(spawn->GetID()) > 0) {
  3487. allowed_access.erase(spawn->GetID());
  3488. GetZone()->HidePrivateSpawn(this);
  3489. }
  3490. }
  3491. void Spawn::SetFollowTarget(Spawn* spawn, int32 follow_distance) {
  3492. if (spawn && spawn != this) {
  3493. m_followTarget = spawn->GetID();
  3494. m_followDistance = follow_distance;
  3495. }
  3496. else {
  3497. m_followTarget = 0;
  3498. if (following)
  3499. following = false;
  3500. m_followDistance = 0;
  3501. }
  3502. }
  3503. void Spawn::AddTempVariable(string var, string val) {
  3504. m_tempVariableTypes[var] = 5;
  3505. m_tempVariables[var] = val;
  3506. }
  3507. void Spawn::AddTempVariable(string var, Spawn* val) {
  3508. m_tempVariableTypes[var] = 1;
  3509. m_tempVariableSpawn[var] = val->GetID();
  3510. }
  3511. void Spawn::AddTempVariable(string var, ZoneServer* val) {
  3512. m_tempVariableTypes[var] = 2;
  3513. m_tempVariableZone[var] = val;
  3514. }
  3515. void Spawn::AddTempVariable(string var, Item* val) {
  3516. m_tempVariableTypes[var] = 3;
  3517. m_tempVariableItem[var] = val;
  3518. }
  3519. void Spawn::AddTempVariable(string var, Quest* val) {
  3520. m_tempVariableTypes[var] = 4;
  3521. m_tempVariableQuest[var] = val;
  3522. }
  3523. string Spawn::GetTempVariable(string var) {
  3524. string ret = "";
  3525. if (m_tempVariables.count(var) > 0)
  3526. ret = m_tempVariables[var];
  3527. return ret;
  3528. }
  3529. Spawn* Spawn::GetTempVariableSpawn(string var) {
  3530. Spawn* ret = 0;
  3531. if (m_tempVariableSpawn.count(var) > 0)
  3532. ret = GetZone()->GetSpawnByID(m_tempVariableSpawn[var]);
  3533. return ret;
  3534. }
  3535. ZoneServer* Spawn::GetTempVariableZone(string var) {
  3536. ZoneServer* ret = 0;
  3537. if (m_tempVariableZone.count(var) > 0)
  3538. ret = m_tempVariableZone[var];
  3539. return ret;
  3540. }
  3541. Item* Spawn::GetTempVariableItem(string var) {
  3542. Item* ret = 0;
  3543. if (m_tempVariableItem.count(var) > 0)
  3544. ret = m_tempVariableItem[var];
  3545. return ret;
  3546. }
  3547. Quest* Spawn::GetTempVariableQuest(string var) {
  3548. Quest* ret = 0;
  3549. if (m_tempVariableQuest.count(var) > 0)
  3550. ret = m_tempVariableQuest[var];
  3551. return ret;
  3552. }
  3553. int8 Spawn::GetTempVariableType(string var) {
  3554. int8 ret = 0;
  3555. if (m_tempVariableTypes.count(var) > 0)
  3556. ret = m_tempVariableTypes[var];
  3557. return ret;
  3558. }
  3559. void Spawn::DeleteTempVariable(string var) {
  3560. int8 type = GetTempVariableType(var);
  3561. switch (type) {
  3562. case 1:
  3563. m_tempVariableSpawn.erase(var);
  3564. break;
  3565. case 2:
  3566. m_tempVariableZone.erase(var);
  3567. break;
  3568. case 3:
  3569. m_tempVariableItem.erase(var);
  3570. break;
  3571. case 4:
  3572. m_tempVariableQuest.erase(var);
  3573. break;
  3574. case 5:
  3575. m_tempVariables.erase(var);
  3576. break;
  3577. }
  3578. m_tempVariableTypes.erase(var);
  3579. }
  3580. Spawn* Spawn::GetRunningTo() {
  3581. return GetZone()->GetSpawnByID(running_to);
  3582. }
  3583. Spawn* Spawn::GetFollowTarget() {
  3584. return GetZone()->GetSpawnByID(m_followTarget);
  3585. }
  3586. void Spawn::CopySpawnAppearance(Spawn* spawn){
  3587. if (!spawn)
  3588. return;
  3589. //This function copies the appearace of the provided spawn to this one
  3590. if (spawn->IsEntity() && IsEntity()){
  3591. memcpy(&((Entity*)this)->features, &((Entity*)spawn)->features, sizeof(CharFeatures));
  3592. memcpy(&((Entity*)this)->equipment, &((Entity*)spawn)->equipment, sizeof(EQ2_Equipment));
  3593. }
  3594. SetSize(spawn->GetSize());
  3595. SetModelType(spawn->GetModelType());
  3596. }
  3597. void Spawn::SetY(float y, bool updateFlags, bool disableYMapCheck)
  3598. {
  3599. SetPos(&appearance.pos.Y, y, updateFlags);
  3600. if (!disableYMapCheck)
  3601. FixZ();
  3602. }
  3603. float Spawn::FindDestGroundZ(glm::vec3 dest, float z_offset)
  3604. {
  3605. float best_z = BEST_Z_INVALID;
  3606. if (GetZone() != nullptr && GetMap() != nullptr)
  3607. {
  3608. dest.z += z_offset;
  3609. best_z = FindBestZ(dest, nullptr);
  3610. }
  3611. return best_z;
  3612. }
  3613. float Spawn::FindBestZ(glm::vec3 loc, glm::vec3* result, int32* new_grid_id, int32* new_widget_id) {
  3614. std::shared_lock lock(MIgnoredWidgets);
  3615. if(!GetMap())
  3616. return BEST_Z_INVALID;
  3617. float new_z = GetMap()->FindBestZ(loc, nullptr, &ignored_widgets, new_grid_id, new_widget_id);
  3618. return new_z;
  3619. }
  3620. float Spawn::GetFixedZ(const glm::vec3& destination, int32 z_find_offset) {
  3621. BenchTimer timer;
  3622. timer.reset();
  3623. float new_z = destination.z;
  3624. if (GetZone() != nullptr && GetMap() != nullptr) {
  3625. /* if (flymode == GravityBehavior::Flying)
  3626. return new_z;
  3627. */
  3628. /* if (zone->HasWaterMap() && zone->watermap->InLiquid(glm::vec3(m_Position)))
  3629. return new_z;
  3630. */
  3631. /*
  3632. * Any more than 5 in the offset makes NPC's hop/snap to ceiling in small corridors
  3633. */
  3634. new_z = this->FindDestGroundZ(destination, z_find_offset);
  3635. if (new_z != BEST_Z_INVALID) {
  3636. if (new_z < -2000) {
  3637. new_z = GetY();
  3638. }
  3639. }
  3640. auto duration = timer.elapsed();
  3641. LogWrite(MAP__DEBUG, 0, "Map", "Mob::GetFixedZ() ([{%s}]) returned [{%f}] at [{%f}], [{%f}], [{%f}] - Took [{%f}]",
  3642. this->GetName(),
  3643. new_z,
  3644. destination.x,
  3645. destination.y,
  3646. destination.z,
  3647. duration);
  3648. }
  3649. return new_z;
  3650. }
  3651. void Spawn::FixZ(bool forceUpdate) {
  3652. if (!GetZone()) {
  3653. return;
  3654. }
  3655. /*
  3656. if (flymode == GravityBehavior::Flying) {
  3657. return;
  3658. }*/
  3659. /*
  3660. if (zone->watermap && zone->watermap->InLiquid(m_Position)) {
  3661. return;
  3662. }*/
  3663. // we do the inwater check here manually to avoid double calling for a Z coordinate
  3664. glm::vec3 current_loc(GetX(), GetZ(), GetY());
  3665. uint32 GridID = 0;
  3666. uint32 WidgetID = 0;
  3667. float new_z = GetY();
  3668. if(GetMap() != nullptr) {
  3669. new_z = FindBestZ(current_loc, nullptr, &GridID, &WidgetID);
  3670. if ((IsTransportSpawn() || !IsFlyingCreature()) && GridID != 0 && GridID != GetLocation()) {
  3671. LogWrite(PLAYER__DEBUG, 0, "Player", "%s left grid %u and entered grid %u", appearance.name, GetLocation(), GridID);
  3672. const char* zone_script = world.GetZoneScript(GetZone()->GetZoneID());
  3673. if (zone_script && lua_interface) {
  3674. lua_interface->RunZoneScript(zone_script, "leave_location", GetZone(), this, GetLocation());
  3675. }
  3676. SetLocation(GridID);
  3677. if (zone_script && lua_interface) {
  3678. lua_interface->RunZoneScript(zone_script, "enter_location", GetZone(), this, GridID);
  3679. }
  3680. }
  3681. trigger_widget_id = WidgetID;
  3682. }
  3683. // no need to go any further for players, flying creatures or objects, just needed the grid id set
  3684. if (IsPlayer() || IsFlyingCreature() || IsObject()) {
  3685. return;
  3686. }
  3687. if ( region_map != nullptr )
  3688. {
  3689. glm::vec3 targPos(GetX(), GetY(), GetZ());
  3690. if(region_map->InWater(targPos, GetLocation()))
  3691. return;
  3692. }
  3693. if (new_z == GetY())
  3694. return;
  3695. if ((new_z > -2000) && new_z != BEST_Z_INVALID) {
  3696. SetY(new_z, forceUpdate, true);
  3697. }
  3698. else {
  3699. LogWrite(MAP__DEBUG, 0, "Map", "[{%s}] is failing to find Z [{%f}]", this->GetName(), std::abs(GetY() - new_z));
  3700. }
  3701. }
  3702. bool Spawn::CheckLoS(Spawn* target)
  3703. {
  3704. float radiusSrc = 2.0f;
  3705. float radiusTarg = 2.0f;
  3706. glm::vec3 targpos(target->GetX(), target->GetZ(), target->GetY()+radiusTarg);
  3707. glm::vec3 pos(GetX(), GetZ(), GetY()+radiusSrc);
  3708. return CheckLoS(pos, targpos);
  3709. }
  3710. bool Spawn::CheckLoS(glm::vec3 myloc, glm::vec3 oloc)
  3711. {
  3712. bool res = false;
  3713. ZoneServer* zone = GetZone();
  3714. if (zone == NULL || GetMap() == NULL || !GetMap()->IsMapLoaded())
  3715. return true;
  3716. else {
  3717. MIgnoredWidgets.lock_shared();
  3718. res = GetMap()->CheckLoS(myloc, oloc, &ignored_widgets);
  3719. MIgnoredWidgets.unlock_shared();
  3720. }
  3721. return res;
  3722. }
  3723. void Spawn::CalculateNewFearpoint()
  3724. {
  3725. if (GetZone() && GetZone()->pathing) {
  3726. auto Node = zone->pathing->GetRandomLocation(glm::vec3(GetX(), GetZ(), GetY()));
  3727. if (Node.x != 0.0f || Node.y != 0.0f || Node.z != 0.0f) {
  3728. AddRunningLocation(Node.x, Node.y, Node.z, GetSpeed(), 0, true, true, "", true);
  3729. }
  3730. }
  3731. }
  3732. Item* Spawn::LootItem(int32 id) {
  3733. Item* ret = 0;
  3734. vector<Item*>::iterator itr;
  3735. MLootItems.lock();
  3736. for (itr = loot_items.begin(); itr != loot_items.end(); itr++) {
  3737. if ((*itr)->details.item_id == id) {
  3738. ret = *itr;
  3739. loot_items.erase(itr);
  3740. break;
  3741. }
  3742. }
  3743. MLootItems.unlock();
  3744. return ret;
  3745. }
  3746. void Spawn::TransferLoot(Spawn* spawn) {
  3747. if(spawn == this || spawn == nullptr)
  3748. return; // mmm no
  3749. vector<Item*>::iterator itr;
  3750. MLootItems.lock();
  3751. for (itr = loot_items.begin(); itr != loot_items.end();) {
  3752. if (!(*itr)->IsBodyDrop()) {
  3753. spawn->AddLootItem(*itr);
  3754. itr = loot_items.erase(itr);
  3755. }
  3756. else {
  3757. itr++;
  3758. }
  3759. }
  3760. MLootItems.unlock();
  3761. }
  3762. int32 Spawn::GetLootItemID() {
  3763. int32 ret = 0;
  3764. vector<Item*>::iterator itr;
  3765. MLootItems.lock();
  3766. for (itr = loot_items.begin(); itr != loot_items.end(); itr++) {
  3767. ret = (*itr)->details.item_id;
  3768. break;
  3769. }
  3770. MLootItems.unlock();
  3771. return ret;
  3772. }
  3773. void Spawn::GetLootItemsList(std::vector<int32>* out_entries) {
  3774. if(!out_entries)
  3775. return;
  3776. vector<Item*>::iterator itr;
  3777. for (itr = loot_items.begin(); itr != loot_items.end(); itr++) {
  3778. out_entries->push_back((*itr)->details.item_id);
  3779. }
  3780. }
  3781. bool Spawn::HasLootItemID(int32 id) {
  3782. bool ret = false;
  3783. vector<Item*>::iterator itr;
  3784. MLootItems.readlock(__FUNCTION__, __LINE__);
  3785. for (itr = loot_items.begin(); itr != loot_items.end(); itr++) {
  3786. if ((*itr)->details.item_id == id) {
  3787. ret = true;
  3788. break;
  3789. }
  3790. }
  3791. MLootItems.releasereadlock(__FUNCTION__, __LINE__);
  3792. return ret;
  3793. }
  3794. void Spawn::CheckProximities()
  3795. {
  3796. if (!has_spawn_proximities)
  3797. return;
  3798. if (spawn_proximities.size() > 0)
  3799. {
  3800. MutexList<SpawnProximity*>::iterator itr = spawn_proximities.begin();
  3801. while (itr.Next()) {
  3802. SpawnProximity* prox = itr.value;
  3803. map<int32, bool>::iterator spawnsItr;
  3804. for (spawnsItr = prox->spawns_in_proximity.begin(); spawnsItr != prox->spawns_in_proximity.end(); spawnsItr++) {
  3805. Spawn* tmpSpawn = 0;
  3806. if (spawnsItr->first &&
  3807. ((prox->spawn_type == SPAWNPROXIMITY_DATABASE_ID && (tmpSpawn = GetZone()->GetSpawnByDatabaseID(spawnsItr->first)) != 0) ||
  3808. (prox->spawn_type == SPAWNPROXIMITY_LOCATION_ID && (tmpSpawn = GetZone()->GetSpawnByLocationID(spawnsItr->first)) != 0)))
  3809. {
  3810. if (!spawnsItr->second && tmpSpawn->GetDistance(this) <= prox->distance)
  3811. {
  3812. if (prox->in_range_lua_function.size() > 0)
  3813. GetZone()->CallSpawnScript(this, SPAWN_SCRIPT_CUSTOM, tmpSpawn, prox->in_range_lua_function.c_str());
  3814. spawnsItr->second = true;
  3815. }
  3816. else if (spawnsItr->second && tmpSpawn->GetDistance(this) > prox->distance)
  3817. {
  3818. if (prox->leaving_range_lua_function.size() > 0)
  3819. GetZone()->CallSpawnScript(this, SPAWN_SCRIPT_CUSTOM, tmpSpawn, prox->leaving_range_lua_function.c_str());
  3820. spawnsItr->second = false;
  3821. }
  3822. }
  3823. }
  3824. }
  3825. }
  3826. }
  3827. void Spawn::AddSpawnToProximity(int32 spawnValue, SpawnProximityType type)
  3828. {
  3829. if (!has_spawn_proximities)
  3830. return;
  3831. if (spawn_proximities.size() > 0)
  3832. {
  3833. MutexList<SpawnProximity*>::iterator itr = spawn_proximities.begin();
  3834. while (itr.Next()) {
  3835. SpawnProximity* prox = itr->value;
  3836. if (prox->spawn_value == spawnValue && prox->spawn_type == type)
  3837. prox->spawns_in_proximity.insert(make_pair(spawnValue, false));
  3838. }
  3839. }
  3840. }
  3841. void Spawn::RemoveSpawnFromProximity(int32 spawnValue, SpawnProximityType type)
  3842. {
  3843. if (!has_spawn_proximities)
  3844. return;
  3845. if (spawn_proximities.size() > 0)
  3846. {
  3847. MutexList<SpawnProximity*>::iterator itr = spawn_proximities.begin();
  3848. while (itr.Next()) {
  3849. SpawnProximity* prox = itr->value;
  3850. if (prox->spawn_value == spawnValue && prox->spawn_type == type &&
  3851. prox->spawns_in_proximity.count(spawnValue) > 0)
  3852. prox->spawns_in_proximity.erase(spawnValue);
  3853. }
  3854. }
  3855. }
  3856. void Spawn::AddPrimaryEntityCommand(const char* name, float distance, const char* command, const char* error_text, int16 cast_time, int32 spell_visual, bool defaultDenyList, Player* player) {
  3857. EntityCommand* cmd = FindEntityCommand(string(command), true);
  3858. bool newCommand = false;
  3859. if (!cmd)
  3860. {
  3861. newCommand = true;
  3862. cmd = CreateEntityCommand(name, distance, command, error_text, cast_time, spell_visual, !defaultDenyList);
  3863. }
  3864. if (defaultDenyList)
  3865. SetPermissionToEntityCommand(cmd, player, true);
  3866. if (newCommand)
  3867. primary_command_list.push_back(cmd);
  3868. }
  3869. void Spawn::RemovePrimaryEntityCommand(const char* command) {
  3870. vector<EntityCommand*>::iterator itr;
  3871. string tmpStr(command);
  3872. for (itr = primary_command_list.begin(); itr != primary_command_list.end(); itr++) {
  3873. EntityCommand* cmd = *itr;
  3874. if (cmd->command.compare(tmpStr) == 0)
  3875. {
  3876. primary_command_list.erase(itr);
  3877. delete cmd;
  3878. break;
  3879. }
  3880. }
  3881. }
  3882. bool Spawn::SetPermissionToEntityCommand(EntityCommand* command, Player* player, bool permissionValue)
  3883. {
  3884. if(!player)
  3885. return false;
  3886. return SetPermissionToEntityCommandByCharID(command, player->GetCharacterID(), permissionValue);
  3887. }
  3888. bool Spawn::SetPermissionToEntityCommandByCharID(EntityCommand* command, int32 charID, bool permissionValue)
  3889. {
  3890. map<int32, bool>::iterator itr = command->allow_or_deny.find(charID);
  3891. if (itr == command->allow_or_deny.end())
  3892. command->allow_or_deny.insert(make_pair(charID, permissionValue));
  3893. else if (itr->second != permissionValue)
  3894. itr->second = permissionValue;
  3895. return true;
  3896. }
  3897. void Spawn::RemoveSpawnFromPlayer(Player* player)
  3898. {
  3899. m_Update.writelock(__FUNCTION__, __LINE__);
  3900. player->RemoveSpawn(this); // sets it as removed
  3901. m_Update.releasewritelock(__FUNCTION__, __LINE__);
  3902. }
  3903. bool Spawn::InWater()
  3904. {
  3905. bool inWater = false;
  3906. if ( region_map != nullptr )
  3907. {
  3908. glm::vec3 targPos(GetX(), GetY(), GetZ());
  3909. if ( IsGroundSpawn() )
  3910. targPos.y -= .5f;
  3911. if(region_map->InWater(targPos, GetLocation()))
  3912. inWater = true;
  3913. }
  3914. return inWater;
  3915. }
  3916. bool Spawn::InLava()
  3917. {
  3918. bool inLava = false;
  3919. if ( region_map != nullptr )
  3920. {
  3921. glm::vec3 targPos(GetX(), GetY(), GetZ());
  3922. if ( IsGroundSpawn() )
  3923. targPos.y -= .5f;
  3924. if(region_map->InLava(targPos, GetLocation()))
  3925. inLava = true;
  3926. }
  3927. return inLava;
  3928. }
  3929. void Spawn::DeleteRegion(Region_Node* inNode, ZBSP_Node* rootNode)
  3930. {
  3931. map<map<Region_Node*, ZBSP_Node*>, Region_Status>::iterator testitr;
  3932. for (testitr = Regions.begin(); testitr != Regions.end(); testitr++)
  3933. {
  3934. map<Region_Node*, ZBSP_Node*>::const_iterator actualItr = testitr->first.begin();
  3935. Region_Node* node = actualItr->first;
  3936. ZBSP_Node* BSP_Root = actualItr->second;
  3937. if(inNode == node && rootNode == BSP_Root )
  3938. {
  3939. testitr = Regions.erase(testitr);
  3940. break;
  3941. }
  3942. }
  3943. }
  3944. bool Spawn::InRegion(Region_Node* inNode, ZBSP_Node* rootNode)
  3945. {
  3946. map<map<Region_Node*, ZBSP_Node*>, Region_Status>::iterator testitr;
  3947. for (testitr = Regions.begin(); testitr != Regions.end(); testitr++)
  3948. {
  3949. map<Region_Node*, ZBSP_Node*>::const_iterator actualItr = testitr->first.begin();
  3950. Region_Node* node = actualItr->first;
  3951. ZBSP_Node* BSP_Root = actualItr->second;
  3952. if(inNode == node && rootNode == BSP_Root )
  3953. {
  3954. return testitr->second.inRegion;
  3955. }
  3956. }
  3957. return false;
  3958. }
  3959. int32 Spawn::GetRegionType(Region_Node* inNode, ZBSP_Node* rootNode)
  3960. {
  3961. map<map<Region_Node*, ZBSP_Node*>, Region_Status>::iterator testitr;
  3962. for (testitr = Regions.begin(); testitr != Regions.end(); testitr++)
  3963. {
  3964. map<Region_Node*, ZBSP_Node*>::const_iterator actualItr = testitr->first.begin();
  3965. Region_Node* node = actualItr->first;
  3966. ZBSP_Node* BSP_Root = actualItr->second;
  3967. if(inNode == node && rootNode == BSP_Root )
  3968. {
  3969. return testitr->second.regionType;
  3970. }
  3971. }
  3972. return false;
  3973. }
  3974. float Spawn::SpawnAngle(Spawn* target, float selfx, float selfz)
  3975. {
  3976. if (!target || target == this)
  3977. return 0.0f;
  3978. float angle, lengthb, vectorx, vectorz, dotp;
  3979. float spx = (target->GetX()); // mob xloc (inverse because eq)
  3980. float spz = -(target->GetZ()); // mob yloc
  3981. float heading = target->GetHeading(); // mob heading
  3982. if (heading < 270)
  3983. heading += 90;
  3984. else
  3985. heading -= 270;
  3986. heading = heading * 3.1415f / 180.0f; // convert to radians
  3987. vectorx = spx + (10.0f * std::cos(heading)); // create a vector based on heading
  3988. vectorz = spz + (10.0f * std::sin(heading)); // of spawn length 10
  3989. // length of spawn to player vector
  3990. lengthb = (float) std::sqrt(((selfx - spx) * (selfx - spx)) + ((-selfz - spz) * (-selfz - spz)));
  3991. // calculate dot product to get angle
  3992. // Handle acos domain errors due to floating point rounding errors
  3993. dotp = ((vectorx - spx) * (selfx - spx) +
  3994. (vectorz - spz) * (-selfz - spz)) / (10.0f * lengthb);
  3995. if (dotp > 1)
  3996. return 0.0f;
  3997. else if (dotp < -1)
  3998. return 180.0f;
  3999. angle = std::acos(dotp);
  4000. angle = angle * 180.0f / 3.1415f;
  4001. return angle;
  4002. }
  4003. void Spawn::StopMovement()
  4004. {
  4005. reset_movement = true;
  4006. }
  4007. bool Spawn::PauseMovement(int32 period_of_time_ms)
  4008. {
  4009. if(period_of_time_ms < 1)
  4010. period_of_time_ms = 1;
  4011. RunToLocation(GetX(),GetY(),GetZ());
  4012. pause_timer.Start(period_of_time_ms, true);
  4013. return true;
  4014. }
  4015. bool Spawn::IsPauseMovementTimerActive()
  4016. {
  4017. if(pause_timer.Check())
  4018. pause_timer.Disable();
  4019. return pause_timer.Enabled();
  4020. }
  4021. bool Spawn::IsFlyingCreature()
  4022. {
  4023. if(!IsEntity())
  4024. return false;
  4025. return ((Entity*)this)->GetInfoStruct()->get_flying_type();
  4026. }
  4027. bool Spawn::IsWaterCreature()
  4028. {
  4029. if(!IsEntity())
  4030. return false;
  4031. return ((Entity*)this)->GetInfoStruct()->get_water_type();
  4032. }
  4033. void Spawn::SetFlyingCreature() {
  4034. if(!IsEntity() || !rule_manager.GetGlobalRule(R_Spawn, UseHardCodeFlyingModelType)->GetInt8())
  4035. return;
  4036. if(((Entity*)this)->GetInfoStruct()->get_flying_type() > 0) // DB spawn npc flag already set
  4037. return;
  4038. switch (GetModelType())
  4039. {
  4040. case 260:
  4041. case 295:
  4042. ((Entity*)this)->GetInfoStruct()->set_flying_type(1);
  4043. is_flying_creature = true;
  4044. break;
  4045. default:
  4046. ((Entity*)this)->GetInfoStruct()->set_flying_type(0);
  4047. break;
  4048. }
  4049. }
  4050. void Spawn::SetWaterCreature() {
  4051. if(!IsEntity() || !rule_manager.GetGlobalRule(R_Spawn, UseHardCodeWaterModelType)->GetInt8())
  4052. return;
  4053. if(((Entity*)this)->GetInfoStruct()->get_water_type() > 0) // DB spawn npc flag already set
  4054. return;
  4055. switch (GetModelType())
  4056. {
  4057. case 194:
  4058. case 204:
  4059. case 210:
  4060. case 241:
  4061. case 242:
  4062. case 254:
  4063. case 10668:
  4064. case 20828:
  4065. ((Entity*)this)->GetInfoStruct()->set_water_type(1);
  4066. break;
  4067. default:
  4068. ((Entity*)this)->GetInfoStruct()->set_water_type(0);
  4069. break;
  4070. }
  4071. }
  4072. void Spawn::AddRailPassenger(int32 char_id)
  4073. {
  4074. std::lock_guard<std::mutex> lk(m_RailMutex);
  4075. rail_passengers.insert(make_pair(char_id,true));
  4076. }
  4077. void Spawn::RemoveRailPassenger(int32 char_id)
  4078. {
  4079. std::lock_guard<std::mutex> lk(m_RailMutex);
  4080. std::map<int32, bool>::iterator itr = rail_passengers.find(char_id);
  4081. if(itr != rail_passengers.end())
  4082. rail_passengers.erase(itr);
  4083. }
  4084. vector<Spawn*> Spawn::GetPassengersOnRail() {
  4085. vector<Spawn*> tmp_list;
  4086. Spawn* spawn;
  4087. m_RailMutex.lock();
  4088. std::map<int32, bool>::iterator itr = rail_passengers.begin();
  4089. while(itr != rail_passengers.end()){
  4090. Client* client = zone_list.GetClientByCharID(itr->first);
  4091. if(!client || !client->GetPlayer())
  4092. continue;
  4093. tmp_list.push_back(client->GetPlayer());
  4094. itr++;
  4095. }
  4096. m_RailMutex.unlock();
  4097. return tmp_list;
  4098. }
  4099. void Spawn::SetAppearancePosition(float x, float y, float z) {
  4100. appearance.pos.X = x;
  4101. appearance.pos.Y = y;
  4102. appearance.pos.Z = z;
  4103. appearance.pos.X2 = appearance.pos.X;
  4104. appearance.pos.Y2 = appearance.pos.Y;
  4105. appearance.pos.Z2 = appearance.pos.Z;
  4106. appearance.pos.X3 = appearance.pos.X;
  4107. appearance.pos.Y3 = appearance.pos.Y;
  4108. appearance.pos.Z3 = appearance.pos.Z;
  4109. SetSpeedX(0);
  4110. SetSpeedY(0);
  4111. SetSpeedZ(0);
  4112. if(IsPlayer()) {
  4113. ((Player*)this)->SetSideSpeed(0);
  4114. ((Player*)this)->pos_packet_speed = 0;
  4115. }
  4116. }
  4117. int32 Spawn::InsertRegionToSpawn(Region_Node* node, ZBSP_Node* bsp_root, WaterRegionType regionType, bool in_region) {
  4118. std::map<Region_Node*, ZBSP_Node*> newMap;
  4119. newMap.insert(make_pair(node, bsp_root));
  4120. Region_Status status;
  4121. status.inRegion = in_region;
  4122. status.regionType = regionType;
  4123. int32 returnValue = 0;
  4124. if(in_region) {
  4125. lua_interface->RunRegionScript(node->regionScriptName, "EnterRegion", GetZone(), this, regionType, &returnValue);
  4126. }
  4127. status.timerTic = returnValue;
  4128. status.lastTimerTic = returnValue ? Timer::GetCurrentTime2() : 0;
  4129. Regions.insert(make_pair(newMap, status));
  4130. return returnValue;
  4131. }
  4132. bool Spawn::HasRegionTracked(Region_Node* node, ZBSP_Node* bsp_root, bool in_region) {
  4133. map<map<Region_Node*, ZBSP_Node*>, Region_Status>::iterator testitr;
  4134. for (testitr = Regions.begin(); testitr != Regions.end(); testitr++)
  4135. {
  4136. map<Region_Node*, ZBSP_Node*>::const_iterator actualItr = testitr->first.begin();
  4137. Region_Node *node = actualItr->first;
  4138. ZBSP_Node *BSP_Root = actualItr->second;
  4139. if(node == actualItr->first && BSP_Root == actualItr->second) {
  4140. if(testitr->second.inRegion == in_region)
  4141. return true;
  4142. else
  4143. break;
  4144. }
  4145. }
  4146. return false;
  4147. }
  4148. void Spawn::SetLocation(int32 id, bool setUpdateFlags)
  4149. {
  4150. if(GetZone()) {
  4151. GetZone()->RemoveSpawnFromGrid(this, GetLocation());
  4152. SetPos(&appearance.pos.grid_id, id, setUpdateFlags);
  4153. GetZone()->AddSpawnToGrid(this, id);
  4154. }
  4155. else {
  4156. SetPos(&appearance.pos.grid_id, id, setUpdateFlags);
  4157. }
  4158. }
  4159. int8 Spawn::GetArrowColor(int8 spawn_level){
  4160. int8 color = 0;
  4161. sint16 diff = spawn_level - GetLevel();
  4162. if(GetLevel() < 10)
  4163. diff *= 3;
  4164. else if(GetLevel() <= 20)
  4165. diff *= 2;
  4166. if(diff >= 9)
  4167. color = ARROW_COLOR_RED;
  4168. else if(diff >= 5)
  4169. color = ARROW_COLOR_ORANGE;
  4170. else if(diff >= 1)
  4171. color = ARROW_COLOR_YELLOW;
  4172. else if(diff == 0)
  4173. color = ARROW_COLOR_WHITE;
  4174. else if(diff <= -11)
  4175. color = ARROW_COLOR_GRAY;
  4176. else if(diff <= -6)
  4177. color = ARROW_COLOR_GREEN;
  4178. else //if(diff < 0)
  4179. color = ARROW_COLOR_BLUE;
  4180. return color;
  4181. }
  4182. void Spawn::AddIgnoredWidget(int32 id) {
  4183. std::unique_lock lock(MIgnoredWidgets);
  4184. if(ignored_widgets.find(id) == ignored_widgets.end()) {
  4185. ignored_widgets.insert(make_pair(id,true));
  4186. }
  4187. }
  4188. void Spawn::SendGroupUpdate() {
  4189. if (IsEntity() && ((Entity*)this)->GetGroupMemberInfo()) {
  4190. ((Entity*)this)->UpdateGroupMemberInfo();
  4191. if (IsPlayer()) {
  4192. Client* client = ((Player*)this)->GetClient();
  4193. if(client) {
  4194. world.GetGroupManager()->SendGroupUpdate(((Entity*)this)->GetGroupMemberInfo()->group_id, client);
  4195. }
  4196. }
  4197. else
  4198. world.GetGroupManager()->SendGroupUpdate(((Entity*)this)->GetGroupMemberInfo()->group_id);
  4199. }
  4200. }
  4201. bool Spawn::AddNeedGreedItemRequest(int32 item_id, int32 spawn_id, bool need_item) {
  4202. LogWrite(LOOT__INFO, 0, "Loot", "%s: AddNeedGreedItemRequest Item ID: %u, Spawn ID: %u, Need Item: %u", GetName(), item_id, spawn_id, need_item);
  4203. if (HasSpawnNeedGreedEntry(item_id, spawn_id)) {
  4204. return false;
  4205. }
  4206. need_greed_items.insert(make_pair(item_id, std::make_pair(spawn_id, need_item)));
  4207. AddSpawnLootWindowCompleted(spawn_id, false);
  4208. return true;
  4209. }
  4210. bool Spawn::AddLottoItemRequest(int32 item_id, int32 spawn_id) {
  4211. LogWrite(LOOT__INFO, 0, "Loot", "%s: AddLottoItemRequest Item ID: %u, Spawn ID: %u", GetName(), item_id, spawn_id);
  4212. if (HasSpawnLottoEntry(item_id, spawn_id)) {
  4213. return false;
  4214. }
  4215. lotto_items.insert(make_pair(item_id, spawn_id));
  4216. AddSpawnLootWindowCompleted(spawn_id, false);
  4217. return true;
  4218. }
  4219. void Spawn::AddSpawnLootWindowCompleted(int32 spawn_id, bool status_) {
  4220. if (loot_complete.find(spawn_id) == loot_complete.end()) {
  4221. loot_complete.insert(make_pair(spawn_id, status_));
  4222. }
  4223. is_loot_complete = HasLootWindowCompleted();
  4224. }
  4225. bool Spawn::SetSpawnLootWindowCompleted(int32 spawn_id) {
  4226. std::map<int32, bool>::iterator itr = loot_complete.find(spawn_id);
  4227. if (itr != loot_complete.end()) {
  4228. itr->second = true;
  4229. is_loot_complete = HasLootWindowCompleted();
  4230. return true;
  4231. }
  4232. return false;
  4233. }
  4234. bool Spawn::HasSpawnLootWindowCompleted(int32 spawn_id) {
  4235. std::map<int32, bool>::iterator itr = loot_complete.find(spawn_id);
  4236. if (itr != loot_complete.end() && itr->second) {
  4237. return true;
  4238. }
  4239. return false;
  4240. }
  4241. bool Spawn::HasSpawnNeedGreedEntry(int32 item_id, int32 spawn_id) {
  4242. for (auto [itr, rangeEnd] = need_greed_items.equal_range(item_id); itr != rangeEnd; itr++) {
  4243. LogWrite(LOOT__DEBUG, 8, "Loot", "%s: HasSpawnNeedGreedEntry Item ID: %u, Spawn ID: %u", GetName(), itr->first, itr->second.first);
  4244. if (spawn_id == itr->second.first) {
  4245. return true;
  4246. }
  4247. }
  4248. return false;
  4249. }
  4250. bool Spawn::HasSpawnLottoEntry(int32 item_id, int32 spawn_id) {
  4251. for (auto [itr, rangeEnd] = lotto_items.equal_range(item_id); itr != rangeEnd; itr++) {
  4252. LogWrite(LOOT__DEBUG, 8, "Loot", "%s: HasSpawnLottoEntry Item ID: %u, Spawn ID: %u", GetName(), itr->first, itr->second);
  4253. if (spawn_id == itr->second) {
  4254. return true;
  4255. }
  4256. }
  4257. return false;
  4258. }
  4259. void Spawn::GetSpawnLottoEntries(int32 item_id, std::map<int32, int32>* out_entries) {
  4260. if (!out_entries)
  4261. return;
  4262. std::map<int32, bool> spawn_matches;
  4263. for (auto [itr, endrange] = lotto_items.equal_range(item_id); itr != endrange; itr++) {
  4264. out_entries->insert(std::make_pair(itr->second, (int32)MakeRandomInt(0, 100)));
  4265. spawn_matches[itr->second] = true;
  4266. }
  4267. // 0xFFFFFFFF represents selecting "All" on the lotto screen
  4268. for (auto [itr, endrange] = lotto_items.equal_range(0xFFFFFFFF); itr != endrange; itr++) {
  4269. if (spawn_matches.find(itr->second) == spawn_matches.end()) {
  4270. out_entries->insert(std::make_pair(itr->second, (int32)MakeRandomInt(0, 100)));
  4271. }
  4272. }
  4273. }
  4274. void Spawn::GetSpawnNeedGreedEntries(int32 item_id, bool need_item, std::map<int32, int32>* out_entries) {
  4275. if (!out_entries)
  4276. return;
  4277. for (auto [itr, rangeEnd] = need_greed_items.equal_range(item_id); itr != rangeEnd; itr++) {
  4278. out_entries->insert(std::make_pair(itr->second.first, (int32)MakeRandomInt(0, 100)));
  4279. }
  4280. }
  4281. bool Spawn::HasLootWindowCompleted() {
  4282. std::map<int32, bool>::iterator itr;
  4283. for (itr = loot_complete.begin(); itr != loot_complete.end(); itr++) {
  4284. if (!itr->second)
  4285. return false;
  4286. }
  4287. return true;
  4288. }
  4289. void Spawn::StartLootTimer(Spawn* looter) {
  4290. if (!IsLootTimerRunning()) {
  4291. int32 loot_timer_time = rule_manager.GetGlobalRule(R_Loot, LootDistributionTime)->GetInt32() * 1000;
  4292. if(rule_manager.GetGlobalRule(R_Loot, AllowChestUnlockByDropTime)->GetBool() && loot_timer_time > rule_manager.GetGlobalRule(R_Loot, ChestUnlockedTimeDrop)->GetInt32()*1000) {
  4293. loot_timer_time = (rule_manager.GetGlobalRule(R_Loot, ChestUnlockedTimeDrop)->GetInt32()*1000) / 2;
  4294. }
  4295. if(rule_manager.GetGlobalRule(R_Loot, AllowChestUnlockByTrapTime)->GetBool() && loot_timer_time > rule_manager.GetGlobalRule(R_Loot, ChestUnlockedTimeTrap)->GetInt32()*1000) {
  4296. loot_timer_time = (rule_manager.GetGlobalRule(R_Loot, ChestUnlockedTimeTrap)->GetInt32()*1000) / 2;
  4297. }
  4298. if(loot_timer_time < 1000) {
  4299. loot_timer_time = 60000; // hardcode assure they aren't setting some really ridiculous low number
  4300. }
  4301. loot_timer.Start(loot_timer_time, true);
  4302. }
  4303. if (looter) {
  4304. looter_spawn_id = looter->GetID();
  4305. }
  4306. }
  4307. void Spawn::CloseLoot(Spawn* sender) {
  4308. if (sender) {
  4309. SetSpawnLootWindowCompleted(sender->GetID());
  4310. }
  4311. if (sender && looter_spawn_id > 0 && sender->GetID() != looter_spawn_id) {
  4312. LogWrite(LOOT__ERROR, 0, "Loot", "%s: CloseLoot Looter Spawn ID: %u does not match sender %u.", GetName(), looter_spawn_id, sender->GetID());
  4313. return;
  4314. }
  4315. if (!IsLootTimerRunning() && GetLootMethod() != GroupLootMethod::METHOD_LOTTO && GetLootMethod() != GroupLootMethod::METHOD_NEED_BEFORE_GREED) {
  4316. loot_timer.Disable();
  4317. }
  4318. looter_spawn_id = 0;
  4319. }
  4320. void Spawn::SetLootMethod(GroupLootMethod method, int8 item_rarity, int32 group_id) {
  4321. LogWrite(LOOT__INFO, 0, "Loot", "%s: Set Loot Method : %u, group id : %u", GetName(), (int32)method, group_id);
  4322. loot_group_id = group_id;
  4323. loot_method = method;
  4324. loot_rarity = item_rarity;
  4325. if (loot_name.size() < 1) {
  4326. loot_name = std::string(GetName());
  4327. }
  4328. }
  4329. bool Spawn::IsItemInLootTier(Item* item) {
  4330. if (!item)
  4331. return true;
  4332. bool skipItem = true;
  4333. switch (GetLootRarity()) {
  4334. case LootTier::ITEMS_TREASURED_PLUS: {
  4335. if (item->details.tier >= ITEM_TAG_TREASURED) {
  4336. skipItem = false;
  4337. }
  4338. break;
  4339. }
  4340. case LootTier::ITEMS_LEGENDARY_PLUS: {
  4341. if (item->details.tier >= ITEM_TAG_LEGENDARY) {
  4342. skipItem = false;
  4343. }
  4344. break;
  4345. }
  4346. case LootTier::ITEMS_FABLED_PLUS: {
  4347. if (item->details.tier >= ITEM_TAG_FABLED) {
  4348. skipItem = false;
  4349. }
  4350. break;
  4351. }
  4352. default: {
  4353. skipItem = false;
  4354. break;
  4355. }
  4356. }
  4357. return skipItem;
  4358. }
  4359. void Spawn::DistributeGroupLoot_RoundRobin(std::vector<int32>* item_list, bool roundRobinTrashLoot) {
  4360. std::vector<int32>::iterator item_itr;
  4361. for (item_itr = item_list->begin(); item_itr != item_list->end(); item_itr++) {
  4362. int32 item_id = *item_itr;
  4363. Item* tmpItem = master_item_list.GetItem(item_id);
  4364. Spawn* looter = nullptr;
  4365. bool skipItem = IsItemInLootTier(tmpItem);
  4366. if ((skipItem && !roundRobinTrashLoot) || (!skipItem && roundRobinTrashLoot))
  4367. continue;
  4368. world.GetGroupManager()->GroupLock(__FUNCTION__, __LINE__);
  4369. PlayerGroup* group = world.GetGroupManager()->GetGroup(GetLootGroupID());
  4370. if (group) {
  4371. group->MGroupMembers.writelock(__FUNCTION__, __LINE__);
  4372. deque<GroupMemberInfo*>* members = group->GetMembers();
  4373. int8 index = group->GetLastLooterIndex();
  4374. if (index >= members->size()) {
  4375. index = 0;
  4376. }
  4377. GroupMemberInfo* gmi = members->at(index);
  4378. if (gmi) {
  4379. looter = gmi->member;
  4380. }
  4381. bool loopAttempted = false;
  4382. while (looter) {
  4383. if (!looter->IsPlayer()) {
  4384. index++;
  4385. if (index >= members->size()) {
  4386. if (loopAttempted) {
  4387. looter = nullptr;
  4388. break;
  4389. }
  4390. loopAttempted = true;
  4391. index = 0;
  4392. }
  4393. gmi = members->at(index);
  4394. if (gmi) {
  4395. looter = gmi->member;
  4396. }
  4397. continue;
  4398. }
  4399. else {
  4400. break;
  4401. }
  4402. }
  4403. index += 1;
  4404. group->SetNextLooterIndex(index);
  4405. group->MGroupMembers.releasewritelock(__FUNCTION__, __LINE__);
  4406. }
  4407. world.GetGroupManager()->ReleaseGroupLock(__FUNCTION__, __LINE__);
  4408. if (looter) {
  4409. if (looter->IsPlayer()) {
  4410. Item* item = LootItem(item_id);
  4411. bool success = false;
  4412. success = ((Player*)looter)->GetClient()->HandleLootItem(this, item, ((Player*)looter), roundRobinTrashLoot);
  4413. if (!success)
  4414. AddLootItem(item);
  4415. }
  4416. else {
  4417. Item* item = LootItem(item_id);
  4418. safe_delete(item);
  4419. }
  4420. }
  4421. }
  4422. }
  4423. const double g = 9.81; // acceleration due to gravity (m/s^2)
  4424. void Spawn::CalculateInitialVelocity(float heading, float distanceHorizontal, float distanceVertical, float distanceDepth, float duration) {
  4425. float vx = distanceHorizontal / duration;
  4426. float vy = (distanceVertical + 0.5 * g * duration * duration) / duration;
  4427. float vz = distanceDepth / duration;
  4428. // Convert heading angle to radians
  4429. knocked_velocity.x = vx * cos(heading);
  4430. knocked_velocity.y = vy;
  4431. knocked_velocity.z = vz * sin(heading);
  4432. }
  4433. // Function to calculate the projectile position at a given time
  4434. glm::vec3 Spawn::CalculateProjectilePosition(glm::vec3 initialVelocity, float time) {
  4435. glm::vec3 position;
  4436. position.x = knocked_back_start_x + initialVelocity.x * time;
  4437. position.y = knocked_back_start_y + initialVelocity.y * time - 0.5 * g * time * time;
  4438. position.z = knocked_back_start_z + initialVelocity.z * time;
  4439. auto loc = glm::vec3(position.x, position.z, position.y);
  4440. float new_z = FindBestZ(loc, nullptr);
  4441. if(new_z > position.y)
  4442. position.y = new_z;
  4443. return position;
  4444. }
  4445. bool Spawn::CalculateSpawnProjectilePosition(float x, float y, float z) {
  4446. float currentTimeOffset = (Timer::GetCurrentTime2() - last_movement_update) * 0.001; // * 0.001 is the same as / 1000, float muliplications is suppose to be faster though
  4447. float stepAheadOne = currentTimeOffset+currentTimeOffset;
  4448. knocked_back_time_step += currentTimeOffset;
  4449. if(Timer::GetCurrentTime2() >= knocked_back_end_time) {
  4450. ResetKnockedBack();
  4451. FixZ(true);
  4452. return false;
  4453. }
  4454. glm::vec3 position = CalculateProjectilePosition(knocked_velocity, knocked_back_time_step);
  4455. glm::vec3 position_two = position;
  4456. if(Timer::GetCurrentTime2() <= knocked_back_end_time+stepAheadOne) {
  4457. position_two = CalculateProjectilePosition(knocked_velocity, knocked_back_time_step+stepAheadOne);
  4458. }
  4459. if(GetMap()) {
  4460. glm::vec3 loc(GetX(), GetZ(), GetY() + .5f);
  4461. glm::vec3 dest_loc(position_two.x, position_two.z, position_two.y);
  4462. MIgnoredWidgets.lock_shared();
  4463. glm::vec3 outNorm;
  4464. float dist = 0.0f;
  4465. bool collide_ = GetMap()->DoCollisionCheck(loc, dest_loc, &ignored_widgets, outNorm, dist);
  4466. if(collide_) {
  4467. LogWrite(SPAWN__ERROR, 0, "Spawn", "Collision Hit: cur loc x,y,z: %f %f %f. to loc %f %f %f. TimeOffset: %f Total Time: %f Duration: %f", GetX(),GetY(),GetZ(),position_two.x,position_two.y,position_two.z, currentTimeOffset, knocked_back_time_step, knocked_back_duration);
  4468. MIgnoredWidgets.unlock_shared();
  4469. ResetKnockedBack();
  4470. FixZ(true);
  4471. return false;
  4472. }
  4473. MIgnoredWidgets.unlock_shared();
  4474. }
  4475. LogWrite(SPAWN__ERROR, 0, "Spawn", "x,y,z: %f %f %f. Final %f %f %f. TimeOffset: %f Total Time: %f Duration: %f", GetX(),GetY(),GetZ(),position.x,position.y,position.z, currentTimeOffset, knocked_back_time_step, knocked_back_duration);
  4476. SetX(position.x, false);
  4477. SetZ(position.z, false);
  4478. SetY(position.y, false, true);
  4479. SetPos(&appearance.pos.X2, position_two.x, false);
  4480. SetPos(&appearance.pos.Z2, position_two.z, false);
  4481. SetPos(&appearance.pos.Y2, position_two.y, false);
  4482. SetPos(&appearance.pos.X3, position_two.x, false);
  4483. SetPos(&appearance.pos.Z3, position_two.z, false);
  4484. SetPos(&appearance.pos.Y3, position_two.y, false);
  4485. position_changed = true;
  4486. changed = true;
  4487. GetZone()->AddChangedSpawn(this);
  4488. return true;
  4489. }
  4490. void Spawn::SetKnockback(Spawn* target, int32 duration, float vertical, float horizontal) {
  4491. if(knocked_back) {
  4492. return; // already being knocked back
  4493. }
  4494. // Calculate the direction vector from source to destination
  4495. glm::vec3 direction = {GetX() - target->GetX(), GetZ() - target->GetZ(), GetY() - target->GetY()};
  4496. // Calculate the heading angle in radians
  4497. double headingRad = atan2(direction.y, sqrt(direction.x * direction.x + direction.z * direction.z));
  4498. knocked_angle = headingRad;
  4499. knocked_back_start_x = GetX();
  4500. knocked_back_start_y = GetY();
  4501. knocked_back_start_z = GetZ();
  4502. knocked_back_h_distance = horizontal / 10.0f;
  4503. knocked_back_v_distance = vertical / 10.0f;
  4504. knocked_back_duration = static_cast<float>(duration) / 1000.0f;
  4505. knocked_back_end_time = Timer::GetCurrentTime2() + duration;
  4506. CalculateInitialVelocity(knocked_angle, knocked_back_h_distance, knocked_back_h_distance, knocked_back_h_distance, knocked_back_duration);
  4507. knocked_back = true;
  4508. }
  4509. void Spawn::ResetKnockedBack() {
  4510. knocked_back = false;
  4511. knocked_back_time_step = 0.0f;
  4512. knocked_back_h_distance = 0.0f;
  4513. knocked_back_v_distance = 0.0f;
  4514. knocked_back_duration = 0.0f;
  4515. knocked_back_end_time = 0;
  4516. knocked_back_start_x = 0.0f;
  4517. knocked_back_start_y = 0.0f;
  4518. knocked_back_start_z = 0.0f;
  4519. knocked_angle = 0.0f;
  4520. knocked_velocity.x = 0.0f;
  4521. knocked_velocity.y = 0.0f;
  4522. knocked_velocity.z = 0.0f;
  4523. }