player.cpp 254 KB

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