player.cpp 252 KB

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