player.cpp 238 KB

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