player.cpp 252 KB

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