player.cpp 232 KB

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