player.cpp 237 KB

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