player.cpp 254 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752
  1. //-----------------------------------------------------------------------------
  2. // Copyright (c) 2012 GarageGames, LLC
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to
  6. // deal in the Software without restriction, including without limitation the
  7. // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
  8. // sell copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  19. // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
  20. // IN THE SOFTWARE.
  21. //-----------------------------------------------------------------------------
  22. //~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~~//
  23. // Arcane-FX for MIT Licensed Open Source version of Torque 3D from GarageGames
  24. // Copyright (C) 2015 Faust Logic, Inc.
  25. //~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~~//
  26. #include "platform/platform.h"
  27. #include "T3D/player.h"
  28. #include "platform/profiler.h"
  29. #include "math/mMath.h"
  30. #include "math/mathIO.h"
  31. #include "core/resourceManager.h"
  32. #include "core/stringTable.h"
  33. #include "core/volume.h"
  34. #include "core/stream/bitStream.h"
  35. #include "console/consoleTypes.h"
  36. #include "console/engineAPI.h"
  37. #include "collision/extrudedPolyList.h"
  38. #include "collision/clippedPolyList.h"
  39. #include "collision/earlyOutPolyList.h"
  40. #include "ts/tsShapeInstance.h"
  41. #include "sfx/sfxSystem.h"
  42. #include "sfx/sfxTrack.h"
  43. #include "sfx/sfxSource.h"
  44. #include "sfx/sfxTypes.h"
  45. #include "scene/sceneManager.h"
  46. #include "scene/sceneRenderState.h"
  47. #include "T3D/gameBase/gameConnection.h"
  48. #include "T3D/trigger.h"
  49. #include "T3D/physicalZone.h"
  50. #include "T3D/item.h"
  51. #include "T3D/missionArea.h"
  52. #include "T3D/fx/particleEmitter.h"
  53. #include "T3D/fx/cameraFXMgr.h"
  54. #include "T3D/fx/splash.h"
  55. #include "T3D/tsStatic.h"
  56. #include "T3D/physics/physicsPlugin.h"
  57. #include "T3D/physics/physicsPlayer.h"
  58. #include "T3D/decal/decalManager.h"
  59. #include "T3D/decal/decalData.h"
  60. #include "materials/baseMatInstance.h"
  61. #include "math/mathUtils.h"
  62. #include "gfx/sim/debugDraw.h"
  63. #ifdef TORQUE_EXTENDED_MOVE
  64. #include "T3D/gameBase/extended/extendedMove.h"
  65. #endif
  66. #ifdef TORQUE_OPENVR
  67. #include "platform/input/openVR/openVRProvider.h"
  68. #include "platform/input/openVR/openVRTrackedObject.h"
  69. #endif
  70. // Amount of time if takes to transition to a new action sequence.
  71. static F32 sAnimationTransitionTime = 0.25f;
  72. static bool sUseAnimationTransitions = true;
  73. static F32 sLandReverseScale = 0.25f;
  74. static F32 sSlowStandThreshSquared = 1.69f;
  75. static S32 sRenderMyPlayer = true;
  76. static S32 sRenderMyItems = true;
  77. static bool sRenderPlayerCollision = false;
  78. // Chooses new action animations every n ticks.
  79. static const F32 sNewAnimationTickTime = 4.0f;
  80. static const F32 sMountPendingTickWait = 13.0f * F32(TickMs);
  81. // Number of ticks before we pick non-contact animations
  82. static const S32 sContactTickTime = 10;
  83. // Movement constants
  84. static F32 sVerticalStepDot = 0.173f; // 80
  85. static F32 sMinFaceDistance = 0.01f;
  86. static F32 sTractionDistance = 0.04f;
  87. static F32 sNormalElasticity = 0.01f;
  88. static U32 sMoveRetryCount = 5;
  89. static F32 sMaxImpulseVelocity = 200.0f;
  90. // Move triggers
  91. static S32 sJumpTrigger = 2;
  92. static S32 sCrouchTrigger = 3;
  93. static S32 sProneTrigger = 4;
  94. static S32 sSprintTrigger = 5;
  95. static S32 sImageTrigger0 = 0;
  96. static S32 sImageTrigger1 = 1;
  97. static S32 sJumpJetTrigger = 1;
  98. static S32 sVehicleDismountTrigger = 2;
  99. // Client prediction
  100. static F32 sMinWarpTicks = 0.5f; // Fraction of tick at which instant warp occurs
  101. static S32 sMaxWarpTicks = 3; // Max warp duration in ticks
  102. static S32 sMaxPredictionTicks = 30; // Number of ticks to predict
  103. S32 Player::smExtendedMoveHeadPosRotIndex = 0; // The ExtendedMove position/rotation index used for head movements
  104. //
  105. static U32 sCollisionMoveMask = TerrainObjectType |
  106. WaterObjectType |
  107. PlayerObjectType |
  108. StaticShapeObjectType |
  109. VehicleObjectType |
  110. PhysicalZoneObjectType |
  111. // PATHSHAPE
  112. PathShapeObjectType;
  113. // PATHSHAPE END
  114. static U32 sServerCollisionContactMask = sCollisionMoveMask |
  115. ItemObjectType |
  116. TriggerObjectType |
  117. CorpseObjectType;
  118. static U32 sClientCollisionContactMask = sCollisionMoveMask |
  119. TriggerObjectType;
  120. enum PlayerConstants {
  121. JumpSkipContactsMax = 8
  122. };
  123. //----------------------------------------------------------------------------
  124. // Player shape animation sequences:
  125. // Action Animations:
  126. PlayerData::ActionAnimationDef PlayerData::ActionAnimationList[NumTableActionAnims] =
  127. {
  128. // *** WARNING ***
  129. // This array is indexed using the enum values defined in player.h
  130. // Root is the default animation
  131. { "root" }, // RootAnim,
  132. // These are selected in the move state based on velocity
  133. { "run", { 0.0f, 1.0f, 0.0f } }, // RunForwardAnim,
  134. { "back", { 0.0f,-1.0f, 0.0f } }, // BackBackwardAnim
  135. { "side", {-1.0f, 0.0f, 0.0f } }, // SideLeftAnim,
  136. { "side_right", { 1.0f, 0.0f, 0.0f } }, // SideRightAnim,
  137. { "sprint_root" },
  138. { "sprint_forward", { 0.0f, 1.0f, 0.0f } },
  139. { "sprint_backward", { 0.0f,-1.0f, 0.0f } },
  140. { "sprint_side", {-1.0f, 0.0f, 0.0f } },
  141. { "sprint_right", { 1.0f, 0.0f, 0.0f } },
  142. { "crouch_root" },
  143. { "crouch_forward", { 0.0f, 1.0f, 0.0f } },
  144. { "crouch_backward", { 0.0f,-1.0f, 0.0f } },
  145. { "crouch_side", {-1.0f, 0.0f, 0.0f } },
  146. { "crouch_right", { 1.0f, 0.0f, 0.0f } },
  147. { "prone_root" },
  148. { "prone_forward", { 0.0f, 1.0f, 0.0f } },
  149. { "prone_backward", { 0.0f,-1.0f, 0.0f } },
  150. { "swim_root" },
  151. { "swim_forward", { 0.0f, 1.0f, 0.0f } },
  152. { "swim_backward", { 0.0f,-1.0f, 0.0f } },
  153. { "swim_left", {-1.0f, 0.0f, 0.0f } },
  154. { "swim_right", { 1.0f, 0.0f, 0.0f } },
  155. // These are set explicitly based on player actions
  156. { "fall" }, // FallAnim
  157. { "jump" }, // JumpAnim
  158. { "standjump" }, // StandJumpAnim
  159. { "land" }, // LandAnim
  160. { "jet" }, // JetAnim
  161. };
  162. //----------------------------------------------------------------------------
  163. //----------------------------------------------------------------------------
  164. //----------------------------------------------------------------------------
  165. IMPLEMENT_CO_DATABLOCK_V1(PlayerData);
  166. ConsoleDocClass( PlayerData,
  167. "@brief Defines properties for a Player object.\n\n"
  168. "@see Player\n"
  169. "@ingroup gameObjects\n"
  170. );
  171. IMPLEMENT_CALLBACK( PlayerData, onPoseChange, void, ( Player* obj, const char* oldPose, const char* newPose ), ( obj, oldPose, newPose ),
  172. "@brief Called when the player changes poses.\n\n"
  173. "@param obj The Player object\n"
  174. "@param oldPose The pose the player is switching from.\n"
  175. "@param newPose The pose the player is switching to.\n");
  176. IMPLEMENT_CALLBACK( PlayerData, onStartSwim, void, ( Player* obj ), ( obj ),
  177. "@brief Called when the player starts swimming.\n\n"
  178. "@param obj The Player object\n" );
  179. IMPLEMENT_CALLBACK( PlayerData, onStopSwim, void, ( Player* obj ), ( obj ),
  180. "@brief Called when the player stops swimming.\n\n"
  181. "@param obj The Player object\n" );
  182. IMPLEMENT_CALLBACK( PlayerData, onStartSprintMotion, void, ( Player* obj ), ( obj ),
  183. "@brief Called when the player starts moving while in a Sprint pose.\n\n"
  184. "@param obj The Player object\n" );
  185. IMPLEMENT_CALLBACK( PlayerData, onStopSprintMotion, void, ( Player* obj ), ( obj ),
  186. "@brief Called when the player stops moving while in a Sprint pose.\n\n"
  187. "@param obj The Player object\n" );
  188. IMPLEMENT_CALLBACK( PlayerData, doDismount, void, ( Player* obj ), ( obj ),
  189. "@brief Called when attempting to dismount the player from a vehicle.\n\n"
  190. "It is up to the doDismount() method to actually perform the dismount. Often "
  191. "there are some conditions that prevent this, such as the vehicle moving too fast.\n"
  192. "@param obj The Player object\n" );
  193. IMPLEMENT_CALLBACK( PlayerData, onEnterLiquid, void, ( Player* obj, F32 coverage, const char* type ), ( obj, coverage, type ),
  194. "@brief Called when the player enters a liquid.\n\n"
  195. "@param obj The Player object\n"
  196. "@param coverage Percentage of the player's bounding box covered by the liquid\n"
  197. "@param type The type of liquid the player has entered\n" );
  198. IMPLEMENT_CALLBACK( PlayerData, onLeaveLiquid, void, ( Player* obj, const char* type ), ( obj, type ),
  199. "@brief Called when the player leaves a liquid.\n\n"
  200. "@param obj The Player object\n"
  201. "@param type The type of liquid the player has left\n" );
  202. IMPLEMENT_CALLBACK( PlayerData, animationDone, void, ( Player* obj ), ( obj ),
  203. "@brief Called on the server when a scripted animation completes.\n\n"
  204. "@param obj The Player object\n"
  205. "@see Player::setActionThread() for setting a scripted animation and its 'hold' parameter to "
  206. "determine if this callback is used.\n" );
  207. IMPLEMENT_CALLBACK( PlayerData, onEnterMissionArea, void, ( Player* obj ), ( obj ),
  208. "@brief Called when the player enters the mission area.\n\n"
  209. "@param obj The Player object\n"
  210. "@see MissionArea\n" );
  211. IMPLEMENT_CALLBACK( PlayerData, onLeaveMissionArea, void, ( Player* obj ), ( obj ),
  212. "@brief Called when the player leaves the mission area.\n"
  213. "@param obj The Player object\n"
  214. "@see MissionArea\n" );
  215. PlayerData::PlayerData()
  216. {
  217. shadowEnable = true;
  218. shadowSize = 256;
  219. shadowProjectionDistance = 14.0f;
  220. renderFirstPerson = true;
  221. firstPersonShadows = false;
  222. // Used for third person image rendering
  223. imageAnimPrefix = StringTable->EmptyString();
  224. allowImageStateAnimation = false;
  225. // Used for first person image rendering
  226. imageAnimPrefixFP = StringTable->EmptyString();
  227. for (U32 i=0; i<ShapeBase::MaxMountedImages; ++i)
  228. {
  229. shapeNameFP[i] = StringTable->EmptyString();
  230. mCRCFP[i] = 0;
  231. mValidShapeFP[i] = false;
  232. }
  233. pickupRadius = 0.0f;
  234. minLookAngle = -1.4f;
  235. maxLookAngle = 1.4f;
  236. maxFreelookAngle = 3.0f;
  237. maxTimeScale = 1.5f;
  238. mass = 9.0f; // from ShapeBase
  239. maxEnergy = 60.0f; // from ShapeBase
  240. drag = 0.3f; // from ShapeBase
  241. density = 1.1f; // from ShapeBase
  242. maxStepHeight = 1.0f;
  243. runSurfaceAngle = 80.0f;
  244. runSurfaceCos = mCos(mDegToRad(runSurfaceAngle));
  245. fallingSpeedThreshold = -10.0f;
  246. recoverDelay = 30;
  247. recoverRunForceScale = 1.0f;
  248. landSequenceTime = 0.0f;
  249. transitionToLand = false;
  250. // Running/Walking
  251. runForce = 40.0f * 9.0f;
  252. runEnergyDrain = 0.0f;
  253. minRunEnergy = 0.0f;
  254. maxForwardSpeed = 10.0f;
  255. maxBackwardSpeed = 10.0f;
  256. maxSideSpeed = 10.0f;
  257. // Jumping
  258. jumpForce = 75.0f;
  259. jumpEnergyDrain = 0.0f;
  260. minJumpEnergy = 0.0f;
  261. jumpSurfaceAngle = 78.0f;
  262. jumpSurfaceCos = mCos(mDegToRad(jumpSurfaceAngle));
  263. for (U32 i = 0; i < NumRecoilSequences; i++)
  264. recoilSequence[i] = -1;
  265. jumpDelay = 30;
  266. minJumpSpeed = 500.0f;
  267. maxJumpSpeed = 2.0f * minJumpSpeed;
  268. // Sprinting
  269. sprintForce = 50.0f * 9.0f;
  270. sprintEnergyDrain = 0.0f;
  271. minSprintEnergy = 0.0f;
  272. maxSprintForwardSpeed = 15.0f;
  273. maxSprintBackwardSpeed = 10.0f;
  274. maxSprintSideSpeed = 10.0f;
  275. sprintStrafeScale = 1.0f;
  276. sprintYawScale = 1.0f;
  277. sprintPitchScale = 1.0f;
  278. sprintCanJump = true;
  279. // Swimming
  280. swimForce = 55.0f * 9.0f;
  281. maxUnderwaterForwardSpeed = 6.0f;
  282. maxUnderwaterBackwardSpeed = 6.0f;
  283. maxUnderwaterSideSpeed = 6.0f;
  284. // Crouching
  285. crouchForce = 45.0f * 9.0f;
  286. maxCrouchForwardSpeed = 4.0f;
  287. maxCrouchBackwardSpeed = 4.0f;
  288. maxCrouchSideSpeed = 4.0f;
  289. // Prone
  290. proneForce = 45.0f * 9.0f;
  291. maxProneForwardSpeed = 2.0f;
  292. maxProneBackwardSpeed = 2.0f;
  293. maxProneSideSpeed = 0.0f;
  294. // Jetting
  295. jetJumpForce = 0;
  296. jetJumpEnergyDrain = 0;
  297. jetMinJumpEnergy = 0;
  298. jetJumpSurfaceAngle = 78;
  299. jetMinJumpSpeed = 20;
  300. jetMaxJumpSpeed = 100;
  301. horizMaxSpeed = 80.0f;
  302. horizResistSpeed = 38.0f;
  303. horizResistFactor = 1.0f;
  304. upMaxSpeed = 80.0f;
  305. upResistSpeed = 38.0f;
  306. upResistFactor = 1.0f;
  307. minImpactSpeed = 25.0f;
  308. minLateralImpactSpeed = 25.0f;
  309. decalData = NULL;
  310. decalID = 0;
  311. decalOffset = 0.0f;
  312. actionCount = 0;
  313. lookAction = 0;
  314. dMemset(spineNode, 0, sizeof(spineNode));
  315. pickupDelta = 0.0f;
  316. // size of bounding box
  317. boxSize.set(1.0f, 1.0f, 2.3f);
  318. crouchBoxSize.set(1.0f, 1.0f, 2.0f);
  319. proneBoxSize.set(1.0f, 2.3f, 1.0f);
  320. swimBoxSize.set(1.0f, 2.3f, 1.0f);
  321. // location of head, torso, legs
  322. boxHeadPercentage = 0.85f;
  323. boxTorsoPercentage = 0.55f;
  324. // damage locations
  325. boxHeadLeftPercentage = 0;
  326. boxHeadRightPercentage = 1;
  327. boxHeadBackPercentage = 0;
  328. boxHeadFrontPercentage = 1;
  329. for (S32 i = 0; i < MaxSounds; i++)
  330. sound[i] = NULL;
  331. footPuffEmitter = NULL;
  332. footPuffID = 0;
  333. footPuffNumParts = 15;
  334. footPuffRadius = .25f;
  335. dustEmitter = NULL;
  336. dustID = 0;
  337. splash = NULL;
  338. splashId = 0;
  339. splashVelocity = 1.0f;
  340. splashAngle = 45.0f;
  341. splashFreqMod = 300.0f;
  342. splashVelEpsilon = 0.25f;
  343. bubbleEmitTime = 0.4f;
  344. medSplashSoundVel = 2.0f;
  345. hardSplashSoundVel = 3.0f;
  346. exitSplashSoundVel = 2.0f;
  347. footSplashHeight = 0.1f;
  348. dMemset( splashEmitterList, 0, sizeof( splashEmitterList ) );
  349. dMemset( splashEmitterIDList, 0, sizeof( splashEmitterIDList ) );
  350. groundImpactMinSpeed = 10.0f;
  351. groundImpactShakeFreq.set( 10.0f, 10.0f, 10.0f );
  352. groundImpactShakeAmp.set( 20.0f, 20.0f, 20.0f );
  353. groundImpactShakeDuration = 1.0f;
  354. groundImpactShakeFalloff = 10.0f;
  355. // Air control
  356. airControl = 0.0f;
  357. jumpTowardsNormal = true;
  358. physicsPlayerType = StringTable->EmptyString();
  359. dMemset( actionList, 0, sizeof(actionList) );
  360. }
  361. bool PlayerData::preload(bool server, String &errorStr)
  362. {
  363. if(!Parent::preload(server, errorStr))
  364. return false;
  365. // Resolve objects transmitted from server
  366. if( !server )
  367. {
  368. for( U32 i = 0; i < MaxSounds; ++ i )
  369. {
  370. String sfxErrorStr;
  371. if( !sfxResolve( &sound[ i ], sfxErrorStr ) )
  372. Con::errorf( "PlayerData::preload: %s", sfxErrorStr.c_str() );
  373. }
  374. }
  375. //
  376. runSurfaceCos = mCos(mDegToRad(runSurfaceAngle));
  377. jumpSurfaceCos = mCos(mDegToRad(jumpSurfaceAngle));
  378. if (minJumpEnergy < jumpEnergyDrain)
  379. minJumpEnergy = jumpEnergyDrain;
  380. // Jetting
  381. if (jetMinJumpEnergy < jetJumpEnergyDrain)
  382. jetMinJumpEnergy = jetJumpEnergyDrain;
  383. // Validate some of the data
  384. if (fallingSpeedThreshold > 0.0f)
  385. Con::printf("PlayerData:: Falling speed threshold should be downwards (negative)");
  386. if (recoverDelay > (1 << RecoverDelayBits) - 1) {
  387. recoverDelay = (1 << RecoverDelayBits) - 1;
  388. Con::printf("PlayerData:: Recover delay exceeds range (0-%d)",recoverDelay);
  389. }
  390. if (jumpDelay > (1 << JumpDelayBits) - 1) {
  391. jumpDelay = (1 << JumpDelayBits) - 1;
  392. Con::printf("PlayerData:: Jump delay exceeds range (0-%d)",jumpDelay);
  393. }
  394. // If we don't have a shape don't crash out trying to
  395. // setup animations and sequences.
  396. if ( mShape )
  397. {
  398. // Go ahead a pre-load the player shape
  399. TSShapeInstance* si = new TSShapeInstance(mShape, false);
  400. TSThread* thread = si->addThread();
  401. // Extract ground transform velocity from animations
  402. // Get the named ones first so they can be indexed directly.
  403. ActionAnimation *dp = &actionList[0];
  404. for (S32 i = 0; i < NumTableActionAnims; i++,dp++)
  405. {
  406. ActionAnimationDef *sp = &ActionAnimationList[i];
  407. dp->name = sp->name;
  408. dp->dir.set(sp->dir.x,sp->dir.y,sp->dir.z);
  409. dp->sequence = mShape->findSequence(sp->name);
  410. // If this is a sprint action and is missing a sequence, attempt to use
  411. // the standard run ones.
  412. if(dp->sequence == -1 && i >= SprintRootAnim && i <= SprintRightAnim)
  413. {
  414. S32 offset = i-SprintRootAnim;
  415. ActionAnimationDef *standDef = &ActionAnimationList[RootAnim+offset];
  416. dp->sequence = mShape->findSequence(standDef->name);
  417. }
  418. dp->velocityScale = true;
  419. dp->death = false;
  420. if (dp->sequence != -1)
  421. getGroundInfo(si,thread,dp);
  422. }
  423. for (S32 b = 0; b < mShape->sequences.size(); b++)
  424. {
  425. if (!isTableSequence(b))
  426. {
  427. dp->sequence = b;
  428. dp->name = mShape->getName(mShape->sequences[b].nameIndex);
  429. dp->velocityScale = false;
  430. getGroundInfo(si,thread,dp++);
  431. }
  432. }
  433. actionCount = dp - actionList;
  434. AssertFatal(actionCount <= NumActionAnims, "Too many action animations!");
  435. delete si;
  436. // Resolve lookAction index
  437. dp = &actionList[0];
  438. String lookName("look");
  439. for (S32 c = 0; c < actionCount; c++,dp++)
  440. if( dStricmp( dp->name, lookName ) == 0 )
  441. lookAction = c;
  442. // Resolve spine
  443. spineNode[0] = mShape->findNode("Bip01 Pelvis");
  444. spineNode[1] = mShape->findNode("Bip01 Spine");
  445. spineNode[2] = mShape->findNode("Bip01 Spine1");
  446. spineNode[3] = mShape->findNode("Bip01 Spine2");
  447. spineNode[4] = mShape->findNode("Bip01 Neck");
  448. spineNode[5] = mShape->findNode("Bip01 Head");
  449. // Recoil animations
  450. recoilSequence[0] = mShape->findSequence("light_recoil");
  451. recoilSequence[1] = mShape->findSequence("medium_recoil");
  452. recoilSequence[2] = mShape->findSequence("heavy_recoil");
  453. }
  454. // Convert pickupRadius to a delta of boundingBox
  455. //
  456. // NOTE: it is not really correct to precalculate a pickupRadius based
  457. // on boxSize since the actual player's bounds can vary by "pose".
  458. //
  459. F32 dr = (boxSize.x > boxSize.y)? boxSize.x: boxSize.y;
  460. if (pickupRadius < dr)
  461. pickupRadius = dr;
  462. else
  463. if (pickupRadius > 2.0f * dr)
  464. pickupRadius = 2.0f * dr;
  465. pickupDelta = (S32)(pickupRadius - dr);
  466. // Validate jump speed
  467. if (maxJumpSpeed <= minJumpSpeed)
  468. maxJumpSpeed = minJumpSpeed + 0.1f;
  469. // Load up all the emitters
  470. if (!footPuffEmitter && footPuffID != 0)
  471. if (!Sim::findObject(footPuffID, footPuffEmitter))
  472. Con::errorf(ConsoleLogEntry::General, "PlayerData::preload - Invalid packet, bad datablockId(footPuffEmitter): 0x%x", footPuffID);
  473. if (!decalData && decalID != 0 )
  474. if (!Sim::findObject(decalID, decalData))
  475. Con::errorf(ConsoleLogEntry::General, "PlayerData::preload Invalid packet, bad datablockId(decalData): 0x%x", decalID);
  476. if (!dustEmitter && dustID != 0 )
  477. if (!Sim::findObject(dustID, dustEmitter))
  478. Con::errorf(ConsoleLogEntry::General, "PlayerData::preload - Invalid packet, bad datablockId(dustEmitter): 0x%x", dustID);
  479. for (S32 i=0; i<NUM_SPLASH_EMITTERS; i++)
  480. if( !splashEmitterList[i] && splashEmitterIDList[i] != 0 )
  481. if( Sim::findObject( splashEmitterIDList[i], splashEmitterList[i] ) == false)
  482. Con::errorf(ConsoleLogEntry::General, "PlayerData::onAdd - Invalid packet, bad datablockId(particle emitter): 0x%x", splashEmitterIDList[i]);
  483. // First person mounted image shapes.
  484. for (U32 i=0; i<ShapeBase::MaxMountedImages; ++i)
  485. {
  486. bool shapeError = false;
  487. if (shapeNameFP[i] && shapeNameFP[i][0])
  488. {
  489. mShapeFP[i] = ResourceManager::get().load(shapeNameFP[i]);
  490. if (bool(mShapeFP[i]) == false)
  491. {
  492. errorStr = String::ToString("PlayerData: Couldn't load mounted image %d shape \"%s\"",i,shapeNameFP[i]);
  493. return false;
  494. }
  495. if(!server && !mShapeFP[i]->preloadMaterialList(mShapeFP[i].getPath()) && NetConnection::filesWereDownloaded())
  496. shapeError = true;
  497. if(computeCRC)
  498. {
  499. Con::printf("Validation required for mounted image %d shape: %s", i, shapeNameFP[i]);
  500. Torque::FS::FileNodeRef fileRef = Torque::FS::GetFileNode(mShapeFP[i].getPath());
  501. if (!fileRef)
  502. {
  503. errorStr = String::ToString("PlayerData: Mounted image %d loading failed, shape \"%s\" is not found.",i,mShapeFP[i].getPath().getFullPath().c_str());
  504. return false;
  505. }
  506. if(server)
  507. mCRCFP[i] = fileRef->getChecksum();
  508. else if(mCRCFP[i] != fileRef->getChecksum())
  509. {
  510. errorStr = String::ToString("PlayerData: Mounted image %d shape \"%s\" does not match version on server.",i,shapeNameFP[i]);
  511. return false;
  512. }
  513. }
  514. mValidShapeFP[i] = true;
  515. }
  516. }
  517. return true;
  518. }
  519. void PlayerData::getGroundInfo(TSShapeInstance* si, TSThread* thread,ActionAnimation *dp)
  520. {
  521. dp->death = !dStrnicmp(dp->name, "death", 5);
  522. if (dp->death)
  523. {
  524. // Death animations use roll frame-to-frame changes in ground transform into position
  525. dp->speed = 0.0f;
  526. dp->dir.set(0.0f, 0.0f, 0.0f);
  527. // Death animations MUST define ground transforms, so add dummy ones if required
  528. if (si->getShape()->sequences[dp->sequence].numGroundFrames == 0)
  529. si->getShape()->setSequenceGroundSpeed(dp->name, Point3F(0, 0, 0), Point3F(0, 0, 0));
  530. }
  531. else
  532. {
  533. VectorF save = dp->dir;
  534. si->setSequence(thread,dp->sequence,0);
  535. si->animate();
  536. si->advanceTime(1);
  537. si->animateGround();
  538. si->getGroundTransform().getColumn(3,&dp->dir);
  539. if ((dp->speed = dp->dir.len()) < 0.01f)
  540. {
  541. // No ground displacement... In this case we'll use the
  542. // default table entry, if there is one.
  543. if (save.len() > 0.01f)
  544. {
  545. dp->dir = save;
  546. dp->speed = 1.0f;
  547. dp->velocityScale = false;
  548. }
  549. else
  550. dp->speed = 0.0f;
  551. }
  552. else
  553. dp->dir *= 1.0f / dp->speed;
  554. }
  555. }
  556. bool PlayerData::isTableSequence(S32 seq)
  557. {
  558. // The sequences from the table must already have
  559. // been loaded for this to work.
  560. for (S32 i = 0; i < NumTableActionAnims; i++)
  561. if (actionList[i].sequence == seq)
  562. return true;
  563. return false;
  564. }
  565. bool PlayerData::isJumpAction(U32 action)
  566. {
  567. return (action == JumpAnim || action == StandJumpAnim);
  568. }
  569. void PlayerData::initPersistFields()
  570. {
  571. addField( "pickupRadius", TypeF32, Offset(pickupRadius, PlayerData),
  572. "@brief Radius around the player to collide with Items in the scene (on server).\n\n"
  573. "Internally the pickupRadius is added to the larger side of the initial bounding box "
  574. "to determine the actual distance, to a maximum of 2 times the bounding box size. The "
  575. "initial bounding box is that used for the root pose, and therefore doesn't take into "
  576. "account the change in pose.\n");
  577. addField( "maxTimeScale", TypeF32, Offset(maxTimeScale, PlayerData),
  578. "@brief Maximum time scale for action animations.\n\n"
  579. "If an action animation has a defined ground frame, it is automatically scaled to match the "
  580. "player's ground velocity. This field limits the maximum time scale used even if "
  581. "the player's velocity exceeds it." );
  582. addGroup( "Camera" );
  583. addField( "renderFirstPerson", TypeBool, Offset(renderFirstPerson, PlayerData),
  584. "@brief Flag controlling whether to render the player shape in first person view.\n\n" );
  585. addField( "firstPersonShadows", TypeBool, Offset(firstPersonShadows, PlayerData),
  586. "@brief Forces shadows to be rendered in first person when renderFirstPerson is disabled. Defaults to false.\n\n" );
  587. addField( "minLookAngle", TypeF32, Offset(minLookAngle, PlayerData),
  588. "@brief Lowest angle (in radians) the player can look.\n\n"
  589. "@note An angle of zero is straight ahead, with positive up and negative down." );
  590. addField( "maxLookAngle", TypeF32, Offset(maxLookAngle, PlayerData),
  591. "@brief Highest angle (in radians) the player can look.\n\n"
  592. "@note An angle of zero is straight ahead, with positive up and negative down." );
  593. addField( "maxFreelookAngle", TypeF32, Offset(maxFreelookAngle, PlayerData),
  594. "@brief Defines the maximum left and right angles (in radians) the player can "
  595. "look in freelook mode.\n\n" );
  596. endGroup( "Camera" );
  597. addGroup( "Movement" );
  598. addField( "maxStepHeight", TypeF32, Offset(maxStepHeight, PlayerData),
  599. "@brief Maximum height the player can step up.\n\n"
  600. "The player will automatically step onto changes in ground height less "
  601. "than maxStepHeight. The player will collide with ground height changes "
  602. "greater than this." );
  603. addField( "runForce", TypeF32, Offset(runForce, PlayerData),
  604. "@brief Force used to accelerate the player when running.\n\n" );
  605. addField( "runEnergyDrain", TypeF32, Offset(runEnergyDrain, PlayerData),
  606. "@brief Energy value drained each tick that the player is moving.\n\n"
  607. "The player will not be able to move when his energy falls below "
  608. "minRunEnergy.\n"
  609. "@note Setting this to zero will disable any energy drain.\n"
  610. "@see minRunEnergy\n");
  611. addField( "minRunEnergy", TypeF32, Offset(minRunEnergy, PlayerData),
  612. "@brief Minimum energy level required to run or swim.\n\n"
  613. "@see runEnergyDrain\n");
  614. addField( "maxForwardSpeed", TypeF32, Offset(maxForwardSpeed, PlayerData),
  615. "@brief Maximum forward speed when running." );
  616. addField( "maxBackwardSpeed", TypeF32, Offset(maxBackwardSpeed, PlayerData),
  617. "@brief Maximum backward speed when running." );
  618. addField( "maxSideSpeed", TypeF32, Offset(maxSideSpeed, PlayerData),
  619. "@brief Maximum sideways speed when running." );
  620. addField( "runSurfaceAngle", TypeF32, Offset(runSurfaceAngle, PlayerData),
  621. "@brief Maximum angle from vertical (in degrees) the player can run up.\n\n" );
  622. addField( "minImpactSpeed", TypeF32, Offset(minImpactSpeed, PlayerData),
  623. "@brief Minimum impact speed to apply falling damage.\n\n"
  624. "This field also sets the minimum speed for the onImpact callback "
  625. "to be invoked.\n"
  626. "@see ShapeBaseData::onImpact()\n");
  627. addField( "minLateralImpactSpeed", TypeF32, Offset(minLateralImpactSpeed, PlayerData),
  628. "@brief Minimum impact speed to apply non-falling damage.\n\n"
  629. "This field also sets the minimum speed for the onLateralImpact callback "
  630. "to be invoked.\n"
  631. "@see ShapeBaseData::onLateralImpact()\n");
  632. addField( "horizMaxSpeed", TypeF32, Offset(horizMaxSpeed, PlayerData),
  633. "@brief Maximum horizontal speed.\n\n"
  634. "@note This limit is only enforced if the player's horizontal speed "
  635. "exceeds horizResistSpeed.\n"
  636. "@see horizResistSpeed\n"
  637. "@see horizResistFactor\n" );
  638. addField( "horizResistSpeed", TypeF32, Offset(horizResistSpeed, PlayerData),
  639. "@brief Horizontal speed at which resistence will take place.\n\n"
  640. "@see horizMaxSpeed\n"
  641. "@see horizResistFactor\n" );
  642. addField( "horizResistFactor", TypeF32, Offset(horizResistFactor, PlayerData),
  643. "@brief Factor of resistence once horizResistSpeed has been reached.\n\n"
  644. "@see horizMaxSpeed\n"
  645. "@see horizResistSpeed\n" );
  646. addField( "upMaxSpeed", TypeF32, Offset(upMaxSpeed, PlayerData),
  647. "@brief Maximum upwards speed.\n\n"
  648. "@note This limit is only enforced if the player's upward speed exceeds "
  649. "upResistSpeed.\n"
  650. "@see upResistSpeed\n"
  651. "@see upResistFactor\n" );
  652. addField( "upResistSpeed", TypeF32, Offset(upResistSpeed, PlayerData),
  653. "@brief Upwards speed at which resistence will take place.\n\n"
  654. "@see upMaxSpeed\n"
  655. "@see upResistFactor\n" );
  656. addField( "upResistFactor", TypeF32, Offset(upResistFactor, PlayerData),
  657. "@brief Factor of resistence once upResistSpeed has been reached.\n\n"
  658. "@see upMaxSpeed\n"
  659. "@see upResistSpeed\n" );
  660. endGroup( "Movement" );
  661. addGroup( "Movement: Jumping" );
  662. addField( "jumpForce", TypeF32, Offset(jumpForce, PlayerData),
  663. "@brief Force used to accelerate the player when a jump is initiated.\n\n" );
  664. addField( "jumpEnergyDrain", TypeF32, Offset(jumpEnergyDrain, PlayerData),
  665. "@brief Energy level drained each time the player jumps.\n\n"
  666. "@note Setting this to zero will disable any energy drain\n"
  667. "@see minJumpEnergy\n");
  668. addField( "minJumpEnergy", TypeF32, Offset(minJumpEnergy, PlayerData),
  669. "@brief Minimum energy level required to jump.\n\n"
  670. "@see jumpEnergyDrain\n");
  671. addField( "minJumpSpeed", TypeF32, Offset(minJumpSpeed, PlayerData),
  672. "@brief Minimum speed needed to jump.\n\n"
  673. "If the player's own z velocity is greater than this, then it is used to scale "
  674. "the jump speed, up to maxJumpSpeed.\n"
  675. "@see maxJumpSpeed\n");
  676. addField( "maxJumpSpeed", TypeF32, Offset(maxJumpSpeed, PlayerData),
  677. "@brief Maximum vertical speed before the player can no longer jump.\n\n" );
  678. addField( "jumpSurfaceAngle", TypeF32, Offset(jumpSurfaceAngle, PlayerData),
  679. "@brief Angle from vertical (in degrees) where the player can jump.\n\n" );
  680. addField( "jumpDelay", TypeS32, Offset(jumpDelay, PlayerData),
  681. "@brief Delay time in number of ticks ticks between jumps.\n\n" );
  682. addField( "airControl", TypeF32, Offset(airControl, PlayerData),
  683. "@brief Amount of movement control the player has when in the air.\n\n"
  684. "This is applied as a multiplier to the player's x and y motion.\n");
  685. addField( "jumpTowardsNormal", TypeBool, Offset(jumpTowardsNormal, PlayerData),
  686. "@brief Controls the direction of the jump impulse.\n"
  687. "When false, jumps are always in the vertical (+Z) direction. When true "
  688. "jumps are in the direction of the ground normal so long as the player is not "
  689. "directly facing the surface. If the player is directly facing the surface, then "
  690. "they will jump straight up.\n" );
  691. endGroup( "Movement: Jumping" );
  692. addGroup( "Movement: Sprinting" );
  693. addField( "sprintForce", TypeF32, Offset(sprintForce, PlayerData),
  694. "@brief Force used to accelerate the player when sprinting.\n\n" );
  695. addField( "sprintEnergyDrain", TypeF32, Offset(sprintEnergyDrain, PlayerData),
  696. "@brief Energy value drained each tick that the player is sprinting.\n\n"
  697. "The player will not be able to move when his energy falls below "
  698. "sprintEnergyDrain.\n"
  699. "@note Setting this to zero will disable any energy drain.\n"
  700. "@see minSprintEnergy\n");
  701. addField( "minSprintEnergy", TypeF32, Offset(minSprintEnergy, PlayerData),
  702. "@brief Minimum energy level required to sprint.\n\n"
  703. "@see sprintEnergyDrain\n");
  704. addField( "maxSprintForwardSpeed", TypeF32, Offset(maxSprintForwardSpeed, PlayerData),
  705. "@brief Maximum forward speed when sprinting." );
  706. addField( "maxSprintBackwardSpeed", TypeF32, Offset(maxSprintBackwardSpeed, PlayerData),
  707. "@brief Maximum backward speed when sprinting." );
  708. addField( "maxSprintSideSpeed", TypeF32, Offset(maxSprintSideSpeed, PlayerData),
  709. "@brief Maximum sideways speed when sprinting." );
  710. addField( "sprintStrafeScale", TypeF32, Offset(sprintStrafeScale, PlayerData),
  711. "@brief Amount to scale strafing motion vector while sprinting." );
  712. addField( "sprintYawScale", TypeF32, Offset(sprintYawScale, PlayerData),
  713. "@brief Amount to scale yaw motion while sprinting." );
  714. addField( "sprintPitchScale", TypeF32, Offset(sprintPitchScale, PlayerData),
  715. "@brief Amount to scale pitch motion while sprinting." );
  716. addField( "sprintCanJump", TypeBool, Offset(sprintCanJump, PlayerData),
  717. "@brief Can the player jump while sprinting." );
  718. endGroup( "Movement: Sprinting" );
  719. addGroup( "Movement: Swimming" );
  720. addField( "swimForce", TypeF32, Offset(swimForce, PlayerData),
  721. "@brief Force used to accelerate the player when swimming.\n\n" );
  722. addField( "maxUnderwaterForwardSpeed", TypeF32, Offset(maxUnderwaterForwardSpeed, PlayerData),
  723. "@brief Maximum forward speed when underwater.\n\n" );
  724. addField( "maxUnderwaterBackwardSpeed", TypeF32, Offset(maxUnderwaterBackwardSpeed, PlayerData),
  725. "@brief Maximum backward speed when underwater.\n\n" );
  726. addField( "maxUnderwaterSideSpeed", TypeF32, Offset(maxUnderwaterSideSpeed, PlayerData),
  727. "@brief Maximum sideways speed when underwater.\n\n" );
  728. endGroup( "Movement: Swimming" );
  729. addGroup( "Movement: Crouching" );
  730. addField( "crouchForce", TypeF32, Offset(crouchForce, PlayerData),
  731. "@brief Force used to accelerate the player when crouching.\n\n" );
  732. addField( "maxCrouchForwardSpeed", TypeF32, Offset(maxCrouchForwardSpeed, PlayerData),
  733. "@brief Maximum forward speed when crouching.\n\n" );
  734. addField( "maxCrouchBackwardSpeed", TypeF32, Offset(maxCrouchBackwardSpeed, PlayerData),
  735. "@brief Maximum backward speed when crouching.\n\n" );
  736. addField( "maxCrouchSideSpeed", TypeF32, Offset(maxCrouchSideSpeed, PlayerData),
  737. "@brief Maximum sideways speed when crouching.\n\n" );
  738. endGroup( "Movement: Crouching" );
  739. addGroup( "Movement: Prone" );
  740. addField( "proneForce", TypeF32, Offset(proneForce, PlayerData),
  741. "@brief Force used to accelerate the player when prone (laying down).\n\n" );
  742. addField( "maxProneForwardSpeed", TypeF32, Offset(maxProneForwardSpeed, PlayerData),
  743. "@brief Maximum forward speed when prone (laying down).\n\n" );
  744. addField( "maxProneBackwardSpeed", TypeF32, Offset(maxProneBackwardSpeed, PlayerData),
  745. "@brief Maximum backward speed when prone (laying down).\n\n" );
  746. addField( "maxProneSideSpeed", TypeF32, Offset(maxProneSideSpeed, PlayerData),
  747. "@brief Maximum sideways speed when prone (laying down).\n\n" );
  748. endGroup( "Movement: Prone" );
  749. addGroup( "Movement: Jetting" );
  750. addField( "jetJumpForce", TypeF32, Offset(jetJumpForce, PlayerData),
  751. "@brief Force used to accelerate the player when a jet jump is initiated.\n\n" );
  752. addField( "jetJumpEnergyDrain", TypeF32, Offset(jetJumpEnergyDrain, PlayerData),
  753. "@brief Energy level drained each time the player jet jumps.\n\n"
  754. "@note Setting this to zero will disable any energy drain\n"
  755. "@see jetMinJumpEnergy\n");
  756. addField( "jetMinJumpEnergy", TypeF32, Offset(jetMinJumpEnergy, PlayerData),
  757. "@brief Minimum energy level required to jet jump.\n\n"
  758. "@see jetJumpEnergyDrain\n");
  759. addField( "jetMinJumpSpeed", TypeF32, Offset(jetMinJumpSpeed, PlayerData),
  760. "@brief Minimum speed needed to jet jump.\n\n"
  761. "If the player's own z velocity is greater than this, then it is used to scale "
  762. "the jet jump speed, up to jetMaxJumpSpeed.\n"
  763. "@see jetMaxJumpSpeed\n");
  764. addField( "jetMaxJumpSpeed", TypeF32, Offset(jetMaxJumpSpeed, PlayerData),
  765. "@brief Maximum vertical speed before the player can no longer jet jump.\n\n" );
  766. addField( "jetJumpSurfaceAngle", TypeF32, Offset(jetJumpSurfaceAngle, PlayerData),
  767. "@brief Angle from vertical (in degrees) where the player can jet jump.\n\n" );
  768. endGroup( "Movement: Jetting" );
  769. addGroup( "Falling" );
  770. addField( "fallingSpeedThreshold", TypeF32, Offset(fallingSpeedThreshold, PlayerData),
  771. "@brief Downward speed at which we consider the player falling.\n\n" );
  772. addField( "recoverDelay", TypeS32, Offset(recoverDelay, PlayerData),
  773. "@brief Number of ticks for the player to recover from falling.\n\n" );
  774. addField( "recoverRunForceScale", TypeF32, Offset(recoverRunForceScale, PlayerData),
  775. "@brief Scale factor applied to runForce while in the recover state.\n\n"
  776. "This can be used to temporarily slow the player's movement after a fall, or "
  777. "prevent the player from moving at all if set to zero.\n" );
  778. addField( "landSequenceTime", TypeF32, Offset(landSequenceTime, PlayerData),
  779. "@brief Time of land sequence play back when using new recover system.\n\n"
  780. "If greater than 0 then the legacy fall recovery system will be bypassed "
  781. "in favour of just playing the player's land sequence. The time to "
  782. "recover from a fall then becomes this parameter's time and the land "
  783. "sequence's playback will be scaled to match.\n"
  784. "@see transitionToLand\n" );
  785. addField( "transitionToLand", TypeBool, Offset(transitionToLand, PlayerData),
  786. "@brief When going from a fall to a land, should we transition between the two.\n\n"
  787. "@note Only takes affect when landSequenceTime is greater than 0.\n"
  788. "@see landSequenceTime\n" );
  789. endGroup( "Falling" );
  790. addGroup( "Collision" );
  791. addField( "boundingBox", TypePoint3F, Offset(boxSize, PlayerData),
  792. "@brief Size of the bounding box used by the player for collision.\n\n"
  793. "Dimensions are given as \"width depth height\"." );
  794. addField( "crouchBoundingBox", TypePoint3F, Offset(crouchBoxSize, PlayerData),
  795. "@brief Collision bounding box used when the player is crouching.\n\n"
  796. "@see boundingBox" );
  797. addField( "proneBoundingBox", TypePoint3F, Offset(proneBoxSize, PlayerData),
  798. "@brief Collision bounding box used when the player is prone (laying down).\n\n"
  799. "@see boundingBox" );
  800. addField( "swimBoundingBox", TypePoint3F, Offset(swimBoxSize, PlayerData),
  801. "@brief Collision bounding box used when the player is swimming.\n\n"
  802. "@see boundingBox" );
  803. addField( "boxHeadPercentage", TypeF32, Offset(boxHeadPercentage, PlayerData),
  804. "@brief Percentage of the player's bounding box height that represents the head.\n\n"
  805. "Used when computing the damage location.\n"
  806. "@see Player::getDamageLocation" );
  807. addField( "boxTorsoPercentage", TypeF32, Offset(boxTorsoPercentage, PlayerData),
  808. "@brief Percentage of the player's bounding box height that represents the torso.\n\n"
  809. "Used when computing the damage location.\n"
  810. "@see Player::getDamageLocation" );
  811. addField( "boxHeadLeftPercentage", TypeF32, Offset(boxHeadLeftPercentage, PlayerData),
  812. "@brief Percentage of the player's bounding box width that represents the left side of the head.\n\n"
  813. "Used when computing the damage location.\n"
  814. "@see Player::getDamageLocation" );
  815. addField( "boxHeadRightPercentage", TypeF32, Offset(boxHeadRightPercentage, PlayerData),
  816. "@brief Percentage of the player's bounding box width that represents the right side of the head.\n\n"
  817. "Used when computing the damage location.\n"
  818. "@see Player::getDamageLocation" );
  819. addField( "boxHeadBackPercentage", TypeF32, Offset(boxHeadBackPercentage, PlayerData),
  820. "@brief Percentage of the player's bounding box depth that represents the back side of the head.\n\n"
  821. "Used when computing the damage location.\n"
  822. "@see Player::getDamageLocation" );
  823. addField( "boxHeadFrontPercentage", TypeF32, Offset(boxHeadFrontPercentage, PlayerData),
  824. "@brief Percentage of the player's bounding box depth that represents the front side of the head.\n\n"
  825. "Used when computing the damage location.\n"
  826. "@see Player::getDamageLocation" );
  827. endGroup( "Collision" );
  828. addGroup( "Interaction: Footsteps" );
  829. addField( "footPuffEmitter", TYPEID< ParticleEmitterData >(), Offset(footPuffEmitter, PlayerData),
  830. "@brief Particle emitter used to generate footpuffs (particles created as the player "
  831. "walks along the ground).\n\n"
  832. "@note The generation of foot puffs requires the appropriate triggeres to be defined in the "
  833. "player's animation sequences. Without these, no foot puffs will be generated.\n");
  834. addField( "footPuffNumParts", TypeS32, Offset(footPuffNumParts, PlayerData),
  835. "@brief Number of footpuff particles to generate each step.\n\n"
  836. "Each foot puff is randomly placed within the defined foot puff radius. This "
  837. "includes having footPuffNumParts set to one.\n"
  838. "@see footPuffRadius\n");
  839. addField( "footPuffRadius", TypeF32, Offset(footPuffRadius, PlayerData),
  840. "@brief Particle creation radius for footpuff particles.\n\n"
  841. "This is applied to each foot puff particle, even if footPuffNumParts is set to one. So "
  842. "set this value to zero if you want a single foot puff placed at exactly the same location "
  843. "under the player each time.\n");
  844. addField( "dustEmitter", TYPEID< ParticleEmitterData >(), Offset(dustEmitter, PlayerData),
  845. "@brief Emitter used to generate dust particles.\n\n"
  846. "@note Currently unused." );
  847. addField( "decalData", TYPEID< DecalData >(), Offset(decalData, PlayerData),
  848. "@brief Decal to place on the ground for player footsteps.\n\n" );
  849. addField( "decalOffset",TypeF32, Offset(decalOffset, PlayerData),
  850. "@brief Distance from the center of the model to the right foot.\n\n"
  851. "While this defines the distance to the right foot, it is also used to place "
  852. "the left foot decal as well. Just on the opposite side of the player." );
  853. endGroup( "Interaction: Footsteps" );
  854. addGroup( "Interaction: Sounds" );
  855. addField( "FootSoftSound", TypeSFXTrackName, Offset(sound[FootSoft], PlayerData),
  856. "@brief Sound to play when walking on a surface with Material footstepSoundId 0.\n\n" );
  857. addField( "FootHardSound", TypeSFXTrackName, Offset(sound[FootHard], PlayerData),
  858. "@brief Sound to play when walking on a surface with Material footstepSoundId 1.\n\n" );
  859. addField( "FootMetalSound", TypeSFXTrackName, Offset(sound[FootMetal], PlayerData),
  860. "@brief Sound to play when walking on a surface with Material footstepSoundId 2.\n\n" );
  861. addField( "FootSnowSound", TypeSFXTrackName, Offset(sound[FootSnow], PlayerData),
  862. "@brief Sound to play when walking on a surface with Material footstepSoundId 3.\n\n" );
  863. addField( "FootShallowSound", TypeSFXTrackName, Offset(sound[FootShallowSplash], PlayerData),
  864. "@brief Sound to play when walking in water and coverage is less than "
  865. "footSplashHeight.\n\n"
  866. "@see footSplashHeight\n" );
  867. addField( "FootWadingSound", TypeSFXTrackName, Offset(sound[FootWading], PlayerData),
  868. "@brief Sound to play when walking in water and coverage is less than 1, "
  869. "but > footSplashHeight.\n\n"
  870. "@see footSplashHeight\n" );
  871. addField( "FootUnderwaterSound", TypeSFXTrackName, Offset(sound[FootUnderWater], PlayerData),
  872. "@brief Sound to play when walking in water and coverage equals 1.0 "
  873. "(fully underwater).\n\n" );
  874. addField( "FootBubblesSound", TypeSFXTrackName, Offset(sound[FootBubbles], PlayerData),
  875. "@brief Sound to play when walking in water and coverage equals 1.0 "
  876. "(fully underwater).\n\n" );
  877. addField( "movingBubblesSound", TypeSFXTrackName, Offset(sound[MoveBubbles], PlayerData),
  878. "@brief Sound to play when in water and coverage equals 1.0 (fully underwater).\n\n"
  879. "Note that unlike FootUnderwaterSound, this sound plays even if the "
  880. "player is not moving around in the water.\n" );
  881. addField( "waterBreathSound", TypeSFXTrackName, Offset(sound[WaterBreath], PlayerData),
  882. "@brief Sound to play when in water and coverage equals 1.0 (fully underwater).\n\n"
  883. "Note that unlike FootUnderwaterSound, this sound plays even if the "
  884. "player is not moving around in the water.\n" );
  885. addField( "impactSoftSound", TypeSFXTrackName, Offset(sound[ImpactSoft], PlayerData),
  886. "@brief Sound to play after falling on a surface with Material footstepSoundId 0.\n\n" );
  887. addField( "impactHardSound", TypeSFXTrackName, Offset(sound[ImpactHard], PlayerData),
  888. "@brief Sound to play after falling on a surface with Material footstepSoundId 1.\n\n" );
  889. addField( "impactMetalSound", TypeSFXTrackName, Offset(sound[ImpactMetal], PlayerData),
  890. "@brief Sound to play after falling on a surface with Material footstepSoundId 2.\n\n" );
  891. addField( "impactSnowSound", TypeSFXTrackName, Offset(sound[ImpactSnow], PlayerData),
  892. "@brief Sound to play after falling on a surface with Material footstepSoundId 3.\n\n" );
  893. addField( "impactWaterEasy", TypeSFXTrackName, Offset(sound[ImpactWaterEasy], PlayerData),
  894. "@brief Sound to play when entering the water with velocity < "
  895. "mediumSplashSoundVelocity.\n\n"
  896. "@see mediumSplashSoundVelocity\n");
  897. addField( "impactWaterMedium", TypeSFXTrackName, Offset(sound[ImpactWaterMedium], PlayerData),
  898. "@brief Sound to play when entering the water with velocity >= "
  899. "mediumSplashSoundVelocity and < hardSplashSoundVelocity.\n\n"
  900. "@see mediumSplashSoundVelocity\n"
  901. "@see hardSplashSoundVelocity\n");
  902. addField( "impactWaterHard", TypeSFXTrackName, Offset(sound[ImpactWaterHard], PlayerData),
  903. "@brief Sound to play when entering the water with velocity >= "
  904. "hardSplashSoundVelocity.\n\n"
  905. "@see hardSplashSoundVelocity\n");
  906. addField( "exitingWater", TypeSFXTrackName, Offset(sound[ExitWater], PlayerData),
  907. "@brief Sound to play when exiting the water with velocity >= exitSplashSoundVelocity.\n\n"
  908. "@see exitSplashSoundVelocity\n");
  909. endGroup( "Interaction: Sounds" );
  910. addGroup( "Interaction: Splashes" );
  911. addField( "splash", TYPEID< SplashData >(), Offset(splash, PlayerData),
  912. "@brief SplashData datablock used to create splashes when the player moves "
  913. "through water.\n\n" );
  914. addField( "splashVelocity", TypeF32, Offset(splashVelocity, PlayerData),
  915. "@brief Minimum velocity when moving through water to generate splashes.\n\n" );
  916. addField( "splashAngle", TypeF32, Offset(splashAngle, PlayerData),
  917. "@brief Maximum angle (in degrees) from pure vertical movement in water to "
  918. "generate splashes.\n\n" );
  919. addField( "splashFreqMod", TypeF32, Offset(splashFreqMod, PlayerData),
  920. "@brief Multipled by speed to determine the number of splash particles to generate.\n\n" );
  921. addField( "splashVelEpsilon", TypeF32, Offset(splashVelEpsilon, PlayerData),
  922. "@brief Minimum speed to generate splash particles.\n\n" );
  923. addField( "bubbleEmitTime", TypeF32, Offset(bubbleEmitTime, PlayerData),
  924. "@brief Time in seconds to generate bubble particles after entering the water.\n\n" );
  925. addField( "splashEmitter", TYPEID< ParticleEmitterData >(), Offset(splashEmitterList, PlayerData), NUM_SPLASH_EMITTERS,
  926. "@brief Particle emitters used to generate splash particles.\n\n" );
  927. addField( "footstepSplashHeight", TypeF32, Offset(footSplashHeight, PlayerData),
  928. "@brief Water coverage level to choose between FootShallowSound and FootWadingSound.\n\n"
  929. "@see FootShallowSound\n"
  930. "@see FootWadingSound\n");
  931. addField( "mediumSplashSoundVelocity", TypeF32, Offset(medSplashSoundVel, PlayerData),
  932. "@brief Minimum velocity when entering the water for choosing between the impactWaterEasy and "
  933. "impactWaterMedium sounds to play.\n\n"
  934. "@see impactWaterEasy\n"
  935. "@see impactWaterMedium\n" );
  936. addField( "hardSplashSoundVelocity", TypeF32, Offset(hardSplashSoundVel, PlayerData),
  937. "@brief Minimum velocity when entering the water for choosing between the impactWaterMedium and "
  938. "impactWaterHard sound to play.\n\n"
  939. "@see impactWaterMedium\n"
  940. "@see impactWaterHard\n" );
  941. addField( "exitSplashSoundVelocity", TypeF32, Offset(exitSplashSoundVel, PlayerData),
  942. "@brief Minimum velocity when leaving the water for the exitingWater sound to "
  943. "play.\n\n"
  944. "@see exitingWater");
  945. endGroup( "Interaction: Splashes" );
  946. addGroup( "Interaction: Ground Impact" );
  947. addField( "groundImpactMinSpeed", TypeF32, Offset(groundImpactMinSpeed, PlayerData),
  948. "@brief Minimum falling impact speed to apply damage and initiate the camera "
  949. "shaking effect.\n\n" );
  950. addField( "groundImpactShakeFreq", TypePoint3F, Offset(groundImpactShakeFreq, PlayerData),
  951. "@brief Frequency of the camera shake effect after falling.\n\n"
  952. "This is how fast to shake the camera.\n");
  953. addField( "groundImpactShakeAmp", TypePoint3F, Offset(groundImpactShakeAmp, PlayerData),
  954. "@brief Amplitude of the camera shake effect after falling.\n\n"
  955. "This is how much to shake the camera.\n");
  956. addField( "groundImpactShakeDuration", TypeF32, Offset(groundImpactShakeDuration, PlayerData),
  957. "@brief Duration (in seconds) of the camera shake effect after falling.\n\n"
  958. "This is how long to shake the camera.\n");
  959. addField( "groundImpactShakeFalloff", TypeF32, Offset(groundImpactShakeFalloff, PlayerData),
  960. "@brief Falloff factor of the camera shake effect after falling.\n\n"
  961. "This is how to fade the camera shake over the duration.\n");
  962. endGroup( "Interaction: Ground Impact" );
  963. addGroup( "Physics" );
  964. // PhysicsPlayer
  965. addField( "physicsPlayerType", TypeString, Offset(physicsPlayerType, PlayerData),
  966. "@brief Specifies the type of physics used by the player.\n\n"
  967. "This depends on the physics module used. An example is 'Capsule'.\n"
  968. "@note Not current used.\n");
  969. endGroup( "Physics" );
  970. addGroup( "First Person Arms" );
  971. addField( "imageAnimPrefixFP", TypeCaseString, Offset(imageAnimPrefixFP, PlayerData),
  972. "@brief Optional prefix to all mounted image animation sequences in first person.\n\n"
  973. "This defines a prefix that will be added when looking up mounted image "
  974. "animation sequences while in first person. It allows for the customization "
  975. "of a first person image based on the type of player.\n");
  976. // Mounted images arrays
  977. addArray( "Mounted Images", ShapeBase::MaxMountedImages );
  978. addField( "shapeNameFP", TypeShapeFilename, Offset(shapeNameFP, PlayerData), ShapeBase::MaxMountedImages,
  979. "@brief File name of this player's shape that will be used in conjunction with the corresponding mounted image.\n\n"
  980. "These optional parameters correspond to each mounted image slot to indicate a shape that is rendered "
  981. "in addition to the mounted image shape. Typically these are a player's arms (or arm) that is "
  982. "animated along with the mounted image's state animation sequences.\n");
  983. endArray( "Mounted Images" );
  984. endGroup( "First Person Arms" );
  985. addGroup( "Third Person" );
  986. addField( "imageAnimPrefix", TypeCaseString, Offset(imageAnimPrefix, PlayerData),
  987. "@brief Optional prefix to all mounted image animation sequences in third person.\n\n"
  988. "This defines a prefix that will be added when looking up mounted image "
  989. "animation sequences while in third person. It allows for the customization "
  990. "of a third person image based on the type of player.\n");
  991. addField( "allowImageStateAnimation", TypeBool, Offset(allowImageStateAnimation, PlayerData),
  992. "@brief Allow mounted images to request a sequence be played on the Player.\n\n"
  993. "When true a new thread is added to the player to allow for "
  994. "mounted images to request a sequence be played on the player "
  995. "through the image's state machine. It is only optional so "
  996. "that we don't create a TSThread on the player if we don't "
  997. "need to.\n");
  998. endGroup( "Third Person" );
  999. Parent::initPersistFields();
  1000. }
  1001. void PlayerData::packData(BitStream* stream)
  1002. {
  1003. Parent::packData(stream);
  1004. stream->writeFlag(renderFirstPerson);
  1005. stream->writeFlag(firstPersonShadows);
  1006. stream->write(minLookAngle);
  1007. stream->write(maxLookAngle);
  1008. stream->write(maxFreelookAngle);
  1009. stream->write(maxTimeScale);
  1010. stream->write(mass);
  1011. stream->write(maxEnergy);
  1012. stream->write(drag);
  1013. stream->write(density);
  1014. stream->write(maxStepHeight);
  1015. stream->write(runForce);
  1016. stream->write(runEnergyDrain);
  1017. stream->write(minRunEnergy);
  1018. stream->write(maxForwardSpeed);
  1019. stream->write(maxBackwardSpeed);
  1020. stream->write(maxSideSpeed);
  1021. stream->write(runSurfaceAngle);
  1022. stream->write(fallingSpeedThreshold);
  1023. stream->write(recoverDelay);
  1024. stream->write(recoverRunForceScale);
  1025. stream->write(landSequenceTime);
  1026. stream->write(transitionToLand);
  1027. // Jumping
  1028. stream->write(jumpForce);
  1029. stream->write(jumpEnergyDrain);
  1030. stream->write(minJumpEnergy);
  1031. stream->write(minJumpSpeed);
  1032. stream->write(maxJumpSpeed);
  1033. stream->write(jumpSurfaceAngle);
  1034. stream->writeInt(jumpDelay,JumpDelayBits);
  1035. // Sprinting
  1036. stream->write(sprintForce);
  1037. stream->write(sprintEnergyDrain);
  1038. stream->write(minSprintEnergy);
  1039. stream->write(maxSprintForwardSpeed);
  1040. stream->write(maxSprintBackwardSpeed);
  1041. stream->write(maxSprintSideSpeed);
  1042. stream->write(sprintStrafeScale);
  1043. stream->write(sprintYawScale);
  1044. stream->write(sprintPitchScale);
  1045. stream->writeFlag(sprintCanJump);
  1046. // Swimming
  1047. stream->write(swimForce);
  1048. stream->write(maxUnderwaterForwardSpeed);
  1049. stream->write(maxUnderwaterBackwardSpeed);
  1050. stream->write(maxUnderwaterSideSpeed);
  1051. // Crouching
  1052. stream->write(crouchForce);
  1053. stream->write(maxCrouchForwardSpeed);
  1054. stream->write(maxCrouchBackwardSpeed);
  1055. stream->write(maxCrouchSideSpeed);
  1056. // Prone
  1057. stream->write(proneForce);
  1058. stream->write(maxProneForwardSpeed);
  1059. stream->write(maxProneBackwardSpeed);
  1060. stream->write(maxProneSideSpeed);
  1061. // Jetting
  1062. stream->write(jetJumpForce);
  1063. stream->write(jetJumpEnergyDrain);
  1064. stream->write(jetMinJumpEnergy);
  1065. stream->write(jetMinJumpSpeed);
  1066. stream->write(jetMaxJumpSpeed);
  1067. stream->write(jetJumpSurfaceAngle);
  1068. stream->write(horizMaxSpeed);
  1069. stream->write(horizResistSpeed);
  1070. stream->write(horizResistFactor);
  1071. stream->write(upMaxSpeed);
  1072. stream->write(upResistSpeed);
  1073. stream->write(upResistFactor);
  1074. stream->write(splashVelocity);
  1075. stream->write(splashAngle);
  1076. stream->write(splashFreqMod);
  1077. stream->write(splashVelEpsilon);
  1078. stream->write(bubbleEmitTime);
  1079. stream->write(medSplashSoundVel);
  1080. stream->write(hardSplashSoundVel);
  1081. stream->write(exitSplashSoundVel);
  1082. stream->write(footSplashHeight);
  1083. // Don't need damage scale on the client
  1084. stream->write(minImpactSpeed);
  1085. stream->write(minLateralImpactSpeed);
  1086. for( U32 i = 0; i < MaxSounds; i++)
  1087. sfxWrite( stream, sound[ i ] );
  1088. mathWrite(*stream, boxSize);
  1089. mathWrite(*stream, crouchBoxSize);
  1090. mathWrite(*stream, proneBoxSize);
  1091. mathWrite(*stream, swimBoxSize);
  1092. if( stream->writeFlag( footPuffEmitter ) )
  1093. {
  1094. stream->writeRangedU32( footPuffEmitter->getId(), DataBlockObjectIdFirst, DataBlockObjectIdLast );
  1095. }
  1096. stream->write( footPuffNumParts );
  1097. stream->write( footPuffRadius );
  1098. if( stream->writeFlag( decalData ) )
  1099. {
  1100. stream->writeRangedU32( decalData->getId(), DataBlockObjectIdFirst, DataBlockObjectIdLast );
  1101. }
  1102. stream->write(decalOffset);
  1103. if( stream->writeFlag( dustEmitter ) )
  1104. {
  1105. stream->writeRangedU32( dustEmitter->getId(), DataBlockObjectIdFirst, DataBlockObjectIdLast );
  1106. }
  1107. if (stream->writeFlag( splash ))
  1108. {
  1109. stream->writeRangedU32(splash->getId(), DataBlockObjectIdFirst, DataBlockObjectIdLast);
  1110. }
  1111. for( U32 i=0; i<NUM_SPLASH_EMITTERS; i++ )
  1112. {
  1113. if( stream->writeFlag( splashEmitterList[i] != NULL ) )
  1114. {
  1115. stream->writeRangedU32( splashEmitterList[i]->getId(), DataBlockObjectIdFirst, DataBlockObjectIdLast );
  1116. }
  1117. }
  1118. stream->write(groundImpactMinSpeed);
  1119. stream->write(groundImpactShakeFreq.x);
  1120. stream->write(groundImpactShakeFreq.y);
  1121. stream->write(groundImpactShakeFreq.z);
  1122. stream->write(groundImpactShakeAmp.x);
  1123. stream->write(groundImpactShakeAmp.y);
  1124. stream->write(groundImpactShakeAmp.z);
  1125. stream->write(groundImpactShakeDuration);
  1126. stream->write(groundImpactShakeFalloff);
  1127. // Air control
  1128. stream->write(airControl);
  1129. // Jump off at normal
  1130. stream->writeFlag(jumpTowardsNormal);
  1131. stream->writeString(physicsPlayerType);
  1132. // Third person mounted image shapes
  1133. stream->writeString(imageAnimPrefix);
  1134. stream->writeFlag(allowImageStateAnimation);
  1135. // First person mounted image shapes
  1136. stream->writeString(imageAnimPrefixFP);
  1137. for (U32 i=0; i<ShapeBase::MaxMountedImages; ++i)
  1138. {
  1139. stream->writeString(shapeNameFP[i]);
  1140. // computeCRC is handled in ShapeBaseData
  1141. if (computeCRC)
  1142. {
  1143. stream->write(mCRCFP[i]);
  1144. }
  1145. }
  1146. }
  1147. void PlayerData::unpackData(BitStream* stream)
  1148. {
  1149. Parent::unpackData(stream);
  1150. renderFirstPerson = stream->readFlag();
  1151. firstPersonShadows = stream->readFlag();
  1152. stream->read(&minLookAngle);
  1153. stream->read(&maxLookAngle);
  1154. stream->read(&maxFreelookAngle);
  1155. stream->read(&maxTimeScale);
  1156. stream->read(&mass);
  1157. stream->read(&maxEnergy);
  1158. stream->read(&drag);
  1159. stream->read(&density);
  1160. stream->read(&maxStepHeight);
  1161. stream->read(&runForce);
  1162. stream->read(&runEnergyDrain);
  1163. stream->read(&minRunEnergy);
  1164. stream->read(&maxForwardSpeed);
  1165. stream->read(&maxBackwardSpeed);
  1166. stream->read(&maxSideSpeed);
  1167. stream->read(&runSurfaceAngle);
  1168. stream->read(&fallingSpeedThreshold);
  1169. stream->read(&recoverDelay);
  1170. stream->read(&recoverRunForceScale);
  1171. stream->read(&landSequenceTime);
  1172. stream->read(&transitionToLand);
  1173. // Jumping
  1174. stream->read(&jumpForce);
  1175. stream->read(&jumpEnergyDrain);
  1176. stream->read(&minJumpEnergy);
  1177. stream->read(&minJumpSpeed);
  1178. stream->read(&maxJumpSpeed);
  1179. stream->read(&jumpSurfaceAngle);
  1180. jumpDelay = stream->readInt(JumpDelayBits);
  1181. // Sprinting
  1182. stream->read(&sprintForce);
  1183. stream->read(&sprintEnergyDrain);
  1184. stream->read(&minSprintEnergy);
  1185. stream->read(&maxSprintForwardSpeed);
  1186. stream->read(&maxSprintBackwardSpeed);
  1187. stream->read(&maxSprintSideSpeed);
  1188. stream->read(&sprintStrafeScale);
  1189. stream->read(&sprintYawScale);
  1190. stream->read(&sprintPitchScale);
  1191. sprintCanJump = stream->readFlag();
  1192. // Swimming
  1193. stream->read(&swimForce);
  1194. stream->read(&maxUnderwaterForwardSpeed);
  1195. stream->read(&maxUnderwaterBackwardSpeed);
  1196. stream->read(&maxUnderwaterSideSpeed);
  1197. // Crouching
  1198. stream->read(&crouchForce);
  1199. stream->read(&maxCrouchForwardSpeed);
  1200. stream->read(&maxCrouchBackwardSpeed);
  1201. stream->read(&maxCrouchSideSpeed);
  1202. // Prone
  1203. stream->read(&proneForce);
  1204. stream->read(&maxProneForwardSpeed);
  1205. stream->read(&maxProneBackwardSpeed);
  1206. stream->read(&maxProneSideSpeed);
  1207. // Jetting
  1208. stream->read(&jetJumpForce);
  1209. stream->read(&jetJumpEnergyDrain);
  1210. stream->read(&jetMinJumpEnergy);
  1211. stream->read(&jetMinJumpSpeed);
  1212. stream->read(&jetMaxJumpSpeed);
  1213. stream->read(&jetJumpSurfaceAngle);
  1214. stream->read(&horizMaxSpeed);
  1215. stream->read(&horizResistSpeed);
  1216. stream->read(&horizResistFactor);
  1217. stream->read(&upMaxSpeed);
  1218. stream->read(&upResistSpeed);
  1219. stream->read(&upResistFactor);
  1220. stream->read(&splashVelocity);
  1221. stream->read(&splashAngle);
  1222. stream->read(&splashFreqMod);
  1223. stream->read(&splashVelEpsilon);
  1224. stream->read(&bubbleEmitTime);
  1225. stream->read(&medSplashSoundVel);
  1226. stream->read(&hardSplashSoundVel);
  1227. stream->read(&exitSplashSoundVel);
  1228. stream->read(&footSplashHeight);
  1229. stream->read(&minImpactSpeed);
  1230. stream->read(&minLateralImpactSpeed);
  1231. for( U32 i = 0; i < MaxSounds; i++)
  1232. sfxRead( stream, &sound[ i ] );
  1233. mathRead(*stream, &boxSize);
  1234. mathRead(*stream, &crouchBoxSize);
  1235. mathRead(*stream, &proneBoxSize);
  1236. mathRead(*stream, &swimBoxSize);
  1237. if( stream->readFlag() )
  1238. {
  1239. footPuffID = (S32) stream->readRangedU32(DataBlockObjectIdFirst, DataBlockObjectIdLast);
  1240. }
  1241. stream->read(&footPuffNumParts);
  1242. stream->read(&footPuffRadius);
  1243. if( stream->readFlag() )
  1244. {
  1245. decalID = (S32) stream->readRangedU32(DataBlockObjectIdFirst, DataBlockObjectIdLast);
  1246. }
  1247. stream->read(&decalOffset);
  1248. if( stream->readFlag() )
  1249. {
  1250. dustID = (S32) stream->readRangedU32(DataBlockObjectIdFirst, DataBlockObjectIdLast);
  1251. }
  1252. if (stream->readFlag())
  1253. {
  1254. splashId = stream->readRangedU32( DataBlockObjectIdFirst, DataBlockObjectIdLast );
  1255. }
  1256. for( U32 i=0; i<NUM_SPLASH_EMITTERS; i++ )
  1257. {
  1258. if( stream->readFlag() )
  1259. {
  1260. splashEmitterIDList[i] = stream->readRangedU32( DataBlockObjectIdFirst, DataBlockObjectIdLast );
  1261. }
  1262. }
  1263. stream->read(&groundImpactMinSpeed);
  1264. stream->read(&groundImpactShakeFreq.x);
  1265. stream->read(&groundImpactShakeFreq.y);
  1266. stream->read(&groundImpactShakeFreq.z);
  1267. stream->read(&groundImpactShakeAmp.x);
  1268. stream->read(&groundImpactShakeAmp.y);
  1269. stream->read(&groundImpactShakeAmp.z);
  1270. stream->read(&groundImpactShakeDuration);
  1271. stream->read(&groundImpactShakeFalloff);
  1272. // Air control
  1273. stream->read(&airControl);
  1274. // Jump off at normal
  1275. jumpTowardsNormal = stream->readFlag();
  1276. physicsPlayerType = stream->readSTString();
  1277. // Third person mounted image shapes
  1278. imageAnimPrefix = stream->readSTString();
  1279. allowImageStateAnimation = stream->readFlag();
  1280. // First person mounted image shapes
  1281. imageAnimPrefixFP = stream->readSTString();
  1282. for (U32 i=0; i<ShapeBase::MaxMountedImages; ++i)
  1283. {
  1284. shapeNameFP[i] = stream->readSTString();
  1285. // computeCRC is handled in ShapeBaseData
  1286. if (computeCRC)
  1287. {
  1288. stream->read(&(mCRCFP[i]));
  1289. }
  1290. }
  1291. }
  1292. //----------------------------------------------------------------------------
  1293. //----------------------------------------------------------------------------
  1294. ImplementEnumType( PlayerPose,
  1295. "@brief The pose of the Player.\n\n"
  1296. "@ingroup gameObjects\n\n")
  1297. { Player::StandPose, "Stand", "Standard movement pose.\n" },
  1298. { Player::SprintPose, "Sprint", "Sprinting pose.\n" },
  1299. { Player::CrouchPose, "Crouch", "Crouch pose.\n" },
  1300. { Player::PronePose, "Prone", "Prone pose.\n" },
  1301. { Player::SwimPose, "Swim", "Swimming pose.\n" },
  1302. EndImplementEnumType;
  1303. //----------------------------------------------------------------------------
  1304. IMPLEMENT_CO_NETOBJECT_V1(Player);
  1305. ConsoleDocClass( Player,
  1306. "@ingroup gameObjects\n"
  1307. );
  1308. F32 Player::mGravity = -20;
  1309. //----------------------------------------------------------------------------
  1310. Player::Player()
  1311. {
  1312. mTypeMask |= PlayerObjectType | DynamicShapeObjectType;
  1313. mDelta.pos = mAnchorPoint = Point3F(0,0,100);
  1314. mDelta.rot = mDelta.head = Point3F(0,0,0);
  1315. mDelta.rotOffset.set(0.0f,0.0f,0.0f);
  1316. mDelta.warpOffset.set(0.0f,0.0f,0.0f);
  1317. mDelta.posVec.set(0.0f,0.0f,0.0f);
  1318. mDelta.rotVec.set(0.0f,0.0f,0.0f);
  1319. mDelta.headVec.set(0.0f,0.0f,0.0f);
  1320. mDelta.warpTicks = 0;
  1321. mDelta.dt = 1.0f;
  1322. mDelta.move = NullMove;
  1323. mPredictionCount = sMaxPredictionTicks;
  1324. mObjToWorld.setColumn(3, mDelta.pos);
  1325. mRot = mDelta.rot;
  1326. mHead = mDelta.head;
  1327. mVelocity.set(0.0f, 0.0f, 0.0f);
  1328. mDataBlock = 0;
  1329. mHeadHThread = mHeadVThread = mRecoilThread = mImageStateThread = 0;
  1330. mArmAnimation.action = PlayerData::NullAnimation;
  1331. mArmAnimation.thread = 0;
  1332. mActionAnimation.action = PlayerData::NullAnimation;
  1333. mActionAnimation.thread = 0;
  1334. mActionAnimation.delayTicks = 0;
  1335. mActionAnimation.forward = true;
  1336. mActionAnimation.firstPerson = false;
  1337. //mActionAnimation.time = 1.0f; //ActionAnimation::Scale;
  1338. mActionAnimation.waitForEnd = false;
  1339. mActionAnimation.holdAtEnd = false;
  1340. mActionAnimation.animateOnServer = false;
  1341. mActionAnimation.atEnd = false;
  1342. mState = MoveState;
  1343. mJetting = false;
  1344. mFalling = false;
  1345. mSwimming = false;
  1346. mInWater = false;
  1347. mPose = StandPose;
  1348. mContactTimer = 0;
  1349. mJumpDelay = 0;
  1350. mJumpSurfaceLastContact = 0;
  1351. mJumpSurfaceNormal.set(0.0f, 0.0f, 1.0f);
  1352. mControlObject = 0;
  1353. dMemset( mSplashEmitter, 0, sizeof( mSplashEmitter ) );
  1354. mUseHeadZCalc = true;
  1355. allowAllPoses();
  1356. mImpactSound = 0;
  1357. mRecoverTicks = 0;
  1358. mReversePending = 0;
  1359. mLastPos.set( 0.0f, 0.0f, 0.0f );
  1360. mMoveBubbleSound = 0;
  1361. mWaterBreathSound = 0;
  1362. mConvex.init(this);
  1363. mWorkingQueryBox.minExtents.set(-1e9f, -1e9f, -1e9f);
  1364. mWorkingQueryBox.maxExtents.set(-1e9f, -1e9f, -1e9f);
  1365. mWeaponBackFraction = 0.0f;
  1366. mInMissionArea = true;
  1367. mBubbleEmitterTime = 10.0;
  1368. mLastWaterPos.set( 0.0, 0.0, 0.0 );
  1369. mMountPending = 0;
  1370. mPhysicsRep = NULL;
  1371. for (U32 i=0; i<ShapeBase::MaxMountedImages; ++i)
  1372. {
  1373. mShapeFPInstance[i] = 0;
  1374. mShapeFPAmbientThread[i] = 0;
  1375. mShapeFPVisThread[i] = 0;
  1376. mShapeFPAnimThread[i] = 0;
  1377. mShapeFPFlashThread[i] = 0;
  1378. mShapeFPSpinThread[i] = 0;
  1379. }
  1380. mLastAbsoluteYaw = 0.0f;
  1381. mLastAbsolutePitch = 0.0f;
  1382. mLastAbsoluteRoll = 0.0f;
  1383. afx_init();
  1384. }
  1385. Player::~Player()
  1386. {
  1387. for (U32 i=0; i<ShapeBase::MaxMountedImages; ++i)
  1388. {
  1389. delete mShapeFPInstance[i];
  1390. mShapeFPInstance[i] = 0;
  1391. }
  1392. }
  1393. //----------------------------------------------------------------------------
  1394. bool Player::onAdd()
  1395. {
  1396. ActionAnimation serverAnim = mActionAnimation;
  1397. if(!Parent::onAdd() || !mDataBlock)
  1398. return false;
  1399. mWorkingQueryBox.minExtents.set(-1e9f, -1e9f, -1e9f);
  1400. mWorkingQueryBox.maxExtents.set(-1e9f, -1e9f, -1e9f);
  1401. addToScene();
  1402. // Make sure any state and animation passed from the server
  1403. // in the initial update is set correctly.
  1404. ActionState state = mState;
  1405. mState = NullState;
  1406. setState(state);
  1407. setPose(StandPose);
  1408. if (serverAnim.action != PlayerData::NullAnimation)
  1409. {
  1410. setActionThread(serverAnim.action, true, serverAnim.holdAtEnd, true, false, true);
  1411. if (serverAnim.atEnd)
  1412. {
  1413. mShapeInstance->clearTransition(mActionAnimation.thread);
  1414. mShapeInstance->setPos(mActionAnimation.thread,
  1415. mActionAnimation.forward ? 1.0f : 0.0f);
  1416. if (inDeathAnim())
  1417. mDeath.lastPos = 1.0f;
  1418. }
  1419. // We have to leave them sitting for a while since mounts don't come through right
  1420. // away (and sometimes not for a while). Still going to let this time out because
  1421. // I'm not sure if we're guaranteed another anim will come through and cancel.
  1422. if (!isServerObject() && inSittingAnim())
  1423. mMountPending = (S32) sMountPendingTickWait;
  1424. else
  1425. mMountPending = 0;
  1426. }
  1427. if (mArmAnimation.action != PlayerData::NullAnimation)
  1428. setArmThread(mArmAnimation.action);
  1429. //
  1430. if (isServerObject())
  1431. {
  1432. scriptOnAdd();
  1433. }
  1434. else
  1435. {
  1436. U32 i;
  1437. for( i=0; i<PlayerData::NUM_SPLASH_EMITTERS; i++ )
  1438. {
  1439. if ( mDataBlock->splashEmitterList[i] )
  1440. {
  1441. mSplashEmitter[i] = new ParticleEmitter;
  1442. mSplashEmitter[i]->onNewDataBlock( mDataBlock->splashEmitterList[i], false );
  1443. if( !mSplashEmitter[i]->registerObject() )
  1444. {
  1445. Con::warnf( ConsoleLogEntry::General, "Could not register splash emitter for class: %s", mDataBlock->getName() );
  1446. mSplashEmitter[i].getPointer()->destroySelf();
  1447. mSplashEmitter[i] = NULL;
  1448. }
  1449. }
  1450. }
  1451. mLastWaterPos = getPosition();
  1452. // clear out all camera effects
  1453. gCamFXMgr.clear();
  1454. }
  1455. if ( PHYSICSMGR )
  1456. {
  1457. PhysicsWorld *world = PHYSICSMGR->getWorld( isServerObject() ? "server" : "client" );
  1458. mPhysicsRep = PHYSICSMGR->createPlayer();
  1459. mPhysicsRep->init( mDataBlock->physicsPlayerType,
  1460. mDataBlock->boxSize,
  1461. mDataBlock->runSurfaceCos,
  1462. mDataBlock->maxStepHeight,
  1463. this,
  1464. world );
  1465. mPhysicsRep->setTransform( getTransform() );
  1466. }
  1467. return true;
  1468. }
  1469. void Player::onRemove()
  1470. {
  1471. setControlObject(0);
  1472. scriptOnRemove();
  1473. removeFromScene();
  1474. if ( isGhost() )
  1475. {
  1476. SFX_DELETE( mMoveBubbleSound );
  1477. SFX_DELETE( mWaterBreathSound );
  1478. }
  1479. U32 i;
  1480. for( i=0; i<PlayerData::NUM_SPLASH_EMITTERS; i++ )
  1481. {
  1482. if( mSplashEmitter[i] )
  1483. {
  1484. mSplashEmitter[i]->deleteWhenEmpty();
  1485. mSplashEmitter[i] = NULL;
  1486. }
  1487. }
  1488. mWorkingQueryBox.minExtents.set(-1e9f, -1e9f, -1e9f);
  1489. mWorkingQueryBox.maxExtents.set(-1e9f, -1e9f, -1e9f);
  1490. SAFE_DELETE( mPhysicsRep );
  1491. Parent::onRemove();
  1492. }
  1493. void Player::onScaleChanged()
  1494. {
  1495. const Point3F& scale = getScale();
  1496. mScaledBox = mObjBox;
  1497. mScaledBox.minExtents.convolve( scale );
  1498. mScaledBox.maxExtents.convolve( scale );
  1499. }
  1500. //----------------------------------------------------------------------------
  1501. bool Player::onNewDataBlock( GameBaseData *dptr, bool reload )
  1502. {
  1503. PlayerData* prevData = mDataBlock;
  1504. mDataBlock = dynamic_cast<PlayerData*>(dptr);
  1505. if ( !mDataBlock || !Parent::onNewDataBlock( dptr, reload ) )
  1506. return false;
  1507. // Player requires a shape instance.
  1508. if ( mShapeInstance == NULL )
  1509. return false;
  1510. // Initialize arm thread, preserve arm sequence from last datablock.
  1511. // Arm animation can be from last datablock, or sent from the server.
  1512. U32 prevAction = mArmAnimation.action;
  1513. mArmAnimation.action = PlayerData::NullAnimation;
  1514. if (mDataBlock->lookAction) {
  1515. mArmAnimation.thread = mShapeInstance->addThread();
  1516. mShapeInstance->setTimeScale(mArmAnimation.thread,0);
  1517. if (prevData) {
  1518. if (prevAction != prevData->lookAction && prevAction != PlayerData::NullAnimation)
  1519. setArmThread(prevData->actionList[prevAction].name);
  1520. prevAction = PlayerData::NullAnimation;
  1521. }
  1522. if (mArmAnimation.action == PlayerData::NullAnimation) {
  1523. mArmAnimation.action = (prevAction != PlayerData::NullAnimation)?
  1524. prevAction: mDataBlock->lookAction;
  1525. mShapeInstance->setSequence(mArmAnimation.thread,
  1526. mDataBlock->actionList[mArmAnimation.action].sequence,0);
  1527. }
  1528. }
  1529. else
  1530. mArmAnimation.thread = 0;
  1531. // Initialize head look thread
  1532. TSShape const* shape = mShapeInstance->getShape();
  1533. S32 headSeq = shape->findSequence("head");
  1534. if (headSeq != -1) {
  1535. mHeadVThread = mShapeInstance->addThread();
  1536. mShapeInstance->setSequence(mHeadVThread,headSeq,0);
  1537. mShapeInstance->setTimeScale(mHeadVThread,0);
  1538. }
  1539. else
  1540. mHeadVThread = 0;
  1541. headSeq = shape->findSequence("headside");
  1542. if (headSeq != -1) {
  1543. mHeadHThread = mShapeInstance->addThread();
  1544. mShapeInstance->setSequence(mHeadHThread,headSeq,0);
  1545. mShapeInstance->setTimeScale(mHeadHThread,0);
  1546. }
  1547. else
  1548. mHeadHThread = 0;
  1549. // Create Recoil thread if any recoil sequences are specified.
  1550. // Note that the server player does not play this animation.
  1551. mRecoilThread = 0;
  1552. if (isGhost())
  1553. for (U32 s = 0; s < PlayerData::NumRecoilSequences; s++)
  1554. if (mDataBlock->recoilSequence[s] != -1) {
  1555. mRecoilThread = mShapeInstance->addThread();
  1556. mShapeInstance->setSequence(mRecoilThread, mDataBlock->recoilSequence[s], 0);
  1557. mShapeInstance->setTimeScale(mRecoilThread, 0);
  1558. break;
  1559. }
  1560. // Reset the image state driven animation thread. This will be properly built
  1561. // in onImageStateAnimation() when needed.
  1562. mImageStateThread = 0;
  1563. // Initialize the primary thread, the actual sequence is
  1564. // set later depending on player actions.
  1565. mActionAnimation.action = PlayerData::NullAnimation;
  1566. mActionAnimation.thread = mShapeInstance->addThread();
  1567. updateAnimationTree(!isGhost());
  1568. // First person mounted image shapes. Only on client.
  1569. if ( isGhost() )
  1570. {
  1571. for (U32 i=0; i<ShapeBase::MaxMountedImages; ++i)
  1572. {
  1573. if (bool(mDataBlock->mShapeFP[i]))
  1574. {
  1575. mShapeFPInstance[i] = new TSShapeInstance(mDataBlock->mShapeFP[i], isClientObject());
  1576. mShapeFPInstance[i]->cloneMaterialList();
  1577. // Ambient animation
  1578. if (mShapeFPAmbientThread[i])
  1579. {
  1580. S32 seq = mShapeFPInstance[i]->getShape()->findSequence("ambient");
  1581. if (seq != -1)
  1582. {
  1583. mShapeFPAmbientThread[i] = mShapeFPInstance[i]->addThread();
  1584. mShapeFPInstance[i]->setTimeScale(mShapeFPAmbientThread[i], 1);
  1585. mShapeFPInstance[i]->setSequence(mShapeFPAmbientThread[i], seq, 0);
  1586. }
  1587. }
  1588. // Standard state animation
  1589. mShapeFPAnimThread[i] = mShapeFPInstance[i]->addThread();
  1590. if (mShapeFPAnimThread[i])
  1591. {
  1592. mShapeFPInstance[i]->setTimeScale(mShapeFPAnimThread[i],0);
  1593. }
  1594. }
  1595. }
  1596. }
  1597. if ( isGhost() )
  1598. {
  1599. // Create the sounds ahead of time. This reduces runtime
  1600. // costs and makes the system easier to understand.
  1601. SFX_DELETE( mMoveBubbleSound );
  1602. SFX_DELETE( mWaterBreathSound );
  1603. if ( mDataBlock->sound[PlayerData::MoveBubbles] )
  1604. mMoveBubbleSound = SFX->createSource( mDataBlock->sound[PlayerData::MoveBubbles] );
  1605. if ( mDataBlock->sound[PlayerData::WaterBreath] )
  1606. mWaterBreathSound = SFX->createSource( mDataBlock->sound[PlayerData::WaterBreath] );
  1607. }
  1608. mObjBox.maxExtents.x = mDataBlock->boxSize.x * 0.5f;
  1609. mObjBox.maxExtents.y = mDataBlock->boxSize.y * 0.5f;
  1610. mObjBox.maxExtents.z = mDataBlock->boxSize.z;
  1611. mObjBox.minExtents.x = -mObjBox.maxExtents.x;
  1612. mObjBox.minExtents.y = -mObjBox.maxExtents.y;
  1613. mObjBox.minExtents.z = 0.0f;
  1614. // Setup the box for our convex object...
  1615. mObjBox.getCenter(&mConvex.mCenter);
  1616. mConvex.mSize.x = mObjBox.len_x() / 2.0f;
  1617. mConvex.mSize.y = mObjBox.len_y() / 2.0f;
  1618. mConvex.mSize.z = mObjBox.len_z() / 2.0f;
  1619. // Initialize our scaled attributes as well
  1620. onScaleChanged();
  1621. resetWorldBox();
  1622. scriptOnNewDataBlock();
  1623. return true;
  1624. }
  1625. //----------------------------------------------------------------------------
  1626. void Player::reSkin()
  1627. {
  1628. if ( isGhost() && mShapeInstance && mSkinNameHandle.isValidString() )
  1629. {
  1630. mShapeInstance->resetMaterialList();
  1631. Vector<String> skins;
  1632. String(mSkinNameHandle.getString()).split( ";", skins );
  1633. for ( S32 i = 0; i < skins.size(); i++ )
  1634. {
  1635. String oldSkin( mAppliedSkinName.c_str() );
  1636. String newSkin( skins[i] );
  1637. // Check if the skin handle contains an explicit "old" base string. This
  1638. // allows all models to support skinning, even if they don't follow the
  1639. // "base_xxx" material naming convention.
  1640. S32 split = newSkin.find( '=' ); // "old=new" format skin?
  1641. if ( split != String::NPos )
  1642. {
  1643. oldSkin = newSkin.substr( 0, split );
  1644. newSkin = newSkin.erase( 0, split+1 );
  1645. }
  1646. // Apply skin to both 3rd person and 1st person shape instances
  1647. mShapeInstance->reSkin( newSkin, oldSkin );
  1648. for ( S32 j = 0; j < ShapeBase::MaxMountedImages; j++ )
  1649. {
  1650. if (mShapeFPInstance[j])
  1651. mShapeFPInstance[j]->reSkin( newSkin, oldSkin );
  1652. }
  1653. mAppliedSkinName = newSkin;
  1654. }
  1655. }
  1656. }
  1657. //----------------------------------------------------------------------------
  1658. void Player::setControllingClient(GameConnection* client)
  1659. {
  1660. Parent::setControllingClient(client);
  1661. if (mControlObject)
  1662. mControlObject->setControllingClient(client);
  1663. }
  1664. void Player::setControlObject(ShapeBase* obj)
  1665. {
  1666. if (mControlObject == obj)
  1667. return;
  1668. if (mControlObject) {
  1669. mControlObject->setControllingObject(0);
  1670. mControlObject->setControllingClient(0);
  1671. }
  1672. if (obj == this || obj == 0)
  1673. mControlObject = 0;
  1674. else {
  1675. if (ShapeBase* coo = obj->getControllingObject())
  1676. coo->setControlObject(0);
  1677. if (GameConnection* con = obj->getControllingClient())
  1678. con->setControlObject(0);
  1679. mControlObject = obj;
  1680. mControlObject->setControllingObject(this);
  1681. mControlObject->setControllingClient(getControllingClient());
  1682. }
  1683. }
  1684. void Player::onCameraScopeQuery(NetConnection *connection, CameraScopeQuery *query)
  1685. {
  1686. // First, we are certainly in scope, and whatever we're riding is too...
  1687. if(mControlObject.isNull() || mControlObject == mMount.object)
  1688. Parent::onCameraScopeQuery(connection, query);
  1689. else
  1690. {
  1691. connection->objectInScope(this);
  1692. if (isMounted())
  1693. connection->objectInScope(mMount.object);
  1694. mControlObject->onCameraScopeQuery(connection, query);
  1695. }
  1696. }
  1697. ShapeBase* Player::getControlObject()
  1698. {
  1699. return mControlObject;
  1700. }
  1701. void Player::processTick(const Move* move)
  1702. {
  1703. PROFILE_SCOPE(Player_ProcessTick);
  1704. bool prevMoveMotion = mMoveMotion;
  1705. Pose prevPose = getPose();
  1706. // If we're not being controlled by a client, let the
  1707. // AI sub-module get a chance at producing a move.
  1708. Move aiMove;
  1709. if (!move && isServerObject() && getAIMove(&aiMove))
  1710. move = &aiMove;
  1711. // Manage the control object and filter moves for the player
  1712. Move pMove,cMove;
  1713. if (mControlObject) {
  1714. if (!move)
  1715. mControlObject->processTick(0);
  1716. else {
  1717. pMove = NullMove;
  1718. cMove = *move;
  1719. //if (isMounted()) {
  1720. // Filter Jump trigger if mounted
  1721. //pMove.trigger[2] = move->trigger[2];
  1722. //cMove.trigger[2] = false;
  1723. //}
  1724. if (move->freeLook) {
  1725. // Filter yaw/picth/roll when freelooking.
  1726. pMove.yaw = move->yaw;
  1727. pMove.pitch = move->pitch;
  1728. pMove.roll = move->roll;
  1729. pMove.freeLook = true;
  1730. cMove.freeLook = false;
  1731. cMove.yaw = cMove.pitch = cMove.roll = 0.0f;
  1732. }
  1733. mControlObject->processTick((mDamageState == Enabled)? &cMove: &NullMove);
  1734. move = &pMove;
  1735. }
  1736. }
  1737. Parent::processTick(move);
  1738. // Check for state changes in the standard move triggers and
  1739. // set bits for any triggers that switched on this tick in
  1740. // the fx_s_triggers mask. Flag any changes to be packed to
  1741. // clients.
  1742. if (isServerObject())
  1743. {
  1744. fx_s_triggers = 0;
  1745. if (move)
  1746. {
  1747. U8 on_bits = 0;
  1748. for (S32 i = 0; i < MaxTriggerKeys; i++)
  1749. if (move->trigger[i])
  1750. on_bits |= BIT(i);
  1751. if (on_bits != move_trigger_states)
  1752. {
  1753. U8 switched_on_bits = (on_bits & ~move_trigger_states);
  1754. if (switched_on_bits)
  1755. {
  1756. fx_s_triggers |= (U32)switched_on_bits;
  1757. setMaskBits(TriggerMask);
  1758. }
  1759. move_trigger_states = on_bits;
  1760. }
  1761. }
  1762. }
  1763. // Warp to catch up to server
  1764. if (mDelta.warpTicks > 0) {
  1765. mDelta.warpTicks--;
  1766. // Set new pos
  1767. getTransform().getColumn(3, &mDelta.pos);
  1768. mDelta.pos += mDelta.warpOffset;
  1769. mDelta.rot += mDelta.rotOffset;
  1770. // Wrap yaw to +/-PI
  1771. if (mDelta.rot.z < - M_PI_F)
  1772. mDelta.rot.z += M_2PI_F;
  1773. else if (mDelta.rot.z > M_PI_F)
  1774. mDelta.rot.z -= M_2PI_F;
  1775. if (!ignore_updates)
  1776. {
  1777. setPosition(mDelta.pos, mDelta.rot);
  1778. }
  1779. updateDeathOffsets();
  1780. updateLookAnimation();
  1781. // Backstepping
  1782. mDelta.posVec = -mDelta.warpOffset;
  1783. mDelta.rotVec = -mDelta.rotOffset;
  1784. }
  1785. else {
  1786. // If there is no move, the player is either an
  1787. // unattached player on the server, or a player's
  1788. // client ghost.
  1789. if (!move) {
  1790. if (isGhost()) {
  1791. // If we haven't run out of prediction time,
  1792. // predict using the last known move.
  1793. if (mPredictionCount-- <= 0)
  1794. return;
  1795. move = &mDelta.move;
  1796. }
  1797. else
  1798. move = &NullMove;
  1799. }
  1800. if (!isGhost())
  1801. updateAnimation(TickSec);
  1802. PROFILE_START(Player_PhysicsSection);
  1803. if ( isServerObject() || didRenderLastRender() || getControllingClient() )
  1804. {
  1805. if ( !mPhysicsRep )
  1806. {
  1807. if ( isMounted() )
  1808. {
  1809. // If we're mounted then do not perform any collision checks
  1810. // and clear our previous working list.
  1811. mConvex.clearWorkingList();
  1812. }
  1813. else
  1814. {
  1815. updateWorkingCollisionSet();
  1816. }
  1817. }
  1818. updateState();
  1819. updateMove(move);
  1820. updateLookAnimation();
  1821. updateDeathOffsets();
  1822. updatePos();
  1823. }
  1824. PROFILE_END();
  1825. if (!isGhost())
  1826. {
  1827. // Animations are advanced based on frame rate on the
  1828. // client and must be ticked on the server.
  1829. updateActionThread();
  1830. updateAnimationTree(true);
  1831. // Check for sprinting motion changes
  1832. Pose currentPose = getPose();
  1833. // Player has just switched into Sprint pose and is moving
  1834. if (currentPose == SprintPose && prevPose != SprintPose && mMoveMotion)
  1835. {
  1836. mDataBlock->onStartSprintMotion_callback( this );
  1837. }
  1838. // Player has just switched out of Sprint pose and is moving, or was just moving
  1839. else if (currentPose != SprintPose && prevPose == SprintPose && (mMoveMotion || prevMoveMotion))
  1840. {
  1841. mDataBlock->onStopSprintMotion_callback( this );
  1842. }
  1843. // Player is in Sprint pose and has modified their motion
  1844. else if (currentPose == SprintPose && prevMoveMotion != mMoveMotion)
  1845. {
  1846. if (mMoveMotion)
  1847. {
  1848. mDataBlock->onStartSprintMotion_callback( this );
  1849. }
  1850. else
  1851. {
  1852. mDataBlock->onStopSprintMotion_callback( this );
  1853. }
  1854. }
  1855. }
  1856. }
  1857. // PATHSHAPE
  1858. if (!isGhost()) updateAttachment();
  1859. // PATHSHAPE END
  1860. }
  1861. void Player::interpolateTick(F32 dt)
  1862. {
  1863. if (mControlObject)
  1864. mControlObject->interpolateTick(dt);
  1865. // Client side interpolation
  1866. Parent::interpolateTick(dt);
  1867. Point3F pos = mDelta.pos + mDelta.posVec * dt;
  1868. Point3F rot = mDelta.rot + mDelta.rotVec * dt;
  1869. if (!ignore_updates)
  1870. setRenderPosition(pos,rot,dt);
  1871. /*
  1872. // apply camera effects - is this the best place? - bramage
  1873. GameConnection* connection = GameConnection::getConnectionToServer();
  1874. if( connection->isFirstPerson() )
  1875. {
  1876. ShapeBase *obj = dynamic_cast<ShapeBase*>(connection->getControlObject());
  1877. if( obj == this )
  1878. {
  1879. MatrixF curTrans = getRenderTransform();
  1880. curTrans.mul( gCamFXMgr.getTrans() );
  1881. Parent::setRenderTransform( curTrans );
  1882. }
  1883. }
  1884. */
  1885. updateLookAnimation(dt);
  1886. mDelta.dt = dt;
  1887. // PATHSHAPE
  1888. updateRenderChangesByParent();
  1889. // PATHSHAPE END
  1890. }
  1891. void Player::advanceTime(F32 dt)
  1892. {
  1893. // Client side animations
  1894. Parent::advanceTime(dt);
  1895. // Increment timer for triggering idle events.
  1896. if (idle_timer >= 0.0f)
  1897. idle_timer += dt;
  1898. updateActionThread();
  1899. updateAnimation(dt);
  1900. updateSplash();
  1901. updateFroth(dt);
  1902. updateWaterSounds(dt);
  1903. mLastPos = getPosition();
  1904. if (mImpactSound)
  1905. playImpactSound();
  1906. // update camera effects. Definitely need to find better place for this - bramage
  1907. if( isControlObject() )
  1908. {
  1909. if( mDamageState == Disabled || mDamageState == Destroyed )
  1910. {
  1911. // clear out all camera effects being applied to player if dead
  1912. gCamFXMgr.clear();
  1913. }
  1914. }
  1915. }
  1916. bool Player::getAIMove(Move* move)
  1917. {
  1918. return false;
  1919. }
  1920. void Player::setState(ActionState state, U32 recoverTicks)
  1921. {
  1922. if (state != mState) {
  1923. // Skip initialization if there is no manager, the state
  1924. // will get reset when the object is added to a manager.
  1925. if (isProperlyAdded()) {
  1926. switch (state) {
  1927. case RecoverState: {
  1928. if (mDataBlock->landSequenceTime > 0.0f)
  1929. {
  1930. // Use the land sequence as the basis for the recovery
  1931. setActionThread(PlayerData::LandAnim, true, false, true, true);
  1932. F32 timeScale = mShapeInstance->getDuration(mActionAnimation.thread) / mDataBlock->landSequenceTime;
  1933. mShapeInstance->setTimeScale(mActionAnimation.thread,timeScale);
  1934. mRecoverDelay = mDataBlock->landSequenceTime;
  1935. }
  1936. else
  1937. {
  1938. // Legacy recover system
  1939. mRecoverTicks = recoverTicks;
  1940. mReversePending = U32(F32(mRecoverTicks) / sLandReverseScale);
  1941. setActionThread(PlayerData::LandAnim, true, false, true, true);
  1942. }
  1943. break;
  1944. }
  1945. default:
  1946. break;
  1947. }
  1948. }
  1949. mState = state;
  1950. }
  1951. }
  1952. void Player::updateState()
  1953. {
  1954. switch (mState)
  1955. {
  1956. case RecoverState:
  1957. if (mDataBlock->landSequenceTime > 0.0f)
  1958. {
  1959. // Count down the land time
  1960. mRecoverDelay -= TickSec;
  1961. if (mRecoverDelay <= 0.0f)
  1962. {
  1963. setState(MoveState);
  1964. }
  1965. }
  1966. else
  1967. {
  1968. // Legacy recover system
  1969. if (mRecoverTicks-- <= 0)
  1970. {
  1971. if (mReversePending && mActionAnimation.action != PlayerData::NullAnimation)
  1972. {
  1973. // this serves and counter, and direction state
  1974. mRecoverTicks = mReversePending;
  1975. mActionAnimation.forward = false;
  1976. S32 seq = mDataBlock->actionList[mActionAnimation.action].sequence;
  1977. S32 imageBasedSeq = convertActionToImagePrefix(mActionAnimation.action);
  1978. if (imageBasedSeq != -1)
  1979. seq = imageBasedSeq;
  1980. F32 pos = mShapeInstance->getPos(mActionAnimation.thread);
  1981. mShapeInstance->setTimeScale(mActionAnimation.thread, -sLandReverseScale);
  1982. mShapeInstance->transitionToSequence(mActionAnimation.thread,
  1983. seq, pos, sAnimationTransitionTime, true);
  1984. mReversePending = 0;
  1985. }
  1986. else
  1987. {
  1988. setState(MoveState);
  1989. }
  1990. } // Stand back up slowly only if not moving much-
  1991. else if (!mReversePending && mVelocity.lenSquared() > sSlowStandThreshSquared)
  1992. {
  1993. mActionAnimation.waitForEnd = false;
  1994. setState(MoveState);
  1995. }
  1996. }
  1997. break;
  1998. default:
  1999. break;
  2000. }
  2001. }
  2002. const char* Player::getStateName()
  2003. {
  2004. if (mDamageState != Enabled)
  2005. return "Dead";
  2006. if (isMounted())
  2007. return "Mounted";
  2008. if (mState == RecoverState)
  2009. return "Recover";
  2010. return "Move";
  2011. }
  2012. void Player::getDamageLocation(const Point3F& in_rPos, const char *&out_rpVert, const char *&out_rpQuad)
  2013. {
  2014. // TODO: This will be WRONG when player is prone or swimming!
  2015. Point3F newPoint;
  2016. mWorldToObj.mulP(in_rPos, &newPoint);
  2017. Point3F boxSize = mObjBox.getExtents();
  2018. F32 zHeight = boxSize.z;
  2019. F32 zTorso = mDataBlock->boxTorsoPercentage;
  2020. F32 zHead = mDataBlock->boxHeadPercentage;
  2021. zTorso *= zHeight;
  2022. zHead *= zHeight;
  2023. if (newPoint.z <= zTorso)
  2024. out_rpVert = "legs";
  2025. else if (newPoint.z <= zHead)
  2026. out_rpVert = "torso";
  2027. else
  2028. out_rpVert = "head";
  2029. if(dStrcmp(out_rpVert, "head") != 0)
  2030. {
  2031. if (newPoint.y >= 0.0f)
  2032. {
  2033. if (newPoint.x <= 0.0f)
  2034. out_rpQuad = "front_left";
  2035. else
  2036. out_rpQuad = "front_right";
  2037. }
  2038. else
  2039. {
  2040. if (newPoint.x <= 0.0f)
  2041. out_rpQuad = "back_left";
  2042. else
  2043. out_rpQuad = "back_right";
  2044. }
  2045. }
  2046. else
  2047. {
  2048. F32 backToFront = boxSize.x;
  2049. F32 leftToRight = boxSize.y;
  2050. F32 backPoint = backToFront * mDataBlock->boxHeadBackPercentage;
  2051. F32 frontPoint = backToFront * mDataBlock->boxHeadFrontPercentage;
  2052. F32 leftPoint = leftToRight * mDataBlock->boxHeadLeftPercentage;
  2053. F32 rightPoint = leftToRight * mDataBlock->boxHeadRightPercentage;
  2054. S32 index = 0;
  2055. if (newPoint.y < backPoint)
  2056. index += 0;
  2057. else if (newPoint.y >= frontPoint)
  2058. index += 3;
  2059. else
  2060. index += 6;
  2061. if (newPoint.x < leftPoint)
  2062. index += 0;
  2063. else if (newPoint.x >= rightPoint)
  2064. index += 1;
  2065. else
  2066. index += 2;
  2067. switch (index)
  2068. {
  2069. case 0: out_rpQuad = "left_back"; break;
  2070. case 1: out_rpQuad = "middle_back"; break;
  2071. case 2: out_rpQuad = "right_back"; break;
  2072. case 3: out_rpQuad = "left_middle"; break;
  2073. case 4: out_rpQuad = "middle_middle"; break;
  2074. case 5: out_rpQuad = "right_middle"; break;
  2075. case 6: out_rpQuad = "left_front"; break;
  2076. case 7: out_rpQuad = "middle_front"; break;
  2077. case 8: out_rpQuad = "right_front"; break;
  2078. default:
  2079. AssertFatal(0, "Bad non-tant index");
  2080. };
  2081. }
  2082. }
  2083. const char* Player::getPoseName() const
  2084. {
  2085. return EngineMarshallData< PlayerPose >(getPose());
  2086. }
  2087. void Player::setPose( Pose pose )
  2088. {
  2089. // Already the set pose, return.
  2090. if ( pose == mPose )
  2091. return;
  2092. Pose oldPose = mPose;
  2093. mPose = pose;
  2094. // Not added yet, just assign the pose and return.
  2095. if ( !isProperlyAdded() )
  2096. return;
  2097. Point3F boxSize(1,1,1);
  2098. // Resize the player boxes
  2099. switch (pose)
  2100. {
  2101. case StandPose:
  2102. case SprintPose:
  2103. boxSize = mDataBlock->boxSize;
  2104. break;
  2105. case CrouchPose:
  2106. boxSize = mDataBlock->crouchBoxSize;
  2107. break;
  2108. case PronePose:
  2109. boxSize = mDataBlock->proneBoxSize;
  2110. break;
  2111. case SwimPose:
  2112. boxSize = mDataBlock->swimBoxSize;
  2113. break;
  2114. }
  2115. // Object and World Boxes...
  2116. mObjBox.maxExtents.x = boxSize.x * 0.5f;
  2117. mObjBox.maxExtents.y = boxSize.y * 0.5f;
  2118. mObjBox.maxExtents.z = boxSize.z;
  2119. mObjBox.minExtents.x = -mObjBox.maxExtents.x;
  2120. mObjBox.minExtents.y = -mObjBox.maxExtents.y;
  2121. mObjBox.minExtents.z = 0.0f;
  2122. resetWorldBox();
  2123. // Setup the box for our convex object...
  2124. mObjBox.getCenter(&mConvex.mCenter);
  2125. mConvex.mSize.x = mObjBox.len_x() / 2.0f;
  2126. mConvex.mSize.y = mObjBox.len_y() / 2.0f;
  2127. mConvex.mSize.z = mObjBox.len_z() / 2.0f;
  2128. // Initialize our scaled attributes as well...
  2129. onScaleChanged();
  2130. // Resize the PhysicsPlayer rep. should we have one
  2131. if ( mPhysicsRep )
  2132. mPhysicsRep->setSpacials( getPosition(), boxSize );
  2133. if ( isServerObject() )
  2134. mDataBlock->onPoseChange_callback( this, EngineMarshallData< PlayerPose >(oldPose), EngineMarshallData< PlayerPose >(mPose));
  2135. }
  2136. void Player::allowAllPoses()
  2137. {
  2138. mAllowJumping = true;
  2139. mAllowJetJumping = true;
  2140. mAllowSprinting = true;
  2141. mAllowCrouching = true;
  2142. mAllowProne = true;
  2143. mAllowSwimming = true;
  2144. }
  2145. AngAxisF gPlayerMoveRot;
  2146. void Player::updateMove(const Move* move)
  2147. {
  2148. struct Move my_move;
  2149. if (override_movement && movement_op < 3)
  2150. {
  2151. my_move = *move;
  2152. switch (movement_op)
  2153. {
  2154. case 0: // add
  2155. my_move.x += movement_data.x;
  2156. my_move.y += movement_data.y;
  2157. my_move.z += movement_data.z;
  2158. break;
  2159. case 1: // mult
  2160. my_move.x *= movement_data.x;
  2161. my_move.y *= movement_data.y;
  2162. my_move.z *= movement_data.z;
  2163. break;
  2164. case 2: // replace
  2165. my_move.x = movement_data.x;
  2166. my_move.y = movement_data.y;
  2167. my_move.z = movement_data.z;
  2168. break;
  2169. }
  2170. move = &my_move;
  2171. }
  2172. mDelta.move = *move;
  2173. #ifdef TORQUE_OPENVR
  2174. if (mControllers[0])
  2175. {
  2176. mControllers[0]->processTick(move);
  2177. }
  2178. if (mControllers[1])
  2179. {
  2180. mControllers[1]->processTick(move);
  2181. }
  2182. #endif
  2183. // Is waterCoverage high enough to be 'swimming'?
  2184. {
  2185. bool swimming = mWaterCoverage > 0.65f && canSwim();
  2186. if ( swimming != mSwimming )
  2187. {
  2188. if ( !isGhost() )
  2189. {
  2190. if ( swimming )
  2191. mDataBlock->onStartSwim_callback( this );
  2192. else
  2193. mDataBlock->onStopSwim_callback( this );
  2194. }
  2195. mSwimming = swimming;
  2196. }
  2197. }
  2198. // Trigger images
  2199. if (mDamageState == Enabled)
  2200. {
  2201. setImageTriggerState( 0, move->trigger[sImageTrigger0] );
  2202. // If you have a secondary mounted image then
  2203. // send the second trigger to it. Else give it
  2204. // to the first image as an alt fire.
  2205. if ( getMountedImage( 1 ) )
  2206. setImageTriggerState( 1, move->trigger[sImageTrigger1] );
  2207. else
  2208. setImageAltTriggerState( 0, move->trigger[sImageTrigger1] );
  2209. }
  2210. // Update current orientation
  2211. if (mDamageState == Enabled) {
  2212. F32 prevZRot = mRot.z;
  2213. mDelta.headVec = mHead;
  2214. bool doStandardMove = true;
  2215. bool absoluteDelta = false;
  2216. GameConnection* con = getControllingClient();
  2217. #ifdef TORQUE_EXTENDED_MOVE
  2218. // Work with an absolute rotation from the ExtendedMove class?
  2219. if(con && con->getControlSchemeAbsoluteRotation())
  2220. {
  2221. doStandardMove = false;
  2222. const ExtendedMove* emove = dynamic_cast<const ExtendedMove*>(move);
  2223. U32 emoveIndex = smExtendedMoveHeadPosRotIndex;
  2224. if(emoveIndex >= ExtendedMove::MaxPositionsRotations)
  2225. emoveIndex = 0;
  2226. if(emove->EulerBasedRotation[emoveIndex])
  2227. {
  2228. // Head pitch
  2229. mHead.x += (emove->rotX[emoveIndex] - mLastAbsolutePitch);
  2230. // Do we also include the relative yaw value?
  2231. if(con->getControlSchemeAddPitchToAbsRot())
  2232. {
  2233. F32 x = move->pitch;
  2234. if (x > M_PI_F)
  2235. x -= M_2PI_F;
  2236. mHead.x += x;
  2237. }
  2238. // Constrain the range of mHead.x
  2239. while (mHead.x < -M_PI_F)
  2240. mHead.x += M_2PI_F;
  2241. while (mHead.x > M_PI_F)
  2242. mHead.x -= M_2PI_F;
  2243. // Rotate (heading) head or body?
  2244. if (move->freeLook && ((isMounted() && getMountNode() == 0) || (con && !con->isFirstPerson())))
  2245. {
  2246. // Rotate head
  2247. mHead.z += (emove->rotZ[emoveIndex] - mLastAbsoluteYaw);
  2248. // Do we also include the relative yaw value?
  2249. if(con->getControlSchemeAddYawToAbsRot())
  2250. {
  2251. F32 z = move->yaw;
  2252. if (z > M_PI_F)
  2253. z -= M_2PI_F;
  2254. mHead.z += z;
  2255. }
  2256. // Constrain the range of mHead.z
  2257. while (mHead.z < 0.0f)
  2258. mHead.z += M_2PI_F;
  2259. while (mHead.z > M_2PI_F)
  2260. mHead.z -= M_2PI_F;
  2261. }
  2262. else
  2263. {
  2264. // Rotate body
  2265. mRot.z += (emove->rotZ[emoveIndex] - mLastAbsoluteYaw);
  2266. // Do we also include the relative yaw value?
  2267. if(con->getControlSchemeAddYawToAbsRot())
  2268. {
  2269. F32 z = move->yaw;
  2270. if (z > M_PI_F)
  2271. z -= M_2PI_F;
  2272. mRot.z += z;
  2273. }
  2274. // Constrain the range of mRot.z
  2275. while (mRot.z < 0.0f)
  2276. mRot.z += M_2PI_F;
  2277. while (mRot.z > M_2PI_F)
  2278. mRot.z -= M_2PI_F;
  2279. }
  2280. mLastAbsoluteYaw = emove->rotZ[emoveIndex];
  2281. mLastAbsolutePitch = emove->rotX[emoveIndex];
  2282. mLastAbsoluteRoll = emove->rotY[emoveIndex];
  2283. // Head bank
  2284. mHead.y = emove->rotY[emoveIndex];
  2285. // Constrain the range of mHead.y
  2286. while (mHead.y > M_PI_F)
  2287. mHead.y -= M_2PI_F;
  2288. }
  2289. else
  2290. {
  2291. // Orient the player so we are looking towards the required position, ignoring any banking
  2292. AngAxisF moveRot(Point3F(emove->rotX[emoveIndex], emove->rotY[emoveIndex], emove->rotZ[emoveIndex]), emove->rotW[emoveIndex]);
  2293. MatrixF trans(1);
  2294. moveRot.setMatrix(&trans);
  2295. trans.inverse();
  2296. Point3F vecForward(0, 10, 0);
  2297. Point3F viewAngle;
  2298. Point3F orient;
  2299. EulerF rot;
  2300. trans.mulV(vecForward);
  2301. viewAngle = vecForward;
  2302. vecForward.z = 0; // flatten
  2303. vecForward.normalizeSafe();
  2304. F32 yawAng;
  2305. F32 pitchAng;
  2306. MathUtils::getAnglesFromVector(vecForward, yawAng, pitchAng);
  2307. mRot = EulerF(0);
  2308. mRot.z = yawAng;
  2309. mHead = EulerF(0);
  2310. while (mRot.z < 0.0f)
  2311. mRot.z += M_2PI_F;
  2312. while (mRot.z > M_2PI_F)
  2313. mRot.z -= M_2PI_F;
  2314. absoluteDelta = true;
  2315. }
  2316. }
  2317. #endif
  2318. if(doStandardMove)
  2319. {
  2320. F32 p = move->pitch * (mPose == SprintPose ? mDataBlock->sprintPitchScale : 1.0f);
  2321. if (p > M_PI_F)
  2322. p -= M_2PI_F;
  2323. mHead.x = mClampF(mHead.x + p,mDataBlock->minLookAngle,
  2324. mDataBlock->maxLookAngle);
  2325. F32 y = move->yaw * (mPose == SprintPose ? mDataBlock->sprintYawScale : 1.0f);
  2326. if (y > M_PI_F)
  2327. y -= M_2PI_F;
  2328. if (move->freeLook && ((isMounted() && getMountNode() == 0) || (con && !con->isFirstPerson())))
  2329. {
  2330. mHead.z = mClampF(mHead.z + y,
  2331. -mDataBlock->maxFreelookAngle,
  2332. mDataBlock->maxFreelookAngle);
  2333. }
  2334. else
  2335. {
  2336. mRot.z += y;
  2337. // Rotate the head back to the front, center horizontal
  2338. // as well if we're controlling another object.
  2339. mHead.z *= 0.5f;
  2340. if (mControlObject)
  2341. mHead.x *= 0.5f;
  2342. }
  2343. // constrain the range of mRot.z
  2344. while (mRot.z < 0.0f)
  2345. mRot.z += M_2PI_F;
  2346. while (mRot.z > M_2PI_F)
  2347. mRot.z -= M_2PI_F;
  2348. }
  2349. mDelta.rot = mRot;
  2350. mDelta.rotVec.x = mDelta.rotVec.y = 0.0f;
  2351. mDelta.rotVec.z = prevZRot - mRot.z;
  2352. if (mDelta.rotVec.z > M_PI_F)
  2353. mDelta.rotVec.z -= M_2PI_F;
  2354. else if (mDelta.rotVec.z < -M_PI_F)
  2355. mDelta.rotVec.z += M_2PI_F;
  2356. mDelta.head = mHead;
  2357. mDelta.headVec -= mHead;
  2358. if (absoluteDelta)
  2359. {
  2360. mDelta.headVec = Point3F(0, 0, 0);
  2361. mDelta.rotVec = Point3F(0, 0, 0);
  2362. }
  2363. for(U32 i=0; i<3; ++i)
  2364. {
  2365. if (mDelta.headVec[i] > M_PI_F)
  2366. mDelta.headVec[i] -= M_2PI_F;
  2367. else if (mDelta.headVec[i] < -M_PI_F)
  2368. mDelta.headVec[i] += M_2PI_F;
  2369. }
  2370. }
  2371. MatrixF zRot;
  2372. zRot.set(EulerF(0.0f, 0.0f, mRot.z));
  2373. // Desired move direction & speed
  2374. VectorF moveVec;
  2375. F32 moveSpeed;
  2376. // If BLOCK_USER_CONTROL is set in anim_clip_flags, the user won't be able to
  2377. // resume control over the player character. This generally happens for
  2378. // short periods of time synchronized with script driven animation at places
  2379. // where it makes sense that user motion is prohibited, such as when the
  2380. // player is lifted off the ground or knocked down.
  2381. if ((mState == MoveState || (mState == RecoverState && mDataBlock->recoverRunForceScale > 0.0f)) && mDamageState == Enabled && !isAnimationLocked())
  2382. {
  2383. zRot.getColumn(0,&moveVec);
  2384. moveVec *= (move->x * (mPose == SprintPose ? mDataBlock->sprintStrafeScale : 1.0f));
  2385. VectorF tv;
  2386. zRot.getColumn(1,&tv);
  2387. moveVec += tv * move->y;
  2388. // Clamp water movement
  2389. if (move->y > 0.0f)
  2390. {
  2391. if ( mSwimming )
  2392. moveSpeed = getMax(mDataBlock->maxUnderwaterForwardSpeed * move->y,
  2393. mDataBlock->maxUnderwaterSideSpeed * mFabs(move->x));
  2394. else if ( mPose == PronePose )
  2395. moveSpeed = getMax(mDataBlock->maxProneForwardSpeed * move->y,
  2396. mDataBlock->maxProneSideSpeed * mFabs(move->x));
  2397. else if ( mPose == CrouchPose )
  2398. moveSpeed = getMax(mDataBlock->maxCrouchForwardSpeed * move->y,
  2399. mDataBlock->maxCrouchSideSpeed * mFabs(move->x));
  2400. else if ( mPose == SprintPose )
  2401. moveSpeed = getMax(mDataBlock->maxSprintForwardSpeed * move->y,
  2402. mDataBlock->maxSprintSideSpeed * mFabs(move->x));
  2403. else // StandPose
  2404. moveSpeed = getMax(mDataBlock->maxForwardSpeed * move->y,
  2405. mDataBlock->maxSideSpeed * mFabs(move->x));
  2406. }
  2407. else
  2408. {
  2409. if ( mSwimming )
  2410. moveSpeed = getMax(mDataBlock->maxUnderwaterBackwardSpeed * mFabs(move->y),
  2411. mDataBlock->maxUnderwaterSideSpeed * mFabs(move->x));
  2412. else if ( mPose == PronePose )
  2413. moveSpeed = getMax(mDataBlock->maxProneBackwardSpeed * mFabs(move->y),
  2414. mDataBlock->maxProneSideSpeed * mFabs(move->x));
  2415. else if ( mPose == CrouchPose )
  2416. moveSpeed = getMax(mDataBlock->maxCrouchBackwardSpeed * mFabs(move->y),
  2417. mDataBlock->maxCrouchSideSpeed * mFabs(move->x));
  2418. else if ( mPose == SprintPose )
  2419. moveSpeed = getMax(mDataBlock->maxSprintBackwardSpeed * mFabs(move->y),
  2420. mDataBlock->maxSprintSideSpeed * mFabs(move->x));
  2421. else // StandPose
  2422. moveSpeed = getMax(mDataBlock->maxBackwardSpeed * mFabs(move->y),
  2423. mDataBlock->maxSideSpeed * mFabs(move->x));
  2424. }
  2425. // Cancel any script driven animations if we are going to move.
  2426. if (moveVec.x + moveVec.y + moveVec.z != 0.0f &&
  2427. (mActionAnimation.action >= PlayerData::NumTableActionAnims
  2428. || mActionAnimation.action == PlayerData::LandAnim))
  2429. mActionAnimation.action = PlayerData::NullAnimation;
  2430. }
  2431. else
  2432. {
  2433. moveVec.set(0.0f, 0.0f, 0.0f);
  2434. moveSpeed = 0.0f;
  2435. }
  2436. // apply speed bias here.
  2437. speed_bias = speed_bias + (speed_bias_goal - speed_bias)*0.1f;
  2438. moveSpeed *= speed_bias;
  2439. // Acceleration due to gravity
  2440. VectorF acc(0.0f, 0.0f, mGravity * mGravityMod * TickSec);
  2441. // Determine ground contact normal. Only look for contacts if
  2442. // we can move and aren't mounted.
  2443. VectorF contactNormal(0,0,0);
  2444. bool jumpSurface = false, runSurface = false;
  2445. if ( !isMounted() )
  2446. findContact( &runSurface, &jumpSurface, &contactNormal );
  2447. if ( jumpSurface )
  2448. mJumpSurfaceNormal = contactNormal;
  2449. // If we don't have a runSurface but we do have a contactNormal,
  2450. // then we are standing on something that is too steep.
  2451. // Deflect the force of gravity by the normal so we slide.
  2452. // We could also try aligning it to the runSurface instead,
  2453. // but this seems to work well.
  2454. if ( !runSurface && !contactNormal.isZero() )
  2455. acc = ( acc - 2 * contactNormal * mDot( acc, contactNormal ) );
  2456. // Acceleration on run surface
  2457. if (runSurface && !mSwimming) {
  2458. mContactTimer = 0;
  2459. // Remove acc into contact surface (should only be gravity)
  2460. // Clear out floating point acc errors, this will allow
  2461. // the player to "rest" on the ground.
  2462. // However, no need to do that if we're using a physics library.
  2463. // It will take care of itself.
  2464. if (!mPhysicsRep)
  2465. {
  2466. F32 vd = -mDot(acc,contactNormal);
  2467. if (vd > 0.0f) {
  2468. VectorF dv = contactNormal * (vd + 0.002f);
  2469. acc += dv;
  2470. if (acc.len() < 0.0001f)
  2471. acc.set(0.0f, 0.0f, 0.0f);
  2472. }
  2473. }
  2474. // Force a 0 move if there is no energy, and only drain
  2475. // move energy if we're moving.
  2476. VectorF pv;
  2477. if (mPose == SprintPose && mEnergy >= mDataBlock->minSprintEnergy) {
  2478. if (moveSpeed)
  2479. mEnergy -= mDataBlock->sprintEnergyDrain;
  2480. pv = moveVec;
  2481. }
  2482. else if (mEnergy >= mDataBlock->minRunEnergy) {
  2483. if (moveSpeed)
  2484. mEnergy -= mDataBlock->runEnergyDrain;
  2485. pv = moveVec;
  2486. }
  2487. else
  2488. pv.set(0.0f, 0.0f, 0.0f);
  2489. // Adjust the player's requested dir. to be parallel
  2490. // to the contact surface.
  2491. F32 pvl = pv.len();
  2492. if(mJetting)
  2493. {
  2494. pvl = moveVec.len();
  2495. if (pvl)
  2496. {
  2497. VectorF nn;
  2498. mCross(pv,VectorF(0.0f, 0.0f, 0.0f),&nn);
  2499. nn *= 1 / pvl;
  2500. VectorF cv(0.0f, 0.0f, 0.0f);
  2501. cv -= nn * mDot(nn,cv);
  2502. pv -= cv * mDot(pv,cv);
  2503. pvl = pv.len();
  2504. }
  2505. }
  2506. else if (!mPhysicsRep)
  2507. {
  2508. // We only do this if we're not using a physics library. The
  2509. // library will take care of itself.
  2510. if (pvl)
  2511. {
  2512. VectorF nn;
  2513. mCross(pv,VectorF(0.0f, 0.0f, 1.0f),&nn);
  2514. nn *= 1.0f / pvl;
  2515. VectorF cv = contactNormal;
  2516. cv -= nn * mDot(nn,cv);
  2517. pv -= cv * mDot(pv,cv);
  2518. pvl = pv.len();
  2519. }
  2520. }
  2521. // Convert to acceleration
  2522. if ( pvl )
  2523. pv *= moveSpeed / pvl;
  2524. VectorF runAcc = pv - (mVelocity + acc);
  2525. F32 runSpeed = runAcc.len();
  2526. // Clamp acceleration, player also accelerates faster when
  2527. // in his hard landing recover state.
  2528. F32 maxAcc;
  2529. if (mPose == SprintPose)
  2530. {
  2531. maxAcc = (mDataBlock->sprintForce / getMass()) * TickSec;
  2532. }
  2533. else
  2534. {
  2535. maxAcc = (mDataBlock->runForce / getMass()) * TickSec;
  2536. }
  2537. if (mState == RecoverState)
  2538. maxAcc *= mDataBlock->recoverRunForceScale;
  2539. if (runSpeed > maxAcc)
  2540. runAcc *= maxAcc / runSpeed;
  2541. acc += runAcc;
  2542. // If we are running on the ground, then we're not jumping
  2543. if (mDataBlock->isJumpAction(mActionAnimation.action))
  2544. mActionAnimation.action = PlayerData::NullAnimation;
  2545. }
  2546. else if (!mSwimming && mDataBlock->airControl > 0.0f)
  2547. {
  2548. VectorF pv;
  2549. pv = moveVec;
  2550. F32 pvl = pv.len();
  2551. if (pvl)
  2552. pv *= moveSpeed / pvl;
  2553. VectorF runAcc = pv - (mVelocity + acc);
  2554. runAcc.z = 0;
  2555. runAcc.x = runAcc.x * mDataBlock->airControl;
  2556. runAcc.y = runAcc.y * mDataBlock->airControl;
  2557. F32 runSpeed = runAcc.len();
  2558. // We don't test for sprinting when performing air control
  2559. F32 maxAcc = (mDataBlock->runForce / getMass()) * TickSec * 0.3f;
  2560. if (runSpeed > maxAcc)
  2561. runAcc *= maxAcc / runSpeed;
  2562. acc += runAcc;
  2563. // There are no special air control animations
  2564. // so... increment this unless you really want to
  2565. // play the run anims in the air.
  2566. mContactTimer++;
  2567. }
  2568. else if (mSwimming)
  2569. {
  2570. // Remove acc into contact surface (should only be gravity)
  2571. // Clear out floating point acc errors, this will allow
  2572. // the player to "rest" on the ground.
  2573. F32 vd = -mDot(acc,contactNormal);
  2574. if (vd > 0.0f) {
  2575. VectorF dv = contactNormal * (vd + 0.002f);
  2576. acc += dv;
  2577. if (acc.len() < 0.0001f)
  2578. acc.set(0.0f, 0.0f, 0.0f);
  2579. }
  2580. // get the head pitch and add it to the moveVec
  2581. // This more accurate swim vector calc comes from Matt Fairfax
  2582. MatrixF xRot;
  2583. xRot.set(EulerF(mHead.x, 0, 0));
  2584. zRot.set(EulerF(0, 0, mRot.z));
  2585. MatrixF rot;
  2586. rot.mul(zRot, xRot);
  2587. rot.getColumn(0,&moveVec);
  2588. moveVec *= move->x;
  2589. VectorF tv;
  2590. rot.getColumn(1,&tv);
  2591. moveVec += tv * move->y;
  2592. rot.getColumn(2,&tv);
  2593. moveVec += tv * move->z;
  2594. // Force a 0 move if there is no energy, and only drain
  2595. // move energy if we're moving.
  2596. VectorF swimVec;
  2597. if (mEnergy >= mDataBlock->minRunEnergy) {
  2598. if (moveSpeed)
  2599. mEnergy -= mDataBlock->runEnergyDrain;
  2600. swimVec = moveVec;
  2601. }
  2602. else
  2603. swimVec.set(0.0f, 0.0f, 0.0f);
  2604. // If we are swimming but close enough to the shore/ground
  2605. // we can still have a surface-normal. In this case align the
  2606. // velocity to the normal to make getting out of water easier.
  2607. moveVec.normalize();
  2608. F32 isSwimUp = mDot( moveVec, contactNormal );
  2609. if ( !contactNormal.isZero() && isSwimUp < 0.1f )
  2610. {
  2611. F32 pvl = swimVec.len();
  2612. if ( true && pvl )
  2613. {
  2614. VectorF nn;
  2615. mCross(swimVec,VectorF(0.0f, 0.0f, 1.0f),&nn);
  2616. nn *= 1.0f / pvl;
  2617. VectorF cv = contactNormal;
  2618. cv -= nn * mDot(nn,cv);
  2619. swimVec -= cv * mDot(swimVec,cv);
  2620. }
  2621. }
  2622. F32 swimVecLen = swimVec.len();
  2623. // Convert to acceleration.
  2624. if ( swimVecLen )
  2625. swimVec *= moveSpeed / swimVecLen;
  2626. VectorF swimAcc = swimVec - (mVelocity + acc);
  2627. F32 swimSpeed = swimAcc.len();
  2628. // Clamp acceleration.
  2629. F32 maxAcc = (mDataBlock->swimForce / getMass()) * TickSec;
  2630. if ( swimSpeed > maxAcc )
  2631. swimAcc *= maxAcc / swimSpeed;
  2632. acc += swimAcc;
  2633. mContactTimer++;
  2634. }
  2635. else
  2636. mContactTimer++;
  2637. // Acceleration from Jumping
  2638. // While BLOCK_USER_CONTROL is set in anim_clip_flags, the user won't be able to
  2639. // make the player character jump.
  2640. if (move->trigger[sJumpTrigger] && canJump() && !isAnimationLocked())
  2641. {
  2642. // Scale the jump impulse base on maxJumpSpeed
  2643. F32 zSpeedScale = mVelocity.z;
  2644. if (zSpeedScale <= mDataBlock->maxJumpSpeed)
  2645. {
  2646. zSpeedScale = (zSpeedScale <= mDataBlock->minJumpSpeed)? 1:
  2647. 1 - (zSpeedScale - mDataBlock->minJumpSpeed) /
  2648. (mDataBlock->maxJumpSpeed - mDataBlock->minJumpSpeed);
  2649. // Desired jump direction
  2650. VectorF pv = moveVec;
  2651. F32 len = pv.len();
  2652. if (len > 0)
  2653. pv *= 1 / len;
  2654. // We want to scale the jump size by the player size, somewhat
  2655. // in reduced ratio so a smaller player can jump higher in
  2656. // proportion to his size, than a larger player.
  2657. F32 scaleZ = (getScale().z * 0.25) + 0.75;
  2658. // Calculate our jump impulse
  2659. F32 impulse = mDataBlock->jumpForce / getMass();
  2660. if (mDataBlock->jumpTowardsNormal)
  2661. {
  2662. // If we are facing into the surface jump up, otherwise
  2663. // jump away from surface.
  2664. F32 dot = mDot(pv,mJumpSurfaceNormal);
  2665. if (dot <= 0)
  2666. acc.z += mJumpSurfaceNormal.z * scaleZ * impulse * zSpeedScale;
  2667. else
  2668. {
  2669. acc.x += pv.x * impulse * dot;
  2670. acc.y += pv.y * impulse * dot;
  2671. acc.z += mJumpSurfaceNormal.z * scaleZ * impulse * zSpeedScale;
  2672. }
  2673. }
  2674. else
  2675. acc.z += scaleZ * impulse * zSpeedScale;
  2676. mJumpDelay = mDataBlock->jumpDelay;
  2677. mEnergy -= mDataBlock->jumpEnergyDrain;
  2678. // If we don't have a StandJumpAnim, just play the JumpAnim...
  2679. S32 seq = (mVelocity.len() < 0.5) ? PlayerData::StandJumpAnim: PlayerData::JumpAnim;
  2680. if ( mDataBlock->actionList[seq].sequence == -1 )
  2681. seq = PlayerData::JumpAnim;
  2682. setActionThread( seq, true, false, true );
  2683. mJumpSurfaceLastContact = JumpSkipContactsMax;
  2684. // Flag the jump event trigger.
  2685. fx_s_triggers |= PLAYER_JUMP_S_TRIGGER;
  2686. setMaskBits(TriggerMask);
  2687. }
  2688. }
  2689. else
  2690. {
  2691. if (jumpSurface)
  2692. {
  2693. if (mJumpDelay > 0)
  2694. mJumpDelay--;
  2695. mJumpSurfaceLastContact = 0;
  2696. }
  2697. else
  2698. mJumpSurfaceLastContact++;
  2699. }
  2700. if (move->trigger[sJumpJetTrigger] && !isMounted() && canJetJump())
  2701. {
  2702. mJetting = true;
  2703. // Scale the jump impulse base on maxJumpSpeed
  2704. F32 zSpeedScale = mVelocity.z;
  2705. if (zSpeedScale <= mDataBlock->jetMaxJumpSpeed)
  2706. {
  2707. zSpeedScale = (zSpeedScale <= mDataBlock->jetMinJumpSpeed)? 1:
  2708. 1 - (zSpeedScale - mDataBlock->jetMinJumpSpeed) / (mDataBlock->jetMaxJumpSpeed - mDataBlock->jetMinJumpSpeed);
  2709. // Desired jump direction
  2710. VectorF pv = moveVec;
  2711. F32 len = pv.len();
  2712. if (len > 0.0f)
  2713. pv *= 1 / len;
  2714. // If we are facing into the surface jump up, otherwise
  2715. // jump away from surface.
  2716. F32 dot = mDot(pv,mJumpSurfaceNormal);
  2717. F32 impulse = mDataBlock->jetJumpForce / getMass();
  2718. if (dot <= 0)
  2719. acc.z += mJumpSurfaceNormal.z * impulse * zSpeedScale;
  2720. else
  2721. {
  2722. acc.x += pv.x * impulse * dot;
  2723. acc.y += pv.y * impulse * dot;
  2724. acc.z += mJumpSurfaceNormal.z * impulse * zSpeedScale;
  2725. }
  2726. mEnergy -= mDataBlock->jetJumpEnergyDrain;
  2727. }
  2728. }
  2729. else
  2730. {
  2731. mJetting = false;
  2732. }
  2733. // Add in force from physical zones...
  2734. acc += (mAppliedForce / getMass()) * TickSec;
  2735. // Adjust velocity with all the move & gravity acceleration
  2736. // TG: I forgot why doesn't the TickSec multiply happen here...
  2737. mVelocity += acc;
  2738. // apply horizontal air resistance
  2739. F32 hvel = mSqrt(mVelocity.x * mVelocity.x + mVelocity.y * mVelocity.y);
  2740. if(hvel > mDataBlock->horizResistSpeed)
  2741. {
  2742. F32 speedCap = hvel;
  2743. if(speedCap > mDataBlock->horizMaxSpeed)
  2744. speedCap = mDataBlock->horizMaxSpeed;
  2745. speedCap -= mDataBlock->horizResistFactor * TickSec * (speedCap - mDataBlock->horizResistSpeed);
  2746. F32 scale = speedCap / hvel;
  2747. mVelocity.x *= scale;
  2748. mVelocity.y *= scale;
  2749. }
  2750. if(mVelocity.z > mDataBlock->upResistSpeed)
  2751. {
  2752. if(mVelocity.z > mDataBlock->upMaxSpeed)
  2753. mVelocity.z = mDataBlock->upMaxSpeed;
  2754. mVelocity.z -= mDataBlock->upResistFactor * TickSec * (mVelocity.z - mDataBlock->upResistSpeed);
  2755. }
  2756. // Container buoyancy & drag
  2757. /* Commented out until the buoyancy calculation can be reworked so that a container and
  2758. ** player with the same density will result in neutral buoyancy.
  2759. if (mBuoyancy != 0)
  2760. {
  2761. // Applying buoyancy when standing still causing some jitters-
  2762. if (mBuoyancy > 1.0 || !mVelocity.isZero() || !runSurface)
  2763. {
  2764. // A little hackery to prevent oscillation
  2765. // based on http://reinot.blogspot.com/2005/11/oh-yes-they-float-georgie-they-all.html
  2766. F32 buoyancyForce = mBuoyancy * mGravity * mGravityMod * TickSec;
  2767. F32 currHeight = getPosition().z;
  2768. const F32 C = 2.0f;
  2769. const F32 M = 0.1f;
  2770. if ( currHeight + mVelocity.z * TickSec * C > mLiquidHeight )
  2771. buoyancyForce *= M;
  2772. mVelocity.z -= buoyancyForce;
  2773. }
  2774. }
  2775. */
  2776. // Apply drag
  2777. if ( mSwimming )
  2778. mVelocity -= mVelocity * mDrag * TickSec * ( mVelocity.len() / mDataBlock->maxUnderwaterForwardSpeed );
  2779. else
  2780. mVelocity -= mVelocity * mDrag * TickSec;
  2781. // Clamp very small velocity to zero
  2782. if ( mVelocity.isZero() )
  2783. mVelocity = Point3F::Zero;
  2784. // If we are not touching anything and have sufficient -z vel,
  2785. // we are falling.
  2786. if (runSurface)
  2787. mFalling = false;
  2788. else
  2789. {
  2790. VectorF vel;
  2791. mWorldToObj.mulV(mVelocity,&vel);
  2792. mFalling = vel.z < mDataBlock->fallingSpeedThreshold;
  2793. }
  2794. // Vehicle Dismount
  2795. if ( !isGhost() && move->trigger[sVehicleDismountTrigger] && canJump())
  2796. mDataBlock->doDismount_callback( this );
  2797. // Enter/Leave Liquid
  2798. if ( !mInWater && mWaterCoverage > 0.0f )
  2799. {
  2800. mInWater = true;
  2801. if ( !isGhost() )
  2802. mDataBlock->onEnterLiquid_callback( this, mWaterCoverage, mLiquidType.c_str() );
  2803. }
  2804. else if ( mInWater && mWaterCoverage <= 0.0f )
  2805. {
  2806. mInWater = false;
  2807. if ( !isGhost() )
  2808. mDataBlock->onLeaveLiquid_callback( this, mLiquidType.c_str() );
  2809. else
  2810. {
  2811. // exit-water splash sound happens for client only
  2812. if ( getSpeed() >= mDataBlock->exitSplashSoundVel && !isMounted() )
  2813. SFX->playOnce( mDataBlock->sound[PlayerData::ExitWater], &getTransform() );
  2814. }
  2815. }
  2816. // Update the PlayerPose
  2817. Pose desiredPose = mPose;
  2818. if ( !mIsAiControlled )
  2819. {
  2820. if ( mSwimming )
  2821. desiredPose = SwimPose;
  2822. else if ( runSurface && move->trigger[sCrouchTrigger] && canCrouch() )
  2823. desiredPose = CrouchPose;
  2824. else if ( runSurface && move->trigger[sProneTrigger] && canProne() )
  2825. desiredPose = PronePose;
  2826. else if ( move->trigger[sSprintTrigger] && canSprint() )
  2827. desiredPose = SprintPose;
  2828. else if ( canStand() )
  2829. desiredPose = StandPose;
  2830. setPose( desiredPose );
  2831. }
  2832. }
  2833. //----------------------------------------------------------------------------
  2834. bool Player::checkDismountPosition(const MatrixF& oldMat, const MatrixF& mat)
  2835. {
  2836. AssertFatal(getContainer() != NULL, "Error, must have a container!");
  2837. AssertFatal(getObjectMount() != NULL, "Error, must be mounted!");
  2838. Point3F pos;
  2839. Point3F oldPos;
  2840. mat.getColumn(3, &pos);
  2841. oldMat.getColumn(3, &oldPos);
  2842. RayInfo info;
  2843. disableCollision();
  2844. getObjectMount()->disableCollision();
  2845. if (getContainer()->castRay(oldPos, pos, sCollisionMoveMask, &info))
  2846. {
  2847. enableCollision();
  2848. getObjectMount()->enableCollision();
  2849. return false;
  2850. }
  2851. Box3F wBox = mObjBox;
  2852. wBox.minExtents += pos;
  2853. wBox.maxExtents += pos;
  2854. EarlyOutPolyList polyList;
  2855. polyList.mNormal.set(0.0f, 0.0f, 0.0f);
  2856. polyList.mPlaneList.clear();
  2857. polyList.mPlaneList.setSize(6);
  2858. polyList.mPlaneList[0].set(wBox.minExtents,VectorF(-1.0f, 0.0f, 0.0f));
  2859. polyList.mPlaneList[1].set(wBox.maxExtents,VectorF(0.0f, 1.0f, 0.0f));
  2860. polyList.mPlaneList[2].set(wBox.maxExtents,VectorF(1.0f, 0.0f, 0.0f));
  2861. polyList.mPlaneList[3].set(wBox.minExtents,VectorF(0.0f, -1.0f, 0.0f));
  2862. polyList.mPlaneList[4].set(wBox.minExtents,VectorF(0.0f, 0.0f, -1.0f));
  2863. polyList.mPlaneList[5].set(wBox.maxExtents,VectorF(0.0f, 0.0f, 1.0f));
  2864. if (getContainer()->buildPolyList(PLC_Collision, wBox, sCollisionMoveMask, &polyList))
  2865. {
  2866. enableCollision();
  2867. getObjectMount()->enableCollision();
  2868. return false;
  2869. }
  2870. enableCollision();
  2871. getObjectMount()->enableCollision();
  2872. return true;
  2873. }
  2874. //----------------------------------------------------------------------------
  2875. bool Player::canJump()
  2876. {
  2877. return mAllowJumping && mState == MoveState && mDamageState == Enabled && !isMounted() && !mJumpDelay && mEnergy >= mDataBlock->minJumpEnergy && mJumpSurfaceLastContact < JumpSkipContactsMax && !mSwimming && (mPose != SprintPose || mDataBlock->sprintCanJump);
  2878. }
  2879. bool Player::canJetJump()
  2880. {
  2881. return mAllowJetJumping && mState == MoveState && mDamageState == Enabled && !isMounted() && mEnergy >= mDataBlock->jetMinJumpEnergy && mDataBlock->jetJumpForce != 0.0f;
  2882. }
  2883. bool Player::canSwim()
  2884. {
  2885. // Not used!
  2886. //return mState == MoveState && mDamageState == Enabled && !isMounted() && mEnergy >= mDataBlock->minSwimEnergy && mWaterCoverage >= 0.8f;
  2887. return mAllowSwimming;
  2888. }
  2889. bool Player::canCrouch()
  2890. {
  2891. if (!mAllowCrouching)
  2892. return false;
  2893. if ( mState != MoveState ||
  2894. mDamageState != Enabled ||
  2895. isMounted() ||
  2896. mSwimming ||
  2897. mFalling )
  2898. return false;
  2899. // Can't crouch if no crouch animation!
  2900. if ( mDataBlock->actionList[PlayerData::CrouchRootAnim].sequence == -1 )
  2901. return false;
  2902. // We are already in this pose, so don't test it again...
  2903. if ( mPose == CrouchPose )
  2904. return true;
  2905. // Do standard Torque physics test here!
  2906. if ( !mPhysicsRep )
  2907. {
  2908. F32 radius;
  2909. if ( mPose == PronePose )
  2910. radius = mDataBlock->proneBoxSize.z;
  2911. else
  2912. return true;
  2913. // use our X and Y dimentions on our boxsize as the radii for our search, and the difference between a standing position
  2914. // and the position we currently are in.
  2915. Point3F extent( mDataBlock->crouchBoxSize.x / 2, mDataBlock->crouchBoxSize.y / 2, mDataBlock->crouchBoxSize.z - radius );
  2916. Point3F position = getPosition();
  2917. position.z += radius;
  2918. // Use these radii to create a box that represents the difference between a standing position and the position
  2919. // we want to move into.
  2920. Box3F B(position - extent, position + extent, true);
  2921. EarlyOutPolyList polyList;
  2922. polyList.mPlaneList.clear();
  2923. polyList.mNormal.set( 0,0,0 );
  2924. polyList.mPlaneList.setSize( 6 );
  2925. polyList.mPlaneList[0].set( B.minExtents, VectorF( -1,0,0 ) );
  2926. polyList.mPlaneList[1].set( B.maxExtents, VectorF( 0,1,0 ) );
  2927. polyList.mPlaneList[2].set( B.maxExtents, VectorF( 1,0,0 ) );
  2928. polyList.mPlaneList[3].set( B.minExtents, VectorF( 0,-1,0 ) );
  2929. polyList.mPlaneList[4].set( B.minExtents, VectorF( 0,0,-1 ) );
  2930. polyList.mPlaneList[5].set( B.maxExtents, VectorF( 0,0,1 ) );
  2931. // If an object exists in this space, we must stay prone. Otherwise we are free to crouch.
  2932. return !getContainer()->buildPolyList( PLC_Collision, B, StaticShapeObjectType, &polyList );
  2933. }
  2934. return mPhysicsRep->testSpacials( getPosition(), mDataBlock->crouchBoxSize );
  2935. }
  2936. bool Player::canStand()
  2937. {
  2938. if ( mState != MoveState ||
  2939. mDamageState != Enabled ||
  2940. isMounted() ||
  2941. mSwimming )
  2942. return false;
  2943. // We are already in this pose, so don't test it again...
  2944. if ( mPose == StandPose )
  2945. return true;
  2946. // Do standard Torque physics test here!
  2947. if ( !mPhysicsRep )
  2948. {
  2949. F32 radius;
  2950. if (mPose == CrouchPose)
  2951. radius = mDataBlock->crouchBoxSize.z;
  2952. else if (mPose == PronePose)
  2953. radius = mDataBlock->proneBoxSize.z;
  2954. else
  2955. return true;
  2956. // use our X and Y dimentions on our boxsize as the radii for our search, and the difference between a standing position
  2957. // and the position we currently are in.
  2958. Point3F extent( mDataBlock->boxSize.x / 2, mDataBlock->boxSize.y / 2, mDataBlock->boxSize.z - radius );
  2959. Point3F position = getPosition();
  2960. position.z += radius;
  2961. // Use these radii to create a box that represents the difference between a standing position and the position
  2962. // we want to move into.
  2963. Box3F B(position - extent, position + extent, true);
  2964. EarlyOutPolyList polyList;
  2965. polyList.mPlaneList.clear();
  2966. polyList.mNormal.set(0,0,0);
  2967. polyList.mPlaneList.setSize(6);
  2968. polyList.mPlaneList[0].set(B.minExtents, VectorF(-1,0,0));
  2969. polyList.mPlaneList[1].set(B.maxExtents, VectorF(0,1,0));
  2970. polyList.mPlaneList[2].set(B.maxExtents, VectorF(1,0,0));
  2971. polyList.mPlaneList[3].set(B.minExtents, VectorF(0,-1,0));
  2972. polyList.mPlaneList[4].set(B.minExtents, VectorF(0,0,-1));
  2973. polyList.mPlaneList[5].set(B.maxExtents, VectorF(0,0,1));
  2974. // If an object exists in this space, we must stay crouched/prone. Otherwise we are free to stand.
  2975. return !getContainer()->buildPolyList(PLC_Collision, B, StaticShapeObjectType, &polyList);
  2976. }
  2977. return mPhysicsRep->testSpacials( getPosition(), mDataBlock->boxSize );
  2978. }
  2979. bool Player::canProne()
  2980. {
  2981. if (!mAllowProne)
  2982. return false;
  2983. if ( mState != MoveState ||
  2984. mDamageState != Enabled ||
  2985. isMounted() ||
  2986. mSwimming ||
  2987. mFalling )
  2988. return false;
  2989. // Can't go prone if no prone animation!
  2990. if ( mDataBlock->actionList[PlayerData::ProneRootAnim].sequence == -1 )
  2991. return false;
  2992. // Do standard Torque physics test here!
  2993. if ( !mPhysicsRep )
  2994. return true;
  2995. // We are already in this pose, so don't test it again...
  2996. if ( mPose == PronePose )
  2997. return true;
  2998. return mPhysicsRep->testSpacials( getPosition(), mDataBlock->proneBoxSize );
  2999. }
  3000. bool Player::canSprint()
  3001. {
  3002. return mAllowSprinting && mState == MoveState && mDamageState == Enabled && !isMounted() && mEnergy >= mDataBlock->minSprintEnergy && !mSwimming;
  3003. }
  3004. //----------------------------------------------------------------------------
  3005. void Player::updateDamageLevel()
  3006. {
  3007. if (!isGhost())
  3008. setDamageState((mDamage >= mDataBlock->maxDamage)? Disabled: Enabled);
  3009. if (mDamageThread)
  3010. mShapeInstance->setPos(mDamageThread, mDamage / mDataBlock->destroyedLevel);
  3011. }
  3012. void Player::updateDamageState()
  3013. {
  3014. // Become a corpse when we're disabled (dead).
  3015. if (mDamageState == Enabled) {
  3016. mTypeMask &= ~CorpseObjectType;
  3017. mTypeMask |= PlayerObjectType;
  3018. }
  3019. else {
  3020. mTypeMask &= ~PlayerObjectType;
  3021. mTypeMask |= CorpseObjectType;
  3022. }
  3023. Parent::updateDamageState();
  3024. }
  3025. //----------------------------------------------------------------------------
  3026. void Player::updateLookAnimation(F32 dt)
  3027. {
  3028. // If the preference setting overrideLookAnimation is true, the player's
  3029. // arm and head no longer animate according to the view direction. They
  3030. // are instead given fixed positions.
  3031. if (overrideLookAnimation)
  3032. {
  3033. if (mArmAnimation.thread)
  3034. mShapeInstance->setPos(mArmAnimation.thread, armLookOverridePos);
  3035. if (mHeadVThread)
  3036. mShapeInstance->setPos(mHeadVThread, headVLookOverridePos);
  3037. if (mHeadHThread)
  3038. mShapeInstance->setPos(mHeadHThread, headHLookOverridePos);
  3039. return;
  3040. }
  3041. // Calculate our interpolated head position.
  3042. Point3F renderHead = mDelta.head + mDelta.headVec * dt;
  3043. // Adjust look pos. This assumes that the animations match
  3044. // the min and max look angles provided in the datablock.
  3045. if (mArmAnimation.thread)
  3046. {
  3047. if(mControlObject)
  3048. {
  3049. mShapeInstance->setPos(mArmAnimation.thread,0.5f);
  3050. }
  3051. else
  3052. {
  3053. F32 d = mDataBlock->maxLookAngle - mDataBlock->minLookAngle;
  3054. F32 tp = (renderHead.x - mDataBlock->minLookAngle) / d;
  3055. mShapeInstance->setPos(mArmAnimation.thread,mClampF(tp,0,1));
  3056. }
  3057. }
  3058. if (mHeadVThread)
  3059. {
  3060. F32 d = mDataBlock->maxLookAngle - mDataBlock->minLookAngle;
  3061. F32 tp = (renderHead.x - mDataBlock->minLookAngle) / d;
  3062. mShapeInstance->setPos(mHeadVThread,mClampF(tp,0,1));
  3063. }
  3064. if (mHeadHThread)
  3065. {
  3066. F32 d = 2 * mDataBlock->maxFreelookAngle;
  3067. F32 tp = (renderHead.z + mDataBlock->maxFreelookAngle) / d;
  3068. mShapeInstance->setPos(mHeadHThread,mClampF(tp,0,1));
  3069. }
  3070. }
  3071. //----------------------------------------------------------------------------
  3072. // Methods to get delta (as amount to affect velocity by)
  3073. bool Player::inDeathAnim()
  3074. {
  3075. if ((anim_clip_flags & ANIM_OVERRIDDEN) != 0 && (anim_clip_flags & IS_DEATH_ANIM) == 0)
  3076. return false;
  3077. if (mActionAnimation.thread && mActionAnimation.action >= 0)
  3078. if (mActionAnimation.action < mDataBlock->actionCount)
  3079. return mDataBlock->actionList[mActionAnimation.action].death;
  3080. return false;
  3081. }
  3082. // Get change from mLastDeathPos - return current pos. Assumes we're in death anim.
  3083. F32 Player::deathDelta(Point3F & delta)
  3084. {
  3085. // Get ground delta from the last time we offset this.
  3086. MatrixF mat;
  3087. F32 pos = mShapeInstance->getPos(mActionAnimation.thread);
  3088. mShapeInstance->deltaGround1(mActionAnimation.thread, mDeath.lastPos, pos, mat);
  3089. mat.getColumn(3, & delta);
  3090. return pos;
  3091. }
  3092. // Called before updatePos() to prepare it's needed change to velocity, which
  3093. // must roll over. Should be updated on tick, this is where we remember last
  3094. // position of animation that was used to roll into velocity.
  3095. void Player::updateDeathOffsets()
  3096. {
  3097. if (inDeathAnim())
  3098. // Get ground delta from the last time we offset this.
  3099. mDeath.lastPos = deathDelta(mDeath.posAdd);
  3100. else
  3101. mDeath.clear();
  3102. }
  3103. //----------------------------------------------------------------------------
  3104. // PATHSHAPE
  3105. static const U32 sPlayerConformMask = StaticShapeObjectType | StaticObjectType |
  3106. TerrainObjectType | PathShapeObjectType;
  3107. // PATHSHAPE END
  3108. static void accel(F32& from, F32 to, F32 rate)
  3109. {
  3110. if (from < to)
  3111. from = getMin(from += rate, to);
  3112. else
  3113. from = getMax(from -= rate, to);
  3114. }
  3115. // if (dt == -1)
  3116. // normal tick, so we advance.
  3117. // else
  3118. // interpolate with dt as % of tick, don't advance
  3119. //
  3120. MatrixF * Player::Death::fallToGround(F32 dt, const Point3F& loc, F32 curZ, F32 boxRad)
  3121. {
  3122. static const F32 sConformCheckDown = 4.0f;
  3123. RayInfo coll;
  3124. bool conformToStairs = false;
  3125. Point3F pos(loc.x, loc.y, loc.z + 0.1f);
  3126. Point3F below(pos.x, pos.y, loc.z - sConformCheckDown);
  3127. MatrixF * retVal = NULL;
  3128. PROFILE_SCOPE(ConformToGround);
  3129. if (gClientContainer.castRay(pos, below, sPlayerConformMask, &coll))
  3130. {
  3131. F32 adjust, height = (loc.z - coll.point.z), sink = curSink;
  3132. VectorF desNormal = coll.normal;
  3133. VectorF normal = curNormal;
  3134. // dt >= 0 means we're interpolating and don't accel the numbers
  3135. if (dt >= 0.0f)
  3136. adjust = dt * TickSec;
  3137. else
  3138. adjust = TickSec;
  3139. // Try to get them to conform to stairs by doing several LOS calls. We do this if
  3140. // normal is within about 5 deg. of vertical.
  3141. if (desNormal.z > 0.995f)
  3142. {
  3143. Point3F corners[3], downpts[3];
  3144. S32 c;
  3145. for (c = 0; c < 3; c++) { // Build 3 corners to cast down from-
  3146. corners[c].set(loc.x - boxRad, loc.y - boxRad, loc.z + 1.0f);
  3147. if (c) // add (0,boxWidth) and (boxWidth,0)
  3148. corners[c][c - 1] += (boxRad * 2.0f);
  3149. downpts[c].set(corners[c].x, corners[c].y, loc.z - sConformCheckDown);
  3150. }
  3151. // Do the three casts-
  3152. for (c = 0; c < 3; c++)
  3153. if (gClientContainer.castRay(corners[c], downpts[c], sPlayerConformMask, &coll))
  3154. downpts[c] = coll.point;
  3155. else
  3156. break;
  3157. // Do the math if everything hit below-
  3158. if (c == 3) {
  3159. mCross(downpts[1] - downpts[0], downpts[2] - downpts[1], &desNormal);
  3160. AssertFatal(desNormal.z > 0, "Abnormality in Player::Death::fallToGround()");
  3161. downpts[2] = downpts[2] - downpts[1];
  3162. downpts[1] = downpts[1] - downpts[0];
  3163. desNormal.normalize();
  3164. conformToStairs = true;
  3165. }
  3166. }
  3167. // Move normal in direction we want-
  3168. F32 * cur = normal, * des = desNormal;
  3169. for (S32 i = 0; i < 3; i++)
  3170. accel(*cur++, *des++, adjust * 0.25f);
  3171. if (mFabs(height) < 2.2f && !normal.isZero() && desNormal.z > 0.01f)
  3172. {
  3173. VectorF upY(0.0f, 1.0f, 0.0f), ahead;
  3174. VectorF sideVec;
  3175. MatrixF mat(true);
  3176. normal.normalize();
  3177. mat.set(EulerF (0.0f, 0.0f, curZ));
  3178. mat.mulV(upY, & ahead);
  3179. mCross(ahead, normal, &sideVec);
  3180. sideVec.normalize();
  3181. mCross(normal, sideVec, &ahead);
  3182. static MatrixF resMat(true);
  3183. resMat.setColumn(0, sideVec);
  3184. resMat.setColumn(1, ahead);
  3185. resMat.setColumn(2, normal);
  3186. // Adjust Z down to account for box offset on slope. Figure out how
  3187. // much we want to sink, and gradually accel to this amount. Don't do if
  3188. // we're conforming to stairs though
  3189. F32 xy = mSqrt(desNormal.x * desNormal.x + desNormal.y * desNormal.y);
  3190. F32 desiredSink = (boxRad * xy / desNormal.z);
  3191. if (conformToStairs)
  3192. desiredSink *= 0.5f;
  3193. accel(sink, desiredSink, adjust * 0.15f);
  3194. Point3F position(pos);
  3195. position.z -= sink;
  3196. resMat.setColumn(3, position);
  3197. if (dt < 0.0f)
  3198. { // we're moving, so update normal and sink amount
  3199. curNormal = normal;
  3200. curSink = sink;
  3201. }
  3202. retVal = &resMat;
  3203. }
  3204. }
  3205. return retVal;
  3206. }
  3207. //-------------------------------------------------------------------------------------
  3208. // This is called ::onAdd() to see if we're in a sitting animation. These then
  3209. // can use a longer tick delay for the mount to get across.
  3210. bool Player::inSittingAnim()
  3211. {
  3212. U32 action = mActionAnimation.action;
  3213. if (mActionAnimation.thread && action < mDataBlock->actionCount) {
  3214. const char * name = mDataBlock->actionList[action].name;
  3215. if (!dStricmp(name, "Sitting") || !dStricmp(name, "Scoutroot"))
  3216. return true;
  3217. }
  3218. return false;
  3219. }
  3220. //----------------------------------------------------------------------------
  3221. const String& Player::getArmThread() const
  3222. {
  3223. if (mArmAnimation.thread && mArmAnimation.thread->hasSequence())
  3224. {
  3225. return mArmAnimation.thread->getSequenceName();
  3226. }
  3227. return String::EmptyString;
  3228. }
  3229. bool Player::setArmThread(const char* sequence)
  3230. {
  3231. // The arm sequence must be in the action list.
  3232. for (U32 i = 1; i < mDataBlock->actionCount; i++)
  3233. if (!dStricmp(mDataBlock->actionList[i].name,sequence))
  3234. return setArmThread(i);
  3235. return false;
  3236. }
  3237. bool Player::setArmThread(U32 action)
  3238. {
  3239. PlayerData::ActionAnimation &anim = mDataBlock->actionList[action];
  3240. if (anim.sequence != -1 &&
  3241. anim.sequence != mShapeInstance->getSequence(mArmAnimation.thread))
  3242. {
  3243. mShapeInstance->setSequence(mArmAnimation.thread,anim.sequence,0);
  3244. mArmAnimation.action = action;
  3245. setMaskBits(ActionMask);
  3246. return true;
  3247. }
  3248. return false;
  3249. }
  3250. //----------------------------------------------------------------------------
  3251. bool Player::setActionThread(const char* sequence,bool hold,bool wait,bool fsp)
  3252. {
  3253. if (anim_clip_flags & ANIM_OVERRIDDEN)
  3254. return false;
  3255. for (U32 i = 1; i < mDataBlock->actionCount; i++)
  3256. {
  3257. PlayerData::ActionAnimation &anim = mDataBlock->actionList[i];
  3258. if (!dStricmp(anim.name,sequence))
  3259. {
  3260. setActionThread(i,true,hold,wait,fsp);
  3261. setMaskBits(ActionMask);
  3262. return true;
  3263. }
  3264. }
  3265. return false;
  3266. }
  3267. void Player::setActionThread(U32 action,bool forward,bool hold,bool wait,bool fsp, bool forceSet)
  3268. {
  3269. if (!mDataBlock || !mDataBlock->actionCount || (mActionAnimation.action == action && mActionAnimation.forward == forward && !forceSet))
  3270. return;
  3271. if (action >= PlayerData::NumActionAnims)
  3272. {
  3273. Con::errorf("Player::setActionThread(%d): Player action out of range", action);
  3274. return;
  3275. }
  3276. if (isClientObject())
  3277. {
  3278. mark_idle = (action == PlayerData::RootAnim);
  3279. idle_timer = (mark_idle) ? 0.0f : -1.0f;
  3280. }
  3281. PlayerData::ActionAnimation &anim = mDataBlock->actionList[action];
  3282. if (anim.sequence != -1)
  3283. {
  3284. U32 lastAction = mActionAnimation.action;
  3285. mActionAnimation.action = action;
  3286. mActionAnimation.forward = forward;
  3287. mActionAnimation.firstPerson = fsp;
  3288. mActionAnimation.holdAtEnd = hold;
  3289. mActionAnimation.waitForEnd = hold? true: wait;
  3290. mActionAnimation.animateOnServer = fsp;
  3291. mActionAnimation.atEnd = false;
  3292. mActionAnimation.delayTicks = (S32)sNewAnimationTickTime;
  3293. mActionAnimation.atEnd = false;
  3294. if (sUseAnimationTransitions && (action != PlayerData::LandAnim || !(mDataBlock->landSequenceTime > 0.0f && !mDataBlock->transitionToLand)) && (isGhost()/* || mActionAnimation.animateOnServer*/))
  3295. {
  3296. // The transition code needs the timeScale to be set in the
  3297. // right direction to know which way to go.
  3298. F32 transTime = sAnimationTransitionTime;
  3299. if (mDataBlock && mDataBlock->isJumpAction(action))
  3300. transTime = 0.15f;
  3301. F32 timeScale = mActionAnimation.forward ? 1.0f : -1.0f;
  3302. if (mDataBlock && mDataBlock->isJumpAction(action))
  3303. timeScale *= 1.5f;
  3304. mShapeInstance->setTimeScale(mActionAnimation.thread,timeScale);
  3305. S32 seq = anim.sequence;
  3306. S32 imageBasedSeq = convertActionToImagePrefix(mActionAnimation.action);
  3307. if (imageBasedSeq != -1)
  3308. seq = imageBasedSeq;
  3309. // If we're transitioning into the same sequence (an action may use the
  3310. // same sequence as a previous action) then we want to start at the same
  3311. // position.
  3312. F32 pos = mActionAnimation.forward ? 0.0f : 1.0f;
  3313. PlayerData::ActionAnimation &lastAnim = mDataBlock->actionList[lastAction];
  3314. if (lastAnim.sequence == anim.sequence)
  3315. {
  3316. pos = mShapeInstance->getPos(mActionAnimation.thread);
  3317. }
  3318. mShapeInstance->transitionToSequence(mActionAnimation.thread,seq,
  3319. pos, transTime, true);
  3320. }
  3321. else
  3322. {
  3323. S32 seq = anim.sequence;
  3324. S32 imageBasedSeq = convertActionToImagePrefix(mActionAnimation.action);
  3325. if (imageBasedSeq != -1)
  3326. seq = imageBasedSeq;
  3327. mShapeInstance->setSequence(mActionAnimation.thread,seq,
  3328. mActionAnimation.forward ? 0.0f : 1.0f);
  3329. }
  3330. }
  3331. }
  3332. void Player::updateActionThread()
  3333. {
  3334. PROFILE_START(UpdateActionThread);
  3335. // Select an action animation sequence, this assumes that
  3336. // this function is called once per tick.
  3337. if(mActionAnimation.action != PlayerData::NullAnimation)
  3338. {
  3339. if (mActionAnimation.forward)
  3340. mActionAnimation.atEnd = mShapeInstance->getPos(mActionAnimation.thread) == 1;
  3341. else
  3342. mActionAnimation.atEnd = mShapeInstance->getPos(mActionAnimation.thread) == 0;
  3343. }
  3344. // Only need to deal with triggers on the client
  3345. if( isGhost() )
  3346. {
  3347. bool triggeredLeft = false;
  3348. bool triggeredRight = false;
  3349. F32 offset = 0.0f;
  3350. if( mShapeInstance->getTriggerState( 1 ) )
  3351. {
  3352. triggeredLeft = true;
  3353. offset = -mDataBlock->decalOffset * getScale().x;
  3354. }
  3355. else if(mShapeInstance->getTriggerState( 2 ) )
  3356. {
  3357. triggeredRight = true;
  3358. offset = mDataBlock->decalOffset * getScale().x;
  3359. }
  3360. process_client_triggers(triggeredLeft, triggeredRight);
  3361. if ((triggeredLeft || triggeredRight) && !noFootfallFX)
  3362. {
  3363. Point3F rot, pos;
  3364. RayInfo rInfo;
  3365. MatrixF mat = getRenderTransform();
  3366. mat.getColumn( 1, &rot );
  3367. mat.mulP( Point3F( offset, 0.0f, 0.0f), &pos );
  3368. if( gClientContainer.castRay( Point3F( pos.x, pos.y, pos.z + 0.01f ),
  3369. Point3F( pos.x, pos.y, pos.z - 2.0f ),
  3370. STATIC_COLLISION_TYPEMASK | VehicleObjectType, &rInfo ) )
  3371. {
  3372. Material* material = ( rInfo.material ? dynamic_cast< Material* >( rInfo.material->getMaterial() ) : 0 );
  3373. // Put footprints on surface, if appropriate for material.
  3374. if( material && material->mShowFootprints
  3375. && mDataBlock->decalData && !footfallDecalOverride )
  3376. {
  3377. Point3F normal;
  3378. Point3F tangent;
  3379. mObjToWorld.getColumn( 0, &tangent );
  3380. mObjToWorld.getColumn( 2, &normal );
  3381. gDecalManager->addDecal( rInfo.point, normal, tangent, mDataBlock->decalData, getScale().y );
  3382. }
  3383. // Emit footpuffs.
  3384. if (!footfallDustOverride && rInfo.t <= 0.5f && mWaterCoverage == 0.0f
  3385. && material && material->mShowDust )
  3386. {
  3387. // New emitter every time for visibility reasons
  3388. ParticleEmitter * emitter = new ParticleEmitter;
  3389. emitter->onNewDataBlock( mDataBlock->footPuffEmitter, false );
  3390. LinearColorF colorList[ ParticleData::PDC_NUM_KEYS];
  3391. for( U32 x = 0; x < getMin( Material::NUM_EFFECT_COLOR_STAGES, ParticleData::PDC_NUM_KEYS ); ++ x )
  3392. colorList[ x ].set( material->mEffectColor[ x ].red,
  3393. material->mEffectColor[ x ].green,
  3394. material->mEffectColor[ x ].blue,
  3395. material->mEffectColor[ x ].alpha );
  3396. for( U32 x = Material::NUM_EFFECT_COLOR_STAGES; x < ParticleData::PDC_NUM_KEYS; ++ x )
  3397. colorList[ x ].set( 1.0, 1.0, 1.0, 0.0 );
  3398. emitter->setColors( colorList );
  3399. if( !emitter->registerObject() )
  3400. {
  3401. Con::warnf( ConsoleLogEntry::General, "Could not register emitter for particle of class: %s", mDataBlock->getName() );
  3402. delete emitter;
  3403. emitter = NULL;
  3404. }
  3405. else
  3406. {
  3407. emitter->emitParticles( pos, Point3F( 0.0, 0.0, 1.0 ), mDataBlock->footPuffRadius,
  3408. Point3F( 0, 0, 0 ), mDataBlock->footPuffNumParts );
  3409. emitter->deleteWhenEmpty();
  3410. }
  3411. }
  3412. // Play footstep sound.
  3413. if (footfallSoundOverride <= 0)
  3414. playFootstepSound( triggeredLeft, material, rInfo.object );
  3415. }
  3416. }
  3417. }
  3418. // Mount pending variable puts a hold on the delayTicks below so players don't
  3419. // inadvertently stand up because their mount has not come over yet.
  3420. if (mMountPending)
  3421. mMountPending = (isMounted() ? 0 : (mMountPending - 1));
  3422. if ((mActionAnimation.action == PlayerData::NullAnimation) ||
  3423. ((!mActionAnimation.waitForEnd || mActionAnimation.atEnd) &&
  3424. (!mActionAnimation.holdAtEnd && (mActionAnimation.delayTicks -= !mMountPending) <= 0)))
  3425. {
  3426. //The scripting language will get a call back when a script animation has finished...
  3427. // example: When the chat menu animations are done playing...
  3428. if ( isServerObject() && mActionAnimation.action >= PlayerData::NumTableActionAnims )
  3429. mDataBlock->animationDone_callback( this );
  3430. pickActionAnimation();
  3431. }
  3432. // prevent scaling of AFX picked actions
  3433. if ( (mActionAnimation.action != PlayerData::LandAnim) &&
  3434. (mActionAnimation.action != PlayerData::NullAnimation) &&
  3435. !(anim_clip_flags & ANIM_OVERRIDDEN))
  3436. {
  3437. // Update action animation time scale to match ground velocity
  3438. PlayerData::ActionAnimation &anim =
  3439. mDataBlock->actionList[mActionAnimation.action];
  3440. F32 scale = 1;
  3441. if (anim.velocityScale && anim.speed) {
  3442. VectorF vel;
  3443. mWorldToObj.mulV(mVelocity,&vel);
  3444. scale = mFabs(mDot(vel, anim.dir) / anim.speed);
  3445. if (scale > mDataBlock->maxTimeScale)
  3446. scale = mDataBlock->maxTimeScale;
  3447. }
  3448. mShapeInstance->setTimeScale(mActionAnimation.thread,
  3449. mActionAnimation.forward? scale: -scale);
  3450. }
  3451. PROFILE_END();
  3452. }
  3453. void Player::pickBestMoveAction(U32 startAnim, U32 endAnim, U32 * action, bool * forward) const
  3454. {
  3455. *action = startAnim;
  3456. *forward = false;
  3457. VectorF vel;
  3458. mWorldToObj.mulV(mVelocity,&vel);
  3459. if (vel.lenSquared() > 0.01f)
  3460. {
  3461. // Bias the velocity towards picking the forward/backward anims over
  3462. // the sideways ones to prevent oscillation between anims.
  3463. vel *= VectorF(0.5f, 1.0f, 0.5f);
  3464. // Pick animation that is the best fit for our current (local) velocity.
  3465. // Assumes that the root (stationary) animation is at startAnim.
  3466. F32 curMax = -0.1f;
  3467. for (U32 i = startAnim+1; i <= endAnim; i++)
  3468. {
  3469. const PlayerData::ActionAnimation &anim = mDataBlock->actionList[i];
  3470. if (anim.sequence != -1 && anim.speed)
  3471. {
  3472. F32 d = mDot(vel, anim.dir);
  3473. if (d > curMax)
  3474. {
  3475. curMax = d;
  3476. *action = i;
  3477. *forward = true;
  3478. }
  3479. else
  3480. {
  3481. // Check if reversing this animation would fit (bias against this
  3482. // so that when moving right, the real right anim is still chosen,
  3483. // but if not present, the reversed left anim will be used instead)
  3484. d *= -0.75f;
  3485. if (d > curMax)
  3486. {
  3487. curMax = d;
  3488. *action = i;
  3489. *forward = false;
  3490. }
  3491. }
  3492. }
  3493. }
  3494. }
  3495. }
  3496. void Player::pickActionAnimation()
  3497. {
  3498. // Only select animations in our normal move state.
  3499. if (mState != MoveState || mDamageState != Enabled)
  3500. return;
  3501. if (isMounted() || mMountPending)
  3502. {
  3503. // Go into root position unless something was set explicitly
  3504. // from a script.
  3505. if (mActionAnimation.action != PlayerData::RootAnim &&
  3506. mActionAnimation.action < PlayerData::NumTableActionAnims)
  3507. setActionThread(PlayerData::RootAnim,true,false,false);
  3508. return;
  3509. }
  3510. bool forward = true;
  3511. U32 action = PlayerData::RootAnim;
  3512. bool fsp = false;
  3513. // Jetting overrides the fall animation condition
  3514. if (mJetting)
  3515. {
  3516. // Play the jetting animation
  3517. action = PlayerData::JetAnim;
  3518. }
  3519. else if (mFalling)
  3520. {
  3521. // Not in contact with any surface and falling
  3522. action = PlayerData::FallAnim;
  3523. }
  3524. else if ( mSwimming )
  3525. {
  3526. pickBestMoveAction(PlayerData::SwimRootAnim, PlayerData::SwimRightAnim, &action, &forward);
  3527. }
  3528. else if ( mPose == StandPose )
  3529. {
  3530. if (mContactTimer >= sContactTickTime)
  3531. {
  3532. // Nothing under our feet
  3533. action = PlayerData::RootAnim;
  3534. }
  3535. else
  3536. {
  3537. // Our feet are on something
  3538. pickBestMoveAction(PlayerData::RootAnim, PlayerData::SideRightAnim, &action, &forward);
  3539. }
  3540. }
  3541. else if ( mPose == CrouchPose )
  3542. {
  3543. pickBestMoveAction(PlayerData::CrouchRootAnim, PlayerData::CrouchRightAnim, &action, &forward);
  3544. }
  3545. else if ( mPose == PronePose )
  3546. {
  3547. pickBestMoveAction(PlayerData::ProneRootAnim, PlayerData::ProneBackwardAnim, &action, &forward);
  3548. }
  3549. else if ( mPose == SprintPose )
  3550. {
  3551. pickBestMoveAction(PlayerData::SprintRootAnim, PlayerData::SprintRightAnim, &action, &forward);
  3552. }
  3553. setActionThread(action,forward,false,false,fsp);
  3554. }
  3555. void Player::onImage(U32 imageSlot, bool unmount)
  3556. {
  3557. // Update 3rd person sequences based on images used. Start be getting a
  3558. // list of all possible image prefix sequences.
  3559. String prefixPaths[ShapeBase::MaxMountedImages];
  3560. buildImagePrefixPaths(prefixPaths);
  3561. // Clear out any previous image state animation
  3562. if (mImageStateThread)
  3563. {
  3564. mShapeInstance->destroyThread(mImageStateThread);
  3565. mImageStateThread = 0;
  3566. }
  3567. // Attempt to update the action thread
  3568. U32 action = mActionAnimation.action;
  3569. if (action != PlayerData::NullAnimation)
  3570. {
  3571. String actionSeq = mDataBlock->actionList[action].name;
  3572. if (actionSeq.isNotEmpty())
  3573. {
  3574. S32 seqIndex = mDataBlock->actionList[action].sequence;
  3575. S32 prefixIndex = findPrefixSequence(prefixPaths, actionSeq);
  3576. if (prefixIndex != -1)
  3577. {
  3578. seqIndex = prefixIndex;
  3579. }
  3580. // Only change the sequence if it isn't already playing.
  3581. if (seqIndex != mShapeInstance->getSequence(mActionAnimation.thread))
  3582. {
  3583. F32 pos = mShapeInstance->getPos(mActionAnimation.thread);
  3584. mShapeInstance->setSequence(mActionAnimation.thread, seqIndex, pos);
  3585. }
  3586. }
  3587. }
  3588. // Attempt to update the arm thread
  3589. U32 armAction = getArmAction();
  3590. if (armAction != PlayerData::NullAnimation)
  3591. {
  3592. String armSeq = mDataBlock->actionList[armAction].name;
  3593. if (armSeq.isNotEmpty())
  3594. {
  3595. S32 seqIndex = mDataBlock->actionList[armAction].sequence;
  3596. S32 prefixIndex = findPrefixSequence(prefixPaths, armSeq);
  3597. if (prefixIndex != -1)
  3598. {
  3599. seqIndex = prefixIndex;
  3600. }
  3601. // Only change the sequence if it isn't already playing.
  3602. if (seqIndex != mShapeInstance->getSequence(mArmAnimation.thread))
  3603. {
  3604. F32 pos = mShapeInstance->getPos(mArmAnimation.thread);
  3605. mShapeInstance->setSequence(mArmAnimation.thread, seqIndex, pos);
  3606. }
  3607. }
  3608. }
  3609. // Attempt to update the head threads
  3610. if (mHeadVThread)
  3611. {
  3612. TSShape const* shape = mShapeInstance->getShape();
  3613. S32 seqIndex = shape->findSequence("head");
  3614. S32 prefixIndex = findPrefixSequence(prefixPaths, "head");
  3615. if (prefixIndex != -1)
  3616. {
  3617. seqIndex = prefixIndex;
  3618. }
  3619. // Only change the sequence if it isn't already playing.
  3620. if (seqIndex != mShapeInstance->getSequence(mHeadVThread))
  3621. {
  3622. F32 pos = mShapeInstance->getPos(mHeadVThread);
  3623. mShapeInstance->setSequence(mHeadVThread, seqIndex, pos);
  3624. }
  3625. }
  3626. if (mHeadHThread)
  3627. {
  3628. TSShape const* shape = mShapeInstance->getShape();
  3629. S32 seqIndex = shape->findSequence("headside");
  3630. S32 prefixIndex = findPrefixSequence(prefixPaths, "headside");
  3631. if (prefixIndex != -1)
  3632. {
  3633. seqIndex = prefixIndex;
  3634. }
  3635. // Only change the sequence if it isn't already playing.
  3636. if (seqIndex != mShapeInstance->getSequence(mHeadHThread))
  3637. {
  3638. F32 pos = mShapeInstance->getPos(mHeadHThread);
  3639. mShapeInstance->setSequence(mHeadHThread, seqIndex, pos);
  3640. }
  3641. }
  3642. }
  3643. void Player::buildImagePrefixPaths(String* prefixPaths)
  3644. {
  3645. // We begin obtaining the anim prefix for each image.
  3646. String prefix[ShapeBase::MaxMountedImages];
  3647. for (U32 i=0; i<ShapeBase::MaxMountedImages; ++i)
  3648. {
  3649. MountedImage& image = mMountedImageList[i];
  3650. if (image.dataBlock && image.dataBlock->imageAnimPrefix && image.dataBlock->imageAnimPrefix[0])
  3651. {
  3652. prefix[i] = String(image.dataBlock->imageAnimPrefix);
  3653. }
  3654. }
  3655. // Build out the full prefix names we will be searching for.
  3656. S32 counter = ShapeBase::MaxMountedImages-1;
  3657. for (U32 i=0; i<ShapeBase::MaxMountedImages; ++i)
  3658. {
  3659. // Only build out the prefix path for images that have a defined prefix.
  3660. if (prefix[i].isNotEmpty())
  3661. {
  3662. bool start = true;
  3663. for (U32 j=0; j<=i; ++j)
  3664. {
  3665. if (prefix[j].isNotEmpty())
  3666. {
  3667. if (!start)
  3668. {
  3669. prefixPaths[counter] += "_";
  3670. }
  3671. else
  3672. {
  3673. start = false;
  3674. }
  3675. prefixPaths[counter] += prefix[j];
  3676. }
  3677. }
  3678. }
  3679. -- counter;
  3680. }
  3681. }
  3682. S32 Player::findPrefixSequence(String* prefixPaths, const String& baseSeq)
  3683. {
  3684. // Go through the prefix list. If we find a match then return the sequence
  3685. // index.
  3686. for (U32 i=0; i<ShapeBase::MaxMountedImages; ++i)
  3687. {
  3688. if (prefixPaths[i].isNotEmpty())
  3689. {
  3690. String seq = prefixPaths[i] + "_" + baseSeq;
  3691. S32 seqIndex = mShapeInstance->getShape()->findSequence(seq);
  3692. if (seqIndex != -1)
  3693. {
  3694. return seqIndex;
  3695. }
  3696. }
  3697. }
  3698. return -1;
  3699. }
  3700. S32 Player::convertActionToImagePrefix(U32 action)
  3701. {
  3702. String prefixPaths[ShapeBase::MaxMountedImages];
  3703. buildImagePrefixPaths(prefixPaths);
  3704. if (action != PlayerData::NullAnimation)
  3705. {
  3706. String actionSeq;
  3707. S32 seq = -1;
  3708. // We'll first attempt to find the action sequence by name
  3709. // as defined within the action list.
  3710. actionSeq = mDataBlock->actionList[action].name;
  3711. if (actionSeq.isNotEmpty())
  3712. {
  3713. seq = findPrefixSequence(prefixPaths, actionSeq);
  3714. }
  3715. if (seq == -1)
  3716. {
  3717. // Couldn't find a valid sequence. If this is a sprint action
  3718. // then we also need to search through the standard movement
  3719. // sequences.
  3720. if (action >= PlayerData::SprintRootAnim && action <= PlayerData::SprintRightAnim)
  3721. {
  3722. U32 standardAction = action - PlayerData::SprintRootAnim;
  3723. actionSeq = mDataBlock->actionList[standardAction].name;
  3724. if (actionSeq.isNotEmpty())
  3725. {
  3726. seq = findPrefixSequence(prefixPaths, actionSeq);
  3727. }
  3728. }
  3729. }
  3730. return seq;
  3731. }
  3732. return -1;
  3733. }
  3734. void Player::onImageRecoil( U32, ShapeBaseImageData::StateData::RecoilState state )
  3735. {
  3736. if ( mRecoilThread )
  3737. {
  3738. if ( state != ShapeBaseImageData::StateData::NoRecoil )
  3739. {
  3740. S32 stateIndex = state - ShapeBaseImageData::StateData::LightRecoil;
  3741. if ( mDataBlock->recoilSequence[stateIndex] != -1 )
  3742. {
  3743. mShapeInstance->setSequence( mRecoilThread, mDataBlock->recoilSequence[stateIndex], 0 );
  3744. mShapeInstance->setTimeScale( mRecoilThread, 1 );
  3745. }
  3746. }
  3747. }
  3748. }
  3749. void Player::onImageStateAnimation(U32 imageSlot, const char* seqName, bool direction, bool scaleToState, F32 stateTimeOutValue)
  3750. {
  3751. if (mDataBlock->allowImageStateAnimation && isGhost())
  3752. {
  3753. MountedImage& image = mMountedImageList[imageSlot];
  3754. // Just as with onImageAnimThreadChange we're going to apply various prefixes to determine the final sequence to use.
  3755. // Here is the order:
  3756. // imageBasePrefix_scriptPrefix_baseAnimName
  3757. // imageBasePrefix_baseAnimName
  3758. // scriptPrefix_baseAnimName
  3759. // baseAnimName
  3760. // Collect the prefixes
  3761. const char* imageBasePrefix = "";
  3762. bool hasImageBasePrefix = image.dataBlock && image.dataBlock->imageAnimPrefix && image.dataBlock->imageAnimPrefix[0];
  3763. if (hasImageBasePrefix)
  3764. imageBasePrefix = image.dataBlock->imageAnimPrefix;
  3765. const char* scriptPrefix = getImageScriptAnimPrefix(imageSlot).getString();
  3766. bool hasScriptPrefix = scriptPrefix && scriptPrefix[0];
  3767. S32 seqIndex = mShapeInstance->getShape()->findSequence(seqName);
  3768. // Find the final sequence based on the prefix combinations
  3769. if (hasImageBasePrefix || hasScriptPrefix)
  3770. {
  3771. bool found = false;
  3772. String baseSeqName(seqName);
  3773. if (!found && hasImageBasePrefix && hasScriptPrefix)
  3774. {
  3775. String comboSeqName = String(imageBasePrefix) + String("_") + String(scriptPrefix) + String("_") + baseSeqName;
  3776. S32 index = mShapeInstance->getShape()->findSequence(comboSeqName);
  3777. if (index != -1)
  3778. {
  3779. seqIndex = index;
  3780. found = true;
  3781. }
  3782. }
  3783. if (!found && hasImageBasePrefix)
  3784. {
  3785. String imgSeqName = String(imageBasePrefix) + String("_") + baseSeqName;
  3786. S32 index = mShapeInstance->getShape()->findSequence(imgSeqName);
  3787. if (index != -1)
  3788. {
  3789. seqIndex = index;
  3790. found = true;
  3791. }
  3792. }
  3793. if (!found && hasScriptPrefix)
  3794. {
  3795. String scriptSeqName = String(scriptPrefix) + String("_") + baseSeqName;
  3796. S32 index = mShapeInstance->getShape()->findSequence(scriptSeqName);
  3797. if (index != -1)
  3798. {
  3799. seqIndex = index;
  3800. found = true;
  3801. }
  3802. }
  3803. }
  3804. if (seqIndex != -1)
  3805. {
  3806. if (!mImageStateThread)
  3807. {
  3808. mImageStateThread = mShapeInstance->addThread();
  3809. }
  3810. mShapeInstance->setSequence( mImageStateThread, seqIndex, 0 );
  3811. F32 timeScale = (scaleToState && stateTimeOutValue) ?
  3812. mShapeInstance->getDuration(mImageStateThread) / stateTimeOutValue : 1.0f;
  3813. mShapeInstance->setTimeScale( mImageStateThread, direction ? timeScale : -timeScale );
  3814. }
  3815. }
  3816. }
  3817. const char* Player::getImageAnimPrefix(U32 imageSlot, S32 imageShapeIndex)
  3818. {
  3819. if (!mDataBlock)
  3820. return "";
  3821. switch (imageShapeIndex)
  3822. {
  3823. case ShapeBaseImageData::StandardImageShape:
  3824. {
  3825. return mDataBlock->imageAnimPrefix;
  3826. }
  3827. case ShapeBaseImageData::FirstPersonImageShape:
  3828. {
  3829. return mDataBlock->imageAnimPrefixFP;
  3830. }
  3831. default:
  3832. {
  3833. return "";
  3834. }
  3835. }
  3836. }
  3837. void Player::onImageAnimThreadChange(U32 imageSlot, S32 imageShapeIndex, ShapeBaseImageData::StateData* lastState, const char* anim, F32 pos, F32 timeScale, bool reset)
  3838. {
  3839. if (!mShapeFPInstance[imageSlot] || !mShapeFPAnimThread[imageSlot])
  3840. return;
  3841. MountedImage& image = mMountedImageList[imageSlot];
  3842. ShapeBaseImageData::StateData& stateData = *image.state;
  3843. if (reset)
  3844. {
  3845. // Reset cyclic sequences back to the first frame to turn it off
  3846. // (the first key frame should be it's off state).
  3847. if (mShapeFPAnimThread[imageSlot]->getSequence()->isCyclic() && (stateData.sequenceNeverTransition || !(stateData.sequenceTransitionIn || (lastState && lastState->sequenceTransitionOut))) )
  3848. {
  3849. mShapeFPInstance[imageSlot]->setPos(mShapeFPAnimThread[imageSlot],0);
  3850. mShapeFPInstance[imageSlot]->setTimeScale(mShapeFPAnimThread[imageSlot],0);
  3851. }
  3852. return;
  3853. }
  3854. // Just as with ShapeBase::udpateAnimThread we're going to apply various prefixes to determine the final sequence to use.
  3855. // Here is the order:
  3856. // imageBasePrefix_scriptPrefix_baseAnimName
  3857. // imageBasePrefix_baseAnimName
  3858. // scriptPrefix_baseAnimName
  3859. // baseAnimName
  3860. // Collect the prefixes
  3861. const char* imageBasePrefix = "";
  3862. bool hasImageBasePrefix = image.dataBlock && image.dataBlock->imageAnimPrefixFP && image.dataBlock->imageAnimPrefixFP[0];
  3863. if (hasImageBasePrefix)
  3864. imageBasePrefix = image.dataBlock->imageAnimPrefixFP;
  3865. const char* scriptPrefix = getImageScriptAnimPrefix(imageSlot).getString();
  3866. bool hasScriptPrefix = scriptPrefix && scriptPrefix[0];
  3867. S32 seqIndex = mShapeFPInstance[imageSlot]->getShape()->findSequence(anim);
  3868. // Find the final sequence based on the prefix combinations
  3869. if (hasImageBasePrefix || hasScriptPrefix)
  3870. {
  3871. bool found = false;
  3872. String baseSeqName(anim);
  3873. if (!found && hasImageBasePrefix && hasScriptPrefix)
  3874. {
  3875. String seqName = String(imageBasePrefix) + String("_") + String(scriptPrefix) + String("_") + baseSeqName;
  3876. S32 index = mShapeFPInstance[imageSlot]->getShape()->findSequence(seqName);
  3877. if (index != -1)
  3878. {
  3879. seqIndex = index;
  3880. found = true;
  3881. }
  3882. }
  3883. if (!found && hasImageBasePrefix)
  3884. {
  3885. String seqName = String(imageBasePrefix) + String("_") + baseSeqName;
  3886. S32 index = mShapeFPInstance[imageSlot]->getShape()->findSequence(seqName);
  3887. if (index != -1)
  3888. {
  3889. seqIndex = index;
  3890. found = true;
  3891. }
  3892. }
  3893. if (!found && hasScriptPrefix)
  3894. {
  3895. String seqName = String(scriptPrefix) + String("_") + baseSeqName;
  3896. S32 index = mShapeFPInstance[imageSlot]->getShape()->findSequence(seqName);
  3897. if (index != -1)
  3898. {
  3899. seqIndex = index;
  3900. found = true;
  3901. }
  3902. }
  3903. }
  3904. if (seqIndex != -1)
  3905. {
  3906. if (!lastState)
  3907. {
  3908. // No lastState indicates that we are just switching animation sequences, not states. Transition into this new sequence, but only
  3909. // if it is different than what we're currently playing.
  3910. S32 prevSeq = -1;
  3911. if (mShapeFPAnimThread[imageSlot]->hasSequence())
  3912. {
  3913. prevSeq = mShapeFPInstance[imageSlot]->getSequence(mShapeFPAnimThread[imageSlot]);
  3914. }
  3915. if (seqIndex != prevSeq)
  3916. {
  3917. mShapeFPInstance[imageSlot]->transitionToSequence(mShapeFPAnimThread[imageSlot], seqIndex, pos, image.dataBlock->scriptAnimTransitionTime, true);
  3918. }
  3919. }
  3920. else if (!stateData.sequenceNeverTransition && stateData.sequenceTransitionTime && (stateData.sequenceTransitionIn || (lastState && lastState->sequenceTransitionOut)) )
  3921. {
  3922. mShapeFPInstance[imageSlot]->transitionToSequence(mShapeFPAnimThread[imageSlot], seqIndex, pos, stateData.sequenceTransitionTime, true);
  3923. }
  3924. else
  3925. {
  3926. mShapeFPInstance[imageSlot]->setSequence(mShapeFPAnimThread[imageSlot], seqIndex, pos);
  3927. }
  3928. mShapeFPInstance[imageSlot]->setTimeScale(mShapeFPAnimThread[imageSlot], timeScale);
  3929. }
  3930. }
  3931. void Player::onImageAnimThreadUpdate(U32 imageSlot, S32 imageShapeIndex, F32 dt)
  3932. {
  3933. if (!mShapeFPInstance[imageSlot])
  3934. return;
  3935. if (mShapeFPAmbientThread[imageSlot] && mShapeFPAmbientThread[imageSlot]->hasSequence())
  3936. {
  3937. mShapeFPInstance[imageSlot]->advanceTime(dt,mShapeFPAmbientThread[imageSlot]);
  3938. }
  3939. if (mShapeFPAnimThread[imageSlot] && mShapeFPAnimThread[imageSlot]->hasSequence())
  3940. {
  3941. mShapeFPInstance[imageSlot]->advanceTime(dt,mShapeFPAnimThread[imageSlot]);
  3942. }
  3943. }
  3944. void Player::onUnmount( SceneObject *obj, S32 node )
  3945. {
  3946. // Reset back to root position during dismount.
  3947. setActionThread(PlayerData::RootAnim,true,false,false);
  3948. // Re-orient the player straight up
  3949. Point3F pos,vec;
  3950. getTransform().getColumn(1,&vec);
  3951. getTransform().getColumn(3,&pos);
  3952. Point3F rot(0.0f,0.0f,-mAtan2(-vec.x,vec.y));
  3953. setPosition(pos,rot);
  3954. // Parent function will call script
  3955. Parent::onUnmount( obj, node );
  3956. }
  3957. void Player::unmount()
  3958. {
  3959. // Reset back to root position during dismount. This copies what is
  3960. // done on the server and corrects the fact that the RootAnim change
  3961. // is not sent across to the client using the standard ActionMask.
  3962. setActionThread(PlayerData::RootAnim,true,false,false);
  3963. Parent::unmount();
  3964. }
  3965. //----------------------------------------------------------------------------
  3966. void Player::updateAnimation(F32 dt)
  3967. {
  3968. // If dead then remove any image animations
  3969. if ((mDamageState == Disabled || mDamageState == Destroyed) && mImageStateThread)
  3970. {
  3971. // Remove the image state animation
  3972. mShapeInstance->destroyThread(mImageStateThread);
  3973. mImageStateThread = 0;
  3974. }
  3975. if ((isGhost() || mActionAnimation.animateOnServer) && mActionAnimation.thread)
  3976. mShapeInstance->advanceTime(dt,mActionAnimation.thread);
  3977. if (mRecoilThread)
  3978. mShapeInstance->advanceTime(dt,mRecoilThread);
  3979. if (mImageStateThread)
  3980. mShapeInstance->advanceTime(dt,mImageStateThread);
  3981. // update any active blend clips
  3982. if (isGhost())
  3983. for (S32 i = 0; i < blend_clips.size(); i++)
  3984. mShapeInstance->advanceTime(dt, blend_clips[i].thread);
  3985. // If we are the client's player on this machine, then we need
  3986. // to make sure the transforms are up to date as they are used
  3987. // to setup the camera.
  3988. if (isGhost())
  3989. {
  3990. if (getControllingClient())
  3991. {
  3992. updateAnimationTree(isFirstPerson());
  3993. mShapeInstance->animate();
  3994. }
  3995. else
  3996. {
  3997. updateAnimationTree(false);
  3998. // This addition forces recently visible players to animate their
  3999. // skeleton now rather than in pre-render so that constrained effects
  4000. // get up-to-date node transforms.
  4001. if (didRenderLastRender())
  4002. mShapeInstance->animate();
  4003. }
  4004. }
  4005. }
  4006. void Player::updateAnimationTree(bool firstPerson)
  4007. {
  4008. S32 mode = 0;
  4009. if (firstPerson)
  4010. {
  4011. if (mActionAnimation.firstPerson)
  4012. mode = 0;
  4013. // TSShapeInstance::MaskNodeRotation;
  4014. // TSShapeInstance::MaskNodePosX |
  4015. // TSShapeInstance::MaskNodePosY;
  4016. else
  4017. mode = TSShapeInstance::MaskNodeAllButBlend;
  4018. }
  4019. for (U32 i = 0; i < PlayerData::NumSpineNodes; i++)
  4020. if (mDataBlock->spineNode[i] != -1)
  4021. mShapeInstance->setNodeAnimationState(mDataBlock->spineNode[i],mode);
  4022. }
  4023. //----------------------------------------------------------------------------
  4024. bool Player::step(Point3F *pos,F32 *maxStep,F32 time)
  4025. {
  4026. const Point3F& scale = getScale();
  4027. Box3F box;
  4028. VectorF offset = mVelocity * time;
  4029. box.minExtents = mObjBox.minExtents + offset + *pos;
  4030. box.maxExtents = mObjBox.maxExtents + offset + *pos;
  4031. box.maxExtents.z += mDataBlock->maxStepHeight * scale.z + sMinFaceDistance;
  4032. SphereF sphere;
  4033. sphere.center = (box.minExtents + box.maxExtents) * 0.5f;
  4034. VectorF bv = box.maxExtents - sphere.center;
  4035. sphere.radius = bv.len();
  4036. ClippedPolyList polyList;
  4037. polyList.mPlaneList.clear();
  4038. polyList.mNormal.set(0.0f, 0.0f, 0.0f);
  4039. polyList.mPlaneList.setSize(6);
  4040. polyList.mPlaneList[0].set(box.minExtents,VectorF(-1.0f, 0.0f, 0.0f));
  4041. polyList.mPlaneList[1].set(box.maxExtents,VectorF(0.0f, 1.0f, 0.0f));
  4042. polyList.mPlaneList[2].set(box.maxExtents,VectorF(1.0f, 0.0f, 0.0f));
  4043. polyList.mPlaneList[3].set(box.minExtents,VectorF(0.0f, -1.0f, 0.0f));
  4044. polyList.mPlaneList[4].set(box.minExtents,VectorF(0.0f, 0.0f, -1.0f));
  4045. polyList.mPlaneList[5].set(box.maxExtents,VectorF(0.0f, 0.0f, 1.0f));
  4046. CollisionWorkingList& rList = mConvex.getWorkingList();
  4047. CollisionWorkingList* pList = rList.wLink.mNext;
  4048. while (pList != &rList) {
  4049. Convex* pConvex = pList->mConvex;
  4050. // Alright, here's the deal... a polysoup mesh really needs to be
  4051. // designed with stepping in mind. If there are too many smallish polygons
  4052. // the stepping system here gets confused and allows you to run up walls
  4053. // or on the edges/seams of meshes.
  4054. TSStatic *st = dynamic_cast<TSStatic *> (pConvex->getObject());
  4055. bool skip = false;
  4056. if (st && !st->allowPlayerStep())
  4057. skip = true;
  4058. if ((pConvex->getObject()->getTypeMask() & StaticObjectType) != 0 && !skip)
  4059. {
  4060. Box3F convexBox = pConvex->getBoundingBox();
  4061. if (box.isOverlapped(convexBox))
  4062. pConvex->getPolyList(&polyList);
  4063. }
  4064. pList = pList->wLink.mNext;
  4065. }
  4066. // Find max step height
  4067. F32 stepHeight = pos->z - sMinFaceDistance;
  4068. U32* vp = polyList.mIndexList.begin();
  4069. U32* ep = polyList.mIndexList.end();
  4070. for (; vp != ep; vp++) {
  4071. F32 h = polyList.mVertexList[*vp].point.z + sMinFaceDistance;
  4072. if (h > stepHeight)
  4073. stepHeight = h;
  4074. }
  4075. F32 step = stepHeight - pos->z;
  4076. if (stepHeight > pos->z && step < *maxStep) {
  4077. // Go ahead and step
  4078. pos->z = stepHeight;
  4079. *maxStep -= step;
  4080. return true;
  4081. }
  4082. return false;
  4083. }
  4084. // PATHSHAPE
  4085. // This Function does a ray cast down to see if a pathshape object is below
  4086. // If so, it will attempt to attach to it.
  4087. void Player::updateAttachment(){
  4088. Point3F rot, pos;
  4089. RayInfo rInfo;
  4090. MatrixF mat = getTransform();
  4091. mat.getColumn(3, &pos);
  4092. if (gServerContainer.castRay(Point3F(pos.x, pos.y, pos.z + 0.1f),
  4093. Point3F(pos.x, pos.y, pos.z - 1.0f ),
  4094. PathShapeObjectType, &rInfo))
  4095. {
  4096. if( rInfo.object->getTypeMask() & PathShapeObjectType) //Ramen
  4097. {
  4098. if (getParent() == NULL)
  4099. { // ONLY do this if we are not parented
  4100. //Con::printf("I'm on a pathshape object. Going to attempt attachment.");
  4101. ShapeBase* col = static_cast<ShapeBase*>(rInfo.object);
  4102. if (!isGhost())
  4103. {
  4104. this->attachToParent(col);
  4105. }
  4106. }
  4107. }
  4108. else
  4109. {
  4110. //Con::printf("object %i",rInfo.object->getId());
  4111. }
  4112. }
  4113. else
  4114. {
  4115. if (getParent() !=NULL)
  4116. {
  4117. clearProcessAfter();
  4118. attachToParent(NULL);
  4119. }
  4120. }
  4121. }
  4122. // PATHSHAPE END
  4123. //----------------------------------------------------------------------------
  4124. inline Point3F createInterpPos(const Point3F& s, const Point3F& e, const F32 t, const F32 d)
  4125. {
  4126. Point3F ret;
  4127. ret.interpolate(s, e, t/d);
  4128. return ret;
  4129. }
  4130. Point3F Player::_move( const F32 travelTime, Collision *outCol )
  4131. {
  4132. // Try and move to new pos
  4133. F32 totalMotion = 0.0f;
  4134. // TODO: not used?
  4135. //F32 initialSpeed = mVelocity.len();
  4136. Point3F start;
  4137. Point3F initialPosition;
  4138. getTransform().getColumn(3,&start);
  4139. initialPosition = start;
  4140. static CollisionList collisionList;
  4141. static CollisionList physZoneCollisionList;
  4142. collisionList.clear();
  4143. physZoneCollisionList.clear();
  4144. MatrixF collisionMatrix(true);
  4145. collisionMatrix.setColumn(3, start);
  4146. VectorF firstNormal(0.0f, 0.0f, 0.0f);
  4147. F32 maxStep = mDataBlock->maxStepHeight;
  4148. F32 time = travelTime;
  4149. U32 count = 0;
  4150. const Point3F& scale = getScale();
  4151. static Polyhedron sBoxPolyhedron;
  4152. static ExtrudedPolyList sExtrudedPolyList;
  4153. static ExtrudedPolyList sPhysZonePolyList;
  4154. for (; count < sMoveRetryCount; count++) {
  4155. F32 speed = mVelocity.len();
  4156. if (!speed && !mDeath.haveVelocity())
  4157. break;
  4158. Point3F end = start + mVelocity * time;
  4159. if (mDeath.haveVelocity()) {
  4160. // Add in death movement-
  4161. VectorF deathVel = mDeath.getPosAdd();
  4162. VectorF resVel;
  4163. getTransform().mulV(deathVel, & resVel);
  4164. end += resVel;
  4165. }
  4166. Point3F distance = end - start;
  4167. if (mFabs(distance.x) < mScaledBox.len_x() &&
  4168. mFabs(distance.y) < mScaledBox.len_y() &&
  4169. mFabs(distance.z) < mScaledBox.len_z())
  4170. {
  4171. // We can potentially early out of this. If there are no polys in the clipped polylist at our
  4172. // end position, then we can bail, and just set start = end;
  4173. Box3F wBox = mScaledBox;
  4174. wBox.minExtents += end;
  4175. wBox.maxExtents += end;
  4176. static EarlyOutPolyList eaPolyList;
  4177. eaPolyList.clear();
  4178. eaPolyList.mNormal.set(0.0f, 0.0f, 0.0f);
  4179. eaPolyList.mPlaneList.clear();
  4180. eaPolyList.mPlaneList.setSize(6);
  4181. eaPolyList.mPlaneList[0].set(wBox.minExtents,VectorF(-1.0f, 0.0f, 0.0f));
  4182. eaPolyList.mPlaneList[1].set(wBox.maxExtents,VectorF(0.0f, 1.0f, 0.0f));
  4183. eaPolyList.mPlaneList[2].set(wBox.maxExtents,VectorF(1.0f, 0.0f, 0.0f));
  4184. eaPolyList.mPlaneList[3].set(wBox.minExtents,VectorF(0.0f, -1.0f, 0.0f));
  4185. eaPolyList.mPlaneList[4].set(wBox.minExtents,VectorF(0.0f, 0.0f, -1.0f));
  4186. eaPolyList.mPlaneList[5].set(wBox.maxExtents,VectorF(0.0f, 0.0f, 1.0f));
  4187. // Build list from convex states here...
  4188. CollisionWorkingList& rList = mConvex.getWorkingList();
  4189. CollisionWorkingList* pList = rList.wLink.mNext;
  4190. while (pList != &rList) {
  4191. Convex* pConvex = pList->mConvex;
  4192. if (pConvex->getObject()->getTypeMask() & sCollisionMoveMask) {
  4193. Box3F convexBox = pConvex->getBoundingBox();
  4194. if (wBox.isOverlapped(convexBox))
  4195. {
  4196. // No need to separate out the physical zones here, we want those
  4197. // to cause a fallthrough as well...
  4198. pConvex->getPolyList(&eaPolyList);
  4199. }
  4200. }
  4201. pList = pList->wLink.mNext;
  4202. }
  4203. if (eaPolyList.isEmpty())
  4204. {
  4205. totalMotion += (end - start).len();
  4206. start = end;
  4207. break;
  4208. }
  4209. }
  4210. collisionMatrix.setColumn(3, start);
  4211. sBoxPolyhedron.buildBox(collisionMatrix, mScaledBox, true);
  4212. // Setup the bounding box for the extrudedPolyList
  4213. Box3F plistBox = mScaledBox;
  4214. collisionMatrix.mul(plistBox);
  4215. Point3F oldMin = plistBox.minExtents;
  4216. Point3F oldMax = plistBox.maxExtents;
  4217. plistBox.minExtents.setMin(oldMin + (mVelocity * time) - Point3F(0.1f, 0.1f, 0.1f));
  4218. plistBox.maxExtents.setMax(oldMax + (mVelocity * time) + Point3F(0.1f, 0.1f, 0.1f));
  4219. // Build extruded polyList...
  4220. VectorF vector = end - start;
  4221. sExtrudedPolyList.extrude(sBoxPolyhedron,vector);
  4222. sExtrudedPolyList.setVelocity(mVelocity);
  4223. sExtrudedPolyList.setCollisionList(&collisionList);
  4224. sPhysZonePolyList.extrude(sBoxPolyhedron,vector);
  4225. sPhysZonePolyList.setVelocity(mVelocity);
  4226. sPhysZonePolyList.setCollisionList(&physZoneCollisionList);
  4227. // Build list from convex states here...
  4228. CollisionWorkingList& rList = mConvex.getWorkingList();
  4229. CollisionWorkingList* pList = rList.wLink.mNext;
  4230. while (pList != &rList) {
  4231. Convex* pConvex = pList->mConvex;
  4232. if (pConvex->getObject()->getTypeMask() & sCollisionMoveMask) {
  4233. Box3F convexBox = pConvex->getBoundingBox();
  4234. if (plistBox.isOverlapped(convexBox))
  4235. {
  4236. if (pConvex->getObject()->getTypeMask() & PhysicalZoneObjectType)
  4237. pConvex->getPolyList(&sPhysZonePolyList);
  4238. else
  4239. pConvex->getPolyList(&sExtrudedPolyList);
  4240. }
  4241. }
  4242. pList = pList->wLink.mNext;
  4243. }
  4244. // Take into account any physical zones...
  4245. for (U32 j = 0; j < physZoneCollisionList.getCount(); j++)
  4246. {
  4247. AssertFatal(dynamic_cast<PhysicalZone*>(physZoneCollisionList[j].object), "Bad phys zone!");
  4248. const PhysicalZone* pZone = (PhysicalZone*)physZoneCollisionList[j].object;
  4249. if (pZone->isActive())
  4250. mVelocity *= pZone->getVelocityMod();
  4251. }
  4252. if (collisionList.getCount() != 0 && collisionList.getTime() < 1.0f)
  4253. {
  4254. // Set to collision point
  4255. F32 velLen = mVelocity.len();
  4256. F32 dt = time * getMin(collisionList.getTime(), 1.0f);
  4257. start += mVelocity * dt;
  4258. time -= dt;
  4259. totalMotion += velLen * dt;
  4260. bool wasFalling = mFalling;
  4261. mFalling = false;
  4262. // Back off...
  4263. if ( velLen > 0.f ) {
  4264. F32 newT = getMin(0.01f / velLen, dt);
  4265. start -= mVelocity * newT;
  4266. totalMotion -= velLen * newT;
  4267. }
  4268. // Try stepping if there is a vertical surface
  4269. if (collisionList.getMaxHeight() < start.z + mDataBlock->maxStepHeight * scale.z)
  4270. {
  4271. bool stepped = false;
  4272. for (U32 c = 0; c < collisionList.getCount(); c++)
  4273. {
  4274. const Collision& cp = collisionList[c];
  4275. // if (mFabs(mDot(cp.normal,VectorF(0,0,1))) < sVerticalStepDot)
  4276. // Dot with (0,0,1) just extracts Z component [lh]-
  4277. if (mFabs(cp.normal.z) < sVerticalStepDot)
  4278. {
  4279. stepped = step(&start,&maxStep,time);
  4280. break;
  4281. }
  4282. }
  4283. if (stepped)
  4284. {
  4285. continue;
  4286. }
  4287. }
  4288. // Pick the surface most parallel to the face that was hit.
  4289. const Collision *collision = &collisionList[0];
  4290. const Collision *cp = collision + 1;
  4291. const Collision *ep = collision + collisionList.getCount();
  4292. for (; cp != ep; cp++)
  4293. {
  4294. if (cp->faceDot > collision->faceDot)
  4295. collision = cp;
  4296. }
  4297. F32 bd = _doCollisionImpact( collision, wasFalling );
  4298. // Copy this collision out so
  4299. // we can use it to do impacts
  4300. // and query collision.
  4301. *outCol = *collision;
  4302. if (isServerObject() && bd > 6.8f && collision->normal.z > 0.7f)
  4303. {
  4304. fx_s_triggers |= PLAYER_LANDING_S_TRIGGER;
  4305. setMaskBits(TriggerMask);
  4306. }
  4307. // Subtract out velocity
  4308. VectorF dv = collision->normal * (bd + sNormalElasticity);
  4309. mVelocity += dv;
  4310. if (count == 0)
  4311. {
  4312. firstNormal = collision->normal;
  4313. }
  4314. else
  4315. {
  4316. if (count == 1)
  4317. {
  4318. // Re-orient velocity along the crease.
  4319. if (mDot(dv,firstNormal) < 0.0f &&
  4320. mDot(collision->normal,firstNormal) < 0.0f)
  4321. {
  4322. VectorF nv;
  4323. mCross(collision->normal,firstNormal,&nv);
  4324. F32 nvl = nv.len();
  4325. if (nvl)
  4326. {
  4327. if (mDot(nv,mVelocity) < 0.0f)
  4328. nvl = -nvl;
  4329. nv *= mVelocity.len() / nvl;
  4330. mVelocity = nv;
  4331. }
  4332. }
  4333. }
  4334. }
  4335. }
  4336. else
  4337. {
  4338. totalMotion += (end - start).len();
  4339. start = end;
  4340. break;
  4341. }
  4342. }
  4343. if (count == sMoveRetryCount)
  4344. {
  4345. // Failed to move
  4346. start = initialPosition;
  4347. mVelocity.set(0.0f, 0.0f, 0.0f);
  4348. }
  4349. return start;
  4350. }
  4351. F32 Player::_doCollisionImpact( const Collision *collision, bool fallingCollision)
  4352. {
  4353. F32 bd = -mDot( mVelocity, collision->normal);
  4354. // shake camera on ground impact
  4355. if( bd > mDataBlock->groundImpactMinSpeed && isControlObject() )
  4356. {
  4357. F32 ampScale = (bd - mDataBlock->groundImpactMinSpeed) / mDataBlock->minImpactSpeed;
  4358. CameraShake *groundImpactShake = new CameraShake;
  4359. groundImpactShake->setDuration( mDataBlock->groundImpactShakeDuration );
  4360. groundImpactShake->setFrequency( mDataBlock->groundImpactShakeFreq );
  4361. VectorF shakeAmp = mDataBlock->groundImpactShakeAmp * ampScale;
  4362. groundImpactShake->setAmplitude( shakeAmp );
  4363. groundImpactShake->setFalloff( mDataBlock->groundImpactShakeFalloff );
  4364. groundImpactShake->init();
  4365. gCamFXMgr.addFX( groundImpactShake );
  4366. }
  4367. if ( ((bd > mDataBlock->minImpactSpeed && fallingCollision) || bd > mDataBlock->minLateralImpactSpeed)
  4368. && !mMountPending )
  4369. {
  4370. if ( !isGhost() )
  4371. onImpact( collision->object, collision->normal * bd );
  4372. if (mDamageState == Enabled && mState != RecoverState)
  4373. {
  4374. // Scale how long we're down for
  4375. if (mDataBlock->landSequenceTime > 0.0f)
  4376. {
  4377. // Recover time is based on the land sequence
  4378. setState(RecoverState);
  4379. }
  4380. else
  4381. {
  4382. // Legacy recover system
  4383. F32 value = (bd - mDataBlock->minImpactSpeed);
  4384. F32 range = (mDataBlock->minImpactSpeed * 0.9f);
  4385. U32 recover = mDataBlock->recoverDelay;
  4386. if (value < range)
  4387. recover = 1 + S32(mFloor( F32(recover) * value / range) );
  4388. //Con::printf("Used %d recover ticks", recover);
  4389. //Con::printf(" minImpact = %g, this one = %g", mDataBlock->minImpactSpeed, bd);
  4390. setState(RecoverState, recover);
  4391. }
  4392. }
  4393. }
  4394. if ( isServerObject() &&
  4395. (bd > (mDataBlock->minImpactSpeed / 3.0f) || bd > (mDataBlock->minLateralImpactSpeed / 3.0f )) )
  4396. {
  4397. mImpactSound = PlayerData::ImpactNormal;
  4398. setMaskBits(ImpactMask);
  4399. }
  4400. return bd;
  4401. }
  4402. void Player::_handleCollision( const Collision &collision )
  4403. {
  4404. // Track collisions
  4405. if ( !isGhost() &&
  4406. collision.object &&
  4407. collision.object != mContactInfo.contactObject )
  4408. queueCollision( collision.object, mVelocity - collision.object->getVelocity() );
  4409. }
  4410. bool Player::updatePos(const F32 travelTime)
  4411. {
  4412. PROFILE_SCOPE(Player_UpdatePos);
  4413. getTransform().getColumn(3,&mDelta.posVec);
  4414. // When mounted to another object, only Z rotation used.
  4415. if (isMounted()) {
  4416. mVelocity = mMount.object->getVelocity();
  4417. setPosition(Point3F(0.0f, 0.0f, 0.0f), mRot);
  4418. setMaskBits(MoveMask);
  4419. return true;
  4420. }
  4421. Point3F newPos;
  4422. Collision col;
  4423. dMemset( &col, 0, sizeof( col ) );
  4424. // DEBUG:
  4425. //Point3F savedVelocity = mVelocity;
  4426. if ( mPhysicsRep )
  4427. {
  4428. static CollisionList collisionList;
  4429. collisionList.clear();
  4430. newPos = mPhysicsRep->move( mVelocity * travelTime, collisionList );
  4431. bool haveCollisions = false;
  4432. bool wasFalling = mFalling;
  4433. if (collisionList.getCount() > 0)
  4434. {
  4435. mFalling = false;
  4436. haveCollisions = true;
  4437. }
  4438. if (haveCollisions)
  4439. {
  4440. // Pick the collision that most closely matches our direction
  4441. VectorF velNormal = mVelocity;
  4442. velNormal.normalizeSafe();
  4443. const Collision *collision = &collisionList[0];
  4444. F32 collisionDot = mDot(velNormal, collision->normal);
  4445. const Collision *cp = collision + 1;
  4446. const Collision *ep = collision + collisionList.getCount();
  4447. for (; cp != ep; cp++)
  4448. {
  4449. F32 dp = mDot(velNormal, cp->normal);
  4450. if (dp < collisionDot)
  4451. {
  4452. collisionDot = dp;
  4453. collision = cp;
  4454. }
  4455. }
  4456. _doCollisionImpact( collision, wasFalling );
  4457. // Modify our velocity based on collisions
  4458. for (U32 i=0; i<collisionList.getCount(); ++i)
  4459. {
  4460. F32 bd = -mDot( mVelocity, collisionList[i].normal );
  4461. VectorF dv = collisionList[i].normal * (bd + sNormalElasticity);
  4462. mVelocity += dv;
  4463. }
  4464. // Store the last collision for use later on. The handle collision
  4465. // code only expects a single collision object.
  4466. if (collisionList.getCount() > 0)
  4467. col = collisionList[collisionList.getCount() - 1];
  4468. // We'll handle any player-to-player collision, and the last collision
  4469. // with other obejct types.
  4470. for (U32 i=0; i<collisionList.getCount(); ++i)
  4471. {
  4472. Collision& colCheck = collisionList[i];
  4473. if (colCheck.object)
  4474. {
  4475. SceneObject* obj = static_cast<SceneObject*>(col.object);
  4476. if (obj->getTypeMask() & PlayerObjectType)
  4477. {
  4478. _handleCollision( colCheck );
  4479. }
  4480. else
  4481. {
  4482. col = colCheck;
  4483. }
  4484. }
  4485. }
  4486. _handleCollision( col );
  4487. }
  4488. }
  4489. else
  4490. {
  4491. if ( mVelocity.isZero() )
  4492. newPos = mDelta.posVec;
  4493. else
  4494. newPos = _move( travelTime, &col );
  4495. _handleCollision( col );
  4496. }
  4497. // DEBUG:
  4498. //if ( isClientObject() )
  4499. // Con::printf( "(client) vel: %g %g %g", mVelocity.x, mVelocity.y, mVelocity.z );
  4500. //else
  4501. // Con::printf( "(server) vel: %g %g %g", mVelocity.x, mVelocity.y, mVelocity.z );
  4502. // Set new position
  4503. // If on the client, calc delta for backstepping
  4504. if (isClientObject())
  4505. {
  4506. mDelta.pos = newPos;
  4507. mDelta.posVec = mDelta.posVec - mDelta.pos;
  4508. mDelta.dt = 1.0f;
  4509. }
  4510. setPosition( newPos, mRot );
  4511. setMaskBits( MoveMask );
  4512. updateContainer();
  4513. if (!isGhost())
  4514. {
  4515. // Collisions are only queued on the server and can be
  4516. // generated by either updateMove or updatePos
  4517. notifyCollision();
  4518. // Do mission area callbacks on the server as well
  4519. checkMissionArea();
  4520. }
  4521. // Check the total distance moved. If it is more than 1000th of the velocity, then
  4522. // we moved a fair amount...
  4523. //if (totalMotion >= (0.001f * initialSpeed))
  4524. return true;
  4525. //else
  4526. //return false;
  4527. }
  4528. //----------------------------------------------------------------------------
  4529. void Player::_findContact( SceneObject **contactObject,
  4530. VectorF *contactNormal,
  4531. Vector<SceneObject*> *outOverlapObjects )
  4532. {
  4533. Point3F pos;
  4534. getTransform().getColumn(3,&pos);
  4535. Box3F wBox;
  4536. Point3F exp(0,0,sTractionDistance);
  4537. wBox.minExtents = pos + mScaledBox.minExtents - exp;
  4538. wBox.maxExtents.x = pos.x + mScaledBox.maxExtents.x;
  4539. wBox.maxExtents.y = pos.y + mScaledBox.maxExtents.y;
  4540. wBox.maxExtents.z = pos.z + mScaledBox.minExtents.z + sTractionDistance;
  4541. static ClippedPolyList polyList;
  4542. polyList.clear();
  4543. polyList.doConstruct();
  4544. polyList.mNormal.set(0.0f, 0.0f, 0.0f);
  4545. polyList.setInterestNormal(Point3F(0.0f, 0.0f, -1.0f));
  4546. polyList.mPlaneList.setSize(6);
  4547. polyList.mPlaneList[0].setYZ(wBox.minExtents, -1.0f);
  4548. polyList.mPlaneList[1].setXZ(wBox.maxExtents, 1.0f);
  4549. polyList.mPlaneList[2].setYZ(wBox.maxExtents, 1.0f);
  4550. polyList.mPlaneList[3].setXZ(wBox.minExtents, -1.0f);
  4551. polyList.mPlaneList[4].setXY(wBox.minExtents, -1.0f);
  4552. polyList.mPlaneList[5].setXY(wBox.maxExtents, 1.0f);
  4553. Box3F plistBox = wBox;
  4554. // Expand build box as it will be used to collide with items.
  4555. // PickupRadius will be at least the size of the box.
  4556. F32 pd = (F32)mDataBlock->pickupDelta;
  4557. wBox.minExtents.x -= pd; wBox.minExtents.y -= pd;
  4558. wBox.maxExtents.x += pd; wBox.maxExtents.y += pd;
  4559. wBox.maxExtents.z = pos.z + mScaledBox.maxExtents.z;
  4560. // Build list from convex states here...
  4561. CollisionWorkingList& rList = mConvex.getWorkingList();
  4562. CollisionWorkingList* pList = rList.wLink.mNext;
  4563. while (pList != &rList)
  4564. {
  4565. Convex* pConvex = pList->mConvex;
  4566. U32 objectMask = pConvex->getObject()->getTypeMask();
  4567. if ( ( objectMask & sCollisionMoveMask ) &&
  4568. !( objectMask & PhysicalZoneObjectType ) )
  4569. {
  4570. Box3F convexBox = pConvex->getBoundingBox();
  4571. if (plistBox.isOverlapped(convexBox))
  4572. pConvex->getPolyList(&polyList);
  4573. }
  4574. else
  4575. outOverlapObjects->push_back( pConvex->getObject() );
  4576. pList = pList->wLink.mNext;
  4577. }
  4578. if (!polyList.isEmpty())
  4579. {
  4580. // Pick flattest surface
  4581. F32 bestVd = -1.0f;
  4582. ClippedPolyList::Poly* poly = polyList.mPolyList.begin();
  4583. ClippedPolyList::Poly* end = polyList.mPolyList.end();
  4584. for (; poly != end; poly++)
  4585. {
  4586. F32 vd = poly->plane.z; // i.e. mDot(Point3F(0,0,1), poly->plane);
  4587. if (vd > bestVd)
  4588. {
  4589. bestVd = vd;
  4590. *contactObject = poly->object;
  4591. *contactNormal = poly->plane;
  4592. }
  4593. }
  4594. }
  4595. }
  4596. void Player::findContact( bool *run, bool *jump, VectorF *contactNormal )
  4597. {
  4598. SceneObject *contactObject = NULL;
  4599. Vector<SceneObject*> overlapObjects;
  4600. if ( mPhysicsRep )
  4601. mPhysicsRep->findContact( &contactObject, contactNormal, &overlapObjects );
  4602. else
  4603. _findContact( &contactObject, contactNormal, &overlapObjects );
  4604. // Check for triggers, corpses and items.
  4605. const U32 filterMask = isGhost() ? sClientCollisionContactMask : sServerCollisionContactMask;
  4606. for ( U32 i=0; i < overlapObjects.size(); i++ )
  4607. {
  4608. SceneObject *obj = overlapObjects[i];
  4609. U32 objectMask = obj->getTypeMask();
  4610. if ( !( objectMask & filterMask ) )
  4611. continue;
  4612. // Check: triggers, corpses and items...
  4613. //
  4614. if (objectMask & TriggerObjectType)
  4615. {
  4616. Trigger* pTrigger = static_cast<Trigger*>( obj );
  4617. pTrigger->potentialEnterObject(this);
  4618. }
  4619. else if (objectMask & CorpseObjectType)
  4620. {
  4621. // If we've overlapped the worldbounding boxes, then that's it...
  4622. if ( getWorldBox().isOverlapped( obj->getWorldBox() ) )
  4623. {
  4624. ShapeBase* col = static_cast<ShapeBase*>( obj );
  4625. queueCollision(col,getVelocity() - col->getVelocity());
  4626. }
  4627. }
  4628. else if (objectMask & ItemObjectType)
  4629. {
  4630. // If we've overlapped the worldbounding boxes, then that's it...
  4631. Item* item = static_cast<Item*>( obj );
  4632. if ( getWorldBox().isOverlapped(item->getWorldBox()) &&
  4633. item->getCollisionObject() != this &&
  4634. !item->isHidden() )
  4635. queueCollision(item,getVelocity() - item->getVelocity());
  4636. }
  4637. }
  4638. F32 vd = (*contactNormal).z;
  4639. *run = vd > mDataBlock->runSurfaceCos;
  4640. *jump = vd > mDataBlock->jumpSurfaceCos;
  4641. mContactInfo.clear();
  4642. mContactInfo.contacted = contactObject != NULL;
  4643. mContactInfo.contactObject = contactObject;
  4644. if ( mContactInfo.contacted )
  4645. mContactInfo.contactNormal = *contactNormal;
  4646. mContactInfo.run = *run;
  4647. mContactInfo.jump = *jump;
  4648. }
  4649. //----------------------------------------------------------------------------
  4650. void Player::checkMissionArea()
  4651. {
  4652. // Checks to see if the player is in the Mission Area...
  4653. Point3F pos;
  4654. MissionArea * obj = MissionArea::getServerObject();
  4655. if(!obj)
  4656. return;
  4657. const RectI &area = obj->getArea();
  4658. getTransform().getColumn(3, &pos);
  4659. if ((pos.x < area.point.x || pos.x > area.point.x + area.extent.x ||
  4660. pos.y < area.point.y || pos.y > area.point.y + area.extent.y)) {
  4661. if(mInMissionArea) {
  4662. mInMissionArea = false;
  4663. mDataBlock->onLeaveMissionArea_callback( this );
  4664. }
  4665. }
  4666. else if(!mInMissionArea)
  4667. {
  4668. mInMissionArea = true;
  4669. mDataBlock->onEnterMissionArea_callback( this );
  4670. }
  4671. }
  4672. //----------------------------------------------------------------------------
  4673. bool Player::isDisplacable() const
  4674. {
  4675. return true;
  4676. }
  4677. Point3F Player::getMomentum() const
  4678. {
  4679. return mVelocity * getMass();
  4680. }
  4681. void Player::setMomentum(const Point3F& newMomentum)
  4682. {
  4683. Point3F newVelocity = newMomentum / getMass();
  4684. mVelocity = newVelocity;
  4685. }
  4686. #define LH_HACK 1
  4687. // Hack for short-term soln to Training crash -
  4688. #if LH_HACK
  4689. static U32 sBalance;
  4690. bool Player::displaceObject(const Point3F& displacement)
  4691. {
  4692. F32 vellen = mVelocity.len();
  4693. if (vellen < 0.001f || sBalance > 16) {
  4694. mVelocity.set(0.0f, 0.0f, 0.0f);
  4695. return false;
  4696. }
  4697. F32 dt = displacement.len() / vellen;
  4698. sBalance++;
  4699. bool result = updatePos(dt);
  4700. sBalance--;
  4701. getTransform().getColumn(3, &mDelta.pos);
  4702. mDelta.posVec.set(0.0f, 0.0f, 0.0f);
  4703. return result;
  4704. }
  4705. #else
  4706. bool Player::displaceObject(const Point3F& displacement)
  4707. {
  4708. F32 vellen = mVelocity.len();
  4709. if (vellen < 0.001f) {
  4710. mVelocity.set(0.0f, 0.0f, 0.0f);
  4711. return false;
  4712. }
  4713. F32 dt = displacement.len() / vellen;
  4714. bool result = updatePos(dt);
  4715. mObjToWorld.getColumn(3, &mDelta.pos);
  4716. mDelta.posVec.set(0.0f, 0.0f, 0.0f);
  4717. return result;
  4718. }
  4719. #endif
  4720. //----------------------------------------------------------------------------
  4721. void Player::setPosition(const Point3F& pos,const Point3F& rot)
  4722. {
  4723. MatrixF mat;
  4724. if (isMounted()) {
  4725. // Use transform from mounted object
  4726. //MatrixF nmat,zrot;
  4727. mMount.object->getMountTransform( mMount.node, mMount.xfm, &mat );
  4728. //zrot.set(EulerF(0.0f, 0.0f, rot.z));
  4729. //mat.mul(nmat,zrot);
  4730. }
  4731. else {
  4732. mat.set(EulerF(0.0f, 0.0f, rot.z));
  4733. mat.setColumn(3,pos);
  4734. }
  4735. Parent::setTransform(mat);
  4736. mRot = rot;
  4737. if ( mPhysicsRep )
  4738. mPhysicsRep->setTransform( mat );
  4739. }
  4740. void Player::setRenderPosition(const Point3F& pos, const Point3F& rot, F32 dt)
  4741. {
  4742. MatrixF mat;
  4743. if (isMounted()) {
  4744. // Use transform from mounted object
  4745. //MatrixF nmat,zrot;
  4746. mMount.object->getRenderMountTransform( dt, mMount.node, mMount.xfm, &mat );
  4747. //zrot.set(EulerF(0.0f, 0.0f, rot.z));
  4748. //mat.mul(nmat,zrot);
  4749. }
  4750. else {
  4751. EulerF orient(0.0f, 0.0f, rot.z);
  4752. mat.set(orient);
  4753. mat.setColumn(3, pos);
  4754. if (inDeathAnim()) {
  4755. F32 boxRad = (mDataBlock->boxSize.x * 0.5f);
  4756. if (MatrixF * fallMat = mDeath.fallToGround(dt, pos, rot.z, boxRad))
  4757. mat = * fallMat;
  4758. }
  4759. else
  4760. mDeath.initFall();
  4761. }
  4762. Parent::setRenderTransform(mat);
  4763. }
  4764. //----------------------------------------------------------------------------
  4765. void Player::setTransform(const MatrixF& mat)
  4766. {
  4767. // This method should never be called on the client.
  4768. // This currently converts all rotation in the mat into
  4769. // rotations around the z axis.
  4770. Point3F pos,vec;
  4771. mat.getColumn(1,&vec);
  4772. mat.getColumn(3,&pos);
  4773. Point3F rot(0.0f, 0.0f, -mAtan2(-vec.x,vec.y));
  4774. setPosition(pos,rot);
  4775. setMaskBits(MoveMask | NoWarpMask);
  4776. }
  4777. void Player::getEyeTransform(MatrixF* mat)
  4778. {
  4779. getEyeBaseTransform(mat, true);
  4780. // The shape instance is animated in getEyeBaseTransform() so we're
  4781. // good here when attempting to get the eye node position on the server.
  4782. S32 imageIndex = -1;
  4783. S32 shapeIndex = -1;
  4784. MountedImage* image = NULL;
  4785. ShapeBaseImageData* data = NULL;
  4786. for (U32 i=0; i<ShapeBase::MaxMountedImages; ++i)
  4787. {
  4788. image = &(mMountedImageList[i]);
  4789. if (image->dataBlock)
  4790. {
  4791. data = image->dataBlock;
  4792. shapeIndex = getImageShapeIndex(*image);
  4793. if ( data->useEyeNode && (data->animateOnServer || isGhost()) && isFirstPerson() && data->eyeMountNode[shapeIndex] != -1 && data->eyeNode[shapeIndex] != -1 )
  4794. {
  4795. imageIndex = i;
  4796. break;
  4797. }
  4798. }
  4799. }
  4800. if (imageIndex >= 0)
  4801. {
  4802. // Get the image's eye node's position relative to the eye mount node
  4803. MatrixF mountTransform = image->shapeInstance[shapeIndex]->mNodeTransforms[data->eyeMountNode[shapeIndex]];
  4804. Point3F eyeMountNodePos = mountTransform.getPosition();
  4805. mountTransform = image->shapeInstance[shapeIndex]->mNodeTransforms[data->eyeNode[shapeIndex]];
  4806. Point3F eyeNodePos = mountTransform.getPosition() - eyeMountNodePos;
  4807. // Now transform to the image's eye node (position only)
  4808. MatrixF xfm(true);
  4809. xfm.setPosition(eyeNodePos);
  4810. mat->mul(xfm);
  4811. }
  4812. }
  4813. void Player::getEyeBaseTransform(MatrixF* mat, bool includeBank)
  4814. {
  4815. // Eye transform in world space. We only use the eye position
  4816. // from the animation and supply our own rotation.
  4817. MatrixF pmat,xmat,zmat;
  4818. if(!isGhost())
  4819. mShapeInstance->animate();
  4820. xmat.set(EulerF(mHead.x, 0.0f, 0.0f));
  4821. if (mUseHeadZCalc)
  4822. zmat.set(EulerF(0.0f, 0.0f, mHead.z));
  4823. else
  4824. zmat.identity();
  4825. if(includeBank && mDataBlock->cameraCanBank)
  4826. {
  4827. // Take mHead.y into account to bank the camera
  4828. MatrixF imat;
  4829. imat.mul(zmat, xmat);
  4830. MatrixF ymat;
  4831. ymat.set(EulerF(0.0f, mHead.y, 0.0f));
  4832. pmat.mul(imat, ymat);
  4833. }
  4834. else
  4835. {
  4836. pmat.mul(zmat,xmat);
  4837. }
  4838. F32 *dp = pmat;
  4839. F32* sp;
  4840. MatrixF eyeMat(true);
  4841. if (mDataBlock->eyeNode != -1)
  4842. {
  4843. sp = mShapeInstance->mNodeTransforms[mDataBlock->eyeNode];
  4844. }
  4845. else
  4846. {
  4847. Point3F center;
  4848. mObjBox.getCenter(&center);
  4849. eyeMat.setPosition(center);
  4850. sp = eyeMat;
  4851. }
  4852. const Point3F& scale = getScale();
  4853. dp[3] = sp[3] * scale.x;
  4854. dp[7] = sp[7] * scale.y;
  4855. dp[11] = sp[11] * scale.z;
  4856. mat->mul(getTransform(),pmat);
  4857. }
  4858. void Player::getRenderEyeTransform(MatrixF* mat)
  4859. {
  4860. getRenderEyeBaseTransform(mat, true);
  4861. // Use the first image that is set to use the eye node
  4862. for (U32 i=0; i<ShapeBase::MaxMountedImages; ++i)
  4863. {
  4864. MountedImage& image = mMountedImageList[i];
  4865. if (image.dataBlock)
  4866. {
  4867. ShapeBaseImageData& data = *image.dataBlock;
  4868. U32 shapeIndex = getImageShapeIndex(image);
  4869. if ( data.useEyeNode && isFirstPerson() && data.eyeMountNode[shapeIndex] != -1 && data.eyeNode[shapeIndex] != -1 )
  4870. {
  4871. // Get the eye node's position relative to the eye mount node
  4872. MatrixF mountTransform = image.shapeInstance[shapeIndex]->mNodeTransforms[data.eyeMountNode[shapeIndex]];
  4873. Point3F eyeMountNodePos = mountTransform.getPosition();
  4874. mountTransform = image.shapeInstance[shapeIndex]->mNodeTransforms[data.eyeNode[shapeIndex]];
  4875. Point3F eyeNodePos = mountTransform.getPosition() - eyeMountNodePos;
  4876. // Now transform to the image's eye node (position only)
  4877. MatrixF xfm(true);
  4878. xfm.setPosition(eyeNodePos);
  4879. mat->mul(xfm);
  4880. return;
  4881. }
  4882. }
  4883. }
  4884. }
  4885. void Player::getRenderEyeBaseTransform(MatrixF* mat, bool includeBank)
  4886. {
  4887. // Eye transform in world space. We only use the eye position
  4888. // from the animation and supply our own rotation.
  4889. MatrixF pmat,xmat,zmat;
  4890. xmat.set(EulerF(mDelta.head.x + mDelta.headVec.x * mDelta.dt, 0.0f, 0.0f));
  4891. if (mUseHeadZCalc)
  4892. zmat.set(EulerF(0.0f, 0.0f, mDelta.head.z + mDelta.headVec.z * mDelta.dt));
  4893. else
  4894. zmat.identity();
  4895. if(includeBank && mDataBlock->cameraCanBank)
  4896. {
  4897. // Take mHead.y delta into account to bank the camera
  4898. MatrixF imat;
  4899. imat.mul(zmat, xmat);
  4900. MatrixF ymat;
  4901. ymat.set(EulerF(0.0f, mDelta.head.y + mDelta.headVec.y * mDelta.dt, 0.0f));
  4902. pmat.mul(imat, ymat);
  4903. }
  4904. else
  4905. {
  4906. pmat.mul(zmat,xmat);
  4907. }
  4908. F32 *dp = pmat;
  4909. F32* sp;
  4910. MatrixF eyeMat(true);
  4911. if (mDataBlock->eyeNode != -1)
  4912. {
  4913. sp = mShapeInstance->mNodeTransforms[mDataBlock->eyeNode];
  4914. }
  4915. else
  4916. {
  4917. // Use the center of the Player's bounding box for the eye position.
  4918. Point3F center;
  4919. mObjBox.getCenter(&center);
  4920. eyeMat.setPosition(center);
  4921. sp = eyeMat;
  4922. }
  4923. // Only use position of eye node, and take Player's scale
  4924. // into account.
  4925. const Point3F& scale = getScale();
  4926. dp[3] = sp[3] * scale.x;
  4927. dp[7] = sp[7] * scale.y;
  4928. dp[11] = sp[11] * scale.z;
  4929. mat->mul(getRenderTransform(), pmat);
  4930. }
  4931. void Player::getMuzzleTransform(U32 imageSlot,MatrixF* mat)
  4932. {
  4933. disableHeadZCalc();
  4934. MatrixF nmat;
  4935. Parent::getRetractionTransform(imageSlot,&nmat);
  4936. MatrixF smat;
  4937. Parent::getImageTransform(imageSlot,&smat);
  4938. disableCollision();
  4939. // See if we are pushed into a wall...
  4940. if (getDamageState() == Enabled) {
  4941. Point3F start, end;
  4942. smat.getColumn(3, &start);
  4943. nmat.getColumn(3, &end);
  4944. RayInfo rinfo;
  4945. if (getContainer()->castRay(start, end, sCollisionMoveMask, &rinfo)) {
  4946. Point3F finalPoint;
  4947. finalPoint.interpolate(start, end, rinfo.t);
  4948. nmat.setColumn(3, finalPoint);
  4949. }
  4950. else
  4951. Parent::getMuzzleTransform(imageSlot,&nmat);
  4952. }
  4953. else
  4954. Parent::getMuzzleTransform(imageSlot,&nmat);
  4955. enableCollision();
  4956. enableHeadZCalc();
  4957. *mat = nmat;
  4958. }
  4959. void Player::getRenderMuzzleTransform(U32 imageSlot,MatrixF* mat)
  4960. {
  4961. disableHeadZCalc();
  4962. MatrixF nmat;
  4963. Parent::getRenderRetractionTransform(imageSlot,&nmat);
  4964. MatrixF smat;
  4965. Parent::getRenderImageTransform(imageSlot,&smat);
  4966. disableCollision();
  4967. // See if we are pushed into a wall...
  4968. if (getDamageState() == Enabled)
  4969. {
  4970. Point3F start, end;
  4971. smat.getColumn(3, &start);
  4972. nmat.getColumn(3, &end);
  4973. RayInfo rinfo;
  4974. if (getContainer()->castRay(start, end, sCollisionMoveMask, &rinfo)) {
  4975. Point3F finalPoint;
  4976. finalPoint.interpolate(start, end, rinfo.t);
  4977. nmat.setColumn(3, finalPoint);
  4978. }
  4979. else
  4980. {
  4981. Parent::getRenderMuzzleTransform(imageSlot,&nmat);
  4982. }
  4983. }
  4984. else
  4985. {
  4986. Parent::getRenderMuzzleTransform(imageSlot,&nmat);
  4987. }
  4988. enableCollision();
  4989. enableHeadZCalc();
  4990. *mat = nmat;
  4991. }
  4992. void Player::getMuzzleVector(U32 imageSlot,VectorF* vec)
  4993. {
  4994. MatrixF mat;
  4995. getMuzzleTransform(imageSlot,&mat);
  4996. GameConnection * gc = getControllingClient();
  4997. if (gc && !gc->isAIControlled())
  4998. {
  4999. MountedImage& image = mMountedImageList[imageSlot];
  5000. bool fp = gc->isFirstPerson();
  5001. if ((fp && image.dataBlock->correctMuzzleVector) ||
  5002. (!fp && image.dataBlock->correctMuzzleVectorTP))
  5003. {
  5004. disableHeadZCalc();
  5005. if (getCorrectedAim(mat, vec))
  5006. {
  5007. enableHeadZCalc();
  5008. return;
  5009. }
  5010. enableHeadZCalc();
  5011. }
  5012. }
  5013. mat.getColumn(1,vec);
  5014. }
  5015. void Player::renderMountedImage( U32 imageSlot, TSRenderState &rstate, SceneRenderState *state )
  5016. {
  5017. GFX->pushWorldMatrix();
  5018. MatrixF world;
  5019. MountedImage& image = mMountedImageList[imageSlot];
  5020. ShapeBaseImageData& data = *image.dataBlock;
  5021. U32 imageShapeIndex;
  5022. if ( state->isShadowPass() )
  5023. {
  5024. // Force the standard image shapes for the shadow pass.
  5025. imageShapeIndex = ShapeBaseImageData::StandardImageShape;
  5026. }
  5027. else
  5028. {
  5029. imageShapeIndex = getImageShapeIndex(image);
  5030. }
  5031. if ( !state->isShadowPass() && isFirstPerson() && (data.useEyeOffset || (data.useEyeNode && data.eyeMountNode[imageShapeIndex] != -1)) )
  5032. {
  5033. if (data.useEyeNode && data.eyeMountNode[imageShapeIndex] != -1)
  5034. {
  5035. MatrixF nmat;
  5036. getRenderEyeBaseTransform(&nmat, mDataBlock->mountedImagesBank);
  5037. MatrixF offsetMat = image.shapeInstance[imageShapeIndex]->mNodeTransforms[data.eyeMountNode[imageShapeIndex]];
  5038. offsetMat.affineInverse();
  5039. world.mul(nmat,offsetMat);
  5040. }
  5041. else
  5042. {
  5043. MatrixF nmat;
  5044. getRenderEyeBaseTransform(&nmat, mDataBlock->mountedImagesBank);
  5045. world.mul(nmat,data.eyeOffset);
  5046. }
  5047. if ( imageSlot == 0 )
  5048. {
  5049. MatrixF nmat;
  5050. MatrixF smat;
  5051. getRenderRetractionTransform(0,&nmat);
  5052. getRenderImageTransform(0,&smat);
  5053. // See if we are pushed into a wall...
  5054. Point3F start, end;
  5055. smat.getColumn(3, &start);
  5056. nmat.getColumn(3, &end);
  5057. Point3F displace = (start - end) * mWeaponBackFraction;
  5058. world.setPosition( world.getPosition() + displace );
  5059. }
  5060. }
  5061. else
  5062. {
  5063. MatrixF nmat;
  5064. getRenderMountTransform( 0.0f, data.mountPoint, MatrixF::Identity, &nmat);
  5065. world.mul(nmat,data.mountTransform[imageShapeIndex]);
  5066. }
  5067. GFX->setWorldMatrix( world );
  5068. image.shapeInstance[imageShapeIndex]->animate();
  5069. image.shapeInstance[imageShapeIndex]->render( rstate );
  5070. // Render the first person mount image shape?
  5071. if (!state->isShadowPass() && imageShapeIndex == ShapeBaseImageData::FirstPersonImageShape && mShapeFPInstance[imageSlot])
  5072. {
  5073. mShapeFPInstance[imageSlot]->animate();
  5074. mShapeFPInstance[imageSlot]->render( rstate );
  5075. }
  5076. GFX->popWorldMatrix();
  5077. }
  5078. // Bot aiming code calls this frequently and will work fine without the check
  5079. // for being pushed into a wall, which shows up on profile at ~ 3% (eight bots)
  5080. void Player::getMuzzlePointAI(U32 imageSlot, Point3F* point)
  5081. {
  5082. MatrixF nmat;
  5083. Parent::getMuzzleTransform(imageSlot, &nmat);
  5084. // If we are in one of the standard player animations, adjust the
  5085. // muzzle to point in the direction we are looking.
  5086. if (mActionAnimation.action < PlayerData::NumTableActionAnims)
  5087. {
  5088. MatrixF xmat;
  5089. xmat.set(EulerF(mHead.x, 0, 0));
  5090. MatrixF result;
  5091. result.mul(getTransform(), xmat);
  5092. F32 *sp = nmat, *dp = result;
  5093. dp[3] = sp[3]; dp[7] = sp[7]; dp[11] = sp[11];
  5094. result.getColumn(3, point);
  5095. }
  5096. else
  5097. nmat.getColumn(3, point);
  5098. }
  5099. void Player::getCameraParameters(F32 *min,F32* max,Point3F* off,MatrixF* rot)
  5100. {
  5101. if (!mControlObject.isNull() && mControlObject == getObjectMount()) {
  5102. mControlObject->getCameraParameters(min,max,off,rot);
  5103. return;
  5104. }
  5105. const Point3F& scale = getScale();
  5106. *min = mDataBlock->cameraMinDist * scale.y;
  5107. *max = mDataBlock->cameraMaxDist * scale.y;
  5108. off->set(0.0f, 0.0f, 0.0f);
  5109. rot->identity();
  5110. }
  5111. //----------------------------------------------------------------------------
  5112. Point3F Player::getVelocity() const
  5113. {
  5114. return mVelocity;
  5115. }
  5116. F32 Player::getSpeed() const
  5117. {
  5118. return mVelocity.len();
  5119. }
  5120. void Player::setVelocity(const VectorF& vel)
  5121. {
  5122. AssertFatal( !mIsNaN( vel ), "Player::setVelocity() - The velocity is NaN!" );
  5123. mVelocity = vel;
  5124. setMaskBits(MoveMask);
  5125. }
  5126. void Player::applyImpulse(const Point3F&,const VectorF& vec)
  5127. {
  5128. AssertFatal( !mIsNaN( vec ), "Player::applyImpulse() - The vector is NaN!" );
  5129. // Players ignore angular velocity
  5130. VectorF vel;
  5131. vel.x = vec.x / getMass();
  5132. vel.y = vec.y / getMass();
  5133. vel.z = vec.z / getMass();
  5134. // Make sure the impulse isn't too big
  5135. F32 len = vel.magnitudeSafe();
  5136. if (len > sMaxImpulseVelocity)
  5137. {
  5138. Point3F excess = vel * ( 1.0f - (sMaxImpulseVelocity / len ) );
  5139. vel -= excess;
  5140. }
  5141. setVelocity(mVelocity + vel);
  5142. }
  5143. //----------------------------------------------------------------------------
  5144. bool Player::castRay(const Point3F &start, const Point3F &end, RayInfo* info)
  5145. {
  5146. // In standard Torque there's a rather brute force culling of all
  5147. // non-enabled players (corpses) from the ray cast. But, to
  5148. // demonstrate a resurrection spell, we need corpses to be
  5149. // selectable, so this code change allows consideration of corpses
  5150. // in the ray cast if corpsesHiddenFromRayCast is set to false.
  5151. if (sCorpsesHiddenFromRayCast && getDamageState() != Enabled)
  5152. return false;
  5153. // Collide against bounding box. Need at least this for the editor.
  5154. F32 st,et,fst = 0.0f,fet = 1.0f;
  5155. F32 *bmin = &mObjBox.minExtents.x;
  5156. F32 *bmax = &mObjBox.maxExtents.x;
  5157. F32 const *si = &start.x;
  5158. F32 const *ei = &end.x;
  5159. for (S32 i = 0; i < 3; i++) {
  5160. if (*si < *ei) {
  5161. if (*si > *bmax || *ei < *bmin)
  5162. return false;
  5163. F32 di = *ei - *si;
  5164. st = (*si < *bmin)? (*bmin - *si) / di: 0.0f;
  5165. et = (*ei > *bmax)? (*bmax - *si) / di: 1.0f;
  5166. }
  5167. else {
  5168. if (*ei > *bmax || *si < *bmin)
  5169. return false;
  5170. F32 di = *ei - *si;
  5171. st = (*si > *bmax)? (*bmax - *si) / di: 0.0f;
  5172. et = (*ei < *bmin)? (*bmin - *si) / di: 1.0f;
  5173. }
  5174. if (st > fst) fst = st;
  5175. if (et < fet) fet = et;
  5176. if (fet < fst)
  5177. return false;
  5178. bmin++; bmax++;
  5179. si++; ei++;
  5180. }
  5181. info->normal = start - end;
  5182. info->normal.normalizeSafe();
  5183. getTransform().mulV( info->normal );
  5184. info->t = fst;
  5185. info->object = this;
  5186. info->point.interpolate(start,end,fst);
  5187. info->material = 0;
  5188. return true;
  5189. }
  5190. //----------------------------------------------------------------------------
  5191. static MatrixF IMat(1);
  5192. bool Player::buildPolyList(PolyListContext, AbstractPolyList* polyList, const Box3F&, const SphereF&)
  5193. {
  5194. // Collision with the player is always against the player's object
  5195. // space bounding box axis aligned in world space.
  5196. Point3F pos;
  5197. getTransform().getColumn(3,&pos);
  5198. IMat.setColumn(3,pos);
  5199. polyList->setTransform(&IMat, Point3F(1.0f,1.0f,1.0f));
  5200. polyList->setObject(this);
  5201. polyList->addBox(mObjBox);
  5202. return true;
  5203. }
  5204. void Player::buildConvex(const Box3F& box, Convex* convex)
  5205. {
  5206. if (mShapeInstance == NULL)
  5207. return;
  5208. // These should really come out of a pool
  5209. mConvexList->collectGarbage();
  5210. Box3F realBox = box;
  5211. mWorldToObj.mul(realBox);
  5212. realBox.minExtents.convolveInverse(mObjScale);
  5213. realBox.maxExtents.convolveInverse(mObjScale);
  5214. if (realBox.isOverlapped(getObjBox()) == false)
  5215. return;
  5216. Convex* cc = 0;
  5217. CollisionWorkingList& wl = convex->getWorkingList();
  5218. for (CollisionWorkingList* itr = wl.wLink.mNext; itr != &wl; itr = itr->wLink.mNext) {
  5219. if (itr->mConvex->getType() == BoxConvexType &&
  5220. itr->mConvex->getObject() == this) {
  5221. cc = itr->mConvex;
  5222. break;
  5223. }
  5224. }
  5225. if (cc)
  5226. return;
  5227. // Create a new convex.
  5228. BoxConvex* cp = new OrthoBoxConvex;
  5229. mConvexList->registerObject(cp);
  5230. convex->addToWorkingList(cp);
  5231. cp->init(this);
  5232. mObjBox.getCenter(&cp->mCenter);
  5233. cp->mSize.x = mObjBox.len_x() / 2.0f;
  5234. cp->mSize.y = mObjBox.len_y() / 2.0f;
  5235. cp->mSize.z = mObjBox.len_z() / 2.0f;
  5236. }
  5237. //----------------------------------------------------------------------------
  5238. void Player::updateWorkingCollisionSet()
  5239. {
  5240. // First, we need to adjust our velocity for possible acceleration. It is assumed
  5241. // that we will never accelerate more than 20 m/s for gravity, plus 10 m/s for
  5242. // jetting, and an equivalent 10 m/s for jumping. We also assume that the
  5243. // working list is updated on a Tick basis, which means we only expand our
  5244. // box by the possible movement in that tick.
  5245. Point3F scaledVelocity = mVelocity * TickSec;
  5246. F32 len = scaledVelocity.len();
  5247. F32 newLen = len + (10.0f * TickSec);
  5248. // Check to see if it is actually necessary to construct the new working list,
  5249. // or if we can use the cached version from the last query. We use the x
  5250. // component of the min member of the mWorkingQueryBox, which is lame, but
  5251. // it works ok.
  5252. bool updateSet = false;
  5253. Box3F convexBox = mConvex.getBoundingBox(getTransform(), getScale());
  5254. F32 l = (newLen * 1.1f) + 0.1f; // from Convex::updateWorkingList
  5255. const Point3F lPoint( l, l, l );
  5256. convexBox.minExtents -= lPoint;
  5257. convexBox.maxExtents += lPoint;
  5258. // Check containment
  5259. if (mWorkingQueryBox.minExtents.x != -1e9f)
  5260. {
  5261. if (mWorkingQueryBox.isContained(convexBox) == false)
  5262. // Needed region is outside the cached region. Update it.
  5263. updateSet = true;
  5264. }
  5265. else
  5266. {
  5267. // Must update
  5268. updateSet = true;
  5269. }
  5270. // Actually perform the query, if necessary
  5271. if (updateSet == true) {
  5272. const Point3F twolPoint( 2.0f * l, 2.0f * l, 2.0f * l );
  5273. mWorkingQueryBox = convexBox;
  5274. mWorkingQueryBox.minExtents -= twolPoint;
  5275. mWorkingQueryBox.maxExtents += twolPoint;
  5276. disableCollision();
  5277. //We temporarily disable the collisions of anything mounted to us so we don't accidentally walk into things we've attached to us
  5278. for (SceneObject *ptr = mMount.list; ptr; ptr = ptr->getMountLink())
  5279. {
  5280. ptr->disableCollision();
  5281. }
  5282. mConvex.updateWorkingList(mWorkingQueryBox,
  5283. isGhost() ? sClientCollisionContactMask : sServerCollisionContactMask);
  5284. //And now re-enable the collisions of the mounted things
  5285. for (SceneObject *ptr = mMount.list; ptr; ptr = ptr->getMountLink())
  5286. {
  5287. ptr->enableCollision();
  5288. }
  5289. enableCollision();
  5290. }
  5291. }
  5292. //----------------------------------------------------------------------------
  5293. void Player::writePacketData(GameConnection *connection, BitStream *stream)
  5294. {
  5295. Parent::writePacketData(connection, stream);
  5296. stream->writeInt(mState,NumStateBits);
  5297. if (stream->writeFlag(mState == RecoverState))
  5298. stream->writeInt(mRecoverTicks,PlayerData::RecoverDelayBits);
  5299. if (stream->writeFlag(mJumpDelay > 0))
  5300. stream->writeInt(mJumpDelay,PlayerData::JumpDelayBits);
  5301. Point3F pos;
  5302. getTransform().getColumn(3,&pos);
  5303. if (stream->writeFlag(!isMounted())) {
  5304. // Will get position from mount
  5305. stream->setCompressionPoint(pos);
  5306. stream->write(pos.x);
  5307. stream->write(pos.y);
  5308. stream->write(pos.z);
  5309. stream->write(mVelocity.x);
  5310. stream->write(mVelocity.y);
  5311. stream->write(mVelocity.z);
  5312. stream->writeInt(mJumpSurfaceLastContact > 15 ? 15 : mJumpSurfaceLastContact, 4);
  5313. if (stream->writeFlag(!mAllowSprinting || !mAllowCrouching || !mAllowProne || !mAllowJumping || !mAllowJetJumping || !mAllowSwimming))
  5314. {
  5315. stream->writeFlag(mAllowJumping);
  5316. stream->writeFlag(mAllowJetJumping);
  5317. stream->writeFlag(mAllowSprinting);
  5318. stream->writeFlag(mAllowCrouching);
  5319. stream->writeFlag(mAllowProne);
  5320. stream->writeFlag(mAllowSwimming);
  5321. }
  5322. }
  5323. stream->write(mHead.x);
  5324. if(stream->writeFlag(mDataBlock->cameraCanBank))
  5325. {
  5326. // Include mHead.y to allow for camera banking
  5327. stream->write(mHead.y);
  5328. }
  5329. stream->write(mHead.z);
  5330. stream->write(mRot.z);
  5331. if (mControlObject) {
  5332. S32 gIndex = connection->getGhostIndex(mControlObject);
  5333. if (stream->writeFlag(gIndex != -1)) {
  5334. stream->writeInt(gIndex,NetConnection::GhostIdBitSize);
  5335. mControlObject->writePacketData(connection, stream);
  5336. }
  5337. }
  5338. else
  5339. stream->writeFlag(false);
  5340. }
  5341. void Player::readPacketData(GameConnection *connection, BitStream *stream)
  5342. {
  5343. Parent::readPacketData(connection, stream);
  5344. mState = (ActionState)stream->readInt(NumStateBits);
  5345. if (stream->readFlag())
  5346. mRecoverTicks = stream->readInt(PlayerData::RecoverDelayBits);
  5347. if (stream->readFlag())
  5348. mJumpDelay = stream->readInt(PlayerData::JumpDelayBits);
  5349. else
  5350. mJumpDelay = 0;
  5351. Point3F pos,rot;
  5352. if (stream->readFlag()) {
  5353. // Only written if we are not mounted
  5354. stream->read(&pos.x);
  5355. stream->read(&pos.y);
  5356. stream->read(&pos.z);
  5357. stream->read(&mVelocity.x);
  5358. stream->read(&mVelocity.y);
  5359. stream->read(&mVelocity.z);
  5360. stream->setCompressionPoint(pos);
  5361. mDelta.pos = pos;
  5362. mJumpSurfaceLastContact = stream->readInt(4);
  5363. if (stream->readFlag())
  5364. {
  5365. mAllowJumping = stream->readFlag();
  5366. mAllowJetJumping = stream->readFlag();
  5367. mAllowSprinting = stream->readFlag();
  5368. mAllowCrouching = stream->readFlag();
  5369. mAllowProne = stream->readFlag();
  5370. mAllowSwimming = stream->readFlag();
  5371. }
  5372. else
  5373. {
  5374. mAllowJumping = true;
  5375. mAllowJetJumping = true;
  5376. mAllowSprinting = true;
  5377. mAllowCrouching = true;
  5378. mAllowProne = true;
  5379. mAllowSwimming = true;
  5380. }
  5381. }
  5382. else
  5383. pos = mDelta.pos;
  5384. stream->read(&mHead.x);
  5385. if(stream->readFlag())
  5386. {
  5387. // Include mHead.y to allow for camera banking
  5388. stream->read(&mHead.y);
  5389. }
  5390. stream->read(&mHead.z);
  5391. stream->read(&rot.z);
  5392. rot.x = rot.y = 0;
  5393. if (!ignore_updates)
  5394. setPosition(pos,rot);
  5395. mDelta.head = mHead;
  5396. mDelta.rot = rot;
  5397. if (stream->readFlag()) {
  5398. S32 gIndex = stream->readInt(NetConnection::GhostIdBitSize);
  5399. ShapeBase* obj = static_cast<ShapeBase*>(connection->resolveGhost(gIndex));
  5400. setControlObject(obj);
  5401. obj->readPacketData(connection, stream);
  5402. }
  5403. else
  5404. setControlObject(0);
  5405. }
  5406. U32 Player::packUpdate(NetConnection *con, U32 mask, BitStream *stream)
  5407. {
  5408. U32 retMask = Parent::packUpdate(con, mask, stream);
  5409. if (stream->writeFlag((mask & ImpactMask) && !(mask & InitialUpdateMask)))
  5410. stream->writeInt(mImpactSound, PlayerData::ImpactBits);
  5411. if (stream->writeFlag(mask & ActionMask &&
  5412. mActionAnimation.action != PlayerData::NullAnimation &&
  5413. mActionAnimation.action >= PlayerData::NumTableActionAnims)) {
  5414. stream->writeInt(mActionAnimation.action,PlayerData::ActionAnimBits);
  5415. stream->writeFlag(mActionAnimation.holdAtEnd);
  5416. stream->writeFlag(mActionAnimation.atEnd);
  5417. stream->writeFlag(mActionAnimation.firstPerson);
  5418. if (!mActionAnimation.atEnd) {
  5419. // If somewhere in middle on initial update, must send position-
  5420. F32 where = mShapeInstance->getPos(mActionAnimation.thread);
  5421. if (stream->writeFlag((mask & InitialUpdateMask) != 0 && where > 0))
  5422. stream->writeSignedFloat(where, 6);
  5423. }
  5424. }
  5425. if (stream->writeFlag(mask & ActionMask &&
  5426. mArmAnimation.action != PlayerData::NullAnimation &&
  5427. (!(mask & InitialUpdateMask) ||
  5428. mArmAnimation.action != mDataBlock->lookAction))) {
  5429. stream->writeInt(mArmAnimation.action,PlayerData::ActionAnimBits);
  5430. }
  5431. retMask = afx_packUpdate(con, mask, stream, retMask);
  5432. // The rest of the data is part of the control object packet update.
  5433. // If we're controlled by this client, we don't need to send it.
  5434. // we only need to send it if this is the initial update - in that case,
  5435. // the client won't know this is the control object yet.
  5436. if(stream->writeFlag(getControllingClient() == con && !(mask & InitialUpdateMask)))
  5437. return(retMask);
  5438. if (stream->writeFlag(mask & MoveMask))
  5439. {
  5440. stream->writeFlag(mFalling);
  5441. stream->writeFlag(mSwimming);
  5442. stream->writeFlag(mJetting);
  5443. stream->writeInt(mPose, NumPoseBits);
  5444. stream->writeInt(mState,NumStateBits);
  5445. if (stream->writeFlag(mState == RecoverState))
  5446. stream->writeInt(mRecoverTicks,PlayerData::RecoverDelayBits);
  5447. Point3F pos;
  5448. getTransform().getColumn(3,&pos);
  5449. stream->writeCompressedPoint(pos);
  5450. F32 len = mVelocity.len();
  5451. if(stream->writeFlag(len > 0.02f))
  5452. {
  5453. Point3F outVel = mVelocity;
  5454. outVel *= 1.0f/len;
  5455. stream->writeNormalVector(outVel, 10);
  5456. len *= 32.0f; // 5 bits of fraction
  5457. if(len > 8191)
  5458. len = 8191;
  5459. stream->writeInt((S32)len, 13);
  5460. // constrain the range of mRot.z
  5461. while (mRot.z < 0.0f)
  5462. mRot.z += M_2PI_F;
  5463. while (mRot.z > M_2PI_F)
  5464. mRot.z -= M_2PI_F;
  5465. }
  5466. stream->writeFloat(mRot.z / M_2PI_F, 7);
  5467. stream->writeSignedFloat(mHead.x / (mDataBlock->maxLookAngle - mDataBlock->minLookAngle), 6);
  5468. stream->writeSignedFloat(mHead.z / mDataBlock->maxFreelookAngle, 6);
  5469. mDelta.move.pack(stream);
  5470. stream->writeFlag(!(mask & NoWarpMask));
  5471. }
  5472. // Ghost need energy to predict reliably
  5473. if (mDataBlock->maxEnergy > 0.f)
  5474. stream->writeFloat(getEnergyLevel() / mDataBlock->maxEnergy, EnergyLevelBits);
  5475. else
  5476. stream->writeFloat(0.f, EnergyLevelBits);
  5477. return retMask;
  5478. }
  5479. void Player::unpackUpdate(NetConnection *con, BitStream *stream)
  5480. {
  5481. Parent::unpackUpdate(con,stream);
  5482. if (stream->readFlag())
  5483. mImpactSound = stream->readInt(PlayerData::ImpactBits);
  5484. // Server specified action animation
  5485. if (stream->readFlag()) {
  5486. U32 action = stream->readInt(PlayerData::ActionAnimBits);
  5487. bool hold = stream->readFlag();
  5488. bool atEnd = stream->readFlag();
  5489. bool fsp = stream->readFlag();
  5490. F32 animPos = -1.0f;
  5491. if (!atEnd && stream->readFlag())
  5492. animPos = stream->readSignedFloat(6);
  5493. if (isProperlyAdded()) {
  5494. setActionThread(action,true,hold,true,fsp);
  5495. bool inDeath = inDeathAnim();
  5496. if (atEnd)
  5497. {
  5498. mShapeInstance->clearTransition(mActionAnimation.thread);
  5499. mShapeInstance->setPos(mActionAnimation.thread,
  5500. mActionAnimation.forward? 1: 0);
  5501. if (inDeath)
  5502. mDeath.lastPos = 1.0f;
  5503. }
  5504. else if (animPos > 0) {
  5505. mShapeInstance->setPos(mActionAnimation.thread, animPos);
  5506. if (inDeath)
  5507. mDeath.lastPos = animPos;
  5508. }
  5509. // mMountPending suppresses tickDelay countdown so players will sit until
  5510. // their mount, or another animation, comes through (or 13 seconds elapses).
  5511. mMountPending = (S32) (inSittingAnim() ? sMountPendingTickWait : 0);
  5512. }
  5513. else {
  5514. mActionAnimation.action = action;
  5515. mActionAnimation.holdAtEnd = hold;
  5516. mActionAnimation.atEnd = atEnd;
  5517. mActionAnimation.firstPerson = fsp;
  5518. }
  5519. }
  5520. // Server specified arm animation
  5521. if (stream->readFlag()) {
  5522. U32 action = stream->readInt(PlayerData::ActionAnimBits);
  5523. if (isProperlyAdded())
  5524. setArmThread(action);
  5525. else
  5526. mArmAnimation.action = action;
  5527. }
  5528. afx_unpackUpdate(con, stream);
  5529. // Done if controlled by client ( and not initial update )
  5530. if(stream->readFlag())
  5531. return;
  5532. // MoveMask
  5533. if (stream->readFlag()) {
  5534. mPredictionCount = sMaxPredictionTicks;
  5535. mFalling = stream->readFlag();
  5536. mSwimming = stream->readFlag();
  5537. mJetting = stream->readFlag();
  5538. mPose = (Pose)(stream->readInt(NumPoseBits));
  5539. ActionState actionState = (ActionState)stream->readInt(NumStateBits);
  5540. if (stream->readFlag()) {
  5541. mRecoverTicks = stream->readInt(PlayerData::RecoverDelayBits);
  5542. setState(actionState, mRecoverTicks);
  5543. }
  5544. else
  5545. setState(actionState);
  5546. Point3F pos,rot;
  5547. stream->readCompressedPoint(&pos);
  5548. F32 speed = mVelocity.len();
  5549. if(stream->readFlag())
  5550. {
  5551. stream->readNormalVector(&mVelocity, 10);
  5552. mVelocity *= stream->readInt(13) / 32.0f;
  5553. }
  5554. else
  5555. {
  5556. mVelocity.set(0.0f, 0.0f, 0.0f);
  5557. }
  5558. rot.y = rot.x = 0.0f;
  5559. rot.z = stream->readFloat(7) * M_2PI_F;
  5560. mHead.x = stream->readSignedFloat(6) * (mDataBlock->maxLookAngle - mDataBlock->minLookAngle);
  5561. mHead.z = stream->readSignedFloat(6) * mDataBlock->maxFreelookAngle;
  5562. mDelta.move.unpack(stream);
  5563. mDelta.head = mHead;
  5564. mDelta.headVec.set(0.0f, 0.0f, 0.0f);
  5565. if (stream->readFlag() && isProperlyAdded())
  5566. {
  5567. // Determine number of ticks to warp based on the average
  5568. // of the client and server velocities.
  5569. mDelta.warpOffset = pos - mDelta.pos;
  5570. F32 as = (speed + mVelocity.len()) * 0.5f * TickSec;
  5571. F32 dt = (as > 0.00001f) ? mDelta.warpOffset.len() / as: sMaxWarpTicks;
  5572. mDelta.warpTicks = (S32)((dt > sMinWarpTicks) ? getMax(mFloor(dt + 0.5f), 1.0f) : 0.0f);
  5573. if (mDelta.warpTicks)
  5574. {
  5575. // Setup the warp to start on the next tick.
  5576. if (mDelta.warpTicks > sMaxWarpTicks)
  5577. mDelta.warpTicks = sMaxWarpTicks;
  5578. mDelta.warpOffset /= (F32)mDelta.warpTicks;
  5579. mDelta.rotOffset = rot - mDelta.rot;
  5580. // Ignore small rotation differences
  5581. if (mFabs(mDelta.rotOffset.z) < 0.001f)
  5582. mDelta.rotOffset.z = 0;
  5583. // Wrap rotation to +/-PI
  5584. if(mDelta.rotOffset.z < - M_PI_F)
  5585. mDelta.rotOffset.z += M_2PI_F;
  5586. else if(mDelta.rotOffset.z > M_PI_F)
  5587. mDelta.rotOffset.z -= M_2PI_F;
  5588. mDelta.rotOffset /= (F32)mDelta.warpTicks;
  5589. }
  5590. else
  5591. {
  5592. // Going to skip the warp, server and client are real close.
  5593. // Adjust the frame interpolation to move smoothly to the
  5594. // new position within the current tick.
  5595. Point3F cp = mDelta.pos + mDelta.posVec * mDelta.dt;
  5596. if (mDelta.dt == 0)
  5597. {
  5598. mDelta.posVec.set(0.0f, 0.0f, 0.0f);
  5599. mDelta.rotVec.set(0.0f, 0.0f, 0.0f);
  5600. }
  5601. else
  5602. {
  5603. F32 dti = 1.0f / mDelta.dt;
  5604. mDelta.posVec = (cp - pos) * dti;
  5605. mDelta.rotVec.z = mRot.z - rot.z;
  5606. if(mDelta.rotVec.z > M_PI_F)
  5607. mDelta.rotVec.z -= M_2PI_F;
  5608. else if(mDelta.rotVec.z < -M_PI_F)
  5609. mDelta.rotVec.z += M_2PI_F;
  5610. mDelta.rotVec.z *= dti;
  5611. }
  5612. mDelta.pos = pos;
  5613. mDelta.rot = rot;
  5614. if (!ignore_updates)
  5615. setPosition(pos,rot);
  5616. }
  5617. }
  5618. else
  5619. {
  5620. // Set the player to the server position
  5621. mDelta.pos = pos;
  5622. mDelta.rot = rot;
  5623. mDelta.posVec.set(0.0f, 0.0f, 0.0f);
  5624. mDelta.rotVec.set(0.0f, 0.0f, 0.0f);
  5625. mDelta.warpTicks = 0;
  5626. mDelta.dt = 0.0f;
  5627. if (!ignore_updates)
  5628. setPosition(pos,rot);
  5629. }
  5630. }
  5631. F32 energy = stream->readFloat(EnergyLevelBits) * mDataBlock->maxEnergy;
  5632. setEnergyLevel(energy);
  5633. }
  5634. //----------------------------------------------------------------------------
  5635. DefineEngineMethod( Player, getPose, const char*, (),,
  5636. "@brief Get the name of the player's current pose.\n\n"
  5637. "The pose is one of the following:\n\n<ul>"
  5638. "<li>Stand - Standard movement pose.</li>"
  5639. "<li>Sprint - Sprinting pose.</li>"
  5640. "<li>Crouch - Crouch pose.</li>"
  5641. "<li>Prone - Prone pose.</li>"
  5642. "<li>Swim - Swimming pose.</li></ul>\n"
  5643. "@return The current pose; one of: \"Stand\", \"Sprint\", \"Crouch\", \"Prone\", \"Swim\"\n" )
  5644. {
  5645. return object->getPoseName();
  5646. }
  5647. DefineEngineMethod( Player, allowAllPoses, void, (),,
  5648. "@brief Allow all poses a chance to occur.\n\n"
  5649. "This method resets any poses that have manually been blocked from occuring. "
  5650. "This includes the regular pose states such as sprinting, crouch, being prone "
  5651. "and swimming. It also includes being able to jump and jet jump. While this "
  5652. "is allowing these poses to occur it doesn't mean that they all can due to other "
  5653. "conditions. We're just not manually blocking them from being allowed.\n"
  5654. "@see allowJumping()\n"
  5655. "@see allowJetJumping()\n"
  5656. "@see allowSprinting()\n"
  5657. "@see allowCrouching()\n"
  5658. "@see allowProne()\n"
  5659. "@see allowSwimming()\n" )
  5660. {
  5661. object->allowAllPoses();
  5662. }
  5663. DefineEngineMethod( Player, allowJumping, void, (bool state),,
  5664. "@brief Set if the Player is allowed to jump.\n\n"
  5665. "The default is to allow jumping unless there are other environmental concerns "
  5666. "that prevent it. This method is mainly used to explicitly disallow jumping "
  5667. "at any time.\n"
  5668. "@param state Set to true to allow jumping, false to disable it.\n"
  5669. "@see allowAllPoses()\n" )
  5670. {
  5671. object->allowJumping(state);
  5672. }
  5673. DefineEngineMethod( Player, allowJetJumping, void, (bool state),,
  5674. "@brief Set if the Player is allowed to jet jump.\n\n"
  5675. "The default is to allow jet jumping unless there are other environmental concerns "
  5676. "that prevent it. This method is mainly used to explicitly disallow jet jumping "
  5677. "at any time.\n"
  5678. "@param state Set to true to allow jet jumping, false to disable it.\n"
  5679. "@see allowAllPoses()\n" )
  5680. {
  5681. object->allowJetJumping(state);
  5682. }
  5683. DefineEngineMethod( Player, allowSprinting, void, (bool state),,
  5684. "@brief Set if the Player is allowed to sprint.\n\n"
  5685. "The default is to allow sprinting unless there are other environmental concerns "
  5686. "that prevent it. This method is mainly used to explicitly disallow sprinting "
  5687. "at any time.\n"
  5688. "@param state Set to true to allow sprinting, false to disable it.\n"
  5689. "@see allowAllPoses()\n" )
  5690. {
  5691. object->allowSprinting(state);
  5692. }
  5693. DefineEngineMethod( Player, allowCrouching, void, (bool state),,
  5694. "@brief Set if the Player is allowed to crouch.\n\n"
  5695. "The default is to allow crouching unless there are other environmental concerns "
  5696. "that prevent it. This method is mainly used to explicitly disallow crouching "
  5697. "at any time.\n"
  5698. "@param state Set to true to allow crouching, false to disable it.\n"
  5699. "@see allowAllPoses()\n" )
  5700. {
  5701. object->allowCrouching(state);
  5702. }
  5703. DefineEngineMethod( Player, allowProne, void, (bool state),,
  5704. "@brief Set if the Player is allowed to go prone.\n\n"
  5705. "The default is to allow being prone unless there are other environmental concerns "
  5706. "that prevent it. This method is mainly used to explicitly disallow going prone "
  5707. "at any time.\n"
  5708. "@param state Set to true to allow being prone, false to disable it.\n"
  5709. "@see allowAllPoses()\n" )
  5710. {
  5711. object->allowProne(state);
  5712. }
  5713. DefineEngineMethod( Player, allowSwimming, void, (bool state),,
  5714. "@brief Set if the Player is allowed to swim.\n\n"
  5715. "The default is to allow swimming unless there are other environmental concerns "
  5716. "that prevent it. This method is mainly used to explicitly disallow swimming "
  5717. "at any time.\n"
  5718. "@param state Set to true to allow swimming, false to disable it.\n"
  5719. "@see allowAllPoses()\n" )
  5720. {
  5721. object->allowSwimming(state);
  5722. }
  5723. //----------------------------------------------------------------------------
  5724. DefineEngineMethod( Player, getState, const char*, (),,
  5725. "@brief Get the name of the player's current state.\n\n"
  5726. "The state is one of the following:\n\n<ul>"
  5727. "<li>Dead - The Player is dead.</li>"
  5728. "<li>Mounted - The Player is mounted to an object such as a vehicle.</li>"
  5729. "<li>Move - The Player is free to move. The usual state.</li>"
  5730. "<li>Recover - The Player is recovering from a fall. See PlayerData::recoverDelay.</li></ul>\n"
  5731. "@return The current state; one of: \"Dead\", \"Mounted\", \"Move\", \"Recover\"\n" )
  5732. {
  5733. return object->getStateName();
  5734. }
  5735. DefineEngineMethod( Player, getDamageLocation, const char*, ( Point3F pos ),,
  5736. "@brief Get the named damage location and modifier for a given world position.\n\n"
  5737. "the Player object can simulate different hit locations based on a pre-defined set "
  5738. "of PlayerData defined percentages. These hit percentages divide up the Player's "
  5739. "bounding box into different regions. The diagram below demonstrates how the various "
  5740. "PlayerData properties split up the bounding volume:\n\n"
  5741. "<img src=\"images/player_damageloc.png\">\n\n"
  5742. "While you may pass in any world position and getDamageLocation() will provide a best-fit "
  5743. "location, you should be aware that this can produce some interesting results. For example, "
  5744. "any position that is above PlayerData::boxHeadPercentage will be considered a 'head' hit, even "
  5745. "if the world position is high in the sky. Therefore it may be wise to keep the passed in point "
  5746. "to somewhere on the surface of, or within, the Player's bounding volume.\n\n"
  5747. "@note This method will not return an accurate location when the player is "
  5748. "prone or swimming.\n\n"
  5749. "@param pos A world position for which to retrieve a body region on this player.\n"
  5750. "@return a string containing two words (space separated strings), where the "
  5751. "first is a location and the second is a modifier.\n\n"
  5752. "Posible locations:<ul>"
  5753. "<li>head</li>"
  5754. "<li>torso</li>"
  5755. "<li>legs</li></ul>\n"
  5756. "Head modifiers:<ul>"
  5757. "<li>left_back</li>"
  5758. "<li>middle_back</li>"
  5759. "<li>right_back</li>"
  5760. "<li>left_middle</li>"
  5761. "<li>middle_middle</li>"
  5762. "<li>right_middle</li>"
  5763. "<li>left_front</li>"
  5764. "<li>middle_front</li>"
  5765. "<li>right_front</li></ul>\n"
  5766. "Legs/Torso modifiers:<ul>"
  5767. "<li>front_left</li>"
  5768. "<li>front_right</li>"
  5769. "<li>back_left</li>"
  5770. "<li>back_right</li></ul>\n"
  5771. "@see PlayerData::boxHeadPercentage\n"
  5772. "@see PlayerData::boxHeadFrontPercentage\n"
  5773. "@see PlayerData::boxHeadBackPercentage\n"
  5774. "@see PlayerData::boxHeadLeftPercentage\n"
  5775. "@see PlayerData::boxHeadRightPercentage\n"
  5776. "@see PlayerData::boxTorsoPercentage\n"
  5777. )
  5778. {
  5779. const char *buffer1;
  5780. const char *buffer2;
  5781. object->getDamageLocation(pos, buffer1, buffer2);
  5782. static const U32 bufSize = 128;
  5783. char *buff = Con::getReturnBuffer(bufSize);
  5784. dSprintf(buff, bufSize, "%s %s", buffer1, buffer2);
  5785. return buff;
  5786. }
  5787. DefineEngineMethod( Player, setArmThread, bool, ( const char* name ),,
  5788. "@brief Set the sequence that controls the player's arms (dynamically adjusted "
  5789. "to match look direction).\n\n"
  5790. "@param name Name of the sequence to play on the player's arms.\n"
  5791. "@return true if successful, false if failed.\n"
  5792. "@note By default the 'look' sequence is used, if available.\n")
  5793. {
  5794. return object->setArmThread( name );
  5795. }
  5796. DefineEngineMethod( Player, setActionThread, bool, ( const char* name, bool hold, bool fsp ), ( false, true ),
  5797. "@brief Set the main action sequence to play for this player.\n\n"
  5798. "@param name Name of the action sequence to set\n"
  5799. "@param hold Set to false to get a callback on the datablock when the sequence ends (PlayerData::animationDone()). "
  5800. "When set to true no callback is made.\n"
  5801. "@param fsp True if first person and none of the spine nodes in the shape should animate. False will allow the shape's "
  5802. "spine nodes to animate.\n"
  5803. "@return True if succesful, false if failed\n"
  5804. "@note The spine nodes for the Player's shape are named as follows:\n\n<ul>"
  5805. "<li>Bip01 Pelvis</li>"
  5806. "<li>Bip01 Spine</li>"
  5807. "<li>Bip01 Spine1</li>"
  5808. "<li>Bip01 Spine2</li>"
  5809. "<li>Bip01 Neck</li>"
  5810. "<li>Bip01 Head</li></ul>\n\n"
  5811. "You cannot use setActionThread() to have the Player play one of the motion "
  5812. "determined action animation sequences. These sequences are chosen based on how "
  5813. "the Player moves and the Player's current pose. The names of these sequences are:\n\n<ul>"
  5814. "<li>root</li>"
  5815. "<li>run</li>"
  5816. "<li>side</li>"
  5817. "<li>side_right</li>"
  5818. "<li>crouch_root</li>"
  5819. "<li>crouch_forward</li>"
  5820. "<li>crouch_backward</li>"
  5821. "<li>crouch_side</li>"
  5822. "<li>crouch_right</li>"
  5823. "<li>prone_root</li>"
  5824. "<li>prone_forward</li>"
  5825. "<li>prone_backward</li>"
  5826. "<li>swim_root</li>"
  5827. "<li>swim_forward</li>"
  5828. "<li>swim_backward</li>"
  5829. "<li>swim_left</li>"
  5830. "<li>swim_right</li>"
  5831. "<li>fall</li>"
  5832. "<li>jump</li>"
  5833. "<li>standjump</li>"
  5834. "<li>land</li>"
  5835. "<li>jet</li></ul>\n\n"
  5836. "If the player moves in any direction then the animation sequence set using this "
  5837. "method will be cancelled and the chosen mation-based sequence will take over. This makes "
  5838. "great for times when the Player cannot move, such as when mounted, or when it doesn't matter "
  5839. "if the action sequence changes, such as waving and saluting.\n"
  5840. "@tsexample\n"
  5841. "// Place the player in a sitting position after being mounted\n"
  5842. "%player.setActionThread( \"sitting\", true, true );\n"
  5843. "@endtsexample\n")
  5844. {
  5845. return object->setActionThread( name, hold, true, fsp);
  5846. }
  5847. DefineEngineMethod( Player, setControlObject, bool, ( ShapeBase* obj ),,
  5848. "@brief Set the object to be controlled by this player\n\n"
  5849. "It is possible to have the moves sent to the Player object from the "
  5850. "GameConnection to be passed along to another object. This happens, for example "
  5851. "when a player is mounted to a vehicle. The move commands pass through the Player "
  5852. "and on to the vehicle (while the player remains stationary within the vehicle). "
  5853. "With setControlObject() you can have the Player pass along its moves to any object. "
  5854. "One possible use is for a player to move a remote controlled vehicle. In this case "
  5855. "the player does not mount the vehicle directly, but still wants to be able to control it.\n"
  5856. "@param obj Object to control with this player\n"
  5857. "@return True if the object is valid, false if not\n"
  5858. "@see getControlObject()\n"
  5859. "@see clearControlObject()\n"
  5860. "@see GameConnection::setControlObject()")
  5861. {
  5862. if (obj) {
  5863. object->setControlObject(obj);
  5864. return true;
  5865. }
  5866. else
  5867. object->setControlObject(0);
  5868. return false;
  5869. }
  5870. DefineEngineMethod( Player, getControlObject, S32, (),,
  5871. "@brief Get the current object we are controlling.\n\n"
  5872. "@return ID of the ShapeBase object we control, or 0 if not controlling an "
  5873. "object.\n"
  5874. "@see setControlObject()\n"
  5875. "@see clearControlObject()")
  5876. {
  5877. ShapeBase* controlObject = object->getControlObject();
  5878. return controlObject ? controlObject->getId(): 0;
  5879. }
  5880. DefineEngineMethod( Player, clearControlObject, void, (),,
  5881. "@brief Clears the player's current control object.\n\n"
  5882. "Returns control to the player. This internally calls "
  5883. "Player::setControlObject(0).\n"
  5884. "@tsexample\n"
  5885. "%player.clearControlObject();\n"
  5886. "echo(%player.getControlObject()); //<-- Returns 0, player assumes control\n"
  5887. "%player.setControlObject(%vehicle);\n"
  5888. "echo(%player.getControlObject()); //<-- Returns %vehicle, player controls the vehicle now.\n"
  5889. "@endtsexample\n"
  5890. "@note If the player does not have a control object, the player will receive all moves "
  5891. "from its GameConnection. If you're looking to remove control from the player itself "
  5892. "(i.e. stop sending moves to the player) use GameConnection::setControlObject() to transfer "
  5893. "control to another object, such as a camera.\n"
  5894. "@see setControlObject()\n"
  5895. "@see getControlObject()\n"
  5896. "@see GameConnection::setControlObject()\n")
  5897. {
  5898. object->setControlObject(0);
  5899. }
  5900. DefineEngineMethod( Player, checkDismountPoint, bool, ( Point3F oldPos, Point3F pos ),,
  5901. "@brief Check if it is safe to dismount at this position.\n\n"
  5902. "Internally this method casts a ray from oldPos to pos to determine if it hits the "
  5903. "terrain, an interior object, a water object, another player, a static shape, "
  5904. "a vehicle (exluding the one currently mounted), or physical zone. If this ray "
  5905. "is in the clear, then the player's bounding box is also checked for a collision at "
  5906. "the pos position. If this displaced bounding box is also in the clear, then "
  5907. "checkDismountPoint() returns true.\n"
  5908. "@param oldPos The player's current position\n"
  5909. "@param pos The dismount position to check\n"
  5910. "@return True if the dismount position is clear, false if not\n"
  5911. "@note The player must be already mounted for this method to not assert.\n")
  5912. {
  5913. MatrixF oldPosMat(true);
  5914. oldPosMat.setColumn(3, oldPos);
  5915. MatrixF posMat(true);
  5916. posMat.setColumn(3, pos);
  5917. return object->checkDismountPosition(oldPosMat, posMat);
  5918. }
  5919. DefineEngineMethod( Player, getNumDeathAnimations, S32, ( ),,
  5920. "@brief Get the number of death animations available to this player.\n\n"
  5921. "Death animations are assumed to be named death1-N using consecutive indices." )
  5922. {
  5923. S32 count = 0;
  5924. const PlayerData * db = dynamic_cast<PlayerData*>( object->getDataBlock() );
  5925. if ( db )
  5926. {
  5927. for ( S32 i = 0; i < db->actionCount; i++ )
  5928. if ( db->actionList[i].death )
  5929. count++;
  5930. }
  5931. return count;
  5932. }
  5933. //----------------------------------------------------------------------------
  5934. void Player::consoleInit()
  5935. {
  5936. Con::addVariable("$player::renderMyPlayer",TypeBool, &sRenderMyPlayer,
  5937. "@brief Determines if the player is rendered or not.\n\n"
  5938. "Used on the client side to disable the rendering of all Player objects. This is "
  5939. "mainly for the tools or debugging.\n"
  5940. "@ingroup GameObjects\n");
  5941. Con::addVariable("$player::renderMyItems",TypeBool, &sRenderMyItems,
  5942. "@brief Determines if mounted shapes are rendered or not.\n\n"
  5943. "Used on the client side to disable the rendering of all Player mounted objects. This is "
  5944. "mainly used for the tools or debugging.\n"
  5945. "@ingroup GameObjects\n");
  5946. Con::addVariable("$player::renderCollision", TypeBool, &sRenderPlayerCollision,
  5947. "@brief Determines if the player's collision mesh should be rendered.\n\n"
  5948. "This is mainly used for the tools and debugging.\n"
  5949. "@ingroup GameObjects\n");
  5950. Con::addVariable("$player::minWarpTicks",TypeF32,&sMinWarpTicks,
  5951. "@brief Fraction of tick at which instant warp occures on the client.\n\n"
  5952. "@ingroup GameObjects\n");
  5953. Con::addVariable("$player::maxWarpTicks",TypeS32,&sMaxWarpTicks,
  5954. "@brief When a warp needs to occur due to the client being too far off from the server, this is the "
  5955. "maximum number of ticks we'll allow the client to warp to catch up.\n\n"
  5956. "@ingroup GameObjects\n");
  5957. Con::addVariable("$player::maxPredictionTicks",TypeS32,&sMaxPredictionTicks,
  5958. "@brief Maximum number of ticks to predict on the client from the last known move obtained from the server.\n\n"
  5959. "@ingroup GameObjects\n");
  5960. Con::addVariable("$player::maxImpulseVelocity", TypeF32, &sMaxImpulseVelocity,
  5961. "@brief The maximum velocity allowed due to a single impulse.\n\n"
  5962. "@ingroup GameObjects\n");
  5963. // Move triggers
  5964. Con::addVariable("$player::jumpTrigger", TypeS32, &sJumpTrigger,
  5965. "@brief The move trigger index used for player jumping.\n\n"
  5966. "@ingroup GameObjects\n");
  5967. Con::addVariable("$player::crouchTrigger", TypeS32, &sCrouchTrigger,
  5968. "@brief The move trigger index used for player crouching.\n\n"
  5969. "@ingroup GameObjects\n");
  5970. Con::addVariable("$player::proneTrigger", TypeS32, &sProneTrigger,
  5971. "@brief The move trigger index used for player prone pose.\n\n"
  5972. "@ingroup GameObjects\n");
  5973. Con::addVariable("$player::sprintTrigger", TypeS32, &sSprintTrigger,
  5974. "@brief The move trigger index used for player sprinting.\n\n"
  5975. "@ingroup GameObjects\n");
  5976. Con::addVariable("$player::imageTrigger0", TypeS32, &sImageTrigger0,
  5977. "@brief The move trigger index used to trigger mounted image 0.\n\n"
  5978. "@ingroup GameObjects\n");
  5979. Con::addVariable("$player::imageTrigger1", TypeS32, &sImageTrigger1,
  5980. "@brief The move trigger index used to trigger mounted image 1 or alternate fire "
  5981. "on mounted image 0.\n\n"
  5982. "@ingroup GameObjects\n");
  5983. Con::addVariable("$player::jumpJetTrigger", TypeS32, &sJumpJetTrigger,
  5984. "@brief The move trigger index used for player jump jetting.\n\n"
  5985. "@ingroup GameObjects\n");
  5986. Con::addVariable("$player::vehicleDismountTrigger", TypeS32, &sVehicleDismountTrigger,
  5987. "@brief The move trigger index used to dismount player.\n\n"
  5988. "@ingroup GameObjects\n");
  5989. // ExtendedMove support
  5990. Con::addVariable("$player::extendedMoveHeadPosRotIndex", TypeS32, &smExtendedMoveHeadPosRotIndex,
  5991. "@brief The ExtendedMove position/rotation index used for head movements.\n\n"
  5992. "@ingroup GameObjects\n");
  5993. afx_consoleInit();
  5994. }
  5995. //--------------------------------------------------------------------------
  5996. void Player::calcClassRenderData()
  5997. {
  5998. Parent::calcClassRenderData();
  5999. // If nothing is mounted do not perform the calculations below. Otherwise,
  6000. // we'll end up with a bad ray cast as both nmat and smat will be the
  6001. // Player's transform.
  6002. MountedImage& image = mMountedImageList[0];
  6003. if (!image.dataBlock)
  6004. {
  6005. mWeaponBackFraction = 0.0f;
  6006. return;
  6007. }
  6008. disableCollision();
  6009. MatrixF nmat;
  6010. MatrixF smat;
  6011. Parent::getRetractionTransform(0,&nmat);
  6012. Parent::getImageTransform(0, &smat);
  6013. // See if we are pushed into a wall...
  6014. Point3F start, end;
  6015. smat.getColumn(3, &start);
  6016. nmat.getColumn(3, &end);
  6017. RayInfo rinfo;
  6018. if (getContainer()->castRay(start, end, sCollisionMoveMask & ~(WaterObjectType|PhysicalZoneObjectType|MarkerObjectType), &rinfo)) {
  6019. if (rinfo.t < 1.0f)
  6020. mWeaponBackFraction = 1.0f - rinfo.t;
  6021. else
  6022. mWeaponBackFraction = 0.0f;
  6023. } else {
  6024. mWeaponBackFraction = 0.0f;
  6025. }
  6026. enableCollision();
  6027. }
  6028. //-----------------------------------------------------------------------------
  6029. void Player::playFootstepSound( bool triggeredLeft, Material* contactMaterial, SceneObject* contactObject )
  6030. {
  6031. if (footfallSoundOverride > 0)
  6032. return;
  6033. MatrixF footMat = getTransform();
  6034. if( mWaterCoverage > 0.0 )
  6035. {
  6036. // Treading water.
  6037. if ( mWaterCoverage < mDataBlock->footSplashHeight )
  6038. SFX->playOnce( mDataBlock->sound[ PlayerData::FootShallowSplash ], &footMat );
  6039. else
  6040. {
  6041. if ( mWaterCoverage < 1.0 )
  6042. SFX->playOnce( mDataBlock->sound[ PlayerData::FootWading ], &footMat );
  6043. else
  6044. {
  6045. if ( triggeredLeft )
  6046. {
  6047. SFX->playOnce( mDataBlock->sound[ PlayerData::FootUnderWater ], &footMat );
  6048. SFX->playOnce( mDataBlock->sound[ PlayerData::FootBubbles ], &footMat );
  6049. }
  6050. }
  6051. }
  6052. }
  6053. else if( contactMaterial && contactMaterial->mFootstepSoundCustom )
  6054. {
  6055. // Footstep sound defined on material.
  6056. SFX->playOnce( contactMaterial->mFootstepSoundCustom, &footMat );
  6057. }
  6058. else
  6059. {
  6060. // Play default sound.
  6061. S32 sound = -1;
  6062. if (contactMaterial && (contactMaterial->mFootstepSoundId>-1 && contactMaterial->mFootstepSoundId<PlayerData::MaxSoundOffsets))
  6063. sound = contactMaterial->mFootstepSoundId;
  6064. else if( contactObject && contactObject->getTypeMask() & VehicleObjectType )
  6065. sound = 2;
  6066. if (sound>=0)
  6067. SFX->playOnce(mDataBlock->sound[sound], &footMat);
  6068. }
  6069. }
  6070. void Player:: playImpactSound()
  6071. {
  6072. if( mWaterCoverage == 0.0f )
  6073. {
  6074. Point3F pos;
  6075. RayInfo rInfo;
  6076. MatrixF mat = getTransform();
  6077. mat.mulP(Point3F(mDataBlock->decalOffset,0.0f,0.0f), &pos);
  6078. if( gClientContainer.castRay( Point3F( pos.x, pos.y, pos.z + 0.01f ),
  6079. Point3F( pos.x, pos.y, pos.z - 2.0f ),
  6080. STATIC_COLLISION_TYPEMASK | VehicleObjectType,
  6081. &rInfo ) )
  6082. {
  6083. Material* material = ( rInfo.material ? dynamic_cast< Material* >( rInfo.material->getMaterial() ) : 0 );
  6084. if( material && material->mImpactSoundCustom )
  6085. SFX->playOnce( material->mImpactSoundCustom, &getTransform() );
  6086. else
  6087. {
  6088. S32 sound = -1;
  6089. if (material && (material->mImpactSoundId>-1 && material->mImpactSoundId<PlayerData::MaxSoundOffsets))
  6090. sound = material->mImpactSoundId;
  6091. else if( rInfo.object->getTypeMask() & VehicleObjectType )
  6092. sound = 2; // Play metal;
  6093. if (sound >= 0)
  6094. SFX->playOnce(mDataBlock->sound[PlayerData::ImpactStart + sound], &getTransform());
  6095. }
  6096. }
  6097. }
  6098. mImpactSound = 0;
  6099. }
  6100. //--------------------------------------------------------------------------
  6101. // Update splash
  6102. //--------------------------------------------------------------------------
  6103. void Player::updateSplash()
  6104. {
  6105. F32 speed = getVelocity().len();
  6106. if( speed < mDataBlock->splashVelocity || isMounted() ) return;
  6107. Point3F curPos = getPosition();
  6108. if ( curPos.equal( mLastPos ) )
  6109. return;
  6110. if (pointInWater( curPos )) {
  6111. if (!pointInWater( mLastPos )) {
  6112. Point3F norm = getVelocity();
  6113. norm.normalize();
  6114. // make sure player is moving vertically at good pace before playing splash
  6115. F32 splashAng = mDataBlock->splashAngle / 360.0;
  6116. if( mDot( norm, Point3F(0.0, 0.0, -1.0) ) < splashAng )
  6117. return;
  6118. RayInfo rInfo;
  6119. if (gClientContainer.castRay(mLastPos, curPos,
  6120. WaterObjectType, &rInfo)) {
  6121. createSplash( rInfo.point, speed );
  6122. mBubbleEmitterTime = 0.0;
  6123. }
  6124. }
  6125. }
  6126. }
  6127. //--------------------------------------------------------------------------
  6128. void Player::updateFroth( F32 dt )
  6129. {
  6130. // update bubbles
  6131. Point3F moveDir = getVelocity();
  6132. mBubbleEmitterTime += dt;
  6133. if (mBubbleEmitterTime < mDataBlock->bubbleEmitTime) {
  6134. if (mSplashEmitter[PlayerData::BUBBLE_EMITTER]) {
  6135. Point3F emissionPoint = getRenderPosition();
  6136. U32 emitNum = PlayerData::BUBBLE_EMITTER;
  6137. mSplashEmitter[emitNum]->emitParticles(mLastPos, emissionPoint,
  6138. Point3F( 0.0, 0.0, 1.0 ), moveDir, (U32)(dt * 1000.0));
  6139. }
  6140. }
  6141. Point3F contactPoint;
  6142. if (!collidingWithWater(contactPoint)) {
  6143. mLastWaterPos = mLastPos;
  6144. return;
  6145. }
  6146. F32 speed = moveDir.len();
  6147. if ( speed < mDataBlock->splashVelEpsilon )
  6148. speed = 0.0;
  6149. U32 emitRate = (U32) (speed * mDataBlock->splashFreqMod * dt);
  6150. // If we're in the water, swimming, but not
  6151. // moving, then lets emit some particles because
  6152. // we're treading water.
  6153. if ( mSwimming && speed == 0.0 )
  6154. {
  6155. emitRate = (U32) (2.0f * mDataBlock->splashFreqMod * dt);
  6156. }
  6157. U32 i;
  6158. for ( i=0; i<PlayerData::BUBBLE_EMITTER; i++ ) {
  6159. if (mSplashEmitter[i] )
  6160. mSplashEmitter[i]->emitParticles( mLastWaterPos,
  6161. contactPoint, Point3F( 0.0, 0.0, 1.0 ),
  6162. moveDir, emitRate );
  6163. }
  6164. mLastWaterPos = contactPoint;
  6165. }
  6166. void Player::updateWaterSounds(F32 dt)
  6167. {
  6168. if ( mWaterCoverage < 1.0f || mDamageState != Enabled )
  6169. {
  6170. // Stop everything
  6171. if ( mMoveBubbleSound )
  6172. mMoveBubbleSound->stop();
  6173. if ( mWaterBreathSound )
  6174. mWaterBreathSound->stop();
  6175. return;
  6176. }
  6177. if ( mMoveBubbleSound )
  6178. {
  6179. // We're under water and still alive, so let's play something
  6180. if ( mVelocity.len() > 1.0f )
  6181. {
  6182. if ( !mMoveBubbleSound->isPlaying() )
  6183. mMoveBubbleSound->play();
  6184. mMoveBubbleSound->setTransform( getTransform() );
  6185. }
  6186. else
  6187. mMoveBubbleSound->stop();
  6188. }
  6189. if ( mWaterBreathSound )
  6190. {
  6191. if ( !mWaterBreathSound->isPlaying() )
  6192. mWaterBreathSound->play();
  6193. mWaterBreathSound->setTransform( getTransform() );
  6194. }
  6195. }
  6196. //--------------------------------------------------------------------------
  6197. // Returns true if player is intersecting a water surface
  6198. //--------------------------------------------------------------------------
  6199. bool Player::collidingWithWater( Point3F &waterHeight )
  6200. {
  6201. if ( !mCurrentWaterObject )
  6202. return false;
  6203. Point3F curPos = getPosition();
  6204. if ( mWorldBox.maxExtents.z < mLiquidHeight )
  6205. return false;
  6206. curPos.z = mLiquidHeight;
  6207. waterHeight = getPosition();
  6208. waterHeight.z = mLiquidHeight;
  6209. return true;
  6210. }
  6211. //--------------------------------------------------------------------------
  6212. void Player::createSplash( Point3F &pos, F32 speed )
  6213. {
  6214. if ( speed >= mDataBlock->hardSplashSoundVel )
  6215. SFX->playOnce( mDataBlock->sound[PlayerData::ImpactWaterHard], &getTransform() );
  6216. else if ( speed >= mDataBlock->medSplashSoundVel )
  6217. SFX->playOnce( mDataBlock->sound[PlayerData::ImpactWaterMedium], &getTransform() );
  6218. else
  6219. SFX->playOnce( mDataBlock->sound[PlayerData::ImpactWaterEasy], &getTransform() );
  6220. if( mDataBlock->splash )
  6221. {
  6222. MatrixF trans = getTransform();
  6223. trans.setPosition( pos );
  6224. Splash *splash = new Splash;
  6225. splash->onNewDataBlock( mDataBlock->splash, false );
  6226. splash->setTransform( trans );
  6227. splash->setInitialState( trans.getPosition(), Point3F( 0.0, 0.0, 1.0 ) );
  6228. if (!splash->registerObject())
  6229. delete splash;
  6230. }
  6231. }
  6232. bool Player::isControlObject()
  6233. {
  6234. GameConnection* connection = GameConnection::getConnectionToServer();
  6235. if( !connection ) return false;
  6236. ShapeBase *obj = dynamic_cast<ShapeBase*>(connection->getControlObject());
  6237. return ( obj == this );
  6238. }
  6239. void Player::prepRenderImage( SceneRenderState* state )
  6240. {
  6241. bool renderPlayer = true;
  6242. bool renderItems = true;
  6243. /*
  6244. if ( mPhysicsRep && Con::getBoolVariable("$PhysicsPlayer::DebugRender",false) )
  6245. {
  6246. ObjectRenderInst *ri = state->getRenderPass()->allocInst<ObjectRenderInst>();
  6247. ri->renderDelegate.bind( mPhysicsRep, &PhysicsPlayer::renderDebug );
  6248. ri->objectIndex = -1;
  6249. ri->type = RenderPassManager::RIT_Editor;
  6250. state->getRenderPass()->addInst( ri );
  6251. }
  6252. */
  6253. // Debug rendering for all convexes in the Players working list.
  6254. if ( sRenderPlayerCollision )
  6255. {
  6256. ObjectRenderInst *ri = state->getRenderPass()->allocInst<ObjectRenderInst>();
  6257. ri->renderDelegate.bind( this, &Player::renderConvex );
  6258. ri->objectIndex = -1;
  6259. ri->type = RenderPassManager::RIT_Editor;
  6260. state->getRenderPass()->addInst( ri );
  6261. }
  6262. GameConnection* connection = GameConnection::getConnectionToServer();
  6263. if( connection && connection->getControlObject() == this && connection->isFirstPerson() )
  6264. {
  6265. // If we're first person and we are not rendering the player
  6266. // then disable all shadow rendering... a floating gun shadow sucks.
  6267. if ( state->isShadowPass() && !mDataBlock->renderFirstPerson && !mDataBlock->firstPersonShadows )
  6268. return;
  6269. renderPlayer = mDataBlock->renderFirstPerson || !state->isDiffusePass();
  6270. if( !sRenderMyPlayer )
  6271. renderPlayer = false;
  6272. if( !sRenderMyItems )
  6273. renderItems = false;
  6274. }
  6275. // Call the protected base class to do the work
  6276. // now that we know if we're rendering the player
  6277. // and mounted shapes.
  6278. return ShapeBase::_prepRenderImage( state,
  6279. renderPlayer,
  6280. renderItems );
  6281. }
  6282. void Player::renderConvex( ObjectRenderInst *ri, SceneRenderState *state, BaseMatInstance *overrideMat )
  6283. {
  6284. GFX->enterDebugEvent( ColorI(255,0,255), "Player_renderConvex" );
  6285. mConvex.renderWorkingList();
  6286. GFX->leaveDebugEvent();
  6287. }
  6288. // static
  6289. bool Player::sCorpsesHiddenFromRayCast = true; // this default matches stock Torque behavior.
  6290. // static
  6291. void Player::afx_consoleInit()
  6292. {
  6293. Con::addVariable("pref::Player::corpsesHiddenFromRayCast", TypeBool, &sCorpsesHiddenFromRayCast);
  6294. }
  6295. void Player::afx_init()
  6296. {
  6297. overrideLookAnimation = false;
  6298. armLookOverridePos = 0.5f;
  6299. headVLookOverridePos = 0.5f;
  6300. headHLookOverridePos = 0.5f;
  6301. ignore_updates = false;
  6302. fx_c_triggers = 0;
  6303. mark_fx_c_triggers = 0;
  6304. fx_s_triggers = 0;
  6305. move_trigger_states = 0;
  6306. z_velocity = 0.0f;
  6307. mark_idle = false;
  6308. idle_timer = 0.0f;
  6309. mark_s_landing = false;
  6310. speed_bias = 1.0f;
  6311. speed_bias_goal = 1.0f;
  6312. override_movement = 0;
  6313. movement_data.zero();
  6314. movement_op = 1;
  6315. last_movement_tag = 0;
  6316. footfallDecalOverride = 0;
  6317. footfallSoundOverride = 0;
  6318. footfallDustOverride = 0;
  6319. noFootfallFX = false;
  6320. }
  6321. U32 Player::afx_packUpdate(NetConnection* con, U32 mask, BitStream* stream, U32 retMask)
  6322. {
  6323. #if 0
  6324. if (stream->writeFlag(mask & LookOverrideMask))
  6325. #else
  6326. if (stream->writeFlag(mask & ActionMask))
  6327. #endif
  6328. stream->writeFlag(overrideLookAnimation);
  6329. if (stream->writeFlag(mask & TriggerMask))
  6330. stream->write(fx_s_triggers);
  6331. return retMask;
  6332. }
  6333. void Player::afx_unpackUpdate(NetConnection* con, BitStream* stream)
  6334. {
  6335. if (stream->readFlag()) // LookOverrideMask
  6336. overrideLookAnimation = stream->readFlag();
  6337. if (stream->readFlag()) // TriggerMask
  6338. {
  6339. U32 mask;
  6340. stream->read(&mask);
  6341. mark_fx_c_triggers = mask;
  6342. }
  6343. }
  6344. // Code for overriding player's animation with sequences selected by the
  6345. // anim-clip component effect.
  6346. void Player::restoreAnimation(U32 tag)
  6347. {
  6348. // check if this is a blended clip
  6349. if ((tag & BLENDED_CLIP) != 0)
  6350. {
  6351. restoreBlendAnimation(tag);
  6352. return;
  6353. }
  6354. if (tag != 0 && tag == last_anim_tag)
  6355. {
  6356. bool is_death_anim = ((anim_clip_flags & IS_DEATH_ANIM) != 0);
  6357. anim_clip_flags &= ~(ANIM_OVERRIDDEN | IS_DEATH_ANIM);
  6358. if (isClientObject())
  6359. {
  6360. if (mDamageState != Enabled)
  6361. {
  6362. if (!is_death_anim)
  6363. {
  6364. // this is a bit hardwired and desperate,
  6365. // but if he's dead he needs to look like it.
  6366. setActionThread("death10", false, false, false);
  6367. }
  6368. }
  6369. else if (mState != MoveState)
  6370. {
  6371. // not sure what happens here
  6372. }
  6373. else
  6374. {
  6375. pickActionAnimation();
  6376. }
  6377. }
  6378. last_anim_tag = 0;
  6379. last_anim_id = -1;
  6380. }
  6381. }
  6382. U32 Player::getAnimationID(const char* name)
  6383. {
  6384. for (U32 i = 0; i < mDataBlock->actionCount; i++)
  6385. {
  6386. PlayerData::ActionAnimation &anim = mDataBlock->actionList[i];
  6387. if (dStricmp(anim.name, name) == 0)
  6388. return i;
  6389. }
  6390. Con::errorf("Player::getAnimationID() -- Player does not contain a sequence that matches the name, %s.", name);
  6391. return BAD_ANIM_ID;
  6392. }
  6393. U32 Player::playAnimationByID(U32 anim_id, F32 pos, F32 rate, F32 trans, bool hold, bool wait, bool is_death_anim)
  6394. {
  6395. if (anim_id == BAD_ANIM_ID)
  6396. return 0;
  6397. S32 seq_id = mDataBlock->actionList[anim_id].sequence;
  6398. if (seq_id == -1)
  6399. {
  6400. Con::errorf("Player::playAnimation() problem. BAD_SEQ_ID");
  6401. return 0;
  6402. }
  6403. if (mShapeInstance->getShape()->sequences[seq_id].isBlend())
  6404. return playBlendAnimation(seq_id, pos, rate);
  6405. if (isClientObject())
  6406. {
  6407. PlayerData::ActionAnimation &anim = mDataBlock->actionList[anim_id];
  6408. if (anim.sequence != -1)
  6409. {
  6410. mActionAnimation.action = anim_id;
  6411. mActionAnimation.forward = (rate >= 0);
  6412. mActionAnimation.firstPerson = false;
  6413. mActionAnimation.holdAtEnd = hold;
  6414. mActionAnimation.waitForEnd = hold? true: wait;
  6415. mActionAnimation.animateOnServer = false;
  6416. mActionAnimation.atEnd = false;
  6417. mActionAnimation.delayTicks = (S32)sNewAnimationTickTime;
  6418. F32 transTime = (trans < 0) ? sAnimationTransitionTime : trans;
  6419. mShapeInstance->setTimeScale(mActionAnimation.thread, rate);
  6420. mShapeInstance->transitionToSequence(mActionAnimation.thread,anim.sequence,
  6421. pos, transTime, true);
  6422. }
  6423. }
  6424. if (is_death_anim)
  6425. anim_clip_flags |= IS_DEATH_ANIM;
  6426. else
  6427. anim_clip_flags &= ~IS_DEATH_ANIM;
  6428. anim_clip_flags |= ANIM_OVERRIDDEN;
  6429. last_anim_tag = unique_anim_tag_counter++;
  6430. last_anim_id = anim_id;
  6431. return last_anim_tag;
  6432. }
  6433. F32 Player::getAnimationDurationByID(U32 anim_id)
  6434. {
  6435. if (anim_id == BAD_ANIM_ID)
  6436. return 0.0f;
  6437. S32 seq_id = mDataBlock->actionList[anim_id].sequence;
  6438. if (seq_id >= 0 && seq_id < mDataBlock->mShape->sequences.size())
  6439. return mDataBlock->mShape->sequences[seq_id].duration;
  6440. return 0.0f;
  6441. }
  6442. bool Player::isBlendAnimation(const char* name)
  6443. {
  6444. U32 anim_id = getAnimationID(name);
  6445. if (anim_id == BAD_ANIM_ID)
  6446. return false;
  6447. S32 seq_id = mDataBlock->actionList[anim_id].sequence;
  6448. if (seq_id >= 0 && seq_id < mDataBlock->mShape->sequences.size())
  6449. return mDataBlock->mShape->sequences[seq_id].isBlend();
  6450. return false;
  6451. }
  6452. const char* Player::getLastClipName(U32 clip_tag)
  6453. {
  6454. if (clip_tag != last_anim_tag || last_anim_id >= PlayerData::NumActionAnims)
  6455. return "";
  6456. return mDataBlock->actionList[last_anim_id].name;
  6457. }
  6458. void Player::unlockAnimation(U32 tag, bool force)
  6459. {
  6460. if ((tag != 0 && tag == last_anim_lock_tag) || force)
  6461. anim_clip_flags &= ~BLOCK_USER_CONTROL;
  6462. }
  6463. U32 Player::lockAnimation()
  6464. {
  6465. anim_clip_flags |= BLOCK_USER_CONTROL;
  6466. last_anim_lock_tag = unique_anim_tag_counter++;
  6467. return last_anim_lock_tag;
  6468. }
  6469. DefineEngineMethod(Player, isAnimationLocked, bool, (),, "")
  6470. {
  6471. return object->isAnimationLocked();
  6472. }
  6473. void Player::setLookAnimationOverride(bool flag)
  6474. {
  6475. overrideLookAnimation = flag;
  6476. #if 0
  6477. setMaskBits(LookOverrideMask);
  6478. #else
  6479. setMaskBits(ActionMask);
  6480. #endif
  6481. }
  6482. DefineEngineMethod(Player, setLookAnimationOverride, void, (bool flag),, "")
  6483. {
  6484. object->setLookAnimationOverride(flag);
  6485. }
  6486. DefineEngineMethod(Player, copyHeadRotation, void, (Player* other_player),, "")
  6487. {
  6488. if (other_player)
  6489. object->copyHeadRotation(other_player);
  6490. }
  6491. void Player::process_client_triggers(bool triggeredLeft, bool triggeredRight)
  6492. {
  6493. bool mark_landing = false;
  6494. Point3F my_vel = getVelocity();
  6495. if (my_vel.z > 5.0f)
  6496. z_velocity = 1;
  6497. else if (my_vel.z < -5.0f)
  6498. z_velocity = -1;
  6499. else
  6500. {
  6501. if (z_velocity < 0)
  6502. mark_landing = true;
  6503. z_velocity = 0.0f;
  6504. }
  6505. fx_c_triggers = mark_fx_c_triggers;
  6506. if (triggeredLeft)
  6507. fx_c_triggers |= PLAYER_LF_FOOT_C_TRIGGER;
  6508. if (triggeredRight)
  6509. fx_c_triggers |= PLAYER_RT_FOOT_C_TRIGGER;
  6510. if (mark_landing)
  6511. fx_c_triggers |= PLAYER_LANDING_C_TRIGGER;
  6512. if (idle_timer > 10.0f)
  6513. {
  6514. fx_c_triggers |= PLAYER_IDLE_C_TRIGGER;
  6515. idle_timer = 0.0f;
  6516. }
  6517. if (fx_c_triggers & PLAYER_LANDING_S_TRIGGER)
  6518. {
  6519. fx_c_triggers &= ~(PLAYER_LANDING_S_TRIGGER);
  6520. }
  6521. }
  6522. U32 Player::unique_movement_tag_counter = 1;
  6523. void Player::setMovementSpeedBias(F32 bias)
  6524. {
  6525. speed_bias_goal = bias;
  6526. }
  6527. U32 Player::setMovementOverride(F32 bias, const Point3F* mov, U32 op)
  6528. {
  6529. if (mov)
  6530. {
  6531. movement_data = *mov;
  6532. override_movement = true;
  6533. movement_op = (U8)op;
  6534. }
  6535. else
  6536. override_movement = false;
  6537. speed_bias_goal = bias;
  6538. last_movement_tag = unique_movement_tag_counter++;
  6539. return last_movement_tag;
  6540. }
  6541. void Player::restoreMovement(U32 tag)
  6542. {
  6543. if (tag != 0 && tag == last_movement_tag)
  6544. {
  6545. speed_bias_goal = 1.0;
  6546. override_movement = false;
  6547. }
  6548. }
  6549. DefineEngineMethod(Player, setMovementSpeedBias, void, (F32 bias),, "setMovementSpeedBias(F32 bias)")
  6550. {
  6551. object->setMovementSpeedBias(bias);
  6552. }
  6553. void Player::overrideFootfallFX(bool decals, bool sounds, bool dust)
  6554. {
  6555. if (decals)
  6556. footfallDecalOverride++;
  6557. if (sounds)
  6558. footfallSoundOverride++;
  6559. if (dust)
  6560. footfallDustOverride++;
  6561. noFootfallFX = (footfallDecalOverride > 0 && footfallSoundOverride > 0 && footfallDustOverride > 0);
  6562. }
  6563. void Player::restoreFootfallFX(bool decals, bool sounds, bool dust)
  6564. {
  6565. if (decals && footfallDecalOverride)
  6566. footfallDecalOverride--;
  6567. if (sounds && footfallSoundOverride)
  6568. footfallSoundOverride--;
  6569. if (dust && footfallDustOverride)
  6570. footfallDustOverride--;
  6571. noFootfallFX = (footfallDecalOverride > 0 && footfallSoundOverride > 0 && footfallDustOverride > 0);
  6572. }
  6573. #ifdef TORQUE_OPENVR
  6574. void Player::setControllers(Vector<OpenVRTrackedObject*> controllerList)
  6575. {
  6576. mControllers[0] = controllerList.size() > 0 ? controllerList[0] : NULL;
  6577. mControllers[1] = controllerList.size() > 1 ? controllerList[1] : NULL;
  6578. }
  6579. DefineEngineMethod(Player, setVRControllers, void, (OpenVRTrackedObject* controllerL, OpenVRTrackedObject* controllerR,, "")
  6580. {
  6581. Vector<OpenVRTrackedObject*> list;
  6582. if (controllerL)
  6583. {
  6584. list.push_back(controllerL);
  6585. }
  6586. else
  6587. {
  6588. list.push_back(NULL);
  6589. }
  6590. if (controllerR)
  6591. {
  6592. list.push_back(controllerR);
  6593. }
  6594. else
  6595. {
  6596. list.push_back(NULL);
  6597. }
  6598. object->setControllers(list);
  6599. }
  6600. #endif