aframe-extras.js 263 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297
  1. (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
  2. 'use strict';
  3. require('./');
  4. },{"./":2}],2:[function(require,module,exports){
  5. 'use strict';
  6. require('./src/controls');
  7. require('./src/loaders');
  8. require('./src/misc');
  9. require('./src/pathfinding');
  10. require('./src/primitives');
  11. },{"./src/controls":14,"./src/loaders":22,"./src/misc":29,"./src/pathfinding":35,"./src/primitives":43}],3:[function(require,module,exports){
  12. 'use strict';
  13. var _typeof2 = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
  14. var _typeof = typeof Symbol === "function" && _typeof2(Symbol.iterator) === "symbol" ? function (obj) {
  15. return typeof obj === "undefined" ? "undefined" : _typeof2(obj);
  16. } : function (obj) {
  17. return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj === "undefined" ? "undefined" : _typeof2(obj);
  18. };
  19. /**
  20. * @author Kyle-Larson https://github.com/Kyle-Larson
  21. * @author Takahiro https://github.com/takahirox
  22. * @author Lewy Blue https://github.com/looeee
  23. *
  24. * Loader loads FBX file and generates Group representing FBX scene.
  25. * Requires FBX file to be >= 7.0 and in ASCII or >= 6400 in Binary format
  26. * Versions lower than this may load but will probably have errors
  27. *
  28. * Needs Support:
  29. * Morph normals / blend shape normals
  30. *
  31. * FBX format references:
  32. * https://wiki.blender.org/index.php/User:Mont29/Foundation/FBX_File_Structure
  33. * http://help.autodesk.com/view/FBX/2017/ENU/?guid=__cpp_ref_index_html (C++ SDK reference)
  34. *
  35. * Binary format specification:
  36. * https://code.blender.org/2013/08/fbx-binary-file-format-specification/
  37. */
  38. // Monkeypatch for <r89
  39. THREE.LoaderUtils = {
  40. extractUrlBase: THREE.Loader.prototype.extractUrlBase,
  41. decodeText: function decodeText(array) {
  42. return new TextDecoder().decode(array);
  43. }
  44. };
  45. module.exports = THREE.FBXLoader = function () {
  46. var fbxTree;
  47. var connections;
  48. var sceneGraph;
  49. function FBXLoader(manager) {
  50. this.manager = manager !== undefined ? manager : THREE.DefaultLoadingManager;
  51. }
  52. FBXLoader.prototype = {
  53. constructor: FBXLoader,
  54. crossOrigin: 'anonymous',
  55. load: function load(url, onLoad, onProgress, onError) {
  56. var self = this;
  57. var resourceDirectory = THREE.LoaderUtils.extractUrlBase(url);
  58. var loader = new THREE.FileLoader(this.manager);
  59. loader.setResponseType('arraybuffer');
  60. loader.load(url, function (buffer) {
  61. try {
  62. var scene = self.parse(buffer, resourceDirectory);
  63. onLoad(scene);
  64. } catch (error) {
  65. setTimeout(function () {
  66. if (onError) onError(error);
  67. self.manager.itemError(url);
  68. }, 0);
  69. }
  70. }, onProgress, onError);
  71. },
  72. setCrossOrigin: function setCrossOrigin(value) {
  73. this.crossOrigin = value;
  74. return this;
  75. },
  76. parse: function parse(FBXBuffer, resourceDirectory) {
  77. if (isFbxFormatBinary(FBXBuffer)) {
  78. fbxTree = new BinaryParser().parse(FBXBuffer);
  79. } else {
  80. var FBXText = convertArrayBufferToString(FBXBuffer);
  81. if (!isFbxFormatASCII(FBXText)) {
  82. throw new Error('THREE.FBXLoader: Unknown format.');
  83. }
  84. if (getFbxVersion(FBXText) < 7000) {
  85. throw new Error('THREE.FBXLoader: FBX version not supported, FileVersion: ' + getFbxVersion(FBXText));
  86. }
  87. fbxTree = new TextParser().parse(FBXText);
  88. }
  89. //console.log( FBXTree );
  90. var textureLoader = new THREE.TextureLoader(this.manager).setPath(resourceDirectory).setCrossOrigin(this.crossOrigin);
  91. return new FBXTreeParser(textureLoader).parse(fbxTree);
  92. }
  93. };
  94. // Parse the FBXTree object returned by the BinaryParser or TextParser and return a THREE.Group
  95. function FBXTreeParser(textureLoader) {
  96. this.textureLoader = textureLoader;
  97. }
  98. FBXTreeParser.prototype = {
  99. constructor: FBXTreeParser,
  100. parse: function parse() {
  101. connections = this.parseConnections();
  102. var images = this.parseImages();
  103. var textures = this.parseTextures(images);
  104. var materials = this.parseMaterials(textures);
  105. var deformers = this.parseDeformers();
  106. var geometryMap = new GeometryParser().parse(deformers);
  107. this.parseScene(deformers, geometryMap, materials);
  108. return sceneGraph;
  109. },
  110. // Parses FBXTree.Connections which holds parent-child connections between objects (e.g. material -> texture, model->geometry )
  111. // and details the connection type
  112. parseConnections: function parseConnections() {
  113. var connectionMap = new Map();
  114. if ('Connections' in fbxTree) {
  115. var rawConnections = fbxTree.Connections.connections;
  116. rawConnections.forEach(function (rawConnection) {
  117. var fromID = rawConnection[0];
  118. var toID = rawConnection[1];
  119. var relationship = rawConnection[2];
  120. if (!connectionMap.has(fromID)) {
  121. connectionMap.set(fromID, {
  122. parents: [],
  123. children: []
  124. });
  125. }
  126. var parentRelationship = { ID: toID, relationship: relationship };
  127. connectionMap.get(fromID).parents.push(parentRelationship);
  128. if (!connectionMap.has(toID)) {
  129. connectionMap.set(toID, {
  130. parents: [],
  131. children: []
  132. });
  133. }
  134. var childRelationship = { ID: fromID, relationship: relationship };
  135. connectionMap.get(toID).children.push(childRelationship);
  136. });
  137. }
  138. return connectionMap;
  139. },
  140. // Parse FBXTree.Objects.Video for embedded image data
  141. // These images are connected to textures in FBXTree.Objects.Textures
  142. // via FBXTree.Connections.
  143. parseImages: function parseImages() {
  144. var images = {};
  145. var blobs = {};
  146. if ('Video' in fbxTree.Objects) {
  147. var videoNodes = fbxTree.Objects.Video;
  148. for (var nodeID in videoNodes) {
  149. var videoNode = videoNodes[nodeID];
  150. var id = parseInt(nodeID);
  151. images[id] = videoNode.RelativeFilename || videoNode.Filename;
  152. // raw image data is in videoNode.Content
  153. if ('Content' in videoNode) {
  154. var arrayBufferContent = videoNode.Content instanceof ArrayBuffer && videoNode.Content.byteLength > 0;
  155. var base64Content = typeof videoNode.Content === 'string' && videoNode.Content !== '';
  156. if (arrayBufferContent || base64Content) {
  157. var image = this.parseImage(videoNodes[nodeID]);
  158. blobs[videoNode.RelativeFilename || videoNode.Filename] = image;
  159. }
  160. }
  161. }
  162. }
  163. for (var id in images) {
  164. var filename = images[id];
  165. if (blobs[filename] !== undefined) images[id] = blobs[filename];else images[id] = images[id].split('\\').pop();
  166. }
  167. return images;
  168. },
  169. // Parse embedded image data in FBXTree.Video.Content
  170. parseImage: function parseImage(videoNode) {
  171. var content = videoNode.Content;
  172. var fileName = videoNode.RelativeFilename || videoNode.Filename;
  173. var extension = fileName.slice(fileName.lastIndexOf('.') + 1).toLowerCase();
  174. var type;
  175. switch (extension) {
  176. case 'bmp':
  177. type = 'image/bmp';
  178. break;
  179. case 'jpg':
  180. case 'jpeg':
  181. type = 'image/jpeg';
  182. break;
  183. case 'png':
  184. type = 'image/png';
  185. break;
  186. case 'tif':
  187. type = 'image/tiff';
  188. break;
  189. case 'tga':
  190. if (typeof THREE.TGALoader !== 'function') {
  191. console.warn('FBXLoader: THREE.TGALoader is required to load TGA textures');
  192. return;
  193. } else {
  194. if (THREE.Loader.Handlers.get('.tga') === null) {
  195. THREE.Loader.Handlers.add(/\.tga$/i, new THREE.TGALoader());
  196. }
  197. type = 'image/tga';
  198. break;
  199. }
  200. default:
  201. console.warn('FBXLoader: Image type "' + extension + '" is not supported.');
  202. return;
  203. }
  204. if (typeof content === 'string') {
  205. // ASCII format
  206. return 'data:' + type + ';base64,' + content;
  207. } else {
  208. // Binary Format
  209. var array = new Uint8Array(content);
  210. return window.URL.createObjectURL(new Blob([array], { type: type }));
  211. }
  212. },
  213. // Parse nodes in FBXTree.Objects.Texture
  214. // These contain details such as UV scaling, cropping, rotation etc and are connected
  215. // to images in FBXTree.Objects.Video
  216. parseTextures: function parseTextures(images) {
  217. var textureMap = new Map();
  218. if ('Texture' in fbxTree.Objects) {
  219. var textureNodes = fbxTree.Objects.Texture;
  220. for (var nodeID in textureNodes) {
  221. var texture = this.parseTexture(textureNodes[nodeID], images);
  222. textureMap.set(parseInt(nodeID), texture);
  223. }
  224. }
  225. return textureMap;
  226. },
  227. // Parse individual node in FBXTree.Objects.Texture
  228. parseTexture: function parseTexture(textureNode, images) {
  229. var texture = this.loadTexture(textureNode, images);
  230. texture.ID = textureNode.id;
  231. texture.name = textureNode.attrName;
  232. var wrapModeU = textureNode.WrapModeU;
  233. var wrapModeV = textureNode.WrapModeV;
  234. var valueU = wrapModeU !== undefined ? wrapModeU.value : 0;
  235. var valueV = wrapModeV !== undefined ? wrapModeV.value : 0;
  236. // http://download.autodesk.com/us/fbx/SDKdocs/FBX_SDK_Help/files/fbxsdkref/class_k_fbx_texture.html#889640e63e2e681259ea81061b85143a
  237. // 0: repeat(default), 1: clamp
  238. texture.wrapS = valueU === 0 ? THREE.RepeatWrapping : THREE.ClampToEdgeWrapping;
  239. texture.wrapT = valueV === 0 ? THREE.RepeatWrapping : THREE.ClampToEdgeWrapping;
  240. if ('Scaling' in textureNode) {
  241. var values = textureNode.Scaling.value;
  242. texture.repeat.x = values[0];
  243. texture.repeat.y = values[1];
  244. }
  245. return texture;
  246. },
  247. // load a texture specified as a blob or data URI, or via an external URL using THREE.TextureLoader
  248. loadTexture: function loadTexture(textureNode, images) {
  249. var fileName;
  250. var currentPath = this.textureLoader.path;
  251. var children = connections.get(textureNode.id).children;
  252. if (children !== undefined && children.length > 0 && images[children[0].ID] !== undefined) {
  253. fileName = images[children[0].ID];
  254. if (fileName.indexOf('blob:') === 0 || fileName.indexOf('data:') === 0) {
  255. this.textureLoader.setPath(undefined);
  256. }
  257. }
  258. var texture;
  259. var extension = textureNode.FileName.slice(-3).toLowerCase();
  260. if (extension === 'tga') {
  261. var loader = THREE.Loader.Handlers.get('.tga');
  262. if (loader === null) {
  263. console.warn('FBXLoader: TGALoader not found, creating empty placeholder texture for', fileName);
  264. texture = new THREE.Texture();
  265. } else {
  266. texture = loader.load(fileName);
  267. }
  268. } else if (extension === 'psd') {
  269. console.warn('FBXLoader: PSD textures are not supported, creating empty placeholder texture for', fileName);
  270. texture = new THREE.Texture();
  271. } else {
  272. texture = this.textureLoader.load(fileName);
  273. }
  274. this.textureLoader.setPath(currentPath);
  275. return texture;
  276. },
  277. // Parse nodes in FBXTree.Objects.Material
  278. parseMaterials: function parseMaterials(textureMap) {
  279. var materialMap = new Map();
  280. if ('Material' in fbxTree.Objects) {
  281. var materialNodes = fbxTree.Objects.Material;
  282. for (var nodeID in materialNodes) {
  283. var material = this.parseMaterial(materialNodes[nodeID], textureMap);
  284. if (material !== null) materialMap.set(parseInt(nodeID), material);
  285. }
  286. }
  287. return materialMap;
  288. },
  289. // Parse single node in FBXTree.Objects.Material
  290. // Materials are connected to texture maps in FBXTree.Objects.Textures
  291. // FBX format currently only supports Lambert and Phong shading models
  292. parseMaterial: function parseMaterial(materialNode, textureMap) {
  293. var ID = materialNode.id;
  294. var name = materialNode.attrName;
  295. var type = materialNode.ShadingModel;
  296. // Case where FBX wraps shading model in property object.
  297. if ((typeof type === 'undefined' ? 'undefined' : _typeof(type)) === 'object') {
  298. type = type.value;
  299. }
  300. // Ignore unused materials which don't have any connections.
  301. if (!connections.has(ID)) return null;
  302. var parameters = this.parseParameters(materialNode, textureMap, ID);
  303. var material;
  304. switch (type.toLowerCase()) {
  305. case 'phong':
  306. material = new THREE.MeshPhongMaterial();
  307. break;
  308. case 'lambert':
  309. material = new THREE.MeshLambertMaterial();
  310. break;
  311. default:
  312. console.warn('THREE.FBXLoader: unknown material type "%s". Defaulting to MeshPhongMaterial.', type);
  313. material = new THREE.MeshPhongMaterial({ color: 0x3300ff });
  314. break;
  315. }
  316. material.setValues(parameters);
  317. material.name = name;
  318. return material;
  319. },
  320. // Parse FBX material and return parameters suitable for a three.js material
  321. // Also parse the texture map and return any textures associated with the material
  322. parseParameters: function parseParameters(materialNode, textureMap, ID) {
  323. var parameters = {};
  324. if (materialNode.BumpFactor) {
  325. parameters.bumpScale = materialNode.BumpFactor.value;
  326. }
  327. if (materialNode.Diffuse) {
  328. parameters.color = new THREE.Color().fromArray(materialNode.Diffuse.value);
  329. } else if (materialNode.DiffuseColor && materialNode.DiffuseColor.type === 'Color') {
  330. // The blender exporter exports diffuse here instead of in materialNode.Diffuse
  331. parameters.color = new THREE.Color().fromArray(materialNode.DiffuseColor.value);
  332. }
  333. if (materialNode.DisplacementFactor) {
  334. parameters.displacementScale = materialNode.DisplacementFactor.value;
  335. }
  336. if (materialNode.Emissive) {
  337. parameters.emissive = new THREE.Color().fromArray(materialNode.Emissive.value);
  338. } else if (materialNode.EmissiveColor && materialNode.EmissiveColor.type === 'Color') {
  339. // The blender exporter exports emissive color here instead of in materialNode.Emissive
  340. parameters.emissive = new THREE.Color().fromArray(materialNode.EmissiveColor.value);
  341. }
  342. if (materialNode.EmissiveFactor) {
  343. parameters.emissiveIntensity = parseFloat(materialNode.EmissiveFactor.value);
  344. }
  345. if (materialNode.Opacity) {
  346. parameters.opacity = parseFloat(materialNode.Opacity.value);
  347. }
  348. if (parameters.opacity < 1.0) {
  349. parameters.transparent = true;
  350. }
  351. if (materialNode.ReflectionFactor) {
  352. parameters.reflectivity = materialNode.ReflectionFactor.value;
  353. }
  354. if (materialNode.Shininess) {
  355. parameters.shininess = materialNode.Shininess.value;
  356. }
  357. if (materialNode.Specular) {
  358. parameters.specular = new THREE.Color().fromArray(materialNode.Specular.value);
  359. } else if (materialNode.SpecularColor && materialNode.SpecularColor.type === 'Color') {
  360. // The blender exporter exports specular color here instead of in materialNode.Specular
  361. parameters.specular = new THREE.Color().fromArray(materialNode.SpecularColor.value);
  362. }
  363. var self = this;
  364. connections.get(ID).children.forEach(function (child) {
  365. var type = child.relationship;
  366. switch (type) {
  367. case 'Bump':
  368. parameters.bumpMap = self.getTexture(textureMap, child.ID);
  369. break;
  370. case 'DiffuseColor':
  371. parameters.map = self.getTexture(textureMap, child.ID);
  372. break;
  373. case 'DisplacementColor':
  374. parameters.displacementMap = self.getTexture(textureMap, child.ID);
  375. break;
  376. case 'EmissiveColor':
  377. parameters.emissiveMap = self.getTexture(textureMap, child.ID);
  378. break;
  379. case 'NormalMap':
  380. parameters.normalMap = self.getTexture(textureMap, child.ID);
  381. break;
  382. case 'ReflectionColor':
  383. parameters.envMap = self.getTexture(textureMap, child.ID);
  384. parameters.envMap.mapping = THREE.EquirectangularReflectionMapping;
  385. break;
  386. case 'SpecularColor':
  387. parameters.specularMap = self.getTexture(textureMap, child.ID);
  388. break;
  389. case 'TransparentColor':
  390. parameters.alphaMap = self.getTexture(textureMap, child.ID);
  391. parameters.transparent = true;
  392. break;
  393. case 'AmbientColor':
  394. case 'ShininessExponent': // AKA glossiness map
  395. case 'SpecularFactor': // AKA specularLevel
  396. case 'VectorDisplacementColor': // NOTE: Seems to be a copy of DisplacementColor
  397. default:
  398. console.warn('THREE.FBXLoader: %s map is not supported in three.js, skipping texture.', type);
  399. break;
  400. }
  401. });
  402. return parameters;
  403. },
  404. // get a texture from the textureMap for use by a material.
  405. getTexture: function getTexture(textureMap, id) {
  406. // if the texture is a layered texture, just use the first layer and issue a warning
  407. if ('LayeredTexture' in fbxTree.Objects && id in fbxTree.Objects.LayeredTexture) {
  408. console.warn('THREE.FBXLoader: layered textures are not supported in three.js. Discarding all but first layer.');
  409. id = connections.get(id).children[0].ID;
  410. }
  411. return textureMap.get(id);
  412. },
  413. // Parse nodes in FBXTree.Objects.Deformer
  414. // Deformer node can contain skinning or Vertex Cache animation data, however only skinning is supported here
  415. // Generates map of Skeleton-like objects for use later when generating and binding skeletons.
  416. parseDeformers: function parseDeformers() {
  417. var skeletons = {};
  418. var morphTargets = {};
  419. if ('Deformer' in fbxTree.Objects) {
  420. var DeformerNodes = fbxTree.Objects.Deformer;
  421. for (var nodeID in DeformerNodes) {
  422. var deformerNode = DeformerNodes[nodeID];
  423. var relationships = connections.get(parseInt(nodeID));
  424. if (deformerNode.attrType === 'Skin') {
  425. var skeleton = this.parseSkeleton(relationships, DeformerNodes);
  426. skeleton.ID = nodeID;
  427. if (relationships.parents.length > 1) console.warn('THREE.FBXLoader: skeleton attached to more than one geometry is not supported.');
  428. skeleton.geometryID = relationships.parents[0].ID;
  429. skeletons[nodeID] = skeleton;
  430. } else if (deformerNode.attrType === 'BlendShape') {
  431. var morphTarget = {
  432. id: nodeID
  433. };
  434. morphTarget.rawTargets = this.parseMorphTargets(relationships, DeformerNodes);
  435. morphTarget.id = nodeID;
  436. if (relationships.parents.length > 1) console.warn('THREE.FBXLoader: morph target attached to more than one geometry is not supported.');
  437. morphTargets[nodeID] = morphTarget;
  438. }
  439. }
  440. }
  441. return {
  442. skeletons: skeletons,
  443. morphTargets: morphTargets
  444. };
  445. },
  446. // Parse single nodes in FBXTree.Objects.Deformer
  447. // The top level skeleton node has type 'Skin' and sub nodes have type 'Cluster'
  448. // Each skin node represents a skeleton and each cluster node represents a bone
  449. parseSkeleton: function parseSkeleton(relationships, deformerNodes) {
  450. var rawBones = [];
  451. relationships.children.forEach(function (child) {
  452. var boneNode = deformerNodes[child.ID];
  453. if (boneNode.attrType !== 'Cluster') return;
  454. var rawBone = {
  455. ID: child.ID,
  456. indices: [],
  457. weights: [],
  458. transform: new THREE.Matrix4().fromArray(boneNode.Transform.a),
  459. transformLink: new THREE.Matrix4().fromArray(boneNode.TransformLink.a),
  460. linkMode: boneNode.Mode
  461. };
  462. if ('Indexes' in boneNode) {
  463. rawBone.indices = boneNode.Indexes.a;
  464. rawBone.weights = boneNode.Weights.a;
  465. }
  466. rawBones.push(rawBone);
  467. });
  468. return {
  469. rawBones: rawBones,
  470. bones: []
  471. };
  472. },
  473. // The top level morph deformer node has type "BlendShape" and sub nodes have type "BlendShapeChannel"
  474. parseMorphTargets: function parseMorphTargets(relationships, deformerNodes) {
  475. var rawMorphTargets = [];
  476. for (var i = 0; i < relationships.children.length; i++) {
  477. if (i === 8) {
  478. console.warn('FBXLoader: maximum of 8 morph targets supported. Ignoring additional targets.');
  479. break;
  480. }
  481. var child = relationships.children[i];
  482. var morphTargetNode = deformerNodes[child.ID];
  483. var rawMorphTarget = {
  484. name: morphTargetNode.attrName,
  485. initialWeight: morphTargetNode.DeformPercent,
  486. id: morphTargetNode.id,
  487. fullWeights: morphTargetNode.FullWeights.a
  488. };
  489. if (morphTargetNode.attrType !== 'BlendShapeChannel') return;
  490. var targetRelationships = connections.get(parseInt(child.ID));
  491. targetRelationships.children.forEach(function (child) {
  492. if (child.relationship === undefined) rawMorphTarget.geoID = child.ID;
  493. });
  494. rawMorphTargets.push(rawMorphTarget);
  495. }
  496. return rawMorphTargets;
  497. },
  498. // create the main THREE.Group() to be returned by the loader
  499. parseScene: function parseScene(deformers, geometryMap, materialMap) {
  500. sceneGraph = new THREE.Group();
  501. var modelMap = this.parseModels(deformers.skeletons, geometryMap, materialMap);
  502. var modelNodes = fbxTree.Objects.Model;
  503. var self = this;
  504. modelMap.forEach(function (model) {
  505. var modelNode = modelNodes[model.ID];
  506. self.setLookAtProperties(model, modelNode);
  507. var parentConnections = connections.get(model.ID).parents;
  508. parentConnections.forEach(function (connection) {
  509. var parent = modelMap.get(connection.ID);
  510. if (parent !== undefined) parent.add(model);
  511. });
  512. if (model.parent === null) {
  513. sceneGraph.add(model);
  514. }
  515. });
  516. this.bindSkeleton(deformers.skeletons, geometryMap, modelMap);
  517. this.createAmbientLight();
  518. this.setupMorphMaterials();
  519. var animations = new AnimationParser().parse();
  520. // if all the models where already combined in a single group, just return that
  521. if (sceneGraph.children.length === 1 && sceneGraph.children[0].isGroup) {
  522. sceneGraph.children[0].animations = animations;
  523. sceneGraph = sceneGraph.children[0];
  524. }
  525. sceneGraph.animations = animations;
  526. },
  527. // parse nodes in FBXTree.Objects.Model
  528. parseModels: function parseModels(skeletons, geometryMap, materialMap) {
  529. var modelMap = new Map();
  530. var modelNodes = fbxTree.Objects.Model;
  531. for (var nodeID in modelNodes) {
  532. var id = parseInt(nodeID);
  533. var node = modelNodes[nodeID];
  534. var relationships = connections.get(id);
  535. var model = this.buildSkeleton(relationships, skeletons, id, node.attrName);
  536. if (!model) {
  537. switch (node.attrType) {
  538. case 'Camera':
  539. model = this.createCamera(relationships);
  540. break;
  541. case 'Light':
  542. model = this.createLight(relationships);
  543. break;
  544. case 'Mesh':
  545. model = this.createMesh(relationships, geometryMap, materialMap);
  546. break;
  547. case 'NurbsCurve':
  548. model = this.createCurve(relationships, geometryMap);
  549. break;
  550. case 'LimbNode': // usually associated with a Bone, however if a Bone was not created we'll make a Group instead
  551. case 'Null':
  552. default:
  553. model = new THREE.Group();
  554. break;
  555. }
  556. model.name = THREE.PropertyBinding.sanitizeNodeName(node.attrName);
  557. model.ID = id;
  558. }
  559. this.setModelTransforms(model, node);
  560. modelMap.set(id, model);
  561. }
  562. return modelMap;
  563. },
  564. buildSkeleton: function buildSkeleton(relationships, skeletons, id, name) {
  565. var bone = null;
  566. relationships.parents.forEach(function (parent) {
  567. for (var ID in skeletons) {
  568. var skeleton = skeletons[ID];
  569. skeleton.rawBones.forEach(function (rawBone, i) {
  570. if (rawBone.ID === parent.ID) {
  571. var subBone = bone;
  572. bone = new THREE.Bone();
  573. bone.matrixWorld.copy(rawBone.transformLink);
  574. // set name and id here - otherwise in cases where "subBone" is created it will not have a name / id
  575. bone.name = THREE.PropertyBinding.sanitizeNodeName(name);
  576. bone.ID = id;
  577. skeleton.bones[i] = bone;
  578. // In cases where a bone is shared between multiple meshes
  579. // duplicate the bone here and and it as a child of the first bone
  580. if (subBone !== null) {
  581. bone.add(subBone);
  582. }
  583. }
  584. });
  585. }
  586. });
  587. return bone;
  588. },
  589. // create a THREE.PerspectiveCamera or THREE.OrthographicCamera
  590. createCamera: function createCamera(relationships) {
  591. var model;
  592. var cameraAttribute;
  593. relationships.children.forEach(function (child) {
  594. var attr = fbxTree.Objects.NodeAttribute[child.ID];
  595. if (attr !== undefined) {
  596. cameraAttribute = attr;
  597. }
  598. });
  599. if (cameraAttribute === undefined) {
  600. model = new THREE.Object3D();
  601. } else {
  602. var type = 0;
  603. if (cameraAttribute.CameraProjectionType !== undefined && cameraAttribute.CameraProjectionType.value === 1) {
  604. type = 1;
  605. }
  606. var nearClippingPlane = 1;
  607. if (cameraAttribute.NearPlane !== undefined) {
  608. nearClippingPlane = cameraAttribute.NearPlane.value / 1000;
  609. }
  610. var farClippingPlane = 1000;
  611. if (cameraAttribute.FarPlane !== undefined) {
  612. farClippingPlane = cameraAttribute.FarPlane.value / 1000;
  613. }
  614. var width = window.innerWidth;
  615. var height = window.innerHeight;
  616. if (cameraAttribute.AspectWidth !== undefined && cameraAttribute.AspectHeight !== undefined) {
  617. width = cameraAttribute.AspectWidth.value;
  618. height = cameraAttribute.AspectHeight.value;
  619. }
  620. var aspect = width / height;
  621. var fov = 45;
  622. if (cameraAttribute.FieldOfView !== undefined) {
  623. fov = cameraAttribute.FieldOfView.value;
  624. }
  625. var focalLength = cameraAttribute.FocalLength ? cameraAttribute.FocalLength.value : null;
  626. switch (type) {
  627. case 0:
  628. // Perspective
  629. model = new THREE.PerspectiveCamera(fov, aspect, nearClippingPlane, farClippingPlane);
  630. if (focalLength !== null) model.setFocalLength(focalLength);
  631. break;
  632. case 1:
  633. // Orthographic
  634. model = new THREE.OrthographicCamera(-width / 2, width / 2, height / 2, -height / 2, nearClippingPlane, farClippingPlane);
  635. break;
  636. default:
  637. console.warn('THREE.FBXLoader: Unknown camera type ' + type + '.');
  638. model = new THREE.Object3D();
  639. break;
  640. }
  641. }
  642. return model;
  643. },
  644. // Create a THREE.DirectionalLight, THREE.PointLight or THREE.SpotLight
  645. createLight: function createLight(relationships) {
  646. var model;
  647. var lightAttribute;
  648. relationships.children.forEach(function (child) {
  649. var attr = fbxTree.Objects.NodeAttribute[child.ID];
  650. if (attr !== undefined) {
  651. lightAttribute = attr;
  652. }
  653. });
  654. if (lightAttribute === undefined) {
  655. model = new THREE.Object3D();
  656. } else {
  657. var type;
  658. // LightType can be undefined for Point lights
  659. if (lightAttribute.LightType === undefined) {
  660. type = 0;
  661. } else {
  662. type = lightAttribute.LightType.value;
  663. }
  664. var color = 0xffffff;
  665. if (lightAttribute.Color !== undefined) {
  666. color = new THREE.Color().fromArray(lightAttribute.Color.value);
  667. }
  668. var intensity = lightAttribute.Intensity === undefined ? 1 : lightAttribute.Intensity.value / 100;
  669. // light disabled
  670. if (lightAttribute.CastLightOnObject !== undefined && lightAttribute.CastLightOnObject.value === 0) {
  671. intensity = 0;
  672. }
  673. var distance = 0;
  674. if (lightAttribute.FarAttenuationEnd !== undefined) {
  675. if (lightAttribute.EnableFarAttenuation !== undefined && lightAttribute.EnableFarAttenuation.value === 0) {
  676. distance = 0;
  677. } else {
  678. distance = lightAttribute.FarAttenuationEnd.value;
  679. }
  680. }
  681. // TODO: could this be calculated linearly from FarAttenuationStart to FarAttenuationEnd?
  682. var decay = 1;
  683. switch (type) {
  684. case 0:
  685. // Point
  686. model = new THREE.PointLight(color, intensity, distance, decay);
  687. break;
  688. case 1:
  689. // Directional
  690. model = new THREE.DirectionalLight(color, intensity);
  691. break;
  692. case 2:
  693. // Spot
  694. var angle = Math.PI / 3;
  695. if (lightAttribute.InnerAngle !== undefined) {
  696. angle = THREE.Math.degToRad(lightAttribute.InnerAngle.value);
  697. }
  698. var penumbra = 0;
  699. if (lightAttribute.OuterAngle !== undefined) {
  700. // TODO: this is not correct - FBX calculates outer and inner angle in degrees
  701. // with OuterAngle > InnerAngle && OuterAngle <= Math.PI
  702. // while three.js uses a penumbra between (0, 1) to attenuate the inner angle
  703. penumbra = THREE.Math.degToRad(lightAttribute.OuterAngle.value);
  704. penumbra = Math.max(penumbra, 1);
  705. }
  706. model = new THREE.SpotLight(color, intensity, distance, angle, penumbra, decay);
  707. break;
  708. default:
  709. console.warn('THREE.FBXLoader: Unknown light type ' + lightAttribute.LightType.value + ', defaulting to a THREE.PointLight.');
  710. model = new THREE.PointLight(color, intensity);
  711. break;
  712. }
  713. if (lightAttribute.CastShadows !== undefined && lightAttribute.CastShadows.value === 1) {
  714. model.castShadow = true;
  715. }
  716. }
  717. return model;
  718. },
  719. createMesh: function createMesh(relationships, geometryMap, materialMap) {
  720. var model;
  721. var geometry = null;
  722. var material = null;
  723. var materials = [];
  724. // get geometry and materials(s) from connections
  725. relationships.children.forEach(function (child) {
  726. if (geometryMap.has(child.ID)) {
  727. geometry = geometryMap.get(child.ID);
  728. }
  729. if (materialMap.has(child.ID)) {
  730. materials.push(materialMap.get(child.ID));
  731. }
  732. });
  733. if (materials.length > 1) {
  734. material = materials;
  735. } else if (materials.length > 0) {
  736. material = materials[0];
  737. } else {
  738. material = new THREE.MeshPhongMaterial({ color: 0xcccccc });
  739. materials.push(material);
  740. }
  741. if ('color' in geometry.attributes) {
  742. materials.forEach(function (material) {
  743. material.vertexColors = THREE.VertexColors;
  744. });
  745. }
  746. if (geometry.FBX_Deformer) {
  747. materials.forEach(function (material) {
  748. material.skinning = true;
  749. });
  750. model = new THREE.SkinnedMesh(geometry, material);
  751. } else {
  752. model = new THREE.Mesh(geometry, material);
  753. }
  754. return model;
  755. },
  756. createCurve: function createCurve(relationships, geometryMap) {
  757. var geometry = relationships.children.reduce(function (geo, child) {
  758. if (geometryMap.has(child.ID)) geo = geometryMap.get(child.ID);
  759. return geo;
  760. }, null);
  761. // FBX does not list materials for Nurbs lines, so we'll just put our own in here.
  762. var material = new THREE.LineBasicMaterial({ color: 0x3300ff, linewidth: 1 });
  763. return new THREE.Line(geometry, material);
  764. },
  765. // parse the model node for transform details and apply them to the model
  766. setModelTransforms: function setModelTransforms(model, modelNode) {
  767. var transformData = {};
  768. if ('RotationOrder' in modelNode) transformData.eulerOrder = parseInt(modelNode.RotationOrder.value);
  769. if ('Lcl_Translation' in modelNode) transformData.translation = modelNode.Lcl_Translation.value;
  770. if ('RotationOffset' in modelNode) transformData.rotationOffset = modelNode.RotationOffset.value;
  771. if ('Lcl_Rotation' in modelNode) transformData.rotation = modelNode.Lcl_Rotation.value;
  772. if ('PreRotation' in modelNode) transformData.preRotation = modelNode.PreRotation.value;
  773. if ('PostRotation' in modelNode) transformData.postRotation = modelNode.PostRotation.value;
  774. if ('Lcl_Scaling' in modelNode) transformData.scale = modelNode.Lcl_Scaling.value;
  775. var transform = generateTransform(transformData);
  776. model.applyMatrix(transform);
  777. },
  778. setLookAtProperties: function setLookAtProperties(model, modelNode) {
  779. if ('LookAtProperty' in modelNode) {
  780. var children = connections.get(model.ID).children;
  781. children.forEach(function (child) {
  782. if (child.relationship === 'LookAtProperty') {
  783. var lookAtTarget = fbxTree.Objects.Model[child.ID];
  784. if ('Lcl_Translation' in lookAtTarget) {
  785. var pos = lookAtTarget.Lcl_Translation.value;
  786. // DirectionalLight, SpotLight
  787. if (model.target !== undefined) {
  788. model.target.position.fromArray(pos);
  789. sceneGraph.add(model.target);
  790. } else {
  791. // Cameras and other Object3Ds
  792. model.lookAt(new THREE.Vector3().fromArray(pos));
  793. }
  794. }
  795. }
  796. });
  797. }
  798. },
  799. bindSkeleton: function bindSkeleton(skeletons, geometryMap, modelMap) {
  800. var bindMatrices = this.parsePoseNodes();
  801. for (var ID in skeletons) {
  802. var skeleton = skeletons[ID];
  803. var parents = connections.get(parseInt(skeleton.ID)).parents;
  804. parents.forEach(function (parent) {
  805. if (geometryMap.has(parent.ID)) {
  806. var geoID = parent.ID;
  807. var geoRelationships = connections.get(geoID);
  808. geoRelationships.parents.forEach(function (geoConnParent) {
  809. if (modelMap.has(geoConnParent.ID)) {
  810. var model = modelMap.get(geoConnParent.ID);
  811. model.bind(new THREE.Skeleton(skeleton.bones), bindMatrices[geoConnParent.ID]);
  812. }
  813. });
  814. }
  815. });
  816. }
  817. },
  818. parsePoseNodes: function parsePoseNodes() {
  819. var bindMatrices = {};
  820. if ('Pose' in fbxTree.Objects) {
  821. var BindPoseNode = fbxTree.Objects.Pose;
  822. for (var nodeID in BindPoseNode) {
  823. if (BindPoseNode[nodeID].attrType === 'BindPose') {
  824. var poseNodes = BindPoseNode[nodeID].PoseNode;
  825. if (Array.isArray(poseNodes)) {
  826. poseNodes.forEach(function (poseNode) {
  827. bindMatrices[poseNode.Node] = new THREE.Matrix4().fromArray(poseNode.Matrix.a);
  828. });
  829. } else {
  830. bindMatrices[poseNodes.Node] = new THREE.Matrix4().fromArray(poseNodes.Matrix.a);
  831. }
  832. }
  833. }
  834. }
  835. return bindMatrices;
  836. },
  837. // Parse ambient color in FBXTree.GlobalSettings - if it's not set to black (default), create an ambient light
  838. createAmbientLight: function createAmbientLight() {
  839. if ('GlobalSettings' in fbxTree && 'AmbientColor' in fbxTree.GlobalSettings) {
  840. var ambientColor = fbxTree.GlobalSettings.AmbientColor.value;
  841. var r = ambientColor[0];
  842. var g = ambientColor[1];
  843. var b = ambientColor[2];
  844. if (r !== 0 || g !== 0 || b !== 0) {
  845. var color = new THREE.Color(r, g, b);
  846. sceneGraph.add(new THREE.AmbientLight(color, 1));
  847. }
  848. }
  849. },
  850. setupMorphMaterials: function setupMorphMaterials() {
  851. sceneGraph.traverse(function (child) {
  852. if (child.isMesh) {
  853. if (child.geometry.morphAttributes.position || child.geometry.morphAttributes.normal) {
  854. var uuid = child.uuid;
  855. var matUuid = child.material.uuid;
  856. // if a geometry has morph targets, it cannot share the material with other geometries
  857. var sharedMat = false;
  858. sceneGraph.traverse(function (child) {
  859. if (child.isMesh) {
  860. if (child.material.uuid === matUuid && child.uuid !== uuid) sharedMat = true;
  861. }
  862. });
  863. if (sharedMat === true) child.material = child.material.clone();
  864. child.material.morphTargets = true;
  865. }
  866. }
  867. });
  868. }
  869. };
  870. // parse Geometry data from FBXTree and return map of BufferGeometries
  871. function GeometryParser() {}
  872. GeometryParser.prototype = {
  873. constructor: GeometryParser,
  874. // Parse nodes in FBXTree.Objects.Geometry
  875. parse: function parse(deformers) {
  876. var geometryMap = new Map();
  877. if ('Geometry' in fbxTree.Objects) {
  878. var geoNodes = fbxTree.Objects.Geometry;
  879. for (var nodeID in geoNodes) {
  880. var relationships = connections.get(parseInt(nodeID));
  881. var geo = this.parseGeometry(relationships, geoNodes[nodeID], deformers);
  882. geometryMap.set(parseInt(nodeID), geo);
  883. }
  884. }
  885. return geometryMap;
  886. },
  887. // Parse single node in FBXTree.Objects.Geometry
  888. parseGeometry: function parseGeometry(relationships, geoNode, deformers) {
  889. switch (geoNode.attrType) {
  890. case 'Mesh':
  891. return this.parseMeshGeometry(relationships, geoNode, deformers);
  892. break;
  893. case 'NurbsCurve':
  894. return this.parseNurbsGeometry(geoNode);
  895. break;
  896. }
  897. },
  898. // Parse single node mesh geometry in FBXTree.Objects.Geometry
  899. parseMeshGeometry: function parseMeshGeometry(relationships, geoNode, deformers) {
  900. var skeletons = deformers.skeletons;
  901. var morphTargets = deformers.morphTargets;
  902. var modelNodes = relationships.parents.map(function (parent) {
  903. return fbxTree.Objects.Model[parent.ID];
  904. });
  905. // don't create geometry if it is not associated with any models
  906. if (modelNodes.length === 0) return;
  907. var skeleton = relationships.children.reduce(function (skeleton, child) {
  908. if (skeletons[child.ID] !== undefined) skeleton = skeletons[child.ID];
  909. return skeleton;
  910. }, null);
  911. var morphTarget = relationships.children.reduce(function (morphTarget, child) {
  912. if (morphTargets[child.ID] !== undefined) morphTarget = morphTargets[child.ID];
  913. return morphTarget;
  914. }, null);
  915. // TODO: if there is more than one model associated with the geometry, AND the models have
  916. // different geometric transforms, then this will cause problems
  917. // if ( modelNodes.length > 1 ) { }
  918. // For now just assume one model and get the preRotations from that
  919. var modelNode = modelNodes[0];
  920. var transformData = {};
  921. if ('RotationOrder' in modelNode) transformData.eulerOrder = modelNode.RotationOrder.value;
  922. if ('GeometricTranslation' in modelNode) transformData.translation = modelNode.GeometricTranslation.value;
  923. if ('GeometricRotation' in modelNode) transformData.rotation = modelNode.GeometricRotation.value;
  924. if ('GeometricScaling' in modelNode) transformData.scale = modelNode.GeometricScaling.value;
  925. var transform = generateTransform(transformData);
  926. return this.genGeometry(geoNode, skeleton, morphTarget, transform);
  927. },
  928. // Generate a THREE.BufferGeometry from a node in FBXTree.Objects.Geometry
  929. genGeometry: function genGeometry(geoNode, skeleton, morphTarget, preTransform) {
  930. var geo = new THREE.BufferGeometry();
  931. if (geoNode.attrName) geo.name = geoNode.attrName;
  932. var geoInfo = this.parseGeoNode(geoNode, skeleton);
  933. var buffers = this.genBuffers(geoInfo);
  934. var positionAttribute = new THREE.Float32BufferAttribute(buffers.vertex, 3);
  935. preTransform.applyToBufferAttribute(positionAttribute);
  936. geo.addAttribute('position', positionAttribute);
  937. if (buffers.colors.length > 0) {
  938. geo.addAttribute('color', new THREE.Float32BufferAttribute(buffers.colors, 3));
  939. }
  940. if (skeleton) {
  941. geo.addAttribute('skinIndex', new THREE.Uint16BufferAttribute(buffers.weightsIndices, 4));
  942. geo.addAttribute('skinWeight', new THREE.Float32BufferAttribute(buffers.vertexWeights, 4));
  943. // used later to bind the skeleton to the model
  944. geo.FBX_Deformer = skeleton;
  945. }
  946. if (buffers.normal.length > 0) {
  947. var normalAttribute = new THREE.Float32BufferAttribute(buffers.normal, 3);
  948. var normalMatrix = new THREE.Matrix3().getNormalMatrix(preTransform);
  949. normalMatrix.applyToBufferAttribute(normalAttribute);
  950. geo.addAttribute('normal', normalAttribute);
  951. }
  952. buffers.uvs.forEach(function (uvBuffer, i) {
  953. // subsequent uv buffers are called 'uv1', 'uv2', ...
  954. var name = 'uv' + (i + 1).toString();
  955. // the first uv buffer is just called 'uv'
  956. if (i === 0) {
  957. name = 'uv';
  958. }
  959. geo.addAttribute(name, new THREE.Float32BufferAttribute(buffers.uvs[i], 2));
  960. });
  961. if (geoInfo.material && geoInfo.material.mappingType !== 'AllSame') {
  962. // Convert the material indices of each vertex into rendering groups on the geometry.
  963. var prevMaterialIndex = buffers.materialIndex[0];
  964. var startIndex = 0;
  965. buffers.materialIndex.forEach(function (currentIndex, i) {
  966. if (currentIndex !== prevMaterialIndex) {
  967. geo.addGroup(startIndex, i - startIndex, prevMaterialIndex);
  968. prevMaterialIndex = currentIndex;
  969. startIndex = i;
  970. }
  971. });
  972. // the loop above doesn't add the last group, do that here.
  973. if (geo.groups.length > 0) {
  974. var lastGroup = geo.groups[geo.groups.length - 1];
  975. var lastIndex = lastGroup.start + lastGroup.count;
  976. if (lastIndex !== buffers.materialIndex.length) {
  977. geo.addGroup(lastIndex, buffers.materialIndex.length - lastIndex, prevMaterialIndex);
  978. }
  979. }
  980. // case where there are multiple materials but the whole geometry is only
  981. // using one of them
  982. if (geo.groups.length === 0) {
  983. geo.addGroup(0, buffers.materialIndex.length, buffers.materialIndex[0]);
  984. }
  985. }
  986. this.addMorphTargets(geo, geoNode, morphTarget, preTransform);
  987. return geo;
  988. },
  989. parseGeoNode: function parseGeoNode(geoNode, skeleton) {
  990. var geoInfo = {};
  991. geoInfo.vertexPositions = geoNode.Vertices !== undefined ? geoNode.Vertices.a : [];
  992. geoInfo.vertexIndices = geoNode.PolygonVertexIndex !== undefined ? geoNode.PolygonVertexIndex.a : [];
  993. if (geoNode.LayerElementColor) {
  994. geoInfo.color = this.parseVertexColors(geoNode.LayerElementColor[0]);
  995. }
  996. if (geoNode.LayerElementMaterial) {
  997. geoInfo.material = this.parseMaterialIndices(geoNode.LayerElementMaterial[0]);
  998. }
  999. if (geoNode.LayerElementNormal) {
  1000. geoInfo.normal = this.parseNormals(geoNode.LayerElementNormal[0]);
  1001. }
  1002. if (geoNode.LayerElementUV) {
  1003. geoInfo.uv = [];
  1004. var i = 0;
  1005. while (geoNode.LayerElementUV[i]) {
  1006. geoInfo.uv.push(this.parseUVs(geoNode.LayerElementUV[i]));
  1007. i++;
  1008. }
  1009. }
  1010. geoInfo.weightTable = {};
  1011. if (skeleton !== null) {
  1012. geoInfo.skeleton = skeleton;
  1013. skeleton.rawBones.forEach(function (rawBone, i) {
  1014. // loop over the bone's vertex indices and weights
  1015. rawBone.indices.forEach(function (index, j) {
  1016. if (geoInfo.weightTable[index] === undefined) geoInfo.weightTable[index] = [];
  1017. geoInfo.weightTable[index].push({
  1018. id: i,
  1019. weight: rawBone.weights[j]
  1020. });
  1021. });
  1022. });
  1023. }
  1024. return geoInfo;
  1025. },
  1026. genBuffers: function genBuffers(geoInfo) {
  1027. var buffers = {
  1028. vertex: [],
  1029. normal: [],
  1030. colors: [],
  1031. uvs: [],
  1032. materialIndex: [],
  1033. vertexWeights: [],
  1034. weightsIndices: []
  1035. };
  1036. var polygonIndex = 0;
  1037. var faceLength = 0;
  1038. var displayedWeightsWarning = false;
  1039. // these will hold data for a single face
  1040. var facePositionIndexes = [];
  1041. var faceNormals = [];
  1042. var faceColors = [];
  1043. var faceUVs = [];
  1044. var faceWeights = [];
  1045. var faceWeightIndices = [];
  1046. var self = this;
  1047. geoInfo.vertexIndices.forEach(function (vertexIndex, polygonVertexIndex) {
  1048. var endOfFace = false;
  1049. // Face index and vertex index arrays are combined in a single array
  1050. // A cube with quad faces looks like this:
  1051. // PolygonVertexIndex: *24 {
  1052. // a: 0, 1, 3, -3, 2, 3, 5, -5, 4, 5, 7, -7, 6, 7, 1, -1, 1, 7, 5, -4, 6, 0, 2, -5
  1053. // }
  1054. // Negative numbers mark the end of a face - first face here is 0, 1, 3, -3
  1055. // to find index of last vertex bit shift the index: ^ - 1
  1056. if (vertexIndex < 0) {
  1057. vertexIndex = vertexIndex ^ -1; // equivalent to ( x * -1 ) - 1
  1058. endOfFace = true;
  1059. }
  1060. var weightIndices = [];
  1061. var weights = [];
  1062. facePositionIndexes.push(vertexIndex * 3, vertexIndex * 3 + 1, vertexIndex * 3 + 2);
  1063. if (geoInfo.color) {
  1064. var data = getData(polygonVertexIndex, polygonIndex, vertexIndex, geoInfo.color);
  1065. faceColors.push(data[0], data[1], data[2]);
  1066. }
  1067. if (geoInfo.skeleton) {
  1068. if (geoInfo.weightTable[vertexIndex] !== undefined) {
  1069. geoInfo.weightTable[vertexIndex].forEach(function (wt) {
  1070. weights.push(wt.weight);
  1071. weightIndices.push(wt.id);
  1072. });
  1073. }
  1074. if (weights.length > 4) {
  1075. if (!displayedWeightsWarning) {
  1076. console.warn('THREE.FBXLoader: Vertex has more than 4 skinning weights assigned to vertex. Deleting additional weights.');
  1077. displayedWeightsWarning = true;
  1078. }
  1079. var wIndex = [0, 0, 0, 0];
  1080. var Weight = [0, 0, 0, 0];
  1081. weights.forEach(function (weight, weightIndex) {
  1082. var currentWeight = weight;
  1083. var currentIndex = weightIndices[weightIndex];
  1084. Weight.forEach(function (comparedWeight, comparedWeightIndex, comparedWeightArray) {
  1085. if (currentWeight > comparedWeight) {
  1086. comparedWeightArray[comparedWeightIndex] = currentWeight;
  1087. currentWeight = comparedWeight;
  1088. var tmp = wIndex[comparedWeightIndex];
  1089. wIndex[comparedWeightIndex] = currentIndex;
  1090. currentIndex = tmp;
  1091. }
  1092. });
  1093. });
  1094. weightIndices = wIndex;
  1095. weights = Weight;
  1096. }
  1097. // if the weight array is shorter than 4 pad with 0s
  1098. while (weights.length < 4) {
  1099. weights.push(0);
  1100. weightIndices.push(0);
  1101. }
  1102. for (var i = 0; i < 4; ++i) {
  1103. faceWeights.push(weights[i]);
  1104. faceWeightIndices.push(weightIndices[i]);
  1105. }
  1106. }
  1107. if (geoInfo.normal) {
  1108. var data = getData(polygonVertexIndex, polygonIndex, vertexIndex, geoInfo.normal);
  1109. faceNormals.push(data[0], data[1], data[2]);
  1110. }
  1111. if (geoInfo.material && geoInfo.material.mappingType !== 'AllSame') {
  1112. var materialIndex = getData(polygonVertexIndex, polygonIndex, vertexIndex, geoInfo.material)[0];
  1113. }
  1114. if (geoInfo.uv) {
  1115. geoInfo.uv.forEach(function (uv, i) {
  1116. var data = getData(polygonVertexIndex, polygonIndex, vertexIndex, uv);
  1117. if (faceUVs[i] === undefined) {
  1118. faceUVs[i] = [];
  1119. }
  1120. faceUVs[i].push(data[0]);
  1121. faceUVs[i].push(data[1]);
  1122. });
  1123. }
  1124. faceLength++;
  1125. if (endOfFace) {
  1126. self.genFace(buffers, geoInfo, facePositionIndexes, materialIndex, faceNormals, faceColors, faceUVs, faceWeights, faceWeightIndices, faceLength);
  1127. polygonIndex++;
  1128. faceLength = 0;
  1129. // reset arrays for the next face
  1130. facePositionIndexes = [];
  1131. faceNormals = [];
  1132. faceColors = [];
  1133. faceUVs = [];
  1134. faceWeights = [];
  1135. faceWeightIndices = [];
  1136. }
  1137. });
  1138. return buffers;
  1139. },
  1140. // Generate data for a single face in a geometry. If the face is a quad then split it into 2 tris
  1141. genFace: function genFace(buffers, geoInfo, facePositionIndexes, materialIndex, faceNormals, faceColors, faceUVs, faceWeights, faceWeightIndices, faceLength) {
  1142. for (var i = 2; i < faceLength; i++) {
  1143. buffers.vertex.push(geoInfo.vertexPositions[facePositionIndexes[0]]);
  1144. buffers.vertex.push(geoInfo.vertexPositions[facePositionIndexes[1]]);
  1145. buffers.vertex.push(geoInfo.vertexPositions[facePositionIndexes[2]]);
  1146. buffers.vertex.push(geoInfo.vertexPositions[facePositionIndexes[(i - 1) * 3]]);
  1147. buffers.vertex.push(geoInfo.vertexPositions[facePositionIndexes[(i - 1) * 3 + 1]]);
  1148. buffers.vertex.push(geoInfo.vertexPositions[facePositionIndexes[(i - 1) * 3 + 2]]);
  1149. buffers.vertex.push(geoInfo.vertexPositions[facePositionIndexes[i * 3]]);
  1150. buffers.vertex.push(geoInfo.vertexPositions[facePositionIndexes[i * 3 + 1]]);
  1151. buffers.vertex.push(geoInfo.vertexPositions[facePositionIndexes[i * 3 + 2]]);
  1152. if (geoInfo.skeleton) {
  1153. buffers.vertexWeights.push(faceWeights[0]);
  1154. buffers.vertexWeights.push(faceWeights[1]);
  1155. buffers.vertexWeights.push(faceWeights[2]);
  1156. buffers.vertexWeights.push(faceWeights[3]);
  1157. buffers.vertexWeights.push(faceWeights[(i - 1) * 4]);
  1158. buffers.vertexWeights.push(faceWeights[(i - 1) * 4 + 1]);
  1159. buffers.vertexWeights.push(faceWeights[(i - 1) * 4 + 2]);
  1160. buffers.vertexWeights.push(faceWeights[(i - 1) * 4 + 3]);
  1161. buffers.vertexWeights.push(faceWeights[i * 4]);
  1162. buffers.vertexWeights.push(faceWeights[i * 4 + 1]);
  1163. buffers.vertexWeights.push(faceWeights[i * 4 + 2]);
  1164. buffers.vertexWeights.push(faceWeights[i * 4 + 3]);
  1165. buffers.weightsIndices.push(faceWeightIndices[0]);
  1166. buffers.weightsIndices.push(faceWeightIndices[1]);
  1167. buffers.weightsIndices.push(faceWeightIndices[2]);
  1168. buffers.weightsIndices.push(faceWeightIndices[3]);
  1169. buffers.weightsIndices.push(faceWeightIndices[(i - 1) * 4]);
  1170. buffers.weightsIndices.push(faceWeightIndices[(i - 1) * 4 + 1]);
  1171. buffers.weightsIndices.push(faceWeightIndices[(i - 1) * 4 + 2]);
  1172. buffers.weightsIndices.push(faceWeightIndices[(i - 1) * 4 + 3]);
  1173. buffers.weightsIndices.push(faceWeightIndices[i * 4]);
  1174. buffers.weightsIndices.push(faceWeightIndices[i * 4 + 1]);
  1175. buffers.weightsIndices.push(faceWeightIndices[i * 4 + 2]);
  1176. buffers.weightsIndices.push(faceWeightIndices[i * 4 + 3]);
  1177. }
  1178. if (geoInfo.color) {
  1179. buffers.colors.push(faceColors[0]);
  1180. buffers.colors.push(faceColors[1]);
  1181. buffers.colors.push(faceColors[2]);
  1182. buffers.colors.push(faceColors[(i - 1) * 3]);
  1183. buffers.colors.push(faceColors[(i - 1) * 3 + 1]);
  1184. buffers.colors.push(faceColors[(i - 1) * 3 + 2]);
  1185. buffers.colors.push(faceColors[i * 3]);
  1186. buffers.colors.push(faceColors[i * 3 + 1]);
  1187. buffers.colors.push(faceColors[i * 3 + 2]);
  1188. }
  1189. if (geoInfo.material && geoInfo.material.mappingType !== 'AllSame') {
  1190. buffers.materialIndex.push(materialIndex);
  1191. buffers.materialIndex.push(materialIndex);
  1192. buffers.materialIndex.push(materialIndex);
  1193. }
  1194. if (geoInfo.normal) {
  1195. buffers.normal.push(faceNormals[0]);
  1196. buffers.normal.push(faceNormals[1]);
  1197. buffers.normal.push(faceNormals[2]);
  1198. buffers.normal.push(faceNormals[(i - 1) * 3]);
  1199. buffers.normal.push(faceNormals[(i - 1) * 3 + 1]);
  1200. buffers.normal.push(faceNormals[(i - 1) * 3 + 2]);
  1201. buffers.normal.push(faceNormals[i * 3]);
  1202. buffers.normal.push(faceNormals[i * 3 + 1]);
  1203. buffers.normal.push(faceNormals[i * 3 + 2]);
  1204. }
  1205. if (geoInfo.uv) {
  1206. geoInfo.uv.forEach(function (uv, j) {
  1207. if (buffers.uvs[j] === undefined) buffers.uvs[j] = [];
  1208. buffers.uvs[j].push(faceUVs[j][0]);
  1209. buffers.uvs[j].push(faceUVs[j][1]);
  1210. buffers.uvs[j].push(faceUVs[j][(i - 1) * 2]);
  1211. buffers.uvs[j].push(faceUVs[j][(i - 1) * 2 + 1]);
  1212. buffers.uvs[j].push(faceUVs[j][i * 2]);
  1213. buffers.uvs[j].push(faceUVs[j][i * 2 + 1]);
  1214. });
  1215. }
  1216. }
  1217. },
  1218. addMorphTargets: function addMorphTargets(parentGeo, parentGeoNode, morphTarget, preTransform) {
  1219. if (morphTarget === null) return;
  1220. parentGeo.morphAttributes.position = [];
  1221. parentGeo.morphAttributes.normal = [];
  1222. var self = this;
  1223. morphTarget.rawTargets.forEach(function (rawTarget) {
  1224. var morphGeoNode = fbxTree.Objects.Geometry[rawTarget.geoID];
  1225. if (morphGeoNode !== undefined) {
  1226. self.genMorphGeometry(parentGeo, parentGeoNode, morphGeoNode, preTransform);
  1227. }
  1228. });
  1229. },
  1230. // a morph geometry node is similar to a standard node, and the node is also contained
  1231. // in FBXTree.Objects.Geometry, however it can only have attributes for position, normal
  1232. // and a special attribute Index defining which vertices of the original geometry are affected
  1233. // Normal and position attributes only have data for the vertices that are affected by the morph
  1234. genMorphGeometry: function genMorphGeometry(parentGeo, parentGeoNode, morphGeoNode, preTransform) {
  1235. var morphGeo = new THREE.BufferGeometry();
  1236. if (morphGeoNode.attrName) morphGeo.name = morphGeoNode.attrName;
  1237. var vertexIndices = parentGeoNode.PolygonVertexIndex !== undefined ? parentGeoNode.PolygonVertexIndex.a : [];
  1238. // make a copy of the parent's vertex positions
  1239. var vertexPositions = parentGeoNode.Vertices !== undefined ? parentGeoNode.Vertices.a.slice() : [];
  1240. var morphPositions = morphGeoNode.Vertices !== undefined ? morphGeoNode.Vertices.a : [];
  1241. var indices = morphGeoNode.Indexes !== undefined ? morphGeoNode.Indexes.a : [];
  1242. for (var i = 0; i < indices.length; i++) {
  1243. var morphIndex = indices[i] * 3;
  1244. // FBX format uses blend shapes rather than morph targets. This can be converted
  1245. // by additively combining the blend shape positions with the original geometry's positions
  1246. vertexPositions[morphIndex] += morphPositions[i * 3];
  1247. vertexPositions[morphIndex + 1] += morphPositions[i * 3 + 1];
  1248. vertexPositions[morphIndex + 2] += morphPositions[i * 3 + 2];
  1249. }
  1250. // TODO: add morph normal support
  1251. var morphGeoInfo = {
  1252. vertexIndices: vertexIndices,
  1253. vertexPositions: vertexPositions
  1254. };
  1255. var morphBuffers = this.genBuffers(morphGeoInfo);
  1256. var positionAttribute = new THREE.Float32BufferAttribute(morphBuffers.vertex, 3);
  1257. positionAttribute.name = morphGeoNode.attrName;
  1258. preTransform.applyToBufferAttribute(positionAttribute);
  1259. parentGeo.morphAttributes.position.push(positionAttribute);
  1260. },
  1261. // Parse normal from FBXTree.Objects.Geometry.LayerElementNormal if it exists
  1262. parseNormals: function parseNormals(NormalNode) {
  1263. var mappingType = NormalNode.MappingInformationType;
  1264. var referenceType = NormalNode.ReferenceInformationType;
  1265. var buffer = NormalNode.Normals.a;
  1266. var indexBuffer = [];
  1267. if (referenceType === 'IndexToDirect') {
  1268. if ('NormalIndex' in NormalNode) {
  1269. indexBuffer = NormalNode.NormalIndex.a;
  1270. } else if ('NormalsIndex' in NormalNode) {
  1271. indexBuffer = NormalNode.NormalsIndex.a;
  1272. }
  1273. }
  1274. return {
  1275. dataSize: 3,
  1276. buffer: buffer,
  1277. indices: indexBuffer,
  1278. mappingType: mappingType,
  1279. referenceType: referenceType
  1280. };
  1281. },
  1282. // Parse UVs from FBXTree.Objects.Geometry.LayerElementUV if it exists
  1283. parseUVs: function parseUVs(UVNode) {
  1284. var mappingType = UVNode.MappingInformationType;
  1285. var referenceType = UVNode.ReferenceInformationType;
  1286. var buffer = UVNode.UV.a;
  1287. var indexBuffer = [];
  1288. if (referenceType === 'IndexToDirect') {
  1289. indexBuffer = UVNode.UVIndex.a;
  1290. }
  1291. return {
  1292. dataSize: 2,
  1293. buffer: buffer,
  1294. indices: indexBuffer,
  1295. mappingType: mappingType,
  1296. referenceType: referenceType
  1297. };
  1298. },
  1299. // Parse Vertex Colors from FBXTree.Objects.Geometry.LayerElementColor if it exists
  1300. parseVertexColors: function parseVertexColors(ColorNode) {
  1301. var mappingType = ColorNode.MappingInformationType;
  1302. var referenceType = ColorNode.ReferenceInformationType;
  1303. var buffer = ColorNode.Colors.a;
  1304. var indexBuffer = [];
  1305. if (referenceType === 'IndexToDirect') {
  1306. indexBuffer = ColorNode.ColorIndex.a;
  1307. }
  1308. return {
  1309. dataSize: 4,
  1310. buffer: buffer,
  1311. indices: indexBuffer,
  1312. mappingType: mappingType,
  1313. referenceType: referenceType
  1314. };
  1315. },
  1316. // Parse mapping and material data in FBXTree.Objects.Geometry.LayerElementMaterial if it exists
  1317. parseMaterialIndices: function parseMaterialIndices(MaterialNode) {
  1318. var mappingType = MaterialNode.MappingInformationType;
  1319. var referenceType = MaterialNode.ReferenceInformationType;
  1320. if (mappingType === 'NoMappingInformation') {
  1321. return {
  1322. dataSize: 1,
  1323. buffer: [0],
  1324. indices: [0],
  1325. mappingType: 'AllSame',
  1326. referenceType: referenceType
  1327. };
  1328. }
  1329. var materialIndexBuffer = MaterialNode.Materials.a;
  1330. // Since materials are stored as indices, there's a bit of a mismatch between FBX and what
  1331. // we expect.So we create an intermediate buffer that points to the index in the buffer,
  1332. // for conforming with the other functions we've written for other data.
  1333. var materialIndices = [];
  1334. for (var i = 0; i < materialIndexBuffer.length; ++i) {
  1335. materialIndices.push(i);
  1336. }
  1337. return {
  1338. dataSize: 1,
  1339. buffer: materialIndexBuffer,
  1340. indices: materialIndices,
  1341. mappingType: mappingType,
  1342. referenceType: referenceType
  1343. };
  1344. },
  1345. // Generate a NurbGeometry from a node in FBXTree.Objects.Geometry
  1346. parseNurbsGeometry: function parseNurbsGeometry(geoNode) {
  1347. if (THREE.NURBSCurve === undefined) {
  1348. console.error('THREE.FBXLoader: The loader relies on THREE.NURBSCurve for any nurbs present in the model. Nurbs will show up as empty geometry.');
  1349. return new THREE.BufferGeometry();
  1350. }
  1351. var order = parseInt(geoNode.Order);
  1352. if (isNaN(order)) {
  1353. console.error('THREE.FBXLoader: Invalid Order %s given for geometry ID: %s', geoNode.Order, geoNode.id);
  1354. return new THREE.BufferGeometry();
  1355. }
  1356. var degree = order - 1;
  1357. var knots = geoNode.KnotVector.a;
  1358. var controlPoints = [];
  1359. var pointsValues = geoNode.Points.a;
  1360. for (var i = 0, l = pointsValues.length; i < l; i += 4) {
  1361. controlPoints.push(new THREE.Vector4().fromArray(pointsValues, i));
  1362. }
  1363. var startKnot, endKnot;
  1364. if (geoNode.Form === 'Closed') {
  1365. controlPoints.push(controlPoints[0]);
  1366. } else if (geoNode.Form === 'Periodic') {
  1367. startKnot = degree;
  1368. endKnot = knots.length - 1 - startKnot;
  1369. for (var i = 0; i < degree; ++i) {
  1370. controlPoints.push(controlPoints[i]);
  1371. }
  1372. }
  1373. var curve = new THREE.NURBSCurve(degree, knots, controlPoints, startKnot, endKnot);
  1374. var vertices = curve.getPoints(controlPoints.length * 7);
  1375. var positions = new Float32Array(vertices.length * 3);
  1376. vertices.forEach(function (vertex, i) {
  1377. vertex.toArray(positions, i * 3);
  1378. });
  1379. var geometry = new THREE.BufferGeometry();
  1380. geometry.addAttribute('position', new THREE.BufferAttribute(positions, 3));
  1381. return geometry;
  1382. }
  1383. };
  1384. // parse animation data from FBXTree
  1385. function AnimationParser() {}
  1386. AnimationParser.prototype = {
  1387. constructor: AnimationParser,
  1388. // take raw animation clips and turn them into three.js animation clips
  1389. parse: function parse() {
  1390. var animationClips = [];
  1391. var rawClips = this.parseClips();
  1392. if (rawClips === undefined) return animationClips;
  1393. for (var key in rawClips) {
  1394. var rawClip = rawClips[key];
  1395. var clip = this.addClip(rawClip);
  1396. animationClips.push(clip);
  1397. }
  1398. return animationClips;
  1399. },
  1400. parseClips: function parseClips() {
  1401. // since the actual transformation data is stored in FBXTree.Objects.AnimationCurve,
  1402. // if this is undefined we can safely assume there are no animations
  1403. if (fbxTree.Objects.AnimationCurve === undefined) return undefined;
  1404. var curveNodesMap = this.parseAnimationCurveNodes();
  1405. this.parseAnimationCurves(curveNodesMap);
  1406. var layersMap = this.parseAnimationLayers(curveNodesMap);
  1407. var rawClips = this.parseAnimStacks(layersMap);
  1408. return rawClips;
  1409. },
  1410. // parse nodes in FBXTree.Objects.AnimationCurveNode
  1411. // each AnimationCurveNode holds data for an animation transform for a model (e.g. left arm rotation )
  1412. // and is referenced by an AnimationLayer
  1413. parseAnimationCurveNodes: function parseAnimationCurveNodes() {
  1414. var rawCurveNodes = fbxTree.Objects.AnimationCurveNode;
  1415. var curveNodesMap = new Map();
  1416. for (var nodeID in rawCurveNodes) {
  1417. var rawCurveNode = rawCurveNodes[nodeID];
  1418. if (rawCurveNode.attrName.match(/S|R|T|DeformPercent/) !== null) {
  1419. var curveNode = {
  1420. id: rawCurveNode.id,
  1421. attr: rawCurveNode.attrName,
  1422. curves: {}
  1423. };
  1424. curveNodesMap.set(curveNode.id, curveNode);
  1425. }
  1426. }
  1427. return curveNodesMap;
  1428. },
  1429. // parse nodes in FBXTree.Objects.AnimationCurve and connect them up to
  1430. // previously parsed AnimationCurveNodes. Each AnimationCurve holds data for a single animated
  1431. // axis ( e.g. times and values of x rotation)
  1432. parseAnimationCurves: function parseAnimationCurves(curveNodesMap) {
  1433. var rawCurves = fbxTree.Objects.AnimationCurve;
  1434. // TODO: Many values are identical up to roundoff error, but won't be optimised
  1435. // e.g. position times: [0, 0.4, 0. 8]
  1436. // position values: [7.23538335023477e-7, 93.67518615722656, -0.9982695579528809, 7.23538335023477e-7, 93.67518615722656, -0.9982695579528809, 7.235384487103147e-7, 93.67520904541016, -0.9982695579528809]
  1437. // clearly, this should be optimised to
  1438. // times: [0], positions [7.23538335023477e-7, 93.67518615722656, -0.9982695579528809]
  1439. // this shows up in nearly every FBX file, and generally time array is length > 100
  1440. for (var nodeID in rawCurves) {
  1441. var animationCurve = {
  1442. id: rawCurves[nodeID].id,
  1443. times: rawCurves[nodeID].KeyTime.a.map(convertFBXTimeToSeconds),
  1444. values: rawCurves[nodeID].KeyValueFloat.a
  1445. };
  1446. var relationships = connections.get(animationCurve.id);
  1447. if (relationships !== undefined) {
  1448. var animationCurveID = relationships.parents[0].ID;
  1449. var animationCurveRelationship = relationships.parents[0].relationship;
  1450. if (animationCurveRelationship.match(/X/)) {
  1451. curveNodesMap.get(animationCurveID).curves['x'] = animationCurve;
  1452. } else if (animationCurveRelationship.match(/Y/)) {
  1453. curveNodesMap.get(animationCurveID).curves['y'] = animationCurve;
  1454. } else if (animationCurveRelationship.match(/Z/)) {
  1455. curveNodesMap.get(animationCurveID).curves['z'] = animationCurve;
  1456. } else if (animationCurveRelationship.match(/d|DeformPercent/) && curveNodesMap.has(animationCurveID)) {
  1457. curveNodesMap.get(animationCurveID).curves['morph'] = animationCurve;
  1458. }
  1459. }
  1460. }
  1461. },
  1462. // parse nodes in FBXTree.Objects.AnimationLayer. Each layers holds references
  1463. // to various AnimationCurveNodes and is referenced by an AnimationStack node
  1464. // note: theoretically a stack can have multiple layers, however in practice there always seems to be one per stack
  1465. parseAnimationLayers: function parseAnimationLayers(curveNodesMap) {
  1466. var rawLayers = fbxTree.Objects.AnimationLayer;
  1467. var layersMap = new Map();
  1468. for (var nodeID in rawLayers) {
  1469. var layerCurveNodes = [];
  1470. var connection = connections.get(parseInt(nodeID));
  1471. if (connection !== undefined) {
  1472. // all the animationCurveNodes used in the layer
  1473. var children = connection.children;
  1474. var self = this;
  1475. children.forEach(function (child, i) {
  1476. if (curveNodesMap.has(child.ID)) {
  1477. var curveNode = curveNodesMap.get(child.ID);
  1478. // check that the curves are defined for at least one axis, otherwise ignore the curveNode
  1479. if (curveNode.curves.x !== undefined || curveNode.curves.y !== undefined || curveNode.curves.z !== undefined) {
  1480. if (layerCurveNodes[i] === undefined) {
  1481. var modelID;
  1482. connections.get(child.ID).parents.forEach(function (parent) {
  1483. if (parent.relationship !== undefined) modelID = parent.ID;
  1484. });
  1485. var rawModel = fbxTree.Objects.Model[modelID.toString()];
  1486. var node = {
  1487. modelName: THREE.PropertyBinding.sanitizeNodeName(rawModel.attrName),
  1488. initialPosition: [0, 0, 0],
  1489. initialRotation: [0, 0, 0],
  1490. initialScale: [1, 1, 1],
  1491. transform: self.getModelAnimTransform(rawModel)
  1492. };
  1493. // if the animated model is pre rotated, we'll have to apply the pre rotations to every
  1494. // animation value as well
  1495. if ('PreRotation' in rawModel) node.preRotations = rawModel.PreRotation.value;
  1496. if ('PostRotation' in rawModel) node.postRotations = rawModel.PostRotation.value;
  1497. layerCurveNodes[i] = node;
  1498. }
  1499. layerCurveNodes[i][curveNode.attr] = curveNode;
  1500. } else if (curveNode.curves.morph !== undefined) {
  1501. if (layerCurveNodes[i] === undefined) {
  1502. var deformerID;
  1503. connections.get(child.ID).parents.forEach(function (parent) {
  1504. if (parent.relationship !== undefined) deformerID = parent.ID;
  1505. });
  1506. var morpherID = connections.get(deformerID).parents[0].ID;
  1507. var geoID = connections.get(morpherID).parents[0].ID;
  1508. // assuming geometry is not used in more than one model
  1509. var modelID = connections.get(geoID).parents[0].ID;
  1510. var rawModel = fbxTree.Objects.Model[modelID];
  1511. var node = {
  1512. modelName: THREE.PropertyBinding.sanitizeNodeName(rawModel.attrName),
  1513. morphName: fbxTree.Objects.Deformer[deformerID].attrName
  1514. };
  1515. layerCurveNodes[i] = node;
  1516. }
  1517. layerCurveNodes[i][curveNode.attr] = curveNode;
  1518. }
  1519. }
  1520. });
  1521. layersMap.set(parseInt(nodeID), layerCurveNodes);
  1522. }
  1523. }
  1524. return layersMap;
  1525. },
  1526. getModelAnimTransform: function getModelAnimTransform(modelNode) {
  1527. var transformData = {};
  1528. if ('RotationOrder' in modelNode) transformData.eulerOrder = parseInt(modelNode.RotationOrder.value);
  1529. if ('Lcl_Translation' in modelNode) transformData.translation = modelNode.Lcl_Translation.value;
  1530. if ('RotationOffset' in modelNode) transformData.rotationOffset = modelNode.RotationOffset.value;
  1531. if ('Lcl_Rotation' in modelNode) transformData.rotation = modelNode.Lcl_Rotation.value;
  1532. if ('PreRotation' in modelNode) transformData.preRotation = modelNode.PreRotation.value;
  1533. if ('PostRotation' in modelNode) transformData.postRotation = modelNode.PostRotation.value;
  1534. if ('Lcl_Scaling' in modelNode) transformData.scale = modelNode.Lcl_Scaling.value;
  1535. return generateTransform(transformData);
  1536. },
  1537. // parse nodes in FBXTree.Objects.AnimationStack. These are the top level node in the animation
  1538. // hierarchy. Each Stack node will be used to create a THREE.AnimationClip
  1539. parseAnimStacks: function parseAnimStacks(layersMap) {
  1540. var rawStacks = fbxTree.Objects.AnimationStack;
  1541. // connect the stacks (clips) up to the layers
  1542. var rawClips = {};
  1543. for (var nodeID in rawStacks) {
  1544. var children = connections.get(parseInt(nodeID)).children;
  1545. if (children.length > 1) {
  1546. // it seems like stacks will always be associated with a single layer. But just in case there are files
  1547. // where there are multiple layers per stack, we'll display a warning
  1548. console.warn('THREE.FBXLoader: Encountered an animation stack with multiple layers, this is currently not supported. Ignoring subsequent layers.');
  1549. }
  1550. var layer = layersMap.get(children[0].ID);
  1551. rawClips[nodeID] = {
  1552. name: rawStacks[nodeID].attrName,
  1553. layer: layer
  1554. };
  1555. }
  1556. return rawClips;
  1557. },
  1558. addClip: function addClip(rawClip) {
  1559. var tracks = [];
  1560. var self = this;
  1561. rawClip.layer.forEach(function (rawTracks) {
  1562. tracks = tracks.concat(self.generateTracks(rawTracks));
  1563. });
  1564. return new THREE.AnimationClip(rawClip.name, -1, tracks);
  1565. },
  1566. generateTracks: function generateTracks(rawTracks) {
  1567. var tracks = [];
  1568. var initialPosition = new THREE.Vector3();
  1569. var initialRotation = new THREE.Quaternion();
  1570. var initialScale = new THREE.Vector3();
  1571. if (rawTracks.transform) rawTracks.transform.decompose(initialPosition, initialRotation, initialScale);
  1572. initialPosition = initialPosition.toArray();
  1573. initialRotation = new THREE.Euler().setFromQuaternion(initialRotation).toArray(); // todo: euler order
  1574. initialScale = initialScale.toArray();
  1575. if (rawTracks.T !== undefined && Object.keys(rawTracks.T.curves).length > 0) {
  1576. var positionTrack = this.generateVectorTrack(rawTracks.modelName, rawTracks.T.curves, initialPosition, 'position');
  1577. if (positionTrack !== undefined) tracks.push(positionTrack);
  1578. }
  1579. if (rawTracks.R !== undefined && Object.keys(rawTracks.R.curves).length > 0) {
  1580. var rotationTrack = this.generateRotationTrack(rawTracks.modelName, rawTracks.R.curves, initialRotation, rawTracks.preRotations, rawTracks.postRotations);
  1581. if (rotationTrack !== undefined) tracks.push(rotationTrack);
  1582. }
  1583. if (rawTracks.S !== undefined && Object.keys(rawTracks.S.curves).length > 0) {
  1584. var scaleTrack = this.generateVectorTrack(rawTracks.modelName, rawTracks.S.curves, initialScale, 'scale');
  1585. if (scaleTrack !== undefined) tracks.push(scaleTrack);
  1586. }
  1587. if (rawTracks.DeformPercent !== undefined) {
  1588. var morphTrack = this.generateMorphTrack(rawTracks);
  1589. if (morphTrack !== undefined) tracks.push(morphTrack);
  1590. }
  1591. return tracks;
  1592. },
  1593. generateVectorTrack: function generateVectorTrack(modelName, curves, initialValue, type) {
  1594. var times = this.getTimesForAllAxes(curves);
  1595. var values = this.getKeyframeTrackValues(times, curves, initialValue);
  1596. return new THREE.VectorKeyframeTrack(modelName + '.' + type, times, values);
  1597. },
  1598. generateRotationTrack: function generateRotationTrack(modelName, curves, initialValue, preRotations, postRotations) {
  1599. if (curves.x !== undefined) {
  1600. this.interpolateRotations(curves.x);
  1601. curves.x.values = curves.x.values.map(THREE.Math.degToRad);
  1602. }
  1603. if (curves.y !== undefined) {
  1604. this.interpolateRotations(curves.y);
  1605. curves.y.values = curves.y.values.map(THREE.Math.degToRad);
  1606. }
  1607. if (curves.z !== undefined) {
  1608. this.interpolateRotations(curves.z);
  1609. curves.z.values = curves.z.values.map(THREE.Math.degToRad);
  1610. }
  1611. var times = this.getTimesForAllAxes(curves);
  1612. var values = this.getKeyframeTrackValues(times, curves, initialValue);
  1613. if (preRotations !== undefined) {
  1614. preRotations = preRotations.map(THREE.Math.degToRad);
  1615. preRotations.push('ZYX');
  1616. preRotations = new THREE.Euler().fromArray(preRotations);
  1617. preRotations = new THREE.Quaternion().setFromEuler(preRotations);
  1618. }
  1619. if (postRotations !== undefined) {
  1620. postRotations = postRotations.map(THREE.Math.degToRad);
  1621. postRotations.push('ZYX');
  1622. postRotations = new THREE.Euler().fromArray(postRotations);
  1623. postRotations = new THREE.Quaternion().setFromEuler(postRotations).inverse();
  1624. }
  1625. var quaternion = new THREE.Quaternion();
  1626. var euler = new THREE.Euler();
  1627. var quaternionValues = [];
  1628. for (var i = 0; i < values.length; i += 3) {
  1629. euler.set(values[i], values[i + 1], values[i + 2], 'ZYX');
  1630. quaternion.setFromEuler(euler);
  1631. if (preRotations !== undefined) quaternion.premultiply(preRotations);
  1632. if (postRotations !== undefined) quaternion.multiply(postRotations);
  1633. quaternion.toArray(quaternionValues, i / 3 * 4);
  1634. }
  1635. return new THREE.QuaternionKeyframeTrack(modelName + '.quaternion', times, quaternionValues);
  1636. },
  1637. generateMorphTrack: function generateMorphTrack(rawTracks) {
  1638. var curves = rawTracks.DeformPercent.curves.morph;
  1639. var values = curves.values.map(function (val) {
  1640. return val / 100;
  1641. });
  1642. var morphNum = sceneGraph.getObjectByName(rawTracks.modelName).morphTargetDictionary[rawTracks.morphName];
  1643. return new THREE.NumberKeyframeTrack(rawTracks.modelName + '.morphTargetInfluences[' + morphNum + ']', curves.times, values);
  1644. },
  1645. // For all animated objects, times are defined separately for each axis
  1646. // Here we'll combine the times into one sorted array without duplicates
  1647. getTimesForAllAxes: function getTimesForAllAxes(curves) {
  1648. var times = [];
  1649. // first join together the times for each axis, if defined
  1650. if (curves.x !== undefined) times = times.concat(curves.x.times);
  1651. if (curves.y !== undefined) times = times.concat(curves.y.times);
  1652. if (curves.z !== undefined) times = times.concat(curves.z.times);
  1653. // then sort them and remove duplicates
  1654. times = times.sort(function (a, b) {
  1655. return a - b;
  1656. }).filter(function (elem, index, array) {
  1657. return array.indexOf(elem) == index;
  1658. });
  1659. return times;
  1660. },
  1661. getKeyframeTrackValues: function getKeyframeTrackValues(times, curves, initialValue) {
  1662. var prevValue = initialValue;
  1663. var values = [];
  1664. var xIndex = -1;
  1665. var yIndex = -1;
  1666. var zIndex = -1;
  1667. times.forEach(function (time) {
  1668. if (curves.x) xIndex = curves.x.times.indexOf(time);
  1669. if (curves.y) yIndex = curves.y.times.indexOf(time);
  1670. if (curves.z) zIndex = curves.z.times.indexOf(time);
  1671. // if there is an x value defined for this frame, use that
  1672. if (xIndex !== -1) {
  1673. var xValue = curves.x.values[xIndex];
  1674. values.push(xValue);
  1675. prevValue[0] = xValue;
  1676. } else {
  1677. // otherwise use the x value from the previous frame
  1678. values.push(prevValue[0]);
  1679. }
  1680. if (yIndex !== -1) {
  1681. var yValue = curves.y.values[yIndex];
  1682. values.push(yValue);
  1683. prevValue[1] = yValue;
  1684. } else {
  1685. values.push(prevValue[1]);
  1686. }
  1687. if (zIndex !== -1) {
  1688. var zValue = curves.z.values[zIndex];
  1689. values.push(zValue);
  1690. prevValue[2] = zValue;
  1691. } else {
  1692. values.push(prevValue[2]);
  1693. }
  1694. });
  1695. return values;
  1696. },
  1697. // Rotations are defined as Euler angles which can have values of any size
  1698. // These will be converted to quaternions which don't support values greater than
  1699. // PI, so we'll interpolate large rotations
  1700. interpolateRotations: function interpolateRotations(curve) {
  1701. for (var i = 1; i < curve.values.length; i++) {
  1702. var initialValue = curve.values[i - 1];
  1703. var valuesSpan = curve.values[i] - initialValue;
  1704. var absoluteSpan = Math.abs(valuesSpan);
  1705. if (absoluteSpan >= 180) {
  1706. var numSubIntervals = absoluteSpan / 180;
  1707. var step = valuesSpan / numSubIntervals;
  1708. var nextValue = initialValue + step;
  1709. var initialTime = curve.times[i - 1];
  1710. var timeSpan = curve.times[i] - initialTime;
  1711. var interval = timeSpan / numSubIntervals;
  1712. var nextTime = initialTime + interval;
  1713. var interpolatedTimes = [];
  1714. var interpolatedValues = [];
  1715. while (nextTime < curve.times[i]) {
  1716. interpolatedTimes.push(nextTime);
  1717. nextTime += interval;
  1718. interpolatedValues.push(nextValue);
  1719. nextValue += step;
  1720. }
  1721. curve.times = inject(curve.times, i, interpolatedTimes);
  1722. curve.values = inject(curve.values, i, interpolatedValues);
  1723. }
  1724. }
  1725. }
  1726. };
  1727. // parse an FBX file in ASCII format
  1728. function TextParser() {}
  1729. TextParser.prototype = {
  1730. constructor: TextParser,
  1731. getPrevNode: function getPrevNode() {
  1732. return this.nodeStack[this.currentIndent - 2];
  1733. },
  1734. getCurrentNode: function getCurrentNode() {
  1735. return this.nodeStack[this.currentIndent - 1];
  1736. },
  1737. getCurrentProp: function getCurrentProp() {
  1738. return this.currentProp;
  1739. },
  1740. pushStack: function pushStack(node) {
  1741. this.nodeStack.push(node);
  1742. this.currentIndent += 1;
  1743. },
  1744. popStack: function popStack() {
  1745. this.nodeStack.pop();
  1746. this.currentIndent -= 1;
  1747. },
  1748. setCurrentProp: function setCurrentProp(val, name) {
  1749. this.currentProp = val;
  1750. this.currentPropName = name;
  1751. },
  1752. parse: function parse(text) {
  1753. this.currentIndent = 0;
  1754. console.log("FBXTree: ", FBXTree);
  1755. this.allNodes = new FBXTree();
  1756. this.nodeStack = [];
  1757. this.currentProp = [];
  1758. this.currentPropName = '';
  1759. var self = this;
  1760. var split = text.split(/[\r\n]+/);
  1761. split.forEach(function (line, i) {
  1762. var matchComment = line.match(/^[\s\t]*;/);
  1763. var matchEmpty = line.match(/^[\s\t]*$/);
  1764. if (matchComment || matchEmpty) return;
  1765. var matchBeginning = line.match('^\\t{' + self.currentIndent + '}(\\w+):(.*){', '');
  1766. var matchProperty = line.match('^\\t{' + self.currentIndent + '}(\\w+):[\\s\\t\\r\\n](.*)');
  1767. var matchEnd = line.match('^\\t{' + (self.currentIndent - 1) + '}}');
  1768. if (matchBeginning) {
  1769. self.parseNodeBegin(line, matchBeginning);
  1770. } else if (matchProperty) {
  1771. self.parseNodeProperty(line, matchProperty, split[++i]);
  1772. } else if (matchEnd) {
  1773. self.popStack();
  1774. } else if (line.match(/^[^\s\t}]/)) {
  1775. // large arrays are split over multiple lines terminated with a ',' character
  1776. // if this is encountered the line needs to be joined to the previous line
  1777. self.parseNodePropertyContinued(line);
  1778. }
  1779. });
  1780. return this.allNodes;
  1781. },
  1782. parseNodeBegin: function parseNodeBegin(line, property) {
  1783. var nodeName = property[1].trim().replace(/^"/, '').replace(/"$/, '');
  1784. var nodeAttrs = property[2].split(',').map(function (attr) {
  1785. return attr.trim().replace(/^"/, '').replace(/"$/, '');
  1786. });
  1787. var node = { name: nodeName };
  1788. var attrs = this.parseNodeAttr(nodeAttrs);
  1789. var currentNode = this.getCurrentNode();
  1790. // a top node
  1791. if (this.currentIndent === 0) {
  1792. this.allNodes.add(nodeName, node);
  1793. } else {
  1794. // a subnode
  1795. // if the subnode already exists, append it
  1796. if (nodeName in currentNode) {
  1797. // special case Pose needs PoseNodes as an array
  1798. if (nodeName === 'PoseNode') {
  1799. currentNode.PoseNode.push(node);
  1800. } else if (currentNode[nodeName].id !== undefined) {
  1801. currentNode[nodeName] = {};
  1802. currentNode[nodeName][currentNode[nodeName].id] = currentNode[nodeName];
  1803. }
  1804. if (attrs.id !== '') currentNode[nodeName][attrs.id] = node;
  1805. } else if (typeof attrs.id === 'number') {
  1806. currentNode[nodeName] = {};
  1807. currentNode[nodeName][attrs.id] = node;
  1808. } else if (nodeName !== 'Properties70') {
  1809. if (nodeName === 'PoseNode') currentNode[nodeName] = [node];else currentNode[nodeName] = node;
  1810. }
  1811. }
  1812. if (typeof attrs.id === 'number') node.id = attrs.id;
  1813. if (attrs.name !== '') node.attrName = attrs.name;
  1814. if (attrs.type !== '') node.attrType = attrs.type;
  1815. this.pushStack(node);
  1816. },
  1817. parseNodeAttr: function parseNodeAttr(attrs) {
  1818. var id = attrs[0];
  1819. if (attrs[0] !== '') {
  1820. id = parseInt(attrs[0]);
  1821. if (isNaN(id)) {
  1822. id = attrs[0];
  1823. }
  1824. }
  1825. var name = '',
  1826. type = '';
  1827. if (attrs.length > 1) {
  1828. name = attrs[1].replace(/^(\w+)::/, '');
  1829. type = attrs[2];
  1830. }
  1831. return { id: id, name: name, type: type };
  1832. },
  1833. parseNodeProperty: function parseNodeProperty(line, property, contentLine) {
  1834. var propName = property[1].replace(/^"/, '').replace(/"$/, '').trim();
  1835. var propValue = property[2].replace(/^"/, '').replace(/"$/, '').trim();
  1836. // for special case: base64 image data follows "Content: ," line
  1837. // Content: ,
  1838. // "/9j/4RDaRXhpZgAATU0A..."
  1839. if (propName === 'Content' && propValue === ',') {
  1840. propValue = contentLine.replace(/"/g, '').replace(/,$/, '').trim();
  1841. }
  1842. var currentNode = this.getCurrentNode();
  1843. var parentName = currentNode.name;
  1844. if (parentName === 'Properties70') {
  1845. this.parseNodeSpecialProperty(line, propName, propValue);
  1846. return;
  1847. }
  1848. // Connections
  1849. if (propName === 'C') {
  1850. var connProps = propValue.split(',').slice(1);
  1851. var from = parseInt(connProps[0]);
  1852. var to = parseInt(connProps[1]);
  1853. var rest = propValue.split(',').slice(3);
  1854. rest = rest.map(function (elem) {
  1855. return elem.trim().replace(/^"/, '');
  1856. });
  1857. propName = 'connections';
  1858. propValue = [from, to];
  1859. append(propValue, rest);
  1860. if (currentNode[propName] === undefined) {
  1861. currentNode[propName] = [];
  1862. }
  1863. }
  1864. // Node
  1865. if (propName === 'Node') currentNode.id = propValue;
  1866. // connections
  1867. if (propName in currentNode && Array.isArray(currentNode[propName])) {
  1868. currentNode[propName].push(propValue);
  1869. } else {
  1870. if (propName !== 'a') currentNode[propName] = propValue;else currentNode.a = propValue;
  1871. }
  1872. this.setCurrentProp(currentNode, propName);
  1873. // convert string to array, unless it ends in ',' in which case more will be added to it
  1874. if (propName === 'a' && propValue.slice(-1) !== ',') {
  1875. currentNode.a = parseNumberArray(propValue);
  1876. }
  1877. },
  1878. parseNodePropertyContinued: function parseNodePropertyContinued(line) {
  1879. var currentNode = this.getCurrentNode();
  1880. currentNode.a += line;
  1881. // if the line doesn't end in ',' we have reached the end of the property value
  1882. // so convert the string to an array
  1883. if (line.slice(-1) !== ',') {
  1884. currentNode.a = parseNumberArray(currentNode.a);
  1885. }
  1886. },
  1887. // parse "Property70"
  1888. parseNodeSpecialProperty: function parseNodeSpecialProperty(line, propName, propValue) {
  1889. // split this
  1890. // P: "Lcl Scaling", "Lcl Scaling", "", "A",1,1,1
  1891. // into array like below
  1892. // ["Lcl Scaling", "Lcl Scaling", "", "A", "1,1,1" ]
  1893. var props = propValue.split('",').map(function (prop) {
  1894. return prop.trim().replace(/^\"/, '').replace(/\s/, '_');
  1895. });
  1896. var innerPropName = props[0];
  1897. var innerPropType1 = props[1];
  1898. var innerPropType2 = props[2];
  1899. var innerPropFlag = props[3];
  1900. var innerPropValue = props[4];
  1901. // cast values where needed, otherwise leave as strings
  1902. switch (innerPropType1) {
  1903. case 'int':
  1904. case 'enum':
  1905. case 'bool':
  1906. case 'ULongLong':
  1907. case 'double':
  1908. case 'Number':
  1909. case 'FieldOfView':
  1910. innerPropValue = parseFloat(innerPropValue);
  1911. break;
  1912. case 'Color':
  1913. case 'ColorRGB':
  1914. case 'Vector3D':
  1915. case 'Lcl_Translation':
  1916. case 'Lcl_Rotation':
  1917. case 'Lcl_Scaling':
  1918. innerPropValue = parseNumberArray(innerPropValue);
  1919. break;
  1920. }
  1921. // CAUTION: these props must append to parent's parent
  1922. this.getPrevNode()[innerPropName] = {
  1923. 'type': innerPropType1,
  1924. 'type2': innerPropType2,
  1925. 'flag': innerPropFlag,
  1926. 'value': innerPropValue
  1927. };
  1928. this.setCurrentProp(this.getPrevNode(), innerPropName);
  1929. }
  1930. };
  1931. // Parse an FBX file in Binary format
  1932. function BinaryParser() {}
  1933. BinaryParser.prototype = {
  1934. constructor: BinaryParser,
  1935. parse: function parse(buffer) {
  1936. var reader = new BinaryReader(buffer);
  1937. reader.skip(23); // skip magic 23 bytes
  1938. var version = reader.getUint32();
  1939. console.log('THREE.FBXLoader: FBX binary version: ' + version);
  1940. var allNodes = new FBXTree();
  1941. while (!this.endOfContent(reader)) {
  1942. var node = this.parseNode(reader, version);
  1943. if (node !== null) allNodes.add(node.name, node);
  1944. }
  1945. return allNodes;
  1946. },
  1947. // Check if reader has reached the end of content.
  1948. endOfContent: function endOfContent(reader) {
  1949. // footer size: 160bytes + 16-byte alignment padding
  1950. // - 16bytes: magic
  1951. // - padding til 16-byte alignment (at least 1byte?)
  1952. // (seems like some exporters embed fixed 15 or 16bytes?)
  1953. // - 4bytes: magic
  1954. // - 4bytes: version
  1955. // - 120bytes: zero
  1956. // - 16bytes: magic
  1957. if (reader.size() % 16 === 0) {
  1958. return (reader.getOffset() + 160 + 16 & ~0xf) >= reader.size();
  1959. } else {
  1960. return reader.getOffset() + 160 + 16 >= reader.size();
  1961. }
  1962. },
  1963. // recursively parse nodes until the end of the file is reached
  1964. parseNode: function parseNode(reader, version) {
  1965. var node = {};
  1966. // The first three data sizes depends on version.
  1967. var endOffset = version >= 7500 ? reader.getUint64() : reader.getUint32();
  1968. var numProperties = version >= 7500 ? reader.getUint64() : reader.getUint32();
  1969. // note: do not remove this even if you get a linter warning as it moves the buffer forward
  1970. var propertyListLen = version >= 7500 ? reader.getUint64() : reader.getUint32();
  1971. var nameLen = reader.getUint8();
  1972. var name = reader.getString(nameLen);
  1973. // Regards this node as NULL-record if endOffset is zero
  1974. if (endOffset === 0) return null;
  1975. var propertyList = [];
  1976. for (var i = 0; i < numProperties; i++) {
  1977. propertyList.push(this.parseProperty(reader));
  1978. }
  1979. // Regards the first three elements in propertyList as id, attrName, and attrType
  1980. var id = propertyList.length > 0 ? propertyList[0] : '';
  1981. var attrName = propertyList.length > 1 ? propertyList[1] : '';
  1982. var attrType = propertyList.length > 2 ? propertyList[2] : '';
  1983. // check if this node represents just a single property
  1984. // like (name, 0) set or (name2, [0, 1, 2]) set of {name: 0, name2: [0, 1, 2]}
  1985. node.singleProperty = numProperties === 1 && reader.getOffset() === endOffset ? true : false;
  1986. while (endOffset > reader.getOffset()) {
  1987. var subNode = this.parseNode(reader, version);
  1988. if (subNode !== null) this.parseSubNode(name, node, subNode);
  1989. }
  1990. node.propertyList = propertyList; // raw property list used by parent
  1991. if (typeof id === 'number') node.id = id;
  1992. if (attrName !== '') node.attrName = attrName;
  1993. if (attrType !== '') node.attrType = attrType;
  1994. if (name !== '') node.name = name;
  1995. return node;
  1996. },
  1997. parseSubNode: function parseSubNode(name, node, subNode) {
  1998. // special case: child node is single property
  1999. if (subNode.singleProperty === true) {
  2000. var value = subNode.propertyList[0];
  2001. if (Array.isArray(value)) {
  2002. node[subNode.name] = subNode;
  2003. subNode.a = value;
  2004. } else {
  2005. node[subNode.name] = value;
  2006. }
  2007. } else if (name === 'Connections' && subNode.name === 'C') {
  2008. var array = [];
  2009. subNode.propertyList.forEach(function (property, i) {
  2010. // first Connection is FBX type (OO, OP, etc.). We'll discard these
  2011. if (i !== 0) array.push(property);
  2012. });
  2013. if (node.connections === undefined) {
  2014. node.connections = [];
  2015. }
  2016. node.connections.push(array);
  2017. } else if (subNode.name === 'Properties70') {
  2018. var keys = Object.keys(subNode);
  2019. keys.forEach(function (key) {
  2020. node[key] = subNode[key];
  2021. });
  2022. } else if (name === 'Properties70' && subNode.name === 'P') {
  2023. var innerPropName = subNode.propertyList[0];
  2024. var innerPropType1 = subNode.propertyList[1];
  2025. var innerPropType2 = subNode.propertyList[2];
  2026. var innerPropFlag = subNode.propertyList[3];
  2027. var innerPropValue;
  2028. if (innerPropName.indexOf('Lcl ') === 0) innerPropName = innerPropName.replace('Lcl ', 'Lcl_');
  2029. if (innerPropType1.indexOf('Lcl ') === 0) innerPropType1 = innerPropType1.replace('Lcl ', 'Lcl_');
  2030. if (innerPropType1 === 'Color' || innerPropType1 === 'ColorRGB' || innerPropType1 === 'Vector' || innerPropType1 === 'Vector3D' || innerPropType1.indexOf('Lcl_') === 0) {
  2031. innerPropValue = [subNode.propertyList[4], subNode.propertyList[5], subNode.propertyList[6]];
  2032. } else {
  2033. innerPropValue = subNode.propertyList[4];
  2034. }
  2035. // this will be copied to parent, see above
  2036. node[innerPropName] = {
  2037. 'type': innerPropType1,
  2038. 'type2': innerPropType2,
  2039. 'flag': innerPropFlag,
  2040. 'value': innerPropValue
  2041. };
  2042. } else if (node[subNode.name] === undefined) {
  2043. if (typeof subNode.id === 'number') {
  2044. node[subNode.name] = {};
  2045. node[subNode.name][subNode.id] = subNode;
  2046. } else {
  2047. node[subNode.name] = subNode;
  2048. }
  2049. } else {
  2050. if (subNode.name === 'PoseNode') {
  2051. if (!Array.isArray(node[subNode.name])) {
  2052. node[subNode.name] = [node[subNode.name]];
  2053. }
  2054. node[subNode.name].push(subNode);
  2055. } else if (node[subNode.name][subNode.id] === undefined) {
  2056. node[subNode.name][subNode.id] = subNode;
  2057. }
  2058. }
  2059. },
  2060. parseProperty: function parseProperty(reader) {
  2061. var type = reader.getString(1);
  2062. switch (type) {
  2063. case 'C':
  2064. return reader.getBoolean();
  2065. case 'D':
  2066. return reader.getFloat64();
  2067. case 'F':
  2068. return reader.getFloat32();
  2069. case 'I':
  2070. return reader.getInt32();
  2071. case 'L':
  2072. return reader.getInt64();
  2073. case 'R':
  2074. var length = reader.getUint32();
  2075. return reader.getArrayBuffer(length);
  2076. case 'S':
  2077. var length = reader.getUint32();
  2078. return reader.getString(length);
  2079. case 'Y':
  2080. return reader.getInt16();
  2081. case 'b':
  2082. case 'c':
  2083. case 'd':
  2084. case 'f':
  2085. case 'i':
  2086. case 'l':
  2087. var arrayLength = reader.getUint32();
  2088. var encoding = reader.getUint32(); // 0: non-compressed, 1: compressed
  2089. var compressedLength = reader.getUint32();
  2090. if (encoding === 0) {
  2091. switch (type) {
  2092. case 'b':
  2093. case 'c':
  2094. return reader.getBooleanArray(arrayLength);
  2095. case 'd':
  2096. return reader.getFloat64Array(arrayLength);
  2097. case 'f':
  2098. return reader.getFloat32Array(arrayLength);
  2099. case 'i':
  2100. return reader.getInt32Array(arrayLength);
  2101. case 'l':
  2102. return reader.getInt64Array(arrayLength);
  2103. }
  2104. }
  2105. if (typeof Zlib === 'undefined') {
  2106. console.error('THREE.FBXLoader: External library Inflate.min.js required, obtain or import from https://github.com/imaya/zlib.js');
  2107. }
  2108. var inflate = new Zlib.Inflate(new Uint8Array(reader.getArrayBuffer(compressedLength))); // eslint-disable-line no-undef
  2109. var reader2 = new BinaryReader(inflate.decompress().buffer);
  2110. switch (type) {
  2111. case 'b':
  2112. case 'c':
  2113. return reader2.getBooleanArray(arrayLength);
  2114. case 'd':
  2115. return reader2.getFloat64Array(arrayLength);
  2116. case 'f':
  2117. return reader2.getFloat32Array(arrayLength);
  2118. case 'i':
  2119. return reader2.getInt32Array(arrayLength);
  2120. case 'l':
  2121. return reader2.getInt64Array(arrayLength);
  2122. }
  2123. default:
  2124. throw new Error('THREE.FBXLoader: Unknown property type ' + type);
  2125. }
  2126. }
  2127. };
  2128. function BinaryReader(buffer, littleEndian) {
  2129. this.dv = new DataView(buffer);
  2130. this.offset = 0;
  2131. this.littleEndian = littleEndian !== undefined ? littleEndian : true;
  2132. }
  2133. BinaryReader.prototype = {
  2134. constructor: BinaryReader,
  2135. getOffset: function getOffset() {
  2136. return this.offset;
  2137. },
  2138. size: function size() {
  2139. return this.dv.buffer.byteLength;
  2140. },
  2141. skip: function skip(length) {
  2142. this.offset += length;
  2143. },
  2144. // seems like true/false representation depends on exporter.
  2145. // true: 1 or 'Y'(=0x59), false: 0 or 'T'(=0x54)
  2146. // then sees LSB.
  2147. getBoolean: function getBoolean() {
  2148. return (this.getUint8() & 1) === 1;
  2149. },
  2150. getBooleanArray: function getBooleanArray(size) {
  2151. var a = [];
  2152. for (var i = 0; i < size; i++) {
  2153. a.push(this.getBoolean());
  2154. }
  2155. return a;
  2156. },
  2157. getUint8: function getUint8() {
  2158. var value = this.dv.getUint8(this.offset);
  2159. this.offset += 1;
  2160. return value;
  2161. },
  2162. getInt16: function getInt16() {
  2163. var value = this.dv.getInt16(this.offset, this.littleEndian);
  2164. this.offset += 2;
  2165. return value;
  2166. },
  2167. getInt32: function getInt32() {
  2168. var value = this.dv.getInt32(this.offset, this.littleEndian);
  2169. this.offset += 4;
  2170. return value;
  2171. },
  2172. getInt32Array: function getInt32Array(size) {
  2173. var a = [];
  2174. for (var i = 0; i < size; i++) {
  2175. a.push(this.getInt32());
  2176. }
  2177. return a;
  2178. },
  2179. getUint32: function getUint32() {
  2180. var value = this.dv.getUint32(this.offset, this.littleEndian);
  2181. this.offset += 4;
  2182. return value;
  2183. },
  2184. // JavaScript doesn't support 64-bit integer so calculate this here
  2185. // 1 << 32 will return 1 so using multiply operation instead here.
  2186. // There's a possibility that this method returns wrong value if the value
  2187. // is out of the range between Number.MAX_SAFE_INTEGER and Number.MIN_SAFE_INTEGER.
  2188. // TODO: safely handle 64-bit integer
  2189. getInt64: function getInt64() {
  2190. var low, high;
  2191. if (this.littleEndian) {
  2192. low = this.getUint32();
  2193. high = this.getUint32();
  2194. } else {
  2195. high = this.getUint32();
  2196. low = this.getUint32();
  2197. }
  2198. // calculate negative value
  2199. if (high & 0x80000000) {
  2200. high = ~high & 0xFFFFFFFF;
  2201. low = ~low & 0xFFFFFFFF;
  2202. if (low === 0xFFFFFFFF) high = high + 1 & 0xFFFFFFFF;
  2203. low = low + 1 & 0xFFFFFFFF;
  2204. return -(high * 0x100000000 + low);
  2205. }
  2206. return high * 0x100000000 + low;
  2207. },
  2208. getInt64Array: function getInt64Array(size) {
  2209. var a = [];
  2210. for (var i = 0; i < size; i++) {
  2211. a.push(this.getInt64());
  2212. }
  2213. return a;
  2214. },
  2215. // Note: see getInt64() comment
  2216. getUint64: function getUint64() {
  2217. var low, high;
  2218. if (this.littleEndian) {
  2219. low = this.getUint32();
  2220. high = this.getUint32();
  2221. } else {
  2222. high = this.getUint32();
  2223. low = this.getUint32();
  2224. }
  2225. return high * 0x100000000 + low;
  2226. },
  2227. getFloat32: function getFloat32() {
  2228. var value = this.dv.getFloat32(this.offset, this.littleEndian);
  2229. this.offset += 4;
  2230. return value;
  2231. },
  2232. getFloat32Array: function getFloat32Array(size) {
  2233. var a = [];
  2234. for (var i = 0; i < size; i++) {
  2235. a.push(this.getFloat32());
  2236. }
  2237. return a;
  2238. },
  2239. getFloat64: function getFloat64() {
  2240. var value = this.dv.getFloat64(this.offset, this.littleEndian);
  2241. this.offset += 8;
  2242. return value;
  2243. },
  2244. getFloat64Array: function getFloat64Array(size) {
  2245. var a = [];
  2246. for (var i = 0; i < size; i++) {
  2247. a.push(this.getFloat64());
  2248. }
  2249. return a;
  2250. },
  2251. getArrayBuffer: function getArrayBuffer(size) {
  2252. var value = this.dv.buffer.slice(this.offset, this.offset + size);
  2253. this.offset += size;
  2254. return value;
  2255. },
  2256. getString: function getString(size) {
  2257. // note: safari 9 doesn't support Uint8Array.indexOf; create intermediate array instead
  2258. var a = [];
  2259. for (var i = 0; i < size; i++) {
  2260. a[i] = this.getUint8();
  2261. }
  2262. var nullByte = a.indexOf(0);
  2263. if (nullByte >= 0) a = a.slice(0, nullByte);
  2264. return THREE.LoaderUtils.decodeText(new Uint8Array(a));
  2265. }
  2266. };
  2267. // FBXTree holds a representation of the FBX data, returned by the TextParser ( FBX ASCII format)
  2268. // and BinaryParser( FBX Binary format)
  2269. function FBXTree() {}
  2270. FBXTree.prototype = {
  2271. constructor: FBXTree,
  2272. add: function add(key, val) {
  2273. this[key] = val;
  2274. }
  2275. };
  2276. // ************** UTILITY FUNCTIONS **************
  2277. function isFbxFormatBinary(buffer) {
  2278. var CORRECT = 'Kaydara FBX Binary \0';
  2279. return buffer.byteLength >= CORRECT.length && CORRECT === convertArrayBufferToString(buffer, 0, CORRECT.length);
  2280. }
  2281. function isFbxFormatASCII(text) {
  2282. var CORRECT = ['K', 'a', 'y', 'd', 'a', 'r', 'a', '\\', 'F', 'B', 'X', '\\', 'B', 'i', 'n', 'a', 'r', 'y', '\\', '\\'];
  2283. var cursor = 0;
  2284. function read(offset) {
  2285. var result = text[offset - 1];
  2286. text = text.slice(cursor + offset);
  2287. cursor++;
  2288. return result;
  2289. }
  2290. for (var i = 0; i < CORRECT.length; ++i) {
  2291. var num = read(1);
  2292. if (num === CORRECT[i]) {
  2293. return false;
  2294. }
  2295. }
  2296. return true;
  2297. }
  2298. function getFbxVersion(text) {
  2299. var versionRegExp = /FBXVersion: (\d+)/;
  2300. var match = text.match(versionRegExp);
  2301. if (match) {
  2302. var version = parseInt(match[1]);
  2303. return version;
  2304. }
  2305. throw new Error('THREE.FBXLoader: Cannot find the version number for the file given.');
  2306. }
  2307. // Converts FBX ticks into real time seconds.
  2308. function convertFBXTimeToSeconds(time) {
  2309. return time / 46186158000;
  2310. }
  2311. var dataArray = [];
  2312. // extracts the data from the correct position in the FBX array based on indexing type
  2313. function getData(polygonVertexIndex, polygonIndex, vertexIndex, infoObject) {
  2314. var index;
  2315. switch (infoObject.mappingType) {
  2316. case 'ByPolygonVertex':
  2317. index = polygonVertexIndex;
  2318. break;
  2319. case 'ByPolygon':
  2320. index = polygonIndex;
  2321. break;
  2322. case 'ByVertice':
  2323. index = vertexIndex;
  2324. break;
  2325. case 'AllSame':
  2326. index = infoObject.indices[0];
  2327. break;
  2328. default:
  2329. console.warn('THREE.FBXLoader: unknown attribute mapping type ' + infoObject.mappingType);
  2330. }
  2331. if (infoObject.referenceType === 'IndexToDirect') index = infoObject.indices[index];
  2332. var from = index * infoObject.dataSize;
  2333. var to = from + infoObject.dataSize;
  2334. return slice(dataArray, infoObject.buffer, from, to);
  2335. }
  2336. var tempMat = new THREE.Matrix4();
  2337. var tempEuler = new THREE.Euler();
  2338. var tempVec = new THREE.Vector3();
  2339. var translation = new THREE.Vector3();
  2340. var rotation = new THREE.Matrix4();
  2341. // generate transformation from FBX transform data
  2342. // ref: https://help.autodesk.com/view/FBX/2017/ENU/?guid=__files_GUID_10CDD63C_79C1_4F2D_BB28_AD2BE65A02ED_htm
  2343. // transformData = {
  2344. // eulerOrder: int,
  2345. // translation: [],
  2346. // rotationOffset: [],
  2347. // preRotation
  2348. // rotation
  2349. // postRotation
  2350. // scale
  2351. // }
  2352. // all entries are optional
  2353. function generateTransform(transformData) {
  2354. var transform = new THREE.Matrix4();
  2355. translation.set(0, 0, 0);
  2356. rotation.identity();
  2357. var order = transformData.eulerOrder ? getEulerOrder(transformData.eulerOrder) : getEulerOrder(0);
  2358. if (transformData.translation) translation.fromArray(transformData.translation);
  2359. if (transformData.rotationOffset) translation.add(tempVec.fromArray(transformData.rotationOffset));
  2360. if (transformData.rotation) {
  2361. var array = transformData.rotation.map(THREE.Math.degToRad);
  2362. array.push(order);
  2363. rotation.makeRotationFromEuler(tempEuler.fromArray(array));
  2364. }
  2365. if (transformData.preRotation) {
  2366. var array = transformData.preRotation.map(THREE.Math.degToRad);
  2367. array.push(order);
  2368. tempMat.makeRotationFromEuler(tempEuler.fromArray(array));
  2369. rotation.premultiply(tempMat);
  2370. }
  2371. if (transformData.postRotation) {
  2372. var array = transformData.postRotation.map(THREE.Math.degToRad);
  2373. array.push(order);
  2374. tempMat.makeRotationFromEuler(tempEuler.fromArray(array));
  2375. tempMat.getInverse(tempMat);
  2376. rotation.multiply(tempMat);
  2377. }
  2378. if (transformData.scale) transform.scale(tempVec.fromArray(transformData.scale));
  2379. transform.setPosition(translation);
  2380. transform.multiply(rotation);
  2381. return transform;
  2382. }
  2383. // Returns the three.js intrinsic Euler order corresponding to FBX extrinsic Euler order
  2384. // ref: http://help.autodesk.com/view/FBX/2017/ENU/?guid=__cpp_ref_class_fbx_euler_html
  2385. function getEulerOrder(order) {
  2386. var enums = ['ZYX', // -> XYZ extrinsic
  2387. 'YZX', // -> XZY extrinsic
  2388. 'XZY', // -> YZX extrinsic
  2389. 'ZXY', // -> YXZ extrinsic
  2390. 'YXZ', // -> ZXY extrinsic
  2391. 'XYZ'];
  2392. if (order === 6) {
  2393. console.warn('THREE.FBXLoader: unsupported Euler Order: Spherical XYZ. Animations and rotations may be incorrect.');
  2394. return enums[0];
  2395. }
  2396. return enums[order];
  2397. }
  2398. // Parses comma separated list of numbers and returns them an array.
  2399. // Used internally by the TextParser
  2400. function parseNumberArray(value) {
  2401. var array = value.split(',').map(function (val) {
  2402. return parseFloat(val);
  2403. });
  2404. return array;
  2405. }
  2406. function convertArrayBufferToString(buffer, from, to) {
  2407. if (from === undefined) from = 0;
  2408. if (to === undefined) to = buffer.byteLength;
  2409. return THREE.LoaderUtils.decodeText(new Uint8Array(buffer, from, to));
  2410. }
  2411. function append(a, b) {
  2412. for (var i = 0, j = a.length, l = b.length; i < l; i++, j++) {
  2413. a[j] = b[i];
  2414. }
  2415. }
  2416. function slice(a, b, from, to) {
  2417. for (var i = from, j = 0; i < to; i++, j++) {
  2418. a[j] = b[i];
  2419. }
  2420. return a;
  2421. }
  2422. // inject array a2 into array a1 at index
  2423. function inject(a1, index, a2) {
  2424. return a1.slice(0, index).concat(a2).concat(a1.slice(index));
  2425. }
  2426. return FBXLoader;
  2427. }();
  2428. },{}],4:[function(require,module,exports){
  2429. "use strict";
  2430. module.exports = Object.assign(function GamepadButton() {}, {
  2431. FACE_1: 0,
  2432. FACE_2: 1,
  2433. FACE_3: 2,
  2434. FACE_4: 3,
  2435. L_SHOULDER_1: 4,
  2436. R_SHOULDER_1: 5,
  2437. L_SHOULDER_2: 6,
  2438. R_SHOULDER_2: 7,
  2439. SELECT: 8,
  2440. START: 9,
  2441. DPAD_UP: 12,
  2442. DPAD_DOWN: 13,
  2443. DPAD_LEFT: 14,
  2444. DPAD_RIGHT: 15,
  2445. VENDOR: 16
  2446. });
  2447. },{}],5:[function(require,module,exports){
  2448. "use strict";
  2449. function GamepadButtonEvent(type, index, details) {
  2450. this.type = type;
  2451. this.index = index;
  2452. this.pressed = details.pressed;
  2453. this.value = details.value;
  2454. }
  2455. module.exports = GamepadButtonEvent;
  2456. },{}],6:[function(require,module,exports){
  2457. 'use strict';
  2458. /**
  2459. * @author Wei Meng / http://about.me/menway
  2460. *
  2461. * Description: A THREE loader for PLY ASCII files (known as the Polygon File Format or the Stanford Triangle Format).
  2462. *
  2463. *
  2464. * Limitations: ASCII decoding assumes file is UTF-8.
  2465. *
  2466. * Usage:
  2467. * var loader = new THREE.PLYLoader();
  2468. * loader.load('./models/ply/ascii/dolphins.ply', function (geometry) {
  2469. *
  2470. * scene.add( new THREE.Mesh( geometry ) );
  2471. *
  2472. * } );
  2473. *
  2474. * If the PLY file uses non standard property names, they can be mapped while
  2475. * loading. For example, the following maps the properties
  2476. * “diffuse_(red|green|blue)” in the file to standard color names.
  2477. *
  2478. * loader.setPropertyNameMapping( {
  2479. * diffuse_red: 'red',
  2480. * diffuse_green: 'green',
  2481. * diffuse_blue: 'blue'
  2482. * } );
  2483. *
  2484. */
  2485. module.exports = THREE.PLYLoader = function (manager) {
  2486. this.manager = manager !== undefined ? manager : THREE.DefaultLoadingManager;
  2487. this.propertyNameMapping = {};
  2488. };
  2489. THREE.PLYLoader.prototype = {
  2490. constructor: THREE.PLYLoader,
  2491. load: function load(url, onLoad, onProgress, onError) {
  2492. var scope = this;
  2493. var loader = new THREE.XHRLoader(this.manager);
  2494. loader.setResponseType('arraybuffer');
  2495. loader.load(url, function (text) {
  2496. onLoad(scope.parse(text));
  2497. }, onProgress, onError);
  2498. },
  2499. setPropertyNameMapping: function setPropertyNameMapping(mapping) {
  2500. this.propertyNameMapping = mapping;
  2501. },
  2502. bin2str: function bin2str(buf) {
  2503. var array_buffer = new Uint8Array(buf);
  2504. var str = '';
  2505. for (var i = 0; i < buf.byteLength; i++) {
  2506. str += String.fromCharCode(array_buffer[i]); // implicitly assumes little-endian
  2507. }
  2508. return str;
  2509. },
  2510. isASCII: function isASCII(data) {
  2511. var header = this.parseHeader(this.bin2str(data));
  2512. return header.format === "ascii";
  2513. },
  2514. parse: function parse(data) {
  2515. if (data instanceof ArrayBuffer) {
  2516. return this.isASCII(data) ? this.parseASCII(this.bin2str(data)) : this.parseBinary(data);
  2517. } else {
  2518. return this.parseASCII(data);
  2519. }
  2520. },
  2521. parseHeader: function parseHeader(data) {
  2522. var patternHeader = /ply([\s\S]*)end_header\s/;
  2523. var headerText = "";
  2524. var headerLength = 0;
  2525. var result = patternHeader.exec(data);
  2526. if (result !== null) {
  2527. headerText = result[1];
  2528. headerLength = result[0].length;
  2529. }
  2530. var header = {
  2531. comments: [],
  2532. elements: [],
  2533. headerLength: headerLength
  2534. };
  2535. var lines = headerText.split('\n');
  2536. var currentElement = undefined;
  2537. var lineType, lineValues;
  2538. function make_ply_element_property(propertValues, propertyNameMapping) {
  2539. var property = {
  2540. type: propertValues[0]
  2541. };
  2542. if (property.type === 'list') {
  2543. property.name = propertValues[3];
  2544. property.countType = propertValues[1];
  2545. property.itemType = propertValues[2];
  2546. } else {
  2547. property.name = propertValues[1];
  2548. }
  2549. if (property.name in propertyNameMapping) {
  2550. property.name = propertyNameMapping[property.name];
  2551. }
  2552. return property;
  2553. }
  2554. for (var i = 0; i < lines.length; i++) {
  2555. var line = lines[i];
  2556. line = line.trim();
  2557. if (line === "") {
  2558. continue;
  2559. }
  2560. lineValues = line.split(/\s+/);
  2561. lineType = lineValues.shift();
  2562. line = lineValues.join(" ");
  2563. switch (lineType) {
  2564. case "format":
  2565. header.format = lineValues[0];
  2566. header.version = lineValues[1];
  2567. break;
  2568. case "comment":
  2569. header.comments.push(line);
  2570. break;
  2571. case "element":
  2572. if (!(currentElement === undefined)) {
  2573. header.elements.push(currentElement);
  2574. }
  2575. currentElement = Object();
  2576. currentElement.name = lineValues[0];
  2577. currentElement.count = parseInt(lineValues[1]);
  2578. currentElement.properties = [];
  2579. break;
  2580. case "property":
  2581. currentElement.properties.push(make_ply_element_property(lineValues, this.propertyNameMapping));
  2582. break;
  2583. default:
  2584. console.log("unhandled", lineType, lineValues);
  2585. }
  2586. }
  2587. if (!(currentElement === undefined)) {
  2588. header.elements.push(currentElement);
  2589. }
  2590. return header;
  2591. },
  2592. parseASCIINumber: function parseASCIINumber(n, type) {
  2593. switch (type) {
  2594. case 'char':case 'uchar':case 'short':case 'ushort':case 'int':case 'uint':
  2595. case 'int8':case 'uint8':case 'int16':case 'uint16':case 'int32':case 'uint32':
  2596. return parseInt(n);
  2597. case 'float':case 'double':case 'float32':case 'float64':
  2598. return parseFloat(n);
  2599. }
  2600. },
  2601. parseASCIIElement: function parseASCIIElement(properties, line) {
  2602. var values = line.split(/\s+/);
  2603. var element = Object();
  2604. for (var i = 0; i < properties.length; i++) {
  2605. if (properties[i].type === "list") {
  2606. var list = [];
  2607. var n = this.parseASCIINumber(values.shift(), properties[i].countType);
  2608. for (var j = 0; j < n; j++) {
  2609. list.push(this.parseASCIINumber(values.shift(), properties[i].itemType));
  2610. }
  2611. element[properties[i].name] = list;
  2612. } else {
  2613. element[properties[i].name] = this.parseASCIINumber(values.shift(), properties[i].type);
  2614. }
  2615. }
  2616. return element;
  2617. },
  2618. parseASCII: function parseASCII(data) {
  2619. // PLY ascii format specification, as per http://en.wikipedia.org/wiki/PLY_(file_format)
  2620. var geometry = new THREE.Geometry();
  2621. var result;
  2622. var header = this.parseHeader(data);
  2623. var patternBody = /end_header\s([\s\S]*)$/;
  2624. var body = "";
  2625. if ((result = patternBody.exec(data)) !== null) {
  2626. body = result[1];
  2627. }
  2628. var lines = body.split('\n');
  2629. var currentElement = 0;
  2630. var currentElementCount = 0;
  2631. geometry.useColor = false;
  2632. for (var i = 0; i < lines.length; i++) {
  2633. var line = lines[i];
  2634. line = line.trim();
  2635. if (line === "") {
  2636. continue;
  2637. }
  2638. if (currentElementCount >= header.elements[currentElement].count) {
  2639. currentElement++;
  2640. currentElementCount = 0;
  2641. }
  2642. var element = this.parseASCIIElement(header.elements[currentElement].properties, line);
  2643. this.handleElement(geometry, header.elements[currentElement].name, element);
  2644. currentElementCount++;
  2645. }
  2646. return this.postProcess(geometry);
  2647. },
  2648. postProcess: function postProcess(geometry) {
  2649. if (geometry.useColor) {
  2650. for (var i = 0; i < geometry.faces.length; i++) {
  2651. geometry.faces[i].vertexColors = [geometry.colors[geometry.faces[i].a], geometry.colors[geometry.faces[i].b], geometry.colors[geometry.faces[i].c]];
  2652. }
  2653. geometry.elementsNeedUpdate = true;
  2654. }
  2655. geometry.computeBoundingSphere();
  2656. return geometry;
  2657. },
  2658. handleElement: function handleElement(geometry, elementName, element) {
  2659. if (elementName === "vertex") {
  2660. geometry.vertices.push(new THREE.Vector3(element.x, element.y, element.z));
  2661. if ('red' in element && 'green' in element && 'blue' in element) {
  2662. geometry.useColor = true;
  2663. var color = new THREE.Color();
  2664. color.setRGB(element.red / 255.0, element.green / 255.0, element.blue / 255.0);
  2665. geometry.colors.push(color);
  2666. }
  2667. } else if (elementName === "face") {
  2668. // BEGIN: Edits by donmccurdy.
  2669. var vertex_indices = element.vertex_indices || element.vertex_index;
  2670. // END: Edits by donmccurdy.
  2671. if (vertex_indices.length === 3) {
  2672. geometry.faces.push(new THREE.Face3(vertex_indices[0], vertex_indices[1], vertex_indices[2]));
  2673. } else if (vertex_indices.length === 4) {
  2674. geometry.faces.push(new THREE.Face3(vertex_indices[0], vertex_indices[1], vertex_indices[3]), new THREE.Face3(vertex_indices[1], vertex_indices[2], vertex_indices[3]));
  2675. }
  2676. }
  2677. },
  2678. binaryRead: function binaryRead(dataview, at, type, little_endian) {
  2679. switch (type) {
  2680. // corespondences for non-specific length types here match rply:
  2681. case 'int8':case 'char':
  2682. return [dataview.getInt8(at), 1];
  2683. case 'uint8':case 'uchar':
  2684. return [dataview.getUint8(at), 1];
  2685. case 'int16':case 'short':
  2686. return [dataview.getInt16(at, little_endian), 2];
  2687. case 'uint16':case 'ushort':
  2688. return [dataview.getUint16(at, little_endian), 2];
  2689. case 'int32':case 'int':
  2690. return [dataview.getInt32(at, little_endian), 4];
  2691. case 'uint32':case 'uint':
  2692. return [dataview.getUint32(at, little_endian), 4];
  2693. case 'float32':case 'float':
  2694. return [dataview.getFloat32(at, little_endian), 4];
  2695. case 'float64':case 'double':
  2696. return [dataview.getFloat64(at, little_endian), 8];
  2697. }
  2698. },
  2699. binaryReadElement: function binaryReadElement(dataview, at, properties, little_endian) {
  2700. var element = Object();
  2701. var result,
  2702. read = 0;
  2703. for (var i = 0; i < properties.length; i++) {
  2704. if (properties[i].type === "list") {
  2705. var list = [];
  2706. result = this.binaryRead(dataview, at + read, properties[i].countType, little_endian);
  2707. var n = result[0];
  2708. read += result[1];
  2709. for (var j = 0; j < n; j++) {
  2710. result = this.binaryRead(dataview, at + read, properties[i].itemType, little_endian);
  2711. list.push(result[0]);
  2712. read += result[1];
  2713. }
  2714. element[properties[i].name] = list;
  2715. } else {
  2716. result = this.binaryRead(dataview, at + read, properties[i].type, little_endian);
  2717. element[properties[i].name] = result[0];
  2718. read += result[1];
  2719. }
  2720. }
  2721. return [element, read];
  2722. },
  2723. parseBinary: function parseBinary(data) {
  2724. var geometry = new THREE.Geometry();
  2725. var header = this.parseHeader(this.bin2str(data));
  2726. var little_endian = header.format === "binary_little_endian";
  2727. var body = new DataView(data, header.headerLength);
  2728. var result,
  2729. loc = 0;
  2730. for (var currentElement = 0; currentElement < header.elements.length; currentElement++) {
  2731. for (var currentElementCount = 0; currentElementCount < header.elements[currentElement].count; currentElementCount++) {
  2732. result = this.binaryReadElement(body, loc, header.elements[currentElement].properties, little_endian);
  2733. loc += result[1];
  2734. var element = result[0];
  2735. this.handleElement(geometry, header.elements[currentElement].name, element);
  2736. }
  2737. }
  2738. return this.postProcess(geometry);
  2739. }
  2740. };
  2741. },{}],7:[function(require,module,exports){
  2742. "use strict";
  2743. module.exports = {
  2744. "size": 5,
  2745. "cellSize": 10,
  2746. "extrudeSettings": {
  2747. "amount": 1,
  2748. "bevelEnabled": true,
  2749. "bevelSegments": 1,
  2750. "steps": 1,
  2751. "bevelSize": 0.5,
  2752. "bevelThickness": 0.5
  2753. },
  2754. "autogenerated": true,
  2755. "cells": [{
  2756. "q": -1,
  2757. "r": 0,
  2758. "s": 1,
  2759. "h": 1,
  2760. "walkable": true,
  2761. "userData": {}
  2762. }, {
  2763. "q": 0,
  2764. "r": -1,
  2765. "s": 1,
  2766. "h": 1,
  2767. "walkable": true,
  2768. "userData": {}
  2769. }, {
  2770. "q": 0,
  2771. "r": 0,
  2772. "s": 0,
  2773. "h": 1,
  2774. "walkable": true,
  2775. "userData": {}
  2776. }, {
  2777. "q": 1,
  2778. "r": -1,
  2779. "s": 0,
  2780. "h": 1,
  2781. "walkable": true,
  2782. "userData": {}
  2783. }, {
  2784. "q": -1,
  2785. "r": 1,
  2786. "s": 0,
  2787. "h": 0,
  2788. "walkable": true,
  2789. "userData": {}
  2790. }, {
  2791. "q": 0,
  2792. "r": 1,
  2793. "s": -1,
  2794. "h": 0,
  2795. "walkable": true,
  2796. "userData": {}
  2797. }, {
  2798. "q": 1,
  2799. "r": 0,
  2800. "s": -1,
  2801. "h": 0,
  2802. "walkable": true,
  2803. "userData": {}
  2804. }]
  2805. };
  2806. },{}],8:[function(require,module,exports){
  2807. 'use strict';
  2808. /**
  2809. * Source: https://github.com/Adobe-Marketing-Cloud/fetch-script
  2810. */
  2811. function getScriptId() {
  2812. return 'script_' + Date.now() + '_' + Math.ceil(Math.random() * 100000);
  2813. }
  2814. function createScript(url, id) {
  2815. var script = document.createElement('script');
  2816. script.type = 'text/javascript';
  2817. script.async = true;
  2818. script.id = id;
  2819. script.src = url;
  2820. return script;
  2821. }
  2822. function removeScript(id) {
  2823. var script = document.getElementById(id);
  2824. var parent = script.parentNode;
  2825. try {
  2826. parent && parent.removeChild(script);
  2827. } catch (e) {
  2828. // ignore
  2829. }
  2830. }
  2831. function appendScript(script) {
  2832. var firstScript = document.getElementsByTagName('script')[0];
  2833. firstScript.parentNode.insertBefore(script, firstScript);
  2834. }
  2835. function fetchScriptInternal(url, options, Promise) {
  2836. return new Promise(function (resolve, reject) {
  2837. var timeout = options.timeout || 5000;
  2838. var scriptId = getScriptId();
  2839. var script = createScript(url, scriptId);
  2840. var timeoutId = setTimeout(function () {
  2841. reject(new Error('Script request to ' + url + ' timed out'));
  2842. removeScript(scriptId);
  2843. }, timeout);
  2844. var disableTimeout = function disableTimeout(timeoutId) {
  2845. clearTimeout(timeoutId);
  2846. };
  2847. script.addEventListener('load', function (e) {
  2848. resolve({ ok: true });
  2849. disableTimeout(timeoutId);
  2850. removeScript(scriptId);
  2851. });
  2852. script.addEventListener('error', function (e) {
  2853. reject(new Error('Script request to ' + url + ' failed ' + e));
  2854. disableTimeout(timeoutId);
  2855. removeScript(scriptId);
  2856. });
  2857. appendScript(script);
  2858. });
  2859. }
  2860. function fetchScript(settings) {
  2861. settings = settings || {};
  2862. return function (url, options) {
  2863. options = options || {};
  2864. return fetchScriptInternal(url, options, settings.Promise || Promise);
  2865. };
  2866. }
  2867. module.exports = fetchScript;
  2868. },{}],9:[function(require,module,exports){
  2869. "use strict";
  2870. var _typeof2 = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
  2871. var _typeof = typeof Symbol === "function" && _typeof2(Symbol.iterator) === "symbol" ? function (obj) {
  2872. return typeof obj === "undefined" ? "undefined" : _typeof2(obj);
  2873. } : function (obj) {
  2874. return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj === "undefined" ? "undefined" : _typeof2(obj);
  2875. };
  2876. var vg = module.exports = { VERSION: "0.1.1", PI: Math.PI, TAU: 2 * Math.PI, DEG_TO_RAD: .0174532925, RAD_TO_DEG: 57.2957795, SQRT3: Math.sqrt(3), TILE: "tile", ENT: "entity", STR: "structure", HEX: "hex", SQR: "square", ABS: "abstract" };vg.Board = function (e, t) {
  2877. if (!e) throw new Error("You must pass in a grid system for the board to use.");this.tiles = [], this.tileGroup = null, this.group = new THREE.Object3D(), this.grid = null, this.overlay = null, this.finder = new vg.AStarFinder(t), vg.Loader.init(), this.setGrid(e);
  2878. }, vg.Board.prototype = { setEntityOnTile: function setEntityOnTile(e, t) {
  2879. var i = this.grid.cellToPixel(t.cell);e.position.copy(i), e.position.y += e.heightOffset || 0, e.tile && (e.tile.entity = null), e.tile = t, t.entity = e;
  2880. }, addTile: function addTile(e) {
  2881. var t = this.tiles.indexOf(e);-1 === t && (this.tiles.push(e), this.snapTileToGrid(e), e.position.y = 0, this.tileGroup.add(e.mesh), this.grid.add(e.cell), e.cell.tile = e);
  2882. }, removeTile: function removeTile(e) {
  2883. if (e) {
  2884. var t = this.tiles.indexOf(e);this.grid.remove(e.cell), -1 !== t && this.tiles.splice(t, 1), e.dispose();
  2885. }
  2886. }, removeAllTiles: function removeAllTiles() {
  2887. if (this.tileGroup) for (var e = this.tileGroup.children, t = 0; t < e.length; t++) {
  2888. this.tileGroup.remove(e[t]);
  2889. }
  2890. }, getTileAtCell: function getTileAtCell(e) {
  2891. var t = this.grid.cellToHash(e);return e.tile || ("undefined" != typeof this.grid.cells[t] ? this.grid.cells[t].tile : null);
  2892. }, snapToGrid: function snapToGrid(e) {
  2893. var t = this.grid.pixelToCell(e);e.copy(this.grid.cellToPixel(t));
  2894. }, snapTileToGrid: function snapTileToGrid(e) {
  2895. if (e.cell) e.position.copy(this.grid.cellToPixel(e.cell));else {
  2896. var t = this.grid.pixelToCell(e.position);e.position.copy(this.grid.cellToPixel(t));
  2897. }return e;
  2898. }, getRandomTile: function getRandomTile() {
  2899. var e = vg.Tools.randomInt(0, this.tiles.length - 1);return this.tiles[e];
  2900. }, findPath: function findPath(e, t, i) {
  2901. return this.finder.findPath(e.cell, t.cell, i, this.grid);
  2902. }, setGrid: function setGrid(e) {
  2903. this.group.remove(this.tileGroup), this.grid && e !== this.grid && (this.removeAllTiles(), this.tiles.forEach(function (e) {
  2904. this.grid.remove(e.cell), e.dispose();
  2905. }), this.grid.dispose()), this.grid = e, this.tiles = [], this.tileGroup = new THREE.Object3D(), this.group.add(this.tileGroup);
  2906. }, generateOverlay: function generateOverlay(e) {
  2907. var t = new THREE.LineBasicMaterial({ color: 0, opacity: .3 });this.overlay && this.group.remove(this.overlay), this.overlay = new THREE.Object3D(), this.grid.generateOverlay(e, this.overlay, t), this.group.add(this.overlay);
  2908. }, generateTilemap: function generateTilemap(e) {
  2909. this.reset();var t = this.grid.generateTiles(e);this.tiles = t, this.tileGroup = new THREE.Object3D();for (var i = 0; i < t.length; i++) {
  2910. this.tileGroup.add(t[i].mesh);
  2911. }this.group.add(this.tileGroup);
  2912. }, reset: function reset() {
  2913. this.removeAllTiles(), this.tileGroup && this.group.remove(this.tileGroup);
  2914. } }, vg.Board.prototype.constructor = vg.Board, vg.Cell = function (e, t, i, s) {
  2915. this.q = e || 0, this.r = t || 0, this.s = i || 0, this.h = s || 1, this.tile = null, this.userData = {}, this.walkable = !0, this._calcCost = 0, this._priority = 0, this._visited = !1, this._parent = null, this.uniqueID = vg.LinkedList.generateID();
  2916. }, vg.Cell.prototype = { set: function set(e, t, i) {
  2917. return this.q = e, this.r = t, this.s = i, this;
  2918. }, copy: function copy(e) {
  2919. return this.q = e.q, this.r = e.r, this.s = e.s, this.h = e.h, this.tile = e.tile || null, this.userData = e.userData || {}, this.walkable = e.walkable, this;
  2920. }, add: function add(e) {
  2921. return this.q += e.q, this.r += e.r, this.s += e.s, this;
  2922. }, equals: function equals(e) {
  2923. return this.q === e.q && this.r === e.r && this.s === e.s;
  2924. } }, vg.Cell.prototype.constructor = vg.Cell, vg.HexGrid = function (e) {
  2925. e = e || {}, this.type = vg.HEX, this.size = 5, this.cellSize = "undefined" == typeof e.cellSize ? 10 : e.cellSize, this.cells = {}, this.numCells = 0, this.extrudeSettings = null, this.autogenerated = !1;var t,
  2926. i = [];for (t = 0; 6 > t; t++) {
  2927. i.push(this._createVertex(t));
  2928. }for (this.cellShape = new THREE.Shape(), this.cellShape.moveTo(i[0].x, i[0].y), t = 1; 6 > t; t++) {
  2929. this.cellShape.lineTo(i[t].x, i[t].y);
  2930. }this.cellShape.lineTo(i[0].x, i[0].y), this.cellShape.autoClose = !0, this.cellGeo = new THREE.Geometry(), this.cellGeo.vertices = i, this.cellGeo.verticesNeedUpdate = !0, this.cellShapeGeo = new THREE.ShapeGeometry(this.cellShape), this._cellWidth = 2 * this.cellSize, this._cellLength = .5 * vg.SQRT3 * this._cellWidth, this._hashDelimeter = ".", this._directions = [new vg.Cell(1, -1, 0), new vg.Cell(1, 0, -1), new vg.Cell(0, 1, -1), new vg.Cell(-1, 1, 0), new vg.Cell(-1, 0, 1), new vg.Cell(0, -1, 1)], this._diagonals = [new vg.Cell(2, -1, -1), new vg.Cell(1, 1, -2), new vg.Cell(-1, 2, -1), new vg.Cell(-2, 1, 1), new vg.Cell(-1, -1, 2), new vg.Cell(1, -2, 1)], this._list = [], this._vec3 = new THREE.Vector3(), this._cel = new vg.Cell(), this._conversionVec = new THREE.Vector3(), this._geoCache = [], this._matCache = [];
  2931. }, vg.HexGrid.TWO_THIRDS = 2 / 3, vg.HexGrid.prototype = { cellToPixel: function cellToPixel(e) {
  2932. return this._vec3.x = e.q * this._cellWidth * .75, this._vec3.y = e.h, this._vec3.z = -((e.s - e.r) * this._cellLength * .5), this._vec3;
  2933. }, pixelToCell: function pixelToCell(e) {
  2934. var t = e.x * (vg.HexGrid.TWO_THIRDS / this.cellSize),
  2935. i = (-e.x / 3 + vg.SQRT3 / 3 * e.z) / this.cellSize;return this._cel.set(t, i, -t - i), this._cubeRound(this._cel);
  2936. }, getCellAt: function getCellAt(e) {
  2937. var t = e.x * (vg.HexGrid.TWO_THIRDS / this.cellSize),
  2938. i = (-e.x / 3 + vg.SQRT3 / 3 * e.z) / this.cellSize;return this._cel.set(t, i, -t - i), this._cubeRound(this._cel), this.cells[this.cellToHash(this._cel)];
  2939. }, getNeighbors: function getNeighbors(e, t, i) {
  2940. var s,
  2941. n,
  2942. l = this._directions.length;for (this._list.length = 0, s = 0; l > s; s++) {
  2943. this._cel.copy(e), this._cel.add(this._directions[s]), n = this.cells[this.cellToHash(this._cel)], !n || i && !i(e, n) || this._list.push(n);
  2944. }if (t) for (s = 0; l > s; s++) {
  2945. this._cel.copy(e), this._cel.add(this._diagonals[s]), n = this.cells[this.cellToHash(this._cel)], !n || i && !i(e, n) || this._list.push(n);
  2946. }return this._list;
  2947. }, getRandomCell: function getRandomCell() {
  2948. var e,
  2949. t = 0,
  2950. i = vg.Tools.randomInt(0, this.numCells);for (e in this.cells) {
  2951. if (t === i) return this.cells[e];t++;
  2952. }return this.cells[e];
  2953. }, cellToHash: function cellToHash(e) {
  2954. return e.q + this._hashDelimeter + e.r + this._hashDelimeter + e.s;
  2955. }, distance: function distance(e, t) {
  2956. var i = Math.max(Math.abs(e.q - t.q), Math.abs(e.r - t.r), Math.abs(e.s - t.s));return i += t.h - e.h;
  2957. }, clearPath: function clearPath() {
  2958. var e, t;for (e in this.cells) {
  2959. t = this.cells[e], t._calcCost = 0, t._priority = 0, t._parent = null, t._visited = !1;
  2960. }
  2961. }, traverse: function traverse(e) {
  2962. var t;for (t in this.cells) {
  2963. e(this.cells[t]);
  2964. }
  2965. }, generateTile: function generateTile(e, t, i) {
  2966. var s = Math.abs(e.h);1 > s && (s = 1);var n = this._geoCache[s];n || (this.extrudeSettings.amount = s, n = new THREE.ExtrudeGeometry(this.cellShape, this.extrudeSettings), this._geoCache[s] = n);var l = new vg.Tile({ size: this.cellSize, scale: t, cell: e, geometry: n, material: i });return e.tile = l, l;
  2967. }, generateTiles: function generateTiles(e) {
  2968. e = e || {};var t = [],
  2969. i = { tileScale: .95, cellSize: this.cellSize, material: null, extrudeSettings: { amount: 1, bevelEnabled: !0, bevelSegments: 1, steps: 1, bevelSize: .5, bevelThickness: .5 } };i = vg.Tools.merge(i, e), this.cellSize = i.cellSize, this._cellWidth = 2 * this.cellSize, this._cellLength = .5 * vg.SQRT3 * this._cellWidth, this.autogenerated = !0, this.extrudeSettings = i.extrudeSettings;var s, n, l;for (s in this.cells) {
  2970. l = this.cells[s], n = this.generateTile(l, i.tileScale, i.material), n.position.copy(this.cellToPixel(l)), n.position.y = 0, t.push(n);
  2971. }return t;
  2972. }, generateTilePoly: function generateTilePoly(e) {
  2973. e || (e = new THREE.MeshBasicMaterial({ color: 2405631 }));var t = new THREE.Mesh(this.cellShapeGeo, e);return this._vec3.set(1, 0, 0), t.rotateOnAxis(this._vec3, vg.PI / 2), t;
  2974. }, generate: function generate(e) {
  2975. e = e || {}, this.size = "undefined" == typeof e.size ? this.size : e.size;var t, i, s, n;for (t = -this.size; t < this.size + 1; t++) {
  2976. for (i = -this.size; i < this.size + 1; i++) {
  2977. s = -t - i, Math.abs(t) <= this.size && Math.abs(i) <= this.size && Math.abs(s) <= this.size && (n = new vg.Cell(t, i, s), this.add(n));
  2978. }
  2979. }
  2980. }, generateOverlay: function generateOverlay(e, t, i) {
  2981. var s,
  2982. n,
  2983. l,
  2984. r = this.cellShape.createPointsGeometry();for (s = -e; e + 1 > s; s++) {
  2985. for (n = -e; e + 1 > n; n++) {
  2986. if (l = -s - n, Math.abs(s) <= e && Math.abs(n) <= e && Math.abs(l) <= e) {
  2987. this._cel.set(s, n, l);var h = new THREE.Line(r, i);h.position.copy(this.cellToPixel(this._cel)), h.rotation.x = 90 * vg.DEG_TO_RAD, t.add(h);
  2988. }
  2989. }
  2990. }
  2991. }, add: function add(e) {
  2992. var t = this.cellToHash(e);if (!this.cells[t]) return this.cells[t] = e, this.numCells++, e;
  2993. }, remove: function remove(e) {
  2994. var t = this.cellToHash(e);this.cells[t] && (delete this.cells[t], this.numCells--);
  2995. }, dispose: function dispose() {
  2996. this.cells = null, this.numCells = 0, this.cellShape = null, this.cellGeo.dispose(), this.cellGeo = null, this.cellShapeGeo.dispose(), this.cellShapeGeo = null, this._list = null, this._vec3 = null, this._conversionVec = null, this._geoCache = null, this._matCache = null;
  2997. }, load: function load(e, t, i) {
  2998. var s = this;vg.Tools.getJSON({ url: e, callback: function callback(e) {
  2999. s.fromJSON(e), t.call(i || null, e);
  3000. }, cache: !1, scope: s });
  3001. }, fromJSON: function fromJSON(e) {
  3002. var t,
  3003. i,
  3004. s = e.cells;for (this.cells = {}, this.numCells = 0, this.size = e.size, this.cellSize = e.cellSize, this._cellWidth = 2 * this.cellSize, this._cellLength = .5 * vg.SQRT3 * this._cellWidth, this.extrudeSettings = e.extrudeSettings, this.autogenerated = e.autogenerated, t = 0; t < s.length; t++) {
  3005. i = new vg.Cell(), i.copy(s[t]), this.add(i);
  3006. }
  3007. }, toJSON: function toJSON() {
  3008. var e,
  3009. t,
  3010. i = { size: this.size, cellSize: this.cellSize, extrudeSettings: this.extrudeSettings, autogenerated: this.autogenerated },
  3011. s = [];for (t in this.cells) {
  3012. e = this.cells[t], s.push({ q: e.q, r: e.r, s: e.s, h: e.h, walkable: e.walkable, userData: e.userData });
  3013. }return i.cells = s, i;
  3014. }, _createVertex: function _createVertex(e) {
  3015. var t = vg.TAU / 6 * e;return new THREE.Vector3(this.cellSize * Math.cos(t), this.cellSize * Math.sin(t), 0);
  3016. }, _cubeRound: function _cubeRound(e) {
  3017. var t = Math.round(e.q),
  3018. i = Math.round(e.r),
  3019. s = Math.round(e.s),
  3020. n = Math.abs(t - e.q),
  3021. l = Math.abs(i - e.r),
  3022. r = Math.abs(s - e.s);return n > l && n > r ? t = -i - s : l > r ? i = -t - s : s = -t - i, this._cel.set(t, i, s);
  3023. } }, vg.HexGrid.prototype.constructor = vg.HexGrid, vg.SqrGrid = function (e) {
  3024. e = e || {}, this.type = vg.SQR, this.size = 5, this.cellSize = "undefined" == typeof e.cellSize ? 10 : e.cellSize, this.cells = {}, this.numCells = 0, this.extrudeSettings = null, this.autogenerated = !1;var t = [];t.push(new THREE.Vector3()), t.push(new THREE.Vector3(-this.cellSize, this.cellSize)), t.push(new THREE.Vector3(this.cellSize, this.cellSize)), t.push(new THREE.Vector3(this.cellSize, -this.cellSize)), this.cellShape = new THREE.Shape(), this.cellShape.moveTo(-this.cellSize, -this.cellSize), this.cellShape.lineTo(-this.cellSize, this.cellSize), this.cellShape.lineTo(this.cellSize, this.cellSize), this.cellShape.lineTo(this.cellSize, -this.cellSize), this.cellShape.lineTo(-this.cellSize, -this.cellSize), this.cellGeo = new THREE.Geometry(), this.cellGeo.vertices = t, this.cellGeo.verticesNeedUpdate = !0, this.cellShapeGeo = new THREE.ShapeGeometry(this.cellShape), this._fullCellSize = 2 * this.cellSize, this._hashDelimeter = ".", this._directions = [new vg.Cell(1, 0, 0), new vg.Cell(0, -1, 0), new vg.Cell(-1, 0, 0), new vg.Cell(0, 1, 0)], this._diagonals = [new vg.Cell(-1, -1, 0), new vg.Cell(-1, 1, 0), new vg.Cell(1, 1, 0), new vg.Cell(1, -1, 0)], this._list = [], this._vec3 = new THREE.Vector3(), this._cel = new vg.Cell(), this._conversionVec = new THREE.Vector3(), this._geoCache = [], this._matCache = [];
  3025. }, vg.SqrGrid.prototype = { cellToPixel: function cellToPixel(e) {
  3026. return this._vec3.x = e.q * this._fullCellSize, this._vec3.y = e.h, this._vec3.z = e.r * this._fullCellSize, this._vec3;
  3027. }, pixelToCell: function pixelToCell(e) {
  3028. var t = Math.round(e.x / this._fullCellSize),
  3029. i = Math.round(e.z / this._fullCellSize);return this._cel.set(t, i, 0);
  3030. }, getCellAt: function getCellAt(e) {
  3031. var t = Math.round(e.x / this._fullCellSize),
  3032. i = Math.round(e.z / this._fullCellSize);return this._cel.set(t, i), this.cells[this.cellToHash(this._cel)];
  3033. }, getNeighbors: function getNeighbors(e, t, i) {
  3034. var s,
  3035. n,
  3036. l = this._directions.length;for (this._list.length = 0, s = 0; l > s; s++) {
  3037. this._cel.copy(e), this._cel.add(this._directions[s]), n = this.cells[this.cellToHash(this._cel)], !n || i && !i(e, n) || this._list.push(n);
  3038. }if (t) for (s = 0; l > s; s++) {
  3039. this._cel.copy(e), this._cel.add(this._diagonals[s]), n = this.cells[this.cellToHash(this._cel)], !n || i && !i(e, n) || this._list.push(n);
  3040. }return this._list;
  3041. }, getRandomCell: function getRandomCell() {
  3042. var e,
  3043. t = 0,
  3044. i = vg.Tools.randomInt(0, this.numCells);for (e in this.cells) {
  3045. if (t === i) return this.cells[e];t++;
  3046. }return this.cells[e];
  3047. }, cellToHash: function cellToHash(e) {
  3048. return e.q + this._hashDelimeter + e.r;
  3049. }, distance: function distance(e, t) {
  3050. var i = Math.max(Math.abs(e.q - t.q), Math.abs(e.r - t.r));return i += t.h - e.h;
  3051. }, clearPath: function clearPath() {
  3052. var e, t;for (e in this.cells) {
  3053. t = this.cells[e], t._calcCost = 0, t._priority = 0, t._parent = null, t._visited = !1;
  3054. }
  3055. }, traverse: function traverse(e) {
  3056. var t;for (t in this.cells) {
  3057. e(this.cells[t]);
  3058. }
  3059. }, generateTile: function generateTile(e, t, i) {
  3060. var s = Math.abs(e.h);1 > s && (s = 1);var n = this._geoCache[s];n || (this.extrudeSettings.amount = s, n = new THREE.ExtrudeGeometry(this.cellShape, this.extrudeSettings), this._geoCache[s] = n);var l = new vg.Tile({ size: this.cellSize, scale: t, cell: e, geometry: n, material: i });return e.tile = l, l;
  3061. }, generateTiles: function generateTiles(e) {
  3062. e = e || {};var t = [],
  3063. i = { tileScale: .95, cellSize: this.cellSize, material: null, extrudeSettings: { amount: 1, bevelEnabled: !0, bevelSegments: 1, steps: 1, bevelSize: .5, bevelThickness: .5 } };i = vg.Tools.merge(i, e), this.cellSize = i.cellSize, this._fullCellSize = 2 * this.cellSize, this.autogenerated = !0, this.extrudeSettings = i.extrudeSettings;var s, n, l;for (s in this.cells) {
  3064. l = this.cells[s], n = this.generateTile(l, i.tileScale, i.material), n.position.copy(this.cellToPixel(l)), n.position.y = 0, t.push(n);
  3065. }return t;
  3066. }, generateTilePoly: function generateTilePoly(e) {
  3067. e || (e = new THREE.MeshBasicMaterial({ color: 2405631 }));var t = new THREE.Mesh(this.cellShapeGeo, e);return this._vec3.set(1, 0, 0), t.rotateOnAxis(this._vec3, vg.PI / 2), t;
  3068. }, generate: function generate(e) {
  3069. e = e || {}, this.size = "undefined" == typeof e.size ? this.size : e.size;var t,
  3070. i,
  3071. s,
  3072. n = Math.ceil(this.size / 2);for (t = -n; n > t; t++) {
  3073. for (i = -n; n > i; i++) {
  3074. s = new vg.Cell(t, i + 1), this.add(s);
  3075. }
  3076. }
  3077. }, generateOverlay: function generateOverlay(e, t, i) {
  3078. var s,
  3079. n,
  3080. l = Math.ceil(e / 2);for (s = -l; l > s; s++) {
  3081. for (n = -l; l > n; n++) {
  3082. this._cel.set(s, n);var r = new THREE.Line(this.cellGeo, i);r.position.copy(this.cellToPixel(this._cel)), r.rotation.x = 90 * vg.DEG_TO_RAD, t.add(r);
  3083. }
  3084. }
  3085. }, add: function add(e) {
  3086. var t = this.cellToHash(e);if (!this.cells[t]) return this.cells[t] = e, this.numCells++, e;
  3087. }, remove: function remove(e) {
  3088. var t = this.cellToHash(e);this.cells[t] && (delete this.cells[t], this.numCells--);
  3089. }, dispose: function dispose() {
  3090. this.cells = null, this.numCells = 0, this.cellShape = null, this.cellGeo.dispose(), this.cellGeo = null, this.cellShapeGeo.dispose(), this.cellShapeGeo = null, this._list = null, this._vec3 = null, this._conversionVec = null, this._geoCache = null, this._matCache = null;
  3091. }, load: function load(e, t, i) {
  3092. vg.Tools.getJSON({ url: e, callback: function callback(e) {
  3093. this.fromJSON(e), t.call(i || null, e);
  3094. }, cache: !1, scope: this });
  3095. }, fromJSON: function fromJSON(e) {
  3096. var t,
  3097. i,
  3098. s = e.cells;for (this.cells = {}, this.numCells = 0, this.size = e.size, this.cellSize = e.cellSize, this._fullCellSize = 2 * this.cellSize, this.extrudeSettings = e.extrudeSettings, this.autogenerated = e.autogenerated, t = 0; t < s.length; t++) {
  3099. i = new vg.Cell(), i.copy(s[t]), this.add(i);
  3100. }
  3101. }, toJSON: function toJSON() {
  3102. var e,
  3103. t,
  3104. i = { size: this.size, cellSize: this.cellSize, extrudeSettings: this.extrudeSettings, autogenerated: this.autogenerated },
  3105. s = [];for (t in this.cells) {
  3106. e = this.cells[t], s.push({ q: e.q, r: e.r, s: e.s, h: e.h, walkable: e.walkable, userData: e.userData });
  3107. }return i.cells = s, i;
  3108. } }, vg.SqrGrid.prototype.constructor = vg.SqrGrid, vg.Tile = function (e) {
  3109. e = e || {};var t = { cell: null, geometry: null, material: null };if (t = vg.Tools.merge(t, e), !t.cell || !t.geometry) throw new Error("Missing vg.Tile configuration");this.cell = t.cell, this.cell.tile && this.cell.tile !== this && this.cell.tile.dispose(), this.cell.tile = this, this.uniqueID = vg.Tools.generateID(), this.geometry = t.geometry, this.material = t.material, this.material || (this.material = new THREE.MeshPhongMaterial({ color: vg.Tools.randomizeRGB("30, 30, 30", 13) })), this.objectType = vg.TILE, this.entity = null, this.userData = {}, this.selected = !1, this.highlight = "0x0084cc", this.mesh = new THREE.Mesh(this.geometry, this.material), this.mesh.userData.structure = this, this.position = this.mesh.position, this.rotation = this.mesh.rotation, this.rotation.x = -90 * vg.DEG_TO_RAD, this.mesh.scale.set(t.scale, t.scale, 1), this.material.emissive ? this._emissive = this.material.emissive.getHex() : this._emissive = null;
  3110. }, vg.Tile.prototype = { select: function select() {
  3111. return this.material.emissive && this.material.emissive.setHex(this.highlight), this.selected = !0, this;
  3112. }, deselect: function deselect() {
  3113. return null !== this._emissive && this.material.emissive && this.material.emissive.setHex(this._emissive), this.selected = !1, this;
  3114. }, toggle: function toggle() {
  3115. return this.selected ? this.deselect() : this.select(), this;
  3116. }, dispose: function dispose() {
  3117. this.cell && this.cell.tile && (this.cell.tile = null), this.cell = null, this.position = null, this.rotation = null, this.mesh.parent && this.mesh.parent.remove(this.mesh), this.mesh.userData.structure = null, this.mesh = null, this.material = null, this.userData = null, this.entity = null, this.geometry = null, this._emissive = null;
  3118. } }, vg.Tile.prototype.constructor = vg.Tile, function () {
  3119. var e = function e() {
  3120. this.obj = null, this.next = null, this.prev = null, this.free = !0;
  3121. },
  3122. t = function t() {
  3123. this.first = null, this.last = null, this.length = 0, this.objToNodeMap = {}, this.uniqueID = Date.now() + "" + Math.floor(1e3 * Math.random()), this.sortArray = [];
  3124. };t.generateID = function () {
  3125. return Math.random().toString(36).slice(2) + Date.now();
  3126. }, t.prototype = { getNode: function getNode(e) {
  3127. return this.objToNodeMap[e.uniqueID];
  3128. }, addNode: function addNode(i) {
  3129. var s = new e();if (!i.uniqueID) try {
  3130. i.uniqueID = t.generateID();
  3131. } catch (n) {
  3132. return console.error("[LinkedList.addNode] obj passed is immutable: cannot attach necessary identifier"), null;
  3133. }return s.obj = i, s.free = !1, this.objToNodeMap[i.uniqueID] = s, s;
  3134. }, swapObjects: function swapObjects(e, t) {
  3135. this.objToNodeMap[e.obj.uniqueID] = null, this.objToNodeMap[t.uniqueID] = e, e.obj = t;
  3136. }, add: function add(e) {
  3137. var t = this.objToNodeMap[e.uniqueID];if (t) {
  3138. if (t.free === !1) return;t.obj = e, t.free = !1, t.next = null, t.prev = null;
  3139. } else t = this.addNode(e);if (this.first) {
  3140. if (!this.last) throw new Error("[LinkedList.add] No last in the list -- that shouldn't happen here");this.last.next = t, t.prev = this.last, this.last = t, t.next = null;
  3141. } else this.first = t, this.last = t, t.next = null, t.prev = null;this.length++, this.showDebug && this.dump("after add");
  3142. }, has: function has(e) {
  3143. return !!this.objToNodeMap[e.uniqueID];
  3144. }, moveUp: function moveUp(e) {
  3145. this.dump("before move up");var t = this.getNode(e);if (!t) throw "Oops, trying to move an object that isn't in the list";if (t.prev) {
  3146. var i = t.prev,
  3147. s = i.prev;t == this.last && (this.last = i);var n = t.next;s && (s.next = t), t.next = i, t.prev = i.prev, i.next = n, i.prev = t, this.first == i && (this.first = t);
  3148. }
  3149. }, moveDown: function moveDown(e) {
  3150. var t = this.getNode(e);if (!t) throw "Oops, trying to move an object that isn't in the list";if (t.next) {
  3151. var i = t.next;this.moveUp(i.obj), this.last == i && (this.last = t);
  3152. }
  3153. }, sort: function sort(e) {
  3154. var t,
  3155. i,
  3156. s = this.sortArray,
  3157. n = this.first;for (s.length = 0; n;) {
  3158. s.push(n.obj), n = n.next;
  3159. }for (this.clear(), s.sort(e), i = s.length, t = 0; i > t; t++) {
  3160. this.add(s[t]);
  3161. }
  3162. }, remove: function remove(e) {
  3163. var t = this.getNode(e);return !t || t.free ? !1 : (t.prev && (t.prev.next = t.next), t.next && (t.next.prev = t.prev), t.prev || (this.first = t.next), t.next || (this.last = t.prev), t.free = !0, t.prev = null, t.next = null, this.length--, !0);
  3164. }, shift: function shift() {
  3165. var e = this.first;return 0 === this.length ? null : (e.prev && (e.prev.next = e.next), e.next && (e.next.prev = e.prev), this.first = e.next, e.next || (this.last = null), e.free = !0, e.prev = null, e.next = null, this.length--, e.obj);
  3166. }, pop: function pop() {
  3167. var e = this.last;return 0 === this.length ? null : (e.prev && (e.prev.next = e.next), e.next && (e.next.prev = e.prev), this.last = e.prev, e.prev || (this.first = null), e.free = !0, e.prev = null, e.next = null, this.length--, e.obj);
  3168. }, concat: function concat(e) {
  3169. for (var t = e.first; t;) {
  3170. this.add(t.obj), t = t.next;
  3171. }
  3172. }, clear: function clear() {
  3173. for (var e = this.first; e;) {
  3174. e.free = !0, e = e.next;
  3175. }this.first = null, this.length = 0;
  3176. }, dispose: function dispose() {
  3177. for (var e = this.first; e;) {
  3178. e.obj = null, e = e.next;
  3179. }this.first = null, this.objToNodeMap = null;
  3180. }, dump: function dump(e) {
  3181. console.log("====================" + e + "=====================");for (var t = this.first; t;) {
  3182. console.log("{" + t.obj.toString() + "} previous=" + (t.prev ? t.prev.obj : "NULL")), t = t.next();
  3183. }console.log("==================================="), console.log("Last: {" + (this.last ? this.last.obj : "NULL") + "} First: {" + (this.first ? this.first.obj : "NULL") + "}");
  3184. } }, t.prototype.constructor = t, vg.LinkedList = t;
  3185. }(), function () {
  3186. var e = function e(_e, t, i, s, n) {
  3187. this._listener = t, this.isOnce = i, this.context = s, this.signal = _e, this._priority = n || 0;
  3188. };e.prototype = { active: !0, params: null, execute: function execute(e) {
  3189. var t, i;return this.active && this._listener && (i = this.params ? this.params.concat(e) : e, t = this._listener.apply(this.context, i), this.isOnce && this.detach()), t;
  3190. }, detach: function detach() {
  3191. return this.isBound() ? this.signal.remove(this._listener, this.context) : null;
  3192. }, isBound: function isBound() {
  3193. return !!this.signal && !!this._listener;
  3194. }, _destroy: function _destroy() {
  3195. delete this.signal, delete this._listener, delete this.context;
  3196. }, toString: function toString() {
  3197. return "[SignalBinding isOnce:" + this.isOnce + ", isBound:" + this.isBound() + ", active:" + this.active + "]";
  3198. } }, e.prototype.constructor = e;var t = function t() {
  3199. this._bindings = [], this._prevParams = null;var e = this;this.dispatch = function () {
  3200. t.prototype.dispatch.apply(e, arguments);
  3201. };
  3202. };t.prototype = { memorize: !1, _shouldPropagate: !0, active: !0, validateListener: function validateListener(e, t) {
  3203. if ("function" != typeof e) throw new Error("Signal: listener is a required param of {fn}() and should be a Function.".replace("{fn}", t));
  3204. }, _registerListener: function _registerListener(t, i, s, n) {
  3205. var l,
  3206. r = this._indexOfListener(t, s);if (-1 !== r) {
  3207. if (l = this._bindings[r], l.isOnce !== i) throw new Error("You cannot add" + (i ? "" : "Once") + "() then add" + (i ? "Once" : "") + "() the same listener without removing the relationship first.");
  3208. } else l = new e(this, t, i, s, n), this._addBinding(l);return this.memorize && this._prevParams && l.execute(this._prevParams), l;
  3209. }, _addBinding: function _addBinding(e) {
  3210. var t = this._bindings.length;do {
  3211. t--;
  3212. } while (this._bindings[t] && e._priority <= this._bindings[t]._priority);this._bindings.splice(t + 1, 0, e);
  3213. }, _indexOfListener: function _indexOfListener(e, t) {
  3214. for (var i, s = this._bindings.length; s--;) {
  3215. if (i = this._bindings[s], i._listener === e && i.context === t) return s;
  3216. }return -1;
  3217. }, has: function has(e, t) {
  3218. return -1 !== this._indexOfListener(e, t);
  3219. }, add: function add(e, t, i) {
  3220. return this.validateListener(e, "add"), this._registerListener(e, !1, t, i);
  3221. }, addOnce: function addOnce(e, t, i) {
  3222. return this.validateListener(e, "addOnce"), this._registerListener(e, !0, t, i);
  3223. }, remove: function remove(e, t) {
  3224. this.validateListener(e, "remove");var i = this._indexOfListener(e, t);return -1 !== i && (this._bindings[i]._destroy(), this._bindings.splice(i, 1)), e;
  3225. }, removeAll: function removeAll(e) {
  3226. "undefined" == typeof e && (e = null);for (var t = this._bindings.length; t--;) {
  3227. e ? this._bindings[t].context === e && (this._bindings[t]._destroy(), this._bindings.splice(t, 1)) : this._bindings[t]._destroy();
  3228. }e || (this._bindings.length = 0);
  3229. }, getNumListeners: function getNumListeners() {
  3230. return this._bindings.length;
  3231. }, halt: function halt() {
  3232. this._shouldPropagate = !1;
  3233. }, dispatch: function dispatch() {
  3234. if (this.active) {
  3235. var e,
  3236. t = Array.prototype.slice.call(arguments),
  3237. i = this._bindings.length;if (this.memorize && (this._prevParams = t), i) {
  3238. e = this._bindings.slice(), this._shouldPropagate = !0;do {
  3239. i--;
  3240. } while (e[i] && this._shouldPropagate && e[i].execute(t) !== !1);
  3241. }
  3242. }
  3243. }, forget: function forget() {
  3244. this._prevParams = null;
  3245. }, dispose: function dispose() {
  3246. this.removeAll(), delete this._bindings, delete this._prevParams;
  3247. }, toString: function toString() {
  3248. return "[Signal active:" + this.active + " numListeners:" + this.getNumListeners() + "]";
  3249. } }, t.prototype.constructor = t, vg.Signal = t;
  3250. }(), vg.AStarFinder = function (e) {
  3251. e = e || {};var t = { allowDiagonal: !1, heuristicFilter: null };t = vg.Tools.merge(t, e), this.allowDiagonal = t.allowDiagonal, this.heuristicFilter = t.heuristicFilter, this.list = new vg.LinkedList();
  3252. }, vg.AStarFinder.prototype = { findPath: function findPath(e, t, i, s) {
  3253. var n, l, r, h, o, a;for (i = i || this.heuristicFilter, s.clearPath(), this.list.clear(), this.list.add(e); this.list.length > 0;) {
  3254. if (this.list.sort(this.compare), n = this.list.shift(), n._visited = !0, n === t) return vg.PathUtil.backtrace(t);for (r = s.getNeighbors(n, this.allowDiagonal, i), o = 0, a = r.length; a > o; o++) {
  3255. if (h = r[o], h.walkable && (l = n._calcCost + s.distance(n, h), !h._visited || l < h._calcCost)) {
  3256. if (h._visited = !0, h._parent = n, h._calcCost = l, h._priority = l + s.distance(t, h), h === t) return vg.PathUtil.backtrace(t);this.list.add(h);
  3257. }
  3258. }
  3259. }return null;
  3260. }, compare: function compare(e, t) {
  3261. return e._priority - t._priority;
  3262. } }, vg.AStarFinder.prototype.constructor = vg.AStarFinder, vg.PathUtil = { backtrace: function backtrace(e) {
  3263. for (var t = [e]; e._parent;) {
  3264. e = e._parent, t.push(e);
  3265. }return t.reverse();
  3266. }, biBacktrace: function biBacktrace(e, t) {
  3267. var i = this.backtrace(e),
  3268. s = this.backtrace(t);return i.concat(s.reverse());
  3269. }, pathLength: function pathLength(e) {
  3270. var t,
  3271. i,
  3272. s,
  3273. n,
  3274. l,
  3275. r = 0;for (t = 1; t < e.length; ++t) {
  3276. i = e[t - 1], s = e[t], n = i[0] - s[0], l = i[1] - s[1], r += Math.sqrt(n * n + l * l);
  3277. }return r;
  3278. }, interpolate: function interpolate(e, t, i, s) {
  3279. var n,
  3280. l,
  3281. r,
  3282. h,
  3283. o,
  3284. a,
  3285. c = Math.abs,
  3286. u = [];for (r = c(i - e), h = c(s - t), n = i > e ? 1 : -1, l = s > t ? 1 : -1, o = r - h; e !== i || t !== s;) {
  3287. u.push([e, t]), a = 2 * o, a > -h && (o -= h, e += n), r > a && (o += r, t += l);
  3288. }return u;
  3289. }, expandPath: function expandPath(e) {
  3290. var t,
  3291. i,
  3292. s,
  3293. n,
  3294. l,
  3295. r,
  3296. h = [],
  3297. o = e.length;if (2 > o) return h;for (l = 0; o - 1 > l; ++l) {
  3298. for (t = e[l], i = e[l + 1], s = this.interpolate(t[0], t[1], i[0], i[1]), n = s.length, r = 0; n - 1 > r; ++r) {
  3299. h.push(s[r]);
  3300. }
  3301. }return h.push(e[o - 1]), h;
  3302. }, smoothenPath: function smoothenPath(e, t) {
  3303. var i,
  3304. s,
  3305. n,
  3306. l,
  3307. r,
  3308. h,
  3309. o,
  3310. a,
  3311. c,
  3312. u,
  3313. d,
  3314. g,
  3315. p = t.length,
  3316. v = t[0][0],
  3317. f = t[0][1],
  3318. m = t[p - 1][0],
  3319. _ = t[p - 1][1];for (i = v, s = f, r = [[i, s]], o = 2; p > o; ++o) {
  3320. for (c = t[o], n = c[0], l = c[1], u = this.interpolate(i, s, n, l), g = !1, a = 1; a < u.length; ++a) {
  3321. if (d = u[a], !e.isWalkableAt(d[0], d[1])) {
  3322. g = !0;break;
  3323. }
  3324. }g && (h = t[o - 1], r.push(h), i = h[0], s = h[1]);
  3325. }return r.push([m, _]), r;
  3326. }, compressPath: function compressPath(e) {
  3327. if (e.length < 3) return e;var t,
  3328. i,
  3329. s,
  3330. n,
  3331. l,
  3332. r,
  3333. h = [],
  3334. o = e[0][0],
  3335. a = e[0][1],
  3336. c = e[1][0],
  3337. u = e[1][1],
  3338. d = c - o,
  3339. g = u - a;for (l = Math.sqrt(d * d + g * g), d /= l, g /= l, h.push([o, a]), r = 2; r < e.length; r++) {
  3340. t = c, i = u, s = d, n = g, c = e[r][0], u = e[r][1], d = c - t, g = u - i, l = Math.sqrt(d * d + g * g), d /= l, g /= l, (d !== s || g !== n) && h.push([t, i]);
  3341. }return h.push([c, u]), h;
  3342. } }, vg.Loader = { manager: null, imageLoader: null, crossOrigin: !1, init: function init(e) {
  3343. this.crossOrigin = e || !1, this.manager = new THREE.LoadingManager(function () {}, function () {}, function () {
  3344. console.warn("Error loading images");
  3345. }), this.imageLoader = new THREE.ImageLoader(this.manager), this.imageLoader.crossOrigin = e;
  3346. }, loadTexture: function loadTexture(e, t, i, s) {
  3347. var n = new THREE.Texture(null, t);return this.imageLoader.load(e, function (e) {
  3348. n.image = e, n.needsUpdate = !0, i && i(n);
  3349. }, null, function (e) {
  3350. s && s(e);
  3351. }), n.sourceFile = e, n;
  3352. } }, vg.MouseCaster = function (e, t, i) {
  3353. this.down = !1, this.rightDown = !1, this.pickedObject = null, this.selectedObject = null, this.allHits = null, this.active = !0, this.shift = !1, this.ctrl = !1, this.wheel = 0, this.position = new THREE.Vector3(), this.screenPosition = new THREE.Vector2(), this.signal = new vg.Signal(), this.group = e, this._camera = t, this._raycaster = new THREE.Raycaster(), this._preventDefault = !1, i = i || document, i.addEventListener("mousemove", this._onDocumentMouseMove.bind(this), !1), i.addEventListener("mousedown", this._onDocumentMouseDown.bind(this), !1), i.addEventListener("mouseup", this._onDocumentMouseUp.bind(this), !1), i.addEventListener("mousewheel", this._onMouseWheel.bind(this), !1), i.addEventListener("DOMMouseScroll", this._onMouseWheel.bind(this), !1);
  3354. }, vg.MouseCaster.OVER = "over", vg.MouseCaster.OUT = "out", vg.MouseCaster.DOWN = "down", vg.MouseCaster.UP = "up", vg.MouseCaster.CLICK = "click", vg.MouseCaster.WHEEL = "wheel", vg.MouseCaster.prototype = { update: function update() {
  3355. if (this.active) {
  3356. this._raycaster.setFromCamera(this.screenPosition, this._camera);var e,
  3357. t,
  3358. i = this._raycaster.intersectObject(this.group, !0);i.length > 0 ? (e = i[0], t = e.object.userData.structure, this.pickedObject != t && (this.pickedObject && this.signal.dispatch(vg.MouseCaster.OUT, this.pickedObject), this.pickedObject = t, this.selectedObject = null, this.signal.dispatch(vg.MouseCaster.OVER, this.pickedObject)), this.position.copy(e.point), this.screenPosition.z = e.distance) : (this.pickedObject && this.signal.dispatch(vg.MouseCaster.OUT, this.pickedObject), this.pickedObject = null, this.selectedObject = null), this.allHits = i;
  3359. }
  3360. }, preventDefault: function preventDefault() {
  3361. this._preventDefault = !0;
  3362. }, _onDocumentMouseDown: function _onDocumentMouseDown(e) {
  3363. return e = e || window.event, e.preventDefault(), this._preventDefault ? (this._preventDefault = !1, !1) : (this.pickedObject && (this.selectedObject = this.pickedObject), this.shift = e.shiftKey, this.ctrl = e.ctrlKey, this.down = 1 === e.which, this.rightDown = 3 === e.which, void this.signal.dispatch(vg.MouseCaster.DOWN, this.pickedObject));
  3364. }, _onDocumentMouseUp: function _onDocumentMouseUp(e) {
  3365. return e.preventDefault(), this._preventDefault ? (this._preventDefault = !1, !1) : (this.shift = e.shiftKey, this.ctrl = e.ctrlKey, this.signal.dispatch(vg.MouseCaster.UP, this.pickedObject), this.selectedObject && this.pickedObject && this.selectedObject.uniqueID === this.pickedObject.uniqueID && this.signal.dispatch(vg.MouseCaster.CLICK, this.pickedObject), this.down = 1 === e.which ? !1 : this.down, void (this.rightDown = 3 === e.which ? !1 : this.rightDown));
  3366. }, _onDocumentMouseMove: function _onDocumentMouseMove(e) {
  3367. e.preventDefault(), this.screenPosition.x = e.clientX / window.innerWidth * 2 - 1, this.screenPosition.y = 2 * -(e.clientY / window.innerHeight) + 1;
  3368. }, _onMouseWheel: function _onMouseWheel(e) {
  3369. if (this.active) {
  3370. e.preventDefault(), e.stopPropagation();var t = 0;void 0 !== e.wheelDelta ? t = e.wheelDelta : void 0 !== e.detail && (t = -e.detail), t > 0 ? this.wheel++ : this.wheel--, this.signal.dispatch(vg.MouseCaster.WHEEL, this.wheel);
  3371. }
  3372. } }, vg.MouseCaster.prototype.constructor = vg.MouseCaster, vg.Scene = function (e, t) {
  3373. var i = { element: document.body, alpha: !0, antialias: !0, clearColor: "#fff", sortObjects: !1, fog: null, light: new THREE.DirectionalLight(16777215), lightPosition: null, cameraType: "PerspectiveCamera", cameraPosition: null, orthoZoom: 4 },
  3374. s = { minDistance: 100, maxDistance: 1e3, zoomSpeed: 2, noZoom: !1 };if (i = vg.Tools.merge(i, e), "boolean" != typeof t && (s = vg.Tools.merge(s, t)), this.renderer = new THREE.WebGLRenderer({ alpha: i.alpha, antialias: i.antialias }), this.renderer.setClearColor(i.clearColor, 0), this.renderer.sortObjects = i.sortObjects, this.width = window.innerWidth, this.height = window.innerHeight, this.orthoZoom = i.orthoZoom, this.container = new THREE.Scene(), this.container.fog = i.fog, this.container.add(new THREE.AmbientLight(14540253)), i.lightPosition || i.light.position.set(-1, 1, -1).normalize(), this.container.add(i.light), "OrthographicCamera" === i.cameraType) {
  3375. var n = window.innerWidth / this.orthoZoom,
  3376. l = window.innerHeight / this.orthoZoom;this.camera = new THREE.OrthographicCamera(n / -2, n / 2, l / 2, l / -2, 1, 5e3);
  3377. } else this.camera = new THREE.PerspectiveCamera(50, this.width / this.height, 1, 5e3);this.contolled = !!t, this.contolled && (this.controls = new THREE.OrbitControls(this.camera, this.renderer.domElement), this.controls.minDistance = s.minDistance, this.controls.maxDistance = s.maxDistance, this.controls.zoomSpeed = s.zoomSpeed, this.controls.noZoom = s.noZoom), i.cameraPosition && this.camera.position.copy(i.cameraPosition), window.addEventListener("resize", function () {
  3378. if (this.width = window.innerWidth, this.height = window.innerHeight, "OrthographicCamera" === this.camera.type) {
  3379. var e = this.width / this.orthoZoom,
  3380. t = this.height / this.orthoZoom;this.camera.left = e / -2, this.camera.right = e / 2, this.camera.top = t / 2, this.camera.bottom = t / -2;
  3381. } else this.camera.aspect = this.width / this.height;this.camera.updateProjectionMatrix(), this.renderer.setSize(this.width, this.height);
  3382. }.bind(this), !1), this.attachTo(i.element);
  3383. }, vg.Scene.prototype = { attachTo: function attachTo(e) {
  3384. e.style.width = this.width + "px", e.style.height = this.height + "px", this.renderer.setPixelRatio(window.devicePixelRatio), this.renderer.setSize(this.width, this.height), e.appendChild(this.renderer.domElement);
  3385. }, add: function add(e) {
  3386. this.container.add(e);
  3387. }, remove: function remove(e) {
  3388. this.container.remove(e);
  3389. }, render: function render() {
  3390. this.contolled && this.controls.update(), this.renderer.render(this.container, this.camera);
  3391. }, updateOrthoZoom: function updateOrthoZoom() {
  3392. if (this.orthoZoom <= 0) return void (this.orthoZoom = 0);var e = this.width / this.orthoZoom,
  3393. t = this.height / this.orthoZoom;this.camera.left = e / -2, this.camera.right = e / 2, this.camera.top = t / 2, this.camera.bottom = t / -2, this.camera.updateProjectionMatrix();
  3394. }, focusOn: function focusOn(e) {
  3395. this.camera.lookAt(e.position);
  3396. } }, vg.Scene.prototype.constructor = vg.Scene, vg.SelectionManager = function (e) {
  3397. this.mouse = e, this.onSelect = new vg.Signal(), this.onDeselect = new vg.Signal(), this.selected = null, this.toggleSelection = !1, this.mouse.signal.add(this.onMouse, this);
  3398. }, vg.SelectionManager.prototype = { select: function select(e, t) {
  3399. e && (t = t || !0, this.selected !== e && this.clearSelection(t), e.selected ? this.toggleSelection && (t && this.onDeselect.dispatch(e), e.deselect()) : e.select(), this.selected = e, t && this.onSelect.dispatch(e));
  3400. }, clearSelection: function clearSelection(e) {
  3401. e = e || !0, this.selected && (e && this.onDeselect.dispatch(this.selected), this.selected.deselect()), this.selected = null;
  3402. }, onMouse: function onMouse(e, t) {
  3403. switch (e) {case vg.MouseCaster.DOWN:
  3404. t || this.clearSelection();break;case vg.MouseCaster.CLICK:
  3405. this.select(t);}
  3406. } }, vg.SelectionManager.prototype.constructor = vg.SelectionManager, vg.Tools = { clamp: function clamp(e, t, i) {
  3407. return Math.max(t, Math.min(i, e));
  3408. }, sign: function sign(e) {
  3409. return e && e / Math.abs(e);
  3410. }, random: function random(e, t) {
  3411. return 1 === arguments.length ? Math.random() * e - .5 * e : Math.random() * (t - e) + e;
  3412. }, randomInt: function randomInt(e, t) {
  3413. return 1 === arguments.length ? Math.random() * e - .5 * e | 0 : Math.random() * (t - e + 1) + e | 0;
  3414. }, normalize: function normalize(e, t, i) {
  3415. return (e - t) / (i - t);
  3416. }, getShortRotation: function getShortRotation(e) {
  3417. return e %= this.TAU, e > this.PI ? e -= this.TAU : e < -this.PI && (e += this.TAU), e;
  3418. }, generateID: function generateID() {
  3419. return Math.random().toString(36).slice(2) + Date.now();
  3420. }, isPlainObject: function isPlainObject(e) {
  3421. if ("object" != (typeof e === "undefined" ? "undefined" : _typeof(e)) || e.nodeType || e === e.window) return !1;try {
  3422. if (e.constructor && !Object.prototype.hasOwnProperty.call(e.constructor.prototype, "isPrototypeOf")) return !1;
  3423. } catch (t) {
  3424. return !1;
  3425. }return !0;
  3426. }, merge: function merge(e, t) {
  3427. var i = this,
  3428. s = Array.isArray(t),
  3429. n = s && [] || {};return s ? (e = e || [], n = n.concat(e), t.forEach(function (t, s) {
  3430. "undefined" == typeof n[s] ? n[s] = t : i.isPlainObject(t) ? n[s] = i.merge(e[s], t) : -1 === e.indexOf(t) && n.push(t);
  3431. }), n) : (e && i.isPlainObject(e) && Object.keys(e).forEach(function (t) {
  3432. n[t] = e[t];
  3433. }), Object.keys(t).forEach(function (s) {
  3434. t[s] && i.isPlainObject(t[s]) && e[s] ? n[s] = i.merge(e[s], t[s]) : n[s] = t[s];
  3435. }), n);
  3436. }, now: function now() {
  3437. return window.nwf ? window.nwf.system.Performance.elapsedTime : window.performance.now();
  3438. }, empty: function empty(e) {
  3439. for (; e.lastChild;) {
  3440. e.removeChild(e.lastChild);
  3441. }
  3442. }, radixSort: function radixSort(e, t, i, s) {
  3443. if (t = t || 0, i = i || e.length, s = s || 31, !(t >= i - 1 || 0 > s)) {
  3444. for (var n = t, l = i, r = 1 << s; l > n;) {
  3445. if (e[n] & r) {
  3446. --l;var h = e[n];e[n] = e[l], e[l] = h;
  3447. } else ++n;
  3448. }this.radixSort(e, t, l, s - 1), this.radixSort(e, l, i, s - 1);
  3449. }
  3450. }, randomizeRGB: function randomizeRGB(e, t) {
  3451. var i,
  3452. s,
  3453. n = e.split(","),
  3454. l = "rgb(";for (t = this.randomInt(t), i = 0; 3 > i; i++) {
  3455. s = parseInt(n[i]) + t, 0 > s ? s = 0 : s > 255 && (s = 255), l += s + ",";
  3456. }return l = l.substring(0, l.length - 1), l += ")";
  3457. }, getJSON: function getJSON(e) {
  3458. var t = new XMLHttpRequest(),
  3459. i = "undefined" == typeof e.cache ? !1 : e.cache,
  3460. s = i ? e.url : e.url + "?t=" + Math.floor(1e4 * Math.random()) + Date.now();t.onreadystatechange = function () {
  3461. if (200 === this.status) {
  3462. var t = null;try {
  3463. t = JSON.parse(this.responseText);
  3464. } catch (i) {
  3465. return;
  3466. }return void e.callback.call(e.scope || null, t);
  3467. }0 !== this.status && console.warn("[Tools.getJSON] Error: " + this.status + " (" + this.statusText + ") :: " + e.url);
  3468. }, t.open("GET", s, !0), t.setRequestHeader("Accept", "application/json"), t.setRequestHeader("Content-Type", "application/json"), t.send("");
  3469. } };
  3470. },{}],10:[function(require,module,exports){
  3471. 'use strict';
  3472. /**
  3473. * Polyfill for the additional KeyboardEvent properties defined in the D3E and
  3474. * D4E draft specifications, by @inexorabletash.
  3475. *
  3476. * See: https://github.com/inexorabletash/polyfill
  3477. */
  3478. (function (global) {
  3479. var nativeKeyboardEvent = 'KeyboardEvent' in global;
  3480. if (!nativeKeyboardEvent) global.KeyboardEvent = function KeyboardEvent() {
  3481. throw TypeError('Illegal constructor');
  3482. };
  3483. if (!('DOM_KEY_LOCATION_STANDARD' in global.KeyboardEvent)) global.KeyboardEvent.DOM_KEY_LOCATION_STANDARD = 0x00; // Default or unknown location
  3484. if (!('DOM_KEY_LOCATION_LEFT' in global.KeyboardEvent)) global.KeyboardEvent.DOM_KEY_LOCATION_LEFT = 0x01; // e.g. Left Alt key
  3485. if (!('DOM_KEY_LOCATION_RIGHT' in global.KeyboardEvent)) global.KeyboardEvent.DOM_KEY_LOCATION_RIGHT = 0x02; // e.g. Right Alt key
  3486. if (!('DOM_KEY_LOCATION_NUMPAD' in global.KeyboardEvent)) global.KeyboardEvent.DOM_KEY_LOCATION_NUMPAD = 0x03; // e.g. Numpad 0 or +
  3487. var STANDARD = window.KeyboardEvent.DOM_KEY_LOCATION_STANDARD,
  3488. LEFT = window.KeyboardEvent.DOM_KEY_LOCATION_LEFT,
  3489. RIGHT = window.KeyboardEvent.DOM_KEY_LOCATION_RIGHT,
  3490. NUMPAD = window.KeyboardEvent.DOM_KEY_LOCATION_NUMPAD;
  3491. //--------------------------------------------------------------------
  3492. //
  3493. // Utilities
  3494. //
  3495. //--------------------------------------------------------------------
  3496. function contains(s, ss) {
  3497. return String(s).indexOf(ss) !== -1;
  3498. }
  3499. var os = function () {
  3500. if (contains(navigator.platform, 'Win')) {
  3501. return 'win';
  3502. }
  3503. if (contains(navigator.platform, 'Mac')) {
  3504. return 'mac';
  3505. }
  3506. if (contains(navigator.platform, 'CrOS')) {
  3507. return 'cros';
  3508. }
  3509. if (contains(navigator.platform, 'Linux')) {
  3510. return 'linux';
  3511. }
  3512. if (contains(navigator.userAgent, 'iPad') || contains(navigator.platform, 'iPod') || contains(navigator.platform, 'iPhone')) {
  3513. return 'ios';
  3514. }
  3515. return '';
  3516. }();
  3517. var browser = function () {
  3518. if (contains(navigator.userAgent, 'Chrome/')) {
  3519. return 'chrome';
  3520. }
  3521. if (contains(navigator.vendor, 'Apple')) {
  3522. return 'safari';
  3523. }
  3524. if (contains(navigator.userAgent, 'MSIE')) {
  3525. return 'ie';
  3526. }
  3527. if (contains(navigator.userAgent, 'Gecko/')) {
  3528. return 'moz';
  3529. }
  3530. if (contains(navigator.userAgent, 'Opera/')) {
  3531. return 'opera';
  3532. }
  3533. return '';
  3534. }();
  3535. var browser_os = browser + '-' + os;
  3536. function mergeIf(baseTable, select, table) {
  3537. if (browser_os === select || browser === select || os === select) {
  3538. Object.keys(table).forEach(function (keyCode) {
  3539. baseTable[keyCode] = table[keyCode];
  3540. });
  3541. }
  3542. }
  3543. function remap(o, key) {
  3544. var r = {};
  3545. Object.keys(o).forEach(function (k) {
  3546. var item = o[k];
  3547. if (key in item) {
  3548. r[item[key]] = item;
  3549. }
  3550. });
  3551. return r;
  3552. }
  3553. function invert(o) {
  3554. var r = {};
  3555. Object.keys(o).forEach(function (k) {
  3556. r[o[k]] = k;
  3557. });
  3558. return r;
  3559. }
  3560. //--------------------------------------------------------------------
  3561. //
  3562. // Generic Mappings
  3563. //
  3564. //--------------------------------------------------------------------
  3565. // "keyInfo" is a dictionary:
  3566. // code: string - name from DOM Level 3 KeyboardEvent code Values
  3567. // https://dvcs.w3.org/hg/dom3events/raw-file/tip/html/DOM3Events-code.html
  3568. // location (optional): number - one of the DOM_KEY_LOCATION values
  3569. // keyCap (optional): string - keyboard label in en-US locale
  3570. // USB code Usage ID from page 0x07 unless otherwise noted (Informative)
  3571. // Map of keyCode to keyInfo
  3572. var keyCodeToInfoTable = {
  3573. // 0x01 - VK_LBUTTON
  3574. // 0x02 - VK_RBUTTON
  3575. 0x03: { code: 'Cancel' }, // [USB: 0x9b] char \x0018 ??? (Not in D3E)
  3576. // 0x04 - VK_MBUTTON
  3577. // 0x05 - VK_XBUTTON1
  3578. // 0x06 - VK_XBUTTON2
  3579. 0x06: { code: 'Help' }, // [USB: 0x75] ???
  3580. // 0x07 - undefined
  3581. 0x08: { code: 'Backspace' }, // [USB: 0x2a] Labelled Delete on Macintosh keyboards.
  3582. 0x09: { code: 'Tab' }, // [USB: 0x2b]
  3583. // 0x0A-0x0B - reserved
  3584. 0X0C: { code: 'Clear' }, // [USB: 0x9c] NumPad Center (Not in D3E)
  3585. 0X0D: { code: 'Enter' }, // [USB: 0x28]
  3586. // 0x0E-0x0F - undefined
  3587. 0x10: { code: 'Shift' },
  3588. 0x11: { code: 'Control' },
  3589. 0x12: { code: 'Alt' },
  3590. 0x13: { code: 'Pause' }, // [USB: 0x48]
  3591. 0x14: { code: 'CapsLock' }, // [USB: 0x39]
  3592. 0x15: { code: 'KanaMode' }, // [USB: 0x88] - "HangulMode" for Korean layout
  3593. 0x16: { code: 'HangulMode' }, // [USB: 0x90] 0x15 as well in MSDN VK table ???
  3594. 0x17: { code: 'JunjaMode' }, // (Not in D3E)
  3595. 0x18: { code: 'FinalMode' }, // (Not in D3E)
  3596. 0x19: { code: 'KanjiMode' }, // [USB: 0x91] - "HanjaMode" for Korean layout
  3597. // 0x1A - undefined
  3598. 0x1B: { code: 'Escape' }, // [USB: 0x29]
  3599. 0x1C: { code: 'Convert' }, // [USB: 0x8a]
  3600. 0x1D: { code: 'NonConvert' }, // [USB: 0x8b]
  3601. 0x1E: { code: 'Accept' }, // (Not in D3E)
  3602. 0x1F: { code: 'ModeChange' }, // (Not in D3E)
  3603. 0x20: { code: 'Space' }, // [USB: 0x2c]
  3604. 0x21: { code: 'PageUp' }, // [USB: 0x4b]
  3605. 0x22: { code: 'PageDown' }, // [USB: 0x4e]
  3606. 0x23: { code: 'End' }, // [USB: 0x4d]
  3607. 0x24: { code: 'Home' }, // [USB: 0x4a]
  3608. 0x25: { code: 'ArrowLeft' }, // [USB: 0x50]
  3609. 0x26: { code: 'ArrowUp' }, // [USB: 0x52]
  3610. 0x27: { code: 'ArrowRight' }, // [USB: 0x4f]
  3611. 0x28: { code: 'ArrowDown' }, // [USB: 0x51]
  3612. 0x29: { code: 'Select' }, // (Not in D3E)
  3613. 0x2A: { code: 'Print' }, // (Not in D3E)
  3614. 0x2B: { code: 'Execute' }, // [USB: 0x74] (Not in D3E)
  3615. 0x2C: { code: 'PrintScreen' }, // [USB: 0x46]
  3616. 0x2D: { code: 'Insert' }, // [USB: 0x49]
  3617. 0x2E: { code: 'Delete' }, // [USB: 0x4c]
  3618. 0x2F: { code: 'Help' }, // [USB: 0x75] ???
  3619. 0x30: { code: 'Digit0', keyCap: '0' }, // [USB: 0x27] 0)
  3620. 0x31: { code: 'Digit1', keyCap: '1' }, // [USB: 0x1e] 1!
  3621. 0x32: { code: 'Digit2', keyCap: '2' }, // [USB: 0x1f] 2@
  3622. 0x33: { code: 'Digit3', keyCap: '3' }, // [USB: 0x20] 3#
  3623. 0x34: { code: 'Digit4', keyCap: '4' }, // [USB: 0x21] 4$
  3624. 0x35: { code: 'Digit5', keyCap: '5' }, // [USB: 0x22] 5%
  3625. 0x36: { code: 'Digit6', keyCap: '6' }, // [USB: 0x23] 6^
  3626. 0x37: { code: 'Digit7', keyCap: '7' }, // [USB: 0x24] 7&
  3627. 0x38: { code: 'Digit8', keyCap: '8' }, // [USB: 0x25] 8*
  3628. 0x39: { code: 'Digit9', keyCap: '9' }, // [USB: 0x26] 9(
  3629. // 0x3A-0x40 - undefined
  3630. 0x41: { code: 'KeyA', keyCap: 'a' }, // [USB: 0x04]
  3631. 0x42: { code: 'KeyB', keyCap: 'b' }, // [USB: 0x05]
  3632. 0x43: { code: 'KeyC', keyCap: 'c' }, // [USB: 0x06]
  3633. 0x44: { code: 'KeyD', keyCap: 'd' }, // [USB: 0x07]
  3634. 0x45: { code: 'KeyE', keyCap: 'e' }, // [USB: 0x08]
  3635. 0x46: { code: 'KeyF', keyCap: 'f' }, // [USB: 0x09]
  3636. 0x47: { code: 'KeyG', keyCap: 'g' }, // [USB: 0x0a]
  3637. 0x48: { code: 'KeyH', keyCap: 'h' }, // [USB: 0x0b]
  3638. 0x49: { code: 'KeyI', keyCap: 'i' }, // [USB: 0x0c]
  3639. 0x4A: { code: 'KeyJ', keyCap: 'j' }, // [USB: 0x0d]
  3640. 0x4B: { code: 'KeyK', keyCap: 'k' }, // [USB: 0x0e]
  3641. 0x4C: { code: 'KeyL', keyCap: 'l' }, // [USB: 0x0f]
  3642. 0x4D: { code: 'KeyM', keyCap: 'm' }, // [USB: 0x10]
  3643. 0x4E: { code: 'KeyN', keyCap: 'n' }, // [USB: 0x11]
  3644. 0x4F: { code: 'KeyO', keyCap: 'o' }, // [USB: 0x12]
  3645. 0x50: { code: 'KeyP', keyCap: 'p' }, // [USB: 0x13]
  3646. 0x51: { code: 'KeyQ', keyCap: 'q' }, // [USB: 0x14]
  3647. 0x52: { code: 'KeyR', keyCap: 'r' }, // [USB: 0x15]
  3648. 0x53: { code: 'KeyS', keyCap: 's' }, // [USB: 0x16]
  3649. 0x54: { code: 'KeyT', keyCap: 't' }, // [USB: 0x17]
  3650. 0x55: { code: 'KeyU', keyCap: 'u' }, // [USB: 0x18]
  3651. 0x56: { code: 'KeyV', keyCap: 'v' }, // [USB: 0x19]
  3652. 0x57: { code: 'KeyW', keyCap: 'w' }, // [USB: 0x1a]
  3653. 0x58: { code: 'KeyX', keyCap: 'x' }, // [USB: 0x1b]
  3654. 0x59: { code: 'KeyY', keyCap: 'y' }, // [USB: 0x1c]
  3655. 0x5A: { code: 'KeyZ', keyCap: 'z' }, // [USB: 0x1d]
  3656. 0x5B: { code: 'OSLeft', location: LEFT }, // [USB: 0xe3]
  3657. 0x5C: { code: 'OSRight', location: RIGHT }, // [USB: 0xe7]
  3658. 0x5D: { code: 'ContextMenu' }, // [USB: 0x65] Context Menu
  3659. // 0x5E - reserved
  3660. 0x5F: { code: 'Standby' }, // [USB: 0x82] Sleep
  3661. 0x60: { code: 'Numpad0', keyCap: '0', location: NUMPAD }, // [USB: 0x62]
  3662. 0x61: { code: 'Numpad1', keyCap: '1', location: NUMPAD }, // [USB: 0x59]
  3663. 0x62: { code: 'Numpad2', keyCap: '2', location: NUMPAD }, // [USB: 0x5a]
  3664. 0x63: { code: 'Numpad3', keyCap: '3', location: NUMPAD }, // [USB: 0x5b]
  3665. 0x64: { code: 'Numpad4', keyCap: '4', location: NUMPAD }, // [USB: 0x5c]
  3666. 0x65: { code: 'Numpad5', keyCap: '5', location: NUMPAD }, // [USB: 0x5d]
  3667. 0x66: { code: 'Numpad6', keyCap: '6', location: NUMPAD }, // [USB: 0x5e]
  3668. 0x67: { code: 'Numpad7', keyCap: '7', location: NUMPAD }, // [USB: 0x5f]
  3669. 0x68: { code: 'Numpad8', keyCap: '8', location: NUMPAD }, // [USB: 0x60]
  3670. 0x69: { code: 'Numpad9', keyCap: '9', location: NUMPAD }, // [USB: 0x61]
  3671. 0x6A: { code: 'NumpadMultiply', keyCap: '*', location: NUMPAD }, // [USB: 0x55]
  3672. 0x6B: { code: 'NumpadAdd', keyCap: '+', location: NUMPAD }, // [USB: 0x57]
  3673. 0x6C: { code: 'NumpadComma', keyCap: ',', location: NUMPAD }, // [USB: 0x85]
  3674. 0x6D: { code: 'NumpadSubtract', keyCap: '-', location: NUMPAD }, // [USB: 0x56]
  3675. 0x6E: { code: 'NumpadDecimal', keyCap: '.', location: NUMPAD }, // [USB: 0x63]
  3676. 0x6F: { code: 'NumpadDivide', keyCap: '/', location: NUMPAD }, // [USB: 0x54]
  3677. 0x70: { code: 'F1' }, // [USB: 0x3a]
  3678. 0x71: { code: 'F2' }, // [USB: 0x3b]
  3679. 0x72: { code: 'F3' }, // [USB: 0x3c]
  3680. 0x73: { code: 'F4' }, // [USB: 0x3d]
  3681. 0x74: { code: 'F5' }, // [USB: 0x3e]
  3682. 0x75: { code: 'F6' }, // [USB: 0x3f]
  3683. 0x76: { code: 'F7' }, // [USB: 0x40]
  3684. 0x77: { code: 'F8' }, // [USB: 0x41]
  3685. 0x78: { code: 'F9' }, // [USB: 0x42]
  3686. 0x79: { code: 'F10' }, // [USB: 0x43]
  3687. 0x7A: { code: 'F11' }, // [USB: 0x44]
  3688. 0x7B: { code: 'F12' }, // [USB: 0x45]
  3689. 0x7C: { code: 'F13' }, // [USB: 0x68]
  3690. 0x7D: { code: 'F14' }, // [USB: 0x69]
  3691. 0x7E: { code: 'F15' }, // [USB: 0x6a]
  3692. 0x7F: { code: 'F16' }, // [USB: 0x6b]
  3693. 0x80: { code: 'F17' }, // [USB: 0x6c]
  3694. 0x81: { code: 'F18' }, // [USB: 0x6d]
  3695. 0x82: { code: 'F19' }, // [USB: 0x6e]
  3696. 0x83: { code: 'F20' }, // [USB: 0x6f]
  3697. 0x84: { code: 'F21' }, // [USB: 0x70]
  3698. 0x85: { code: 'F22' }, // [USB: 0x71]
  3699. 0x86: { code: 'F23' }, // [USB: 0x72]
  3700. 0x87: { code: 'F24' }, // [USB: 0x73]
  3701. // 0x88-0x8F - unassigned
  3702. 0x90: { code: 'NumLock', location: NUMPAD }, // [USB: 0x53]
  3703. 0x91: { code: 'ScrollLock' }, // [USB: 0x47]
  3704. // 0x92-0x96 - OEM specific
  3705. // 0x97-0x9F - unassigned
  3706. // NOTE: 0xA0-0xA5 usually mapped to 0x10-0x12 in browsers
  3707. 0xA0: { code: 'ShiftLeft', location: LEFT }, // [USB: 0xe1]
  3708. 0xA1: { code: 'ShiftRight', location: RIGHT }, // [USB: 0xe5]
  3709. 0xA2: { code: 'ControlLeft', location: LEFT }, // [USB: 0xe0]
  3710. 0xA3: { code: 'ControlRight', location: RIGHT }, // [USB: 0xe4]
  3711. 0xA4: { code: 'AltLeft', location: LEFT }, // [USB: 0xe2]
  3712. 0xA5: { code: 'AltRight', location: RIGHT }, // [USB: 0xe6]
  3713. 0xA6: { code: 'BrowserBack' }, // [USB: 0x0c/0x0224]
  3714. 0xA7: { code: 'BrowserForward' }, // [USB: 0x0c/0x0225]
  3715. 0xA8: { code: 'BrowserRefresh' }, // [USB: 0x0c/0x0227]
  3716. 0xA9: { code: 'BrowserStop' }, // [USB: 0x0c/0x0226]
  3717. 0xAA: { code: 'BrowserSearch' }, // [USB: 0x0c/0x0221]
  3718. 0xAB: { code: 'BrowserFavorites' }, // [USB: 0x0c/0x0228]
  3719. 0xAC: { code: 'BrowserHome' }, // [USB: 0x0c/0x0222]
  3720. 0xAD: { code: 'VolumeMute' }, // [USB: 0x7f]
  3721. 0xAE: { code: 'VolumeDown' }, // [USB: 0x81]
  3722. 0xAF: { code: 'VolumeUp' }, // [USB: 0x80]
  3723. 0xB0: { code: 'MediaTrackNext' }, // [USB: 0x0c/0x00b5]
  3724. 0xB1: { code: 'MediaTrackPrevious' }, // [USB: 0x0c/0x00b6]
  3725. 0xB2: { code: 'MediaStop' }, // [USB: 0x0c/0x00b7]
  3726. 0xB3: { code: 'MediaPlayPause' }, // [USB: 0x0c/0x00cd]
  3727. 0xB4: { code: 'LaunchMail' }, // [USB: 0x0c/0x018a]
  3728. 0xB5: { code: 'MediaSelect' },
  3729. 0xB6: { code: 'LaunchApp1' },
  3730. 0xB7: { code: 'LaunchApp2' },
  3731. // 0xB8-0xB9 - reserved
  3732. 0xBA: { code: 'Semicolon', keyCap: ';' }, // [USB: 0x33] ;: (US Standard 101)
  3733. 0xBB: { code: 'Equal', keyCap: '=' }, // [USB: 0x2e] =+
  3734. 0xBC: { code: 'Comma', keyCap: ',' }, // [USB: 0x36] ,<
  3735. 0xBD: { code: 'Minus', keyCap: '-' }, // [USB: 0x2d] -_
  3736. 0xBE: { code: 'Period', keyCap: '.' }, // [USB: 0x37] .>
  3737. 0xBF: { code: 'Slash', keyCap: '/' }, // [USB: 0x38] /? (US Standard 101)
  3738. 0xC0: { code: 'Backquote', keyCap: '`' }, // [USB: 0x35] `~ (US Standard 101)
  3739. // 0xC1-0xCF - reserved
  3740. // 0xD0-0xD7 - reserved
  3741. // 0xD8-0xDA - unassigned
  3742. 0xDB: { code: 'BracketLeft', keyCap: '[' }, // [USB: 0x2f] [{ (US Standard 101)
  3743. 0xDC: { code: 'Backslash', keyCap: '\\' }, // [USB: 0x31] \| (US Standard 101)
  3744. 0xDD: { code: 'BracketRight', keyCap: ']' }, // [USB: 0x30] ]} (US Standard 101)
  3745. 0xDE: { code: 'Quote', keyCap: '\'' }, // [USB: 0x34] '" (US Standard 101)
  3746. // 0xDF - miscellaneous/varies
  3747. // 0xE0 - reserved
  3748. // 0xE1 - OEM specific
  3749. 0xE2: { code: 'IntlBackslash', keyCap: '\\' }, // [USB: 0x64] \| (UK Standard 102)
  3750. // 0xE3-0xE4 - OEM specific
  3751. 0xE5: { code: 'Process' }, // (Not in D3E)
  3752. // 0xE6 - OEM specific
  3753. // 0xE7 - VK_PACKET
  3754. // 0xE8 - unassigned
  3755. // 0xE9-0xEF - OEM specific
  3756. // 0xF0-0xF5 - OEM specific
  3757. 0xF6: { code: 'Attn' }, // [USB: 0x9a] (Not in D3E)
  3758. 0xF7: { code: 'CrSel' }, // [USB: 0xa3] (Not in D3E)
  3759. 0xF8: { code: 'ExSel' }, // [USB: 0xa4] (Not in D3E)
  3760. 0xF9: { code: 'EraseEof' }, // (Not in D3E)
  3761. 0xFA: { code: 'Play' }, // (Not in D3E)
  3762. 0xFB: { code: 'ZoomToggle' }, // (Not in D3E)
  3763. // 0xFC - VK_NONAME - reserved
  3764. // 0xFD - VK_PA1
  3765. 0xFE: { code: 'Clear' // [USB: 0x9c] (Not in D3E)
  3766. } };
  3767. // No legacy keyCode, but listed in D3E:
  3768. // code: usb
  3769. // 'IntlHash': 0x070032,
  3770. // 'IntlRo': 0x070087,
  3771. // 'IntlYen': 0x070089,
  3772. // 'NumpadBackspace': 0x0700bb,
  3773. // 'NumpadClear': 0x0700d8,
  3774. // 'NumpadClearEntry': 0x0700d9,
  3775. // 'NumpadMemoryAdd': 0x0700d3,
  3776. // 'NumpadMemoryClear': 0x0700d2,
  3777. // 'NumpadMemoryRecall': 0x0700d1,
  3778. // 'NumpadMemoryStore': 0x0700d0,
  3779. // 'NumpadMemorySubtract': 0x0700d4,
  3780. // 'NumpadParenLeft': 0x0700b6,
  3781. // 'NumpadParenRight': 0x0700b7,
  3782. //--------------------------------------------------------------------
  3783. //
  3784. // Browser/OS Specific Mappings
  3785. //
  3786. //--------------------------------------------------------------------
  3787. mergeIf(keyCodeToInfoTable, 'moz', {
  3788. 0x3B: { code: 'Semicolon', keyCap: ';' }, // [USB: 0x33] ;: (US Standard 101)
  3789. 0x3D: { code: 'Equal', keyCap: '=' }, // [USB: 0x2e] =+
  3790. 0x6B: { code: 'Equal', keyCap: '=' }, // [USB: 0x2e] =+
  3791. 0x6D: { code: 'Minus', keyCap: '-' }, // [USB: 0x2d] -_
  3792. 0xBB: { code: 'NumpadAdd', keyCap: '+', location: NUMPAD }, // [USB: 0x57]
  3793. 0xBD: { code: 'NumpadSubtract', keyCap: '-', location: NUMPAD // [USB: 0x56]
  3794. } });
  3795. mergeIf(keyCodeToInfoTable, 'moz-mac', {
  3796. 0x0C: { code: 'NumLock', location: NUMPAD }, // [USB: 0x53]
  3797. 0xAD: { code: 'Minus', keyCap: '-' // [USB: 0x2d] -_
  3798. } });
  3799. mergeIf(keyCodeToInfoTable, 'moz-win', {
  3800. 0xAD: { code: 'Minus', keyCap: '-' // [USB: 0x2d] -_
  3801. } });
  3802. mergeIf(keyCodeToInfoTable, 'chrome-mac', {
  3803. 0x5D: { code: 'OSRight', location: RIGHT // [USB: 0xe7]
  3804. } });
  3805. // Windows via Bootcamp (!)
  3806. if (0) {
  3807. mergeIf(keyCodeToInfoTable, 'chrome-win', {
  3808. 0xC0: { code: 'Quote', keyCap: '\'' }, // [USB: 0x34] '" (US Standard 101)
  3809. 0xDE: { code: 'Backslash', keyCap: '\\' }, // [USB: 0x31] \| (US Standard 101)
  3810. 0xDF: { code: 'Backquote', keyCap: '`' // [USB: 0x35] `~ (US Standard 101)
  3811. } });
  3812. mergeIf(keyCodeToInfoTable, 'ie', {
  3813. 0xC0: { code: 'Quote', keyCap: '\'' }, // [USB: 0x34] '" (US Standard 101)
  3814. 0xDE: { code: 'Backslash', keyCap: '\\' }, // [USB: 0x31] \| (US Standard 101)
  3815. 0xDF: { code: 'Backquote', keyCap: '`' // [USB: 0x35] `~ (US Standard 101)
  3816. } });
  3817. }
  3818. mergeIf(keyCodeToInfoTable, 'safari', {
  3819. 0x03: { code: 'Enter' }, // [USB: 0x28] old Safari
  3820. 0x19: { code: 'Tab' // [USB: 0x2b] old Safari for Shift+Tab
  3821. } });
  3822. mergeIf(keyCodeToInfoTable, 'ios', {
  3823. 0x0A: { code: 'Enter', location: STANDARD // [USB: 0x28]
  3824. } });
  3825. mergeIf(keyCodeToInfoTable, 'safari-mac', {
  3826. 0x5B: { code: 'OSLeft', location: LEFT }, // [USB: 0xe3]
  3827. 0x5D: { code: 'OSRight', location: RIGHT }, // [USB: 0xe7]
  3828. 0xE5: { code: 'KeyQ', keyCap: 'Q' // [USB: 0x14] On alternate presses, Ctrl+Q sends this
  3829. } });
  3830. //--------------------------------------------------------------------
  3831. //
  3832. // Identifier Mappings
  3833. //
  3834. //--------------------------------------------------------------------
  3835. // Cases where newer-ish browsers send keyIdentifier which can be
  3836. // used to disambiguate keys.
  3837. // keyIdentifierTable[keyIdentifier] -> keyInfo
  3838. var keyIdentifierTable = {};
  3839. if ('cros' === os) {
  3840. keyIdentifierTable['U+00A0'] = { code: 'ShiftLeft', location: LEFT };
  3841. keyIdentifierTable['U+00A1'] = { code: 'ShiftRight', location: RIGHT };
  3842. keyIdentifierTable['U+00A2'] = { code: 'ControlLeft', location: LEFT };
  3843. keyIdentifierTable['U+00A3'] = { code: 'ControlRight', location: RIGHT };
  3844. keyIdentifierTable['U+00A4'] = { code: 'AltLeft', location: LEFT };
  3845. keyIdentifierTable['U+00A5'] = { code: 'AltRight', location: RIGHT };
  3846. }
  3847. if ('chrome-mac' === browser_os) {
  3848. keyIdentifierTable['U+0010'] = { code: 'ContextMenu' };
  3849. }
  3850. if ('safari-mac' === browser_os) {
  3851. keyIdentifierTable['U+0010'] = { code: 'ContextMenu' };
  3852. }
  3853. if ('ios' === os) {
  3854. // These only generate keyup events
  3855. keyIdentifierTable['U+0010'] = { code: 'Function' };
  3856. keyIdentifierTable['U+001C'] = { code: 'ArrowLeft' };
  3857. keyIdentifierTable['U+001D'] = { code: 'ArrowRight' };
  3858. keyIdentifierTable['U+001E'] = { code: 'ArrowUp' };
  3859. keyIdentifierTable['U+001F'] = { code: 'ArrowDown' };
  3860. keyIdentifierTable['U+0001'] = { code: 'Home' }; // [USB: 0x4a] Fn + ArrowLeft
  3861. keyIdentifierTable['U+0004'] = { code: 'End' }; // [USB: 0x4d] Fn + ArrowRight
  3862. keyIdentifierTable['U+000B'] = { code: 'PageUp' }; // [USB: 0x4b] Fn + ArrowUp
  3863. keyIdentifierTable['U+000C'] = { code: 'PageDown' }; // [USB: 0x4e] Fn + ArrowDown
  3864. }
  3865. //--------------------------------------------------------------------
  3866. //
  3867. // Location Mappings
  3868. //
  3869. //--------------------------------------------------------------------
  3870. // Cases where newer-ish browsers send location/keyLocation which
  3871. // can be used to disambiguate keys.
  3872. // locationTable[location][keyCode] -> keyInfo
  3873. var locationTable = [];
  3874. locationTable[LEFT] = {
  3875. 0x10: { code: 'ShiftLeft', location: LEFT }, // [USB: 0xe1]
  3876. 0x11: { code: 'ControlLeft', location: LEFT }, // [USB: 0xe0]
  3877. 0x12: { code: 'AltLeft', location: LEFT // [USB: 0xe2]
  3878. } };
  3879. locationTable[RIGHT] = {
  3880. 0x10: { code: 'ShiftRight', location: RIGHT }, // [USB: 0xe5]
  3881. 0x11: { code: 'ControlRight', location: RIGHT }, // [USB: 0xe4]
  3882. 0x12: { code: 'AltRight', location: RIGHT // [USB: 0xe6]
  3883. } };
  3884. locationTable[NUMPAD] = {
  3885. 0x0D: { code: 'NumpadEnter', location: NUMPAD // [USB: 0x58]
  3886. } };
  3887. mergeIf(locationTable[NUMPAD], 'moz', {
  3888. 0x6D: { code: 'NumpadSubtract', location: NUMPAD }, // [USB: 0x56]
  3889. 0x6B: { code: 'NumpadAdd', location: NUMPAD // [USB: 0x57]
  3890. } });
  3891. mergeIf(locationTable[LEFT], 'moz-mac', {
  3892. 0xE0: { code: 'OSLeft', location: LEFT // [USB: 0xe3]
  3893. } });
  3894. mergeIf(locationTable[RIGHT], 'moz-mac', {
  3895. 0xE0: { code: 'OSRight', location: RIGHT // [USB: 0xe7]
  3896. } });
  3897. mergeIf(locationTable[RIGHT], 'moz-win', {
  3898. 0x5B: { code: 'OSRight', location: RIGHT // [USB: 0xe7]
  3899. } });
  3900. mergeIf(locationTable[RIGHT], 'mac', {
  3901. 0x5D: { code: 'OSRight', location: RIGHT // [USB: 0xe7]
  3902. } });
  3903. mergeIf(locationTable[NUMPAD], 'chrome-mac', {
  3904. 0x0C: { code: 'NumLock', location: NUMPAD // [USB: 0x53]
  3905. } });
  3906. mergeIf(locationTable[NUMPAD], 'safari-mac', {
  3907. 0x0C: { code: 'NumLock', location: NUMPAD }, // [USB: 0x53]
  3908. 0xBB: { code: 'NumpadAdd', location: NUMPAD }, // [USB: 0x57]
  3909. 0xBD: { code: 'NumpadSubtract', location: NUMPAD }, // [USB: 0x56]
  3910. 0xBE: { code: 'NumpadDecimal', location: NUMPAD }, // [USB: 0x63]
  3911. 0xBF: { code: 'NumpadDivide', location: NUMPAD // [USB: 0x54]
  3912. } });
  3913. //--------------------------------------------------------------------
  3914. //
  3915. // Key Values
  3916. //
  3917. //--------------------------------------------------------------------
  3918. // Mapping from `code` values to `key` values. Values defined at:
  3919. // https://dvcs.w3.org/hg/dom3events/raw-file/tip/html/DOM3Events-key.html
  3920. // Entries are only provided when `key` differs from `code`. If
  3921. // printable, `shiftKey` has the shifted printable character. This
  3922. // assumes US Standard 101 layout
  3923. var codeToKeyTable = {
  3924. // Modifier Keys
  3925. ShiftLeft: { key: 'Shift' },
  3926. ShiftRight: { key: 'Shift' },
  3927. ControlLeft: { key: 'Control' },
  3928. ControlRight: { key: 'Control' },
  3929. AltLeft: { key: 'Alt' },
  3930. AltRight: { key: 'Alt' },
  3931. OSLeft: { key: 'OS' },
  3932. OSRight: { key: 'OS' },
  3933. // Whitespace Keys
  3934. NumpadEnter: { key: 'Enter' },
  3935. Space: { key: ' ' },
  3936. // Printable Keys
  3937. Digit0: { key: '0', shiftKey: ')' },
  3938. Digit1: { key: '1', shiftKey: '!' },
  3939. Digit2: { key: '2', shiftKey: '@' },
  3940. Digit3: { key: '3', shiftKey: '#' },
  3941. Digit4: { key: '4', shiftKey: '$' },
  3942. Digit5: { key: '5', shiftKey: '%' },
  3943. Digit6: { key: '6', shiftKey: '^' },
  3944. Digit7: { key: '7', shiftKey: '&' },
  3945. Digit8: { key: '8', shiftKey: '*' },
  3946. Digit9: { key: '9', shiftKey: '(' },
  3947. KeyA: { key: 'a', shiftKey: 'A' },
  3948. KeyB: { key: 'b', shiftKey: 'B' },
  3949. KeyC: { key: 'c', shiftKey: 'C' },
  3950. KeyD: { key: 'd', shiftKey: 'D' },
  3951. KeyE: { key: 'e', shiftKey: 'E' },
  3952. KeyF: { key: 'f', shiftKey: 'F' },
  3953. KeyG: { key: 'g', shiftKey: 'G' },
  3954. KeyH: { key: 'h', shiftKey: 'H' },
  3955. KeyI: { key: 'i', shiftKey: 'I' },
  3956. KeyJ: { key: 'j', shiftKey: 'J' },
  3957. KeyK: { key: 'k', shiftKey: 'K' },
  3958. KeyL: { key: 'l', shiftKey: 'L' },
  3959. KeyM: { key: 'm', shiftKey: 'M' },
  3960. KeyN: { key: 'n', shiftKey: 'N' },
  3961. KeyO: { key: 'o', shiftKey: 'O' },
  3962. KeyP: { key: 'p', shiftKey: 'P' },
  3963. KeyQ: { key: 'q', shiftKey: 'Q' },
  3964. KeyR: { key: 'r', shiftKey: 'R' },
  3965. KeyS: { key: 's', shiftKey: 'S' },
  3966. KeyT: { key: 't', shiftKey: 'T' },
  3967. KeyU: { key: 'u', shiftKey: 'U' },
  3968. KeyV: { key: 'v', shiftKey: 'V' },
  3969. KeyW: { key: 'w', shiftKey: 'W' },
  3970. KeyX: { key: 'x', shiftKey: 'X' },
  3971. KeyY: { key: 'y', shiftKey: 'Y' },
  3972. KeyZ: { key: 'z', shiftKey: 'Z' },
  3973. Numpad0: { key: '0' },
  3974. Numpad1: { key: '1' },
  3975. Numpad2: { key: '2' },
  3976. Numpad3: { key: '3' },
  3977. Numpad4: { key: '4' },
  3978. Numpad5: { key: '5' },
  3979. Numpad6: { key: '6' },
  3980. Numpad7: { key: '7' },
  3981. Numpad8: { key: '8' },
  3982. Numpad9: { key: '9' },
  3983. NumpadMultiply: { key: '*' },
  3984. NumpadAdd: { key: '+' },
  3985. NumpadComma: { key: ',' },
  3986. NumpadSubtract: { key: '-' },
  3987. NumpadDecimal: { key: '.' },
  3988. NumpadDivide: { key: '/' },
  3989. Semicolon: { key: ';', shiftKey: ':' },
  3990. Equal: { key: '=', shiftKey: '+' },
  3991. Comma: { key: ',', shiftKey: '<' },
  3992. Minus: { key: '-', shiftKey: '_' },
  3993. Period: { key: '.', shiftKey: '>' },
  3994. Slash: { key: '/', shiftKey: '?' },
  3995. Backquote: { key: '`', shiftKey: '~' },
  3996. BracketLeft: { key: '[', shiftKey: '{' },
  3997. Backslash: { key: '\\', shiftKey: '|' },
  3998. BracketRight: { key: ']', shiftKey: '}' },
  3999. Quote: { key: '\'', shiftKey: '"' },
  4000. IntlBackslash: { key: '\\', shiftKey: '|' }
  4001. };
  4002. mergeIf(codeToKeyTable, 'mac', {
  4003. OSLeft: { key: 'Meta' },
  4004. OSRight: { key: 'Meta' }
  4005. });
  4006. // Corrections for 'key' names in older browsers (e.g. FF36-)
  4007. // https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent.key#Key_values
  4008. var keyFixTable = {
  4009. Esc: 'Escape',
  4010. Nonconvert: 'NonConvert',
  4011. Left: 'ArrowLeft',
  4012. Up: 'ArrowUp',
  4013. Right: 'ArrowRight',
  4014. Down: 'ArrowDown',
  4015. Del: 'Delete',
  4016. Menu: 'ContextMenu',
  4017. MediaNextTrack: 'MediaTrackNext',
  4018. MediaPreviousTrack: 'MediaTrackPrevious',
  4019. SelectMedia: 'MediaSelect',
  4020. HalfWidth: 'Hankaku',
  4021. FullWidth: 'Zenkaku',
  4022. RomanCharacters: 'Romaji',
  4023. Crsel: 'CrSel',
  4024. Exsel: 'ExSel',
  4025. Zoom: 'ZoomToggle'
  4026. };
  4027. //--------------------------------------------------------------------
  4028. //
  4029. // Exported Functions
  4030. //
  4031. //--------------------------------------------------------------------
  4032. var codeTable = remap(keyCodeToInfoTable, 'code');
  4033. try {
  4034. var nativeLocation = nativeKeyboardEvent && 'location' in new KeyboardEvent('');
  4035. } catch (_) {}
  4036. function keyInfoForEvent(event) {
  4037. var keyCode = 'keyCode' in event ? event.keyCode : 'which' in event ? event.which : 0;
  4038. var keyInfo = function () {
  4039. if (nativeLocation || 'keyLocation' in event) {
  4040. var location = nativeLocation ? event.location : event.keyLocation;
  4041. if (location && keyCode in locationTable[location]) {
  4042. return locationTable[location][keyCode];
  4043. }
  4044. }
  4045. if ('keyIdentifier' in event && event.keyIdentifier in keyIdentifierTable) {
  4046. return keyIdentifierTable[event.keyIdentifier];
  4047. }
  4048. if (keyCode in keyCodeToInfoTable) {
  4049. return keyCodeToInfoTable[keyCode];
  4050. }
  4051. return null;
  4052. }();
  4053. // TODO: Track these down and move to general tables
  4054. if (0) {
  4055. // TODO: Map these for newerish browsers?
  4056. // TODO: iOS only?
  4057. // TODO: Override with more common keyIdentifier name?
  4058. switch (event.keyIdentifier) {
  4059. case 'U+0010':
  4060. keyInfo = { code: 'Function' };break;
  4061. case 'U+001C':
  4062. keyInfo = { code: 'ArrowLeft' };break;
  4063. case 'U+001D':
  4064. keyInfo = { code: 'ArrowRight' };break;
  4065. case 'U+001E':
  4066. keyInfo = { code: 'ArrowUp' };break;
  4067. case 'U+001F':
  4068. keyInfo = { code: 'ArrowDown' };break;
  4069. }
  4070. }
  4071. if (!keyInfo) return null;
  4072. var key = function () {
  4073. var entry = codeToKeyTable[keyInfo.code];
  4074. if (!entry) return keyInfo.code;
  4075. return event.shiftKey && 'shiftKey' in entry ? entry.shiftKey : entry.key;
  4076. }();
  4077. return {
  4078. code: keyInfo.code,
  4079. key: key,
  4080. location: keyInfo.location,
  4081. keyCap: keyInfo.keyCap
  4082. };
  4083. }
  4084. function queryKeyCap(code, locale) {
  4085. code = String(code);
  4086. if (!codeTable.hasOwnProperty(code)) return 'Undefined';
  4087. if (locale && String(locale).toLowerCase() !== 'en-us') throw Error('Unsupported locale');
  4088. var keyInfo = codeTable[code];
  4089. return keyInfo.keyCap || keyInfo.code || 'Undefined';
  4090. }
  4091. if ('KeyboardEvent' in global && 'defineProperty' in Object) {
  4092. (function () {
  4093. function define(o, p, v) {
  4094. if (p in o) return;
  4095. Object.defineProperty(o, p, v);
  4096. }
  4097. define(KeyboardEvent.prototype, 'code', { get: function get() {
  4098. var keyInfo = keyInfoForEvent(this);
  4099. return keyInfo ? keyInfo.code : '';
  4100. } });
  4101. // Fix for nonstandard `key` values (FF36-)
  4102. if ('key' in KeyboardEvent.prototype) {
  4103. var desc = Object.getOwnPropertyDescriptor(KeyboardEvent.prototype, 'key');
  4104. Object.defineProperty(KeyboardEvent.prototype, 'key', { get: function get() {
  4105. var key = desc.get.call(this);
  4106. return keyFixTable.hasOwnProperty(key) ? keyFixTable[key] : key;
  4107. } });
  4108. }
  4109. define(KeyboardEvent.prototype, 'key', { get: function get() {
  4110. var keyInfo = keyInfoForEvent(this);
  4111. return keyInfo && 'key' in keyInfo ? keyInfo.key : 'Unidentified';
  4112. } });
  4113. define(KeyboardEvent.prototype, 'location', { get: function get() {
  4114. var keyInfo = keyInfoForEvent(this);
  4115. return keyInfo && 'location' in keyInfo ? keyInfo.location : STANDARD;
  4116. } });
  4117. define(KeyboardEvent.prototype, 'locale', { get: function get() {
  4118. return '';
  4119. } });
  4120. })();
  4121. }
  4122. if (!('queryKeyCap' in global.KeyboardEvent)) global.KeyboardEvent.queryKeyCap = queryKeyCap;
  4123. // Helper for IE8-
  4124. global.identifyKey = function (event) {
  4125. if ('code' in event) return;
  4126. var keyInfo = keyInfoForEvent(event);
  4127. event.code = keyInfo ? keyInfo.code : '';
  4128. event.key = keyInfo && 'key' in keyInfo ? keyInfo.key : 'Unidentified';
  4129. event.location = 'location' in event ? event.location : 'keyLocation' in event ? event.keyLocation : keyInfo && 'location' in keyInfo ? keyInfo.location : STANDARD;
  4130. event.locale = '';
  4131. };
  4132. })(window);
  4133. },{}],11:[function(require,module,exports){
  4134. var e=function(){};e.computeCentroids=function(e){var t,n,r;for(t=0,n=e.faces.length;t<n;t++)(r=e.faces[t]).centroid=new THREE.Vector3(0,0,0),r.centroid.add(e.vertices[r.a]),r.centroid.add(e.vertices[r.b]),r.centroid.add(e.vertices[r.c]),r.centroid.divideScalar(3)},e.roundNumber=function(e,t){return Number(e.toFixed(t))},e.sample=function(e){return e[Math.floor(Math.random()*e.length)]},e.mergeVertexIds=function(e,t){var n=[];if(e.forEach(function(e){t.indexOf(e)>=0&&n.push(e)}),n.length<2)return[];n.includes(e[0])&&n.includes(e[e.length-1])&&e.push(e.shift()),n.includes(t[0])&&n.includes(t[t.length-1])&&t.push(t.shift()),n=[],e.forEach(function(e){t.includes(e)&&n.push(e)});for(var r=n[1],o=n[0],i=e.slice();i[0]!==r;)i.push(i.shift());for(var s=0,u=t.slice();u[0]!==o;)if(u.push(u.shift()),s++>10)throw new Error("Unexpected state");return u.shift(),u.pop(),i=i.concat(u)},e.setPolygonCentroid=function(e,t){var n=new THREE.Vector3,r=t.vertices;e.vertexIds.forEach(function(e){n.add(r[e])}),n.divideScalar(e.vertexIds.length),e.centroid.copy(n)},e.cleanPolygon=function(e,t){for(var n=[],r=t.vertices,o=0;o<e.vertexIds.length;o++){var i,s,u,c=r[e.vertexIds[o]];0===o?(i=e.vertexIds[1],s=e.vertexIds[e.vertexIds.length-1]):o===e.vertexIds.length-1?(i=e.vertexIds[0],s=e.vertexIds[e.vertexIds.length-2]):(i=e.vertexIds[o+1],s=e.vertexIds[o-1]),u=r[s];var h=r[i].clone().sub(c),a=u.clone().sub(c),d=h.angleTo(a);if(d>Math.PI-.01&&d<Math.PI+.01){var f=[];e.neighbours.forEach(function(t){t.vertexIds.includes(e.vertexIds[o])||f.push(t)}),e.neighbours=f}else n.push(e.vertexIds[o])}e.vertexIds=n,this.setPolygonCentroid(e,t)},e.isConvex=function(e,t){var n=t.vertices;if(e.vertexIds.length<3)return!1;for(var r=!0,o=[],i=0;i<e.vertexIds.length;i++){var s,u,c=n[e.vertexIds[i]];0===i?(s=n[e.vertexIds[1]],u=n[e.vertexIds[e.vertexIds.length-1]]):i===e.vertexIds.length-1?(s=n[e.vertexIds[0]],u=n[e.vertexIds[e.vertexIds.length-2]]):(s=n[e.vertexIds[i+1]],u=n[e.vertexIds[i-1]]);var h=s.clone().sub(c),a=u.clone().sub(c),d=h.angleTo(a);if(d===Math.PI||0===d)return!1;var f=h.cross(a).y;o.push(f)}return o.forEach(function(e){0===e&&(r=!1)}),o.forEach(o[0]>0?function(e){e<0&&(r=!1)}:function(e){e>0&&(r=!1)}),r},e.distanceToSquared=function(e,t){var n=e.x-t.x,r=e.y-t.y,o=e.z-t.z;return n*n+r*r+o*o},e.isPointInPoly=function(e,t){for(var n=!1,r=-1,o=e.length,i=o-1;++r<o;i=r)(e[r].z<=t.z&&t.z<e[i].z||e[i].z<=t.z&&t.z<e[r].z)&&t.x<(e[i].x-e[r].x)*(t.z-e[r].z)/(e[i].z-e[r].z)+e[r].x&&(n=!n);return n},e.isVectorInPolygon=function(e,t,n){var r=1e5,o=-1e5,i=[];return t.vertexIds.forEach(function(e){r=Math.min(n[e].y,r),o=Math.max(n[e].y,o),i.push(n[e])}),!!(e.y<o+.5&&e.y>r-.5&&this.isPointInPoly(i,e))},e.triarea2=function(e,t,n){return(n.x-e.x)*(t.z-e.z)-(t.x-e.x)*(n.z-e.z)},e.vequal=function(e,t){return this.distanceToSquared(e,t)<1e-5};var t=function(e){this.content=[],this.scoreFunction=e};t.prototype.push=function(e){this.content.push(e),this.sinkDown(this.content.length-1)},t.prototype.pop=function(){var e=this.content[0],t=this.content.pop();return this.content.length>0&&(this.content[0]=t,this.bubbleUp(0)),e},t.prototype.remove=function(e){var t=this.content.indexOf(e),n=this.content.pop();t!==this.content.length-1&&(this.content[t]=n,this.scoreFunction(n)<this.scoreFunction(e)?this.sinkDown(t):this.bubbleUp(t))},t.prototype.size=function(){return this.content.length},t.prototype.rescoreElement=function(e){this.sinkDown(this.content.indexOf(e))},t.prototype.sinkDown=function(e){for(var t=this.content[e];e>0;){var n=(e+1>>1)-1,r=this.content[n];if(!(this.scoreFunction(t)<this.scoreFunction(r)))break;this.content[n]=t,this.content[e]=r,e=n}},t.prototype.bubbleUp=function(e){for(var t=this.content.length,n=this.content[e],r=this.scoreFunction(n);;){var o=e+1<<1,i=o-1,s=null,u=void 0;if(i<t)(u=this.scoreFunction(this.content[i]))<r&&(s=i);if(o<t)this.scoreFunction(this.content[o])<(null===s?r:u)&&(s=o);if(null===s)break;this.content[e]=this.content[s],this.content[s]=n,e=s}};var n=function(){};n.init=function(e){for(var t=0;t<e.length;t++){var n=e[t];n.f=0,n.g=0,n.h=0,n.cost=1,n.visited=!1,n.closed=!1,n.parent=null}},n.cleanUp=function(e){for(var t=0;t<e.length;t++){var n=e[t];delete n.f,delete n.g,delete n.h,delete n.cost,delete n.visited,delete n.closed,delete n.parent}},n.heap=function(){return new t(function(e){return e.f})},n.search=function(e,t,n){this.init(e);var r=this.heap();for(r.push(t);r.size()>0;){var o=r.pop();if(o===n){for(var i=o,s=[];i.parent;)s.push(i),i=i.parent;return this.cleanUp(s),s.reverse()}o.closed=!0;for(var u=this.neighbours(e,o),c=0,h=u.length;c<h;c++){var a=u[c];if(!a.closed){var d=o.g+a.cost,f=a.visited;if(!f||d<a.g){if(a.visited=!0,a.parent=o,!a.centroid||!n.centroid)throw new Error("Unexpected state");a.h=a.h||this.heuristic(a.centroid,n.centroid),a.g=d,a.f=a.g+a.h,f?r.rescoreElement(a):r.push(a)}}}}return[]},n.heuristic=function(t,n){return e.distanceToSquared(t,n)},n.neighbours=function(e,t){for(var n=[],r=0;r<t.neighbours.length;r++)n.push(e[t.neighbours[r]]);return n};var r=1,o=function(){};o.buildZone=function(t){var n=this,r=this._buildNavigationMesh(t),o={};r.vertices.forEach(function(t){t.x=e.roundNumber(t.x,2),t.y=e.roundNumber(t.y,2),t.z=e.roundNumber(t.z,2)}),o.vertices=r.vertices;var i=this._buildPolygonGroups(r);o.groups=[];var s=function(e,t){for(var n=0;n<e.length;n++)if(t===e[n])return n};return i.forEach(function(t){var r=[];t.forEach(function(o){var i=o.neighbours.map(function(e){return s(t,e)}),u=o.neighbours.map(function(e){return n._getSharedVerticesInOrder(o,e)});o.centroid.x=e.roundNumber(o.centroid.x,2),o.centroid.y=e.roundNumber(o.centroid.y,2),o.centroid.z=e.roundNumber(o.centroid.z,2),r.push({id:s(t,o),neighbours:i,vertexIds:o.vertexIds,centroid:o.centroid,portals:u})}),o.groups.push(r)}),o},o._buildNavigationMesh=function(t){return e.computeCentroids(t),t.mergeVertices(),this._buildPolygonsFromGeometry(t)},o._buildPolygonGroups=function(e){var t=[],n=0,r=function(e){e.neighbours.forEach(function(t){void 0===t.group&&(t.group=e.group,r(t))})};return e.polygons.forEach(function(e){void 0===e.group&&(e.group=n++,r(e)),t[e.group]||(t[e.group]=[]),t[e.group].push(e)}),t},o._buildPolygonNeighbours=function(e,t,n){var r=new Set,o=n.get(e.vertexIds[0]),i=n.get(e.vertexIds[1]),s=n.get(e.vertexIds[2]);o.forEach(function(e){(i.has(e)||s.has(e))&&r.add(t.polygons[e])}),i.forEach(function(e){s.has(e)&&r.add(t.polygons[e])}),e.neighbours=Array.from(r)},o._buildPolygonsFromGeometry=function(e){for(var t=this,n=[],o=e.vertices,i=e.faceVertexUvs,s=new Map,u=0;u<o.length;u++)s.set(u,new Set);e.faces.forEach(function(e){n.push({id:r++,vertexIds:[e.a,e.b,e.c],centroid:e.centroid,normal:e.normal,neighbours:[]}),s.get(e.a).add(n.length-1),s.get(e.b).add(n.length-1),s.get(e.c).add(n.length-1)});var c={polygons:n,vertices:o,faceVertexUvs:i};return n.forEach(function(e){t._buildPolygonNeighbours(e,c,s)}),c},o._getSharedVerticesInOrder=function(e,t){var n=e.vertexIds,r=t.vertexIds,o=new Set;if(n.forEach(function(e){r.includes(e)&&o.add(e)}),o.size<2)return[];o.has(n[0])&&o.has(n[n.length-1])&&n.push(n.shift()),o.has(r[0])&&o.has(r[r.length-1])&&r.push(r.shift());var i=[];return n.forEach(function(e){r.includes(e)&&i.push(e)}),i};var i=function(){this.portals=[]};i.prototype.push=function(e,t){void 0===t&&(t=e),this.portals.push({left:e,right:t})},i.prototype.stringPull=function(){var t,n,r,o=this.portals,i=[],s=0,u=0,c=0;n=o[0].left,r=o[0].right,i.push(t=o[0].left);for(var h=1;h<o.length;h++){var a=o[h].left,d=o[h].right;if(e.triarea2(t,r,d)<=0){if(!(e.vequal(t,r)||e.triarea2(t,n,d)>0)){i.push(n),n=t=n,r=t,u=s=u,c=s,h=s;continue}r=d,c=h}if(e.triarea2(t,n,a)>=0){if(!(e.vequal(t,n)||e.triarea2(t,r,a)<0)){i.push(r),n=t=r,r=t,u=s=c,c=s,h=s;continue}n=a,u=h}}return 0!==i.length&&e.vequal(i[i.length-1],o[o.length-1].left)||i.push(o[o.length-1].left),this.path=i,i};var s,u,c,h,a,d,f=function(){this.zones={}};f.createZone=function(e){return o.buildZone(e)},f.prototype.setZoneData=function(e,t){this.zones[e]=t},f.prototype.getGroup=function(t,n){if(!this.zones[t])return null;var r=null,o=Math.pow(50,2);return this.zones[t].groups.forEach(function(t,i){t.forEach(function(t){var s=e.distanceToSquared(t.centroid,n);s<o&&(r=i,o=s)})}),r},f.prototype.getRandomNode=function(t,n,r,o){if(!this.zones[t])return new THREE.Vector3;r=r||null,o=o||0;var i=[];return this.zones[t].groups[n].forEach(function(t){r&&o?e.distanceToSquared(r,t.centroid)<o*o&&i.push(t.centroid):i.push(t.centroid)}),e.sample(i)||new THREE.Vector3},f.prototype.getClosestNode=function(t,n,r,o){void 0===o&&(o=!1);var i=this.zones[n].vertices,s=null,u=Infinity;return this.zones[n].groups[r].forEach(function(n){var r=e.distanceToSquared(n.centroid,t);r<u&&(!o||e.isVectorInPolygon(t,n,i))&&(s=n,u=r)}),s},f.prototype.findPath=function(e,t,r,o){var s=this.zones[r].groups[o],u=this.zones[r].vertices,c=this.getClosestNode(e,r,o),h=this.getClosestNode(t,r,o,!0);if(!c||!h)return null;var a=n.search(s,c,h),d=function(e,t){for(var n=0;n<e.neighbours.length;n++)if(e.neighbours[n]===t.id)return e.portals[n]},f=new i;f.push(e);for(var l=0;l<a.length;l++){var v=a[l+1];if(v){var p=d(a[l],v);f.push(u[p[0]],u[p[1]])}}f.push(t),f.stringPull();var g=f.path.map(function(e){return new THREE.Vector3(e.x,e.y,e.z)});return g.shift(),g},f.prototype.clampStep=(c=new THREE.Vector3,h=new THREE.Plane,a=new THREE.Triangle,d=new THREE.Vector3,function(e,t,n,r,o,i){var f=this.zones[r].vertices,l=this.zones[r].groups[o],v=[n],p={};p[n.id]=0,s=void 0,d.set(0,0,0),u=Infinity,h.setFromCoplanarPoints(f[n.vertexIds[0]],f[n.vertexIds[1]],f[n.vertexIds[2]]),h.projectPoint(t,c),t.copy(c);for(var g=v.pop();g;g=v.pop()){a.set(f[g.vertexIds[0]],f[g.vertexIds[1]],f[g.vertexIds[2]]),a.closestPointToPoint(t,c),c.distanceToSquared(t)<u&&(s=g,d.copy(c),u=c.distanceToSquared(t));var x=p[g];if(!(x>2))for(var I=0;I<g.neighbours.length;I++){var b=l[g.neighbours[I]];b.id in p||(v.push(b),p[b.id]=x+1)}}return i.copy(d),s}),exports.Pathfinding=f;
  4135. },{}],12:[function(require,module,exports){
  4136. 'use strict';
  4137. var EPS = 0.1;
  4138. module.exports = AFRAME.registerComponent('checkpoint-controls', {
  4139. schema: {
  4140. enabled: { default: true },
  4141. mode: { default: 'teleport', oneOf: ['teleport', 'animate'] },
  4142. animateSpeed: { default: 3.0 }
  4143. },
  4144. init: function init() {
  4145. this.active = true;
  4146. this.checkpoint = null;
  4147. this.isNavMeshConstrained = false;
  4148. this.offset = new THREE.Vector3();
  4149. this.position = new THREE.Vector3();
  4150. this.targetPosition = new THREE.Vector3();
  4151. },
  4152. play: function play() {
  4153. this.active = true;
  4154. },
  4155. pause: function pause() {
  4156. this.active = false;
  4157. },
  4158. setCheckpoint: function setCheckpoint(checkpoint) {
  4159. var el = this.el;
  4160. if (!this.active) return;
  4161. if (this.checkpoint === checkpoint) return;
  4162. if (this.checkpoint) {
  4163. el.emit('navigation-end', { checkpoint: this.checkpoint });
  4164. }
  4165. this.checkpoint = checkpoint;
  4166. this.sync();
  4167. // Ignore new checkpoint if we're already there.
  4168. if (this.position.distanceTo(this.targetPosition) < EPS) {
  4169. this.checkpoint = null;
  4170. return;
  4171. }
  4172. el.emit('navigation-start', { checkpoint: checkpoint });
  4173. if (this.data.mode === 'teleport') {
  4174. this.el.setAttribute('position', this.targetPosition);
  4175. this.checkpoint = null;
  4176. el.emit('navigation-end', { checkpoint: checkpoint });
  4177. el.components['movement-controls'].updateNavLocation();
  4178. }
  4179. },
  4180. isVelocityActive: function isVelocityActive() {
  4181. return !!(this.active && this.checkpoint);
  4182. },
  4183. getVelocity: function getVelocity() {
  4184. if (!this.active) return;
  4185. var data = this.data;
  4186. var offset = this.offset;
  4187. var position = this.position;
  4188. var targetPosition = this.targetPosition;
  4189. var checkpoint = this.checkpoint;
  4190. this.sync();
  4191. if (position.distanceTo(targetPosition) < EPS) {
  4192. this.checkpoint = null;
  4193. this.el.emit('navigation-end', { checkpoint: checkpoint });
  4194. return offset.set(0, 0, 0);
  4195. }
  4196. offset.setLength(data.animateSpeed);
  4197. return offset;
  4198. },
  4199. sync: function sync() {
  4200. var offset = this.offset;
  4201. var position = this.position;
  4202. var targetPosition = this.targetPosition;
  4203. position.copy(this.el.getAttribute('position'));
  4204. targetPosition.copy(this.checkpoint.object3D.getWorldPosition());
  4205. targetPosition.add(this.checkpoint.components.checkpoint.getOffset());
  4206. offset.copy(targetPosition).sub(position);
  4207. }
  4208. });
  4209. },{}],13:[function(require,module,exports){
  4210. 'use strict';
  4211. /**
  4212. * Gamepad controls for A-Frame.
  4213. *
  4214. * Stripped-down version of: https://github.com/donmccurdy/aframe-gamepad-controls
  4215. *
  4216. * For more information about the Gamepad API, see:
  4217. * https://developer.mozilla.org/en-US/docs/Web/API/Gamepad_API/Using_the_Gamepad_API
  4218. */
  4219. var GamepadButton = require('../../lib/GamepadButton'),
  4220. GamepadButtonEvent = require('../../lib/GamepadButtonEvent');
  4221. var JOYSTICK_EPS = 0.2;
  4222. module.exports = AFRAME.registerComponent('gamepad-controls', {
  4223. /*******************************************************************
  4224. * Statics
  4225. */
  4226. GamepadButton: GamepadButton,
  4227. /*******************************************************************
  4228. * Schema
  4229. */
  4230. schema: {
  4231. // Controller 0-3
  4232. controller: { default: 0, oneOf: [0, 1, 2, 3] },
  4233. // Enable/disable features
  4234. enabled: { default: true },
  4235. // Debugging
  4236. debug: { default: false },
  4237. // Heading element for rotation
  4238. camera: { default: '[camera]', type: 'selector' },
  4239. // Rotation sensitivity
  4240. rotationSensitivity: { default: 2.0 }
  4241. },
  4242. /*******************************************************************
  4243. * Core
  4244. */
  4245. /**
  4246. * Called once when component is attached. Generally for initial setup.
  4247. */
  4248. init: function init() {
  4249. var scene = this.el.sceneEl;
  4250. this.prevTime = window.performance.now();
  4251. // Button state
  4252. this.buttons = {};
  4253. // Rotation
  4254. var rotation = this.el.object3D.rotation;
  4255. this.pitch = new THREE.Object3D();
  4256. this.pitch.rotation.x = THREE.Math.degToRad(rotation.x);
  4257. this.yaw = new THREE.Object3D();
  4258. this.yaw.position.y = 10;
  4259. this.yaw.rotation.y = THREE.Math.degToRad(rotation.y);
  4260. this.yaw.add(this.pitch);
  4261. scene.addBehavior(this);
  4262. },
  4263. /**
  4264. * Called when component is attached and when component data changes.
  4265. * Generally modifies the entity based on the data.
  4266. */
  4267. update: function update() {
  4268. this.tick();
  4269. },
  4270. /**
  4271. * Called on each iteration of main render loop.
  4272. */
  4273. tick: function tick(t, dt) {
  4274. this.updateButtonState();
  4275. this.updateRotation(dt);
  4276. },
  4277. /**
  4278. * Called when a component is removed (e.g., via removeAttribute).
  4279. * Generally undoes all modifications to the entity.
  4280. */
  4281. remove: function remove() {},
  4282. /*******************************************************************
  4283. * Movement
  4284. */
  4285. isVelocityActive: function isVelocityActive() {
  4286. if (!this.data.enabled || !this.isConnected()) return false;
  4287. var dpad = this.getDpad(),
  4288. joystick0 = this.getJoystick(0),
  4289. inputX = dpad.x || joystick0.x,
  4290. inputY = dpad.y || joystick0.y;
  4291. return Math.abs(inputX) > JOYSTICK_EPS || Math.abs(inputY) > JOYSTICK_EPS;
  4292. },
  4293. getVelocityDelta: function getVelocityDelta() {
  4294. var dpad = this.getDpad(),
  4295. joystick0 = this.getJoystick(0),
  4296. inputX = dpad.x || joystick0.x,
  4297. inputY = dpad.y || joystick0.y,
  4298. dVelocity = new THREE.Vector3();
  4299. if (Math.abs(inputX) > JOYSTICK_EPS) {
  4300. dVelocity.x += inputX;
  4301. }
  4302. if (Math.abs(inputY) > JOYSTICK_EPS) {
  4303. dVelocity.z += inputY;
  4304. }
  4305. return dVelocity;
  4306. },
  4307. /*******************************************************************
  4308. * Rotation
  4309. */
  4310. isRotationActive: function isRotationActive() {
  4311. if (!this.data.enabled || !this.isConnected()) return false;
  4312. var joystick1 = this.getJoystick(1);
  4313. return Math.abs(joystick1.x) > JOYSTICK_EPS || Math.abs(joystick1.y) > JOYSTICK_EPS;
  4314. },
  4315. updateRotation: function updateRotation(dt) {
  4316. if (!this.isRotationActive()) return;
  4317. var data = this.data;
  4318. var yaw = this.yaw;
  4319. var pitch = this.pitch;
  4320. var lookControls = data.camera.components['look-controls'];
  4321. var hasLookControls = lookControls && lookControls.pitchObject && lookControls.yawObject;
  4322. // Sync with look-controls pitch/yaw if available.
  4323. if (hasLookControls) {
  4324. pitch.rotation.copy(lookControls.pitchObject.rotation);
  4325. yaw.rotation.copy(lookControls.yawObject.rotation);
  4326. }
  4327. var lookVector = this.getJoystick(1);
  4328. if (Math.abs(lookVector.x) <= JOYSTICK_EPS) lookVector.x = 0;
  4329. if (Math.abs(lookVector.y) <= JOYSTICK_EPS) lookVector.y = 0;
  4330. lookVector.multiplyScalar(data.rotationSensitivity * dt / 1000);
  4331. yaw.rotation.y -= lookVector.x;
  4332. pitch.rotation.x -= lookVector.y;
  4333. pitch.rotation.x = Math.max(-Math.PI / 2, Math.min(Math.PI / 2, pitch.rotation.x));
  4334. data.camera.object3D.rotation.set(pitch.rotation.x, yaw.rotation.y, 0);
  4335. // Sync with look-controls pitch/yaw if available.
  4336. if (hasLookControls) {
  4337. lookControls.pitchObject.rotation.copy(pitch.rotation);
  4338. lookControls.yawObject.rotation.copy(yaw.rotation);
  4339. }
  4340. },
  4341. /*******************************************************************
  4342. * Button events
  4343. */
  4344. updateButtonState: function updateButtonState() {
  4345. var gamepad = this.getGamepad();
  4346. if (this.data.enabled && gamepad) {
  4347. // Fire DOM events for button state changes.
  4348. for (var i = 0; i < gamepad.buttons.length; i++) {
  4349. if (gamepad.buttons[i].pressed && !this.buttons[i]) {
  4350. this.emit(new GamepadButtonEvent('gamepadbuttondown', i, gamepad.buttons[i]));
  4351. } else if (!gamepad.buttons[i].pressed && this.buttons[i]) {
  4352. this.emit(new GamepadButtonEvent('gamepadbuttonup', i, gamepad.buttons[i]));
  4353. }
  4354. this.buttons[i] = gamepad.buttons[i].pressed;
  4355. }
  4356. } else if (Object.keys(this.buttons)) {
  4357. // Reset state if controls are disabled or controller is lost.
  4358. this.buttons = {};
  4359. }
  4360. },
  4361. emit: function emit(event) {
  4362. // Emit original event.
  4363. this.el.emit(event.type, event);
  4364. // Emit convenience event, identifying button index.
  4365. this.el.emit(event.type + ':' + event.index, new GamepadButtonEvent(event.type, event.index, event));
  4366. },
  4367. /*******************************************************************
  4368. * Gamepad state
  4369. */
  4370. /**
  4371. * Returns the Gamepad instance attached to the component. If connected,
  4372. * a proxy-controls component may provide access to Gamepad input from a
  4373. * remote device.
  4374. *
  4375. * @return {Gamepad}
  4376. */
  4377. getGamepad: function getGamepad() {
  4378. var localGamepad = navigator.getGamepads && navigator.getGamepads()[this.data.controller],
  4379. proxyControls = this.el.sceneEl.components['proxy-controls'],
  4380. proxyGamepad = proxyControls && proxyControls.isConnected() && proxyControls.getGamepad(this.data.controller);
  4381. return proxyGamepad || localGamepad;
  4382. },
  4383. /**
  4384. * Returns the state of the given button.
  4385. * @param {number} index The button (0-N) for which to find state.
  4386. * @return {GamepadButton}
  4387. */
  4388. getButton: function getButton(index) {
  4389. return this.getGamepad().buttons[index];
  4390. },
  4391. /**
  4392. * Returns state of the given axis. Axes are labelled 0-N, where 0-1 will
  4393. * represent X/Y on the first joystick, and 2-3 X/Y on the second.
  4394. * @param {number} index The axis (0-N) for which to find state.
  4395. * @return {number} On the interval [-1,1].
  4396. */
  4397. getAxis: function getAxis(index) {
  4398. return this.getGamepad().axes[index];
  4399. },
  4400. /**
  4401. * Returns the state of the given joystick (0 or 1) as a THREE.Vector2.
  4402. * @param {number} id The joystick (0, 1) for which to find state.
  4403. * @return {THREE.Vector2}
  4404. */
  4405. getJoystick: function getJoystick(index) {
  4406. var gamepad = this.getGamepad();
  4407. switch (index) {
  4408. case 0:
  4409. return new THREE.Vector2(gamepad.axes[0], gamepad.axes[1]);
  4410. case 1:
  4411. return new THREE.Vector2(gamepad.axes[2], gamepad.axes[3]);
  4412. default:
  4413. throw new Error('Unexpected joystick index "%d".', index);
  4414. }
  4415. },
  4416. /**
  4417. * Returns the state of the dpad as a THREE.Vector2.
  4418. * @return {THREE.Vector2}
  4419. */
  4420. getDpad: function getDpad() {
  4421. var gamepad = this.getGamepad();
  4422. if (!gamepad.buttons[GamepadButton.DPAD_RIGHT]) {
  4423. return new THREE.Vector2();
  4424. }
  4425. return new THREE.Vector2((gamepad.buttons[GamepadButton.DPAD_RIGHT].pressed ? 1 : 0) + (gamepad.buttons[GamepadButton.DPAD_LEFT].pressed ? -1 : 0), (gamepad.buttons[GamepadButton.DPAD_UP].pressed ? -1 : 0) + (gamepad.buttons[GamepadButton.DPAD_DOWN].pressed ? 1 : 0));
  4426. },
  4427. /**
  4428. * Returns true if the gamepad is currently connected to the system.
  4429. * @return {boolean}
  4430. */
  4431. isConnected: function isConnected() {
  4432. var gamepad = this.getGamepad();
  4433. return !!(gamepad && gamepad.connected);
  4434. },
  4435. /**
  4436. * Returns a string containing some information about the controller. Result
  4437. * may vary across browsers, for a given controller.
  4438. * @return {string}
  4439. */
  4440. getID: function getID() {
  4441. return this.getGamepad().id;
  4442. }
  4443. });
  4444. },{"../../lib/GamepadButton":4,"../../lib/GamepadButtonEvent":5}],14:[function(require,module,exports){
  4445. 'use strict';
  4446. require('./checkpoint-controls');
  4447. require('./gamepad-controls');
  4448. require('./keyboard-controls');
  4449. require('./touch-controls');
  4450. require('./movement-controls');
  4451. require('./trackpad-controls');
  4452. },{"./checkpoint-controls":12,"./gamepad-controls":13,"./keyboard-controls":15,"./movement-controls":16,"./touch-controls":17,"./trackpad-controls":18}],15:[function(require,module,exports){
  4453. 'use strict';
  4454. require('../../lib/keyboard.polyfill');
  4455. var MAX_DELTA = 0.2,
  4456. PROXY_FLAG = '__keyboard-controls-proxy';
  4457. var KeyboardEvent = window.KeyboardEvent;
  4458. /**
  4459. * Keyboard Controls component.
  4460. *
  4461. * Stripped-down version of: https://github.com/donmccurdy/aframe-keyboard-controls
  4462. *
  4463. * Bind keyboard events to components, or control your entities with the WASD keys.
  4464. *
  4465. * Why use KeyboardEvent.code? "This is set to a string representing the key that was pressed to
  4466. * generate the KeyboardEvent, without taking the current keyboard layout (e.g., QWERTY vs.
  4467. * Dvorak), locale (e.g., English vs. French), or any modifier keys into account. This is useful
  4468. * when you care about which physical key was pressed, rather thanwhich character it corresponds
  4469. * to. For example, if you’re a writing a game, you might want a certain set of keys to move the
  4470. * player in different directions, and that mapping should ideally be independent of keyboard
  4471. * layout. See: https://developers.google.com/web/updates/2016/04/keyboardevent-keys-codes
  4472. *
  4473. * @namespace wasd-controls
  4474. * keys the entity moves and if you release it will stop. Easing simulates friction.
  4475. * to the entity when pressing the keys.
  4476. * @param {bool} [enabled=true] - To completely enable or disable the controls
  4477. */
  4478. module.exports = AFRAME.registerComponent('keyboard-controls', {
  4479. schema: {
  4480. enabled: { default: true },
  4481. debug: { default: false }
  4482. },
  4483. init: function init() {
  4484. this.dVelocity = new THREE.Vector3();
  4485. this.localKeys = {};
  4486. this.listeners = {
  4487. keydown: this.onKeyDown.bind(this),
  4488. keyup: this.onKeyUp.bind(this),
  4489. blur: this.onBlur.bind(this)
  4490. };
  4491. this.attachEventListeners();
  4492. },
  4493. /*******************************************************************
  4494. * Movement
  4495. */
  4496. isVelocityActive: function isVelocityActive() {
  4497. return this.data.enabled && !!Object.keys(this.getKeys()).length;
  4498. },
  4499. getVelocityDelta: function getVelocityDelta() {
  4500. var data = this.data,
  4501. keys = this.getKeys();
  4502. this.dVelocity.set(0, 0, 0);
  4503. if (data.enabled) {
  4504. if (keys.KeyW || keys.ArrowUp) {
  4505. this.dVelocity.z -= 1;
  4506. }
  4507. if (keys.KeyA || keys.ArrowLeft) {
  4508. this.dVelocity.x -= 1;
  4509. }
  4510. if (keys.KeyS || keys.ArrowDown) {
  4511. this.dVelocity.z += 1;
  4512. }
  4513. if (keys.KeyD || keys.ArrowRight) {
  4514. this.dVelocity.x += 1;
  4515. }
  4516. }
  4517. return this.dVelocity.clone();
  4518. },
  4519. /*******************************************************************
  4520. * Events
  4521. */
  4522. play: function play() {
  4523. this.attachEventListeners();
  4524. },
  4525. pause: function pause() {
  4526. this.removeEventListeners();
  4527. },
  4528. remove: function remove() {
  4529. this.pause();
  4530. },
  4531. attachEventListeners: function attachEventListeners() {
  4532. window.addEventListener('keydown', this.listeners.keydown, false);
  4533. window.addEventListener('keyup', this.listeners.keyup, false);
  4534. window.addEventListener('blur', this.listeners.blur, false);
  4535. },
  4536. removeEventListeners: function removeEventListeners() {
  4537. window.removeEventListener('keydown', this.listeners.keydown);
  4538. window.removeEventListener('keyup', this.listeners.keyup);
  4539. window.removeEventListener('blur', this.listeners.blur);
  4540. },
  4541. onKeyDown: function onKeyDown(event) {
  4542. if (AFRAME.utils.shouldCaptureKeyEvent(event)) {
  4543. this.localKeys[event.code] = true;
  4544. this.emit(event);
  4545. }
  4546. },
  4547. onKeyUp: function onKeyUp(event) {
  4548. if (AFRAME.utils.shouldCaptureKeyEvent(event)) {
  4549. delete this.localKeys[event.code];
  4550. this.emit(event);
  4551. }
  4552. },
  4553. onBlur: function onBlur() {
  4554. for (var code in this.localKeys) {
  4555. if (this.localKeys.hasOwnProperty(code)) {
  4556. delete this.localKeys[code];
  4557. }
  4558. }
  4559. },
  4560. emit: function emit(event) {
  4561. // TODO - keydown only initially?
  4562. // TODO - where the f is the spacebar
  4563. // Emit original event.
  4564. if (PROXY_FLAG in event) {
  4565. // TODO - Method never triggered.
  4566. this.el.emit(event.type, event);
  4567. }
  4568. // Emit convenience event, identifying key.
  4569. this.el.emit(event.type + ':' + event.code, new KeyboardEvent(event.type, event));
  4570. if (this.data.debug) console.log(event.type + ':' + event.code);
  4571. },
  4572. /*******************************************************************
  4573. * Accessors
  4574. */
  4575. isPressed: function isPressed(code) {
  4576. return code in this.getKeys();
  4577. },
  4578. getKeys: function getKeys() {
  4579. if (this.isProxied()) {
  4580. return this.el.sceneEl.components['proxy-controls'].getKeyboard();
  4581. }
  4582. return this.localKeys;
  4583. },
  4584. isProxied: function isProxied() {
  4585. var proxyControls = this.el.sceneEl.components['proxy-controls'];
  4586. return proxyControls && proxyControls.isConnected();
  4587. }
  4588. });
  4589. },{"../../lib/keyboard.polyfill":10}],16:[function(require,module,exports){
  4590. 'use strict';
  4591. /**
  4592. * Movement Controls
  4593. *
  4594. * @author Don McCurdy <dm@donmccurdy.com>
  4595. */
  4596. var COMPONENT_SUFFIX = '-controls',
  4597. MAX_DELTA = 0.2,
  4598. // ms
  4599. EPS = 10e-6;
  4600. module.exports = AFRAME.registerComponent('movement-controls', {
  4601. /*******************************************************************
  4602. * Schema
  4603. */
  4604. dependencies: ['rotation'],
  4605. schema: {
  4606. enabled: { default: true },
  4607. controls: { default: ['gamepad', 'trackpad', 'keyboard', 'touch'] },
  4608. speed: { default: 0.3, min: 0 },
  4609. fly: { default: false },
  4610. constrainToNavMesh: { default: false },
  4611. camera: { default: '[camera]', type: 'selector' }
  4612. },
  4613. /*******************************************************************
  4614. * Lifecycle
  4615. */
  4616. init: function init() {
  4617. var el = this.el;
  4618. this.velocityCtrl = null;
  4619. this.velocity = new THREE.Vector3();
  4620. this.heading = new THREE.Quaternion();
  4621. // Navigation
  4622. this.navGroup = null;
  4623. this.navNode = null;
  4624. if (el.sceneEl.hasLoaded) {
  4625. this.injectControls();
  4626. } else {
  4627. el.sceneEl.addEventListener('loaded', this.injectControls.bind(this));
  4628. }
  4629. },
  4630. update: function update(prevData) {
  4631. var el = this.el;
  4632. var data = this.data;
  4633. var nav = el.sceneEl.systems.nav;
  4634. if (el.sceneEl.hasLoaded) {
  4635. this.injectControls();
  4636. }
  4637. if (nav && data.constrainToNavMesh !== prevData.constrainToNavMesh) {
  4638. data.constrainToNavMesh ? nav.addAgent(this) : nav.removeAgent(this);
  4639. }
  4640. },
  4641. injectControls: function injectControls() {
  4642. var data = this.data;
  4643. var name;
  4644. for (var i = 0; i < data.controls.length; i++) {
  4645. name = data.controls[i] + COMPONENT_SUFFIX;
  4646. if (!this.el.components[name]) {
  4647. this.el.setAttribute(name, '');
  4648. }
  4649. }
  4650. },
  4651. updateNavLocation: function updateNavLocation() {
  4652. this.navGroup = null;
  4653. this.navNode = null;
  4654. },
  4655. /*******************************************************************
  4656. * Tick
  4657. */
  4658. tick: function () {
  4659. var start = new THREE.Vector3();
  4660. var end = new THREE.Vector3();
  4661. var clampedEnd = new THREE.Vector3();
  4662. return function (t, dt) {
  4663. if (!dt) return;
  4664. var el = this.el;
  4665. var data = this.data;
  4666. if (!data.enabled) return;
  4667. this.updateVelocityCtrl();
  4668. var velocityCtrl = this.velocityCtrl;
  4669. var velocity = this.velocity;
  4670. if (!velocityCtrl) return;
  4671. // Update velocity. If FPS is too low, reset.
  4672. if (dt / 1000 > MAX_DELTA) {
  4673. velocity.set(0, 0, 0);
  4674. } else {
  4675. this.updateVelocity(dt);
  4676. }
  4677. if (data.constrainToNavMesh && velocityCtrl.isNavMeshConstrained !== false) {
  4678. if (velocity.lengthSq() < EPS) return;
  4679. start.copy(el.object3D.position);
  4680. end.copy(velocity).multiplyScalar(dt / 1000).add(start);
  4681. var nav = el.sceneEl.systems.nav;
  4682. this.navGroup = this.navGroup === null ? nav.getGroup(start) : this.navGroup;
  4683. this.navNode = this.navNode || nav.getNode(start, this.navGroup);
  4684. this.navNode = nav.clampStep(start, end, this.navGroup, this.navNode, clampedEnd);
  4685. el.object3D.position.copy(clampedEnd);
  4686. } else if (el.hasAttribute('velocity')) {
  4687. el.setAttribute('velocity', velocity);
  4688. } else {
  4689. el.object3D.position.x += velocity.x * dt / 1000;
  4690. el.object3D.position.y += velocity.y * dt / 1000;
  4691. el.object3D.position.z += velocity.z * dt / 1000;
  4692. }
  4693. };
  4694. }(),
  4695. /*******************************************************************
  4696. * Movement
  4697. */
  4698. updateVelocityCtrl: function updateVelocityCtrl() {
  4699. var data = this.data;
  4700. if (data.enabled) {
  4701. for (var i = 0, l = data.controls.length; i < l; i++) {
  4702. var control = this.el.components[data.controls[i] + COMPONENT_SUFFIX];
  4703. if (control && control.isVelocityActive()) {
  4704. this.velocityCtrl = control;
  4705. return;
  4706. }
  4707. }
  4708. this.velocityCtrl = null;
  4709. }
  4710. },
  4711. updateVelocity: function () {
  4712. var vector2 = new THREE.Vector2();
  4713. var quaternion = new THREE.Quaternion();
  4714. return function (dt) {
  4715. var dVelocity = void 0;
  4716. var el = this.el;
  4717. var control = this.velocityCtrl;
  4718. var velocity = this.velocity;
  4719. var data = this.data;
  4720. if (control) {
  4721. if (control.getVelocityDelta) {
  4722. dVelocity = control.getVelocityDelta(dt);
  4723. } else if (control.getVelocity) {
  4724. velocity.copy(control.getVelocity());
  4725. return;
  4726. } else if (control.getPositionDelta) {
  4727. velocity.copy(control.getPositionDelta(dt).multiplyScalar(1000 / dt));
  4728. return;
  4729. } else {
  4730. throw new Error('Incompatible movement controls: ', control);
  4731. }
  4732. }
  4733. if (el.hasAttribute('velocity') && !data.constrainToNavMesh) {
  4734. velocity.copy(this.el.getAttribute('velocity'));
  4735. }
  4736. if (dVelocity && data.enabled) {
  4737. var cameraEl = data.camera;
  4738. // Rotate to heading
  4739. quaternion.copy(cameraEl.object3D.quaternion);
  4740. quaternion.premultiply(el.object3D.quaternion);
  4741. dVelocity.applyQuaternion(quaternion);
  4742. var factor = dVelocity.length();
  4743. if (data.fly) {
  4744. velocity.copy(dVelocity);
  4745. velocity.multiplyScalar(this.data.speed * 16.66667);
  4746. } else {
  4747. vector2.set(dVelocity.x, dVelocity.z);
  4748. vector2.setLength(factor * this.data.speed * 16.66667);
  4749. velocity.x = vector2.x;
  4750. velocity.z = vector2.y;
  4751. }
  4752. }
  4753. };
  4754. }()
  4755. });
  4756. },{}],17:[function(require,module,exports){
  4757. 'use strict';
  4758. /**
  4759. * Touch-to-move-forward controls for mobile.
  4760. */
  4761. module.exports = AFRAME.registerComponent('touch-controls', {
  4762. schema: {
  4763. enabled: { default: true },
  4764. reverseEnabled: { default: true }
  4765. },
  4766. init: function init() {
  4767. this.dVelocity = new THREE.Vector3();
  4768. this.bindMethods();
  4769. this.direction = 0;
  4770. },
  4771. play: function play() {
  4772. this.addEventListeners();
  4773. },
  4774. pause: function pause() {
  4775. this.removeEventListeners();
  4776. this.dVelocity.set(0, 0, 0);
  4777. },
  4778. remove: function remove() {
  4779. this.pause();
  4780. },
  4781. addEventListeners: function addEventListeners() {
  4782. var sceneEl = this.el.sceneEl;
  4783. var canvasEl = sceneEl.canvas;
  4784. if (!canvasEl) {
  4785. sceneEl.addEventListener('render-target-loaded', this.addEventListeners.bind(this));
  4786. return;
  4787. }
  4788. canvasEl.addEventListener('touchstart', this.onTouchStart);
  4789. canvasEl.addEventListener('touchend', this.onTouchEnd);
  4790. },
  4791. removeEventListeners: function removeEventListeners() {
  4792. var canvasEl = this.el.sceneEl && this.el.sceneEl.canvas;
  4793. if (!canvasEl) {
  4794. return;
  4795. }
  4796. canvasEl.removeEventListener('touchstart', this.onTouchStart);
  4797. canvasEl.removeEventListener('touchend', this.onTouchEnd);
  4798. },
  4799. isVelocityActive: function isVelocityActive() {
  4800. return this.data.enabled && !!this.direction;
  4801. },
  4802. getVelocityDelta: function getVelocityDelta() {
  4803. this.dVelocity.z = this.direction;
  4804. return this.dVelocity.clone();
  4805. },
  4806. bindMethods: function bindMethods() {
  4807. this.onTouchStart = this.onTouchStart.bind(this);
  4808. this.onTouchEnd = this.onTouchEnd.bind(this);
  4809. },
  4810. onTouchStart: function onTouchStart(e) {
  4811. this.direction = -1;
  4812. if (this.data.reverseEnabled && e.touches.length === 2) {
  4813. this.direction = 1;
  4814. }
  4815. e.preventDefault();
  4816. },
  4817. onTouchEnd: function onTouchEnd(e) {
  4818. this.direction = 0;
  4819. e.preventDefault();
  4820. }
  4821. });
  4822. },{}],18:[function(require,module,exports){
  4823. 'use strict';
  4824. /**
  4825. * 3dof (Gear VR, Daydream) controls for mobile.
  4826. */
  4827. module.exports = AFRAME.registerComponent('trackpad-controls', {
  4828. schema: {
  4829. enabled: { default: true }
  4830. },
  4831. init: function init() {
  4832. this.dVelocity = new THREE.Vector3();
  4833. this.zVel = 0;
  4834. this.bindMethods();
  4835. },
  4836. play: function play() {
  4837. this.addEventListeners();
  4838. },
  4839. pause: function pause() {
  4840. this.removeEventListeners();
  4841. this.dVelocity.set(0, 0, 0);
  4842. },
  4843. remove: function remove() {
  4844. this.pause();
  4845. },
  4846. addEventListeners: function addEventListeners() {
  4847. var sceneEl = this.el.sceneEl;
  4848. sceneEl.addEventListener('axismove', this.onAxisMove);
  4849. sceneEl.addEventListener('trackpadtouchstart', this.onTouchStart);
  4850. sceneEl.addEventListener('trackpadtouchend', this.onTouchEnd);
  4851. },
  4852. removeEventListeners: function removeEventListeners() {
  4853. var sceneEl = this.el.sceneEl;
  4854. sceneEl.removeEventListener('axismove', this.onAxisMove);
  4855. sceneEl.removeEventListener('trackpadtouchstart', this.onTouchStart);
  4856. sceneEl.removeEventListener('trackpadtouchend', this.onTouchEnd);
  4857. },
  4858. isVelocityActive: function isVelocityActive() {
  4859. return this.data.enabled && this.isMoving;
  4860. },
  4861. getVelocityDelta: function getVelocityDelta() {
  4862. this.dVelocity.z = this.isMoving ? -this.zVel : 1;
  4863. return this.dVelocity.clone();
  4864. },
  4865. bindMethods: function bindMethods() {
  4866. this.onTouchStart = this.onTouchStart.bind(this);
  4867. this.onTouchEnd = this.onTouchEnd.bind(this);
  4868. this.onAxisMove = this.onAxisMove.bind(this);
  4869. },
  4870. onTouchStart: function onTouchStart(e) {
  4871. this.isMoving = true;
  4872. e.preventDefault();
  4873. },
  4874. onTouchEnd: function onTouchEnd(e) {
  4875. this.isMoving = false;
  4876. e.preventDefault();
  4877. },
  4878. onAxisMove: function onAxisMove(e) {
  4879. var axis_data = e.detail.axis;
  4880. if (axis_data[1] < 0) {
  4881. this.zVel = 1;
  4882. }
  4883. if (axis_data[1] > 0) {
  4884. this.zVel = -1;
  4885. }
  4886. }
  4887. });
  4888. },{}],19:[function(require,module,exports){
  4889. 'use strict';
  4890. var LoopMode = {
  4891. once: THREE.LoopOnce,
  4892. repeat: THREE.LoopRepeat,
  4893. pingpong: THREE.LoopPingPong
  4894. };
  4895. /**
  4896. * animation-mixer
  4897. *
  4898. * Player for animation clips. Intended to be compatible with any model format that supports
  4899. * skeletal or morph animations through THREE.AnimationMixer.
  4900. * See: https://threejs.org/docs/?q=animation#Reference/Animation/AnimationMixer
  4901. */
  4902. module.exports = AFRAME.registerComponent('animation-mixer', {
  4903. schema: {
  4904. clip: { default: '*' },
  4905. duration: { default: 0 },
  4906. clampWhenFinished: { default: false, type: 'boolean' },
  4907. crossFadeDuration: { default: 0 },
  4908. loop: { default: 'repeat', oneOf: Object.keys(LoopMode) },
  4909. repetitions: { default: Infinity, min: 0 },
  4910. timeScale: { default: 1 }
  4911. },
  4912. init: function init() {
  4913. var _this = this;
  4914. /** @type {THREE.Mesh} */
  4915. this.model = null;
  4916. /** @type {THREE.AnimationMixer} */
  4917. this.mixer = null;
  4918. /** @type {Array<THREE.AnimationAction>} */
  4919. this.activeActions = [];
  4920. var model = this.el.getObject3D('mesh');
  4921. if (model) {
  4922. this.load(model);
  4923. } else {
  4924. this.el.addEventListener('model-loaded', function (e) {
  4925. _this.load(e.detail.model);
  4926. });
  4927. }
  4928. },
  4929. load: function load(model) {
  4930. var el = this.el;
  4931. this.model = model;
  4932. this.mixer = new THREE.AnimationMixer(model);
  4933. this.mixer.addEventListener('loop', function (e) {
  4934. el.emit('animation-loop', { action: e.action, loopDelta: e.loopDelta });
  4935. });
  4936. this.mixer.addEventListener('finished', function (e) {
  4937. el.emit('animation-finished', { action: e.action, direction: e.direction });
  4938. });
  4939. if (this.data.clip) this.update({});
  4940. },
  4941. remove: function remove() {
  4942. if (this.mixer) this.mixer.stopAllAction();
  4943. },
  4944. update: function update(prevData) {
  4945. if (!prevData) return;
  4946. var data = this.data;
  4947. var changes = AFRAME.utils.diff(data, prevData);
  4948. // If selected clips have changed, restart animation.
  4949. if ('clip' in changes) {
  4950. this.stopAction();
  4951. if (data.clip) this.playAction();
  4952. return;
  4953. }
  4954. // Otherwise, modify running actions.
  4955. this.activeActions.forEach(function (action) {
  4956. if ('duration' in changes && data.duration) {
  4957. action.setDuration(data.duration);
  4958. }
  4959. if ('clampWhenFinished' in changes) {
  4960. action.clampWhenFinished = data.clampWhenFinished;
  4961. }
  4962. if ('loop' in changes || 'repetitions' in changes) {
  4963. action.setLoop(LoopMode[data.loop], data.repetitions);
  4964. }
  4965. if ('timeScale' in changes) {
  4966. action.setEffectiveTimeScale(data.timeScale);
  4967. }
  4968. });
  4969. },
  4970. stopAction: function stopAction() {
  4971. var data = this.data;
  4972. for (var i = 0; i < this.activeActions.length; i++) {
  4973. data.crossFadeDuration ? this.activeActions[i].fadeOut(data.crossFadeDuration) : this.activeActions[i].stop();
  4974. }
  4975. this.activeActions.length = 0;
  4976. },
  4977. playAction: function playAction() {
  4978. if (!this.mixer) return;
  4979. var model = this.model,
  4980. data = this.data,
  4981. clips = model.animations || (model.geometry || {}).animations || [];
  4982. if (!clips.length) return;
  4983. var re = wildcardToRegExp(data.clip);
  4984. for (var clip, i = 0; clip = clips[i]; i++) {
  4985. if (clip.name.match(re)) {
  4986. var action = this.mixer.clipAction(clip, model);
  4987. action.enabled = true;
  4988. action.clampWhenFinished = data.clampWhenFinished;
  4989. if (data.duration) action.setDuration(data.duration);
  4990. action.setLoop(LoopMode[data.loop], data.repetitions).setEffectiveTimeScale(data.timeScale).fadeIn(data.crossFadeDuration).play();
  4991. this.activeActions.push(action);
  4992. }
  4993. }
  4994. },
  4995. tick: function tick(t, dt) {
  4996. if (this.mixer && !isNaN(dt)) this.mixer.update(dt / 1000);
  4997. }
  4998. });
  4999. /**
  5000. * Creates a RegExp from the given string, converting asterisks to .* expressions,
  5001. * and escaping all other characters.
  5002. */
  5003. function wildcardToRegExp(s) {
  5004. return new RegExp('^' + s.split(/\*+/).map(regExpEscape).join('.*') + '$');
  5005. }
  5006. /**
  5007. * RegExp-escapes all characters in the given string.
  5008. */
  5009. function regExpEscape(s) {
  5010. return s.replace(/[|\\{}()[\]^$+*?.]/g, '\\$&');
  5011. }
  5012. },{}],20:[function(require,module,exports){
  5013. 'use strict';
  5014. THREE.FBXLoader = require('../../lib/FBXLoader');
  5015. /**
  5016. * fbx-model
  5017. *
  5018. * Loader for FBX format. Supports ASCII, but *not* binary, models.
  5019. */
  5020. module.exports = AFRAME.registerComponent('fbx-model', {
  5021. schema: {
  5022. src: { type: 'asset' },
  5023. crossorigin: { default: '' }
  5024. },
  5025. init: function init() {
  5026. this.model = null;
  5027. },
  5028. update: function update() {
  5029. var data = this.data;
  5030. if (!data.src) return;
  5031. this.remove();
  5032. var loader = new THREE.FBXLoader();
  5033. if (data.crossorigin) loader.setCrossOrigin(data.crossorigin);
  5034. loader.load(data.src, this.load.bind(this));
  5035. },
  5036. load: function load(model) {
  5037. this.model = model;
  5038. this.el.setObject3D('mesh', model);
  5039. this.el.emit('model-loaded', { format: 'fbx', model: model });
  5040. },
  5041. remove: function remove() {
  5042. if (this.model) this.el.removeObject3D('mesh');
  5043. }
  5044. });
  5045. },{"../../lib/FBXLoader":3}],21:[function(require,module,exports){
  5046. 'use strict';
  5047. var fetchScript = require('../../lib/fetch-script')();
  5048. var LOADER_SRC = 'https://rawgit.com/mrdoob/three.js/r86/examples/js/loaders/GLTFLoader.js';
  5049. var loadLoader = function () {
  5050. var promise = void 0;
  5051. return function () {
  5052. promise = promise || fetchScript(LOADER_SRC);
  5053. return promise;
  5054. };
  5055. }();
  5056. /**
  5057. * Legacy loader for glTF 1.0 models.
  5058. * Asynchronously loads THREE.GLTFLoader from rawgit.
  5059. */
  5060. module.exports = AFRAME.registerComponent('gltf-model-legacy', {
  5061. schema: { type: 'model' },
  5062. init: function init() {
  5063. var _this = this;
  5064. this.model = null;
  5065. this.loader = null;
  5066. this.loaderPromise = loadLoader().then(function () {
  5067. _this.loader = new THREE.GLTFLoader();
  5068. _this.loader.setCrossOrigin('Anonymous');
  5069. });
  5070. },
  5071. update: function update() {
  5072. var _this2 = this;
  5073. var self = this;
  5074. var el = this.el;
  5075. var src = this.data;
  5076. if (!src) {
  5077. return;
  5078. }
  5079. this.remove();
  5080. this.loaderPromise.then(function () {
  5081. _this2.loader.load(src, function gltfLoaded(gltfModel) {
  5082. self.model = gltfModel.scene;
  5083. self.model.animations = gltfModel.animations;
  5084. el.setObject3D('mesh', self.model);
  5085. el.emit('model-loaded', { format: 'gltf', model: self.model });
  5086. });
  5087. });
  5088. },
  5089. remove: function remove() {
  5090. if (!this.model) {
  5091. return;
  5092. }
  5093. this.el.removeObject3D('mesh');
  5094. }
  5095. });
  5096. },{"../../lib/fetch-script":8}],22:[function(require,module,exports){
  5097. 'use strict';
  5098. require('./animation-mixer');
  5099. require('./fbx-model');
  5100. require('./gltf-model-legacy');
  5101. require('./json-model');
  5102. require('./object-model');
  5103. require('./ply-model');
  5104. },{"./animation-mixer":19,"./fbx-model":20,"./gltf-model-legacy":21,"./json-model":23,"./object-model":24,"./ply-model":25}],23:[function(require,module,exports){
  5105. 'use strict';
  5106. /**
  5107. * json-model
  5108. *
  5109. * Loader for THREE.js JSON format. Somewhat confusingly, there are two different THREE.js formats,
  5110. * both having the .json extension. This loader supports only THREE.JsonLoader, which typically
  5111. * includes only a single mesh.
  5112. *
  5113. * Check the console for errors, if in doubt. You may need to use `object-model` or
  5114. * `blend-character-model` for some .js and .json files.
  5115. *
  5116. * See: https://clara.io/learn/user-guide/data_exchange/threejs_export
  5117. */
  5118. module.exports = AFRAME.registerComponent('json-model', {
  5119. schema: {
  5120. src: { type: 'asset' },
  5121. crossorigin: { default: '' }
  5122. },
  5123. init: function init() {
  5124. this.model = null;
  5125. },
  5126. update: function update() {
  5127. var _this = this;
  5128. var loader = void 0;
  5129. var data = this.data;
  5130. if (!data.src) return;
  5131. this.remove();
  5132. loader = new THREE.JSONLoader();
  5133. if (data.crossorigin) loader.crossOrigin = data.crossorigin;
  5134. loader.load(data.src, function (geometry, materials) {
  5135. // Attempt to automatically detect common material options.
  5136. materials.forEach(function (mat) {
  5137. mat.vertexColors = (geometry.faces[0] || {}).color ? THREE.FaceColors : THREE.NoColors;
  5138. mat.skinning = !!(geometry.bones || []).length;
  5139. mat.morphTargets = !!(geometry.morphTargets || []).length;
  5140. mat.morphNormals = !!(geometry.morphNormals || []).length;
  5141. });
  5142. var model = (geometry.bones || []).length ? new THREE.SkinnedMesh(geometry, new THREE.MultiMaterial(materials)) : new THREE.Mesh(geometry, new THREE.MultiMaterial(materials));
  5143. _this.load(model);
  5144. });
  5145. },
  5146. load: function load(model) {
  5147. this.model = model;
  5148. this.el.setObject3D('mesh', model);
  5149. this.el.emit('model-loaded', { format: 'json', model: model });
  5150. },
  5151. remove: function remove() {
  5152. if (this.model) this.el.removeObject3D('mesh');
  5153. }
  5154. });
  5155. },{}],24:[function(require,module,exports){
  5156. 'use strict';
  5157. /**
  5158. * object-model
  5159. *
  5160. * Loader for THREE.js JSON format. Somewhat confusingly, there are two different THREE.js formats,
  5161. * both having the .json extension. This loader supports only THREE.ObjectLoader, which typically
  5162. * includes multiple meshes or an entire scene.
  5163. *
  5164. * Check the console for errors, if in doubt. You may need to use `json-model` or
  5165. * `blend-character-model` for some .js and .json files.
  5166. *
  5167. * See: https://clara.io/learn/user-guide/data_exchange/threejs_export
  5168. */
  5169. module.exports = AFRAME.registerComponent('object-model', {
  5170. schema: {
  5171. src: { type: 'asset' },
  5172. crossorigin: { default: '' }
  5173. },
  5174. init: function init() {
  5175. this.model = null;
  5176. },
  5177. update: function update() {
  5178. var _this = this;
  5179. var loader = void 0;
  5180. var data = this.data;
  5181. if (!data.src) return;
  5182. this.remove();
  5183. loader = new THREE.ObjectLoader();
  5184. if (data.crossorigin) loader.setCrossOrigin(data.crossorigin);
  5185. loader.load(data.src, function (object) {
  5186. // Enable skinning, if applicable.
  5187. object.traverse(function (o) {
  5188. if (o instanceof THREE.SkinnedMesh && o.material) {
  5189. o.material.skinning = !!(o.geometry && o.geometry.bones || []).length;
  5190. }
  5191. });
  5192. _this.load(object);
  5193. });
  5194. },
  5195. load: function load(model) {
  5196. this.model = model;
  5197. this.el.setObject3D('mesh', model);
  5198. this.el.emit('model-loaded', { format: 'json', model: model });
  5199. },
  5200. remove: function remove() {
  5201. if (this.model) this.el.removeObject3D('mesh');
  5202. }
  5203. });
  5204. },{}],25:[function(require,module,exports){
  5205. 'use strict';
  5206. /**
  5207. * ply-model
  5208. *
  5209. * Wraps THREE.PLYLoader.
  5210. */
  5211. THREE.PLYLoader = require('../../lib/PLYLoader');
  5212. /**
  5213. * Loads, caches, resolves geometries.
  5214. *
  5215. * @member cache - Promises that resolve geometries keyed by `src`.
  5216. */
  5217. module.exports.System = AFRAME.registerSystem('ply-model', {
  5218. init: function init() {
  5219. this.cache = {};
  5220. },
  5221. /**
  5222. * @returns {Promise}
  5223. */
  5224. getOrLoadGeometry: function getOrLoadGeometry(src, skipCache) {
  5225. var cache = this.cache;
  5226. var cacheItem = cache[src];
  5227. if (!skipCache && cacheItem) {
  5228. return cacheItem;
  5229. }
  5230. cache[src] = new Promise(function (resolve) {
  5231. var loader = new THREE.PLYLoader();
  5232. loader.load(src, function (geometry) {
  5233. resolve(geometry);
  5234. });
  5235. });
  5236. return cache[src];
  5237. }
  5238. });
  5239. module.exports.Component = AFRAME.registerComponent('ply-model', {
  5240. schema: {
  5241. skipCache: { type: 'boolean', default: false },
  5242. src: { type: 'asset' }
  5243. },
  5244. init: function init() {
  5245. this.model = null;
  5246. },
  5247. update: function update() {
  5248. var data = this.data;
  5249. var el = this.el;
  5250. if (!data.src) {
  5251. console.warn('[%s] `src` property is required.', this.name);
  5252. return;
  5253. }
  5254. // Get geometry from system, create and set mesh.
  5255. this.system.getOrLoadGeometry(data.src, data.skipCache).then(function (geometry) {
  5256. var model = createModel(geometry);
  5257. el.setObject3D('mesh', model);
  5258. el.emit('model-loaded', { format: 'ply', model: model });
  5259. });
  5260. },
  5261. remove: function remove() {
  5262. if (this.model) {
  5263. this.el.removeObject3D('mesh');
  5264. }
  5265. }
  5266. });
  5267. function createModel(geometry) {
  5268. return new THREE.Mesh(geometry, new THREE.MeshPhongMaterial({
  5269. color: 0xFFFFFF,
  5270. shading: THREE.FlatShading,
  5271. vertexColors: THREE.VertexColors,
  5272. shininess: 0
  5273. }));
  5274. }
  5275. },{"../../lib/PLYLoader":6}],26:[function(require,module,exports){
  5276. 'use strict';
  5277. module.exports = AFRAME.registerComponent('checkpoint', {
  5278. schema: {
  5279. offset: { default: { x: 0, y: 0, z: 0 }, type: 'vec3' }
  5280. },
  5281. init: function init() {
  5282. this.active = false;
  5283. this.targetEl = null;
  5284. this.fire = this.fire.bind(this);
  5285. this.offset = new THREE.Vector3();
  5286. },
  5287. update: function update() {
  5288. this.offset.copy(this.data.offset);
  5289. },
  5290. play: function play() {
  5291. this.el.addEventListener('click', this.fire);
  5292. },
  5293. pause: function pause() {
  5294. this.el.removeEventListener('click', this.fire);
  5295. },
  5296. remove: function remove() {
  5297. this.pause();
  5298. },
  5299. fire: function fire() {
  5300. var targetEl = this.el.sceneEl.querySelector('[checkpoint-controls]');
  5301. if (!targetEl) {
  5302. throw new Error('No `checkpoint-controls` component found.');
  5303. }
  5304. targetEl.components['checkpoint-controls'].setCheckpoint(this.el);
  5305. },
  5306. getOffset: function getOffset() {
  5307. return this.offset.copy(this.data.offset);
  5308. }
  5309. });
  5310. },{}],27:[function(require,module,exports){
  5311. 'use strict';
  5312. /**
  5313. * @param {Array<THREE.Material>|THREE.Material} material
  5314. * @return {Array<THREE.Material>}
  5315. */
  5316. function ensureMaterialArray(material) {
  5317. if (!material) {
  5318. return [];
  5319. } else if (Array.isArray(material)) {
  5320. return material;
  5321. } else if (material.materials) {
  5322. return material.materials;
  5323. } else {
  5324. return [material];
  5325. }
  5326. }
  5327. /**
  5328. * @param {THREE.Object3D} mesh
  5329. * @param {Array<string>} materialNames
  5330. * @param {THREE.Texture} envMap
  5331. * @param {number} reflectivity [description]
  5332. */
  5333. function applyEnvMap(mesh, materialNames, envMap, reflectivity) {
  5334. if (!mesh) return;
  5335. materialNames = materialNames || [];
  5336. mesh.traverse(function (node) {
  5337. if (!node.isMesh) return;
  5338. var meshMaterials = ensureMaterialArray(node.material);
  5339. meshMaterials.forEach(function (material) {
  5340. if (material && !('envMap' in material)) return;
  5341. if (materialNames.length && materialNames.indexOf(material.name) === -1) return;
  5342. material.envMap = envMap;
  5343. material.reflectivity = reflectivity;
  5344. material.needsUpdate = true;
  5345. });
  5346. });
  5347. }
  5348. /**
  5349. * Specifies an envMap on an entity, without replacing any existing material
  5350. * properties.
  5351. */
  5352. module.exports = AFRAME.registerComponent('cube-env-map', {
  5353. multiple: true,
  5354. schema: {
  5355. path: { default: '' },
  5356. extension: { default: 'jpg', oneOf: ['jpg', 'png'] },
  5357. format: { default: 'RGBFormat', oneOf: ['RGBFormat', 'RGBAFormat'] },
  5358. enableBackground: { default: false },
  5359. reflectivity: { default: 1, min: 0, max: 1 },
  5360. materials: { default: [] }
  5361. },
  5362. init: function init() {
  5363. var _this = this;
  5364. var data = this.data;
  5365. this.texture = new THREE.CubeTextureLoader().load([data.path + 'posx.' + data.extension, data.path + 'negx.' + data.extension, data.path + 'posy.' + data.extension, data.path + 'negy.' + data.extension, data.path + 'posz.' + data.extension, data.path + 'negz.' + data.extension]);
  5366. this.texture.format = THREE[data.format];
  5367. this.object3dsetHandler = function () {
  5368. var mesh = _this.el.getObject3D('mesh');
  5369. var data = _this.data;
  5370. applyEnvMap(mesh, data.materials, _this.texture, data.reflectivity);
  5371. };
  5372. this.el.addEventListener('object3dset', this.object3dsetHandler);
  5373. },
  5374. update: function update(oldData) {
  5375. var data = this.data;
  5376. var mesh = this.el.getObject3D('mesh');
  5377. var addedMaterialNames = [];
  5378. var removedMaterialNames = [];
  5379. if (data.materials.length) {
  5380. if (oldData.materials) {
  5381. addedMaterialNames = data.materials.filter(function (name) {
  5382. return !oldData.materials.includes(name);
  5383. });
  5384. removedMaterialNames = oldData.materials.filter(function (name) {
  5385. return !data.materials.includes(name);
  5386. });
  5387. } else {
  5388. addedMaterialNames = data.materials;
  5389. }
  5390. }
  5391. if (addedMaterialNames.length) {
  5392. applyEnvMap(mesh, addedMaterialNames, this.texture, data.reflectivity);
  5393. }
  5394. if (removedMaterialNames.length) {
  5395. applyEnvMap(mesh, removedMaterialNames, null, 1);
  5396. }
  5397. if (oldData.materials && data.reflectivity !== oldData.reflectivity) {
  5398. var maintainedMaterialNames = data.materials.filter(function (name) {
  5399. return oldData.materials.includes(name);
  5400. });
  5401. if (maintainedMaterialNames.length) {
  5402. applyEnvMap(mesh, maintainedMaterialNames, this.texture, data.reflectivity);
  5403. }
  5404. }
  5405. if (this.data.enableBackground && !oldData.enableBackground) {
  5406. this.setBackground(this.texture);
  5407. } else if (!this.data.enableBackground && oldData.enableBackground) {
  5408. this.setBackground(null);
  5409. }
  5410. },
  5411. remove: function remove() {
  5412. this.el.removeEventListener('object3dset', this.object3dsetHandler);
  5413. var mesh = this.el.getObject3D('mesh');
  5414. var data = this.data;
  5415. applyEnvMap(mesh, data.materials, null, 1);
  5416. if (data.enableBackground) this.setBackground(null);
  5417. },
  5418. setBackground: function setBackground(texture) {
  5419. this.el.sceneEl.object3D.background = texture;
  5420. }
  5421. });
  5422. },{}],28:[function(require,module,exports){
  5423. 'use strict';
  5424. /* global CANNON */
  5425. /**
  5426. * Based on aframe/examples/showcase/tracked-controls.
  5427. *
  5428. * Handles events coming from the hand-controls.
  5429. * Determines if the entity is grabbed or released.
  5430. * Updates its position to move along the controller.
  5431. */
  5432. module.exports = AFRAME.registerComponent('grab', {
  5433. init: function init() {
  5434. this.system = this.el.sceneEl.systems.physics;
  5435. this.GRABBED_STATE = 'grabbed';
  5436. this.grabbing = false;
  5437. this.hitEl = /** @type {AFRAME.Element} */null;
  5438. this.physics = /** @type {AFRAME.System} */this.el.sceneEl.systems.physics;
  5439. this.constraint = /** @type {CANNON.Constraint} */null;
  5440. // Bind event handlers
  5441. this.onHit = this.onHit.bind(this);
  5442. this.onGripOpen = this.onGripOpen.bind(this);
  5443. this.onGripClose = this.onGripClose.bind(this);
  5444. },
  5445. play: function play() {
  5446. var el = this.el;
  5447. el.addEventListener('hit', this.onHit);
  5448. el.addEventListener('gripdown', this.onGripClose);
  5449. el.addEventListener('gripup', this.onGripOpen);
  5450. el.addEventListener('trackpaddown', this.onGripClose);
  5451. el.addEventListener('trackpadup', this.onGripOpen);
  5452. el.addEventListener('triggerdown', this.onGripClose);
  5453. el.addEventListener('triggerup', this.onGripOpen);
  5454. },
  5455. pause: function pause() {
  5456. var el = this.el;
  5457. el.removeEventListener('hit', this.onHit);
  5458. el.removeEventListener('gripdown', this.onGripClose);
  5459. el.removeEventListener('gripup', this.onGripOpen);
  5460. el.removeEventListener('trackpaddown', this.onGripClose);
  5461. el.removeEventListener('trackpadup', this.onGripOpen);
  5462. el.removeEventListener('triggerdown', this.onGripClose);
  5463. el.removeEventListener('triggerup', this.onGripOpen);
  5464. },
  5465. onGripClose: function onGripClose() {
  5466. this.grabbing = true;
  5467. },
  5468. onGripOpen: function onGripOpen() {
  5469. var hitEl = this.hitEl;
  5470. this.grabbing = false;
  5471. if (!hitEl) {
  5472. return;
  5473. }
  5474. hitEl.removeState(this.GRABBED_STATE);
  5475. this.hitEl = undefined;
  5476. this.system.removeConstraint(this.constraint);
  5477. this.constraint = null;
  5478. },
  5479. onHit: function onHit(evt) {
  5480. var hitEl = evt.detail.el;
  5481. // If the element is already grabbed (it could be grabbed by another controller).
  5482. // If the hand is not grabbing the element does not stick.
  5483. // If we're already grabbing something you can't grab again.
  5484. if (!hitEl || hitEl.is(this.GRABBED_STATE) || !this.grabbing || this.hitEl) {
  5485. return;
  5486. }
  5487. hitEl.addState(this.GRABBED_STATE);
  5488. this.hitEl = hitEl;
  5489. this.constraint = new CANNON.LockConstraint(this.el.body, hitEl.body);
  5490. this.system.addConstraint(this.constraint);
  5491. }
  5492. });
  5493. },{}],29:[function(require,module,exports){
  5494. 'use strict';
  5495. require('./checkpoint');
  5496. require('./cube-env-map');
  5497. require('./grab');
  5498. require('./jump-ability');
  5499. require('./kinematic-body');
  5500. require('./mesh-smooth');
  5501. require('./normal-material');
  5502. require('./sphere-collider');
  5503. },{"./checkpoint":26,"./cube-env-map":27,"./grab":28,"./jump-ability":30,"./kinematic-body":31,"./mesh-smooth":32,"./normal-material":33,"./sphere-collider":34}],30:[function(require,module,exports){
  5504. 'use strict';
  5505. var ACCEL_G = -9.8,
  5506. // m/s^2
  5507. EASING = -15; // m/s^2
  5508. /**
  5509. * Jump ability.
  5510. */
  5511. module.exports = AFRAME.registerComponent('jump-ability', {
  5512. dependencies: ['velocity'],
  5513. /* Schema
  5514. ——————————————————————————————————————————————*/
  5515. schema: {
  5516. on: { default: 'keydown:Space gamepadbuttondown:0' },
  5517. playerHeight: { default: 1.764 },
  5518. maxJumps: { default: 1 },
  5519. distance: { default: 5 },
  5520. debug: { default: false }
  5521. },
  5522. init: function init() {
  5523. this.velocity = 0;
  5524. this.numJumps = 0;
  5525. var beginJump = this.beginJump.bind(this),
  5526. events = this.data.on.split(' ');
  5527. this.bindings = {};
  5528. for (var i = 0; i < events.length; i++) {
  5529. this.bindings[events[i]] = beginJump;
  5530. this.el.addEventListener(events[i], beginJump);
  5531. }
  5532. this.bindings.collide = this.onCollide.bind(this);
  5533. this.el.addEventListener('collide', this.bindings.collide);
  5534. },
  5535. remove: function remove() {
  5536. for (var event in this.bindings) {
  5537. if (this.bindings.hasOwnProperty(event)) {
  5538. this.el.removeEventListener(event, this.bindings[event]);
  5539. delete this.bindings[event];
  5540. }
  5541. }
  5542. this.el.removeEventListener('collide', this.bindings.collide);
  5543. delete this.bindings.collide;
  5544. },
  5545. beginJump: function beginJump() {
  5546. if (this.numJumps < this.data.maxJumps) {
  5547. var data = this.data,
  5548. initialVelocity = Math.sqrt(-2 * data.distance * (ACCEL_G + EASING)),
  5549. v = this.el.getAttribute('velocity');
  5550. this.el.setAttribute('velocity', { x: v.x, y: initialVelocity, z: v.z });
  5551. this.numJumps++;
  5552. this.el.emit('jumpstart');
  5553. }
  5554. },
  5555. onCollide: function onCollide() {
  5556. if (this.numJumps > 0) this.el.emit('jumpend');
  5557. this.numJumps = 0;
  5558. }
  5559. });
  5560. },{}],31:[function(require,module,exports){
  5561. 'use strict';
  5562. /* global CANNON */
  5563. /**
  5564. * Kinematic body.
  5565. *
  5566. * Managed dynamic body, which moves but is not affected (directly) by the
  5567. * physics engine. This is not a true kinematic body, in the sense that we are
  5568. * letting the physics engine _compute_ collisions against it and selectively
  5569. * applying those collisions to the object. The physics engine does not decide
  5570. * the position/velocity/rotation of the element.
  5571. *
  5572. * Used for the camera object, because full physics simulation would create
  5573. * movement that feels unnatural to the player. Bipedal movement does not
  5574. * translate nicely to rigid body physics.
  5575. *
  5576. * See: http://www.learn-cocos2d.com/2013/08/physics-engine-platformer-terrible-idea/
  5577. * And: http://oxleygamedev.blogspot.com/2011/04/player-physics-part-2.html
  5578. */
  5579. var EPS = 0.000001;
  5580. module.exports = AFRAME.registerComponent('kinematic-body', {
  5581. dependencies: ['velocity'],
  5582. /*******************************************************************
  5583. * Schema
  5584. */
  5585. schema: {
  5586. mass: { default: 5 },
  5587. radius: { default: 1.3 },
  5588. userHeight: { default: 1.6 },
  5589. linearDamping: { default: 0.05 },
  5590. enableSlopes: { default: true }
  5591. },
  5592. /*******************************************************************
  5593. * Lifecycle
  5594. */
  5595. init: function init() {
  5596. this.system = this.el.sceneEl.systems.physics;
  5597. this.system.addComponent(this);
  5598. var el = this.el,
  5599. data = this.data,
  5600. position = new CANNON.Vec3().copy(el.getAttribute('position'));
  5601. this.body = new CANNON.Body({
  5602. material: this.system.getMaterial('staticMaterial'),
  5603. position: position,
  5604. mass: data.mass,
  5605. linearDamping: data.linearDamping,
  5606. fixedRotation: true
  5607. });
  5608. this.body.addShape(new CANNON.Sphere(data.radius), new CANNON.Vec3(0, data.radius - data.height, 0));
  5609. this.body.el = this.el;
  5610. this.el.body = this.body;
  5611. this.system.addBody(this.body);
  5612. if (el.hasAttribute('wasd-controls')) {
  5613. console.warn('[kinematic-body] Not compatible with wasd-controls, use movement-controls.');
  5614. }
  5615. },
  5616. remove: function remove() {
  5617. this.system.removeBody(this.body);
  5618. this.system.removeComponent(this);
  5619. delete this.el.body;
  5620. },
  5621. /*******************************************************************
  5622. * Update
  5623. */
  5624. /**
  5625. * Checks CANNON.World for collisions and attempts to apply them to the
  5626. * element automatically, in a player-friendly way.
  5627. *
  5628. * There's extra logic for horizontal surfaces here. The basic requirements:
  5629. * (1) Only apply gravity when not in contact with _any_ horizontal surface.
  5630. * (2) When moving, project the velocity against exactly one ground surface.
  5631. * If in contact with two ground surfaces (e.g. ground + ramp), choose
  5632. * the one that collides with current velocity, if any.
  5633. */
  5634. beforeStep: function beforeStep(t, dt) {
  5635. if (!dt) return;
  5636. var el = this.el;
  5637. var body = this.body;
  5638. body.velocity.copy(el.getAttribute('velocity'));
  5639. body.position.copy(el.getAttribute('position'));
  5640. body.position.y += this.data.userHeight;
  5641. },
  5642. step: function () {
  5643. var velocity = new THREE.Vector3(),
  5644. normalizedVelocity = new THREE.Vector3(),
  5645. currentSurfaceNormal = new THREE.Vector3(),
  5646. groundNormal = new THREE.Vector3();
  5647. return function (t, dt) {
  5648. if (!dt) return;
  5649. var body = this.body,
  5650. data = this.data,
  5651. didCollide = false,
  5652. height = void 0,
  5653. groundHeight = -Infinity,
  5654. groundBody = void 0,
  5655. contacts = this.system.getContacts();
  5656. dt = Math.min(dt, this.system.data.maxInterval * 1000);
  5657. groundNormal.set(0, 0, 0);
  5658. velocity.copy(this.el.getAttribute('velocity'));
  5659. body.velocity.copy(velocity);
  5660. for (var i = 0, contact; contact = contacts[i]; i++) {
  5661. // 1. Find any collisions involving this element. Get the contact
  5662. // normal, and make sure it's oriented _out_ of the other object and
  5663. // enabled (body.collisionReponse is true for both bodies)
  5664. if (!contact.enabled) {
  5665. continue;
  5666. }
  5667. if (body.id === contact.bi.id) {
  5668. contact.ni.negate(currentSurfaceNormal);
  5669. } else if (body.id === contact.bj.id) {
  5670. currentSurfaceNormal.copy(contact.ni);
  5671. } else {
  5672. continue;
  5673. }
  5674. didCollide = body.velocity.dot(currentSurfaceNormal) < -EPS;
  5675. if (didCollide && currentSurfaceNormal.y <= 0.5) {
  5676. // 2. If current trajectory attempts to move _through_ another
  5677. // object, project the velocity against the collision plane to
  5678. // prevent passing through.
  5679. velocity = velocity.projectOnPlane(currentSurfaceNormal);
  5680. } else if (currentSurfaceNormal.y > 0.5) {
  5681. // 3. If in contact with something roughly horizontal (+/- 45º) then
  5682. // consider that the current ground. Only the highest qualifying
  5683. // ground is retained.
  5684. height = body.id === contact.bi.id ? Math.abs(contact.rj.y + contact.bj.position.y) : Math.abs(contact.ri.y + contact.bi.position.y);
  5685. if (height > groundHeight) {
  5686. groundHeight = height;
  5687. groundNormal.copy(currentSurfaceNormal);
  5688. groundBody = body.id === contact.bi.id ? contact.bj : contact.bi;
  5689. }
  5690. }
  5691. }
  5692. normalizedVelocity.copy(velocity).normalize();
  5693. if (groundBody && normalizedVelocity.y < 0.5) {
  5694. if (!data.enableSlopes) {
  5695. groundNormal.set(0, 1, 0);
  5696. } else if (groundNormal.y < 1 - EPS) {
  5697. groundNormal.copy(this.raycastToGround(groundBody, groundNormal));
  5698. }
  5699. // 4. Project trajectory onto the top-most ground object, unless
  5700. // trajectory is > 45º.
  5701. velocity = velocity.projectOnPlane(groundNormal);
  5702. } else if (this.system.driver.world) {
  5703. // 5. If not in contact with anything horizontal, apply world gravity.
  5704. // TODO - Why is the 4x scalar necessary.
  5705. // NOTE: Does not work if physics runs on a worker.
  5706. velocity.add(this.system.driver.world.gravity.scale(dt * 4.0 / 1000));
  5707. }
  5708. // 6. If the ground surface has a velocity, apply it directly to current
  5709. // position, not velocity, to preserve relative velocity.
  5710. if (groundBody && groundBody.el && groundBody.el.components.velocity) {
  5711. var groundVelocity = groundBody.el.getAttribute('velocity');
  5712. body.position.copy({
  5713. x: body.position.x + groundVelocity.x * dt / 1000,
  5714. y: body.position.y + groundVelocity.y * dt / 1000,
  5715. z: body.position.z + groundVelocity.z * dt / 1000
  5716. });
  5717. }
  5718. body.velocity.copy(velocity);
  5719. body.position.y -= data.userHeight;
  5720. this.el.setAttribute('velocity', body.velocity);
  5721. this.el.setAttribute('position', body.position);
  5722. };
  5723. }(),
  5724. /**
  5725. * When walking on complex surfaces (trimeshes, borders between two shapes),
  5726. * the collision normals returned for the player sphere can be very
  5727. * inconsistent. To address this, raycast straight down, find the collision
  5728. * normal, and return whichever normal is more vertical.
  5729. * @param {CANNON.Body} groundBody
  5730. * @param {CANNON.Vec3} groundNormal
  5731. * @return {CANNON.Vec3}
  5732. */
  5733. raycastToGround: function raycastToGround(groundBody, groundNormal) {
  5734. var ray = void 0,
  5735. hitNormal = void 0,
  5736. vFrom = this.body.position,
  5737. vTo = this.body.position.clone();
  5738. vTo.y -= this.data.height;
  5739. ray = new CANNON.Ray(vFrom, vTo);
  5740. ray._updateDirection(); // TODO - Report bug.
  5741. ray.intersectBody(groundBody);
  5742. if (!ray.hasHit) return groundNormal;
  5743. // Compare ABS, in case we're projecting against the inside of the face.
  5744. hitNormal = ray.result.hitNormalWorld;
  5745. return Math.abs(hitNormal.y) > Math.abs(groundNormal.y) ? hitNormal : groundNormal;
  5746. }
  5747. });
  5748. },{}],32:[function(require,module,exports){
  5749. 'use strict';
  5750. /**
  5751. * Apply this component to models that looks "blocky", to have Three.js compute
  5752. * vertex normals on the fly for a "smoother" look.
  5753. */
  5754. module.exports = AFRAME.registerComponent('mesh-smooth', {
  5755. init: function init() {
  5756. this.el.addEventListener('model-loaded', function (e) {
  5757. e.detail.model.traverse(function (node) {
  5758. if (node.isMesh) node.geometry.computeVertexNormals();
  5759. });
  5760. });
  5761. }
  5762. });
  5763. },{}],33:[function(require,module,exports){
  5764. 'use strict';
  5765. /**
  5766. * Recursively applies a MeshNormalMaterial to the entity, such that
  5767. * face colors are determined by their orientation. Helpful for
  5768. * debugging geometry
  5769. */
  5770. module.exports = AFRAME.registerComponent('normal-material', {
  5771. init: function init() {
  5772. this.material = new THREE.MeshNormalMaterial({ flatShading: true });
  5773. this.applyMaterial = this.applyMaterial.bind(this);
  5774. this.el.addEventListener('object3dset', this.applyMaterial);
  5775. },
  5776. remove: function remove() {
  5777. this.el.removeEventListener('object3dset', this.applyMaterial);
  5778. },
  5779. applyMaterial: function applyMaterial() {
  5780. var _this = this;
  5781. this.el.object3D.traverse(function (node) {
  5782. if (node.isMesh) node.material = _this.material;
  5783. });
  5784. }
  5785. });
  5786. },{}],34:[function(require,module,exports){
  5787. 'use strict';
  5788. /**
  5789. * Based on aframe/examples/showcase/tracked-controls.
  5790. *
  5791. * Implement bounding sphere collision detection for entities with a mesh.
  5792. * Sets the specified state on the intersected entities.
  5793. *
  5794. * @property {string} objects - Selector of the entities to test for collision.
  5795. * @property {string} state - State to set on collided entities.
  5796. *
  5797. */
  5798. module.exports = AFRAME.registerComponent('sphere-collider', {
  5799. schema: {
  5800. objects: { default: '' },
  5801. state: { default: 'collided' },
  5802. radius: { default: 0.05 },
  5803. watch: { default: true }
  5804. },
  5805. init: function init() {
  5806. /** @type {MutationObserver} */
  5807. this.observer = null;
  5808. /** @type {Array<Element>} Elements to watch for collisions. */
  5809. this.els = [];
  5810. /** @type {Array<Element>} Elements currently in collision state. */
  5811. this.collisions = [];
  5812. this.handleHit = this.handleHit.bind(this);
  5813. this.handleHitEnd = this.handleHitEnd.bind(this);
  5814. },
  5815. remove: function remove() {
  5816. this.pause();
  5817. },
  5818. play: function play() {
  5819. var sceneEl = this.el.sceneEl;
  5820. if (this.data.watch) {
  5821. this.observer = new MutationObserver(this.update.bind(this, null));
  5822. this.observer.observe(sceneEl, { childList: true, subtree: true });
  5823. }
  5824. },
  5825. pause: function pause() {
  5826. if (this.observer) {
  5827. this.observer.disconnect();
  5828. this.observer = null;
  5829. }
  5830. },
  5831. /**
  5832. * Update list of entities to test for collision.
  5833. */
  5834. update: function update() {
  5835. var data = this.data;
  5836. var objectEls = void 0;
  5837. // Push entities into list of els to intersect.
  5838. if (data.objects) {
  5839. objectEls = this.el.sceneEl.querySelectorAll(data.objects);
  5840. } else {
  5841. // If objects not defined, intersect with everything.
  5842. objectEls = this.el.sceneEl.children;
  5843. }
  5844. // Convert from NodeList to Array
  5845. this.els = Array.prototype.slice.call(objectEls);
  5846. },
  5847. tick: function () {
  5848. var position = new THREE.Vector3(),
  5849. meshPosition = new THREE.Vector3(),
  5850. colliderScale = new THREE.Vector3(),
  5851. distanceMap = new Map();
  5852. return function () {
  5853. var el = this.el,
  5854. data = this.data,
  5855. mesh = el.getObject3D('mesh'),
  5856. collisions = [];
  5857. var colliderRadius = void 0;
  5858. if (!mesh) {
  5859. return;
  5860. }
  5861. distanceMap.clear();
  5862. position.copy(el.object3D.getWorldPosition());
  5863. el.object3D.getWorldScale(colliderScale);
  5864. colliderRadius = data.radius * scaleFactor(colliderScale);
  5865. // Update collision list.
  5866. this.els.forEach(intersect);
  5867. // Emit events and add collision states, in order of distance.
  5868. collisions.sort(function (a, b) {
  5869. return distanceMap.get(a) > distanceMap.get(b) ? 1 : -1;
  5870. }).forEach(this.handleHit);
  5871. // Remove collision state from current element.
  5872. if (collisions.length === 0) {
  5873. el.emit('hit', { el: null });
  5874. }
  5875. // Remove collision state from other elements.
  5876. this.collisions.filter(function (el) {
  5877. return !distanceMap.has(el);
  5878. }).forEach(this.handleHitEnd);
  5879. // Store new collisions
  5880. this.collisions = collisions;
  5881. // Bounding sphere collision detection
  5882. function intersect(el) {
  5883. var radius = void 0,
  5884. mesh = void 0,
  5885. distance = void 0,
  5886. box = void 0,
  5887. extent = void 0,
  5888. size = void 0;
  5889. if (!el.isEntity) {
  5890. return;
  5891. }
  5892. mesh = el.getObject3D('mesh');
  5893. if (!mesh) {
  5894. return;
  5895. }
  5896. box = new THREE.Box3().setFromObject(mesh);
  5897. size = box.getSize();
  5898. extent = Math.max(size.x, size.y, size.z) / 2;
  5899. radius = Math.sqrt(2 * extent * extent);
  5900. box.getCenter(meshPosition);
  5901. if (!radius) {
  5902. return;
  5903. }
  5904. distance = position.distanceTo(meshPosition);
  5905. if (distance < radius + colliderRadius) {
  5906. collisions.push(el);
  5907. distanceMap.set(el, distance);
  5908. }
  5909. }
  5910. // use max of scale factors to maintain bounding sphere collision
  5911. function scaleFactor(scaleVec) {
  5912. return Math.max.apply(null, scaleVec.toArray());
  5913. }
  5914. };
  5915. }(),
  5916. handleHit: function handleHit(targetEl) {
  5917. targetEl.emit('hit');
  5918. targetEl.addState(this.data.state);
  5919. this.el.emit('hit', { el: targetEl });
  5920. },
  5921. handleHitEnd: function handleHitEnd(targetEl) {
  5922. targetEl.emit('hitend');
  5923. targetEl.removeState(this.data.state);
  5924. this.el.emit('hitend', { el: targetEl });
  5925. }
  5926. });
  5927. },{}],35:[function(require,module,exports){
  5928. 'use strict';
  5929. require('./nav-mesh');
  5930. require('./nav-agent');
  5931. require('./system');
  5932. },{"./nav-agent":36,"./nav-mesh":37,"./system":38}],36:[function(require,module,exports){
  5933. 'use strict';
  5934. module.exports = AFRAME.registerComponent('nav-agent', {
  5935. schema: {
  5936. destination: { type: 'vec3' },
  5937. active: { default: false },
  5938. speed: { default: 2 }
  5939. },
  5940. init: function init() {
  5941. this.system = this.el.sceneEl.systems.nav;
  5942. this.system.addAgent(this);
  5943. this.group = null;
  5944. this.path = [];
  5945. this.raycaster = new THREE.Raycaster();
  5946. },
  5947. remove: function remove() {
  5948. this.system.removeAgent(this);
  5949. },
  5950. update: function update() {
  5951. this.path.length = 0;
  5952. },
  5953. updateNavLocation: function updateNavLocation() {
  5954. this.group = null;
  5955. this.path = [];
  5956. },
  5957. tick: function () {
  5958. var vDest = new THREE.Vector3();
  5959. var vDelta = new THREE.Vector3();
  5960. var vNext = new THREE.Vector3();
  5961. return function (t, dt) {
  5962. var el = this.el;
  5963. var data = this.data;
  5964. var raycaster = this.raycaster;
  5965. var speed = data.speed * dt / 1000;
  5966. if (!data.active) return;
  5967. // Use PatrolJS pathfinding system to get shortest path to target.
  5968. if (!this.path.length) {
  5969. var position = this.el.object3D.position;
  5970. this.group = this.group || this.system.getGroup(position);
  5971. this.path = this.system.getPath(position, vDest.copy(data.destination), this.group) || [];
  5972. el.emit('navigation-start');
  5973. }
  5974. // If no path is found, exit.
  5975. if (!this.path.length) {
  5976. console.warn('[nav] Unable to find path to %o.', data.destination);
  5977. this.el.setAttribute('nav-agent', { active: false });
  5978. el.emit('navigation-end');
  5979. return;
  5980. }
  5981. // Current segment is a vector from current position to next waypoint.
  5982. var vCurrent = el.object3D.position;
  5983. var vWaypoint = this.path[0];
  5984. vDelta.subVectors(vWaypoint, vCurrent);
  5985. var distance = vDelta.length();
  5986. var gazeTarget = void 0;
  5987. if (distance < speed) {
  5988. // If <1 step from current waypoint, discard it and move toward next.
  5989. this.path.shift();
  5990. // After discarding the last waypoint, exit pathfinding.
  5991. if (!this.path.length) {
  5992. this.el.setAttribute('nav-agent', { active: false });
  5993. el.emit('navigation-end');
  5994. return;
  5995. }
  5996. vNext.copy(vCurrent);
  5997. gazeTarget = this.path[0];
  5998. } else {
  5999. // If still far away from next waypoint, find next position for
  6000. // the current frame.
  6001. vNext.copy(vDelta.setLength(speed)).add(vCurrent);
  6002. gazeTarget = vWaypoint;
  6003. }
  6004. // Look at the next waypoint.
  6005. gazeTarget.y = vCurrent.y;
  6006. el.object3D.lookAt(gazeTarget);
  6007. // Raycast against the nav mesh, to keep the agent moving along the
  6008. // ground, not traveling in a straight line from higher to lower waypoints.
  6009. raycaster.ray.origin.copy(vNext);
  6010. raycaster.ray.origin.y += 1.5;
  6011. raycaster.ray.direction.y = -1;
  6012. var intersections = raycaster.intersectObject(this.system.getNavMesh());
  6013. if (!intersections.length) {
  6014. // Raycasting failed. Step toward the waypoint and hope for the best.
  6015. vCurrent.copy(vNext);
  6016. } else {
  6017. // Re-project next position onto nav mesh.
  6018. vDelta.subVectors(intersections[0].point, vCurrent);
  6019. vCurrent.add(vDelta.setLength(speed));
  6020. }
  6021. };
  6022. }()
  6023. });
  6024. },{}],37:[function(require,module,exports){
  6025. 'use strict';
  6026. /**
  6027. * nav-mesh
  6028. *
  6029. * Waits for a mesh to be loaded on the current entity, then sets it as the
  6030. * nav mesh in the pathfinding system.
  6031. */
  6032. module.exports = AFRAME.registerComponent('nav-mesh', {
  6033. init: function init() {
  6034. this.system = this.el.sceneEl.systems.nav;
  6035. this.hasLoadedNavMesh = false;
  6036. this.el.addEventListener('object3dset', this.loadNavMesh.bind(this));
  6037. },
  6038. play: function play() {
  6039. if (!this.hasLoadedNavMesh) this.loadNavMesh();
  6040. },
  6041. loadNavMesh: function loadNavMesh() {
  6042. var object = this.el.getObject3D('mesh');
  6043. var scene = this.el.sceneEl.object3D;
  6044. if (!object) return;
  6045. var navMesh = void 0;
  6046. object.traverse(function (node) {
  6047. if (node.isMesh) navMesh = node;
  6048. });
  6049. if (!navMesh) return;
  6050. var navMeshGeometry = navMesh.geometry.isBufferGeometry ? new THREE.Geometry().fromBufferGeometry(navMesh.geometry) : navMesh.geometry.clone();
  6051. scene.updateMatrixWorld();
  6052. navMeshGeometry.applyMatrix(navMesh.matrixWorld);
  6053. this.system.setNavMeshGeometry(navMeshGeometry);
  6054. this.hasLoadedNavMesh = true;
  6055. }
  6056. });
  6057. },{}],38:[function(require,module,exports){
  6058. 'use strict';
  6059. var _require = require('three-pathfinding'),
  6060. Pathfinding = _require.Pathfinding;
  6061. var pathfinder = new Pathfinding();
  6062. var ZONE = 'level';
  6063. /**
  6064. * nav
  6065. *
  6066. * Pathfinding system, using PatrolJS.
  6067. */
  6068. module.exports = AFRAME.registerSystem('nav', {
  6069. init: function init() {
  6070. this.navMesh = null;
  6071. this.agents = new Set();
  6072. },
  6073. /**
  6074. * @param {THREE.Geometry} geometry
  6075. */
  6076. setNavMeshGeometry: function setNavMeshGeometry(geometry) {
  6077. this.navMesh = new THREE.Mesh(geometry);
  6078. pathfinder.setZoneData(ZONE, Pathfinding.createZone(geometry));
  6079. Array.from(this.agents).forEach(function (agent) {
  6080. return agent.updateNavLocation();
  6081. });
  6082. },
  6083. /**
  6084. * @return {THREE.Mesh}
  6085. */
  6086. getNavMesh: function getNavMesh() {
  6087. return this.navMesh;
  6088. },
  6089. /**
  6090. * @param {NavAgent} ctrl
  6091. */
  6092. addAgent: function addAgent(ctrl) {
  6093. this.agents.add(ctrl);
  6094. },
  6095. /**
  6096. * @param {NavAgent} ctrl
  6097. */
  6098. removeAgent: function removeAgent(ctrl) {
  6099. this.agents.delete(ctrl);
  6100. },
  6101. /**
  6102. * @param {THREE.Vector3} start
  6103. * @param {THREE.Vector3} end
  6104. * @param {number} groupID
  6105. * @return {Array<THREE.Vector3>}
  6106. */
  6107. getPath: function getPath(start, end, groupID) {
  6108. return this.navMesh ? pathfinder.findPath(start, end, ZONE, groupID) : null;
  6109. },
  6110. /**
  6111. * @param {THREE.Vector3} position
  6112. * @return {number}
  6113. */
  6114. getGroup: function getGroup(position) {
  6115. return this.navMesh ? pathfinder.getGroup(ZONE, position) : null;
  6116. },
  6117. /**
  6118. * @param {THREE.Vector3} position
  6119. * @param {number} groupID
  6120. * @return {Node}
  6121. */
  6122. getNode: function getNode(position, groupID) {
  6123. return this.navMesh ? pathfinder.getClosestNode(position, ZONE, groupID, true) : null;
  6124. },
  6125. /**
  6126. * @param {THREE.Vector3} start Starting position.
  6127. * @param {THREE.Vector3} end Desired ending position.
  6128. * @param {number} groupID
  6129. * @param {Node} node
  6130. * @param {THREE.Vector3} endTarget (Output) Adjusted step end position.
  6131. * @return {Node} Current node, after step is taken.
  6132. */
  6133. clampStep: function clampStep(start, end, groupID, node, endTarget) {
  6134. if (!this.navMesh) {
  6135. endTarget.copy(end);
  6136. return null;
  6137. } else if (!node) {
  6138. endTarget.copy(end);
  6139. return this.getNode(end, groupID);
  6140. }
  6141. return pathfinder.clampStep(start, end, node, ZONE, groupID, endTarget);
  6142. }
  6143. });
  6144. },{"three-pathfinding":11}],39:[function(require,module,exports){
  6145. 'use strict';
  6146. /**
  6147. * Flat grid.
  6148. *
  6149. * Defaults to 75x75.
  6150. */
  6151. module.exports = AFRAME.registerPrimitive('a-grid', {
  6152. defaultComponents: {
  6153. geometry: {
  6154. primitive: 'plane',
  6155. width: 75,
  6156. height: 75
  6157. },
  6158. rotation: { x: -90, y: 0, z: 0 },
  6159. material: {
  6160. src: 'url(https://cdn.rawgit.com/donmccurdy/aframe-extras/v1.16.3/assets/grid.png)',
  6161. repeat: '75 75'
  6162. }
  6163. },
  6164. mappings: {
  6165. width: 'geometry.width',
  6166. height: 'geometry.height',
  6167. src: 'material.src'
  6168. }
  6169. });
  6170. },{}],40:[function(require,module,exports){
  6171. 'use strict';
  6172. var vg = require('../../lib/hex-grid.min.js');
  6173. var defaultHexGrid = require('../../lib/default-hex-grid');
  6174. /**
  6175. * Hex grid.
  6176. */
  6177. module.exports.Primitive = AFRAME.registerPrimitive('a-hexgrid', {
  6178. defaultComponents: {
  6179. 'hexgrid': {}
  6180. },
  6181. mappings: {
  6182. src: 'hexgrid.src'
  6183. }
  6184. });
  6185. module.exports.Component = AFRAME.registerComponent('hexgrid', {
  6186. dependencies: ['material'],
  6187. schema: {
  6188. src: { type: 'asset' }
  6189. },
  6190. init: function init() {
  6191. var _this = this;
  6192. var data = this.data;
  6193. if (data.src) {
  6194. fetch(data.src).then(function (response) {
  6195. return response.json();
  6196. }).then(function (json) {
  6197. return _this.addMesh(json);
  6198. });
  6199. } else {
  6200. this.addMesh(defaultHexGrid);
  6201. }
  6202. },
  6203. addMesh: function addMesh(json) {
  6204. var grid = new vg.HexGrid();
  6205. grid.fromJSON(json);
  6206. var board = new vg.Board(grid);
  6207. board.generateTilemap();
  6208. this.el.setObject3D('mesh', board.group);
  6209. this.addMaterial();
  6210. },
  6211. addMaterial: function addMaterial() {
  6212. var materialComponent = this.el.components.material;
  6213. var material = (materialComponent || {}).material;
  6214. if (!material) return;
  6215. this.el.object3D.traverse(function (node) {
  6216. if (node.isMesh) {
  6217. node.material = material;
  6218. }
  6219. });
  6220. },
  6221. remove: function remove() {
  6222. this.el.removeObject3D('mesh');
  6223. }
  6224. });
  6225. },{"../../lib/default-hex-grid":7,"../../lib/hex-grid.min.js":9}],41:[function(require,module,exports){
  6226. 'use strict';
  6227. /**
  6228. * Flat-shaded ocean primitive.
  6229. *
  6230. * Based on a Codrops tutorial:
  6231. * http://tympanus.net/codrops/2016/04/26/the-aviator-animating-basic-3d-scene-threejs/
  6232. */
  6233. module.exports.Primitive = AFRAME.registerPrimitive('a-ocean', {
  6234. defaultComponents: {
  6235. ocean: {},
  6236. rotation: { x: -90, y: 0, z: 0 }
  6237. },
  6238. mappings: {
  6239. width: 'ocean.width',
  6240. depth: 'ocean.depth',
  6241. density: 'ocean.density',
  6242. amplitude: 'ocean.amplitude',
  6243. amplitudeVariance: 'ocean.amplitudeVariance',
  6244. speed: 'ocean.speed',
  6245. speedVariance: 'ocean.speedVariance',
  6246. color: 'ocean.color',
  6247. opacity: 'ocean.opacity'
  6248. }
  6249. });
  6250. module.exports.Component = AFRAME.registerComponent('ocean', {
  6251. schema: {
  6252. // Dimensions of the ocean area.
  6253. width: { default: 10, min: 0 },
  6254. depth: { default: 10, min: 0 },
  6255. // Density of waves.
  6256. density: { default: 10 },
  6257. // Wave amplitude and variance.
  6258. amplitude: { default: 0.1 },
  6259. amplitudeVariance: { default: 0.3 },
  6260. // Wave speed and variance.
  6261. speed: { default: 1 },
  6262. speedVariance: { default: 2 },
  6263. // Material.
  6264. color: { default: '#7AD2F7', type: 'color' },
  6265. opacity: { default: 0.8 }
  6266. },
  6267. /**
  6268. * Use play() instead of init(), because component mappings – unavailable as dependencies – are
  6269. * not guaranteed to have parsed when this component is initialized.
  6270. */
  6271. play: function play() {
  6272. var el = this.el,
  6273. data = this.data;
  6274. var material = el.components.material;
  6275. var geometry = new THREE.PlaneGeometry(data.width, data.depth, data.density, data.density);
  6276. geometry.mergeVertices();
  6277. this.waves = [];
  6278. for (var v, i = 0, l = geometry.vertices.length; i < l; i++) {
  6279. v = geometry.vertices[i];
  6280. this.waves.push({
  6281. z: v.z,
  6282. ang: Math.random() * Math.PI * 2,
  6283. amp: data.amplitude + Math.random() * data.amplitudeVariance,
  6284. speed: (data.speed + Math.random() * data.speedVariance) / 1000 // radians / frame
  6285. });
  6286. }
  6287. if (!material) {
  6288. material = {};
  6289. material.material = new THREE.MeshPhongMaterial({
  6290. color: data.color,
  6291. transparent: data.opacity < 1,
  6292. opacity: data.opacity,
  6293. shading: THREE.FlatShading
  6294. });
  6295. }
  6296. this.mesh = new THREE.Mesh(geometry, material.material);
  6297. el.setObject3D('mesh', this.mesh);
  6298. },
  6299. remove: function remove() {
  6300. this.el.removeObject3D('mesh');
  6301. },
  6302. tick: function tick(t, dt) {
  6303. if (!dt) return;
  6304. var verts = this.mesh.geometry.vertices;
  6305. for (var v, vprops, i = 0; v = verts[i]; i++) {
  6306. vprops = this.waves[i];
  6307. v.z = vprops.z + Math.sin(vprops.ang) * vprops.amp;
  6308. vprops.ang += vprops.speed * dt;
  6309. }
  6310. this.mesh.geometry.verticesNeedUpdate = true;
  6311. }
  6312. });
  6313. },{}],42:[function(require,module,exports){
  6314. 'use strict';
  6315. /**
  6316. * Tube following a custom path.
  6317. *
  6318. * Usage:
  6319. *
  6320. * ```html
  6321. * <a-tube path="5 0 5, 5 0 -5, -5 0 -5" radius="0.5"></a-tube>
  6322. * ```
  6323. */
  6324. module.exports.Primitive = AFRAME.registerPrimitive('a-tube', {
  6325. defaultComponents: {
  6326. tube: {}
  6327. },
  6328. mappings: {
  6329. path: 'tube.path',
  6330. segments: 'tube.segments',
  6331. radius: 'tube.radius',
  6332. 'radial-segments': 'tube.radialSegments',
  6333. closed: 'tube.closed'
  6334. }
  6335. });
  6336. module.exports.Component = AFRAME.registerComponent('tube', {
  6337. schema: {
  6338. path: { default: [] },
  6339. segments: { default: 64 },
  6340. radius: { default: 1 },
  6341. radialSegments: { default: 8 },
  6342. closed: { default: false }
  6343. },
  6344. init: function init() {
  6345. var el = this.el,
  6346. data = this.data;
  6347. var material = el.components.material;
  6348. if (!data.path.length) {
  6349. console.error('[a-tube] `path` property expected but not found.');
  6350. return;
  6351. }
  6352. var curve = new THREE.CatmullRomCurve3(data.path.map(function (point) {
  6353. point = point.split(' ');
  6354. return new THREE.Vector3(Number(point[0]), Number(point[1]), Number(point[2]));
  6355. }));
  6356. var geometry = new THREE.TubeGeometry(curve, data.segments, data.radius, data.radialSegments, data.closed);
  6357. if (!material) {
  6358. material = {};
  6359. material.material = new THREE.MeshPhongMaterial();
  6360. }
  6361. this.mesh = new THREE.Mesh(geometry, material.material);
  6362. this.el.setObject3D('mesh', this.mesh);
  6363. },
  6364. update: function update(prevData) {
  6365. if (!Object.keys(prevData).length) return;
  6366. this.remove();
  6367. this.init();
  6368. },
  6369. remove: function remove() {
  6370. if (this.mesh) this.el.removeObject3D('mesh');
  6371. }
  6372. });
  6373. },{}],43:[function(require,module,exports){
  6374. 'use strict';
  6375. require('./a-grid');
  6376. require('./a-hexgrid');
  6377. require('./a-ocean');
  6378. require('./a-tube');
  6379. },{"./a-grid":39,"./a-hexgrid":40,"./a-ocean":41,"./a-tube":42}]},{},[1]);