aframe-extras.js 338 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477
  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":23,"./src/misc":28,"./src/pathfinding":34,"./src/primitives":42}],3:[function(require,module,exports){
  12. 'use strict';
  13. /**
  14. * @author mrdoob / http://mrdoob.com/
  15. * @author Mugen87 / https://github.com/Mugen87
  16. */
  17. module.exports = THREE.ColladaLoader = function (manager) {
  18. this.manager = manager !== undefined ? manager : THREE.DefaultLoadingManager;
  19. };
  20. THREE.ColladaLoader.prototype = {
  21. constructor: THREE.ColladaLoader,
  22. crossOrigin: 'anonymous',
  23. load: function load(url, onLoad, onProgress, onError) {
  24. var scope = this;
  25. var path = scope.path === undefined ? THREE.LoaderUtils.extractUrlBase(url) : scope.path;
  26. var loader = new THREE.FileLoader(scope.manager);
  27. loader.setPath(scope.path);
  28. loader.load(url, function (text) {
  29. onLoad(scope.parse(text, path));
  30. }, onProgress, onError);
  31. },
  32. setPath: function setPath(value) {
  33. this.path = value;
  34. return this;
  35. },
  36. setResourcePath: function setResourcePath(value) {
  37. this.resourcePath = value;
  38. return this;
  39. },
  40. options: {
  41. set convertUpAxis(value) {
  42. console.warn('THREE.ColladaLoader: options.convertUpAxis() has been removed. Up axis is converted automatically.');
  43. }
  44. },
  45. setCrossOrigin: function setCrossOrigin(value) {
  46. this.crossOrigin = value;
  47. return this;
  48. },
  49. parse: function parse(text, path) {
  50. function getElementsByTagName(xml, name) {
  51. // Non recursive xml.getElementsByTagName() ...
  52. var array = [];
  53. var childNodes = xml.childNodes;
  54. for (var i = 0, l = childNodes.length; i < l; i++) {
  55. var child = childNodes[i];
  56. if (child.nodeName === name) {
  57. array.push(child);
  58. }
  59. }
  60. return array;
  61. }
  62. function parseStrings(text) {
  63. if (text.length === 0) return [];
  64. var parts = text.trim().split(/\s+/);
  65. var array = new Array(parts.length);
  66. for (var i = 0, l = parts.length; i < l; i++) {
  67. array[i] = parts[i];
  68. }
  69. return array;
  70. }
  71. function parseFloats(text) {
  72. if (text.length === 0) return [];
  73. var parts = text.trim().split(/\s+/);
  74. var array = new Array(parts.length);
  75. for (var i = 0, l = parts.length; i < l; i++) {
  76. array[i] = parseFloat(parts[i]);
  77. }
  78. return array;
  79. }
  80. function parseInts(text) {
  81. if (text.length === 0) return [];
  82. var parts = text.trim().split(/\s+/);
  83. var array = new Array(parts.length);
  84. for (var i = 0, l = parts.length; i < l; i++) {
  85. array[i] = parseInt(parts[i]);
  86. }
  87. return array;
  88. }
  89. function parseId(text) {
  90. return text.substring(1);
  91. }
  92. function generateId() {
  93. return 'three_default_' + count++;
  94. }
  95. function isEmpty(object) {
  96. return Object.keys(object).length === 0;
  97. }
  98. // asset
  99. function parseAsset(xml) {
  100. return {
  101. unit: parseAssetUnit(getElementsByTagName(xml, 'unit')[0]),
  102. upAxis: parseAssetUpAxis(getElementsByTagName(xml, 'up_axis')[0])
  103. };
  104. }
  105. function parseAssetUnit(xml) {
  106. if (xml !== undefined && xml.hasAttribute('meter') === true) {
  107. return parseFloat(xml.getAttribute('meter'));
  108. } else {
  109. return 1; // default 1 meter
  110. }
  111. }
  112. function parseAssetUpAxis(xml) {
  113. return xml !== undefined ? xml.textContent : 'Y_UP';
  114. }
  115. // library
  116. function parseLibrary(xml, libraryName, nodeName, parser) {
  117. var library = getElementsByTagName(xml, libraryName)[0];
  118. if (library !== undefined) {
  119. var elements = getElementsByTagName(library, nodeName);
  120. for (var i = 0; i < elements.length; i++) {
  121. parser(elements[i]);
  122. }
  123. }
  124. }
  125. function buildLibrary(data, builder) {
  126. for (var name in data) {
  127. var object = data[name];
  128. object.build = builder(data[name]);
  129. }
  130. }
  131. // get
  132. function getBuild(data, builder) {
  133. if (data.build !== undefined) return data.build;
  134. data.build = builder(data);
  135. return data.build;
  136. }
  137. // animation
  138. function parseAnimation(xml) {
  139. var data = {
  140. sources: {},
  141. samplers: {},
  142. channels: {}
  143. };
  144. for (var i = 0, l = xml.childNodes.length; i < l; i++) {
  145. var child = xml.childNodes[i];
  146. if (child.nodeType !== 1) continue;
  147. var id;
  148. switch (child.nodeName) {
  149. case 'source':
  150. id = child.getAttribute('id');
  151. data.sources[id] = parseSource(child);
  152. break;
  153. case 'sampler':
  154. id = child.getAttribute('id');
  155. data.samplers[id] = parseAnimationSampler(child);
  156. break;
  157. case 'channel':
  158. id = child.getAttribute('target');
  159. data.channels[id] = parseAnimationChannel(child);
  160. break;
  161. default:
  162. console.log(child);
  163. }
  164. }
  165. library.animations[xml.getAttribute('id')] = data;
  166. }
  167. function parseAnimationSampler(xml) {
  168. var data = {
  169. inputs: {}
  170. };
  171. for (var i = 0, l = xml.childNodes.length; i < l; i++) {
  172. var child = xml.childNodes[i];
  173. if (child.nodeType !== 1) continue;
  174. switch (child.nodeName) {
  175. case 'input':
  176. var id = parseId(child.getAttribute('source'));
  177. var semantic = child.getAttribute('semantic');
  178. data.inputs[semantic] = id;
  179. break;
  180. }
  181. }
  182. return data;
  183. }
  184. function parseAnimationChannel(xml) {
  185. var data = {};
  186. var target = xml.getAttribute('target');
  187. // parsing SID Addressing Syntax
  188. var parts = target.split('/');
  189. var id = parts.shift();
  190. var sid = parts.shift();
  191. // check selection syntax
  192. var arraySyntax = sid.indexOf('(') !== -1;
  193. var memberSyntax = sid.indexOf('.') !== -1;
  194. if (memberSyntax) {
  195. // member selection access
  196. parts = sid.split('.');
  197. sid = parts.shift();
  198. data.member = parts.shift();
  199. } else if (arraySyntax) {
  200. // array-access syntax. can be used to express fields in one-dimensional vectors or two-dimensional matrices.
  201. var indices = sid.split('(');
  202. sid = indices.shift();
  203. for (var i = 0; i < indices.length; i++) {
  204. indices[i] = parseInt(indices[i].replace(/\)/, ''));
  205. }
  206. data.indices = indices;
  207. }
  208. data.id = id;
  209. data.sid = sid;
  210. data.arraySyntax = arraySyntax;
  211. data.memberSyntax = memberSyntax;
  212. data.sampler = parseId(xml.getAttribute('source'));
  213. return data;
  214. }
  215. function buildAnimation(data) {
  216. var tracks = [];
  217. var channels = data.channels;
  218. var samplers = data.samplers;
  219. var sources = data.sources;
  220. for (var target in channels) {
  221. if (channels.hasOwnProperty(target)) {
  222. var channel = channels[target];
  223. var sampler = samplers[channel.sampler];
  224. var inputId = sampler.inputs.INPUT;
  225. var outputId = sampler.inputs.OUTPUT;
  226. var inputSource = sources[inputId];
  227. var outputSource = sources[outputId];
  228. var animation = buildAnimationChannel(channel, inputSource, outputSource);
  229. createKeyframeTracks(animation, tracks);
  230. }
  231. }
  232. return tracks;
  233. }
  234. function getAnimation(id) {
  235. return getBuild(library.animations[id], buildAnimation);
  236. }
  237. function buildAnimationChannel(channel, inputSource, outputSource) {
  238. var node = library.nodes[channel.id];
  239. var object3D = getNode(node.id);
  240. var transform = node.transforms[channel.sid];
  241. var defaultMatrix = node.matrix.clone().transpose();
  242. var time, stride;
  243. var i, il, j, jl;
  244. var data = {};
  245. // the collada spec allows the animation of data in various ways.
  246. // depending on the transform type (matrix, translate, rotate, scale), we execute different logic
  247. switch (transform) {
  248. case 'matrix':
  249. for (i = 0, il = inputSource.array.length; i < il; i++) {
  250. time = inputSource.array[i];
  251. stride = i * outputSource.stride;
  252. if (data[time] === undefined) data[time] = {};
  253. if (channel.arraySyntax === true) {
  254. var value = outputSource.array[stride];
  255. var index = channel.indices[0] + 4 * channel.indices[1];
  256. data[time][index] = value;
  257. } else {
  258. for (j = 0, jl = outputSource.stride; j < jl; j++) {
  259. data[time][j] = outputSource.array[stride + j];
  260. }
  261. }
  262. }
  263. break;
  264. case 'translate':
  265. console.warn('THREE.ColladaLoader: Animation transform type "%s" not yet implemented.', transform);
  266. break;
  267. case 'rotate':
  268. console.warn('THREE.ColladaLoader: Animation transform type "%s" not yet implemented.', transform);
  269. break;
  270. case 'scale':
  271. console.warn('THREE.ColladaLoader: Animation transform type "%s" not yet implemented.', transform);
  272. break;
  273. }
  274. var keyframes = prepareAnimationData(data, defaultMatrix);
  275. var animation = {
  276. name: object3D.uuid,
  277. keyframes: keyframes
  278. };
  279. return animation;
  280. }
  281. function prepareAnimationData(data, defaultMatrix) {
  282. var keyframes = [];
  283. // transfer data into a sortable array
  284. for (var time in data) {
  285. keyframes.push({ time: parseFloat(time), value: data[time] });
  286. }
  287. // ensure keyframes are sorted by time
  288. keyframes.sort(ascending);
  289. // now we clean up all animation data, so we can use them for keyframe tracks
  290. for (var i = 0; i < 16; i++) {
  291. transformAnimationData(keyframes, i, defaultMatrix.elements[i]);
  292. }
  293. return keyframes;
  294. // array sort function
  295. function ascending(a, b) {
  296. return a.time - b.time;
  297. }
  298. }
  299. var position = new THREE.Vector3();
  300. var scale = new THREE.Vector3();
  301. var quaternion = new THREE.Quaternion();
  302. function createKeyframeTracks(animation, tracks) {
  303. var keyframes = animation.keyframes;
  304. var name = animation.name;
  305. var times = [];
  306. var positionData = [];
  307. var quaternionData = [];
  308. var scaleData = [];
  309. for (var i = 0, l = keyframes.length; i < l; i++) {
  310. var keyframe = keyframes[i];
  311. var time = keyframe.time;
  312. var value = keyframe.value;
  313. matrix.fromArray(value).transpose();
  314. matrix.decompose(position, quaternion, scale);
  315. times.push(time);
  316. positionData.push(position.x, position.y, position.z);
  317. quaternionData.push(quaternion.x, quaternion.y, quaternion.z, quaternion.w);
  318. scaleData.push(scale.x, scale.y, scale.z);
  319. }
  320. if (positionData.length > 0) tracks.push(new THREE.VectorKeyframeTrack(name + '.position', times, positionData));
  321. if (quaternionData.length > 0) tracks.push(new THREE.QuaternionKeyframeTrack(name + '.quaternion', times, quaternionData));
  322. if (scaleData.length > 0) tracks.push(new THREE.VectorKeyframeTrack(name + '.scale', times, scaleData));
  323. return tracks;
  324. }
  325. function transformAnimationData(keyframes, property, defaultValue) {
  326. var keyframe;
  327. var empty = true;
  328. var i, l;
  329. // check, if values of a property are missing in our keyframes
  330. for (i = 0, l = keyframes.length; i < l; i++) {
  331. keyframe = keyframes[i];
  332. if (keyframe.value[property] === undefined) {
  333. keyframe.value[property] = null; // mark as missing
  334. } else {
  335. empty = false;
  336. }
  337. }
  338. if (empty === true) {
  339. // no values at all, so we set a default value
  340. for (i = 0, l = keyframes.length; i < l; i++) {
  341. keyframe = keyframes[i];
  342. keyframe.value[property] = defaultValue;
  343. }
  344. } else {
  345. // filling gaps
  346. createMissingKeyframes(keyframes, property);
  347. }
  348. }
  349. function createMissingKeyframes(keyframes, property) {
  350. var prev, next;
  351. for (var i = 0, l = keyframes.length; i < l; i++) {
  352. var keyframe = keyframes[i];
  353. if (keyframe.value[property] === null) {
  354. prev = getPrev(keyframes, i, property);
  355. next = getNext(keyframes, i, property);
  356. if (prev === null) {
  357. keyframe.value[property] = next.value[property];
  358. continue;
  359. }
  360. if (next === null) {
  361. keyframe.value[property] = prev.value[property];
  362. continue;
  363. }
  364. interpolate(keyframe, prev, next, property);
  365. }
  366. }
  367. }
  368. function getPrev(keyframes, i, property) {
  369. while (i >= 0) {
  370. var keyframe = keyframes[i];
  371. if (keyframe.value[property] !== null) return keyframe;
  372. i--;
  373. }
  374. return null;
  375. }
  376. function getNext(keyframes, i, property) {
  377. while (i < keyframes.length) {
  378. var keyframe = keyframes[i];
  379. if (keyframe.value[property] !== null) return keyframe;
  380. i++;
  381. }
  382. return null;
  383. }
  384. function interpolate(key, prev, next, property) {
  385. if (next.time - prev.time === 0) {
  386. key.value[property] = prev.value[property];
  387. return;
  388. }
  389. key.value[property] = (key.time - prev.time) * (next.value[property] - prev.value[property]) / (next.time - prev.time) + prev.value[property];
  390. }
  391. // animation clips
  392. function parseAnimationClip(xml) {
  393. var data = {
  394. name: xml.getAttribute('id') || 'default',
  395. start: parseFloat(xml.getAttribute('start') || 0),
  396. end: parseFloat(xml.getAttribute('end') || 0),
  397. animations: []
  398. };
  399. for (var i = 0, l = xml.childNodes.length; i < l; i++) {
  400. var child = xml.childNodes[i];
  401. if (child.nodeType !== 1) continue;
  402. switch (child.nodeName) {
  403. case 'instance_animation':
  404. data.animations.push(parseId(child.getAttribute('url')));
  405. break;
  406. }
  407. }
  408. library.clips[xml.getAttribute('id')] = data;
  409. }
  410. function buildAnimationClip(data) {
  411. var tracks = [];
  412. var name = data.name;
  413. var duration = data.end - data.start || -1;
  414. var animations = data.animations;
  415. for (var i = 0, il = animations.length; i < il; i++) {
  416. var animationTracks = getAnimation(animations[i]);
  417. for (var j = 0, jl = animationTracks.length; j < jl; j++) {
  418. tracks.push(animationTracks[j]);
  419. }
  420. }
  421. return new THREE.AnimationClip(name, duration, tracks);
  422. }
  423. function getAnimationClip(id) {
  424. return getBuild(library.clips[id], buildAnimationClip);
  425. }
  426. // controller
  427. function parseController(xml) {
  428. var data = {};
  429. for (var i = 0, l = xml.childNodes.length; i < l; i++) {
  430. var child = xml.childNodes[i];
  431. if (child.nodeType !== 1) continue;
  432. switch (child.nodeName) {
  433. case 'skin':
  434. // there is exactly one skin per controller
  435. data.id = parseId(child.getAttribute('source'));
  436. data.skin = parseSkin(child);
  437. break;
  438. case 'morph':
  439. data.id = parseId(child.getAttribute('source'));
  440. console.warn('THREE.ColladaLoader: Morph target animation not supported yet.');
  441. break;
  442. }
  443. }
  444. library.controllers[xml.getAttribute('id')] = data;
  445. }
  446. function parseSkin(xml) {
  447. var data = {
  448. sources: {}
  449. };
  450. for (var i = 0, l = xml.childNodes.length; i < l; i++) {
  451. var child = xml.childNodes[i];
  452. if (child.nodeType !== 1) continue;
  453. switch (child.nodeName) {
  454. case 'bind_shape_matrix':
  455. data.bindShapeMatrix = parseFloats(child.textContent);
  456. break;
  457. case 'source':
  458. var id = child.getAttribute('id');
  459. data.sources[id] = parseSource(child);
  460. break;
  461. case 'joints':
  462. data.joints = parseJoints(child);
  463. break;
  464. case 'vertex_weights':
  465. data.vertexWeights = parseVertexWeights(child);
  466. break;
  467. }
  468. }
  469. return data;
  470. }
  471. function parseJoints(xml) {
  472. var data = {
  473. inputs: {}
  474. };
  475. for (var i = 0, l = xml.childNodes.length; i < l; i++) {
  476. var child = xml.childNodes[i];
  477. if (child.nodeType !== 1) continue;
  478. switch (child.nodeName) {
  479. case 'input':
  480. var semantic = child.getAttribute('semantic');
  481. var id = parseId(child.getAttribute('source'));
  482. data.inputs[semantic] = id;
  483. break;
  484. }
  485. }
  486. return data;
  487. }
  488. function parseVertexWeights(xml) {
  489. var data = {
  490. inputs: {}
  491. };
  492. for (var i = 0, l = xml.childNodes.length; i < l; i++) {
  493. var child = xml.childNodes[i];
  494. if (child.nodeType !== 1) continue;
  495. switch (child.nodeName) {
  496. case 'input':
  497. var semantic = child.getAttribute('semantic');
  498. var id = parseId(child.getAttribute('source'));
  499. var offset = parseInt(child.getAttribute('offset'));
  500. data.inputs[semantic] = { id: id, offset: offset };
  501. break;
  502. case 'vcount':
  503. data.vcount = parseInts(child.textContent);
  504. break;
  505. case 'v':
  506. data.v = parseInts(child.textContent);
  507. break;
  508. }
  509. }
  510. return data;
  511. }
  512. function buildController(data) {
  513. var build = {
  514. id: data.id
  515. };
  516. var geometry = library.geometries[build.id];
  517. if (data.skin !== undefined) {
  518. build.skin = buildSkin(data.skin);
  519. // we enhance the 'sources' property of the corresponding geometry with our skin data
  520. geometry.sources.skinIndices = build.skin.indices;
  521. geometry.sources.skinWeights = build.skin.weights;
  522. }
  523. return build;
  524. }
  525. function buildSkin(data) {
  526. var BONE_LIMIT = 4;
  527. var build = {
  528. joints: [], // this must be an array to preserve the joint order
  529. indices: {
  530. array: [],
  531. stride: BONE_LIMIT
  532. },
  533. weights: {
  534. array: [],
  535. stride: BONE_LIMIT
  536. }
  537. };
  538. var sources = data.sources;
  539. var vertexWeights = data.vertexWeights;
  540. var vcount = vertexWeights.vcount;
  541. var v = vertexWeights.v;
  542. var jointOffset = vertexWeights.inputs.JOINT.offset;
  543. var weightOffset = vertexWeights.inputs.WEIGHT.offset;
  544. var jointSource = data.sources[data.joints.inputs.JOINT];
  545. var inverseSource = data.sources[data.joints.inputs.INV_BIND_MATRIX];
  546. var weights = sources[vertexWeights.inputs.WEIGHT.id].array;
  547. var stride = 0;
  548. var i, j, l;
  549. // procces skin data for each vertex
  550. for (i = 0, l = vcount.length; i < l; i++) {
  551. var jointCount = vcount[i]; // this is the amount of joints that affect a single vertex
  552. var vertexSkinData = [];
  553. for (j = 0; j < jointCount; j++) {
  554. var skinIndex = v[stride + jointOffset];
  555. var weightId = v[stride + weightOffset];
  556. var skinWeight = weights[weightId];
  557. vertexSkinData.push({ index: skinIndex, weight: skinWeight });
  558. stride += 2;
  559. }
  560. // we sort the joints in descending order based on the weights.
  561. // this ensures, we only procced the most important joints of the vertex
  562. vertexSkinData.sort(descending);
  563. // now we provide for each vertex a set of four index and weight values.
  564. // the order of the skin data matches the order of vertices
  565. for (j = 0; j < BONE_LIMIT; j++) {
  566. var d = vertexSkinData[j];
  567. if (d !== undefined) {
  568. build.indices.array.push(d.index);
  569. build.weights.array.push(d.weight);
  570. } else {
  571. build.indices.array.push(0);
  572. build.weights.array.push(0);
  573. }
  574. }
  575. }
  576. // setup bind matrix
  577. if (data.bindShapeMatrix) {
  578. build.bindMatrix = new THREE.Matrix4().fromArray(data.bindShapeMatrix).transpose();
  579. } else {
  580. build.bindMatrix = new THREE.Matrix4().identity();
  581. }
  582. // process bones and inverse bind matrix data
  583. for (i = 0, l = jointSource.array.length; i < l; i++) {
  584. var name = jointSource.array[i];
  585. var boneInverse = new THREE.Matrix4().fromArray(inverseSource.array, i * inverseSource.stride).transpose();
  586. build.joints.push({ name: name, boneInverse: boneInverse });
  587. }
  588. return build;
  589. // array sort function
  590. function descending(a, b) {
  591. return b.weight - a.weight;
  592. }
  593. }
  594. function getController(id) {
  595. return getBuild(library.controllers[id], buildController);
  596. }
  597. // image
  598. function parseImage(xml) {
  599. var data = {
  600. init_from: getElementsByTagName(xml, 'init_from')[0].textContent
  601. };
  602. library.images[xml.getAttribute('id')] = data;
  603. }
  604. function buildImage(data) {
  605. if (data.build !== undefined) return data.build;
  606. return data.init_from;
  607. }
  608. function getImage(id) {
  609. var data = library.images[id];
  610. if (data !== undefined) {
  611. return getBuild(data, buildImage);
  612. }
  613. console.warn('THREE.ColladaLoader: Couldn\'t find image with ID:', id);
  614. return null;
  615. }
  616. // effect
  617. function parseEffect(xml) {
  618. var data = {};
  619. for (var i = 0, l = xml.childNodes.length; i < l; i++) {
  620. var child = xml.childNodes[i];
  621. if (child.nodeType !== 1) continue;
  622. switch (child.nodeName) {
  623. case 'profile_COMMON':
  624. data.profile = parseEffectProfileCOMMON(child);
  625. break;
  626. }
  627. }
  628. library.effects[xml.getAttribute('id')] = data;
  629. }
  630. function parseEffectProfileCOMMON(xml) {
  631. var data = {
  632. surfaces: {},
  633. samplers: {}
  634. };
  635. for (var i = 0, l = xml.childNodes.length; i < l; i++) {
  636. var child = xml.childNodes[i];
  637. if (child.nodeType !== 1) continue;
  638. switch (child.nodeName) {
  639. case 'newparam':
  640. parseEffectNewparam(child, data);
  641. break;
  642. case 'technique':
  643. data.technique = parseEffectTechnique(child);
  644. break;
  645. case 'extra':
  646. data.extra = parseEffectExtra(child);
  647. break;
  648. }
  649. }
  650. return data;
  651. }
  652. function parseEffectNewparam(xml, data) {
  653. var sid = xml.getAttribute('sid');
  654. for (var i = 0, l = xml.childNodes.length; i < l; i++) {
  655. var child = xml.childNodes[i];
  656. if (child.nodeType !== 1) continue;
  657. switch (child.nodeName) {
  658. case 'surface':
  659. data.surfaces[sid] = parseEffectSurface(child);
  660. break;
  661. case 'sampler2D':
  662. data.samplers[sid] = parseEffectSampler(child);
  663. break;
  664. }
  665. }
  666. }
  667. function parseEffectSurface(xml) {
  668. var data = {};
  669. for (var i = 0, l = xml.childNodes.length; i < l; i++) {
  670. var child = xml.childNodes[i];
  671. if (child.nodeType !== 1) continue;
  672. switch (child.nodeName) {
  673. case 'init_from':
  674. data.init_from = child.textContent;
  675. break;
  676. }
  677. }
  678. return data;
  679. }
  680. function parseEffectSampler(xml) {
  681. var data = {};
  682. for (var i = 0, l = xml.childNodes.length; i < l; i++) {
  683. var child = xml.childNodes[i];
  684. if (child.nodeType !== 1) continue;
  685. switch (child.nodeName) {
  686. case 'source':
  687. data.source = child.textContent;
  688. break;
  689. }
  690. }
  691. return data;
  692. }
  693. function parseEffectTechnique(xml) {
  694. var data = {};
  695. for (var i = 0, l = xml.childNodes.length; i < l; i++) {
  696. var child = xml.childNodes[i];
  697. if (child.nodeType !== 1) continue;
  698. switch (child.nodeName) {
  699. case 'constant':
  700. case 'lambert':
  701. case 'blinn':
  702. case 'phong':
  703. data.type = child.nodeName;
  704. data.parameters = parseEffectParameters(child);
  705. break;
  706. }
  707. }
  708. return data;
  709. }
  710. function parseEffectParameters(xml) {
  711. var data = {};
  712. for (var i = 0, l = xml.childNodes.length; i < l; i++) {
  713. var child = xml.childNodes[i];
  714. if (child.nodeType !== 1) continue;
  715. switch (child.nodeName) {
  716. case 'emission':
  717. case 'diffuse':
  718. case 'specular':
  719. case 'bump':
  720. case 'ambient':
  721. case 'shininess':
  722. case 'transparency':
  723. data[child.nodeName] = parseEffectParameter(child);
  724. break;
  725. case 'transparent':
  726. data[child.nodeName] = {
  727. opaque: child.getAttribute('opaque'),
  728. data: parseEffectParameter(child)
  729. };
  730. break;
  731. }
  732. }
  733. return data;
  734. }
  735. function parseEffectParameter(xml) {
  736. var data = {};
  737. for (var i = 0, l = xml.childNodes.length; i < l; i++) {
  738. var child = xml.childNodes[i];
  739. if (child.nodeType !== 1) continue;
  740. switch (child.nodeName) {
  741. case 'color':
  742. data[child.nodeName] = parseFloats(child.textContent);
  743. break;
  744. case 'float':
  745. data[child.nodeName] = parseFloat(child.textContent);
  746. break;
  747. case 'texture':
  748. data[child.nodeName] = { id: child.getAttribute('texture'), extra: parseEffectParameterTexture(child) };
  749. break;
  750. }
  751. }
  752. return data;
  753. }
  754. function parseEffectParameterTexture(xml) {
  755. var data = {
  756. technique: {}
  757. };
  758. for (var i = 0, l = xml.childNodes.length; i < l; i++) {
  759. var child = xml.childNodes[i];
  760. if (child.nodeType !== 1) continue;
  761. switch (child.nodeName) {
  762. case 'extra':
  763. parseEffectParameterTextureExtra(child, data);
  764. break;
  765. }
  766. }
  767. return data;
  768. }
  769. function parseEffectParameterTextureExtra(xml, data) {
  770. for (var i = 0, l = xml.childNodes.length; i < l; i++) {
  771. var child = xml.childNodes[i];
  772. if (child.nodeType !== 1) continue;
  773. switch (child.nodeName) {
  774. case 'technique':
  775. parseEffectParameterTextureExtraTechnique(child, data);
  776. break;
  777. }
  778. }
  779. }
  780. function parseEffectParameterTextureExtraTechnique(xml, data) {
  781. for (var i = 0, l = xml.childNodes.length; i < l; i++) {
  782. var child = xml.childNodes[i];
  783. if (child.nodeType !== 1) continue;
  784. switch (child.nodeName) {
  785. case 'repeatU':
  786. case 'repeatV':
  787. case 'offsetU':
  788. case 'offsetV':
  789. data.technique[child.nodeName] = parseFloat(child.textContent);
  790. break;
  791. case 'wrapU':
  792. case 'wrapV':
  793. // some files have values for wrapU/wrapV which become NaN via parseInt
  794. if (child.textContent.toUpperCase() === 'TRUE') {
  795. data.technique[child.nodeName] = 1;
  796. } else if (child.textContent.toUpperCase() === 'FALSE') {
  797. data.technique[child.nodeName] = 0;
  798. } else {
  799. data.technique[child.nodeName] = parseInt(child.textContent);
  800. }
  801. break;
  802. }
  803. }
  804. }
  805. function parseEffectExtra(xml) {
  806. var data = {};
  807. for (var i = 0, l = xml.childNodes.length; i < l; i++) {
  808. var child = xml.childNodes[i];
  809. if (child.nodeType !== 1) continue;
  810. switch (child.nodeName) {
  811. case 'technique':
  812. data.technique = parseEffectExtraTechnique(child);
  813. break;
  814. }
  815. }
  816. return data;
  817. }
  818. function parseEffectExtraTechnique(xml) {
  819. var data = {};
  820. for (var i = 0, l = xml.childNodes.length; i < l; i++) {
  821. var child = xml.childNodes[i];
  822. if (child.nodeType !== 1) continue;
  823. switch (child.nodeName) {
  824. case 'double_sided':
  825. data[child.nodeName] = parseInt(child.textContent);
  826. break;
  827. }
  828. }
  829. return data;
  830. }
  831. function buildEffect(data) {
  832. return data;
  833. }
  834. function getEffect(id) {
  835. return getBuild(library.effects[id], buildEffect);
  836. }
  837. // material
  838. function parseMaterial(xml) {
  839. var data = {
  840. name: xml.getAttribute('name')
  841. };
  842. for (var i = 0, l = xml.childNodes.length; i < l; i++) {
  843. var child = xml.childNodes[i];
  844. if (child.nodeType !== 1) continue;
  845. switch (child.nodeName) {
  846. case 'instance_effect':
  847. data.url = parseId(child.getAttribute('url'));
  848. break;
  849. }
  850. }
  851. library.materials[xml.getAttribute('id')] = data;
  852. }
  853. function getTextureLoader(image) {
  854. var loader;
  855. var extension = image.slice((image.lastIndexOf('.') - 1 >>> 0) + 2); // http://www.jstips.co/en/javascript/get-file-extension/
  856. extension = extension.toLowerCase();
  857. switch (extension) {
  858. case 'tga':
  859. loader = tgaLoader;
  860. break;
  861. default:
  862. loader = textureLoader;
  863. }
  864. return loader;
  865. }
  866. function buildMaterial(data) {
  867. var effect = getEffect(data.url);
  868. var technique = effect.profile.technique;
  869. var extra = effect.profile.extra;
  870. var material;
  871. switch (technique.type) {
  872. case 'phong':
  873. case 'blinn':
  874. material = new THREE.MeshPhongMaterial();
  875. break;
  876. case 'lambert':
  877. material = new THREE.MeshLambertMaterial();
  878. break;
  879. default:
  880. material = new THREE.MeshBasicMaterial();
  881. break;
  882. }
  883. material.name = data.name;
  884. function getTexture(textureObject) {
  885. var sampler = effect.profile.samplers[textureObject.id];
  886. var image = null;
  887. // get image
  888. if (sampler !== undefined) {
  889. var surface = effect.profile.surfaces[sampler.source];
  890. image = getImage(surface.init_from);
  891. } else {
  892. console.warn('THREE.ColladaLoader: Undefined sampler. Access image directly (see #12530).');
  893. image = getImage(textureObject.id);
  894. }
  895. // create texture if image is avaiable
  896. if (image !== null) {
  897. var loader = getTextureLoader(image);
  898. if (loader !== undefined) {
  899. var texture = loader.load(image);
  900. var extra = textureObject.extra;
  901. if (extra !== undefined && extra.technique !== undefined && isEmpty(extra.technique) === false) {
  902. var technique = extra.technique;
  903. texture.wrapS = technique.wrapU ? THREE.RepeatWrapping : THREE.ClampToEdgeWrapping;
  904. texture.wrapT = technique.wrapV ? THREE.RepeatWrapping : THREE.ClampToEdgeWrapping;
  905. texture.offset.set(technique.offsetU || 0, technique.offsetV || 0);
  906. texture.repeat.set(technique.repeatU || 1, technique.repeatV || 1);
  907. } else {
  908. texture.wrapS = THREE.RepeatWrapping;
  909. texture.wrapT = THREE.RepeatWrapping;
  910. }
  911. return texture;
  912. } else {
  913. console.warn('THREE.ColladaLoader: Loader for texture %s not found.', image);
  914. return null;
  915. }
  916. } else {
  917. console.warn('THREE.ColladaLoader: Couldn\'t create texture with ID:', textureObject.id);
  918. return null;
  919. }
  920. }
  921. var parameters = technique.parameters;
  922. for (var key in parameters) {
  923. var parameter = parameters[key];
  924. switch (key) {
  925. case 'diffuse':
  926. if (parameter.color) material.color.fromArray(parameter.color);
  927. if (parameter.texture) material.map = getTexture(parameter.texture);
  928. break;
  929. case 'specular':
  930. if (parameter.color && material.specular) material.specular.fromArray(parameter.color);
  931. if (parameter.texture) material.specularMap = getTexture(parameter.texture);
  932. break;
  933. case 'bump':
  934. if (parameter.texture) material.normalMap = getTexture(parameter.texture);
  935. break;
  936. case 'ambient':
  937. if (parameter.texture) material.lightMap = getTexture(parameter.texture);
  938. break;
  939. case 'shininess':
  940. if (parameter.float && material.shininess) material.shininess = parameter.float;
  941. break;
  942. case 'emission':
  943. if (parameter.color && material.emissive) material.emissive.fromArray(parameter.color);
  944. if (parameter.texture) material.emissiveMap = getTexture(parameter.texture);
  945. break;
  946. }
  947. }
  948. //
  949. var transparent = parameters['transparent'];
  950. var transparency = parameters['transparency'];
  951. // <transparency> does not exist but <transparent>
  952. if (transparency === undefined && transparent) {
  953. transparency = {
  954. float: 1
  955. };
  956. }
  957. // <transparent> does not exist but <transparency>
  958. if (transparent === undefined && transparency) {
  959. transparent = {
  960. opaque: 'A_ONE',
  961. data: {
  962. color: [1, 1, 1, 1]
  963. } };
  964. }
  965. if (transparent && transparency) {
  966. // handle case if a texture exists but no color
  967. if (transparent.data.texture) {
  968. // we do not set an alpha map (see #13792)
  969. material.transparent = true;
  970. } else {
  971. var color = transparent.data.color;
  972. switch (transparent.opaque) {
  973. case 'A_ONE':
  974. material.opacity = color[3] * transparency.float;
  975. break;
  976. case 'RGB_ZERO':
  977. material.opacity = 1 - color[0] * transparency.float;
  978. break;
  979. case 'A_ZERO':
  980. material.opacity = 1 - color[3] * transparency.float;
  981. break;
  982. case 'RGB_ONE':
  983. material.opacity = color[0] * transparency.float;
  984. break;
  985. default:
  986. console.warn('THREE.ColladaLoader: Invalid opaque type "%s" of transparent tag.', transparent.opaque);
  987. }
  988. if (material.opacity < 1) material.transparent = true;
  989. }
  990. }
  991. //
  992. if (extra !== undefined && extra.technique !== undefined && extra.technique.double_sided === 1) {
  993. material.side = THREE.DoubleSide;
  994. }
  995. return material;
  996. }
  997. function getMaterial(id) {
  998. return getBuild(library.materials[id], buildMaterial);
  999. }
  1000. // camera
  1001. function parseCamera(xml) {
  1002. var data = {
  1003. name: xml.getAttribute('name')
  1004. };
  1005. for (var i = 0, l = xml.childNodes.length; i < l; i++) {
  1006. var child = xml.childNodes[i];
  1007. if (child.nodeType !== 1) continue;
  1008. switch (child.nodeName) {
  1009. case 'optics':
  1010. data.optics = parseCameraOptics(child);
  1011. break;
  1012. }
  1013. }
  1014. library.cameras[xml.getAttribute('id')] = data;
  1015. }
  1016. function parseCameraOptics(xml) {
  1017. for (var i = 0; i < xml.childNodes.length; i++) {
  1018. var child = xml.childNodes[i];
  1019. switch (child.nodeName) {
  1020. case 'technique_common':
  1021. return parseCameraTechnique(child);
  1022. }
  1023. }
  1024. return {};
  1025. }
  1026. function parseCameraTechnique(xml) {
  1027. var data = {};
  1028. for (var i = 0; i < xml.childNodes.length; i++) {
  1029. var child = xml.childNodes[i];
  1030. switch (child.nodeName) {
  1031. case 'perspective':
  1032. case 'orthographic':
  1033. data.technique = child.nodeName;
  1034. data.parameters = parseCameraParameters(child);
  1035. break;
  1036. }
  1037. }
  1038. return data;
  1039. }
  1040. function parseCameraParameters(xml) {
  1041. var data = {};
  1042. for (var i = 0; i < xml.childNodes.length; i++) {
  1043. var child = xml.childNodes[i];
  1044. switch (child.nodeName) {
  1045. case 'xfov':
  1046. case 'yfov':
  1047. case 'xmag':
  1048. case 'ymag':
  1049. case 'znear':
  1050. case 'zfar':
  1051. case 'aspect_ratio':
  1052. data[child.nodeName] = parseFloat(child.textContent);
  1053. break;
  1054. }
  1055. }
  1056. return data;
  1057. }
  1058. function buildCamera(data) {
  1059. var camera;
  1060. switch (data.optics.technique) {
  1061. case 'perspective':
  1062. camera = new THREE.PerspectiveCamera(data.optics.parameters.yfov, data.optics.parameters.aspect_ratio, data.optics.parameters.znear, data.optics.parameters.zfar);
  1063. break;
  1064. case 'orthographic':
  1065. var ymag = data.optics.parameters.ymag;
  1066. var xmag = data.optics.parameters.xmag;
  1067. var aspectRatio = data.optics.parameters.aspect_ratio;
  1068. xmag = xmag === undefined ? ymag * aspectRatio : xmag;
  1069. ymag = ymag === undefined ? xmag / aspectRatio : ymag;
  1070. xmag *= 0.5;
  1071. ymag *= 0.5;
  1072. camera = new THREE.OrthographicCamera(-xmag, xmag, ymag, -ymag, // left, right, top, bottom
  1073. data.optics.parameters.znear, data.optics.parameters.zfar);
  1074. break;
  1075. default:
  1076. camera = new THREE.PerspectiveCamera();
  1077. break;
  1078. }
  1079. camera.name = data.name;
  1080. return camera;
  1081. }
  1082. function getCamera(id) {
  1083. var data = library.cameras[id];
  1084. if (data !== undefined) {
  1085. return getBuild(data, buildCamera);
  1086. }
  1087. console.warn('THREE.ColladaLoader: Couldn\'t find camera with ID:', id);
  1088. return null;
  1089. }
  1090. // light
  1091. function parseLight(xml) {
  1092. var data = {};
  1093. for (var i = 0, l = xml.childNodes.length; i < l; i++) {
  1094. var child = xml.childNodes[i];
  1095. if (child.nodeType !== 1) continue;
  1096. switch (child.nodeName) {
  1097. case 'technique_common':
  1098. data = parseLightTechnique(child);
  1099. break;
  1100. }
  1101. }
  1102. library.lights[xml.getAttribute('id')] = data;
  1103. }
  1104. function parseLightTechnique(xml) {
  1105. var data = {};
  1106. for (var i = 0, l = xml.childNodes.length; i < l; i++) {
  1107. var child = xml.childNodes[i];
  1108. if (child.nodeType !== 1) continue;
  1109. switch (child.nodeName) {
  1110. case 'directional':
  1111. case 'point':
  1112. case 'spot':
  1113. case 'ambient':
  1114. data.technique = child.nodeName;
  1115. data.parameters = parseLightParameters(child);
  1116. }
  1117. }
  1118. return data;
  1119. }
  1120. function parseLightParameters(xml) {
  1121. var data = {};
  1122. for (var i = 0, l = xml.childNodes.length; i < l; i++) {
  1123. var child = xml.childNodes[i];
  1124. if (child.nodeType !== 1) continue;
  1125. switch (child.nodeName) {
  1126. case 'color':
  1127. var array = parseFloats(child.textContent);
  1128. data.color = new THREE.Color().fromArray(array);
  1129. break;
  1130. case 'falloff_angle':
  1131. data.falloffAngle = parseFloat(child.textContent);
  1132. break;
  1133. case 'quadratic_attenuation':
  1134. var f = parseFloat(child.textContent);
  1135. data.distance = f ? Math.sqrt(1 / f) : 0;
  1136. break;
  1137. }
  1138. }
  1139. return data;
  1140. }
  1141. function buildLight(data) {
  1142. var light;
  1143. switch (data.technique) {
  1144. case 'directional':
  1145. light = new THREE.DirectionalLight();
  1146. break;
  1147. case 'point':
  1148. light = new THREE.PointLight();
  1149. break;
  1150. case 'spot':
  1151. light = new THREE.SpotLight();
  1152. break;
  1153. case 'ambient':
  1154. light = new THREE.AmbientLight();
  1155. break;
  1156. }
  1157. if (data.parameters.color) light.color.copy(data.parameters.color);
  1158. if (data.parameters.distance) light.distance = data.parameters.distance;
  1159. return light;
  1160. }
  1161. function getLight(id) {
  1162. var data = library.lights[id];
  1163. if (data !== undefined) {
  1164. return getBuild(data, buildLight);
  1165. }
  1166. console.warn('THREE.ColladaLoader: Couldn\'t find light with ID:', id);
  1167. return null;
  1168. }
  1169. // geometry
  1170. function parseGeometry(xml) {
  1171. var data = {
  1172. name: xml.getAttribute('name'),
  1173. sources: {},
  1174. vertices: {},
  1175. primitives: []
  1176. };
  1177. var mesh = getElementsByTagName(xml, 'mesh')[0];
  1178. // the following tags inside geometry are not supported yet (see https://github.com/mrdoob/three.js/pull/12606): convex_mesh, spline, brep
  1179. if (mesh === undefined) return;
  1180. for (var i = 0; i < mesh.childNodes.length; i++) {
  1181. var child = mesh.childNodes[i];
  1182. if (child.nodeType !== 1) continue;
  1183. var id = child.getAttribute('id');
  1184. switch (child.nodeName) {
  1185. case 'source':
  1186. data.sources[id] = parseSource(child);
  1187. break;
  1188. case 'vertices':
  1189. // data.sources[ id ] = data.sources[ parseId( getElementsByTagName( child, 'input' )[ 0 ].getAttribute( 'source' ) ) ];
  1190. data.vertices = parseGeometryVertices(child);
  1191. break;
  1192. case 'polygons':
  1193. console.warn('THREE.ColladaLoader: Unsupported primitive type: ', child.nodeName);
  1194. break;
  1195. case 'lines':
  1196. case 'linestrips':
  1197. case 'polylist':
  1198. case 'triangles':
  1199. data.primitives.push(parseGeometryPrimitive(child));
  1200. break;
  1201. default:
  1202. console.log(child);
  1203. }
  1204. }
  1205. library.geometries[xml.getAttribute('id')] = data;
  1206. }
  1207. function parseSource(xml) {
  1208. var data = {
  1209. array: [],
  1210. stride: 3
  1211. };
  1212. for (var i = 0; i < xml.childNodes.length; i++) {
  1213. var child = xml.childNodes[i];
  1214. if (child.nodeType !== 1) continue;
  1215. switch (child.nodeName) {
  1216. case 'float_array':
  1217. data.array = parseFloats(child.textContent);
  1218. break;
  1219. case 'Name_array':
  1220. data.array = parseStrings(child.textContent);
  1221. break;
  1222. case 'technique_common':
  1223. var accessor = getElementsByTagName(child, 'accessor')[0];
  1224. if (accessor !== undefined) {
  1225. data.stride = parseInt(accessor.getAttribute('stride'));
  1226. }
  1227. break;
  1228. }
  1229. }
  1230. return data;
  1231. }
  1232. function parseGeometryVertices(xml) {
  1233. var data = {};
  1234. for (var i = 0; i < xml.childNodes.length; i++) {
  1235. var child = xml.childNodes[i];
  1236. if (child.nodeType !== 1) continue;
  1237. data[child.getAttribute('semantic')] = parseId(child.getAttribute('source'));
  1238. }
  1239. return data;
  1240. }
  1241. function parseGeometryPrimitive(xml) {
  1242. var primitive = {
  1243. type: xml.nodeName,
  1244. material: xml.getAttribute('material'),
  1245. count: parseInt(xml.getAttribute('count')),
  1246. inputs: {},
  1247. stride: 0,
  1248. hasUV: false
  1249. };
  1250. for (var i = 0, l = xml.childNodes.length; i < l; i++) {
  1251. var child = xml.childNodes[i];
  1252. if (child.nodeType !== 1) continue;
  1253. switch (child.nodeName) {
  1254. case 'input':
  1255. var id = parseId(child.getAttribute('source'));
  1256. var semantic = child.getAttribute('semantic');
  1257. var offset = parseInt(child.getAttribute('offset'));
  1258. var set = parseInt(child.getAttribute('set'));
  1259. var inputname = set > 0 ? semantic + set : semantic;
  1260. primitive.inputs[inputname] = { id: id, offset: offset };
  1261. primitive.stride = Math.max(primitive.stride, offset + 1);
  1262. if (semantic === 'TEXCOORD') primitive.hasUV = true;
  1263. break;
  1264. case 'vcount':
  1265. primitive.vcount = parseInts(child.textContent);
  1266. break;
  1267. case 'p':
  1268. primitive.p = parseInts(child.textContent);
  1269. break;
  1270. }
  1271. }
  1272. return primitive;
  1273. }
  1274. function groupPrimitives(primitives) {
  1275. var build = {};
  1276. for (var i = 0; i < primitives.length; i++) {
  1277. var primitive = primitives[i];
  1278. if (build[primitive.type] === undefined) build[primitive.type] = [];
  1279. build[primitive.type].push(primitive);
  1280. }
  1281. return build;
  1282. }
  1283. function checkUVCoordinates(primitives) {
  1284. var count = 0;
  1285. for (var i = 0, l = primitives.length; i < l; i++) {
  1286. var primitive = primitives[i];
  1287. if (primitive.hasUV === true) {
  1288. count++;
  1289. }
  1290. }
  1291. if (count > 0 && count < primitives.length) {
  1292. primitives.uvsNeedsFix = true;
  1293. }
  1294. }
  1295. function buildGeometry(data) {
  1296. var build = {};
  1297. var sources = data.sources;
  1298. var vertices = data.vertices;
  1299. var primitives = data.primitives;
  1300. if (primitives.length === 0) return {};
  1301. // our goal is to create one buffer geometry for a single type of primitives
  1302. // first, we group all primitives by their type
  1303. var groupedPrimitives = groupPrimitives(primitives);
  1304. for (var type in groupedPrimitives) {
  1305. var primitiveType = groupedPrimitives[type];
  1306. // second, ensure consistent uv coordinates for each type of primitives (polylist,triangles or lines)
  1307. checkUVCoordinates(primitiveType);
  1308. // third, create a buffer geometry for each type of primitives
  1309. build[type] = buildGeometryType(primitiveType, sources, vertices);
  1310. }
  1311. return build;
  1312. }
  1313. function buildGeometryType(primitives, sources, vertices) {
  1314. var build = {};
  1315. var position = { array: [], stride: 0 };
  1316. var normal = { array: [], stride: 0 };
  1317. var uv = { array: [], stride: 0 };
  1318. var uv2 = { array: [], stride: 0 };
  1319. var color = { array: [], stride: 0 };
  1320. var skinIndex = { array: [], stride: 4 };
  1321. var skinWeight = { array: [], stride: 4 };
  1322. var geometry = new THREE.BufferGeometry();
  1323. var materialKeys = [];
  1324. var start = 0;
  1325. for (var p = 0; p < primitives.length; p++) {
  1326. var primitive = primitives[p];
  1327. var inputs = primitive.inputs;
  1328. // groups
  1329. var count = 0;
  1330. switch (primitive.type) {
  1331. case 'lines':
  1332. case 'linestrips':
  1333. count = primitive.count * 2;
  1334. break;
  1335. case 'triangles':
  1336. count = primitive.count * 3;
  1337. break;
  1338. case 'polylist':
  1339. for (var g = 0; g < primitive.count; g++) {
  1340. var vc = primitive.vcount[g];
  1341. switch (vc) {
  1342. case 3:
  1343. count += 3; // single triangle
  1344. break;
  1345. case 4:
  1346. count += 6; // quad, subdivided into two triangles
  1347. break;
  1348. default:
  1349. count += (vc - 2) * 3; // polylist with more than four vertices
  1350. break;
  1351. }
  1352. }
  1353. break;
  1354. default:
  1355. console.warn('THREE.ColladaLoader: Unknow primitive type:', primitive.type);
  1356. }
  1357. geometry.addGroup(start, count, p);
  1358. start += count;
  1359. // material
  1360. if (primitive.material) {
  1361. materialKeys.push(primitive.material);
  1362. }
  1363. // geometry data
  1364. for (var name in inputs) {
  1365. var input = inputs[name];
  1366. switch (name) {
  1367. case 'VERTEX':
  1368. for (var key in vertices) {
  1369. var id = vertices[key];
  1370. switch (key) {
  1371. case 'POSITION':
  1372. var prevLength = position.array.length;
  1373. buildGeometryData(primitive, sources[id], input.offset, position.array);
  1374. position.stride = sources[id].stride;
  1375. if (sources.skinWeights && sources.skinIndices) {
  1376. buildGeometryData(primitive, sources.skinIndices, input.offset, skinIndex.array);
  1377. buildGeometryData(primitive, sources.skinWeights, input.offset, skinWeight.array);
  1378. }
  1379. // see #3803
  1380. if (primitive.hasUV === false && primitives.uvsNeedsFix === true) {
  1381. var count = (position.array.length - prevLength) / position.stride;
  1382. for (var i = 0; i < count; i++) {
  1383. // fill missing uv coordinates
  1384. uv.array.push(0, 0);
  1385. }
  1386. }
  1387. break;
  1388. case 'NORMAL':
  1389. buildGeometryData(primitive, sources[id], input.offset, normal.array);
  1390. normal.stride = sources[id].stride;
  1391. break;
  1392. case 'COLOR':
  1393. buildGeometryData(primitive, sources[id], input.offset, color.array);
  1394. color.stride = sources[id].stride;
  1395. break;
  1396. case 'TEXCOORD':
  1397. buildGeometryData(primitive, sources[id], input.offset, uv.array);
  1398. uv.stride = sources[id].stride;
  1399. break;
  1400. case 'TEXCOORD1':
  1401. buildGeometryData(primitive, sources[id], input.offset, uv2.array);
  1402. uv.stride = sources[id].stride;
  1403. break;
  1404. default:
  1405. console.warn('THREE.ColladaLoader: Semantic "%s" not handled in geometry build process.', key);
  1406. }
  1407. }
  1408. break;
  1409. case 'NORMAL':
  1410. buildGeometryData(primitive, sources[input.id], input.offset, normal.array);
  1411. normal.stride = sources[input.id].stride;
  1412. break;
  1413. case 'COLOR':
  1414. buildGeometryData(primitive, sources[input.id], input.offset, color.array);
  1415. color.stride = sources[input.id].stride;
  1416. break;
  1417. case 'TEXCOORD':
  1418. buildGeometryData(primitive, sources[input.id], input.offset, uv.array);
  1419. uv.stride = sources[input.id].stride;
  1420. break;
  1421. case 'TEXCOORD1':
  1422. buildGeometryData(primitive, sources[input.id], input.offset, uv2.array);
  1423. uv2.stride = sources[input.id].stride;
  1424. break;
  1425. }
  1426. }
  1427. }
  1428. // build geometry
  1429. if (position.array.length > 0) geometry.addAttribute('position', new THREE.Float32BufferAttribute(position.array, position.stride));
  1430. if (normal.array.length > 0) geometry.addAttribute('normal', new THREE.Float32BufferAttribute(normal.array, normal.stride));
  1431. if (color.array.length > 0) geometry.addAttribute('color', new THREE.Float32BufferAttribute(color.array, color.stride));
  1432. if (uv.array.length > 0) geometry.addAttribute('uv', new THREE.Float32BufferAttribute(uv.array, uv.stride));
  1433. if (uv2.array.length > 0) geometry.addAttribute('uv2', new THREE.Float32BufferAttribute(uv2.array, uv2.stride));
  1434. if (skinIndex.array.length > 0) geometry.addAttribute('skinIndex', new THREE.Float32BufferAttribute(skinIndex.array, skinIndex.stride));
  1435. if (skinWeight.array.length > 0) geometry.addAttribute('skinWeight', new THREE.Float32BufferAttribute(skinWeight.array, skinWeight.stride));
  1436. build.data = geometry;
  1437. build.type = primitives[0].type;
  1438. build.materialKeys = materialKeys;
  1439. return build;
  1440. }
  1441. function buildGeometryData(primitive, source, offset, array) {
  1442. var indices = primitive.p;
  1443. var stride = primitive.stride;
  1444. var vcount = primitive.vcount;
  1445. function pushVector(i) {
  1446. var index = indices[i + offset] * sourceStride;
  1447. var length = index + sourceStride;
  1448. for (; index < length; index++) {
  1449. array.push(sourceArray[index]);
  1450. }
  1451. }
  1452. var sourceArray = source.array;
  1453. var sourceStride = source.stride;
  1454. if (primitive.vcount !== undefined) {
  1455. var index = 0;
  1456. for (var i = 0, l = vcount.length; i < l; i++) {
  1457. var count = vcount[i];
  1458. if (count === 4) {
  1459. var a = index + stride * 0;
  1460. var b = index + stride * 1;
  1461. var c = index + stride * 2;
  1462. var d = index + stride * 3;
  1463. pushVector(a);pushVector(b);pushVector(d);
  1464. pushVector(b);pushVector(c);pushVector(d);
  1465. } else if (count === 3) {
  1466. var a = index + stride * 0;
  1467. var b = index + stride * 1;
  1468. var c = index + stride * 2;
  1469. pushVector(a);pushVector(b);pushVector(c);
  1470. } else if (count > 4) {
  1471. for (var k = 1, kl = count - 2; k <= kl; k++) {
  1472. var a = index + stride * 0;
  1473. var b = index + stride * k;
  1474. var c = index + stride * (k + 1);
  1475. pushVector(a);pushVector(b);pushVector(c);
  1476. }
  1477. }
  1478. index += stride * count;
  1479. }
  1480. } else {
  1481. for (var i = 0, l = indices.length; i < l; i += stride) {
  1482. pushVector(i);
  1483. }
  1484. }
  1485. }
  1486. function getGeometry(id) {
  1487. return getBuild(library.geometries[id], buildGeometry);
  1488. }
  1489. // kinematics
  1490. function parseKinematicsModel(xml) {
  1491. var data = {
  1492. name: xml.getAttribute('name') || '',
  1493. joints: {},
  1494. links: []
  1495. };
  1496. for (var i = 0; i < xml.childNodes.length; i++) {
  1497. var child = xml.childNodes[i];
  1498. if (child.nodeType !== 1) continue;
  1499. switch (child.nodeName) {
  1500. case 'technique_common':
  1501. parseKinematicsTechniqueCommon(child, data);
  1502. break;
  1503. }
  1504. }
  1505. library.kinematicsModels[xml.getAttribute('id')] = data;
  1506. }
  1507. function buildKinematicsModel(data) {
  1508. if (data.build !== undefined) return data.build;
  1509. return data;
  1510. }
  1511. function getKinematicsModel(id) {
  1512. return getBuild(library.kinematicsModels[id], buildKinematicsModel);
  1513. }
  1514. function parseKinematicsTechniqueCommon(xml, data) {
  1515. for (var i = 0; i < xml.childNodes.length; i++) {
  1516. var child = xml.childNodes[i];
  1517. if (child.nodeType !== 1) continue;
  1518. switch (child.nodeName) {
  1519. case 'joint':
  1520. data.joints[child.getAttribute('sid')] = parseKinematicsJoint(child);
  1521. break;
  1522. case 'link':
  1523. data.links.push(parseKinematicsLink(child));
  1524. break;
  1525. }
  1526. }
  1527. }
  1528. function parseKinematicsJoint(xml) {
  1529. var data;
  1530. for (var i = 0; i < xml.childNodes.length; i++) {
  1531. var child = xml.childNodes[i];
  1532. if (child.nodeType !== 1) continue;
  1533. switch (child.nodeName) {
  1534. case 'prismatic':
  1535. case 'revolute':
  1536. data = parseKinematicsJointParameter(child);
  1537. break;
  1538. }
  1539. }
  1540. return data;
  1541. }
  1542. function parseKinematicsJointParameter(xml, data) {
  1543. var data = {
  1544. sid: xml.getAttribute('sid'),
  1545. name: xml.getAttribute('name') || '',
  1546. axis: new THREE.Vector3(),
  1547. limits: {
  1548. min: 0,
  1549. max: 0
  1550. },
  1551. type: xml.nodeName,
  1552. static: false,
  1553. zeroPosition: 0,
  1554. middlePosition: 0
  1555. };
  1556. for (var i = 0; i < xml.childNodes.length; i++) {
  1557. var child = xml.childNodes[i];
  1558. if (child.nodeType !== 1) continue;
  1559. switch (child.nodeName) {
  1560. case 'axis':
  1561. var array = parseFloats(child.textContent);
  1562. data.axis.fromArray(array);
  1563. break;
  1564. case 'limits':
  1565. var max = child.getElementsByTagName('max')[0];
  1566. var min = child.getElementsByTagName('min')[0];
  1567. data.limits.max = parseFloat(max.textContent);
  1568. data.limits.min = parseFloat(min.textContent);
  1569. break;
  1570. }
  1571. }
  1572. // if min is equal to or greater than max, consider the joint static
  1573. if (data.limits.min >= data.limits.max) {
  1574. data.static = true;
  1575. }
  1576. // calculate middle position
  1577. data.middlePosition = (data.limits.min + data.limits.max) / 2.0;
  1578. return data;
  1579. }
  1580. function parseKinematicsLink(xml) {
  1581. var data = {
  1582. sid: xml.getAttribute('sid'),
  1583. name: xml.getAttribute('name') || '',
  1584. attachments: [],
  1585. transforms: []
  1586. };
  1587. for (var i = 0; i < xml.childNodes.length; i++) {
  1588. var child = xml.childNodes[i];
  1589. if (child.nodeType !== 1) continue;
  1590. switch (child.nodeName) {
  1591. case 'attachment_full':
  1592. data.attachments.push(parseKinematicsAttachment(child));
  1593. break;
  1594. case 'matrix':
  1595. case 'translate':
  1596. case 'rotate':
  1597. data.transforms.push(parseKinematicsTransform(child));
  1598. break;
  1599. }
  1600. }
  1601. return data;
  1602. }
  1603. function parseKinematicsAttachment(xml) {
  1604. var data = {
  1605. joint: xml.getAttribute('joint').split('/').pop(),
  1606. transforms: [],
  1607. links: []
  1608. };
  1609. for (var i = 0; i < xml.childNodes.length; i++) {
  1610. var child = xml.childNodes[i];
  1611. if (child.nodeType !== 1) continue;
  1612. switch (child.nodeName) {
  1613. case 'link':
  1614. data.links.push(parseKinematicsLink(child));
  1615. break;
  1616. case 'matrix':
  1617. case 'translate':
  1618. case 'rotate':
  1619. data.transforms.push(parseKinematicsTransform(child));
  1620. break;
  1621. }
  1622. }
  1623. return data;
  1624. }
  1625. function parseKinematicsTransform(xml) {
  1626. var data = {
  1627. type: xml.nodeName
  1628. };
  1629. var array = parseFloats(xml.textContent);
  1630. switch (data.type) {
  1631. case 'matrix':
  1632. data.obj = new THREE.Matrix4();
  1633. data.obj.fromArray(array).transpose();
  1634. break;
  1635. case 'translate':
  1636. data.obj = new THREE.Vector3();
  1637. data.obj.fromArray(array);
  1638. break;
  1639. case 'rotate':
  1640. data.obj = new THREE.Vector3();
  1641. data.obj.fromArray(array);
  1642. data.angle = THREE.Math.degToRad(array[3]);
  1643. break;
  1644. }
  1645. return data;
  1646. }
  1647. // physics
  1648. function parsePhysicsModel(xml) {
  1649. var data = {
  1650. name: xml.getAttribute('name') || '',
  1651. rigidBodies: {}
  1652. };
  1653. for (var i = 0; i < xml.childNodes.length; i++) {
  1654. var child = xml.childNodes[i];
  1655. if (child.nodeType !== 1) continue;
  1656. switch (child.nodeName) {
  1657. case 'rigid_body':
  1658. data.rigidBodies[child.getAttribute('name')] = {};
  1659. parsePhysicsRigidBody(child, data.rigidBodies[child.getAttribute('name')]);
  1660. break;
  1661. }
  1662. }
  1663. library.physicsModels[xml.getAttribute('id')] = data;
  1664. }
  1665. function parsePhysicsRigidBody(xml, data) {
  1666. for (var i = 0; i < xml.childNodes.length; i++) {
  1667. var child = xml.childNodes[i];
  1668. if (child.nodeType !== 1) continue;
  1669. switch (child.nodeName) {
  1670. case 'technique_common':
  1671. parsePhysicsTechniqueCommon(child, data);
  1672. break;
  1673. }
  1674. }
  1675. }
  1676. function parsePhysicsTechniqueCommon(xml, data) {
  1677. for (var i = 0; i < xml.childNodes.length; i++) {
  1678. var child = xml.childNodes[i];
  1679. if (child.nodeType !== 1) continue;
  1680. switch (child.nodeName) {
  1681. case 'inertia':
  1682. data.inertia = parseFloats(child.textContent);
  1683. break;
  1684. case 'mass':
  1685. data.mass = parseFloats(child.textContent)[0];
  1686. break;
  1687. }
  1688. }
  1689. }
  1690. // scene
  1691. function parseKinematicsScene(xml) {
  1692. var data = {
  1693. bindJointAxis: []
  1694. };
  1695. for (var i = 0; i < xml.childNodes.length; i++) {
  1696. var child = xml.childNodes[i];
  1697. if (child.nodeType !== 1) continue;
  1698. switch (child.nodeName) {
  1699. case 'bind_joint_axis':
  1700. data.bindJointAxis.push(parseKinematicsBindJointAxis(child));
  1701. break;
  1702. }
  1703. }
  1704. library.kinematicsScenes[parseId(xml.getAttribute('url'))] = data;
  1705. }
  1706. function parseKinematicsBindJointAxis(xml) {
  1707. var data = {
  1708. target: xml.getAttribute('target').split('/').pop()
  1709. };
  1710. for (var i = 0; i < xml.childNodes.length; i++) {
  1711. var child = xml.childNodes[i];
  1712. if (child.nodeType !== 1) continue;
  1713. switch (child.nodeName) {
  1714. case 'axis':
  1715. var param = child.getElementsByTagName('param')[0];
  1716. data.axis = param.textContent;
  1717. var tmpJointIndex = data.axis.split('inst_').pop().split('axis')[0];
  1718. data.jointIndex = tmpJointIndex.substr(0, tmpJointIndex.length - 1);
  1719. break;
  1720. }
  1721. }
  1722. return data;
  1723. }
  1724. function buildKinematicsScene(data) {
  1725. if (data.build !== undefined) return data.build;
  1726. return data;
  1727. }
  1728. function getKinematicsScene(id) {
  1729. return getBuild(library.kinematicsScenes[id], buildKinematicsScene);
  1730. }
  1731. function setupKinematics() {
  1732. var kinematicsModelId = Object.keys(library.kinematicsModels)[0];
  1733. var kinematicsSceneId = Object.keys(library.kinematicsScenes)[0];
  1734. var visualSceneId = Object.keys(library.visualScenes)[0];
  1735. if (kinematicsModelId === undefined || kinematicsSceneId === undefined) return;
  1736. var kinematicsModel = getKinematicsModel(kinematicsModelId);
  1737. var kinematicsScene = getKinematicsScene(kinematicsSceneId);
  1738. var visualScene = getVisualScene(visualSceneId);
  1739. var bindJointAxis = kinematicsScene.bindJointAxis;
  1740. var jointMap = {};
  1741. for (var i = 0, l = bindJointAxis.length; i < l; i++) {
  1742. var axis = bindJointAxis[i];
  1743. // the result of the following query is an element of type 'translate', 'rotate','scale' or 'matrix'
  1744. var targetElement = collada.querySelector('[sid="' + axis.target + '"]');
  1745. if (targetElement) {
  1746. // get the parent of the transfrom element
  1747. var parentVisualElement = targetElement.parentElement;
  1748. // connect the joint of the kinematics model with the element in the visual scene
  1749. connect(axis.jointIndex, parentVisualElement);
  1750. }
  1751. }
  1752. function connect(jointIndex, visualElement) {
  1753. var visualElementName = visualElement.getAttribute('name');
  1754. var joint = kinematicsModel.joints[jointIndex];
  1755. visualScene.traverse(function (object) {
  1756. if (object.name === visualElementName) {
  1757. jointMap[jointIndex] = {
  1758. object: object,
  1759. transforms: buildTransformList(visualElement),
  1760. joint: joint,
  1761. position: joint.zeroPosition
  1762. };
  1763. }
  1764. });
  1765. }
  1766. var m0 = new THREE.Matrix4();
  1767. kinematics = {
  1768. joints: kinematicsModel && kinematicsModel.joints,
  1769. getJointValue: function getJointValue(jointIndex) {
  1770. var jointData = jointMap[jointIndex];
  1771. if (jointData) {
  1772. return jointData.position;
  1773. } else {
  1774. console.warn('THREE.ColladaLoader: Joint ' + jointIndex + ' doesn\'t exist.');
  1775. }
  1776. },
  1777. setJointValue: function setJointValue(jointIndex, value) {
  1778. var jointData = jointMap[jointIndex];
  1779. if (jointData) {
  1780. var joint = jointData.joint;
  1781. if (value > joint.limits.max || value < joint.limits.min) {
  1782. console.warn('THREE.ColladaLoader: Joint ' + jointIndex + ' value ' + value + ' outside of limits (min: ' + joint.limits.min + ', max: ' + joint.limits.max + ').');
  1783. } else if (joint.static) {
  1784. console.warn('THREE.ColladaLoader: Joint ' + jointIndex + ' is static.');
  1785. } else {
  1786. var object = jointData.object;
  1787. var axis = joint.axis;
  1788. var transforms = jointData.transforms;
  1789. matrix.identity();
  1790. // each update, we have to apply all transforms in the correct order
  1791. for (var i = 0; i < transforms.length; i++) {
  1792. var transform = transforms[i];
  1793. // if there is a connection of the transform node with a joint, apply the joint value
  1794. if (transform.sid && transform.sid.indexOf(jointIndex) !== -1) {
  1795. switch (joint.type) {
  1796. case 'revolute':
  1797. matrix.multiply(m0.makeRotationAxis(axis, THREE.Math.degToRad(value)));
  1798. break;
  1799. case 'prismatic':
  1800. matrix.multiply(m0.makeTranslation(axis.x * value, axis.y * value, axis.z * value));
  1801. break;
  1802. default:
  1803. console.warn('THREE.ColladaLoader: Unknown joint type: ' + joint.type);
  1804. break;
  1805. }
  1806. } else {
  1807. switch (transform.type) {
  1808. case 'matrix':
  1809. matrix.multiply(transform.obj);
  1810. break;
  1811. case 'translate':
  1812. matrix.multiply(m0.makeTranslation(transform.obj.x, transform.obj.y, transform.obj.z));
  1813. break;
  1814. case 'scale':
  1815. matrix.scale(transform.obj);
  1816. break;
  1817. case 'rotate':
  1818. matrix.multiply(m0.makeRotationAxis(transform.obj, transform.angle));
  1819. break;
  1820. }
  1821. }
  1822. }
  1823. object.matrix.copy(matrix);
  1824. object.matrix.decompose(object.position, object.quaternion, object.scale);
  1825. jointMap[jointIndex].position = value;
  1826. }
  1827. } else {
  1828. console.log('THREE.ColladaLoader: ' + jointIndex + ' does not exist.');
  1829. }
  1830. }
  1831. };
  1832. }
  1833. function buildTransformList(node) {
  1834. var transforms = [];
  1835. var xml = collada.querySelector('[id="' + node.id + '"]');
  1836. for (var i = 0; i < xml.childNodes.length; i++) {
  1837. var child = xml.childNodes[i];
  1838. if (child.nodeType !== 1) continue;
  1839. switch (child.nodeName) {
  1840. case 'matrix':
  1841. var array = parseFloats(child.textContent);
  1842. var matrix = new THREE.Matrix4().fromArray(array).transpose();
  1843. transforms.push({
  1844. sid: child.getAttribute('sid'),
  1845. type: child.nodeName,
  1846. obj: matrix
  1847. });
  1848. break;
  1849. case 'translate':
  1850. case 'scale':
  1851. var array = parseFloats(child.textContent);
  1852. var vector = new THREE.Vector3().fromArray(array);
  1853. transforms.push({
  1854. sid: child.getAttribute('sid'),
  1855. type: child.nodeName,
  1856. obj: vector
  1857. });
  1858. break;
  1859. case 'rotate':
  1860. var array = parseFloats(child.textContent);
  1861. var vector = new THREE.Vector3().fromArray(array);
  1862. var angle = THREE.Math.degToRad(array[3]);
  1863. transforms.push({
  1864. sid: child.getAttribute('sid'),
  1865. type: child.nodeName,
  1866. obj: vector,
  1867. angle: angle
  1868. });
  1869. break;
  1870. }
  1871. }
  1872. return transforms;
  1873. }
  1874. // nodes
  1875. function prepareNodes(xml) {
  1876. var elements = xml.getElementsByTagName('node');
  1877. // ensure all node elements have id attributes
  1878. for (var i = 0; i < elements.length; i++) {
  1879. var element = elements[i];
  1880. if (element.hasAttribute('id') === false) {
  1881. element.setAttribute('id', generateId());
  1882. }
  1883. }
  1884. }
  1885. var matrix = new THREE.Matrix4();
  1886. var vector = new THREE.Vector3();
  1887. function parseNode(xml) {
  1888. var data = {
  1889. name: xml.getAttribute('name') || '',
  1890. type: xml.getAttribute('type'),
  1891. id: xml.getAttribute('id'),
  1892. sid: xml.getAttribute('sid'),
  1893. matrix: new THREE.Matrix4(),
  1894. nodes: [],
  1895. instanceCameras: [],
  1896. instanceControllers: [],
  1897. instanceLights: [],
  1898. instanceGeometries: [],
  1899. instanceNodes: [],
  1900. transforms: {}
  1901. };
  1902. for (var i = 0; i < xml.childNodes.length; i++) {
  1903. var child = xml.childNodes[i];
  1904. if (child.nodeType !== 1) continue;
  1905. switch (child.nodeName) {
  1906. case 'node':
  1907. data.nodes.push(child.getAttribute('id'));
  1908. parseNode(child);
  1909. break;
  1910. case 'instance_camera':
  1911. data.instanceCameras.push(parseId(child.getAttribute('url')));
  1912. break;
  1913. case 'instance_controller':
  1914. data.instanceControllers.push(parseNodeInstance(child));
  1915. break;
  1916. case 'instance_light':
  1917. data.instanceLights.push(parseId(child.getAttribute('url')));
  1918. break;
  1919. case 'instance_geometry':
  1920. data.instanceGeometries.push(parseNodeInstance(child));
  1921. break;
  1922. case 'instance_node':
  1923. data.instanceNodes.push(parseId(child.getAttribute('url')));
  1924. break;
  1925. case 'matrix':
  1926. var array = parseFloats(child.textContent);
  1927. data.matrix.multiply(matrix.fromArray(array).transpose());
  1928. data.transforms[child.getAttribute('sid')] = child.nodeName;
  1929. break;
  1930. case 'translate':
  1931. var array = parseFloats(child.textContent);
  1932. vector.fromArray(array);
  1933. data.matrix.multiply(matrix.makeTranslation(vector.x, vector.y, vector.z));
  1934. data.transforms[child.getAttribute('sid')] = child.nodeName;
  1935. break;
  1936. case 'rotate':
  1937. var array = parseFloats(child.textContent);
  1938. var angle = THREE.Math.degToRad(array[3]);
  1939. data.matrix.multiply(matrix.makeRotationAxis(vector.fromArray(array), angle));
  1940. data.transforms[child.getAttribute('sid')] = child.nodeName;
  1941. break;
  1942. case 'scale':
  1943. var array = parseFloats(child.textContent);
  1944. data.matrix.scale(vector.fromArray(array));
  1945. data.transforms[child.getAttribute('sid')] = child.nodeName;
  1946. break;
  1947. case 'extra':
  1948. break;
  1949. default:
  1950. console.log(child);
  1951. }
  1952. }
  1953. if (hasNode(data.id)) {
  1954. console.warn('THREE.ColladaLoader: There is already a node with ID %s. Exclude current node from further processing.', data.id);
  1955. } else {
  1956. library.nodes[data.id] = data;
  1957. }
  1958. return data;
  1959. }
  1960. function parseNodeInstance(xml) {
  1961. var data = {
  1962. id: parseId(xml.getAttribute('url')),
  1963. materials: {},
  1964. skeletons: []
  1965. };
  1966. for (var i = 0; i < xml.childNodes.length; i++) {
  1967. var child = xml.childNodes[i];
  1968. switch (child.nodeName) {
  1969. case 'bind_material':
  1970. var instances = child.getElementsByTagName('instance_material');
  1971. for (var j = 0; j < instances.length; j++) {
  1972. var instance = instances[j];
  1973. var symbol = instance.getAttribute('symbol');
  1974. var target = instance.getAttribute('target');
  1975. data.materials[symbol] = parseId(target);
  1976. }
  1977. break;
  1978. case 'skeleton':
  1979. data.skeletons.push(parseId(child.textContent));
  1980. break;
  1981. default:
  1982. break;
  1983. }
  1984. }
  1985. return data;
  1986. }
  1987. function buildSkeleton(skeletons, joints) {
  1988. var boneData = [];
  1989. var sortedBoneData = [];
  1990. var i, j, data;
  1991. // a skeleton can have multiple root bones. collada expresses this
  1992. // situtation with multiple "skeleton" tags per controller instance
  1993. for (i = 0; i < skeletons.length; i++) {
  1994. var skeleton = skeletons[i];
  1995. var root;
  1996. if (hasNode(skeleton)) {
  1997. root = getNode(skeleton);
  1998. buildBoneHierarchy(root, joints, boneData);
  1999. } else if (hasVisualScene(skeleton)) {
  2000. // handle case where the skeleton refers to the visual scene (#13335)
  2001. var visualScene = library.visualScenes[skeleton];
  2002. var children = visualScene.children;
  2003. for (var j = 0; j < children.length; j++) {
  2004. var child = children[j];
  2005. if (child.type === 'JOINT') {
  2006. var root = getNode(child.id);
  2007. buildBoneHierarchy(root, joints, boneData);
  2008. }
  2009. }
  2010. } else {
  2011. console.error('THREE.ColladaLoader: Unable to find root bone of skeleton with ID:', skeleton);
  2012. }
  2013. }
  2014. // sort bone data (the order is defined in the corresponding controller)
  2015. for (i = 0; i < joints.length; i++) {
  2016. for (j = 0; j < boneData.length; j++) {
  2017. data = boneData[j];
  2018. if (data.bone.name === joints[i].name) {
  2019. sortedBoneData[i] = data;
  2020. data.processed = true;
  2021. break;
  2022. }
  2023. }
  2024. }
  2025. // add unprocessed bone data at the end of the list
  2026. for (i = 0; i < boneData.length; i++) {
  2027. data = boneData[i];
  2028. if (data.processed === false) {
  2029. sortedBoneData.push(data);
  2030. data.processed = true;
  2031. }
  2032. }
  2033. // setup arrays for skeleton creation
  2034. var bones = [];
  2035. var boneInverses = [];
  2036. for (i = 0; i < sortedBoneData.length; i++) {
  2037. data = sortedBoneData[i];
  2038. bones.push(data.bone);
  2039. boneInverses.push(data.boneInverse);
  2040. }
  2041. return new THREE.Skeleton(bones, boneInverses);
  2042. }
  2043. function buildBoneHierarchy(root, joints, boneData) {
  2044. // setup bone data from visual scene
  2045. root.traverse(function (object) {
  2046. if (object.isBone === true) {
  2047. var boneInverse;
  2048. // retrieve the boneInverse from the controller data
  2049. for (var i = 0; i < joints.length; i++) {
  2050. var joint = joints[i];
  2051. if (joint.name === object.name) {
  2052. boneInverse = joint.boneInverse;
  2053. break;
  2054. }
  2055. }
  2056. if (boneInverse === undefined) {
  2057. // Unfortunately, there can be joints in the visual scene that are not part of the
  2058. // corresponding controller. In this case, we have to create a dummy boneInverse matrix
  2059. // for the respective bone. This bone won't affect any vertices, because there are no skin indices
  2060. // and weights defined for it. But we still have to add the bone to the sorted bone list in order to
  2061. // ensure a correct animation of the model.
  2062. boneInverse = new THREE.Matrix4();
  2063. }
  2064. boneData.push({ bone: object, boneInverse: boneInverse, processed: false });
  2065. }
  2066. });
  2067. }
  2068. function buildNode(data) {
  2069. var objects = [];
  2070. var matrix = data.matrix;
  2071. var nodes = data.nodes;
  2072. var type = data.type;
  2073. var instanceCameras = data.instanceCameras;
  2074. var instanceControllers = data.instanceControllers;
  2075. var instanceLights = data.instanceLights;
  2076. var instanceGeometries = data.instanceGeometries;
  2077. var instanceNodes = data.instanceNodes;
  2078. // nodes
  2079. for (var i = 0, l = nodes.length; i < l; i++) {
  2080. objects.push(getNode(nodes[i]));
  2081. }
  2082. // instance cameras
  2083. for (var i = 0, l = instanceCameras.length; i < l; i++) {
  2084. var instanceCamera = getCamera(instanceCameras[i]);
  2085. if (instanceCamera !== null) {
  2086. objects.push(instanceCamera.clone());
  2087. }
  2088. }
  2089. // instance controllers
  2090. for (var i = 0, l = instanceControllers.length; i < l; i++) {
  2091. var instance = instanceControllers[i];
  2092. var controller = getController(instance.id);
  2093. var geometries = getGeometry(controller.id);
  2094. var newObjects = buildObjects(geometries, instance.materials);
  2095. var skeletons = instance.skeletons;
  2096. var joints = controller.skin.joints;
  2097. var skeleton = buildSkeleton(skeletons, joints);
  2098. for (var j = 0, jl = newObjects.length; j < jl; j++) {
  2099. var object = newObjects[j];
  2100. if (object.isSkinnedMesh) {
  2101. object.bind(skeleton, controller.skin.bindMatrix);
  2102. object.normalizeSkinWeights();
  2103. }
  2104. objects.push(object);
  2105. }
  2106. }
  2107. // instance lights
  2108. for (var i = 0, l = instanceLights.length; i < l; i++) {
  2109. var instanceLight = getLight(instanceLights[i]);
  2110. if (instanceLight !== null) {
  2111. objects.push(instanceLight.clone());
  2112. }
  2113. }
  2114. // instance geometries
  2115. for (var i = 0, l = instanceGeometries.length; i < l; i++) {
  2116. var instance = instanceGeometries[i];
  2117. // a single geometry instance in collada can lead to multiple object3Ds.
  2118. // this is the case when primitives are combined like triangles and lines
  2119. var geometries = getGeometry(instance.id);
  2120. var newObjects = buildObjects(geometries, instance.materials);
  2121. for (var j = 0, jl = newObjects.length; j < jl; j++) {
  2122. objects.push(newObjects[j]);
  2123. }
  2124. }
  2125. // instance nodes
  2126. for (var i = 0, l = instanceNodes.length; i < l; i++) {
  2127. objects.push(getNode(instanceNodes[i]).clone());
  2128. }
  2129. var object;
  2130. if (nodes.length === 0 && objects.length === 1) {
  2131. object = objects[0];
  2132. } else {
  2133. object = type === 'JOINT' ? new THREE.Bone() : new THREE.Group();
  2134. for (var i = 0; i < objects.length; i++) {
  2135. object.add(objects[i]);
  2136. }
  2137. }
  2138. if (object.name === '') {
  2139. object.name = type === 'JOINT' ? data.sid : data.name;
  2140. }
  2141. object.matrix.copy(matrix);
  2142. object.matrix.decompose(object.position, object.quaternion, object.scale);
  2143. return object;
  2144. }
  2145. var fallbackMaterial = new THREE.MeshBasicMaterial({ color: 0xff00ff });
  2146. function resolveMaterialBinding(keys, instanceMaterials) {
  2147. var materials = [];
  2148. for (var i = 0, l = keys.length; i < l; i++) {
  2149. var id = instanceMaterials[keys[i]];
  2150. if (id === undefined) {
  2151. console.warn('THREE.ColladaLoader: Material with key %s not found. Apply fallback material.', keys[i]);
  2152. materials.push(fallbackMaterial);
  2153. } else {
  2154. materials.push(getMaterial(id));
  2155. }
  2156. }
  2157. return materials;
  2158. }
  2159. function buildObjects(geometries, instanceMaterials) {
  2160. var objects = [];
  2161. for (var type in geometries) {
  2162. var geometry = geometries[type];
  2163. var materials = resolveMaterialBinding(geometry.materialKeys, instanceMaterials);
  2164. // handle case if no materials are defined
  2165. if (materials.length === 0) {
  2166. if (type === 'lines' || type === 'linestrips') {
  2167. materials.push(new THREE.LineBasicMaterial());
  2168. } else {
  2169. materials.push(new THREE.MeshPhongMaterial());
  2170. }
  2171. }
  2172. // regard skinning
  2173. var skinning = geometry.data.attributes.skinIndex !== undefined;
  2174. if (skinning) {
  2175. for (var i = 0, l = materials.length; i < l; i++) {
  2176. materials[i].skinning = true;
  2177. }
  2178. }
  2179. // choose between a single or multi materials (material array)
  2180. var material = materials.length === 1 ? materials[0] : materials;
  2181. // now create a specific 3D object
  2182. var object;
  2183. switch (type) {
  2184. case 'lines':
  2185. object = new THREE.LineSegments(geometry.data, material);
  2186. break;
  2187. case 'linestrips':
  2188. object = new THREE.Line(geometry.data, material);
  2189. break;
  2190. case 'triangles':
  2191. case 'polylist':
  2192. if (skinning) {
  2193. object = new THREE.SkinnedMesh(geometry.data, material);
  2194. } else {
  2195. object = new THREE.Mesh(geometry.data, material);
  2196. }
  2197. break;
  2198. }
  2199. objects.push(object);
  2200. }
  2201. return objects;
  2202. }
  2203. function hasNode(id) {
  2204. return library.nodes[id] !== undefined;
  2205. }
  2206. function getNode(id) {
  2207. return getBuild(library.nodes[id], buildNode);
  2208. }
  2209. // visual scenes
  2210. function parseVisualScene(xml) {
  2211. var data = {
  2212. name: xml.getAttribute('name'),
  2213. children: []
  2214. };
  2215. prepareNodes(xml);
  2216. var elements = getElementsByTagName(xml, 'node');
  2217. for (var i = 0; i < elements.length; i++) {
  2218. data.children.push(parseNode(elements[i]));
  2219. }
  2220. library.visualScenes[xml.getAttribute('id')] = data;
  2221. }
  2222. function buildVisualScene(data) {
  2223. var group = new THREE.Group();
  2224. group.name = data.name;
  2225. var children = data.children;
  2226. for (var i = 0; i < children.length; i++) {
  2227. var child = children[i];
  2228. group.add(getNode(child.id));
  2229. }
  2230. return group;
  2231. }
  2232. function hasVisualScene(id) {
  2233. return library.visualScenes[id] !== undefined;
  2234. }
  2235. function getVisualScene(id) {
  2236. return getBuild(library.visualScenes[id], buildVisualScene);
  2237. }
  2238. // scenes
  2239. function parseScene(xml) {
  2240. var instance = getElementsByTagName(xml, 'instance_visual_scene')[0];
  2241. return getVisualScene(parseId(instance.getAttribute('url')));
  2242. }
  2243. function setupAnimations() {
  2244. var clips = library.clips;
  2245. if (isEmpty(clips) === true) {
  2246. if (isEmpty(library.animations) === false) {
  2247. // if there are animations but no clips, we create a default clip for playback
  2248. var tracks = [];
  2249. for (var id in library.animations) {
  2250. var animationTracks = getAnimation(id);
  2251. for (var i = 0, l = animationTracks.length; i < l; i++) {
  2252. tracks.push(animationTracks[i]);
  2253. }
  2254. }
  2255. animations.push(new THREE.AnimationClip('default', -1, tracks));
  2256. }
  2257. } else {
  2258. for (var id in clips) {
  2259. animations.push(getAnimationClip(id));
  2260. }
  2261. }
  2262. }
  2263. if (text.length === 0) {
  2264. return { scene: new THREE.Scene() };
  2265. }
  2266. var xml = new DOMParser().parseFromString(text, 'application/xml');
  2267. var collada = getElementsByTagName(xml, 'COLLADA')[0];
  2268. // metadata
  2269. var version = collada.getAttribute('version');
  2270. console.log('THREE.ColladaLoader: File version', version);
  2271. var asset = parseAsset(getElementsByTagName(collada, 'asset')[0]);
  2272. var textureLoader = new THREE.TextureLoader(this.manager);
  2273. textureLoader.setPath(this.resourcePath || path).setCrossOrigin(this.crossOrigin);
  2274. var tgaLoader;
  2275. if (THREE.TGALoader) {
  2276. tgaLoader = new THREE.TGALoader(this.manager);
  2277. tgaLoader.setPath(this.resourcePath || path);
  2278. }
  2279. //
  2280. var animations = [];
  2281. var kinematics = {};
  2282. var count = 0;
  2283. //
  2284. var library = {
  2285. animations: {},
  2286. clips: {},
  2287. controllers: {},
  2288. images: {},
  2289. effects: {},
  2290. materials: {},
  2291. cameras: {},
  2292. lights: {},
  2293. geometries: {},
  2294. nodes: {},
  2295. visualScenes: {},
  2296. kinematicsModels: {},
  2297. physicsModels: {},
  2298. kinematicsScenes: {}
  2299. };
  2300. parseLibrary(collada, 'library_animations', 'animation', parseAnimation);
  2301. parseLibrary(collada, 'library_animation_clips', 'animation_clip', parseAnimationClip);
  2302. parseLibrary(collada, 'library_controllers', 'controller', parseController);
  2303. parseLibrary(collada, 'library_images', 'image', parseImage);
  2304. parseLibrary(collada, 'library_effects', 'effect', parseEffect);
  2305. parseLibrary(collada, 'library_materials', 'material', parseMaterial);
  2306. parseLibrary(collada, 'library_cameras', 'camera', parseCamera);
  2307. parseLibrary(collada, 'library_lights', 'light', parseLight);
  2308. parseLibrary(collada, 'library_geometries', 'geometry', parseGeometry);
  2309. parseLibrary(collada, 'library_nodes', 'node', parseNode);
  2310. parseLibrary(collada, 'library_visual_scenes', 'visual_scene', parseVisualScene);
  2311. parseLibrary(collada, 'library_kinematics_models', 'kinematics_model', parseKinematicsModel);
  2312. parseLibrary(collada, 'library_physics_models', 'physics_model', parsePhysicsModel);
  2313. parseLibrary(collada, 'scene', 'instance_kinematics_scene', parseKinematicsScene);
  2314. buildLibrary(library.animations, buildAnimation);
  2315. buildLibrary(library.clips, buildAnimationClip);
  2316. buildLibrary(library.controllers, buildController);
  2317. buildLibrary(library.images, buildImage);
  2318. buildLibrary(library.effects, buildEffect);
  2319. buildLibrary(library.materials, buildMaterial);
  2320. buildLibrary(library.cameras, buildCamera);
  2321. buildLibrary(library.lights, buildLight);
  2322. buildLibrary(library.geometries, buildGeometry);
  2323. buildLibrary(library.visualScenes, buildVisualScene);
  2324. setupAnimations();
  2325. setupKinematics();
  2326. var scene = parseScene(getElementsByTagName(collada, 'scene')[0]);
  2327. if (asset.upAxis === 'Z_UP') {
  2328. scene.quaternion.setFromEuler(new THREE.Euler(-Math.PI / 2, 0, 0));
  2329. }
  2330. scene.scale.multiplyScalar(asset.unit);
  2331. return {
  2332. animations: animations,
  2333. kinematics: kinematics,
  2334. library: library,
  2335. scene: scene
  2336. };
  2337. }
  2338. };
  2339. },{}],4:[function(require,module,exports){
  2340. 'use strict';
  2341. 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; };
  2342. var _typeof = typeof Symbol === "function" && _typeof2(Symbol.iterator) === "symbol" ? function (obj) {
  2343. return typeof obj === "undefined" ? "undefined" : _typeof2(obj);
  2344. } : function (obj) {
  2345. return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj === "undefined" ? "undefined" : _typeof2(obj);
  2346. };
  2347. /**
  2348. * @author Kyle-Larson https://github.com/Kyle-Larson
  2349. * @author Takahiro https://github.com/takahirox
  2350. * @author Lewy Blue https://github.com/looeee
  2351. *
  2352. * Loader loads FBX file and generates Group representing FBX scene.
  2353. * Requires FBX file to be >= 7.0 and in ASCII or >= 6400 in Binary format
  2354. * Versions lower than this may load but will probably have errors
  2355. *
  2356. * Needs Support:
  2357. * Morph normals / blend shape normals
  2358. *
  2359. * FBX format references:
  2360. * https://wiki.blender.org/index.php/User:Mont29/Foundation/FBX_File_Structure
  2361. * http://help.autodesk.com/view/FBX/2017/ENU/?guid=__cpp_ref_index_html (C++ SDK reference)
  2362. *
  2363. * Binary format specification:
  2364. * https://code.blender.org/2013/08/fbx-binary-file-format-specification/
  2365. */
  2366. module.exports = THREE.FBXLoader = function () {
  2367. var fbxTree;
  2368. var connections;
  2369. var sceneGraph;
  2370. function FBXLoader(manager) {
  2371. this.manager = manager !== undefined ? manager : THREE.DefaultLoadingManager;
  2372. }
  2373. FBXLoader.prototype = {
  2374. constructor: FBXLoader,
  2375. crossOrigin: 'anonymous',
  2376. load: function load(url, onLoad, onProgress, onError) {
  2377. var self = this;
  2378. var resourceDirectory = THREE.LoaderUtils.extractUrlBase(url);
  2379. var loader = new THREE.FileLoader(this.manager);
  2380. loader.setResponseType('arraybuffer');
  2381. loader.load(url, function (buffer) {
  2382. try {
  2383. var scene = self.parse(buffer, resourceDirectory);
  2384. onLoad(scene);
  2385. } catch (error) {
  2386. setTimeout(function () {
  2387. if (onError) onError(error);
  2388. self.manager.itemError(url);
  2389. }, 0);
  2390. }
  2391. }, onProgress, onError);
  2392. },
  2393. setCrossOrigin: function setCrossOrigin(value) {
  2394. this.crossOrigin = value;
  2395. return this;
  2396. },
  2397. parse: function parse(FBXBuffer, resourceDirectory) {
  2398. if (isFbxFormatBinary(FBXBuffer)) {
  2399. fbxTree = new BinaryParser().parse(FBXBuffer);
  2400. } else {
  2401. var FBXText = convertArrayBufferToString(FBXBuffer);
  2402. if (!isFbxFormatASCII(FBXText)) {
  2403. throw new Error('THREE.FBXLoader: Unknown format.');
  2404. }
  2405. if (getFbxVersion(FBXText) < 7000) {
  2406. throw new Error('THREE.FBXLoader: FBX version not supported, FileVersion: ' + getFbxVersion(FBXText));
  2407. }
  2408. fbxTree = new TextParser().parse(FBXText);
  2409. }
  2410. //console.log( FBXTree );
  2411. var textureLoader = new THREE.TextureLoader(this.manager).setPath(resourceDirectory).setCrossOrigin(this.crossOrigin);
  2412. return new FBXTreeParser(textureLoader).parse(fbxTree);
  2413. }
  2414. };
  2415. // Parse the FBXTree object returned by the BinaryParser or TextParser and return a THREE.Group
  2416. function FBXTreeParser(textureLoader) {
  2417. this.textureLoader = textureLoader;
  2418. }
  2419. FBXTreeParser.prototype = {
  2420. constructor: FBXTreeParser,
  2421. parse: function parse() {
  2422. connections = this.parseConnections();
  2423. var images = this.parseImages();
  2424. var textures = this.parseTextures(images);
  2425. var materials = this.parseMaterials(textures);
  2426. var deformers = this.parseDeformers();
  2427. var geometryMap = new GeometryParser().parse(deformers);
  2428. this.parseScene(deformers, geometryMap, materials);
  2429. return sceneGraph;
  2430. },
  2431. // Parses FBXTree.Connections which holds parent-child connections between objects (e.g. material -> texture, model->geometry )
  2432. // and details the connection type
  2433. parseConnections: function parseConnections() {
  2434. var connectionMap = new Map();
  2435. if ('Connections' in fbxTree) {
  2436. var rawConnections = fbxTree.Connections.connections;
  2437. rawConnections.forEach(function (rawConnection) {
  2438. var fromID = rawConnection[0];
  2439. var toID = rawConnection[1];
  2440. var relationship = rawConnection[2];
  2441. if (!connectionMap.has(fromID)) {
  2442. connectionMap.set(fromID, {
  2443. parents: [],
  2444. children: []
  2445. });
  2446. }
  2447. var parentRelationship = { ID: toID, relationship: relationship };
  2448. connectionMap.get(fromID).parents.push(parentRelationship);
  2449. if (!connectionMap.has(toID)) {
  2450. connectionMap.set(toID, {
  2451. parents: [],
  2452. children: []
  2453. });
  2454. }
  2455. var childRelationship = { ID: fromID, relationship: relationship };
  2456. connectionMap.get(toID).children.push(childRelationship);
  2457. });
  2458. }
  2459. return connectionMap;
  2460. },
  2461. // Parse FBXTree.Objects.Video for embedded image data
  2462. // These images are connected to textures in FBXTree.Objects.Textures
  2463. // via FBXTree.Connections.
  2464. parseImages: function parseImages() {
  2465. var images = {};
  2466. var blobs = {};
  2467. if ('Video' in fbxTree.Objects) {
  2468. var videoNodes = fbxTree.Objects.Video;
  2469. for (var nodeID in videoNodes) {
  2470. var videoNode = videoNodes[nodeID];
  2471. var id = parseInt(nodeID);
  2472. images[id] = videoNode.RelativeFilename || videoNode.Filename;
  2473. // raw image data is in videoNode.Content
  2474. if ('Content' in videoNode) {
  2475. var arrayBufferContent = videoNode.Content instanceof ArrayBuffer && videoNode.Content.byteLength > 0;
  2476. var base64Content = typeof videoNode.Content === 'string' && videoNode.Content !== '';
  2477. if (arrayBufferContent || base64Content) {
  2478. var image = this.parseImage(videoNodes[nodeID]);
  2479. blobs[videoNode.RelativeFilename || videoNode.Filename] = image;
  2480. }
  2481. }
  2482. }
  2483. }
  2484. for (var id in images) {
  2485. var filename = images[id];
  2486. if (blobs[filename] !== undefined) images[id] = blobs[filename];else images[id] = images[id].split('\\').pop();
  2487. }
  2488. return images;
  2489. },
  2490. // Parse embedded image data in FBXTree.Video.Content
  2491. parseImage: function parseImage(videoNode) {
  2492. var content = videoNode.Content;
  2493. var fileName = videoNode.RelativeFilename || videoNode.Filename;
  2494. var extension = fileName.slice(fileName.lastIndexOf('.') + 1).toLowerCase();
  2495. var type;
  2496. switch (extension) {
  2497. case 'bmp':
  2498. type = 'image/bmp';
  2499. break;
  2500. case 'jpg':
  2501. case 'jpeg':
  2502. type = 'image/jpeg';
  2503. break;
  2504. case 'png':
  2505. type = 'image/png';
  2506. break;
  2507. case 'tif':
  2508. type = 'image/tiff';
  2509. break;
  2510. case 'tga':
  2511. if (typeof THREE.TGALoader !== 'function') {
  2512. console.warn('FBXLoader: THREE.TGALoader is required to load TGA textures');
  2513. return;
  2514. } else {
  2515. if (THREE.Loader.Handlers.get('.tga') === null) {
  2516. THREE.Loader.Handlers.add(/\.tga$/i, new THREE.TGALoader());
  2517. }
  2518. type = 'image/tga';
  2519. break;
  2520. }
  2521. default:
  2522. console.warn('FBXLoader: Image type "' + extension + '" is not supported.');
  2523. return;
  2524. }
  2525. if (typeof content === 'string') {
  2526. // ASCII format
  2527. return 'data:' + type + ';base64,' + content;
  2528. } else {
  2529. // Binary Format
  2530. var array = new Uint8Array(content);
  2531. return window.URL.createObjectURL(new Blob([array], { type: type }));
  2532. }
  2533. },
  2534. // Parse nodes in FBXTree.Objects.Texture
  2535. // These contain details such as UV scaling, cropping, rotation etc and are connected
  2536. // to images in FBXTree.Objects.Video
  2537. parseTextures: function parseTextures(images) {
  2538. var textureMap = new Map();
  2539. if ('Texture' in fbxTree.Objects) {
  2540. var textureNodes = fbxTree.Objects.Texture;
  2541. for (var nodeID in textureNodes) {
  2542. var texture = this.parseTexture(textureNodes[nodeID], images);
  2543. textureMap.set(parseInt(nodeID), texture);
  2544. }
  2545. }
  2546. return textureMap;
  2547. },
  2548. // Parse individual node in FBXTree.Objects.Texture
  2549. parseTexture: function parseTexture(textureNode, images) {
  2550. var texture = this.loadTexture(textureNode, images);
  2551. texture.ID = textureNode.id;
  2552. texture.name = textureNode.attrName;
  2553. var wrapModeU = textureNode.WrapModeU;
  2554. var wrapModeV = textureNode.WrapModeV;
  2555. var valueU = wrapModeU !== undefined ? wrapModeU.value : 0;
  2556. var valueV = wrapModeV !== undefined ? wrapModeV.value : 0;
  2557. // http://download.autodesk.com/us/fbx/SDKdocs/FBX_SDK_Help/files/fbxsdkref/class_k_fbx_texture.html#889640e63e2e681259ea81061b85143a
  2558. // 0: repeat(default), 1: clamp
  2559. texture.wrapS = valueU === 0 ? THREE.RepeatWrapping : THREE.ClampToEdgeWrapping;
  2560. texture.wrapT = valueV === 0 ? THREE.RepeatWrapping : THREE.ClampToEdgeWrapping;
  2561. if ('Scaling' in textureNode) {
  2562. var values = textureNode.Scaling.value;
  2563. texture.repeat.x = values[0];
  2564. texture.repeat.y = values[1];
  2565. }
  2566. return texture;
  2567. },
  2568. // load a texture specified as a blob or data URI, or via an external URL using THREE.TextureLoader
  2569. loadTexture: function loadTexture(textureNode, images) {
  2570. var fileName;
  2571. var currentPath = this.textureLoader.path;
  2572. var children = connections.get(textureNode.id).children;
  2573. if (children !== undefined && children.length > 0 && images[children[0].ID] !== undefined) {
  2574. fileName = images[children[0].ID];
  2575. if (fileName.indexOf('blob:') === 0 || fileName.indexOf('data:') === 0) {
  2576. this.textureLoader.setPath(undefined);
  2577. }
  2578. }
  2579. var texture;
  2580. var extension = textureNode.FileName.slice(-3).toLowerCase();
  2581. if (extension === 'tga') {
  2582. var loader = THREE.Loader.Handlers.get('.tga');
  2583. if (loader === null) {
  2584. console.warn('FBXLoader: TGALoader not found, creating empty placeholder texture for', fileName);
  2585. texture = new THREE.Texture();
  2586. } else {
  2587. texture = loader.load(fileName);
  2588. }
  2589. } else if (extension === 'psd') {
  2590. console.warn('FBXLoader: PSD textures are not supported, creating empty placeholder texture for', fileName);
  2591. texture = new THREE.Texture();
  2592. } else {
  2593. texture = this.textureLoader.load(fileName);
  2594. }
  2595. this.textureLoader.setPath(currentPath);
  2596. return texture;
  2597. },
  2598. // Parse nodes in FBXTree.Objects.Material
  2599. parseMaterials: function parseMaterials(textureMap) {
  2600. var materialMap = new Map();
  2601. if ('Material' in fbxTree.Objects) {
  2602. var materialNodes = fbxTree.Objects.Material;
  2603. for (var nodeID in materialNodes) {
  2604. var material = this.parseMaterial(materialNodes[nodeID], textureMap);
  2605. if (material !== null) materialMap.set(parseInt(nodeID), material);
  2606. }
  2607. }
  2608. return materialMap;
  2609. },
  2610. // Parse single node in FBXTree.Objects.Material
  2611. // Materials are connected to texture maps in FBXTree.Objects.Textures
  2612. // FBX format currently only supports Lambert and Phong shading models
  2613. parseMaterial: function parseMaterial(materialNode, textureMap) {
  2614. var ID = materialNode.id;
  2615. var name = materialNode.attrName;
  2616. var type = materialNode.ShadingModel;
  2617. // Case where FBX wraps shading model in property object.
  2618. if ((typeof type === 'undefined' ? 'undefined' : _typeof(type)) === 'object') {
  2619. type = type.value;
  2620. }
  2621. // Ignore unused materials which don't have any connections.
  2622. if (!connections.has(ID)) return null;
  2623. var parameters = this.parseParameters(materialNode, textureMap, ID);
  2624. var material;
  2625. switch (type.toLowerCase()) {
  2626. case 'phong':
  2627. material = new THREE.MeshPhongMaterial();
  2628. break;
  2629. case 'lambert':
  2630. material = new THREE.MeshLambertMaterial();
  2631. break;
  2632. default:
  2633. console.warn('THREE.FBXLoader: unknown material type "%s". Defaulting to MeshPhongMaterial.', type);
  2634. material = new THREE.MeshPhongMaterial({ color: 0x3300ff });
  2635. break;
  2636. }
  2637. material.setValues(parameters);
  2638. material.name = name;
  2639. return material;
  2640. },
  2641. // Parse FBX material and return parameters suitable for a three.js material
  2642. // Also parse the texture map and return any textures associated with the material
  2643. parseParameters: function parseParameters(materialNode, textureMap, ID) {
  2644. var parameters = {};
  2645. if (materialNode.BumpFactor) {
  2646. parameters.bumpScale = materialNode.BumpFactor.value;
  2647. }
  2648. if (materialNode.Diffuse) {
  2649. parameters.color = new THREE.Color().fromArray(materialNode.Diffuse.value);
  2650. } else if (materialNode.DiffuseColor && materialNode.DiffuseColor.type === 'Color') {
  2651. // The blender exporter exports diffuse here instead of in materialNode.Diffuse
  2652. parameters.color = new THREE.Color().fromArray(materialNode.DiffuseColor.value);
  2653. }
  2654. if (materialNode.DisplacementFactor) {
  2655. parameters.displacementScale = materialNode.DisplacementFactor.value;
  2656. }
  2657. if (materialNode.Emissive) {
  2658. parameters.emissive = new THREE.Color().fromArray(materialNode.Emissive.value);
  2659. } else if (materialNode.EmissiveColor && materialNode.EmissiveColor.type === 'Color') {
  2660. // The blender exporter exports emissive color here instead of in materialNode.Emissive
  2661. parameters.emissive = new THREE.Color().fromArray(materialNode.EmissiveColor.value);
  2662. }
  2663. if (materialNode.EmissiveFactor) {
  2664. parameters.emissiveIntensity = parseFloat(materialNode.EmissiveFactor.value);
  2665. }
  2666. if (materialNode.Opacity) {
  2667. parameters.opacity = parseFloat(materialNode.Opacity.value);
  2668. }
  2669. if (parameters.opacity < 1.0) {
  2670. parameters.transparent = true;
  2671. }
  2672. if (materialNode.ReflectionFactor) {
  2673. parameters.reflectivity = materialNode.ReflectionFactor.value;
  2674. }
  2675. if (materialNode.Shininess) {
  2676. parameters.shininess = materialNode.Shininess.value;
  2677. }
  2678. if (materialNode.Specular) {
  2679. parameters.specular = new THREE.Color().fromArray(materialNode.Specular.value);
  2680. } else if (materialNode.SpecularColor && materialNode.SpecularColor.type === 'Color') {
  2681. // The blender exporter exports specular color here instead of in materialNode.Specular
  2682. parameters.specular = new THREE.Color().fromArray(materialNode.SpecularColor.value);
  2683. }
  2684. var self = this;
  2685. connections.get(ID).children.forEach(function (child) {
  2686. var type = child.relationship;
  2687. switch (type) {
  2688. case 'Bump':
  2689. parameters.bumpMap = self.getTexture(textureMap, child.ID);
  2690. break;
  2691. case 'DiffuseColor':
  2692. parameters.map = self.getTexture(textureMap, child.ID);
  2693. break;
  2694. case 'DisplacementColor':
  2695. parameters.displacementMap = self.getTexture(textureMap, child.ID);
  2696. break;
  2697. case 'EmissiveColor':
  2698. parameters.emissiveMap = self.getTexture(textureMap, child.ID);
  2699. break;
  2700. case 'NormalMap':
  2701. parameters.normalMap = self.getTexture(textureMap, child.ID);
  2702. break;
  2703. case 'ReflectionColor':
  2704. parameters.envMap = self.getTexture(textureMap, child.ID);
  2705. parameters.envMap.mapping = THREE.EquirectangularReflectionMapping;
  2706. break;
  2707. case 'SpecularColor':
  2708. parameters.specularMap = self.getTexture(textureMap, child.ID);
  2709. break;
  2710. case 'TransparentColor':
  2711. parameters.alphaMap = self.getTexture(textureMap, child.ID);
  2712. parameters.transparent = true;
  2713. break;
  2714. case 'AmbientColor':
  2715. case 'ShininessExponent': // AKA glossiness map
  2716. case 'SpecularFactor': // AKA specularLevel
  2717. case 'VectorDisplacementColor': // NOTE: Seems to be a copy of DisplacementColor
  2718. default:
  2719. console.warn('THREE.FBXLoader: %s map is not supported in three.js, skipping texture.', type);
  2720. break;
  2721. }
  2722. });
  2723. return parameters;
  2724. },
  2725. // get a texture from the textureMap for use by a material.
  2726. getTexture: function getTexture(textureMap, id) {
  2727. // if the texture is a layered texture, just use the first layer and issue a warning
  2728. if ('LayeredTexture' in fbxTree.Objects && id in fbxTree.Objects.LayeredTexture) {
  2729. console.warn('THREE.FBXLoader: layered textures are not supported in three.js. Discarding all but first layer.');
  2730. id = connections.get(id).children[0].ID;
  2731. }
  2732. return textureMap.get(id);
  2733. },
  2734. // Parse nodes in FBXTree.Objects.Deformer
  2735. // Deformer node can contain skinning or Vertex Cache animation data, however only skinning is supported here
  2736. // Generates map of Skeleton-like objects for use later when generating and binding skeletons.
  2737. parseDeformers: function parseDeformers() {
  2738. var skeletons = {};
  2739. var morphTargets = {};
  2740. if ('Deformer' in fbxTree.Objects) {
  2741. var DeformerNodes = fbxTree.Objects.Deformer;
  2742. for (var nodeID in DeformerNodes) {
  2743. var deformerNode = DeformerNodes[nodeID];
  2744. var relationships = connections.get(parseInt(nodeID));
  2745. if (deformerNode.attrType === 'Skin') {
  2746. var skeleton = this.parseSkeleton(relationships, DeformerNodes);
  2747. skeleton.ID = nodeID;
  2748. if (relationships.parents.length > 1) console.warn('THREE.FBXLoader: skeleton attached to more than one geometry is not supported.');
  2749. skeleton.geometryID = relationships.parents[0].ID;
  2750. skeletons[nodeID] = skeleton;
  2751. } else if (deformerNode.attrType === 'BlendShape') {
  2752. var morphTarget = {
  2753. id: nodeID
  2754. };
  2755. morphTarget.rawTargets = this.parseMorphTargets(relationships, DeformerNodes);
  2756. morphTarget.id = nodeID;
  2757. if (relationships.parents.length > 1) console.warn('THREE.FBXLoader: morph target attached to more than one geometry is not supported.');
  2758. morphTargets[nodeID] = morphTarget;
  2759. }
  2760. }
  2761. }
  2762. return {
  2763. skeletons: skeletons,
  2764. morphTargets: morphTargets
  2765. };
  2766. },
  2767. // Parse single nodes in FBXTree.Objects.Deformer
  2768. // The top level skeleton node has type 'Skin' and sub nodes have type 'Cluster'
  2769. // Each skin node represents a skeleton and each cluster node represents a bone
  2770. parseSkeleton: function parseSkeleton(relationships, deformerNodes) {
  2771. var rawBones = [];
  2772. relationships.children.forEach(function (child) {
  2773. var boneNode = deformerNodes[child.ID];
  2774. if (boneNode.attrType !== 'Cluster') return;
  2775. var rawBone = {
  2776. ID: child.ID,
  2777. indices: [],
  2778. weights: [],
  2779. transform: new THREE.Matrix4().fromArray(boneNode.Transform.a),
  2780. transformLink: new THREE.Matrix4().fromArray(boneNode.TransformLink.a),
  2781. linkMode: boneNode.Mode
  2782. };
  2783. if ('Indexes' in boneNode) {
  2784. rawBone.indices = boneNode.Indexes.a;
  2785. rawBone.weights = boneNode.Weights.a;
  2786. }
  2787. rawBones.push(rawBone);
  2788. });
  2789. return {
  2790. rawBones: rawBones,
  2791. bones: []
  2792. };
  2793. },
  2794. // The top level morph deformer node has type "BlendShape" and sub nodes have type "BlendShapeChannel"
  2795. parseMorphTargets: function parseMorphTargets(relationships, deformerNodes) {
  2796. var rawMorphTargets = [];
  2797. for (var i = 0; i < relationships.children.length; i++) {
  2798. if (i === 8) {
  2799. console.warn('FBXLoader: maximum of 8 morph targets supported. Ignoring additional targets.');
  2800. break;
  2801. }
  2802. var child = relationships.children[i];
  2803. var morphTargetNode = deformerNodes[child.ID];
  2804. var rawMorphTarget = {
  2805. name: morphTargetNode.attrName,
  2806. initialWeight: morphTargetNode.DeformPercent,
  2807. id: morphTargetNode.id,
  2808. fullWeights: morphTargetNode.FullWeights.a
  2809. };
  2810. if (morphTargetNode.attrType !== 'BlendShapeChannel') return;
  2811. var targetRelationships = connections.get(parseInt(child.ID));
  2812. targetRelationships.children.forEach(function (child) {
  2813. if (child.relationship === undefined) rawMorphTarget.geoID = child.ID;
  2814. });
  2815. rawMorphTargets.push(rawMorphTarget);
  2816. }
  2817. return rawMorphTargets;
  2818. },
  2819. // create the main THREE.Group() to be returned by the loader
  2820. parseScene: function parseScene(deformers, geometryMap, materialMap) {
  2821. sceneGraph = new THREE.Group();
  2822. var modelMap = this.parseModels(deformers.skeletons, geometryMap, materialMap);
  2823. var modelNodes = fbxTree.Objects.Model;
  2824. var self = this;
  2825. modelMap.forEach(function (model) {
  2826. var modelNode = modelNodes[model.ID];
  2827. self.setLookAtProperties(model, modelNode);
  2828. var parentConnections = connections.get(model.ID).parents;
  2829. parentConnections.forEach(function (connection) {
  2830. var parent = modelMap.get(connection.ID);
  2831. if (parent !== undefined) parent.add(model);
  2832. });
  2833. if (model.parent === null) {
  2834. sceneGraph.add(model);
  2835. }
  2836. });
  2837. this.bindSkeleton(deformers.skeletons, geometryMap, modelMap);
  2838. this.createAmbientLight();
  2839. this.setupMorphMaterials();
  2840. var animations = new AnimationParser().parse();
  2841. // if all the models where already combined in a single group, just return that
  2842. if (sceneGraph.children.length === 1 && sceneGraph.children[0].isGroup) {
  2843. sceneGraph.children[0].animations = animations;
  2844. sceneGraph = sceneGraph.children[0];
  2845. }
  2846. sceneGraph.animations = animations;
  2847. },
  2848. // parse nodes in FBXTree.Objects.Model
  2849. parseModels: function parseModels(skeletons, geometryMap, materialMap) {
  2850. var modelMap = new Map();
  2851. var modelNodes = fbxTree.Objects.Model;
  2852. for (var nodeID in modelNodes) {
  2853. var id = parseInt(nodeID);
  2854. var node = modelNodes[nodeID];
  2855. var relationships = connections.get(id);
  2856. var model = this.buildSkeleton(relationships, skeletons, id, node.attrName);
  2857. if (!model) {
  2858. switch (node.attrType) {
  2859. case 'Camera':
  2860. model = this.createCamera(relationships);
  2861. break;
  2862. case 'Light':
  2863. model = this.createLight(relationships);
  2864. break;
  2865. case 'Mesh':
  2866. model = this.createMesh(relationships, geometryMap, materialMap);
  2867. break;
  2868. case 'NurbsCurve':
  2869. model = this.createCurve(relationships, geometryMap);
  2870. break;
  2871. case 'LimbNode': // usually associated with a Bone, however if a Bone was not created we'll make a Group instead
  2872. case 'Null':
  2873. default:
  2874. model = new THREE.Group();
  2875. break;
  2876. }
  2877. model.name = THREE.PropertyBinding.sanitizeNodeName(node.attrName);
  2878. model.ID = id;
  2879. }
  2880. this.setModelTransforms(model, node);
  2881. modelMap.set(id, model);
  2882. }
  2883. return modelMap;
  2884. },
  2885. buildSkeleton: function buildSkeleton(relationships, skeletons, id, name) {
  2886. var bone = null;
  2887. relationships.parents.forEach(function (parent) {
  2888. for (var ID in skeletons) {
  2889. var skeleton = skeletons[ID];
  2890. skeleton.rawBones.forEach(function (rawBone, i) {
  2891. if (rawBone.ID === parent.ID) {
  2892. var subBone = bone;
  2893. bone = new THREE.Bone();
  2894. bone.matrixWorld.copy(rawBone.transformLink);
  2895. // set name and id here - otherwise in cases where "subBone" is created it will not have a name / id
  2896. bone.name = THREE.PropertyBinding.sanitizeNodeName(name);
  2897. bone.ID = id;
  2898. skeleton.bones[i] = bone;
  2899. // In cases where a bone is shared between multiple meshes
  2900. // duplicate the bone here and and it as a child of the first bone
  2901. if (subBone !== null) {
  2902. bone.add(subBone);
  2903. }
  2904. }
  2905. });
  2906. }
  2907. });
  2908. return bone;
  2909. },
  2910. // create a THREE.PerspectiveCamera or THREE.OrthographicCamera
  2911. createCamera: function createCamera(relationships) {
  2912. var model;
  2913. var cameraAttribute;
  2914. relationships.children.forEach(function (child) {
  2915. var attr = fbxTree.Objects.NodeAttribute[child.ID];
  2916. if (attr !== undefined) {
  2917. cameraAttribute = attr;
  2918. }
  2919. });
  2920. if (cameraAttribute === undefined) {
  2921. model = new THREE.Object3D();
  2922. } else {
  2923. var type = 0;
  2924. if (cameraAttribute.CameraProjectionType !== undefined && cameraAttribute.CameraProjectionType.value === 1) {
  2925. type = 1;
  2926. }
  2927. var nearClippingPlane = 1;
  2928. if (cameraAttribute.NearPlane !== undefined) {
  2929. nearClippingPlane = cameraAttribute.NearPlane.value / 1000;
  2930. }
  2931. var farClippingPlane = 1000;
  2932. if (cameraAttribute.FarPlane !== undefined) {
  2933. farClippingPlane = cameraAttribute.FarPlane.value / 1000;
  2934. }
  2935. var width = window.innerWidth;
  2936. var height = window.innerHeight;
  2937. if (cameraAttribute.AspectWidth !== undefined && cameraAttribute.AspectHeight !== undefined) {
  2938. width = cameraAttribute.AspectWidth.value;
  2939. height = cameraAttribute.AspectHeight.value;
  2940. }
  2941. var aspect = width / height;
  2942. var fov = 45;
  2943. if (cameraAttribute.FieldOfView !== undefined) {
  2944. fov = cameraAttribute.FieldOfView.value;
  2945. }
  2946. var focalLength = cameraAttribute.FocalLength ? cameraAttribute.FocalLength.value : null;
  2947. switch (type) {
  2948. case 0:
  2949. // Perspective
  2950. model = new THREE.PerspectiveCamera(fov, aspect, nearClippingPlane, farClippingPlane);
  2951. if (focalLength !== null) model.setFocalLength(focalLength);
  2952. break;
  2953. case 1:
  2954. // Orthographic
  2955. model = new THREE.OrthographicCamera(-width / 2, width / 2, height / 2, -height / 2, nearClippingPlane, farClippingPlane);
  2956. break;
  2957. default:
  2958. console.warn('THREE.FBXLoader: Unknown camera type ' + type + '.');
  2959. model = new THREE.Object3D();
  2960. break;
  2961. }
  2962. }
  2963. return model;
  2964. },
  2965. // Create a THREE.DirectionalLight, THREE.PointLight or THREE.SpotLight
  2966. createLight: function createLight(relationships) {
  2967. var model;
  2968. var lightAttribute;
  2969. relationships.children.forEach(function (child) {
  2970. var attr = fbxTree.Objects.NodeAttribute[child.ID];
  2971. if (attr !== undefined) {
  2972. lightAttribute = attr;
  2973. }
  2974. });
  2975. if (lightAttribute === undefined) {
  2976. model = new THREE.Object3D();
  2977. } else {
  2978. var type;
  2979. // LightType can be undefined for Point lights
  2980. if (lightAttribute.LightType === undefined) {
  2981. type = 0;
  2982. } else {
  2983. type = lightAttribute.LightType.value;
  2984. }
  2985. var color = 0xffffff;
  2986. if (lightAttribute.Color !== undefined) {
  2987. color = new THREE.Color().fromArray(lightAttribute.Color.value);
  2988. }
  2989. var intensity = lightAttribute.Intensity === undefined ? 1 : lightAttribute.Intensity.value / 100;
  2990. // light disabled
  2991. if (lightAttribute.CastLightOnObject !== undefined && lightAttribute.CastLightOnObject.value === 0) {
  2992. intensity = 0;
  2993. }
  2994. var distance = 0;
  2995. if (lightAttribute.FarAttenuationEnd !== undefined) {
  2996. if (lightAttribute.EnableFarAttenuation !== undefined && lightAttribute.EnableFarAttenuation.value === 0) {
  2997. distance = 0;
  2998. } else {
  2999. distance = lightAttribute.FarAttenuationEnd.value;
  3000. }
  3001. }
  3002. // TODO: could this be calculated linearly from FarAttenuationStart to FarAttenuationEnd?
  3003. var decay = 1;
  3004. switch (type) {
  3005. case 0:
  3006. // Point
  3007. model = new THREE.PointLight(color, intensity, distance, decay);
  3008. break;
  3009. case 1:
  3010. // Directional
  3011. model = new THREE.DirectionalLight(color, intensity);
  3012. break;
  3013. case 2:
  3014. // Spot
  3015. var angle = Math.PI / 3;
  3016. if (lightAttribute.InnerAngle !== undefined) {
  3017. angle = THREE.Math.degToRad(lightAttribute.InnerAngle.value);
  3018. }
  3019. var penumbra = 0;
  3020. if (lightAttribute.OuterAngle !== undefined) {
  3021. // TODO: this is not correct - FBX calculates outer and inner angle in degrees
  3022. // with OuterAngle > InnerAngle && OuterAngle <= Math.PI
  3023. // while three.js uses a penumbra between (0, 1) to attenuate the inner angle
  3024. penumbra = THREE.Math.degToRad(lightAttribute.OuterAngle.value);
  3025. penumbra = Math.max(penumbra, 1);
  3026. }
  3027. model = new THREE.SpotLight(color, intensity, distance, angle, penumbra, decay);
  3028. break;
  3029. default:
  3030. console.warn('THREE.FBXLoader: Unknown light type ' + lightAttribute.LightType.value + ', defaulting to a THREE.PointLight.');
  3031. model = new THREE.PointLight(color, intensity);
  3032. break;
  3033. }
  3034. if (lightAttribute.CastShadows !== undefined && lightAttribute.CastShadows.value === 1) {
  3035. model.castShadow = true;
  3036. }
  3037. }
  3038. return model;
  3039. },
  3040. createMesh: function createMesh(relationships, geometryMap, materialMap) {
  3041. var model;
  3042. var geometry = null;
  3043. var material = null;
  3044. var materials = [];
  3045. // get geometry and materials(s) from connections
  3046. relationships.children.forEach(function (child) {
  3047. if (geometryMap.has(child.ID)) {
  3048. geometry = geometryMap.get(child.ID);
  3049. }
  3050. if (materialMap.has(child.ID)) {
  3051. materials.push(materialMap.get(child.ID));
  3052. }
  3053. });
  3054. if (materials.length > 1) {
  3055. material = materials;
  3056. } else if (materials.length > 0) {
  3057. material = materials[0];
  3058. } else {
  3059. material = new THREE.MeshPhongMaterial({ color: 0xcccccc });
  3060. materials.push(material);
  3061. }
  3062. if ('color' in geometry.attributes) {
  3063. materials.forEach(function (material) {
  3064. material.vertexColors = THREE.VertexColors;
  3065. });
  3066. }
  3067. if (geometry.FBX_Deformer) {
  3068. materials.forEach(function (material) {
  3069. material.skinning = true;
  3070. });
  3071. model = new THREE.SkinnedMesh(geometry, material);
  3072. } else {
  3073. model = new THREE.Mesh(geometry, material);
  3074. }
  3075. return model;
  3076. },
  3077. createCurve: function createCurve(relationships, geometryMap) {
  3078. var geometry = relationships.children.reduce(function (geo, child) {
  3079. if (geometryMap.has(child.ID)) geo = geometryMap.get(child.ID);
  3080. return geo;
  3081. }, null);
  3082. // FBX does not list materials for Nurbs lines, so we'll just put our own in here.
  3083. var material = new THREE.LineBasicMaterial({ color: 0x3300ff, linewidth: 1 });
  3084. return new THREE.Line(geometry, material);
  3085. },
  3086. // parse the model node for transform details and apply them to the model
  3087. setModelTransforms: function setModelTransforms(model, modelNode) {
  3088. var transformData = {};
  3089. if ('RotationOrder' in modelNode) transformData.eulerOrder = parseInt(modelNode.RotationOrder.value);
  3090. if ('Lcl_Translation' in modelNode) transformData.translation = modelNode.Lcl_Translation.value;
  3091. if ('RotationOffset' in modelNode) transformData.rotationOffset = modelNode.RotationOffset.value;
  3092. if ('Lcl_Rotation' in modelNode) transformData.rotation = modelNode.Lcl_Rotation.value;
  3093. if ('PreRotation' in modelNode) transformData.preRotation = modelNode.PreRotation.value;
  3094. if ('PostRotation' in modelNode) transformData.postRotation = modelNode.PostRotation.value;
  3095. if ('Lcl_Scaling' in modelNode) transformData.scale = modelNode.Lcl_Scaling.value;
  3096. var transform = generateTransform(transformData);
  3097. model.applyMatrix(transform);
  3098. },
  3099. setLookAtProperties: function setLookAtProperties(model, modelNode) {
  3100. if ('LookAtProperty' in modelNode) {
  3101. var children = connections.get(model.ID).children;
  3102. children.forEach(function (child) {
  3103. if (child.relationship === 'LookAtProperty') {
  3104. var lookAtTarget = fbxTree.Objects.Model[child.ID];
  3105. if ('Lcl_Translation' in lookAtTarget) {
  3106. var pos = lookAtTarget.Lcl_Translation.value;
  3107. // DirectionalLight, SpotLight
  3108. if (model.target !== undefined) {
  3109. model.target.position.fromArray(pos);
  3110. sceneGraph.add(model.target);
  3111. } else {
  3112. // Cameras and other Object3Ds
  3113. model.lookAt(new THREE.Vector3().fromArray(pos));
  3114. }
  3115. }
  3116. }
  3117. });
  3118. }
  3119. },
  3120. bindSkeleton: function bindSkeleton(skeletons, geometryMap, modelMap) {
  3121. var bindMatrices = this.parsePoseNodes();
  3122. for (var ID in skeletons) {
  3123. var skeleton = skeletons[ID];
  3124. var parents = connections.get(parseInt(skeleton.ID)).parents;
  3125. parents.forEach(function (parent) {
  3126. if (geometryMap.has(parent.ID)) {
  3127. var geoID = parent.ID;
  3128. var geoRelationships = connections.get(geoID);
  3129. geoRelationships.parents.forEach(function (geoConnParent) {
  3130. if (modelMap.has(geoConnParent.ID)) {
  3131. var model = modelMap.get(geoConnParent.ID);
  3132. model.bind(new THREE.Skeleton(skeleton.bones), bindMatrices[geoConnParent.ID]);
  3133. }
  3134. });
  3135. }
  3136. });
  3137. }
  3138. },
  3139. parsePoseNodes: function parsePoseNodes() {
  3140. var bindMatrices = {};
  3141. if ('Pose' in fbxTree.Objects) {
  3142. var BindPoseNode = fbxTree.Objects.Pose;
  3143. for (var nodeID in BindPoseNode) {
  3144. if (BindPoseNode[nodeID].attrType === 'BindPose') {
  3145. var poseNodes = BindPoseNode[nodeID].PoseNode;
  3146. if (Array.isArray(poseNodes)) {
  3147. poseNodes.forEach(function (poseNode) {
  3148. bindMatrices[poseNode.Node] = new THREE.Matrix4().fromArray(poseNode.Matrix.a);
  3149. });
  3150. } else {
  3151. bindMatrices[poseNodes.Node] = new THREE.Matrix4().fromArray(poseNodes.Matrix.a);
  3152. }
  3153. }
  3154. }
  3155. }
  3156. return bindMatrices;
  3157. },
  3158. // Parse ambient color in FBXTree.GlobalSettings - if it's not set to black (default), create an ambient light
  3159. createAmbientLight: function createAmbientLight() {
  3160. if ('GlobalSettings' in fbxTree && 'AmbientColor' in fbxTree.GlobalSettings) {
  3161. var ambientColor = fbxTree.GlobalSettings.AmbientColor.value;
  3162. var r = ambientColor[0];
  3163. var g = ambientColor[1];
  3164. var b = ambientColor[2];
  3165. if (r !== 0 || g !== 0 || b !== 0) {
  3166. var color = new THREE.Color(r, g, b);
  3167. sceneGraph.add(new THREE.AmbientLight(color, 1));
  3168. }
  3169. }
  3170. },
  3171. setupMorphMaterials: function setupMorphMaterials() {
  3172. sceneGraph.traverse(function (child) {
  3173. if (child.isMesh) {
  3174. if (child.geometry.morphAttributes.position || child.geometry.morphAttributes.normal) {
  3175. var uuid = child.uuid;
  3176. var matUuid = child.material.uuid;
  3177. // if a geometry has morph targets, it cannot share the material with other geometries
  3178. var sharedMat = false;
  3179. sceneGraph.traverse(function (child) {
  3180. if (child.isMesh) {
  3181. if (child.material.uuid === matUuid && child.uuid !== uuid) sharedMat = true;
  3182. }
  3183. });
  3184. if (sharedMat === true) child.material = child.material.clone();
  3185. child.material.morphTargets = true;
  3186. }
  3187. }
  3188. });
  3189. }
  3190. };
  3191. // parse Geometry data from FBXTree and return map of BufferGeometries
  3192. function GeometryParser() {}
  3193. GeometryParser.prototype = {
  3194. constructor: GeometryParser,
  3195. // Parse nodes in FBXTree.Objects.Geometry
  3196. parse: function parse(deformers) {
  3197. var geometryMap = new Map();
  3198. if ('Geometry' in fbxTree.Objects) {
  3199. var geoNodes = fbxTree.Objects.Geometry;
  3200. for (var nodeID in geoNodes) {
  3201. var relationships = connections.get(parseInt(nodeID));
  3202. var geo = this.parseGeometry(relationships, geoNodes[nodeID], deformers);
  3203. geometryMap.set(parseInt(nodeID), geo);
  3204. }
  3205. }
  3206. return geometryMap;
  3207. },
  3208. // Parse single node in FBXTree.Objects.Geometry
  3209. parseGeometry: function parseGeometry(relationships, geoNode, deformers) {
  3210. switch (geoNode.attrType) {
  3211. case 'Mesh':
  3212. return this.parseMeshGeometry(relationships, geoNode, deformers);
  3213. break;
  3214. case 'NurbsCurve':
  3215. return this.parseNurbsGeometry(geoNode);
  3216. break;
  3217. }
  3218. },
  3219. // Parse single node mesh geometry in FBXTree.Objects.Geometry
  3220. parseMeshGeometry: function parseMeshGeometry(relationships, geoNode, deformers) {
  3221. var skeletons = deformers.skeletons;
  3222. var morphTargets = deformers.morphTargets;
  3223. var modelNodes = relationships.parents.map(function (parent) {
  3224. return fbxTree.Objects.Model[parent.ID];
  3225. });
  3226. // don't create geometry if it is not associated with any models
  3227. if (modelNodes.length === 0) return;
  3228. var skeleton = relationships.children.reduce(function (skeleton, child) {
  3229. if (skeletons[child.ID] !== undefined) skeleton = skeletons[child.ID];
  3230. return skeleton;
  3231. }, null);
  3232. var morphTarget = relationships.children.reduce(function (morphTarget, child) {
  3233. if (morphTargets[child.ID] !== undefined) morphTarget = morphTargets[child.ID];
  3234. return morphTarget;
  3235. }, null);
  3236. // TODO: if there is more than one model associated with the geometry, AND the models have
  3237. // different geometric transforms, then this will cause problems
  3238. // if ( modelNodes.length > 1 ) { }
  3239. // For now just assume one model and get the preRotations from that
  3240. var modelNode = modelNodes[0];
  3241. var transformData = {};
  3242. if ('RotationOrder' in modelNode) transformData.eulerOrder = modelNode.RotationOrder.value;
  3243. if ('GeometricTranslation' in modelNode) transformData.translation = modelNode.GeometricTranslation.value;
  3244. if ('GeometricRotation' in modelNode) transformData.rotation = modelNode.GeometricRotation.value;
  3245. if ('GeometricScaling' in modelNode) transformData.scale = modelNode.GeometricScaling.value;
  3246. var transform = generateTransform(transformData);
  3247. return this.genGeometry(geoNode, skeleton, morphTarget, transform);
  3248. },
  3249. // Generate a THREE.BufferGeometry from a node in FBXTree.Objects.Geometry
  3250. genGeometry: function genGeometry(geoNode, skeleton, morphTarget, preTransform) {
  3251. var geo = new THREE.BufferGeometry();
  3252. if (geoNode.attrName) geo.name = geoNode.attrName;
  3253. var geoInfo = this.parseGeoNode(geoNode, skeleton);
  3254. var buffers = this.genBuffers(geoInfo);
  3255. var positionAttribute = new THREE.Float32BufferAttribute(buffers.vertex, 3);
  3256. preTransform.applyToBufferAttribute(positionAttribute);
  3257. geo.addAttribute('position', positionAttribute);
  3258. if (buffers.colors.length > 0) {
  3259. geo.addAttribute('color', new THREE.Float32BufferAttribute(buffers.colors, 3));
  3260. }
  3261. if (skeleton) {
  3262. geo.addAttribute('skinIndex', new THREE.Uint16BufferAttribute(buffers.weightsIndices, 4));
  3263. geo.addAttribute('skinWeight', new THREE.Float32BufferAttribute(buffers.vertexWeights, 4));
  3264. // used later to bind the skeleton to the model
  3265. geo.FBX_Deformer = skeleton;
  3266. }
  3267. if (buffers.normal.length > 0) {
  3268. var normalAttribute = new THREE.Float32BufferAttribute(buffers.normal, 3);
  3269. var normalMatrix = new THREE.Matrix3().getNormalMatrix(preTransform);
  3270. normalMatrix.applyToBufferAttribute(normalAttribute);
  3271. geo.addAttribute('normal', normalAttribute);
  3272. }
  3273. buffers.uvs.forEach(function (uvBuffer, i) {
  3274. // subsequent uv buffers are called 'uv1', 'uv2', ...
  3275. var name = 'uv' + (i + 1).toString();
  3276. // the first uv buffer is just called 'uv'
  3277. if (i === 0) {
  3278. name = 'uv';
  3279. }
  3280. geo.addAttribute(name, new THREE.Float32BufferAttribute(buffers.uvs[i], 2));
  3281. });
  3282. if (geoInfo.material && geoInfo.material.mappingType !== 'AllSame') {
  3283. // Convert the material indices of each vertex into rendering groups on the geometry.
  3284. var prevMaterialIndex = buffers.materialIndex[0];
  3285. var startIndex = 0;
  3286. buffers.materialIndex.forEach(function (currentIndex, i) {
  3287. if (currentIndex !== prevMaterialIndex) {
  3288. geo.addGroup(startIndex, i - startIndex, prevMaterialIndex);
  3289. prevMaterialIndex = currentIndex;
  3290. startIndex = i;
  3291. }
  3292. });
  3293. // the loop above doesn't add the last group, do that here.
  3294. if (geo.groups.length > 0) {
  3295. var lastGroup = geo.groups[geo.groups.length - 1];
  3296. var lastIndex = lastGroup.start + lastGroup.count;
  3297. if (lastIndex !== buffers.materialIndex.length) {
  3298. geo.addGroup(lastIndex, buffers.materialIndex.length - lastIndex, prevMaterialIndex);
  3299. }
  3300. }
  3301. // case where there are multiple materials but the whole geometry is only
  3302. // using one of them
  3303. if (geo.groups.length === 0) {
  3304. geo.addGroup(0, buffers.materialIndex.length, buffers.materialIndex[0]);
  3305. }
  3306. }
  3307. this.addMorphTargets(geo, geoNode, morphTarget, preTransform);
  3308. return geo;
  3309. },
  3310. parseGeoNode: function parseGeoNode(geoNode, skeleton) {
  3311. var geoInfo = {};
  3312. geoInfo.vertexPositions = geoNode.Vertices !== undefined ? geoNode.Vertices.a : [];
  3313. geoInfo.vertexIndices = geoNode.PolygonVertexIndex !== undefined ? geoNode.PolygonVertexIndex.a : [];
  3314. if (geoNode.LayerElementColor) {
  3315. geoInfo.color = this.parseVertexColors(geoNode.LayerElementColor[0]);
  3316. }
  3317. if (geoNode.LayerElementMaterial) {
  3318. geoInfo.material = this.parseMaterialIndices(geoNode.LayerElementMaterial[0]);
  3319. }
  3320. if (geoNode.LayerElementNormal) {
  3321. geoInfo.normal = this.parseNormals(geoNode.LayerElementNormal[0]);
  3322. }
  3323. if (geoNode.LayerElementUV) {
  3324. geoInfo.uv = [];
  3325. var i = 0;
  3326. while (geoNode.LayerElementUV[i]) {
  3327. geoInfo.uv.push(this.parseUVs(geoNode.LayerElementUV[i]));
  3328. i++;
  3329. }
  3330. }
  3331. geoInfo.weightTable = {};
  3332. if (skeleton !== null) {
  3333. geoInfo.skeleton = skeleton;
  3334. skeleton.rawBones.forEach(function (rawBone, i) {
  3335. // loop over the bone's vertex indices and weights
  3336. rawBone.indices.forEach(function (index, j) {
  3337. if (geoInfo.weightTable[index] === undefined) geoInfo.weightTable[index] = [];
  3338. geoInfo.weightTable[index].push({
  3339. id: i,
  3340. weight: rawBone.weights[j]
  3341. });
  3342. });
  3343. });
  3344. }
  3345. return geoInfo;
  3346. },
  3347. genBuffers: function genBuffers(geoInfo) {
  3348. var buffers = {
  3349. vertex: [],
  3350. normal: [],
  3351. colors: [],
  3352. uvs: [],
  3353. materialIndex: [],
  3354. vertexWeights: [],
  3355. weightsIndices: []
  3356. };
  3357. var polygonIndex = 0;
  3358. var faceLength = 0;
  3359. var displayedWeightsWarning = false;
  3360. // these will hold data for a single face
  3361. var facePositionIndexes = [];
  3362. var faceNormals = [];
  3363. var faceColors = [];
  3364. var faceUVs = [];
  3365. var faceWeights = [];
  3366. var faceWeightIndices = [];
  3367. var self = this;
  3368. geoInfo.vertexIndices.forEach(function (vertexIndex, polygonVertexIndex) {
  3369. var endOfFace = false;
  3370. // Face index and vertex index arrays are combined in a single array
  3371. // A cube with quad faces looks like this:
  3372. // PolygonVertexIndex: *24 {
  3373. // 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
  3374. // }
  3375. // Negative numbers mark the end of a face - first face here is 0, 1, 3, -3
  3376. // to find index of last vertex bit shift the index: ^ - 1
  3377. if (vertexIndex < 0) {
  3378. vertexIndex = vertexIndex ^ -1; // equivalent to ( x * -1 ) - 1
  3379. endOfFace = true;
  3380. }
  3381. var weightIndices = [];
  3382. var weights = [];
  3383. facePositionIndexes.push(vertexIndex * 3, vertexIndex * 3 + 1, vertexIndex * 3 + 2);
  3384. if (geoInfo.color) {
  3385. var data = getData(polygonVertexIndex, polygonIndex, vertexIndex, geoInfo.color);
  3386. faceColors.push(data[0], data[1], data[2]);
  3387. }
  3388. if (geoInfo.skeleton) {
  3389. if (geoInfo.weightTable[vertexIndex] !== undefined) {
  3390. geoInfo.weightTable[vertexIndex].forEach(function (wt) {
  3391. weights.push(wt.weight);
  3392. weightIndices.push(wt.id);
  3393. });
  3394. }
  3395. if (weights.length > 4) {
  3396. if (!displayedWeightsWarning) {
  3397. console.warn('THREE.FBXLoader: Vertex has more than 4 skinning weights assigned to vertex. Deleting additional weights.');
  3398. displayedWeightsWarning = true;
  3399. }
  3400. var wIndex = [0, 0, 0, 0];
  3401. var Weight = [0, 0, 0, 0];
  3402. weights.forEach(function (weight, weightIndex) {
  3403. var currentWeight = weight;
  3404. var currentIndex = weightIndices[weightIndex];
  3405. Weight.forEach(function (comparedWeight, comparedWeightIndex, comparedWeightArray) {
  3406. if (currentWeight > comparedWeight) {
  3407. comparedWeightArray[comparedWeightIndex] = currentWeight;
  3408. currentWeight = comparedWeight;
  3409. var tmp = wIndex[comparedWeightIndex];
  3410. wIndex[comparedWeightIndex] = currentIndex;
  3411. currentIndex = tmp;
  3412. }
  3413. });
  3414. });
  3415. weightIndices = wIndex;
  3416. weights = Weight;
  3417. }
  3418. // if the weight array is shorter than 4 pad with 0s
  3419. while (weights.length < 4) {
  3420. weights.push(0);
  3421. weightIndices.push(0);
  3422. }
  3423. for (var i = 0; i < 4; ++i) {
  3424. faceWeights.push(weights[i]);
  3425. faceWeightIndices.push(weightIndices[i]);
  3426. }
  3427. }
  3428. if (geoInfo.normal) {
  3429. var data = getData(polygonVertexIndex, polygonIndex, vertexIndex, geoInfo.normal);
  3430. faceNormals.push(data[0], data[1], data[2]);
  3431. }
  3432. if (geoInfo.material && geoInfo.material.mappingType !== 'AllSame') {
  3433. var materialIndex = getData(polygonVertexIndex, polygonIndex, vertexIndex, geoInfo.material)[0];
  3434. }
  3435. if (geoInfo.uv) {
  3436. geoInfo.uv.forEach(function (uv, i) {
  3437. var data = getData(polygonVertexIndex, polygonIndex, vertexIndex, uv);
  3438. if (faceUVs[i] === undefined) {
  3439. faceUVs[i] = [];
  3440. }
  3441. faceUVs[i].push(data[0]);
  3442. faceUVs[i].push(data[1]);
  3443. });
  3444. }
  3445. faceLength++;
  3446. if (endOfFace) {
  3447. self.genFace(buffers, geoInfo, facePositionIndexes, materialIndex, faceNormals, faceColors, faceUVs, faceWeights, faceWeightIndices, faceLength);
  3448. polygonIndex++;
  3449. faceLength = 0;
  3450. // reset arrays for the next face
  3451. facePositionIndexes = [];
  3452. faceNormals = [];
  3453. faceColors = [];
  3454. faceUVs = [];
  3455. faceWeights = [];
  3456. faceWeightIndices = [];
  3457. }
  3458. });
  3459. return buffers;
  3460. },
  3461. // Generate data for a single face in a geometry. If the face is a quad then split it into 2 tris
  3462. genFace: function genFace(buffers, geoInfo, facePositionIndexes, materialIndex, faceNormals, faceColors, faceUVs, faceWeights, faceWeightIndices, faceLength) {
  3463. for (var i = 2; i < faceLength; i++) {
  3464. buffers.vertex.push(geoInfo.vertexPositions[facePositionIndexes[0]]);
  3465. buffers.vertex.push(geoInfo.vertexPositions[facePositionIndexes[1]]);
  3466. buffers.vertex.push(geoInfo.vertexPositions[facePositionIndexes[2]]);
  3467. buffers.vertex.push(geoInfo.vertexPositions[facePositionIndexes[(i - 1) * 3]]);
  3468. buffers.vertex.push(geoInfo.vertexPositions[facePositionIndexes[(i - 1) * 3 + 1]]);
  3469. buffers.vertex.push(geoInfo.vertexPositions[facePositionIndexes[(i - 1) * 3 + 2]]);
  3470. buffers.vertex.push(geoInfo.vertexPositions[facePositionIndexes[i * 3]]);
  3471. buffers.vertex.push(geoInfo.vertexPositions[facePositionIndexes[i * 3 + 1]]);
  3472. buffers.vertex.push(geoInfo.vertexPositions[facePositionIndexes[i * 3 + 2]]);
  3473. if (geoInfo.skeleton) {
  3474. buffers.vertexWeights.push(faceWeights[0]);
  3475. buffers.vertexWeights.push(faceWeights[1]);
  3476. buffers.vertexWeights.push(faceWeights[2]);
  3477. buffers.vertexWeights.push(faceWeights[3]);
  3478. buffers.vertexWeights.push(faceWeights[(i - 1) * 4]);
  3479. buffers.vertexWeights.push(faceWeights[(i - 1) * 4 + 1]);
  3480. buffers.vertexWeights.push(faceWeights[(i - 1) * 4 + 2]);
  3481. buffers.vertexWeights.push(faceWeights[(i - 1) * 4 + 3]);
  3482. buffers.vertexWeights.push(faceWeights[i * 4]);
  3483. buffers.vertexWeights.push(faceWeights[i * 4 + 1]);
  3484. buffers.vertexWeights.push(faceWeights[i * 4 + 2]);
  3485. buffers.vertexWeights.push(faceWeights[i * 4 + 3]);
  3486. buffers.weightsIndices.push(faceWeightIndices[0]);
  3487. buffers.weightsIndices.push(faceWeightIndices[1]);
  3488. buffers.weightsIndices.push(faceWeightIndices[2]);
  3489. buffers.weightsIndices.push(faceWeightIndices[3]);
  3490. buffers.weightsIndices.push(faceWeightIndices[(i - 1) * 4]);
  3491. buffers.weightsIndices.push(faceWeightIndices[(i - 1) * 4 + 1]);
  3492. buffers.weightsIndices.push(faceWeightIndices[(i - 1) * 4 + 2]);
  3493. buffers.weightsIndices.push(faceWeightIndices[(i - 1) * 4 + 3]);
  3494. buffers.weightsIndices.push(faceWeightIndices[i * 4]);
  3495. buffers.weightsIndices.push(faceWeightIndices[i * 4 + 1]);
  3496. buffers.weightsIndices.push(faceWeightIndices[i * 4 + 2]);
  3497. buffers.weightsIndices.push(faceWeightIndices[i * 4 + 3]);
  3498. }
  3499. if (geoInfo.color) {
  3500. buffers.colors.push(faceColors[0]);
  3501. buffers.colors.push(faceColors[1]);
  3502. buffers.colors.push(faceColors[2]);
  3503. buffers.colors.push(faceColors[(i - 1) * 3]);
  3504. buffers.colors.push(faceColors[(i - 1) * 3 + 1]);
  3505. buffers.colors.push(faceColors[(i - 1) * 3 + 2]);
  3506. buffers.colors.push(faceColors[i * 3]);
  3507. buffers.colors.push(faceColors[i * 3 + 1]);
  3508. buffers.colors.push(faceColors[i * 3 + 2]);
  3509. }
  3510. if (geoInfo.material && geoInfo.material.mappingType !== 'AllSame') {
  3511. buffers.materialIndex.push(materialIndex);
  3512. buffers.materialIndex.push(materialIndex);
  3513. buffers.materialIndex.push(materialIndex);
  3514. }
  3515. if (geoInfo.normal) {
  3516. buffers.normal.push(faceNormals[0]);
  3517. buffers.normal.push(faceNormals[1]);
  3518. buffers.normal.push(faceNormals[2]);
  3519. buffers.normal.push(faceNormals[(i - 1) * 3]);
  3520. buffers.normal.push(faceNormals[(i - 1) * 3 + 1]);
  3521. buffers.normal.push(faceNormals[(i - 1) * 3 + 2]);
  3522. buffers.normal.push(faceNormals[i * 3]);
  3523. buffers.normal.push(faceNormals[i * 3 + 1]);
  3524. buffers.normal.push(faceNormals[i * 3 + 2]);
  3525. }
  3526. if (geoInfo.uv) {
  3527. geoInfo.uv.forEach(function (uv, j) {
  3528. if (buffers.uvs[j] === undefined) buffers.uvs[j] = [];
  3529. buffers.uvs[j].push(faceUVs[j][0]);
  3530. buffers.uvs[j].push(faceUVs[j][1]);
  3531. buffers.uvs[j].push(faceUVs[j][(i - 1) * 2]);
  3532. buffers.uvs[j].push(faceUVs[j][(i - 1) * 2 + 1]);
  3533. buffers.uvs[j].push(faceUVs[j][i * 2]);
  3534. buffers.uvs[j].push(faceUVs[j][i * 2 + 1]);
  3535. });
  3536. }
  3537. }
  3538. },
  3539. addMorphTargets: function addMorphTargets(parentGeo, parentGeoNode, morphTarget, preTransform) {
  3540. if (morphTarget === null) return;
  3541. parentGeo.morphAttributes.position = [];
  3542. parentGeo.morphAttributes.normal = [];
  3543. var self = this;
  3544. morphTarget.rawTargets.forEach(function (rawTarget) {
  3545. var morphGeoNode = fbxTree.Objects.Geometry[rawTarget.geoID];
  3546. if (morphGeoNode !== undefined) {
  3547. self.genMorphGeometry(parentGeo, parentGeoNode, morphGeoNode, preTransform);
  3548. }
  3549. });
  3550. },
  3551. // a morph geometry node is similar to a standard node, and the node is also contained
  3552. // in FBXTree.Objects.Geometry, however it can only have attributes for position, normal
  3553. // and a special attribute Index defining which vertices of the original geometry are affected
  3554. // Normal and position attributes only have data for the vertices that are affected by the morph
  3555. genMorphGeometry: function genMorphGeometry(parentGeo, parentGeoNode, morphGeoNode, preTransform) {
  3556. var morphGeo = new THREE.BufferGeometry();
  3557. if (morphGeoNode.attrName) morphGeo.name = morphGeoNode.attrName;
  3558. var vertexIndices = parentGeoNode.PolygonVertexIndex !== undefined ? parentGeoNode.PolygonVertexIndex.a : [];
  3559. // make a copy of the parent's vertex positions
  3560. var vertexPositions = parentGeoNode.Vertices !== undefined ? parentGeoNode.Vertices.a.slice() : [];
  3561. var morphPositions = morphGeoNode.Vertices !== undefined ? morphGeoNode.Vertices.a : [];
  3562. var indices = morphGeoNode.Indexes !== undefined ? morphGeoNode.Indexes.a : [];
  3563. for (var i = 0; i < indices.length; i++) {
  3564. var morphIndex = indices[i] * 3;
  3565. // FBX format uses blend shapes rather than morph targets. This can be converted
  3566. // by additively combining the blend shape positions with the original geometry's positions
  3567. vertexPositions[morphIndex] += morphPositions[i * 3];
  3568. vertexPositions[morphIndex + 1] += morphPositions[i * 3 + 1];
  3569. vertexPositions[morphIndex + 2] += morphPositions[i * 3 + 2];
  3570. }
  3571. // TODO: add morph normal support
  3572. var morphGeoInfo = {
  3573. vertexIndices: vertexIndices,
  3574. vertexPositions: vertexPositions
  3575. };
  3576. var morphBuffers = this.genBuffers(morphGeoInfo);
  3577. var positionAttribute = new THREE.Float32BufferAttribute(morphBuffers.vertex, 3);
  3578. positionAttribute.name = morphGeoNode.attrName;
  3579. preTransform.applyToBufferAttribute(positionAttribute);
  3580. parentGeo.morphAttributes.position.push(positionAttribute);
  3581. },
  3582. // Parse normal from FBXTree.Objects.Geometry.LayerElementNormal if it exists
  3583. parseNormals: function parseNormals(NormalNode) {
  3584. var mappingType = NormalNode.MappingInformationType;
  3585. var referenceType = NormalNode.ReferenceInformationType;
  3586. var buffer = NormalNode.Normals.a;
  3587. var indexBuffer = [];
  3588. if (referenceType === 'IndexToDirect') {
  3589. if ('NormalIndex' in NormalNode) {
  3590. indexBuffer = NormalNode.NormalIndex.a;
  3591. } else if ('NormalsIndex' in NormalNode) {
  3592. indexBuffer = NormalNode.NormalsIndex.a;
  3593. }
  3594. }
  3595. return {
  3596. dataSize: 3,
  3597. buffer: buffer,
  3598. indices: indexBuffer,
  3599. mappingType: mappingType,
  3600. referenceType: referenceType
  3601. };
  3602. },
  3603. // Parse UVs from FBXTree.Objects.Geometry.LayerElementUV if it exists
  3604. parseUVs: function parseUVs(UVNode) {
  3605. var mappingType = UVNode.MappingInformationType;
  3606. var referenceType = UVNode.ReferenceInformationType;
  3607. var buffer = UVNode.UV.a;
  3608. var indexBuffer = [];
  3609. if (referenceType === 'IndexToDirect') {
  3610. indexBuffer = UVNode.UVIndex.a;
  3611. }
  3612. return {
  3613. dataSize: 2,
  3614. buffer: buffer,
  3615. indices: indexBuffer,
  3616. mappingType: mappingType,
  3617. referenceType: referenceType
  3618. };
  3619. },
  3620. // Parse Vertex Colors from FBXTree.Objects.Geometry.LayerElementColor if it exists
  3621. parseVertexColors: function parseVertexColors(ColorNode) {
  3622. var mappingType = ColorNode.MappingInformationType;
  3623. var referenceType = ColorNode.ReferenceInformationType;
  3624. var buffer = ColorNode.Colors.a;
  3625. var indexBuffer = [];
  3626. if (referenceType === 'IndexToDirect') {
  3627. indexBuffer = ColorNode.ColorIndex.a;
  3628. }
  3629. return {
  3630. dataSize: 4,
  3631. buffer: buffer,
  3632. indices: indexBuffer,
  3633. mappingType: mappingType,
  3634. referenceType: referenceType
  3635. };
  3636. },
  3637. // Parse mapping and material data in FBXTree.Objects.Geometry.LayerElementMaterial if it exists
  3638. parseMaterialIndices: function parseMaterialIndices(MaterialNode) {
  3639. var mappingType = MaterialNode.MappingInformationType;
  3640. var referenceType = MaterialNode.ReferenceInformationType;
  3641. if (mappingType === 'NoMappingInformation') {
  3642. return {
  3643. dataSize: 1,
  3644. buffer: [0],
  3645. indices: [0],
  3646. mappingType: 'AllSame',
  3647. referenceType: referenceType
  3648. };
  3649. }
  3650. var materialIndexBuffer = MaterialNode.Materials.a;
  3651. // Since materials are stored as indices, there's a bit of a mismatch between FBX and what
  3652. // we expect.So we create an intermediate buffer that points to the index in the buffer,
  3653. // for conforming with the other functions we've written for other data.
  3654. var materialIndices = [];
  3655. for (var i = 0; i < materialIndexBuffer.length; ++i) {
  3656. materialIndices.push(i);
  3657. }
  3658. return {
  3659. dataSize: 1,
  3660. buffer: materialIndexBuffer,
  3661. indices: materialIndices,
  3662. mappingType: mappingType,
  3663. referenceType: referenceType
  3664. };
  3665. },
  3666. // Generate a NurbGeometry from a node in FBXTree.Objects.Geometry
  3667. parseNurbsGeometry: function parseNurbsGeometry(geoNode) {
  3668. if (THREE.NURBSCurve === undefined) {
  3669. console.error('THREE.FBXLoader: The loader relies on THREE.NURBSCurve for any nurbs present in the model. Nurbs will show up as empty geometry.');
  3670. return new THREE.BufferGeometry();
  3671. }
  3672. var order = parseInt(geoNode.Order);
  3673. if (isNaN(order)) {
  3674. console.error('THREE.FBXLoader: Invalid Order %s given for geometry ID: %s', geoNode.Order, geoNode.id);
  3675. return new THREE.BufferGeometry();
  3676. }
  3677. var degree = order - 1;
  3678. var knots = geoNode.KnotVector.a;
  3679. var controlPoints = [];
  3680. var pointsValues = geoNode.Points.a;
  3681. for (var i = 0, l = pointsValues.length; i < l; i += 4) {
  3682. controlPoints.push(new THREE.Vector4().fromArray(pointsValues, i));
  3683. }
  3684. var startKnot, endKnot;
  3685. if (geoNode.Form === 'Closed') {
  3686. controlPoints.push(controlPoints[0]);
  3687. } else if (geoNode.Form === 'Periodic') {
  3688. startKnot = degree;
  3689. endKnot = knots.length - 1 - startKnot;
  3690. for (var i = 0; i < degree; ++i) {
  3691. controlPoints.push(controlPoints[i]);
  3692. }
  3693. }
  3694. var curve = new THREE.NURBSCurve(degree, knots, controlPoints, startKnot, endKnot);
  3695. var vertices = curve.getPoints(controlPoints.length * 7);
  3696. var positions = new Float32Array(vertices.length * 3);
  3697. vertices.forEach(function (vertex, i) {
  3698. vertex.toArray(positions, i * 3);
  3699. });
  3700. var geometry = new THREE.BufferGeometry();
  3701. geometry.addAttribute('position', new THREE.BufferAttribute(positions, 3));
  3702. return geometry;
  3703. }
  3704. };
  3705. // parse animation data from FBXTree
  3706. function AnimationParser() {}
  3707. AnimationParser.prototype = {
  3708. constructor: AnimationParser,
  3709. // take raw animation clips and turn them into three.js animation clips
  3710. parse: function parse() {
  3711. var animationClips = [];
  3712. var rawClips = this.parseClips();
  3713. if (rawClips === undefined) return animationClips;
  3714. for (var key in rawClips) {
  3715. var rawClip = rawClips[key];
  3716. var clip = this.addClip(rawClip);
  3717. animationClips.push(clip);
  3718. }
  3719. return animationClips;
  3720. },
  3721. parseClips: function parseClips() {
  3722. // since the actual transformation data is stored in FBXTree.Objects.AnimationCurve,
  3723. // if this is undefined we can safely assume there are no animations
  3724. if (fbxTree.Objects.AnimationCurve === undefined) return undefined;
  3725. var curveNodesMap = this.parseAnimationCurveNodes();
  3726. this.parseAnimationCurves(curveNodesMap);
  3727. var layersMap = this.parseAnimationLayers(curveNodesMap);
  3728. var rawClips = this.parseAnimStacks(layersMap);
  3729. return rawClips;
  3730. },
  3731. // parse nodes in FBXTree.Objects.AnimationCurveNode
  3732. // each AnimationCurveNode holds data for an animation transform for a model (e.g. left arm rotation )
  3733. // and is referenced by an AnimationLayer
  3734. parseAnimationCurveNodes: function parseAnimationCurveNodes() {
  3735. var rawCurveNodes = fbxTree.Objects.AnimationCurveNode;
  3736. var curveNodesMap = new Map();
  3737. for (var nodeID in rawCurveNodes) {
  3738. var rawCurveNode = rawCurveNodes[nodeID];
  3739. if (rawCurveNode.attrName.match(/S|R|T|DeformPercent/) !== null) {
  3740. var curveNode = {
  3741. id: rawCurveNode.id,
  3742. attr: rawCurveNode.attrName,
  3743. curves: {}
  3744. };
  3745. curveNodesMap.set(curveNode.id, curveNode);
  3746. }
  3747. }
  3748. return curveNodesMap;
  3749. },
  3750. // parse nodes in FBXTree.Objects.AnimationCurve and connect them up to
  3751. // previously parsed AnimationCurveNodes. Each AnimationCurve holds data for a single animated
  3752. // axis ( e.g. times and values of x rotation)
  3753. parseAnimationCurves: function parseAnimationCurves(curveNodesMap) {
  3754. var rawCurves = fbxTree.Objects.AnimationCurve;
  3755. // TODO: Many values are identical up to roundoff error, but won't be optimised
  3756. // e.g. position times: [0, 0.4, 0. 8]
  3757. // position values: [7.23538335023477e-7, 93.67518615722656, -0.9982695579528809, 7.23538335023477e-7, 93.67518615722656, -0.9982695579528809, 7.235384487103147e-7, 93.67520904541016, -0.9982695579528809]
  3758. // clearly, this should be optimised to
  3759. // times: [0], positions [7.23538335023477e-7, 93.67518615722656, -0.9982695579528809]
  3760. // this shows up in nearly every FBX file, and generally time array is length > 100
  3761. for (var nodeID in rawCurves) {
  3762. var animationCurve = {
  3763. id: rawCurves[nodeID].id,
  3764. times: rawCurves[nodeID].KeyTime.a.map(convertFBXTimeToSeconds),
  3765. values: rawCurves[nodeID].KeyValueFloat.a
  3766. };
  3767. var relationships = connections.get(animationCurve.id);
  3768. if (relationships !== undefined) {
  3769. var animationCurveID = relationships.parents[0].ID;
  3770. var animationCurveRelationship = relationships.parents[0].relationship;
  3771. if (animationCurveRelationship.match(/X/)) {
  3772. curveNodesMap.get(animationCurveID).curves['x'] = animationCurve;
  3773. } else if (animationCurveRelationship.match(/Y/)) {
  3774. curveNodesMap.get(animationCurveID).curves['y'] = animationCurve;
  3775. } else if (animationCurveRelationship.match(/Z/)) {
  3776. curveNodesMap.get(animationCurveID).curves['z'] = animationCurve;
  3777. } else if (animationCurveRelationship.match(/d|DeformPercent/) && curveNodesMap.has(animationCurveID)) {
  3778. curveNodesMap.get(animationCurveID).curves['morph'] = animationCurve;
  3779. }
  3780. }
  3781. }
  3782. },
  3783. // parse nodes in FBXTree.Objects.AnimationLayer. Each layers holds references
  3784. // to various AnimationCurveNodes and is referenced by an AnimationStack node
  3785. // note: theoretically a stack can have multiple layers, however in practice there always seems to be one per stack
  3786. parseAnimationLayers: function parseAnimationLayers(curveNodesMap) {
  3787. var rawLayers = fbxTree.Objects.AnimationLayer;
  3788. var layersMap = new Map();
  3789. for (var nodeID in rawLayers) {
  3790. var layerCurveNodes = [];
  3791. var connection = connections.get(parseInt(nodeID));
  3792. if (connection !== undefined) {
  3793. // all the animationCurveNodes used in the layer
  3794. var children = connection.children;
  3795. var self = this;
  3796. children.forEach(function (child, i) {
  3797. if (curveNodesMap.has(child.ID)) {
  3798. var curveNode = curveNodesMap.get(child.ID);
  3799. // check that the curves are defined for at least one axis, otherwise ignore the curveNode
  3800. if (curveNode.curves.x !== undefined || curveNode.curves.y !== undefined || curveNode.curves.z !== undefined) {
  3801. if (layerCurveNodes[i] === undefined) {
  3802. var modelID;
  3803. connections.get(child.ID).parents.forEach(function (parent) {
  3804. if (parent.relationship !== undefined) modelID = parent.ID;
  3805. });
  3806. var rawModel = fbxTree.Objects.Model[modelID.toString()];
  3807. var node = {
  3808. modelName: THREE.PropertyBinding.sanitizeNodeName(rawModel.attrName),
  3809. initialPosition: [0, 0, 0],
  3810. initialRotation: [0, 0, 0],
  3811. initialScale: [1, 1, 1],
  3812. transform: self.getModelAnimTransform(rawModel)
  3813. };
  3814. // if the animated model is pre rotated, we'll have to apply the pre rotations to every
  3815. // animation value as well
  3816. if ('PreRotation' in rawModel) node.preRotations = rawModel.PreRotation.value;
  3817. if ('PostRotation' in rawModel) node.postRotations = rawModel.PostRotation.value;
  3818. layerCurveNodes[i] = node;
  3819. }
  3820. layerCurveNodes[i][curveNode.attr] = curveNode;
  3821. } else if (curveNode.curves.morph !== undefined) {
  3822. if (layerCurveNodes[i] === undefined) {
  3823. var deformerID;
  3824. connections.get(child.ID).parents.forEach(function (parent) {
  3825. if (parent.relationship !== undefined) deformerID = parent.ID;
  3826. });
  3827. var morpherID = connections.get(deformerID).parents[0].ID;
  3828. var geoID = connections.get(morpherID).parents[0].ID;
  3829. // assuming geometry is not used in more than one model
  3830. var modelID = connections.get(geoID).parents[0].ID;
  3831. var rawModel = fbxTree.Objects.Model[modelID];
  3832. var node = {
  3833. modelName: THREE.PropertyBinding.sanitizeNodeName(rawModel.attrName),
  3834. morphName: fbxTree.Objects.Deformer[deformerID].attrName
  3835. };
  3836. layerCurveNodes[i] = node;
  3837. }
  3838. layerCurveNodes[i][curveNode.attr] = curveNode;
  3839. }
  3840. }
  3841. });
  3842. layersMap.set(parseInt(nodeID), layerCurveNodes);
  3843. }
  3844. }
  3845. return layersMap;
  3846. },
  3847. getModelAnimTransform: function getModelAnimTransform(modelNode) {
  3848. var transformData = {};
  3849. if ('RotationOrder' in modelNode) transformData.eulerOrder = parseInt(modelNode.RotationOrder.value);
  3850. if ('Lcl_Translation' in modelNode) transformData.translation = modelNode.Lcl_Translation.value;
  3851. if ('RotationOffset' in modelNode) transformData.rotationOffset = modelNode.RotationOffset.value;
  3852. if ('Lcl_Rotation' in modelNode) transformData.rotation = modelNode.Lcl_Rotation.value;
  3853. if ('PreRotation' in modelNode) transformData.preRotation = modelNode.PreRotation.value;
  3854. if ('PostRotation' in modelNode) transformData.postRotation = modelNode.PostRotation.value;
  3855. if ('Lcl_Scaling' in modelNode) transformData.scale = modelNode.Lcl_Scaling.value;
  3856. return generateTransform(transformData);
  3857. },
  3858. // parse nodes in FBXTree.Objects.AnimationStack. These are the top level node in the animation
  3859. // hierarchy. Each Stack node will be used to create a THREE.AnimationClip
  3860. parseAnimStacks: function parseAnimStacks(layersMap) {
  3861. var rawStacks = fbxTree.Objects.AnimationStack;
  3862. // connect the stacks (clips) up to the layers
  3863. var rawClips = {};
  3864. for (var nodeID in rawStacks) {
  3865. var children = connections.get(parseInt(nodeID)).children;
  3866. if (children.length > 1) {
  3867. // it seems like stacks will always be associated with a single layer. But just in case there are files
  3868. // where there are multiple layers per stack, we'll display a warning
  3869. console.warn('THREE.FBXLoader: Encountered an animation stack with multiple layers, this is currently not supported. Ignoring subsequent layers.');
  3870. }
  3871. var layer = layersMap.get(children[0].ID);
  3872. rawClips[nodeID] = {
  3873. name: rawStacks[nodeID].attrName,
  3874. layer: layer
  3875. };
  3876. }
  3877. return rawClips;
  3878. },
  3879. addClip: function addClip(rawClip) {
  3880. var tracks = [];
  3881. var self = this;
  3882. rawClip.layer.forEach(function (rawTracks) {
  3883. tracks = tracks.concat(self.generateTracks(rawTracks));
  3884. });
  3885. return new THREE.AnimationClip(rawClip.name, -1, tracks);
  3886. },
  3887. generateTracks: function generateTracks(rawTracks) {
  3888. var tracks = [];
  3889. var initialPosition = new THREE.Vector3();
  3890. var initialRotation = new THREE.Quaternion();
  3891. var initialScale = new THREE.Vector3();
  3892. if (rawTracks.transform) rawTracks.transform.decompose(initialPosition, initialRotation, initialScale);
  3893. initialPosition = initialPosition.toArray();
  3894. initialRotation = new THREE.Euler().setFromQuaternion(initialRotation).toArray(); // todo: euler order
  3895. initialScale = initialScale.toArray();
  3896. if (rawTracks.T !== undefined && Object.keys(rawTracks.T.curves).length > 0) {
  3897. var positionTrack = this.generateVectorTrack(rawTracks.modelName, rawTracks.T.curves, initialPosition, 'position');
  3898. if (positionTrack !== undefined) tracks.push(positionTrack);
  3899. }
  3900. if (rawTracks.R !== undefined && Object.keys(rawTracks.R.curves).length > 0) {
  3901. var rotationTrack = this.generateRotationTrack(rawTracks.modelName, rawTracks.R.curves, initialRotation, rawTracks.preRotations, rawTracks.postRotations);
  3902. if (rotationTrack !== undefined) tracks.push(rotationTrack);
  3903. }
  3904. if (rawTracks.S !== undefined && Object.keys(rawTracks.S.curves).length > 0) {
  3905. var scaleTrack = this.generateVectorTrack(rawTracks.modelName, rawTracks.S.curves, initialScale, 'scale');
  3906. if (scaleTrack !== undefined) tracks.push(scaleTrack);
  3907. }
  3908. if (rawTracks.DeformPercent !== undefined) {
  3909. var morphTrack = this.generateMorphTrack(rawTracks);
  3910. if (morphTrack !== undefined) tracks.push(morphTrack);
  3911. }
  3912. return tracks;
  3913. },
  3914. generateVectorTrack: function generateVectorTrack(modelName, curves, initialValue, type) {
  3915. var times = this.getTimesForAllAxes(curves);
  3916. var values = this.getKeyframeTrackValues(times, curves, initialValue);
  3917. return new THREE.VectorKeyframeTrack(modelName + '.' + type, times, values);
  3918. },
  3919. generateRotationTrack: function generateRotationTrack(modelName, curves, initialValue, preRotations, postRotations) {
  3920. if (curves.x !== undefined) {
  3921. this.interpolateRotations(curves.x);
  3922. curves.x.values = curves.x.values.map(THREE.Math.degToRad);
  3923. }
  3924. if (curves.y !== undefined) {
  3925. this.interpolateRotations(curves.y);
  3926. curves.y.values = curves.y.values.map(THREE.Math.degToRad);
  3927. }
  3928. if (curves.z !== undefined) {
  3929. this.interpolateRotations(curves.z);
  3930. curves.z.values = curves.z.values.map(THREE.Math.degToRad);
  3931. }
  3932. var times = this.getTimesForAllAxes(curves);
  3933. var values = this.getKeyframeTrackValues(times, curves, initialValue);
  3934. if (preRotations !== undefined) {
  3935. preRotations = preRotations.map(THREE.Math.degToRad);
  3936. preRotations.push('ZYX');
  3937. preRotations = new THREE.Euler().fromArray(preRotations);
  3938. preRotations = new THREE.Quaternion().setFromEuler(preRotations);
  3939. }
  3940. if (postRotations !== undefined) {
  3941. postRotations = postRotations.map(THREE.Math.degToRad);
  3942. postRotations.push('ZYX');
  3943. postRotations = new THREE.Euler().fromArray(postRotations);
  3944. postRotations = new THREE.Quaternion().setFromEuler(postRotations).inverse();
  3945. }
  3946. var quaternion = new THREE.Quaternion();
  3947. var euler = new THREE.Euler();
  3948. var quaternionValues = [];
  3949. for (var i = 0; i < values.length; i += 3) {
  3950. euler.set(values[i], values[i + 1], values[i + 2], 'ZYX');
  3951. quaternion.setFromEuler(euler);
  3952. if (preRotations !== undefined) quaternion.premultiply(preRotations);
  3953. if (postRotations !== undefined) quaternion.multiply(postRotations);
  3954. quaternion.toArray(quaternionValues, i / 3 * 4);
  3955. }
  3956. return new THREE.QuaternionKeyframeTrack(modelName + '.quaternion', times, quaternionValues);
  3957. },
  3958. generateMorphTrack: function generateMorphTrack(rawTracks) {
  3959. var curves = rawTracks.DeformPercent.curves.morph;
  3960. var values = curves.values.map(function (val) {
  3961. return val / 100;
  3962. });
  3963. var morphNum = sceneGraph.getObjectByName(rawTracks.modelName).morphTargetDictionary[rawTracks.morphName];
  3964. return new THREE.NumberKeyframeTrack(rawTracks.modelName + '.morphTargetInfluences[' + morphNum + ']', curves.times, values);
  3965. },
  3966. // For all animated objects, times are defined separately for each axis
  3967. // Here we'll combine the times into one sorted array without duplicates
  3968. getTimesForAllAxes: function getTimesForAllAxes(curves) {
  3969. var times = [];
  3970. // first join together the times for each axis, if defined
  3971. if (curves.x !== undefined) times = times.concat(curves.x.times);
  3972. if (curves.y !== undefined) times = times.concat(curves.y.times);
  3973. if (curves.z !== undefined) times = times.concat(curves.z.times);
  3974. // then sort them and remove duplicates
  3975. times = times.sort(function (a, b) {
  3976. return a - b;
  3977. }).filter(function (elem, index, array) {
  3978. return array.indexOf(elem) == index;
  3979. });
  3980. return times;
  3981. },
  3982. getKeyframeTrackValues: function getKeyframeTrackValues(times, curves, initialValue) {
  3983. var prevValue = initialValue;
  3984. var values = [];
  3985. var xIndex = -1;
  3986. var yIndex = -1;
  3987. var zIndex = -1;
  3988. times.forEach(function (time) {
  3989. if (curves.x) xIndex = curves.x.times.indexOf(time);
  3990. if (curves.y) yIndex = curves.y.times.indexOf(time);
  3991. if (curves.z) zIndex = curves.z.times.indexOf(time);
  3992. // if there is an x value defined for this frame, use that
  3993. if (xIndex !== -1) {
  3994. var xValue = curves.x.values[xIndex];
  3995. values.push(xValue);
  3996. prevValue[0] = xValue;
  3997. } else {
  3998. // otherwise use the x value from the previous frame
  3999. values.push(prevValue[0]);
  4000. }
  4001. if (yIndex !== -1) {
  4002. var yValue = curves.y.values[yIndex];
  4003. values.push(yValue);
  4004. prevValue[1] = yValue;
  4005. } else {
  4006. values.push(prevValue[1]);
  4007. }
  4008. if (zIndex !== -1) {
  4009. var zValue = curves.z.values[zIndex];
  4010. values.push(zValue);
  4011. prevValue[2] = zValue;
  4012. } else {
  4013. values.push(prevValue[2]);
  4014. }
  4015. });
  4016. return values;
  4017. },
  4018. // Rotations are defined as Euler angles which can have values of any size
  4019. // These will be converted to quaternions which don't support values greater than
  4020. // PI, so we'll interpolate large rotations
  4021. interpolateRotations: function interpolateRotations(curve) {
  4022. for (var i = 1; i < curve.values.length; i++) {
  4023. var initialValue = curve.values[i - 1];
  4024. var valuesSpan = curve.values[i] - initialValue;
  4025. var absoluteSpan = Math.abs(valuesSpan);
  4026. if (absoluteSpan >= 180) {
  4027. var numSubIntervals = absoluteSpan / 180;
  4028. var step = valuesSpan / numSubIntervals;
  4029. var nextValue = initialValue + step;
  4030. var initialTime = curve.times[i - 1];
  4031. var timeSpan = curve.times[i] - initialTime;
  4032. var interval = timeSpan / numSubIntervals;
  4033. var nextTime = initialTime + interval;
  4034. var interpolatedTimes = [];
  4035. var interpolatedValues = [];
  4036. while (nextTime < curve.times[i]) {
  4037. interpolatedTimes.push(nextTime);
  4038. nextTime += interval;
  4039. interpolatedValues.push(nextValue);
  4040. nextValue += step;
  4041. }
  4042. curve.times = inject(curve.times, i, interpolatedTimes);
  4043. curve.values = inject(curve.values, i, interpolatedValues);
  4044. }
  4045. }
  4046. }
  4047. };
  4048. // parse an FBX file in ASCII format
  4049. function TextParser() {}
  4050. TextParser.prototype = {
  4051. constructor: TextParser,
  4052. getPrevNode: function getPrevNode() {
  4053. return this.nodeStack[this.currentIndent - 2];
  4054. },
  4055. getCurrentNode: function getCurrentNode() {
  4056. return this.nodeStack[this.currentIndent - 1];
  4057. },
  4058. getCurrentProp: function getCurrentProp() {
  4059. return this.currentProp;
  4060. },
  4061. pushStack: function pushStack(node) {
  4062. this.nodeStack.push(node);
  4063. this.currentIndent += 1;
  4064. },
  4065. popStack: function popStack() {
  4066. this.nodeStack.pop();
  4067. this.currentIndent -= 1;
  4068. },
  4069. setCurrentProp: function setCurrentProp(val, name) {
  4070. this.currentProp = val;
  4071. this.currentPropName = name;
  4072. },
  4073. parse: function parse(text) {
  4074. this.currentIndent = 0;
  4075. console.log("FBXTree: ", FBXTree);
  4076. this.allNodes = new FBXTree();
  4077. this.nodeStack = [];
  4078. this.currentProp = [];
  4079. this.currentPropName = '';
  4080. var self = this;
  4081. var split = text.split(/[\r\n]+/);
  4082. split.forEach(function (line, i) {
  4083. var matchComment = line.match(/^[\s\t]*;/);
  4084. var matchEmpty = line.match(/^[\s\t]*$/);
  4085. if (matchComment || matchEmpty) return;
  4086. var matchBeginning = line.match('^\\t{' + self.currentIndent + '}(\\w+):(.*){', '');
  4087. var matchProperty = line.match('^\\t{' + self.currentIndent + '}(\\w+):[\\s\\t\\r\\n](.*)');
  4088. var matchEnd = line.match('^\\t{' + (self.currentIndent - 1) + '}}');
  4089. if (matchBeginning) {
  4090. self.parseNodeBegin(line, matchBeginning);
  4091. } else if (matchProperty) {
  4092. self.parseNodeProperty(line, matchProperty, split[++i]);
  4093. } else if (matchEnd) {
  4094. self.popStack();
  4095. } else if (line.match(/^[^\s\t}]/)) {
  4096. // large arrays are split over multiple lines terminated with a ',' character
  4097. // if this is encountered the line needs to be joined to the previous line
  4098. self.parseNodePropertyContinued(line);
  4099. }
  4100. });
  4101. return this.allNodes;
  4102. },
  4103. parseNodeBegin: function parseNodeBegin(line, property) {
  4104. var nodeName = property[1].trim().replace(/^"/, '').replace(/"$/, '');
  4105. var nodeAttrs = property[2].split(',').map(function (attr) {
  4106. return attr.trim().replace(/^"/, '').replace(/"$/, '');
  4107. });
  4108. var node = { name: nodeName };
  4109. var attrs = this.parseNodeAttr(nodeAttrs);
  4110. var currentNode = this.getCurrentNode();
  4111. // a top node
  4112. if (this.currentIndent === 0) {
  4113. this.allNodes.add(nodeName, node);
  4114. } else {
  4115. // a subnode
  4116. // if the subnode already exists, append it
  4117. if (nodeName in currentNode) {
  4118. // special case Pose needs PoseNodes as an array
  4119. if (nodeName === 'PoseNode') {
  4120. currentNode.PoseNode.push(node);
  4121. } else if (currentNode[nodeName].id !== undefined) {
  4122. currentNode[nodeName] = {};
  4123. currentNode[nodeName][currentNode[nodeName].id] = currentNode[nodeName];
  4124. }
  4125. if (attrs.id !== '') currentNode[nodeName][attrs.id] = node;
  4126. } else if (typeof attrs.id === 'number') {
  4127. currentNode[nodeName] = {};
  4128. currentNode[nodeName][attrs.id] = node;
  4129. } else if (nodeName !== 'Properties70') {
  4130. if (nodeName === 'PoseNode') currentNode[nodeName] = [node];else currentNode[nodeName] = node;
  4131. }
  4132. }
  4133. if (typeof attrs.id === 'number') node.id = attrs.id;
  4134. if (attrs.name !== '') node.attrName = attrs.name;
  4135. if (attrs.type !== '') node.attrType = attrs.type;
  4136. this.pushStack(node);
  4137. },
  4138. parseNodeAttr: function parseNodeAttr(attrs) {
  4139. var id = attrs[0];
  4140. if (attrs[0] !== '') {
  4141. id = parseInt(attrs[0]);
  4142. if (isNaN(id)) {
  4143. id = attrs[0];
  4144. }
  4145. }
  4146. var name = '',
  4147. type = '';
  4148. if (attrs.length > 1) {
  4149. name = attrs[1].replace(/^(\w+)::/, '');
  4150. type = attrs[2];
  4151. }
  4152. return { id: id, name: name, type: type };
  4153. },
  4154. parseNodeProperty: function parseNodeProperty(line, property, contentLine) {
  4155. var propName = property[1].replace(/^"/, '').replace(/"$/, '').trim();
  4156. var propValue = property[2].replace(/^"/, '').replace(/"$/, '').trim();
  4157. // for special case: base64 image data follows "Content: ," line
  4158. // Content: ,
  4159. // "/9j/4RDaRXhpZgAATU0A..."
  4160. if (propName === 'Content' && propValue === ',') {
  4161. propValue = contentLine.replace(/"/g, '').replace(/,$/, '').trim();
  4162. }
  4163. var currentNode = this.getCurrentNode();
  4164. var parentName = currentNode.name;
  4165. if (parentName === 'Properties70') {
  4166. this.parseNodeSpecialProperty(line, propName, propValue);
  4167. return;
  4168. }
  4169. // Connections
  4170. if (propName === 'C') {
  4171. var connProps = propValue.split(',').slice(1);
  4172. var from = parseInt(connProps[0]);
  4173. var to = parseInt(connProps[1]);
  4174. var rest = propValue.split(',').slice(3);
  4175. rest = rest.map(function (elem) {
  4176. return elem.trim().replace(/^"/, '');
  4177. });
  4178. propName = 'connections';
  4179. propValue = [from, to];
  4180. append(propValue, rest);
  4181. if (currentNode[propName] === undefined) {
  4182. currentNode[propName] = [];
  4183. }
  4184. }
  4185. // Node
  4186. if (propName === 'Node') currentNode.id = propValue;
  4187. // connections
  4188. if (propName in currentNode && Array.isArray(currentNode[propName])) {
  4189. currentNode[propName].push(propValue);
  4190. } else {
  4191. if (propName !== 'a') currentNode[propName] = propValue;else currentNode.a = propValue;
  4192. }
  4193. this.setCurrentProp(currentNode, propName);
  4194. // convert string to array, unless it ends in ',' in which case more will be added to it
  4195. if (propName === 'a' && propValue.slice(-1) !== ',') {
  4196. currentNode.a = parseNumberArray(propValue);
  4197. }
  4198. },
  4199. parseNodePropertyContinued: function parseNodePropertyContinued(line) {
  4200. var currentNode = this.getCurrentNode();
  4201. currentNode.a += line;
  4202. // if the line doesn't end in ',' we have reached the end of the property value
  4203. // so convert the string to an array
  4204. if (line.slice(-1) !== ',') {
  4205. currentNode.a = parseNumberArray(currentNode.a);
  4206. }
  4207. },
  4208. // parse "Property70"
  4209. parseNodeSpecialProperty: function parseNodeSpecialProperty(line, propName, propValue) {
  4210. // split this
  4211. // P: "Lcl Scaling", "Lcl Scaling", "", "A",1,1,1
  4212. // into array like below
  4213. // ["Lcl Scaling", "Lcl Scaling", "", "A", "1,1,1" ]
  4214. var props = propValue.split('",').map(function (prop) {
  4215. return prop.trim().replace(/^\"/, '').replace(/\s/, '_');
  4216. });
  4217. var innerPropName = props[0];
  4218. var innerPropType1 = props[1];
  4219. var innerPropType2 = props[2];
  4220. var innerPropFlag = props[3];
  4221. var innerPropValue = props[4];
  4222. // cast values where needed, otherwise leave as strings
  4223. switch (innerPropType1) {
  4224. case 'int':
  4225. case 'enum':
  4226. case 'bool':
  4227. case 'ULongLong':
  4228. case 'double':
  4229. case 'Number':
  4230. case 'FieldOfView':
  4231. innerPropValue = parseFloat(innerPropValue);
  4232. break;
  4233. case 'Color':
  4234. case 'ColorRGB':
  4235. case 'Vector3D':
  4236. case 'Lcl_Translation':
  4237. case 'Lcl_Rotation':
  4238. case 'Lcl_Scaling':
  4239. innerPropValue = parseNumberArray(innerPropValue);
  4240. break;
  4241. }
  4242. // CAUTION: these props must append to parent's parent
  4243. this.getPrevNode()[innerPropName] = {
  4244. 'type': innerPropType1,
  4245. 'type2': innerPropType2,
  4246. 'flag': innerPropFlag,
  4247. 'value': innerPropValue
  4248. };
  4249. this.setCurrentProp(this.getPrevNode(), innerPropName);
  4250. }
  4251. };
  4252. // Parse an FBX file in Binary format
  4253. function BinaryParser() {}
  4254. BinaryParser.prototype = {
  4255. constructor: BinaryParser,
  4256. parse: function parse(buffer) {
  4257. var reader = new BinaryReader(buffer);
  4258. reader.skip(23); // skip magic 23 bytes
  4259. var version = reader.getUint32();
  4260. console.log('THREE.FBXLoader: FBX binary version: ' + version);
  4261. var allNodes = new FBXTree();
  4262. while (!this.endOfContent(reader)) {
  4263. var node = this.parseNode(reader, version);
  4264. if (node !== null) allNodes.add(node.name, node);
  4265. }
  4266. return allNodes;
  4267. },
  4268. // Check if reader has reached the end of content.
  4269. endOfContent: function endOfContent(reader) {
  4270. // footer size: 160bytes + 16-byte alignment padding
  4271. // - 16bytes: magic
  4272. // - padding til 16-byte alignment (at least 1byte?)
  4273. // (seems like some exporters embed fixed 15 or 16bytes?)
  4274. // - 4bytes: magic
  4275. // - 4bytes: version
  4276. // - 120bytes: zero
  4277. // - 16bytes: magic
  4278. if (reader.size() % 16 === 0) {
  4279. return (reader.getOffset() + 160 + 16 & ~0xf) >= reader.size();
  4280. } else {
  4281. return reader.getOffset() + 160 + 16 >= reader.size();
  4282. }
  4283. },
  4284. // recursively parse nodes until the end of the file is reached
  4285. parseNode: function parseNode(reader, version) {
  4286. var node = {};
  4287. // The first three data sizes depends on version.
  4288. var endOffset = version >= 7500 ? reader.getUint64() : reader.getUint32();
  4289. var numProperties = version >= 7500 ? reader.getUint64() : reader.getUint32();
  4290. // note: do not remove this even if you get a linter warning as it moves the buffer forward
  4291. var propertyListLen = version >= 7500 ? reader.getUint64() : reader.getUint32();
  4292. var nameLen = reader.getUint8();
  4293. var name = reader.getString(nameLen);
  4294. // Regards this node as NULL-record if endOffset is zero
  4295. if (endOffset === 0) return null;
  4296. var propertyList = [];
  4297. for (var i = 0; i < numProperties; i++) {
  4298. propertyList.push(this.parseProperty(reader));
  4299. }
  4300. // Regards the first three elements in propertyList as id, attrName, and attrType
  4301. var id = propertyList.length > 0 ? propertyList[0] : '';
  4302. var attrName = propertyList.length > 1 ? propertyList[1] : '';
  4303. var attrType = propertyList.length > 2 ? propertyList[2] : '';
  4304. // check if this node represents just a single property
  4305. // like (name, 0) set or (name2, [0, 1, 2]) set of {name: 0, name2: [0, 1, 2]}
  4306. node.singleProperty = numProperties === 1 && reader.getOffset() === endOffset ? true : false;
  4307. while (endOffset > reader.getOffset()) {
  4308. var subNode = this.parseNode(reader, version);
  4309. if (subNode !== null) this.parseSubNode(name, node, subNode);
  4310. }
  4311. node.propertyList = propertyList; // raw property list used by parent
  4312. if (typeof id === 'number') node.id = id;
  4313. if (attrName !== '') node.attrName = attrName;
  4314. if (attrType !== '') node.attrType = attrType;
  4315. if (name !== '') node.name = name;
  4316. return node;
  4317. },
  4318. parseSubNode: function parseSubNode(name, node, subNode) {
  4319. // special case: child node is single property
  4320. if (subNode.singleProperty === true) {
  4321. var value = subNode.propertyList[0];
  4322. if (Array.isArray(value)) {
  4323. node[subNode.name] = subNode;
  4324. subNode.a = value;
  4325. } else {
  4326. node[subNode.name] = value;
  4327. }
  4328. } else if (name === 'Connections' && subNode.name === 'C') {
  4329. var array = [];
  4330. subNode.propertyList.forEach(function (property, i) {
  4331. // first Connection is FBX type (OO, OP, etc.). We'll discard these
  4332. if (i !== 0) array.push(property);
  4333. });
  4334. if (node.connections === undefined) {
  4335. node.connections = [];
  4336. }
  4337. node.connections.push(array);
  4338. } else if (subNode.name === 'Properties70') {
  4339. var keys = Object.keys(subNode);
  4340. keys.forEach(function (key) {
  4341. node[key] = subNode[key];
  4342. });
  4343. } else if (name === 'Properties70' && subNode.name === 'P') {
  4344. var innerPropName = subNode.propertyList[0];
  4345. var innerPropType1 = subNode.propertyList[1];
  4346. var innerPropType2 = subNode.propertyList[2];
  4347. var innerPropFlag = subNode.propertyList[3];
  4348. var innerPropValue;
  4349. if (innerPropName.indexOf('Lcl ') === 0) innerPropName = innerPropName.replace('Lcl ', 'Lcl_');
  4350. if (innerPropType1.indexOf('Lcl ') === 0) innerPropType1 = innerPropType1.replace('Lcl ', 'Lcl_');
  4351. if (innerPropType1 === 'Color' || innerPropType1 === 'ColorRGB' || innerPropType1 === 'Vector' || innerPropType1 === 'Vector3D' || innerPropType1.indexOf('Lcl_') === 0) {
  4352. innerPropValue = [subNode.propertyList[4], subNode.propertyList[5], subNode.propertyList[6]];
  4353. } else {
  4354. innerPropValue = subNode.propertyList[4];
  4355. }
  4356. // this will be copied to parent, see above
  4357. node[innerPropName] = {
  4358. 'type': innerPropType1,
  4359. 'type2': innerPropType2,
  4360. 'flag': innerPropFlag,
  4361. 'value': innerPropValue
  4362. };
  4363. } else if (node[subNode.name] === undefined) {
  4364. if (typeof subNode.id === 'number') {
  4365. node[subNode.name] = {};
  4366. node[subNode.name][subNode.id] = subNode;
  4367. } else {
  4368. node[subNode.name] = subNode;
  4369. }
  4370. } else {
  4371. if (subNode.name === 'PoseNode') {
  4372. if (!Array.isArray(node[subNode.name])) {
  4373. node[subNode.name] = [node[subNode.name]];
  4374. }
  4375. node[subNode.name].push(subNode);
  4376. } else if (node[subNode.name][subNode.id] === undefined) {
  4377. node[subNode.name][subNode.id] = subNode;
  4378. }
  4379. }
  4380. },
  4381. parseProperty: function parseProperty(reader) {
  4382. var type = reader.getString(1);
  4383. switch (type) {
  4384. case 'C':
  4385. return reader.getBoolean();
  4386. case 'D':
  4387. return reader.getFloat64();
  4388. case 'F':
  4389. return reader.getFloat32();
  4390. case 'I':
  4391. return reader.getInt32();
  4392. case 'L':
  4393. return reader.getInt64();
  4394. case 'R':
  4395. var length = reader.getUint32();
  4396. return reader.getArrayBuffer(length);
  4397. case 'S':
  4398. var length = reader.getUint32();
  4399. return reader.getString(length);
  4400. case 'Y':
  4401. return reader.getInt16();
  4402. case 'b':
  4403. case 'c':
  4404. case 'd':
  4405. case 'f':
  4406. case 'i':
  4407. case 'l':
  4408. var arrayLength = reader.getUint32();
  4409. var encoding = reader.getUint32(); // 0: non-compressed, 1: compressed
  4410. var compressedLength = reader.getUint32();
  4411. if (encoding === 0) {
  4412. switch (type) {
  4413. case 'b':
  4414. case 'c':
  4415. return reader.getBooleanArray(arrayLength);
  4416. case 'd':
  4417. return reader.getFloat64Array(arrayLength);
  4418. case 'f':
  4419. return reader.getFloat32Array(arrayLength);
  4420. case 'i':
  4421. return reader.getInt32Array(arrayLength);
  4422. case 'l':
  4423. return reader.getInt64Array(arrayLength);
  4424. }
  4425. }
  4426. if (typeof Zlib === 'undefined') {
  4427. console.error('THREE.FBXLoader: External library Inflate.min.js required, obtain or import from https://github.com/imaya/zlib.js');
  4428. }
  4429. var inflate = new Zlib.Inflate(new Uint8Array(reader.getArrayBuffer(compressedLength))); // eslint-disable-line no-undef
  4430. var reader2 = new BinaryReader(inflate.decompress().buffer);
  4431. switch (type) {
  4432. case 'b':
  4433. case 'c':
  4434. return reader2.getBooleanArray(arrayLength);
  4435. case 'd':
  4436. return reader2.getFloat64Array(arrayLength);
  4437. case 'f':
  4438. return reader2.getFloat32Array(arrayLength);
  4439. case 'i':
  4440. return reader2.getInt32Array(arrayLength);
  4441. case 'l':
  4442. return reader2.getInt64Array(arrayLength);
  4443. }
  4444. default:
  4445. throw new Error('THREE.FBXLoader: Unknown property type ' + type);
  4446. }
  4447. }
  4448. };
  4449. function BinaryReader(buffer, littleEndian) {
  4450. this.dv = new DataView(buffer);
  4451. this.offset = 0;
  4452. this.littleEndian = littleEndian !== undefined ? littleEndian : true;
  4453. }
  4454. BinaryReader.prototype = {
  4455. constructor: BinaryReader,
  4456. getOffset: function getOffset() {
  4457. return this.offset;
  4458. },
  4459. size: function size() {
  4460. return this.dv.buffer.byteLength;
  4461. },
  4462. skip: function skip(length) {
  4463. this.offset += length;
  4464. },
  4465. // seems like true/false representation depends on exporter.
  4466. // true: 1 or 'Y'(=0x59), false: 0 or 'T'(=0x54)
  4467. // then sees LSB.
  4468. getBoolean: function getBoolean() {
  4469. return (this.getUint8() & 1) === 1;
  4470. },
  4471. getBooleanArray: function getBooleanArray(size) {
  4472. var a = [];
  4473. for (var i = 0; i < size; i++) {
  4474. a.push(this.getBoolean());
  4475. }
  4476. return a;
  4477. },
  4478. getUint8: function getUint8() {
  4479. var value = this.dv.getUint8(this.offset);
  4480. this.offset += 1;
  4481. return value;
  4482. },
  4483. getInt16: function getInt16() {
  4484. var value = this.dv.getInt16(this.offset, this.littleEndian);
  4485. this.offset += 2;
  4486. return value;
  4487. },
  4488. getInt32: function getInt32() {
  4489. var value = this.dv.getInt32(this.offset, this.littleEndian);
  4490. this.offset += 4;
  4491. return value;
  4492. },
  4493. getInt32Array: function getInt32Array(size) {
  4494. var a = [];
  4495. for (var i = 0; i < size; i++) {
  4496. a.push(this.getInt32());
  4497. }
  4498. return a;
  4499. },
  4500. getUint32: function getUint32() {
  4501. var value = this.dv.getUint32(this.offset, this.littleEndian);
  4502. this.offset += 4;
  4503. return value;
  4504. },
  4505. // JavaScript doesn't support 64-bit integer so calculate this here
  4506. // 1 << 32 will return 1 so using multiply operation instead here.
  4507. // There's a possibility that this method returns wrong value if the value
  4508. // is out of the range between Number.MAX_SAFE_INTEGER and Number.MIN_SAFE_INTEGER.
  4509. // TODO: safely handle 64-bit integer
  4510. getInt64: function getInt64() {
  4511. var low, high;
  4512. if (this.littleEndian) {
  4513. low = this.getUint32();
  4514. high = this.getUint32();
  4515. } else {
  4516. high = this.getUint32();
  4517. low = this.getUint32();
  4518. }
  4519. // calculate negative value
  4520. if (high & 0x80000000) {
  4521. high = ~high & 0xFFFFFFFF;
  4522. low = ~low & 0xFFFFFFFF;
  4523. if (low === 0xFFFFFFFF) high = high + 1 & 0xFFFFFFFF;
  4524. low = low + 1 & 0xFFFFFFFF;
  4525. return -(high * 0x100000000 + low);
  4526. }
  4527. return high * 0x100000000 + low;
  4528. },
  4529. getInt64Array: function getInt64Array(size) {
  4530. var a = [];
  4531. for (var i = 0; i < size; i++) {
  4532. a.push(this.getInt64());
  4533. }
  4534. return a;
  4535. },
  4536. // Note: see getInt64() comment
  4537. getUint64: function getUint64() {
  4538. var low, high;
  4539. if (this.littleEndian) {
  4540. low = this.getUint32();
  4541. high = this.getUint32();
  4542. } else {
  4543. high = this.getUint32();
  4544. low = this.getUint32();
  4545. }
  4546. return high * 0x100000000 + low;
  4547. },
  4548. getFloat32: function getFloat32() {
  4549. var value = this.dv.getFloat32(this.offset, this.littleEndian);
  4550. this.offset += 4;
  4551. return value;
  4552. },
  4553. getFloat32Array: function getFloat32Array(size) {
  4554. var a = [];
  4555. for (var i = 0; i < size; i++) {
  4556. a.push(this.getFloat32());
  4557. }
  4558. return a;
  4559. },
  4560. getFloat64: function getFloat64() {
  4561. var value = this.dv.getFloat64(this.offset, this.littleEndian);
  4562. this.offset += 8;
  4563. return value;
  4564. },
  4565. getFloat64Array: function getFloat64Array(size) {
  4566. var a = [];
  4567. for (var i = 0; i < size; i++) {
  4568. a.push(this.getFloat64());
  4569. }
  4570. return a;
  4571. },
  4572. getArrayBuffer: function getArrayBuffer(size) {
  4573. var value = this.dv.buffer.slice(this.offset, this.offset + size);
  4574. this.offset += size;
  4575. return value;
  4576. },
  4577. getString: function getString(size) {
  4578. // note: safari 9 doesn't support Uint8Array.indexOf; create intermediate array instead
  4579. var a = [];
  4580. for (var i = 0; i < size; i++) {
  4581. a[i] = this.getUint8();
  4582. }
  4583. var nullByte = a.indexOf(0);
  4584. if (nullByte >= 0) a = a.slice(0, nullByte);
  4585. return THREE.LoaderUtils.decodeText(new Uint8Array(a));
  4586. }
  4587. };
  4588. // FBXTree holds a representation of the FBX data, returned by the TextParser ( FBX ASCII format)
  4589. // and BinaryParser( FBX Binary format)
  4590. function FBXTree() {}
  4591. FBXTree.prototype = {
  4592. constructor: FBXTree,
  4593. add: function add(key, val) {
  4594. this[key] = val;
  4595. }
  4596. };
  4597. // ************** UTILITY FUNCTIONS **************
  4598. function isFbxFormatBinary(buffer) {
  4599. var CORRECT = 'Kaydara FBX Binary \0';
  4600. return buffer.byteLength >= CORRECT.length && CORRECT === convertArrayBufferToString(buffer, 0, CORRECT.length);
  4601. }
  4602. function isFbxFormatASCII(text) {
  4603. var CORRECT = ['K', 'a', 'y', 'd', 'a', 'r', 'a', '\\', 'F', 'B', 'X', '\\', 'B', 'i', 'n', 'a', 'r', 'y', '\\', '\\'];
  4604. var cursor = 0;
  4605. function read(offset) {
  4606. var result = text[offset - 1];
  4607. text = text.slice(cursor + offset);
  4608. cursor++;
  4609. return result;
  4610. }
  4611. for (var i = 0; i < CORRECT.length; ++i) {
  4612. var num = read(1);
  4613. if (num === CORRECT[i]) {
  4614. return false;
  4615. }
  4616. }
  4617. return true;
  4618. }
  4619. function getFbxVersion(text) {
  4620. var versionRegExp = /FBXVersion: (\d+)/;
  4621. var match = text.match(versionRegExp);
  4622. if (match) {
  4623. var version = parseInt(match[1]);
  4624. return version;
  4625. }
  4626. throw new Error('THREE.FBXLoader: Cannot find the version number for the file given.');
  4627. }
  4628. // Converts FBX ticks into real time seconds.
  4629. function convertFBXTimeToSeconds(time) {
  4630. return time / 46186158000;
  4631. }
  4632. var dataArray = [];
  4633. // extracts the data from the correct position in the FBX array based on indexing type
  4634. function getData(polygonVertexIndex, polygonIndex, vertexIndex, infoObject) {
  4635. var index;
  4636. switch (infoObject.mappingType) {
  4637. case 'ByPolygonVertex':
  4638. index = polygonVertexIndex;
  4639. break;
  4640. case 'ByPolygon':
  4641. index = polygonIndex;
  4642. break;
  4643. case 'ByVertice':
  4644. index = vertexIndex;
  4645. break;
  4646. case 'AllSame':
  4647. index = infoObject.indices[0];
  4648. break;
  4649. default:
  4650. console.warn('THREE.FBXLoader: unknown attribute mapping type ' + infoObject.mappingType);
  4651. }
  4652. if (infoObject.referenceType === 'IndexToDirect') index = infoObject.indices[index];
  4653. var from = index * infoObject.dataSize;
  4654. var to = from + infoObject.dataSize;
  4655. return slice(dataArray, infoObject.buffer, from, to);
  4656. }
  4657. var tempMat = new THREE.Matrix4();
  4658. var tempEuler = new THREE.Euler();
  4659. var tempVec = new THREE.Vector3();
  4660. var translation = new THREE.Vector3();
  4661. var rotation = new THREE.Matrix4();
  4662. // generate transformation from FBX transform data
  4663. // ref: https://help.autodesk.com/view/FBX/2017/ENU/?guid=__files_GUID_10CDD63C_79C1_4F2D_BB28_AD2BE65A02ED_htm
  4664. // transformData = {
  4665. // eulerOrder: int,
  4666. // translation: [],
  4667. // rotationOffset: [],
  4668. // preRotation
  4669. // rotation
  4670. // postRotation
  4671. // scale
  4672. // }
  4673. // all entries are optional
  4674. function generateTransform(transformData) {
  4675. var transform = new THREE.Matrix4();
  4676. translation.set(0, 0, 0);
  4677. rotation.identity();
  4678. var order = transformData.eulerOrder ? getEulerOrder(transformData.eulerOrder) : getEulerOrder(0);
  4679. if (transformData.translation) translation.fromArray(transformData.translation);
  4680. if (transformData.rotationOffset) translation.add(tempVec.fromArray(transformData.rotationOffset));
  4681. if (transformData.rotation) {
  4682. var array = transformData.rotation.map(THREE.Math.degToRad);
  4683. array.push(order);
  4684. rotation.makeRotationFromEuler(tempEuler.fromArray(array));
  4685. }
  4686. if (transformData.preRotation) {
  4687. var array = transformData.preRotation.map(THREE.Math.degToRad);
  4688. array.push(order);
  4689. tempMat.makeRotationFromEuler(tempEuler.fromArray(array));
  4690. rotation.premultiply(tempMat);
  4691. }
  4692. if (transformData.postRotation) {
  4693. var array = transformData.postRotation.map(THREE.Math.degToRad);
  4694. array.push(order);
  4695. tempMat.makeRotationFromEuler(tempEuler.fromArray(array));
  4696. tempMat.getInverse(tempMat);
  4697. rotation.multiply(tempMat);
  4698. }
  4699. if (transformData.scale) transform.scale(tempVec.fromArray(transformData.scale));
  4700. transform.setPosition(translation);
  4701. transform.multiply(rotation);
  4702. return transform;
  4703. }
  4704. // Returns the three.js intrinsic Euler order corresponding to FBX extrinsic Euler order
  4705. // ref: http://help.autodesk.com/view/FBX/2017/ENU/?guid=__cpp_ref_class_fbx_euler_html
  4706. function getEulerOrder(order) {
  4707. var enums = ['ZYX', // -> XYZ extrinsic
  4708. 'YZX', // -> XZY extrinsic
  4709. 'XZY', // -> YZX extrinsic
  4710. 'ZXY', // -> YXZ extrinsic
  4711. 'YXZ', // -> ZXY extrinsic
  4712. 'XYZ'];
  4713. if (order === 6) {
  4714. console.warn('THREE.FBXLoader: unsupported Euler Order: Spherical XYZ. Animations and rotations may be incorrect.');
  4715. return enums[0];
  4716. }
  4717. return enums[order];
  4718. }
  4719. // Parses comma separated list of numbers and returns them an array.
  4720. // Used internally by the TextParser
  4721. function parseNumberArray(value) {
  4722. var array = value.split(',').map(function (val) {
  4723. return parseFloat(val);
  4724. });
  4725. return array;
  4726. }
  4727. function convertArrayBufferToString(buffer, from, to) {
  4728. if (from === undefined) from = 0;
  4729. if (to === undefined) to = buffer.byteLength;
  4730. return THREE.LoaderUtils.decodeText(new Uint8Array(buffer, from, to));
  4731. }
  4732. function append(a, b) {
  4733. for (var i = 0, j = a.length, l = b.length; i < l; i++, j++) {
  4734. a[j] = b[i];
  4735. }
  4736. }
  4737. function slice(a, b, from, to) {
  4738. for (var i = from, j = 0; i < to; i++, j++) {
  4739. a[j] = b[i];
  4740. }
  4741. return a;
  4742. }
  4743. // inject array a2 into array a1 at index
  4744. function inject(a1, index, a2) {
  4745. return a1.slice(0, index).concat(a2).concat(a1.slice(index));
  4746. }
  4747. return FBXLoader;
  4748. }();
  4749. },{}],5:[function(require,module,exports){
  4750. "use strict";
  4751. module.exports = Object.assign(function GamepadButton() {}, {
  4752. FACE_1: 0,
  4753. FACE_2: 1,
  4754. FACE_3: 2,
  4755. FACE_4: 3,
  4756. L_SHOULDER_1: 4,
  4757. R_SHOULDER_1: 5,
  4758. L_SHOULDER_2: 6,
  4759. R_SHOULDER_2: 7,
  4760. SELECT: 8,
  4761. START: 9,
  4762. DPAD_UP: 12,
  4763. DPAD_DOWN: 13,
  4764. DPAD_LEFT: 14,
  4765. DPAD_RIGHT: 15,
  4766. VENDOR: 16
  4767. });
  4768. },{}],6:[function(require,module,exports){
  4769. "use strict";
  4770. function GamepadButtonEvent(type, index, details) {
  4771. this.type = type;
  4772. this.index = index;
  4773. this.pressed = details.pressed;
  4774. this.value = details.value;
  4775. }
  4776. module.exports = GamepadButtonEvent;
  4777. },{}],7:[function(require,module,exports){
  4778. "use strict";
  4779. module.exports = {
  4780. "size": 5,
  4781. "cellSize": 10,
  4782. "extrudeSettings": {
  4783. "amount": 1,
  4784. "bevelEnabled": true,
  4785. "bevelSegments": 1,
  4786. "steps": 1,
  4787. "bevelSize": 0.5,
  4788. "bevelThickness": 0.5
  4789. },
  4790. "autogenerated": true,
  4791. "cells": [{
  4792. "q": -1,
  4793. "r": 0,
  4794. "s": 1,
  4795. "h": 1,
  4796. "walkable": true,
  4797. "userData": {}
  4798. }, {
  4799. "q": 0,
  4800. "r": -1,
  4801. "s": 1,
  4802. "h": 1,
  4803. "walkable": true,
  4804. "userData": {}
  4805. }, {
  4806. "q": 0,
  4807. "r": 0,
  4808. "s": 0,
  4809. "h": 1,
  4810. "walkable": true,
  4811. "userData": {}
  4812. }, {
  4813. "q": 1,
  4814. "r": -1,
  4815. "s": 0,
  4816. "h": 1,
  4817. "walkable": true,
  4818. "userData": {}
  4819. }, {
  4820. "q": -1,
  4821. "r": 1,
  4822. "s": 0,
  4823. "h": 0,
  4824. "walkable": true,
  4825. "userData": {}
  4826. }, {
  4827. "q": 0,
  4828. "r": 1,
  4829. "s": -1,
  4830. "h": 0,
  4831. "walkable": true,
  4832. "userData": {}
  4833. }, {
  4834. "q": 1,
  4835. "r": 0,
  4836. "s": -1,
  4837. "h": 0,
  4838. "walkable": true,
  4839. "userData": {}
  4840. }]
  4841. };
  4842. },{}],8:[function(require,module,exports){
  4843. 'use strict';
  4844. /**
  4845. * Source: https://github.com/Adobe-Marketing-Cloud/fetch-script
  4846. */
  4847. function getScriptId() {
  4848. return 'script_' + Date.now() + '_' + Math.ceil(Math.random() * 100000);
  4849. }
  4850. function createScript(url, id) {
  4851. var script = document.createElement('script');
  4852. script.type = 'text/javascript';
  4853. script.async = true;
  4854. script.id = id;
  4855. script.src = url;
  4856. return script;
  4857. }
  4858. function removeScript(id) {
  4859. var script = document.getElementById(id);
  4860. var parent = script.parentNode;
  4861. try {
  4862. parent && parent.removeChild(script);
  4863. } catch (e) {
  4864. // ignore
  4865. }
  4866. }
  4867. function appendScript(script) {
  4868. var firstScript = document.getElementsByTagName('script')[0];
  4869. firstScript.parentNode.insertBefore(script, firstScript);
  4870. }
  4871. function fetchScriptInternal(url, options, Promise) {
  4872. return new Promise(function (resolve, reject) {
  4873. var timeout = options.timeout || 5000;
  4874. var scriptId = getScriptId();
  4875. var script = createScript(url, scriptId);
  4876. var timeoutId = setTimeout(function () {
  4877. reject(new Error('Script request to ' + url + ' timed out'));
  4878. removeScript(scriptId);
  4879. }, timeout);
  4880. var disableTimeout = function disableTimeout(timeoutId) {
  4881. clearTimeout(timeoutId);
  4882. };
  4883. script.addEventListener('load', function (e) {
  4884. resolve({ ok: true });
  4885. disableTimeout(timeoutId);
  4886. removeScript(scriptId);
  4887. });
  4888. script.addEventListener('error', function (e) {
  4889. reject(new Error('Script request to ' + url + ' failed ' + e));
  4890. disableTimeout(timeoutId);
  4891. removeScript(scriptId);
  4892. });
  4893. appendScript(script);
  4894. });
  4895. }
  4896. function fetchScript(settings) {
  4897. settings = settings || {};
  4898. return function (url, options) {
  4899. options = options || {};
  4900. return fetchScriptInternal(url, options, settings.Promise || Promise);
  4901. };
  4902. }
  4903. module.exports = fetchScript;
  4904. },{}],9:[function(require,module,exports){
  4905. "use strict";
  4906. 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; };
  4907. var _typeof = typeof Symbol === "function" && _typeof2(Symbol.iterator) === "symbol" ? function (obj) {
  4908. return typeof obj === "undefined" ? "undefined" : _typeof2(obj);
  4909. } : function (obj) {
  4910. return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj === "undefined" ? "undefined" : _typeof2(obj);
  4911. };
  4912. 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) {
  4913. 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);
  4914. }, vg.Board.prototype = { setEntityOnTile: function setEntityOnTile(e, t) {
  4915. 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;
  4916. }, addTile: function addTile(e) {
  4917. 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);
  4918. }, removeTile: function removeTile(e) {
  4919. if (e) {
  4920. var t = this.tiles.indexOf(e);this.grid.remove(e.cell), -1 !== t && this.tiles.splice(t, 1), e.dispose();
  4921. }
  4922. }, removeAllTiles: function removeAllTiles() {
  4923. if (this.tileGroup) for (var e = this.tileGroup.children, t = 0; t < e.length; t++) {
  4924. this.tileGroup.remove(e[t]);
  4925. }
  4926. }, getTileAtCell: function getTileAtCell(e) {
  4927. var t = this.grid.cellToHash(e);return e.tile || ("undefined" != typeof this.grid.cells[t] ? this.grid.cells[t].tile : null);
  4928. }, snapToGrid: function snapToGrid(e) {
  4929. var t = this.grid.pixelToCell(e);e.copy(this.grid.cellToPixel(t));
  4930. }, snapTileToGrid: function snapTileToGrid(e) {
  4931. if (e.cell) e.position.copy(this.grid.cellToPixel(e.cell));else {
  4932. var t = this.grid.pixelToCell(e.position);e.position.copy(this.grid.cellToPixel(t));
  4933. }return e;
  4934. }, getRandomTile: function getRandomTile() {
  4935. var e = vg.Tools.randomInt(0, this.tiles.length - 1);return this.tiles[e];
  4936. }, findPath: function findPath(e, t, i) {
  4937. return this.finder.findPath(e.cell, t.cell, i, this.grid);
  4938. }, setGrid: function setGrid(e) {
  4939. this.group.remove(this.tileGroup), this.grid && e !== this.grid && (this.removeAllTiles(), this.tiles.forEach(function (e) {
  4940. this.grid.remove(e.cell), e.dispose();
  4941. }), this.grid.dispose()), this.grid = e, this.tiles = [], this.tileGroup = new THREE.Object3D(), this.group.add(this.tileGroup);
  4942. }, generateOverlay: function generateOverlay(e) {
  4943. 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);
  4944. }, generateTilemap: function generateTilemap(e) {
  4945. this.reset();var t = this.grid.generateTiles(e);this.tiles = t, this.tileGroup = new THREE.Object3D();for (var i = 0; i < t.length; i++) {
  4946. this.tileGroup.add(t[i].mesh);
  4947. }this.group.add(this.tileGroup);
  4948. }, reset: function reset() {
  4949. this.removeAllTiles(), this.tileGroup && this.group.remove(this.tileGroup);
  4950. } }, vg.Board.prototype.constructor = vg.Board, vg.Cell = function (e, t, i, s) {
  4951. 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();
  4952. }, vg.Cell.prototype = { set: function set(e, t, i) {
  4953. return this.q = e, this.r = t, this.s = i, this;
  4954. }, copy: function copy(e) {
  4955. 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;
  4956. }, add: function add(e) {
  4957. return this.q += e.q, this.r += e.r, this.s += e.s, this;
  4958. }, equals: function equals(e) {
  4959. return this.q === e.q && this.r === e.r && this.s === e.s;
  4960. } }, vg.Cell.prototype.constructor = vg.Cell, vg.HexGrid = function (e) {
  4961. 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,
  4962. i = [];for (t = 0; 6 > t; t++) {
  4963. i.push(this._createVertex(t));
  4964. }for (this.cellShape = new THREE.Shape(), this.cellShape.moveTo(i[0].x, i[0].y), t = 1; 6 > t; t++) {
  4965. this.cellShape.lineTo(i[t].x, i[t].y);
  4966. }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 = [];
  4967. }, vg.HexGrid.TWO_THIRDS = 2 / 3, vg.HexGrid.prototype = { cellToPixel: function cellToPixel(e) {
  4968. 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;
  4969. }, pixelToCell: function pixelToCell(e) {
  4970. var t = e.x * (vg.HexGrid.TWO_THIRDS / this.cellSize),
  4971. i = (-e.x / 3 + vg.SQRT3 / 3 * e.z) / this.cellSize;return this._cel.set(t, i, -t - i), this._cubeRound(this._cel);
  4972. }, getCellAt: function getCellAt(e) {
  4973. var t = e.x * (vg.HexGrid.TWO_THIRDS / this.cellSize),
  4974. 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)];
  4975. }, getNeighbors: function getNeighbors(e, t, i) {
  4976. var s,
  4977. n,
  4978. l = this._directions.length;for (this._list.length = 0, s = 0; l > s; s++) {
  4979. 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);
  4980. }if (t) for (s = 0; l > s; s++) {
  4981. 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);
  4982. }return this._list;
  4983. }, getRandomCell: function getRandomCell() {
  4984. var e,
  4985. t = 0,
  4986. i = vg.Tools.randomInt(0, this.numCells);for (e in this.cells) {
  4987. if (t === i) return this.cells[e];t++;
  4988. }return this.cells[e];
  4989. }, cellToHash: function cellToHash(e) {
  4990. return e.q + this._hashDelimeter + e.r + this._hashDelimeter + e.s;
  4991. }, distance: function distance(e, t) {
  4992. 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;
  4993. }, clearPath: function clearPath() {
  4994. var e, t;for (e in this.cells) {
  4995. t = this.cells[e], t._calcCost = 0, t._priority = 0, t._parent = null, t._visited = !1;
  4996. }
  4997. }, traverse: function traverse(e) {
  4998. var t;for (t in this.cells) {
  4999. e(this.cells[t]);
  5000. }
  5001. }, generateTile: function generateTile(e, t, i) {
  5002. 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;
  5003. }, generateTiles: function generateTiles(e) {
  5004. e = e || {};var t = [],
  5005. 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) {
  5006. 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);
  5007. }return t;
  5008. }, generateTilePoly: function generateTilePoly(e) {
  5009. 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;
  5010. }, generate: function generate(e) {
  5011. 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++) {
  5012. for (i = -this.size; i < this.size + 1; i++) {
  5013. 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));
  5014. }
  5015. }
  5016. }, generateOverlay: function generateOverlay(e, t, i) {
  5017. var s,
  5018. n,
  5019. l,
  5020. r = this.cellShape.createPointsGeometry();for (s = -e; e + 1 > s; s++) {
  5021. for (n = -e; e + 1 > n; n++) {
  5022. if (l = -s - n, Math.abs(s) <= e && Math.abs(n) <= e && Math.abs(l) <= e) {
  5023. 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);
  5024. }
  5025. }
  5026. }
  5027. }, add: function add(e) {
  5028. var t = this.cellToHash(e);if (!this.cells[t]) return this.cells[t] = e, this.numCells++, e;
  5029. }, remove: function remove(e) {
  5030. var t = this.cellToHash(e);this.cells[t] && (delete this.cells[t], this.numCells--);
  5031. }, dispose: function dispose() {
  5032. 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;
  5033. }, load: function load(e, t, i) {
  5034. var s = this;vg.Tools.getJSON({ url: e, callback: function callback(e) {
  5035. s.fromJSON(e), t.call(i || null, e);
  5036. }, cache: !1, scope: s });
  5037. }, fromJSON: function fromJSON(e) {
  5038. var t,
  5039. i,
  5040. 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++) {
  5041. i = new vg.Cell(), i.copy(s[t]), this.add(i);
  5042. }
  5043. }, toJSON: function toJSON() {
  5044. var e,
  5045. t,
  5046. i = { size: this.size, cellSize: this.cellSize, extrudeSettings: this.extrudeSettings, autogenerated: this.autogenerated },
  5047. s = [];for (t in this.cells) {
  5048. e = this.cells[t], s.push({ q: e.q, r: e.r, s: e.s, h: e.h, walkable: e.walkable, userData: e.userData });
  5049. }return i.cells = s, i;
  5050. }, _createVertex: function _createVertex(e) {
  5051. var t = vg.TAU / 6 * e;return new THREE.Vector3(this.cellSize * Math.cos(t), this.cellSize * Math.sin(t), 0);
  5052. }, _cubeRound: function _cubeRound(e) {
  5053. var t = Math.round(e.q),
  5054. i = Math.round(e.r),
  5055. s = Math.round(e.s),
  5056. n = Math.abs(t - e.q),
  5057. l = Math.abs(i - e.r),
  5058. 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);
  5059. } }, vg.HexGrid.prototype.constructor = vg.HexGrid, vg.SqrGrid = function (e) {
  5060. 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 = [];
  5061. }, vg.SqrGrid.prototype = { cellToPixel: function cellToPixel(e) {
  5062. return this._vec3.x = e.q * this._fullCellSize, this._vec3.y = e.h, this._vec3.z = e.r * this._fullCellSize, this._vec3;
  5063. }, pixelToCell: function pixelToCell(e) {
  5064. var t = Math.round(e.x / this._fullCellSize),
  5065. i = Math.round(e.z / this._fullCellSize);return this._cel.set(t, i, 0);
  5066. }, getCellAt: function getCellAt(e) {
  5067. var t = Math.round(e.x / this._fullCellSize),
  5068. i = Math.round(e.z / this._fullCellSize);return this._cel.set(t, i), this.cells[this.cellToHash(this._cel)];
  5069. }, getNeighbors: function getNeighbors(e, t, i) {
  5070. var s,
  5071. n,
  5072. l = this._directions.length;for (this._list.length = 0, s = 0; l > s; s++) {
  5073. 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);
  5074. }if (t) for (s = 0; l > s; s++) {
  5075. 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);
  5076. }return this._list;
  5077. }, getRandomCell: function getRandomCell() {
  5078. var e,
  5079. t = 0,
  5080. i = vg.Tools.randomInt(0, this.numCells);for (e in this.cells) {
  5081. if (t === i) return this.cells[e];t++;
  5082. }return this.cells[e];
  5083. }, cellToHash: function cellToHash(e) {
  5084. return e.q + this._hashDelimeter + e.r;
  5085. }, distance: function distance(e, t) {
  5086. var i = Math.max(Math.abs(e.q - t.q), Math.abs(e.r - t.r));return i += t.h - e.h;
  5087. }, clearPath: function clearPath() {
  5088. var e, t;for (e in this.cells) {
  5089. t = this.cells[e], t._calcCost = 0, t._priority = 0, t._parent = null, t._visited = !1;
  5090. }
  5091. }, traverse: function traverse(e) {
  5092. var t;for (t in this.cells) {
  5093. e(this.cells[t]);
  5094. }
  5095. }, generateTile: function generateTile(e, t, i) {
  5096. 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;
  5097. }, generateTiles: function generateTiles(e) {
  5098. e = e || {};var t = [],
  5099. 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) {
  5100. 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);
  5101. }return t;
  5102. }, generateTilePoly: function generateTilePoly(e) {
  5103. 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;
  5104. }, generate: function generate(e) {
  5105. e = e || {}, this.size = "undefined" == typeof e.size ? this.size : e.size;var t,
  5106. i,
  5107. s,
  5108. n = Math.ceil(this.size / 2);for (t = -n; n > t; t++) {
  5109. for (i = -n; n > i; i++) {
  5110. s = new vg.Cell(t, i + 1), this.add(s);
  5111. }
  5112. }
  5113. }, generateOverlay: function generateOverlay(e, t, i) {
  5114. var s,
  5115. n,
  5116. l = Math.ceil(e / 2);for (s = -l; l > s; s++) {
  5117. for (n = -l; l > n; n++) {
  5118. 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);
  5119. }
  5120. }
  5121. }, add: function add(e) {
  5122. var t = this.cellToHash(e);if (!this.cells[t]) return this.cells[t] = e, this.numCells++, e;
  5123. }, remove: function remove(e) {
  5124. var t = this.cellToHash(e);this.cells[t] && (delete this.cells[t], this.numCells--);
  5125. }, dispose: function dispose() {
  5126. 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;
  5127. }, load: function load(e, t, i) {
  5128. vg.Tools.getJSON({ url: e, callback: function callback(e) {
  5129. this.fromJSON(e), t.call(i || null, e);
  5130. }, cache: !1, scope: this });
  5131. }, fromJSON: function fromJSON(e) {
  5132. var t,
  5133. i,
  5134. 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++) {
  5135. i = new vg.Cell(), i.copy(s[t]), this.add(i);
  5136. }
  5137. }, toJSON: function toJSON() {
  5138. var e,
  5139. t,
  5140. i = { size: this.size, cellSize: this.cellSize, extrudeSettings: this.extrudeSettings, autogenerated: this.autogenerated },
  5141. s = [];for (t in this.cells) {
  5142. e = this.cells[t], s.push({ q: e.q, r: e.r, s: e.s, h: e.h, walkable: e.walkable, userData: e.userData });
  5143. }return i.cells = s, i;
  5144. } }, vg.SqrGrid.prototype.constructor = vg.SqrGrid, vg.Tile = function (e) {
  5145. 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;
  5146. }, vg.Tile.prototype = { select: function select() {
  5147. return this.material.emissive && this.material.emissive.setHex(this.highlight), this.selected = !0, this;
  5148. }, deselect: function deselect() {
  5149. return null !== this._emissive && this.material.emissive && this.material.emissive.setHex(this._emissive), this.selected = !1, this;
  5150. }, toggle: function toggle() {
  5151. return this.selected ? this.deselect() : this.select(), this;
  5152. }, dispose: function dispose() {
  5153. 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;
  5154. } }, vg.Tile.prototype.constructor = vg.Tile, function () {
  5155. var e = function e() {
  5156. this.obj = null, this.next = null, this.prev = null, this.free = !0;
  5157. },
  5158. t = function t() {
  5159. this.first = null, this.last = null, this.length = 0, this.objToNodeMap = {}, this.uniqueID = Date.now() + "" + Math.floor(1e3 * Math.random()), this.sortArray = [];
  5160. };t.generateID = function () {
  5161. return Math.random().toString(36).slice(2) + Date.now();
  5162. }, t.prototype = { getNode: function getNode(e) {
  5163. return this.objToNodeMap[e.uniqueID];
  5164. }, addNode: function addNode(i) {
  5165. var s = new e();if (!i.uniqueID) try {
  5166. i.uniqueID = t.generateID();
  5167. } catch (n) {
  5168. return console.error("[LinkedList.addNode] obj passed is immutable: cannot attach necessary identifier"), null;
  5169. }return s.obj = i, s.free = !1, this.objToNodeMap[i.uniqueID] = s, s;
  5170. }, swapObjects: function swapObjects(e, t) {
  5171. this.objToNodeMap[e.obj.uniqueID] = null, this.objToNodeMap[t.uniqueID] = e, e.obj = t;
  5172. }, add: function add(e) {
  5173. var t = this.objToNodeMap[e.uniqueID];if (t) {
  5174. if (t.free === !1) return;t.obj = e, t.free = !1, t.next = null, t.prev = null;
  5175. } else t = this.addNode(e);if (this.first) {
  5176. 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;
  5177. } else this.first = t, this.last = t, t.next = null, t.prev = null;this.length++, this.showDebug && this.dump("after add");
  5178. }, has: function has(e) {
  5179. return !!this.objToNodeMap[e.uniqueID];
  5180. }, moveUp: function moveUp(e) {
  5181. 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) {
  5182. var i = t.prev,
  5183. 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);
  5184. }
  5185. }, moveDown: function moveDown(e) {
  5186. var t = this.getNode(e);if (!t) throw "Oops, trying to move an object that isn't in the list";if (t.next) {
  5187. var i = t.next;this.moveUp(i.obj), this.last == i && (this.last = t);
  5188. }
  5189. }, sort: function sort(e) {
  5190. var t,
  5191. i,
  5192. s = this.sortArray,
  5193. n = this.first;for (s.length = 0; n;) {
  5194. s.push(n.obj), n = n.next;
  5195. }for (this.clear(), s.sort(e), i = s.length, t = 0; i > t; t++) {
  5196. this.add(s[t]);
  5197. }
  5198. }, remove: function remove(e) {
  5199. 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);
  5200. }, shift: function shift() {
  5201. 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);
  5202. }, pop: function pop() {
  5203. 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);
  5204. }, concat: function concat(e) {
  5205. for (var t = e.first; t;) {
  5206. this.add(t.obj), t = t.next;
  5207. }
  5208. }, clear: function clear() {
  5209. for (var e = this.first; e;) {
  5210. e.free = !0, e = e.next;
  5211. }this.first = null, this.length = 0;
  5212. }, dispose: function dispose() {
  5213. for (var e = this.first; e;) {
  5214. e.obj = null, e = e.next;
  5215. }this.first = null, this.objToNodeMap = null;
  5216. }, dump: function dump(e) {
  5217. console.log("====================" + e + "=====================");for (var t = this.first; t;) {
  5218. console.log("{" + t.obj.toString() + "} previous=" + (t.prev ? t.prev.obj : "NULL")), t = t.next();
  5219. }console.log("==================================="), console.log("Last: {" + (this.last ? this.last.obj : "NULL") + "} First: {" + (this.first ? this.first.obj : "NULL") + "}");
  5220. } }, t.prototype.constructor = t, vg.LinkedList = t;
  5221. }(), function () {
  5222. var e = function e(_e, t, i, s, n) {
  5223. this._listener = t, this.isOnce = i, this.context = s, this.signal = _e, this._priority = n || 0;
  5224. };e.prototype = { active: !0, params: null, execute: function execute(e) {
  5225. 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;
  5226. }, detach: function detach() {
  5227. return this.isBound() ? this.signal.remove(this._listener, this.context) : null;
  5228. }, isBound: function isBound() {
  5229. return !!this.signal && !!this._listener;
  5230. }, _destroy: function _destroy() {
  5231. delete this.signal, delete this._listener, delete this.context;
  5232. }, toString: function toString() {
  5233. return "[SignalBinding isOnce:" + this.isOnce + ", isBound:" + this.isBound() + ", active:" + this.active + "]";
  5234. } }, e.prototype.constructor = e;var t = function t() {
  5235. this._bindings = [], this._prevParams = null;var e = this;this.dispatch = function () {
  5236. t.prototype.dispatch.apply(e, arguments);
  5237. };
  5238. };t.prototype = { memorize: !1, _shouldPropagate: !0, active: !0, validateListener: function validateListener(e, t) {
  5239. if ("function" != typeof e) throw new Error("Signal: listener is a required param of {fn}() and should be a Function.".replace("{fn}", t));
  5240. }, _registerListener: function _registerListener(t, i, s, n) {
  5241. var l,
  5242. r = this._indexOfListener(t, s);if (-1 !== r) {
  5243. 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.");
  5244. } else l = new e(this, t, i, s, n), this._addBinding(l);return this.memorize && this._prevParams && l.execute(this._prevParams), l;
  5245. }, _addBinding: function _addBinding(e) {
  5246. var t = this._bindings.length;do {
  5247. t--;
  5248. } while (this._bindings[t] && e._priority <= this._bindings[t]._priority);this._bindings.splice(t + 1, 0, e);
  5249. }, _indexOfListener: function _indexOfListener(e, t) {
  5250. for (var i, s = this._bindings.length; s--;) {
  5251. if (i = this._bindings[s], i._listener === e && i.context === t) return s;
  5252. }return -1;
  5253. }, has: function has(e, t) {
  5254. return -1 !== this._indexOfListener(e, t);
  5255. }, add: function add(e, t, i) {
  5256. return this.validateListener(e, "add"), this._registerListener(e, !1, t, i);
  5257. }, addOnce: function addOnce(e, t, i) {
  5258. return this.validateListener(e, "addOnce"), this._registerListener(e, !0, t, i);
  5259. }, remove: function remove(e, t) {
  5260. this.validateListener(e, "remove");var i = this._indexOfListener(e, t);return -1 !== i && (this._bindings[i]._destroy(), this._bindings.splice(i, 1)), e;
  5261. }, removeAll: function removeAll(e) {
  5262. "undefined" == typeof e && (e = null);for (var t = this._bindings.length; t--;) {
  5263. e ? this._bindings[t].context === e && (this._bindings[t]._destroy(), this._bindings.splice(t, 1)) : this._bindings[t]._destroy();
  5264. }e || (this._bindings.length = 0);
  5265. }, getNumListeners: function getNumListeners() {
  5266. return this._bindings.length;
  5267. }, halt: function halt() {
  5268. this._shouldPropagate = !1;
  5269. }, dispatch: function dispatch() {
  5270. if (this.active) {
  5271. var e,
  5272. t = Array.prototype.slice.call(arguments),
  5273. i = this._bindings.length;if (this.memorize && (this._prevParams = t), i) {
  5274. e = this._bindings.slice(), this._shouldPropagate = !0;do {
  5275. i--;
  5276. } while (e[i] && this._shouldPropagate && e[i].execute(t) !== !1);
  5277. }
  5278. }
  5279. }, forget: function forget() {
  5280. this._prevParams = null;
  5281. }, dispose: function dispose() {
  5282. this.removeAll(), delete this._bindings, delete this._prevParams;
  5283. }, toString: function toString() {
  5284. return "[Signal active:" + this.active + " numListeners:" + this.getNumListeners() + "]";
  5285. } }, t.prototype.constructor = t, vg.Signal = t;
  5286. }(), vg.AStarFinder = function (e) {
  5287. 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();
  5288. }, vg.AStarFinder.prototype = { findPath: function findPath(e, t, i, s) {
  5289. 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;) {
  5290. 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++) {
  5291. if (h = r[o], h.walkable && (l = n._calcCost + s.distance(n, h), !h._visited || l < h._calcCost)) {
  5292. 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);
  5293. }
  5294. }
  5295. }return null;
  5296. }, compare: function compare(e, t) {
  5297. return e._priority - t._priority;
  5298. } }, vg.AStarFinder.prototype.constructor = vg.AStarFinder, vg.PathUtil = { backtrace: function backtrace(e) {
  5299. for (var t = [e]; e._parent;) {
  5300. e = e._parent, t.push(e);
  5301. }return t.reverse();
  5302. }, biBacktrace: function biBacktrace(e, t) {
  5303. var i = this.backtrace(e),
  5304. s = this.backtrace(t);return i.concat(s.reverse());
  5305. }, pathLength: function pathLength(e) {
  5306. var t,
  5307. i,
  5308. s,
  5309. n,
  5310. l,
  5311. r = 0;for (t = 1; t < e.length; ++t) {
  5312. i = e[t - 1], s = e[t], n = i[0] - s[0], l = i[1] - s[1], r += Math.sqrt(n * n + l * l);
  5313. }return r;
  5314. }, interpolate: function interpolate(e, t, i, s) {
  5315. var n,
  5316. l,
  5317. r,
  5318. h,
  5319. o,
  5320. a,
  5321. c = Math.abs,
  5322. 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;) {
  5323. u.push([e, t]), a = 2 * o, a > -h && (o -= h, e += n), r > a && (o += r, t += l);
  5324. }return u;
  5325. }, expandPath: function expandPath(e) {
  5326. var t,
  5327. i,
  5328. s,
  5329. n,
  5330. l,
  5331. r,
  5332. h = [],
  5333. o = e.length;if (2 > o) return h;for (l = 0; o - 1 > l; ++l) {
  5334. 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) {
  5335. h.push(s[r]);
  5336. }
  5337. }return h.push(e[o - 1]), h;
  5338. }, smoothenPath: function smoothenPath(e, t) {
  5339. var i,
  5340. s,
  5341. n,
  5342. l,
  5343. r,
  5344. h,
  5345. o,
  5346. a,
  5347. c,
  5348. u,
  5349. d,
  5350. g,
  5351. p = t.length,
  5352. v = t[0][0],
  5353. f = t[0][1],
  5354. m = t[p - 1][0],
  5355. _ = t[p - 1][1];for (i = v, s = f, r = [[i, s]], o = 2; p > o; ++o) {
  5356. 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) {
  5357. if (d = u[a], !e.isWalkableAt(d[0], d[1])) {
  5358. g = !0;break;
  5359. }
  5360. }g && (h = t[o - 1], r.push(h), i = h[0], s = h[1]);
  5361. }return r.push([m, _]), r;
  5362. }, compressPath: function compressPath(e) {
  5363. if (e.length < 3) return e;var t,
  5364. i,
  5365. s,
  5366. n,
  5367. l,
  5368. r,
  5369. h = [],
  5370. o = e[0][0],
  5371. a = e[0][1],
  5372. c = e[1][0],
  5373. u = e[1][1],
  5374. d = c - o,
  5375. 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++) {
  5376. 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]);
  5377. }return h.push([c, u]), h;
  5378. } }, vg.Loader = { manager: null, imageLoader: null, crossOrigin: !1, init: function init(e) {
  5379. this.crossOrigin = e || !1, this.manager = new THREE.LoadingManager(function () {}, function () {}, function () {
  5380. console.warn("Error loading images");
  5381. }), this.imageLoader = new THREE.ImageLoader(this.manager), this.imageLoader.crossOrigin = e;
  5382. }, loadTexture: function loadTexture(e, t, i, s) {
  5383. var n = new THREE.Texture(null, t);return this.imageLoader.load(e, function (e) {
  5384. n.image = e, n.needsUpdate = !0, i && i(n);
  5385. }, null, function (e) {
  5386. s && s(e);
  5387. }), n.sourceFile = e, n;
  5388. } }, vg.MouseCaster = function (e, t, i) {
  5389. 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);
  5390. }, 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() {
  5391. if (this.active) {
  5392. this._raycaster.setFromCamera(this.screenPosition, this._camera);var e,
  5393. t,
  5394. 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;
  5395. }
  5396. }, preventDefault: function preventDefault() {
  5397. this._preventDefault = !0;
  5398. }, _onDocumentMouseDown: function _onDocumentMouseDown(e) {
  5399. 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));
  5400. }, _onDocumentMouseUp: function _onDocumentMouseUp(e) {
  5401. 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));
  5402. }, _onDocumentMouseMove: function _onDocumentMouseMove(e) {
  5403. e.preventDefault(), this.screenPosition.x = e.clientX / window.innerWidth * 2 - 1, this.screenPosition.y = 2 * -(e.clientY / window.innerHeight) + 1;
  5404. }, _onMouseWheel: function _onMouseWheel(e) {
  5405. if (this.active) {
  5406. 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);
  5407. }
  5408. } }, vg.MouseCaster.prototype.constructor = vg.MouseCaster, vg.Scene = function (e, t) {
  5409. 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 },
  5410. 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) {
  5411. var n = window.innerWidth / this.orthoZoom,
  5412. l = window.innerHeight / this.orthoZoom;this.camera = new THREE.OrthographicCamera(n / -2, n / 2, l / 2, l / -2, 1, 5e3);
  5413. } 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 () {
  5414. if (this.width = window.innerWidth, this.height = window.innerHeight, "OrthographicCamera" === this.camera.type) {
  5415. var e = this.width / this.orthoZoom,
  5416. 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;
  5417. } else this.camera.aspect = this.width / this.height;this.camera.updateProjectionMatrix(), this.renderer.setSize(this.width, this.height);
  5418. }.bind(this), !1), this.attachTo(i.element);
  5419. }, vg.Scene.prototype = { attachTo: function attachTo(e) {
  5420. 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);
  5421. }, add: function add(e) {
  5422. this.container.add(e);
  5423. }, remove: function remove(e) {
  5424. this.container.remove(e);
  5425. }, render: function render() {
  5426. this.contolled && this.controls.update(), this.renderer.render(this.container, this.camera);
  5427. }, updateOrthoZoom: function updateOrthoZoom() {
  5428. if (this.orthoZoom <= 0) return void (this.orthoZoom = 0);var e = this.width / this.orthoZoom,
  5429. 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();
  5430. }, focusOn: function focusOn(e) {
  5431. this.camera.lookAt(e.position);
  5432. } }, vg.Scene.prototype.constructor = vg.Scene, vg.SelectionManager = function (e) {
  5433. 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);
  5434. }, vg.SelectionManager.prototype = { select: function select(e, t) {
  5435. 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));
  5436. }, clearSelection: function clearSelection(e) {
  5437. e = e || !0, this.selected && (e && this.onDeselect.dispatch(this.selected), this.selected.deselect()), this.selected = null;
  5438. }, onMouse: function onMouse(e, t) {
  5439. switch (e) {case vg.MouseCaster.DOWN:
  5440. t || this.clearSelection();break;case vg.MouseCaster.CLICK:
  5441. this.select(t);}
  5442. } }, vg.SelectionManager.prototype.constructor = vg.SelectionManager, vg.Tools = { clamp: function clamp(e, t, i) {
  5443. return Math.max(t, Math.min(i, e));
  5444. }, sign: function sign(e) {
  5445. return e && e / Math.abs(e);
  5446. }, random: function random(e, t) {
  5447. return 1 === arguments.length ? Math.random() * e - .5 * e : Math.random() * (t - e) + e;
  5448. }, randomInt: function randomInt(e, t) {
  5449. return 1 === arguments.length ? Math.random() * e - .5 * e | 0 : Math.random() * (t - e + 1) + e | 0;
  5450. }, normalize: function normalize(e, t, i) {
  5451. return (e - t) / (i - t);
  5452. }, getShortRotation: function getShortRotation(e) {
  5453. return e %= this.TAU, e > this.PI ? e -= this.TAU : e < -this.PI && (e += this.TAU), e;
  5454. }, generateID: function generateID() {
  5455. return Math.random().toString(36).slice(2) + Date.now();
  5456. }, isPlainObject: function isPlainObject(e) {
  5457. if ("object" != (typeof e === "undefined" ? "undefined" : _typeof(e)) || e.nodeType || e === e.window) return !1;try {
  5458. if (e.constructor && !Object.prototype.hasOwnProperty.call(e.constructor.prototype, "isPrototypeOf")) return !1;
  5459. } catch (t) {
  5460. return !1;
  5461. }return !0;
  5462. }, merge: function merge(e, t) {
  5463. var i = this,
  5464. s = Array.isArray(t),
  5465. n = s && [] || {};return s ? (e = e || [], n = n.concat(e), t.forEach(function (t, s) {
  5466. "undefined" == typeof n[s] ? n[s] = t : i.isPlainObject(t) ? n[s] = i.merge(e[s], t) : -1 === e.indexOf(t) && n.push(t);
  5467. }), n) : (e && i.isPlainObject(e) && Object.keys(e).forEach(function (t) {
  5468. n[t] = e[t];
  5469. }), Object.keys(t).forEach(function (s) {
  5470. t[s] && i.isPlainObject(t[s]) && e[s] ? n[s] = i.merge(e[s], t[s]) : n[s] = t[s];
  5471. }), n);
  5472. }, now: function now() {
  5473. return window.nwf ? window.nwf.system.Performance.elapsedTime : window.performance.now();
  5474. }, empty: function empty(e) {
  5475. for (; e.lastChild;) {
  5476. e.removeChild(e.lastChild);
  5477. }
  5478. }, radixSort: function radixSort(e, t, i, s) {
  5479. if (t = t || 0, i = i || e.length, s = s || 31, !(t >= i - 1 || 0 > s)) {
  5480. for (var n = t, l = i, r = 1 << s; l > n;) {
  5481. if (e[n] & r) {
  5482. --l;var h = e[n];e[n] = e[l], e[l] = h;
  5483. } else ++n;
  5484. }this.radixSort(e, t, l, s - 1), this.radixSort(e, l, i, s - 1);
  5485. }
  5486. }, randomizeRGB: function randomizeRGB(e, t) {
  5487. var i,
  5488. s,
  5489. n = e.split(","),
  5490. l = "rgb(";for (t = this.randomInt(t), i = 0; 3 > i; i++) {
  5491. s = parseInt(n[i]) + t, 0 > s ? s = 0 : s > 255 && (s = 255), l += s + ",";
  5492. }return l = l.substring(0, l.length - 1), l += ")";
  5493. }, getJSON: function getJSON(e) {
  5494. var t = new XMLHttpRequest(),
  5495. i = "undefined" == typeof e.cache ? !1 : e.cache,
  5496. s = i ? e.url : e.url + "?t=" + Math.floor(1e4 * Math.random()) + Date.now();t.onreadystatechange = function () {
  5497. if (200 === this.status) {
  5498. var t = null;try {
  5499. t = JSON.parse(this.responseText);
  5500. } catch (i) {
  5501. return;
  5502. }return void e.callback.call(e.scope || null, t);
  5503. }0 !== this.status && console.warn("[Tools.getJSON] Error: " + this.status + " (" + this.statusText + ") :: " + e.url);
  5504. }, t.open("GET", s, !0), t.setRequestHeader("Accept", "application/json"), t.setRequestHeader("Content-Type", "application/json"), t.send("");
  5505. } };
  5506. },{}],10:[function(require,module,exports){
  5507. 'use strict';
  5508. /**
  5509. * Polyfill for the additional KeyboardEvent properties defined in the D3E and
  5510. * D4E draft specifications, by @inexorabletash.
  5511. *
  5512. * See: https://github.com/inexorabletash/polyfill
  5513. */
  5514. (function (global) {
  5515. var nativeKeyboardEvent = 'KeyboardEvent' in global;
  5516. if (!nativeKeyboardEvent) global.KeyboardEvent = function KeyboardEvent() {
  5517. throw TypeError('Illegal constructor');
  5518. };
  5519. if (!('DOM_KEY_LOCATION_STANDARD' in global.KeyboardEvent)) global.KeyboardEvent.DOM_KEY_LOCATION_STANDARD = 0x00; // Default or unknown location
  5520. if (!('DOM_KEY_LOCATION_LEFT' in global.KeyboardEvent)) global.KeyboardEvent.DOM_KEY_LOCATION_LEFT = 0x01; // e.g. Left Alt key
  5521. if (!('DOM_KEY_LOCATION_RIGHT' in global.KeyboardEvent)) global.KeyboardEvent.DOM_KEY_LOCATION_RIGHT = 0x02; // e.g. Right Alt key
  5522. if (!('DOM_KEY_LOCATION_NUMPAD' in global.KeyboardEvent)) global.KeyboardEvent.DOM_KEY_LOCATION_NUMPAD = 0x03; // e.g. Numpad 0 or +
  5523. var STANDARD = window.KeyboardEvent.DOM_KEY_LOCATION_STANDARD,
  5524. LEFT = window.KeyboardEvent.DOM_KEY_LOCATION_LEFT,
  5525. RIGHT = window.KeyboardEvent.DOM_KEY_LOCATION_RIGHT,
  5526. NUMPAD = window.KeyboardEvent.DOM_KEY_LOCATION_NUMPAD;
  5527. //--------------------------------------------------------------------
  5528. //
  5529. // Utilities
  5530. //
  5531. //--------------------------------------------------------------------
  5532. function contains(s, ss) {
  5533. return String(s).indexOf(ss) !== -1;
  5534. }
  5535. var os = function () {
  5536. if (contains(navigator.platform, 'Win')) {
  5537. return 'win';
  5538. }
  5539. if (contains(navigator.platform, 'Mac')) {
  5540. return 'mac';
  5541. }
  5542. if (contains(navigator.platform, 'CrOS')) {
  5543. return 'cros';
  5544. }
  5545. if (contains(navigator.platform, 'Linux')) {
  5546. return 'linux';
  5547. }
  5548. if (contains(navigator.userAgent, 'iPad') || contains(navigator.platform, 'iPod') || contains(navigator.platform, 'iPhone')) {
  5549. return 'ios';
  5550. }
  5551. return '';
  5552. }();
  5553. var browser = function () {
  5554. if (contains(navigator.userAgent, 'Chrome/')) {
  5555. return 'chrome';
  5556. }
  5557. if (contains(navigator.vendor, 'Apple')) {
  5558. return 'safari';
  5559. }
  5560. if (contains(navigator.userAgent, 'MSIE')) {
  5561. return 'ie';
  5562. }
  5563. if (contains(navigator.userAgent, 'Gecko/')) {
  5564. return 'moz';
  5565. }
  5566. if (contains(navigator.userAgent, 'Opera/')) {
  5567. return 'opera';
  5568. }
  5569. return '';
  5570. }();
  5571. var browser_os = browser + '-' + os;
  5572. function mergeIf(baseTable, select, table) {
  5573. if (browser_os === select || browser === select || os === select) {
  5574. Object.keys(table).forEach(function (keyCode) {
  5575. baseTable[keyCode] = table[keyCode];
  5576. });
  5577. }
  5578. }
  5579. function remap(o, key) {
  5580. var r = {};
  5581. Object.keys(o).forEach(function (k) {
  5582. var item = o[k];
  5583. if (key in item) {
  5584. r[item[key]] = item;
  5585. }
  5586. });
  5587. return r;
  5588. }
  5589. function invert(o) {
  5590. var r = {};
  5591. Object.keys(o).forEach(function (k) {
  5592. r[o[k]] = k;
  5593. });
  5594. return r;
  5595. }
  5596. //--------------------------------------------------------------------
  5597. //
  5598. // Generic Mappings
  5599. //
  5600. //--------------------------------------------------------------------
  5601. // "keyInfo" is a dictionary:
  5602. // code: string - name from DOM Level 3 KeyboardEvent code Values
  5603. // https://dvcs.w3.org/hg/dom3events/raw-file/tip/html/DOM3Events-code.html
  5604. // location (optional): number - one of the DOM_KEY_LOCATION values
  5605. // keyCap (optional): string - keyboard label in en-US locale
  5606. // USB code Usage ID from page 0x07 unless otherwise noted (Informative)
  5607. // Map of keyCode to keyInfo
  5608. var keyCodeToInfoTable = {
  5609. // 0x01 - VK_LBUTTON
  5610. // 0x02 - VK_RBUTTON
  5611. 0x03: { code: 'Cancel' }, // [USB: 0x9b] char \x0018 ??? (Not in D3E)
  5612. // 0x04 - VK_MBUTTON
  5613. // 0x05 - VK_XBUTTON1
  5614. // 0x06 - VK_XBUTTON2
  5615. 0x06: { code: 'Help' }, // [USB: 0x75] ???
  5616. // 0x07 - undefined
  5617. 0x08: { code: 'Backspace' }, // [USB: 0x2a] Labelled Delete on Macintosh keyboards.
  5618. 0x09: { code: 'Tab' }, // [USB: 0x2b]
  5619. // 0x0A-0x0B - reserved
  5620. 0X0C: { code: 'Clear' }, // [USB: 0x9c] NumPad Center (Not in D3E)
  5621. 0X0D: { code: 'Enter' }, // [USB: 0x28]
  5622. // 0x0E-0x0F - undefined
  5623. 0x10: { code: 'Shift' },
  5624. 0x11: { code: 'Control' },
  5625. 0x12: { code: 'Alt' },
  5626. 0x13: { code: 'Pause' }, // [USB: 0x48]
  5627. 0x14: { code: 'CapsLock' }, // [USB: 0x39]
  5628. 0x15: { code: 'KanaMode' }, // [USB: 0x88] - "HangulMode" for Korean layout
  5629. 0x16: { code: 'HangulMode' }, // [USB: 0x90] 0x15 as well in MSDN VK table ???
  5630. 0x17: { code: 'JunjaMode' }, // (Not in D3E)
  5631. 0x18: { code: 'FinalMode' }, // (Not in D3E)
  5632. 0x19: { code: 'KanjiMode' }, // [USB: 0x91] - "HanjaMode" for Korean layout
  5633. // 0x1A - undefined
  5634. 0x1B: { code: 'Escape' }, // [USB: 0x29]
  5635. 0x1C: { code: 'Convert' }, // [USB: 0x8a]
  5636. 0x1D: { code: 'NonConvert' }, // [USB: 0x8b]
  5637. 0x1E: { code: 'Accept' }, // (Not in D3E)
  5638. 0x1F: { code: 'ModeChange' }, // (Not in D3E)
  5639. 0x20: { code: 'Space' }, // [USB: 0x2c]
  5640. 0x21: { code: 'PageUp' }, // [USB: 0x4b]
  5641. 0x22: { code: 'PageDown' }, // [USB: 0x4e]
  5642. 0x23: { code: 'End' }, // [USB: 0x4d]
  5643. 0x24: { code: 'Home' }, // [USB: 0x4a]
  5644. 0x25: { code: 'ArrowLeft' }, // [USB: 0x50]
  5645. 0x26: { code: 'ArrowUp' }, // [USB: 0x52]
  5646. 0x27: { code: 'ArrowRight' }, // [USB: 0x4f]
  5647. 0x28: { code: 'ArrowDown' }, // [USB: 0x51]
  5648. 0x29: { code: 'Select' }, // (Not in D3E)
  5649. 0x2A: { code: 'Print' }, // (Not in D3E)
  5650. 0x2B: { code: 'Execute' }, // [USB: 0x74] (Not in D3E)
  5651. 0x2C: { code: 'PrintScreen' }, // [USB: 0x46]
  5652. 0x2D: { code: 'Insert' }, // [USB: 0x49]
  5653. 0x2E: { code: 'Delete' }, // [USB: 0x4c]
  5654. 0x2F: { code: 'Help' }, // [USB: 0x75] ???
  5655. 0x30: { code: 'Digit0', keyCap: '0' }, // [USB: 0x27] 0)
  5656. 0x31: { code: 'Digit1', keyCap: '1' }, // [USB: 0x1e] 1!
  5657. 0x32: { code: 'Digit2', keyCap: '2' }, // [USB: 0x1f] 2@
  5658. 0x33: { code: 'Digit3', keyCap: '3' }, // [USB: 0x20] 3#
  5659. 0x34: { code: 'Digit4', keyCap: '4' }, // [USB: 0x21] 4$
  5660. 0x35: { code: 'Digit5', keyCap: '5' }, // [USB: 0x22] 5%
  5661. 0x36: { code: 'Digit6', keyCap: '6' }, // [USB: 0x23] 6^
  5662. 0x37: { code: 'Digit7', keyCap: '7' }, // [USB: 0x24] 7&
  5663. 0x38: { code: 'Digit8', keyCap: '8' }, // [USB: 0x25] 8*
  5664. 0x39: { code: 'Digit9', keyCap: '9' }, // [USB: 0x26] 9(
  5665. // 0x3A-0x40 - undefined
  5666. 0x41: { code: 'KeyA', keyCap: 'a' }, // [USB: 0x04]
  5667. 0x42: { code: 'KeyB', keyCap: 'b' }, // [USB: 0x05]
  5668. 0x43: { code: 'KeyC', keyCap: 'c' }, // [USB: 0x06]
  5669. 0x44: { code: 'KeyD', keyCap: 'd' }, // [USB: 0x07]
  5670. 0x45: { code: 'KeyE', keyCap: 'e' }, // [USB: 0x08]
  5671. 0x46: { code: 'KeyF', keyCap: 'f' }, // [USB: 0x09]
  5672. 0x47: { code: 'KeyG', keyCap: 'g' }, // [USB: 0x0a]
  5673. 0x48: { code: 'KeyH', keyCap: 'h' }, // [USB: 0x0b]
  5674. 0x49: { code: 'KeyI', keyCap: 'i' }, // [USB: 0x0c]
  5675. 0x4A: { code: 'KeyJ', keyCap: 'j' }, // [USB: 0x0d]
  5676. 0x4B: { code: 'KeyK', keyCap: 'k' }, // [USB: 0x0e]
  5677. 0x4C: { code: 'KeyL', keyCap: 'l' }, // [USB: 0x0f]
  5678. 0x4D: { code: 'KeyM', keyCap: 'm' }, // [USB: 0x10]
  5679. 0x4E: { code: 'KeyN', keyCap: 'n' }, // [USB: 0x11]
  5680. 0x4F: { code: 'KeyO', keyCap: 'o' }, // [USB: 0x12]
  5681. 0x50: { code: 'KeyP', keyCap: 'p' }, // [USB: 0x13]
  5682. 0x51: { code: 'KeyQ', keyCap: 'q' }, // [USB: 0x14]
  5683. 0x52: { code: 'KeyR', keyCap: 'r' }, // [USB: 0x15]
  5684. 0x53: { code: 'KeyS', keyCap: 's' }, // [USB: 0x16]
  5685. 0x54: { code: 'KeyT', keyCap: 't' }, // [USB: 0x17]
  5686. 0x55: { code: 'KeyU', keyCap: 'u' }, // [USB: 0x18]
  5687. 0x56: { code: 'KeyV', keyCap: 'v' }, // [USB: 0x19]
  5688. 0x57: { code: 'KeyW', keyCap: 'w' }, // [USB: 0x1a]
  5689. 0x58: { code: 'KeyX', keyCap: 'x' }, // [USB: 0x1b]
  5690. 0x59: { code: 'KeyY', keyCap: 'y' }, // [USB: 0x1c]
  5691. 0x5A: { code: 'KeyZ', keyCap: 'z' }, // [USB: 0x1d]
  5692. 0x5B: { code: 'OSLeft', location: LEFT }, // [USB: 0xe3]
  5693. 0x5C: { code: 'OSRight', location: RIGHT }, // [USB: 0xe7]
  5694. 0x5D: { code: 'ContextMenu' }, // [USB: 0x65] Context Menu
  5695. // 0x5E - reserved
  5696. 0x5F: { code: 'Standby' }, // [USB: 0x82] Sleep
  5697. 0x60: { code: 'Numpad0', keyCap: '0', location: NUMPAD }, // [USB: 0x62]
  5698. 0x61: { code: 'Numpad1', keyCap: '1', location: NUMPAD }, // [USB: 0x59]
  5699. 0x62: { code: 'Numpad2', keyCap: '2', location: NUMPAD }, // [USB: 0x5a]
  5700. 0x63: { code: 'Numpad3', keyCap: '3', location: NUMPAD }, // [USB: 0x5b]
  5701. 0x64: { code: 'Numpad4', keyCap: '4', location: NUMPAD }, // [USB: 0x5c]
  5702. 0x65: { code: 'Numpad5', keyCap: '5', location: NUMPAD }, // [USB: 0x5d]
  5703. 0x66: { code: 'Numpad6', keyCap: '6', location: NUMPAD }, // [USB: 0x5e]
  5704. 0x67: { code: 'Numpad7', keyCap: '7', location: NUMPAD }, // [USB: 0x5f]
  5705. 0x68: { code: 'Numpad8', keyCap: '8', location: NUMPAD }, // [USB: 0x60]
  5706. 0x69: { code: 'Numpad9', keyCap: '9', location: NUMPAD }, // [USB: 0x61]
  5707. 0x6A: { code: 'NumpadMultiply', keyCap: '*', location: NUMPAD }, // [USB: 0x55]
  5708. 0x6B: { code: 'NumpadAdd', keyCap: '+', location: NUMPAD }, // [USB: 0x57]
  5709. 0x6C: { code: 'NumpadComma', keyCap: ',', location: NUMPAD }, // [USB: 0x85]
  5710. 0x6D: { code: 'NumpadSubtract', keyCap: '-', location: NUMPAD }, // [USB: 0x56]
  5711. 0x6E: { code: 'NumpadDecimal', keyCap: '.', location: NUMPAD }, // [USB: 0x63]
  5712. 0x6F: { code: 'NumpadDivide', keyCap: '/', location: NUMPAD }, // [USB: 0x54]
  5713. 0x70: { code: 'F1' }, // [USB: 0x3a]
  5714. 0x71: { code: 'F2' }, // [USB: 0x3b]
  5715. 0x72: { code: 'F3' }, // [USB: 0x3c]
  5716. 0x73: { code: 'F4' }, // [USB: 0x3d]
  5717. 0x74: { code: 'F5' }, // [USB: 0x3e]
  5718. 0x75: { code: 'F6' }, // [USB: 0x3f]
  5719. 0x76: { code: 'F7' }, // [USB: 0x40]
  5720. 0x77: { code: 'F8' }, // [USB: 0x41]
  5721. 0x78: { code: 'F9' }, // [USB: 0x42]
  5722. 0x79: { code: 'F10' }, // [USB: 0x43]
  5723. 0x7A: { code: 'F11' }, // [USB: 0x44]
  5724. 0x7B: { code: 'F12' }, // [USB: 0x45]
  5725. 0x7C: { code: 'F13' }, // [USB: 0x68]
  5726. 0x7D: { code: 'F14' }, // [USB: 0x69]
  5727. 0x7E: { code: 'F15' }, // [USB: 0x6a]
  5728. 0x7F: { code: 'F16' }, // [USB: 0x6b]
  5729. 0x80: { code: 'F17' }, // [USB: 0x6c]
  5730. 0x81: { code: 'F18' }, // [USB: 0x6d]
  5731. 0x82: { code: 'F19' }, // [USB: 0x6e]
  5732. 0x83: { code: 'F20' }, // [USB: 0x6f]
  5733. 0x84: { code: 'F21' }, // [USB: 0x70]
  5734. 0x85: { code: 'F22' }, // [USB: 0x71]
  5735. 0x86: { code: 'F23' }, // [USB: 0x72]
  5736. 0x87: { code: 'F24' }, // [USB: 0x73]
  5737. // 0x88-0x8F - unassigned
  5738. 0x90: { code: 'NumLock', location: NUMPAD }, // [USB: 0x53]
  5739. 0x91: { code: 'ScrollLock' }, // [USB: 0x47]
  5740. // 0x92-0x96 - OEM specific
  5741. // 0x97-0x9F - unassigned
  5742. // NOTE: 0xA0-0xA5 usually mapped to 0x10-0x12 in browsers
  5743. 0xA0: { code: 'ShiftLeft', location: LEFT }, // [USB: 0xe1]
  5744. 0xA1: { code: 'ShiftRight', location: RIGHT }, // [USB: 0xe5]
  5745. 0xA2: { code: 'ControlLeft', location: LEFT }, // [USB: 0xe0]
  5746. 0xA3: { code: 'ControlRight', location: RIGHT }, // [USB: 0xe4]
  5747. 0xA4: { code: 'AltLeft', location: LEFT }, // [USB: 0xe2]
  5748. 0xA5: { code: 'AltRight', location: RIGHT }, // [USB: 0xe6]
  5749. 0xA6: { code: 'BrowserBack' }, // [USB: 0x0c/0x0224]
  5750. 0xA7: { code: 'BrowserForward' }, // [USB: 0x0c/0x0225]
  5751. 0xA8: { code: 'BrowserRefresh' }, // [USB: 0x0c/0x0227]
  5752. 0xA9: { code: 'BrowserStop' }, // [USB: 0x0c/0x0226]
  5753. 0xAA: { code: 'BrowserSearch' }, // [USB: 0x0c/0x0221]
  5754. 0xAB: { code: 'BrowserFavorites' }, // [USB: 0x0c/0x0228]
  5755. 0xAC: { code: 'BrowserHome' }, // [USB: 0x0c/0x0222]
  5756. 0xAD: { code: 'VolumeMute' }, // [USB: 0x7f]
  5757. 0xAE: { code: 'VolumeDown' }, // [USB: 0x81]
  5758. 0xAF: { code: 'VolumeUp' }, // [USB: 0x80]
  5759. 0xB0: { code: 'MediaTrackNext' }, // [USB: 0x0c/0x00b5]
  5760. 0xB1: { code: 'MediaTrackPrevious' }, // [USB: 0x0c/0x00b6]
  5761. 0xB2: { code: 'MediaStop' }, // [USB: 0x0c/0x00b7]
  5762. 0xB3: { code: 'MediaPlayPause' }, // [USB: 0x0c/0x00cd]
  5763. 0xB4: { code: 'LaunchMail' }, // [USB: 0x0c/0x018a]
  5764. 0xB5: { code: 'MediaSelect' },
  5765. 0xB6: { code: 'LaunchApp1' },
  5766. 0xB7: { code: 'LaunchApp2' },
  5767. // 0xB8-0xB9 - reserved
  5768. 0xBA: { code: 'Semicolon', keyCap: ';' }, // [USB: 0x33] ;: (US Standard 101)
  5769. 0xBB: { code: 'Equal', keyCap: '=' }, // [USB: 0x2e] =+
  5770. 0xBC: { code: 'Comma', keyCap: ',' }, // [USB: 0x36] ,<
  5771. 0xBD: { code: 'Minus', keyCap: '-' }, // [USB: 0x2d] -_
  5772. 0xBE: { code: 'Period', keyCap: '.' }, // [USB: 0x37] .>
  5773. 0xBF: { code: 'Slash', keyCap: '/' }, // [USB: 0x38] /? (US Standard 101)
  5774. 0xC0: { code: 'Backquote', keyCap: '`' }, // [USB: 0x35] `~ (US Standard 101)
  5775. // 0xC1-0xCF - reserved
  5776. // 0xD0-0xD7 - reserved
  5777. // 0xD8-0xDA - unassigned
  5778. 0xDB: { code: 'BracketLeft', keyCap: '[' }, // [USB: 0x2f] [{ (US Standard 101)
  5779. 0xDC: { code: 'Backslash', keyCap: '\\' }, // [USB: 0x31] \| (US Standard 101)
  5780. 0xDD: { code: 'BracketRight', keyCap: ']' }, // [USB: 0x30] ]} (US Standard 101)
  5781. 0xDE: { code: 'Quote', keyCap: '\'' }, // [USB: 0x34] '" (US Standard 101)
  5782. // 0xDF - miscellaneous/varies
  5783. // 0xE0 - reserved
  5784. // 0xE1 - OEM specific
  5785. 0xE2: { code: 'IntlBackslash', keyCap: '\\' }, // [USB: 0x64] \| (UK Standard 102)
  5786. // 0xE3-0xE4 - OEM specific
  5787. 0xE5: { code: 'Process' }, // (Not in D3E)
  5788. // 0xE6 - OEM specific
  5789. // 0xE7 - VK_PACKET
  5790. // 0xE8 - unassigned
  5791. // 0xE9-0xEF - OEM specific
  5792. // 0xF0-0xF5 - OEM specific
  5793. 0xF6: { code: 'Attn' }, // [USB: 0x9a] (Not in D3E)
  5794. 0xF7: { code: 'CrSel' }, // [USB: 0xa3] (Not in D3E)
  5795. 0xF8: { code: 'ExSel' }, // [USB: 0xa4] (Not in D3E)
  5796. 0xF9: { code: 'EraseEof' }, // (Not in D3E)
  5797. 0xFA: { code: 'Play' }, // (Not in D3E)
  5798. 0xFB: { code: 'ZoomToggle' }, // (Not in D3E)
  5799. // 0xFC - VK_NONAME - reserved
  5800. // 0xFD - VK_PA1
  5801. 0xFE: { code: 'Clear' // [USB: 0x9c] (Not in D3E)
  5802. } };
  5803. // No legacy keyCode, but listed in D3E:
  5804. // code: usb
  5805. // 'IntlHash': 0x070032,
  5806. // 'IntlRo': 0x070087,
  5807. // 'IntlYen': 0x070089,
  5808. // 'NumpadBackspace': 0x0700bb,
  5809. // 'NumpadClear': 0x0700d8,
  5810. // 'NumpadClearEntry': 0x0700d9,
  5811. // 'NumpadMemoryAdd': 0x0700d3,
  5812. // 'NumpadMemoryClear': 0x0700d2,
  5813. // 'NumpadMemoryRecall': 0x0700d1,
  5814. // 'NumpadMemoryStore': 0x0700d0,
  5815. // 'NumpadMemorySubtract': 0x0700d4,
  5816. // 'NumpadParenLeft': 0x0700b6,
  5817. // 'NumpadParenRight': 0x0700b7,
  5818. //--------------------------------------------------------------------
  5819. //
  5820. // Browser/OS Specific Mappings
  5821. //
  5822. //--------------------------------------------------------------------
  5823. mergeIf(keyCodeToInfoTable, 'moz', {
  5824. 0x3B: { code: 'Semicolon', keyCap: ';' }, // [USB: 0x33] ;: (US Standard 101)
  5825. 0x3D: { code: 'Equal', keyCap: '=' }, // [USB: 0x2e] =+
  5826. 0x6B: { code: 'Equal', keyCap: '=' }, // [USB: 0x2e] =+
  5827. 0x6D: { code: 'Minus', keyCap: '-' }, // [USB: 0x2d] -_
  5828. 0xBB: { code: 'NumpadAdd', keyCap: '+', location: NUMPAD }, // [USB: 0x57]
  5829. 0xBD: { code: 'NumpadSubtract', keyCap: '-', location: NUMPAD // [USB: 0x56]
  5830. } });
  5831. mergeIf(keyCodeToInfoTable, 'moz-mac', {
  5832. 0x0C: { code: 'NumLock', location: NUMPAD }, // [USB: 0x53]
  5833. 0xAD: { code: 'Minus', keyCap: '-' // [USB: 0x2d] -_
  5834. } });
  5835. mergeIf(keyCodeToInfoTable, 'moz-win', {
  5836. 0xAD: { code: 'Minus', keyCap: '-' // [USB: 0x2d] -_
  5837. } });
  5838. mergeIf(keyCodeToInfoTable, 'chrome-mac', {
  5839. 0x5D: { code: 'OSRight', location: RIGHT // [USB: 0xe7]
  5840. } });
  5841. // Windows via Bootcamp (!)
  5842. if (0) {
  5843. mergeIf(keyCodeToInfoTable, 'chrome-win', {
  5844. 0xC0: { code: 'Quote', keyCap: '\'' }, // [USB: 0x34] '" (US Standard 101)
  5845. 0xDE: { code: 'Backslash', keyCap: '\\' }, // [USB: 0x31] \| (US Standard 101)
  5846. 0xDF: { code: 'Backquote', keyCap: '`' // [USB: 0x35] `~ (US Standard 101)
  5847. } });
  5848. mergeIf(keyCodeToInfoTable, 'ie', {
  5849. 0xC0: { code: 'Quote', keyCap: '\'' }, // [USB: 0x34] '" (US Standard 101)
  5850. 0xDE: { code: 'Backslash', keyCap: '\\' }, // [USB: 0x31] \| (US Standard 101)
  5851. 0xDF: { code: 'Backquote', keyCap: '`' // [USB: 0x35] `~ (US Standard 101)
  5852. } });
  5853. }
  5854. mergeIf(keyCodeToInfoTable, 'safari', {
  5855. 0x03: { code: 'Enter' }, // [USB: 0x28] old Safari
  5856. 0x19: { code: 'Tab' // [USB: 0x2b] old Safari for Shift+Tab
  5857. } });
  5858. mergeIf(keyCodeToInfoTable, 'ios', {
  5859. 0x0A: { code: 'Enter', location: STANDARD // [USB: 0x28]
  5860. } });
  5861. mergeIf(keyCodeToInfoTable, 'safari-mac', {
  5862. 0x5B: { code: 'OSLeft', location: LEFT }, // [USB: 0xe3]
  5863. 0x5D: { code: 'OSRight', location: RIGHT }, // [USB: 0xe7]
  5864. 0xE5: { code: 'KeyQ', keyCap: 'Q' // [USB: 0x14] On alternate presses, Ctrl+Q sends this
  5865. } });
  5866. //--------------------------------------------------------------------
  5867. //
  5868. // Identifier Mappings
  5869. //
  5870. //--------------------------------------------------------------------
  5871. // Cases where newer-ish browsers send keyIdentifier which can be
  5872. // used to disambiguate keys.
  5873. // keyIdentifierTable[keyIdentifier] -> keyInfo
  5874. var keyIdentifierTable = {};
  5875. if ('cros' === os) {
  5876. keyIdentifierTable['U+00A0'] = { code: 'ShiftLeft', location: LEFT };
  5877. keyIdentifierTable['U+00A1'] = { code: 'ShiftRight', location: RIGHT };
  5878. keyIdentifierTable['U+00A2'] = { code: 'ControlLeft', location: LEFT };
  5879. keyIdentifierTable['U+00A3'] = { code: 'ControlRight', location: RIGHT };
  5880. keyIdentifierTable['U+00A4'] = { code: 'AltLeft', location: LEFT };
  5881. keyIdentifierTable['U+00A5'] = { code: 'AltRight', location: RIGHT };
  5882. }
  5883. if ('chrome-mac' === browser_os) {
  5884. keyIdentifierTable['U+0010'] = { code: 'ContextMenu' };
  5885. }
  5886. if ('safari-mac' === browser_os) {
  5887. keyIdentifierTable['U+0010'] = { code: 'ContextMenu' };
  5888. }
  5889. if ('ios' === os) {
  5890. // These only generate keyup events
  5891. keyIdentifierTable['U+0010'] = { code: 'Function' };
  5892. keyIdentifierTable['U+001C'] = { code: 'ArrowLeft' };
  5893. keyIdentifierTable['U+001D'] = { code: 'ArrowRight' };
  5894. keyIdentifierTable['U+001E'] = { code: 'ArrowUp' };
  5895. keyIdentifierTable['U+001F'] = { code: 'ArrowDown' };
  5896. keyIdentifierTable['U+0001'] = { code: 'Home' }; // [USB: 0x4a] Fn + ArrowLeft
  5897. keyIdentifierTable['U+0004'] = { code: 'End' }; // [USB: 0x4d] Fn + ArrowRight
  5898. keyIdentifierTable['U+000B'] = { code: 'PageUp' }; // [USB: 0x4b] Fn + ArrowUp
  5899. keyIdentifierTable['U+000C'] = { code: 'PageDown' }; // [USB: 0x4e] Fn + ArrowDown
  5900. }
  5901. //--------------------------------------------------------------------
  5902. //
  5903. // Location Mappings
  5904. //
  5905. //--------------------------------------------------------------------
  5906. // Cases where newer-ish browsers send location/keyLocation which
  5907. // can be used to disambiguate keys.
  5908. // locationTable[location][keyCode] -> keyInfo
  5909. var locationTable = [];
  5910. locationTable[LEFT] = {
  5911. 0x10: { code: 'ShiftLeft', location: LEFT }, // [USB: 0xe1]
  5912. 0x11: { code: 'ControlLeft', location: LEFT }, // [USB: 0xe0]
  5913. 0x12: { code: 'AltLeft', location: LEFT // [USB: 0xe2]
  5914. } };
  5915. locationTable[RIGHT] = {
  5916. 0x10: { code: 'ShiftRight', location: RIGHT }, // [USB: 0xe5]
  5917. 0x11: { code: 'ControlRight', location: RIGHT }, // [USB: 0xe4]
  5918. 0x12: { code: 'AltRight', location: RIGHT // [USB: 0xe6]
  5919. } };
  5920. locationTable[NUMPAD] = {
  5921. 0x0D: { code: 'NumpadEnter', location: NUMPAD // [USB: 0x58]
  5922. } };
  5923. mergeIf(locationTable[NUMPAD], 'moz', {
  5924. 0x6D: { code: 'NumpadSubtract', location: NUMPAD }, // [USB: 0x56]
  5925. 0x6B: { code: 'NumpadAdd', location: NUMPAD // [USB: 0x57]
  5926. } });
  5927. mergeIf(locationTable[LEFT], 'moz-mac', {
  5928. 0xE0: { code: 'OSLeft', location: LEFT // [USB: 0xe3]
  5929. } });
  5930. mergeIf(locationTable[RIGHT], 'moz-mac', {
  5931. 0xE0: { code: 'OSRight', location: RIGHT // [USB: 0xe7]
  5932. } });
  5933. mergeIf(locationTable[RIGHT], 'moz-win', {
  5934. 0x5B: { code: 'OSRight', location: RIGHT // [USB: 0xe7]
  5935. } });
  5936. mergeIf(locationTable[RIGHT], 'mac', {
  5937. 0x5D: { code: 'OSRight', location: RIGHT // [USB: 0xe7]
  5938. } });
  5939. mergeIf(locationTable[NUMPAD], 'chrome-mac', {
  5940. 0x0C: { code: 'NumLock', location: NUMPAD // [USB: 0x53]
  5941. } });
  5942. mergeIf(locationTable[NUMPAD], 'safari-mac', {
  5943. 0x0C: { code: 'NumLock', location: NUMPAD }, // [USB: 0x53]
  5944. 0xBB: { code: 'NumpadAdd', location: NUMPAD }, // [USB: 0x57]
  5945. 0xBD: { code: 'NumpadSubtract', location: NUMPAD }, // [USB: 0x56]
  5946. 0xBE: { code: 'NumpadDecimal', location: NUMPAD }, // [USB: 0x63]
  5947. 0xBF: { code: 'NumpadDivide', location: NUMPAD // [USB: 0x54]
  5948. } });
  5949. //--------------------------------------------------------------------
  5950. //
  5951. // Key Values
  5952. //
  5953. //--------------------------------------------------------------------
  5954. // Mapping from `code` values to `key` values. Values defined at:
  5955. // https://dvcs.w3.org/hg/dom3events/raw-file/tip/html/DOM3Events-key.html
  5956. // Entries are only provided when `key` differs from `code`. If
  5957. // printable, `shiftKey` has the shifted printable character. This
  5958. // assumes US Standard 101 layout
  5959. var codeToKeyTable = {
  5960. // Modifier Keys
  5961. ShiftLeft: { key: 'Shift' },
  5962. ShiftRight: { key: 'Shift' },
  5963. ControlLeft: { key: 'Control' },
  5964. ControlRight: { key: 'Control' },
  5965. AltLeft: { key: 'Alt' },
  5966. AltRight: { key: 'Alt' },
  5967. OSLeft: { key: 'OS' },
  5968. OSRight: { key: 'OS' },
  5969. // Whitespace Keys
  5970. NumpadEnter: { key: 'Enter' },
  5971. Space: { key: ' ' },
  5972. // Printable Keys
  5973. Digit0: { key: '0', shiftKey: ')' },
  5974. Digit1: { key: '1', shiftKey: '!' },
  5975. Digit2: { key: '2', shiftKey: '@' },
  5976. Digit3: { key: '3', shiftKey: '#' },
  5977. Digit4: { key: '4', shiftKey: '$' },
  5978. Digit5: { key: '5', shiftKey: '%' },
  5979. Digit6: { key: '6', shiftKey: '^' },
  5980. Digit7: { key: '7', shiftKey: '&' },
  5981. Digit8: { key: '8', shiftKey: '*' },
  5982. Digit9: { key: '9', shiftKey: '(' },
  5983. KeyA: { key: 'a', shiftKey: 'A' },
  5984. KeyB: { key: 'b', shiftKey: 'B' },
  5985. KeyC: { key: 'c', shiftKey: 'C' },
  5986. KeyD: { key: 'd', shiftKey: 'D' },
  5987. KeyE: { key: 'e', shiftKey: 'E' },
  5988. KeyF: { key: 'f', shiftKey: 'F' },
  5989. KeyG: { key: 'g', shiftKey: 'G' },
  5990. KeyH: { key: 'h', shiftKey: 'H' },
  5991. KeyI: { key: 'i', shiftKey: 'I' },
  5992. KeyJ: { key: 'j', shiftKey: 'J' },
  5993. KeyK: { key: 'k', shiftKey: 'K' },
  5994. KeyL: { key: 'l', shiftKey: 'L' },
  5995. KeyM: { key: 'm', shiftKey: 'M' },
  5996. KeyN: { key: 'n', shiftKey: 'N' },
  5997. KeyO: { key: 'o', shiftKey: 'O' },
  5998. KeyP: { key: 'p', shiftKey: 'P' },
  5999. KeyQ: { key: 'q', shiftKey: 'Q' },
  6000. KeyR: { key: 'r', shiftKey: 'R' },
  6001. KeyS: { key: 's', shiftKey: 'S' },
  6002. KeyT: { key: 't', shiftKey: 'T' },
  6003. KeyU: { key: 'u', shiftKey: 'U' },
  6004. KeyV: { key: 'v', shiftKey: 'V' },
  6005. KeyW: { key: 'w', shiftKey: 'W' },
  6006. KeyX: { key: 'x', shiftKey: 'X' },
  6007. KeyY: { key: 'y', shiftKey: 'Y' },
  6008. KeyZ: { key: 'z', shiftKey: 'Z' },
  6009. Numpad0: { key: '0' },
  6010. Numpad1: { key: '1' },
  6011. Numpad2: { key: '2' },
  6012. Numpad3: { key: '3' },
  6013. Numpad4: { key: '4' },
  6014. Numpad5: { key: '5' },
  6015. Numpad6: { key: '6' },
  6016. Numpad7: { key: '7' },
  6017. Numpad8: { key: '8' },
  6018. Numpad9: { key: '9' },
  6019. NumpadMultiply: { key: '*' },
  6020. NumpadAdd: { key: '+' },
  6021. NumpadComma: { key: ',' },
  6022. NumpadSubtract: { key: '-' },
  6023. NumpadDecimal: { key: '.' },
  6024. NumpadDivide: { key: '/' },
  6025. Semicolon: { key: ';', shiftKey: ':' },
  6026. Equal: { key: '=', shiftKey: '+' },
  6027. Comma: { key: ',', shiftKey: '<' },
  6028. Minus: { key: '-', shiftKey: '_' },
  6029. Period: { key: '.', shiftKey: '>' },
  6030. Slash: { key: '/', shiftKey: '?' },
  6031. Backquote: { key: '`', shiftKey: '~' },
  6032. BracketLeft: { key: '[', shiftKey: '{' },
  6033. Backslash: { key: '\\', shiftKey: '|' },
  6034. BracketRight: { key: ']', shiftKey: '}' },
  6035. Quote: { key: '\'', shiftKey: '"' },
  6036. IntlBackslash: { key: '\\', shiftKey: '|' }
  6037. };
  6038. mergeIf(codeToKeyTable, 'mac', {
  6039. OSLeft: { key: 'Meta' },
  6040. OSRight: { key: 'Meta' }
  6041. });
  6042. // Corrections for 'key' names in older browsers (e.g. FF36-)
  6043. // https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent.key#Key_values
  6044. var keyFixTable = {
  6045. Esc: 'Escape',
  6046. Nonconvert: 'NonConvert',
  6047. Left: 'ArrowLeft',
  6048. Up: 'ArrowUp',
  6049. Right: 'ArrowRight',
  6050. Down: 'ArrowDown',
  6051. Del: 'Delete',
  6052. Menu: 'ContextMenu',
  6053. MediaNextTrack: 'MediaTrackNext',
  6054. MediaPreviousTrack: 'MediaTrackPrevious',
  6055. SelectMedia: 'MediaSelect',
  6056. HalfWidth: 'Hankaku',
  6057. FullWidth: 'Zenkaku',
  6058. RomanCharacters: 'Romaji',
  6059. Crsel: 'CrSel',
  6060. Exsel: 'ExSel',
  6061. Zoom: 'ZoomToggle'
  6062. };
  6063. //--------------------------------------------------------------------
  6064. //
  6065. // Exported Functions
  6066. //
  6067. //--------------------------------------------------------------------
  6068. var codeTable = remap(keyCodeToInfoTable, 'code');
  6069. try {
  6070. var nativeLocation = nativeKeyboardEvent && 'location' in new KeyboardEvent('');
  6071. } catch (_) {}
  6072. function keyInfoForEvent(event) {
  6073. var keyCode = 'keyCode' in event ? event.keyCode : 'which' in event ? event.which : 0;
  6074. var keyInfo = function () {
  6075. if (nativeLocation || 'keyLocation' in event) {
  6076. var location = nativeLocation ? event.location : event.keyLocation;
  6077. if (location && keyCode in locationTable[location]) {
  6078. return locationTable[location][keyCode];
  6079. }
  6080. }
  6081. if ('keyIdentifier' in event && event.keyIdentifier in keyIdentifierTable) {
  6082. return keyIdentifierTable[event.keyIdentifier];
  6083. }
  6084. if (keyCode in keyCodeToInfoTable) {
  6085. return keyCodeToInfoTable[keyCode];
  6086. }
  6087. return null;
  6088. }();
  6089. // TODO: Track these down and move to general tables
  6090. if (0) {
  6091. // TODO: Map these for newerish browsers?
  6092. // TODO: iOS only?
  6093. // TODO: Override with more common keyIdentifier name?
  6094. switch (event.keyIdentifier) {
  6095. case 'U+0010':
  6096. keyInfo = { code: 'Function' };break;
  6097. case 'U+001C':
  6098. keyInfo = { code: 'ArrowLeft' };break;
  6099. case 'U+001D':
  6100. keyInfo = { code: 'ArrowRight' };break;
  6101. case 'U+001E':
  6102. keyInfo = { code: 'ArrowUp' };break;
  6103. case 'U+001F':
  6104. keyInfo = { code: 'ArrowDown' };break;
  6105. }
  6106. }
  6107. if (!keyInfo) return null;
  6108. var key = function () {
  6109. var entry = codeToKeyTable[keyInfo.code];
  6110. if (!entry) return keyInfo.code;
  6111. return event.shiftKey && 'shiftKey' in entry ? entry.shiftKey : entry.key;
  6112. }();
  6113. return {
  6114. code: keyInfo.code,
  6115. key: key,
  6116. location: keyInfo.location,
  6117. keyCap: keyInfo.keyCap
  6118. };
  6119. }
  6120. function queryKeyCap(code, locale) {
  6121. code = String(code);
  6122. if (!codeTable.hasOwnProperty(code)) return 'Undefined';
  6123. if (locale && String(locale).toLowerCase() !== 'en-us') throw Error('Unsupported locale');
  6124. var keyInfo = codeTable[code];
  6125. return keyInfo.keyCap || keyInfo.code || 'Undefined';
  6126. }
  6127. if ('KeyboardEvent' in global && 'defineProperty' in Object) {
  6128. (function () {
  6129. function define(o, p, v) {
  6130. if (p in o) return;
  6131. Object.defineProperty(o, p, v);
  6132. }
  6133. define(KeyboardEvent.prototype, 'code', { get: function get() {
  6134. var keyInfo = keyInfoForEvent(this);
  6135. return keyInfo ? keyInfo.code : '';
  6136. } });
  6137. // Fix for nonstandard `key` values (FF36-)
  6138. if ('key' in KeyboardEvent.prototype) {
  6139. var desc = Object.getOwnPropertyDescriptor(KeyboardEvent.prototype, 'key');
  6140. Object.defineProperty(KeyboardEvent.prototype, 'key', { get: function get() {
  6141. var key = desc.get.call(this);
  6142. return keyFixTable.hasOwnProperty(key) ? keyFixTable[key] : key;
  6143. } });
  6144. }
  6145. define(KeyboardEvent.prototype, 'key', { get: function get() {
  6146. var keyInfo = keyInfoForEvent(this);
  6147. return keyInfo && 'key' in keyInfo ? keyInfo.key : 'Unidentified';
  6148. } });
  6149. define(KeyboardEvent.prototype, 'location', { get: function get() {
  6150. var keyInfo = keyInfoForEvent(this);
  6151. return keyInfo && 'location' in keyInfo ? keyInfo.location : STANDARD;
  6152. } });
  6153. define(KeyboardEvent.prototype, 'locale', { get: function get() {
  6154. return '';
  6155. } });
  6156. })();
  6157. }
  6158. if (!('queryKeyCap' in global.KeyboardEvent)) global.KeyboardEvent.queryKeyCap = queryKeyCap;
  6159. // Helper for IE8-
  6160. global.identifyKey = function (event) {
  6161. if ('code' in event) return;
  6162. var keyInfo = keyInfoForEvent(event);
  6163. event.code = keyInfo ? keyInfo.code : '';
  6164. event.key = keyInfo && 'key' in keyInfo ? keyInfo.key : 'Unidentified';
  6165. event.location = 'location' in event ? event.location : 'keyLocation' in event ? event.keyLocation : keyInfo && 'location' in keyInfo ? keyInfo.location : STANDARD;
  6166. event.locale = '';
  6167. };
  6168. })(window);
  6169. },{}],11:[function(require,module,exports){
  6170. 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;
  6171. },{}],12:[function(require,module,exports){
  6172. 'use strict';
  6173. var EPS = 0.1;
  6174. module.exports = AFRAME.registerComponent('checkpoint-controls', {
  6175. schema: {
  6176. enabled: { default: true },
  6177. mode: { default: 'teleport', oneOf: ['teleport', 'animate'] },
  6178. animateSpeed: { default: 3.0 }
  6179. },
  6180. init: function init() {
  6181. this.active = true;
  6182. this.checkpoint = null;
  6183. this.isNavMeshConstrained = false;
  6184. this.offset = new THREE.Vector3();
  6185. this.position = new THREE.Vector3();
  6186. this.targetPosition = new THREE.Vector3();
  6187. },
  6188. play: function play() {
  6189. this.active = true;
  6190. },
  6191. pause: function pause() {
  6192. this.active = false;
  6193. },
  6194. setCheckpoint: function setCheckpoint(checkpoint) {
  6195. var el = this.el;
  6196. if (!this.active) return;
  6197. if (this.checkpoint === checkpoint) return;
  6198. if (this.checkpoint) {
  6199. el.emit('navigation-end', { checkpoint: this.checkpoint });
  6200. }
  6201. this.checkpoint = checkpoint;
  6202. this.sync();
  6203. // Ignore new checkpoint if we're already there.
  6204. if (this.position.distanceTo(this.targetPosition) < EPS) {
  6205. this.checkpoint = null;
  6206. return;
  6207. }
  6208. el.emit('navigation-start', { checkpoint: checkpoint });
  6209. if (this.data.mode === 'teleport') {
  6210. this.el.setAttribute('position', this.targetPosition);
  6211. this.checkpoint = null;
  6212. el.emit('navigation-end', { checkpoint: checkpoint });
  6213. el.components['movement-controls'].updateNavLocation();
  6214. }
  6215. },
  6216. isVelocityActive: function isVelocityActive() {
  6217. return !!(this.active && this.checkpoint);
  6218. },
  6219. getVelocity: function getVelocity() {
  6220. if (!this.active) return;
  6221. var data = this.data;
  6222. var offset = this.offset;
  6223. var position = this.position;
  6224. var targetPosition = this.targetPosition;
  6225. var checkpoint = this.checkpoint;
  6226. this.sync();
  6227. if (position.distanceTo(targetPosition) < EPS) {
  6228. this.checkpoint = null;
  6229. this.el.emit('navigation-end', { checkpoint: checkpoint });
  6230. return offset.set(0, 0, 0);
  6231. }
  6232. offset.setLength(data.animateSpeed);
  6233. return offset;
  6234. },
  6235. sync: function sync() {
  6236. var offset = this.offset;
  6237. var position = this.position;
  6238. var targetPosition = this.targetPosition;
  6239. position.copy(this.el.getAttribute('position'));
  6240. this.checkpoint.object3D.getWorldPosition(targetPosition);
  6241. targetPosition.add(this.checkpoint.components.checkpoint.getOffset());
  6242. offset.copy(targetPosition).sub(position);
  6243. }
  6244. });
  6245. },{}],13:[function(require,module,exports){
  6246. 'use strict';
  6247. /**
  6248. * Gamepad controls for A-Frame.
  6249. *
  6250. * Stripped-down version of: https://github.com/donmccurdy/aframe-gamepad-controls
  6251. *
  6252. * For more information about the Gamepad API, see:
  6253. * https://developer.mozilla.org/en-US/docs/Web/API/Gamepad_API/Using_the_Gamepad_API
  6254. */
  6255. var GamepadButton = require('../../lib/GamepadButton'),
  6256. GamepadButtonEvent = require('../../lib/GamepadButtonEvent');
  6257. var JOYSTICK_EPS = 0.2;
  6258. var Joystick = {
  6259. MOVEMENT: 1,
  6260. ROTATION: 2
  6261. };
  6262. module.exports = AFRAME.registerComponent('gamepad-controls', {
  6263. /*******************************************************************
  6264. * Statics
  6265. */
  6266. GamepadButton: GamepadButton,
  6267. /*******************************************************************
  6268. * Schema
  6269. */
  6270. schema: {
  6271. // Controller 0-3
  6272. controller: { default: 0, oneOf: [0, 1, 2, 3] },
  6273. // Enable/disable features
  6274. enabled: { default: true },
  6275. // Debugging
  6276. debug: { default: false },
  6277. // Heading element for rotation
  6278. camera: { default: '[camera]', type: 'selector' },
  6279. // Rotation sensitivity
  6280. rotationSensitivity: { default: 2.0 }
  6281. },
  6282. /*******************************************************************
  6283. * Core
  6284. */
  6285. /**
  6286. * Called once when component is attached. Generally for initial setup.
  6287. */
  6288. init: function init() {
  6289. var sceneEl = this.el.sceneEl;
  6290. this.system = sceneEl.systems['tracked-controls-webxr'] || { controllers: [] };
  6291. this.prevTime = window.performance.now();
  6292. // Button state
  6293. this.buttons = {};
  6294. // Rotation
  6295. var rotation = this.el.object3D.rotation;
  6296. this.pitch = new THREE.Object3D();
  6297. this.pitch.rotation.x = THREE.Math.degToRad(rotation.x);
  6298. this.yaw = new THREE.Object3D();
  6299. this.yaw.position.y = 10;
  6300. this.yaw.rotation.y = THREE.Math.degToRad(rotation.y);
  6301. this.yaw.add(this.pitch);
  6302. this._lookVector = new THREE.Vector2();
  6303. this._moveVector = new THREE.Vector2();
  6304. this._dpadVector = new THREE.Vector2();
  6305. sceneEl.addBehavior(this);
  6306. },
  6307. /**
  6308. * Called when component is attached and when component data changes.
  6309. * Generally modifies the entity based on the data.
  6310. */
  6311. update: function update() {
  6312. this.tick();
  6313. },
  6314. /**
  6315. * Called on each iteration of main render loop.
  6316. */
  6317. tick: function tick(t, dt) {
  6318. this.updateButtonState();
  6319. this.updateRotation(dt);
  6320. },
  6321. /**
  6322. * Called when a component is removed (e.g., via removeAttribute).
  6323. * Generally undoes all modifications to the entity.
  6324. */
  6325. remove: function remove() {},
  6326. /*******************************************************************
  6327. * Movement
  6328. */
  6329. isVelocityActive: function isVelocityActive() {
  6330. if (!this.data.enabled || !this.isConnected()) return false;
  6331. var dpad = this._dpadVector;
  6332. var joystick = this._moveVector;
  6333. this.getDpad(dpad);
  6334. this.getJoystick(Joystick.MOVEMENT, joystick);
  6335. var inputX = dpad.x || joystick.x;
  6336. var inputY = dpad.y || joystick.y;
  6337. return Math.abs(inputX) > JOYSTICK_EPS || Math.abs(inputY) > JOYSTICK_EPS;
  6338. },
  6339. getVelocityDelta: function getVelocityDelta() {
  6340. var dpad = this._dpadVector;
  6341. var joystick = this._moveVector;
  6342. this.getDpad(dpad);
  6343. this.getJoystick(Joystick.MOVEMENT, joystick);
  6344. var inputX = dpad.x || joystick.x;
  6345. var inputY = dpad.y || joystick.y;
  6346. var dVelocity = new THREE.Vector3();
  6347. if (Math.abs(inputX) > JOYSTICK_EPS) {
  6348. dVelocity.x += inputX;
  6349. }
  6350. if (Math.abs(inputY) > JOYSTICK_EPS) {
  6351. dVelocity.z += inputY;
  6352. }
  6353. return dVelocity;
  6354. },
  6355. /*******************************************************************
  6356. * Rotation
  6357. */
  6358. isRotationActive: function isRotationActive() {
  6359. if (!this.data.enabled || !this.isConnected()) return false;
  6360. var joystick = this._lookVector;
  6361. this.getJoystick(Joystick.ROTATION, joystick);
  6362. return Math.abs(joystick.x) > JOYSTICK_EPS || Math.abs(joystick.y) > JOYSTICK_EPS;
  6363. },
  6364. updateRotation: function updateRotation(dt) {
  6365. if (!this.isRotationActive()) return;
  6366. var data = this.data;
  6367. var yaw = this.yaw;
  6368. var pitch = this.pitch;
  6369. var lookControls = data.camera.components['look-controls'];
  6370. var hasLookControls = lookControls && lookControls.pitchObject && lookControls.yawObject;
  6371. // Sync with look-controls pitch/yaw if available.
  6372. if (hasLookControls) {
  6373. pitch.rotation.copy(lookControls.pitchObject.rotation);
  6374. yaw.rotation.copy(lookControls.yawObject.rotation);
  6375. }
  6376. var lookVector = this._lookVector;
  6377. this.getJoystick(Joystick.ROTATION, lookVector);
  6378. if (Math.abs(lookVector.x) <= JOYSTICK_EPS) lookVector.x = 0;
  6379. if (Math.abs(lookVector.y) <= JOYSTICK_EPS) lookVector.y = 0;
  6380. lookVector.multiplyScalar(data.rotationSensitivity * dt / 1000);
  6381. yaw.rotation.y -= lookVector.x;
  6382. pitch.rotation.x -= lookVector.y;
  6383. pitch.rotation.x = Math.max(-Math.PI / 2, Math.min(Math.PI / 2, pitch.rotation.x));
  6384. data.camera.object3D.rotation.set(pitch.rotation.x, yaw.rotation.y, 0);
  6385. // Sync with look-controls pitch/yaw if available.
  6386. if (hasLookControls) {
  6387. lookControls.pitchObject.rotation.copy(pitch.rotation);
  6388. lookControls.yawObject.rotation.copy(yaw.rotation);
  6389. }
  6390. },
  6391. /*******************************************************************
  6392. * Button events
  6393. */
  6394. updateButtonState: function updateButtonState() {
  6395. var gamepad = this.getGamepad();
  6396. if (this.data.enabled && gamepad) {
  6397. // Fire DOM events for button state changes.
  6398. for (var i = 0; i < gamepad.buttons.length; i++) {
  6399. if (gamepad.buttons[i].pressed && !this.buttons[i]) {
  6400. this.emit(new GamepadButtonEvent('gamepadbuttondown', i, gamepad.buttons[i]));
  6401. } else if (!gamepad.buttons[i].pressed && this.buttons[i]) {
  6402. this.emit(new GamepadButtonEvent('gamepadbuttonup', i, gamepad.buttons[i]));
  6403. }
  6404. this.buttons[i] = gamepad.buttons[i].pressed;
  6405. }
  6406. } else if (Object.keys(this.buttons)) {
  6407. // Reset state if controls are disabled or controller is lost.
  6408. this.buttons = {};
  6409. }
  6410. },
  6411. emit: function emit(event) {
  6412. // Emit original event.
  6413. this.el.emit(event.type, event);
  6414. // Emit convenience event, identifying button index.
  6415. this.el.emit(event.type + ':' + event.index, new GamepadButtonEvent(event.type, event.index, event));
  6416. },
  6417. /*******************************************************************
  6418. * Gamepad state
  6419. */
  6420. /**
  6421. * Returns the Gamepad instance attached to the component. If connected,
  6422. * a proxy-controls component may provide access to Gamepad input from a
  6423. * remote device.
  6424. *
  6425. * @return {Gamepad}
  6426. */
  6427. getGamepad: function getGamepad() {
  6428. var stdGamepad = navigator.getGamepads && navigator.getGamepads()[this.data.controller],
  6429. xrController = this.system.controllers[this.data.controller],
  6430. xrGamepad = xrController && xrController.gamepad,
  6431. proxyControls = this.el.sceneEl.components['proxy-controls'],
  6432. proxyGamepad = proxyControls && proxyControls.isConnected() && proxyControls.getGamepad(this.data.controller);
  6433. return proxyGamepad || xrGamepad || stdGamepad;
  6434. },
  6435. /**
  6436. * Returns the state of the given button.
  6437. * @param {number} index The button (0-N) for which to find state.
  6438. * @return {GamepadButton}
  6439. */
  6440. getButton: function getButton(index) {
  6441. return this.getGamepad().buttons[index];
  6442. },
  6443. /**
  6444. * Returns state of the given axis. Axes are labelled 0-N, where 0-1 will
  6445. * represent X/Y on the first joystick, and 2-3 X/Y on the second.
  6446. * @param {number} index The axis (0-N) for which to find state.
  6447. * @return {number} On the interval [-1,1].
  6448. */
  6449. getAxis: function getAxis(index) {
  6450. return this.getGamepad().axes[index];
  6451. },
  6452. /**
  6453. * Returns the state of the specified joystick as a THREE.Vector2.
  6454. * @param {Joystick} role
  6455. * @param {THREE.Vector2} target
  6456. * @return {THREE.Vector2}
  6457. */
  6458. getJoystick: function getJoystick(index, target) {
  6459. var gamepad = this.getGamepad();
  6460. if (gamepad.mapping === 'xr-standard') {
  6461. // See: https://github.com/donmccurdy/aframe-extras/issues/307
  6462. switch (index) {
  6463. case Joystick.MOVEMENT:
  6464. return target.set(gamepad.axes[2], gamepad.axes[3]);
  6465. case Joystick.ROTATION:
  6466. return target.set(gamepad.axes[0], gamepad.axes[1]);
  6467. }
  6468. } else {
  6469. switch (index) {
  6470. case Joystick.MOVEMENT:
  6471. return target.set(gamepad.axes[0], gamepad.axes[1]);
  6472. case Joystick.ROTATION:
  6473. return target.set(gamepad.axes[2], gamepad.axes[3]);
  6474. }
  6475. }
  6476. throw new Error('Unexpected joystick index "%d".', index);
  6477. },
  6478. /**
  6479. * Returns the state of the dpad as a THREE.Vector2.
  6480. * @param {THREE.Vector2} target
  6481. * @return {THREE.Vector2}
  6482. */
  6483. getDpad: function getDpad(target) {
  6484. var gamepad = this.getGamepad();
  6485. if (!gamepad.buttons[GamepadButton.DPAD_RIGHT]) {
  6486. return target.set(0, 0);
  6487. }
  6488. return target.set((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));
  6489. },
  6490. /**
  6491. * Returns true if the gamepad is currently connected to the system.
  6492. * @return {boolean}
  6493. */
  6494. isConnected: function isConnected() {
  6495. var gamepad = this.getGamepad();
  6496. return !!(gamepad && gamepad.connected);
  6497. },
  6498. /**
  6499. * Returns a string containing some information about the controller. Result
  6500. * may vary across browsers, for a given controller.
  6501. * @return {string}
  6502. */
  6503. getID: function getID() {
  6504. return this.getGamepad().id;
  6505. }
  6506. });
  6507. },{"../../lib/GamepadButton":5,"../../lib/GamepadButtonEvent":6}],14:[function(require,module,exports){
  6508. 'use strict';
  6509. require('./checkpoint-controls');
  6510. require('./gamepad-controls');
  6511. require('./keyboard-controls');
  6512. require('./touch-controls');
  6513. require('./movement-controls');
  6514. require('./trackpad-controls');
  6515. },{"./checkpoint-controls":12,"./gamepad-controls":13,"./keyboard-controls":15,"./movement-controls":16,"./touch-controls":17,"./trackpad-controls":18}],15:[function(require,module,exports){
  6516. 'use strict';
  6517. require('../../lib/keyboard.polyfill');
  6518. var MAX_DELTA = 0.2,
  6519. PROXY_FLAG = '__keyboard-controls-proxy';
  6520. var KeyboardEvent = window.KeyboardEvent;
  6521. /**
  6522. * Keyboard Controls component.
  6523. *
  6524. * Stripped-down version of: https://github.com/donmccurdy/aframe-keyboard-controls
  6525. *
  6526. * Bind keyboard events to components, or control your entities with the WASD keys.
  6527. *
  6528. * Why use KeyboardEvent.code? "This is set to a string representing the key that was pressed to
  6529. * generate the KeyboardEvent, without taking the current keyboard layout (e.g., QWERTY vs.
  6530. * Dvorak), locale (e.g., English vs. French), or any modifier keys into account. This is useful
  6531. * when you care about which physical key was pressed, rather thanwhich character it corresponds
  6532. * to. For example, if you’re a writing a game, you might want a certain set of keys to move the
  6533. * player in different directions, and that mapping should ideally be independent of keyboard
  6534. * layout. See: https://developers.google.com/web/updates/2016/04/keyboardevent-keys-codes
  6535. *
  6536. * @namespace wasd-controls
  6537. * keys the entity moves and if you release it will stop. Easing simulates friction.
  6538. * to the entity when pressing the keys.
  6539. * @param {bool} [enabled=true] - To completely enable or disable the controls
  6540. */
  6541. module.exports = AFRAME.registerComponent('keyboard-controls', {
  6542. schema: {
  6543. enabled: { default: true },
  6544. debug: { default: false }
  6545. },
  6546. init: function init() {
  6547. this.dVelocity = new THREE.Vector3();
  6548. this.localKeys = {};
  6549. this.listeners = {
  6550. keydown: this.onKeyDown.bind(this),
  6551. keyup: this.onKeyUp.bind(this),
  6552. blur: this.onBlur.bind(this)
  6553. };
  6554. this.attachEventListeners();
  6555. },
  6556. /*******************************************************************
  6557. * Movement
  6558. */
  6559. isVelocityActive: function isVelocityActive() {
  6560. return this.data.enabled && !!Object.keys(this.getKeys()).length;
  6561. },
  6562. getVelocityDelta: function getVelocityDelta() {
  6563. var data = this.data,
  6564. keys = this.getKeys();
  6565. this.dVelocity.set(0, 0, 0);
  6566. if (data.enabled) {
  6567. if (keys.KeyW || keys.ArrowUp) {
  6568. this.dVelocity.z -= 1;
  6569. }
  6570. if (keys.KeyA || keys.ArrowLeft) {
  6571. this.dVelocity.x -= 1;
  6572. }
  6573. if (keys.KeyS || keys.ArrowDown) {
  6574. this.dVelocity.z += 1;
  6575. }
  6576. if (keys.KeyD || keys.ArrowRight) {
  6577. this.dVelocity.x += 1;
  6578. }
  6579. }
  6580. return this.dVelocity.clone();
  6581. },
  6582. /*******************************************************************
  6583. * Events
  6584. */
  6585. play: function play() {
  6586. this.attachEventListeners();
  6587. },
  6588. pause: function pause() {
  6589. this.removeEventListeners();
  6590. },
  6591. remove: function remove() {
  6592. this.pause();
  6593. },
  6594. attachEventListeners: function attachEventListeners() {
  6595. window.addEventListener('keydown', this.listeners.keydown, false);
  6596. window.addEventListener('keyup', this.listeners.keyup, false);
  6597. window.addEventListener('blur', this.listeners.blur, false);
  6598. },
  6599. removeEventListeners: function removeEventListeners() {
  6600. window.removeEventListener('keydown', this.listeners.keydown);
  6601. window.removeEventListener('keyup', this.listeners.keyup);
  6602. window.removeEventListener('blur', this.listeners.blur);
  6603. },
  6604. onKeyDown: function onKeyDown(event) {
  6605. if (AFRAME.utils.shouldCaptureKeyEvent(event)) {
  6606. this.localKeys[event.code] = true;
  6607. this.emit(event);
  6608. }
  6609. },
  6610. onKeyUp: function onKeyUp(event) {
  6611. if (AFRAME.utils.shouldCaptureKeyEvent(event)) {
  6612. delete this.localKeys[event.code];
  6613. this.emit(event);
  6614. }
  6615. },
  6616. onBlur: function onBlur() {
  6617. for (var code in this.localKeys) {
  6618. if (this.localKeys.hasOwnProperty(code)) {
  6619. delete this.localKeys[code];
  6620. }
  6621. }
  6622. },
  6623. emit: function emit(event) {
  6624. // TODO - keydown only initially?
  6625. // TODO - where the f is the spacebar
  6626. // Emit original event.
  6627. if (PROXY_FLAG in event) {
  6628. // TODO - Method never triggered.
  6629. this.el.emit(event.type, event);
  6630. }
  6631. // Emit convenience event, identifying key.
  6632. this.el.emit(event.type + ':' + event.code, new KeyboardEvent(event.type, event));
  6633. if (this.data.debug) console.log(event.type + ':' + event.code);
  6634. },
  6635. /*******************************************************************
  6636. * Accessors
  6637. */
  6638. isPressed: function isPressed(code) {
  6639. return code in this.getKeys();
  6640. },
  6641. getKeys: function getKeys() {
  6642. if (this.isProxied()) {
  6643. return this.el.sceneEl.components['proxy-controls'].getKeyboard();
  6644. }
  6645. return this.localKeys;
  6646. },
  6647. isProxied: function isProxied() {
  6648. var proxyControls = this.el.sceneEl.components['proxy-controls'];
  6649. return proxyControls && proxyControls.isConnected();
  6650. }
  6651. });
  6652. },{"../../lib/keyboard.polyfill":10}],16:[function(require,module,exports){
  6653. 'use strict';
  6654. /**
  6655. * Movement Controls
  6656. *
  6657. * @author Don McCurdy <dm@donmccurdy.com>
  6658. */
  6659. var COMPONENT_SUFFIX = '-controls',
  6660. MAX_DELTA = 0.2,
  6661. // ms
  6662. EPS = 10e-6;
  6663. module.exports = AFRAME.registerComponent('movement-controls', {
  6664. /*******************************************************************
  6665. * Schema
  6666. */
  6667. dependencies: ['rotation'],
  6668. schema: {
  6669. enabled: { default: true },
  6670. controls: { default: ['gamepad', 'trackpad', 'keyboard', 'touch'] },
  6671. speed: { default: 0.3, min: 0 },
  6672. fly: { default: false },
  6673. constrainToNavMesh: { default: false },
  6674. camera: { default: '[movement-controls] [camera]', type: 'selector' }
  6675. },
  6676. /*******************************************************************
  6677. * Lifecycle
  6678. */
  6679. init: function init() {
  6680. var el = this.el;
  6681. this.velocityCtrl = null;
  6682. this.velocity = new THREE.Vector3();
  6683. this.heading = new THREE.Quaternion();
  6684. // Navigation
  6685. this.navGroup = null;
  6686. this.navNode = null;
  6687. if (el.sceneEl.hasLoaded) {
  6688. this.injectControls();
  6689. } else {
  6690. el.sceneEl.addEventListener('loaded', this.injectControls.bind(this));
  6691. }
  6692. },
  6693. update: function update(prevData) {
  6694. var el = this.el;
  6695. var data = this.data;
  6696. var nav = el.sceneEl.systems.nav;
  6697. if (el.sceneEl.hasLoaded) {
  6698. this.injectControls();
  6699. }
  6700. if (nav && data.constrainToNavMesh !== prevData.constrainToNavMesh) {
  6701. data.constrainToNavMesh ? nav.addAgent(this) : nav.removeAgent(this);
  6702. }
  6703. },
  6704. injectControls: function injectControls() {
  6705. var data = this.data;
  6706. var name;
  6707. for (var i = 0; i < data.controls.length; i++) {
  6708. name = data.controls[i] + COMPONENT_SUFFIX;
  6709. if (!this.el.components[name]) {
  6710. this.el.setAttribute(name, '');
  6711. }
  6712. }
  6713. },
  6714. updateNavLocation: function updateNavLocation() {
  6715. this.navGroup = null;
  6716. this.navNode = null;
  6717. },
  6718. /*******************************************************************
  6719. * Tick
  6720. */
  6721. tick: function () {
  6722. var start = new THREE.Vector3();
  6723. var end = new THREE.Vector3();
  6724. var clampedEnd = new THREE.Vector3();
  6725. return function (t, dt) {
  6726. if (!dt) return;
  6727. var el = this.el;
  6728. var data = this.data;
  6729. if (!data.enabled) return;
  6730. this.updateVelocityCtrl();
  6731. var velocityCtrl = this.velocityCtrl;
  6732. var velocity = this.velocity;
  6733. if (!velocityCtrl) return;
  6734. // Update velocity. If FPS is too low, reset.
  6735. if (dt / 1000 > MAX_DELTA) {
  6736. velocity.set(0, 0, 0);
  6737. } else {
  6738. this.updateVelocity(dt);
  6739. }
  6740. if (data.constrainToNavMesh && velocityCtrl.isNavMeshConstrained !== false) {
  6741. if (velocity.lengthSq() < EPS) return;
  6742. start.copy(el.object3D.position);
  6743. end.copy(velocity).multiplyScalar(dt / 1000).add(start);
  6744. var nav = el.sceneEl.systems.nav;
  6745. this.navGroup = this.navGroup === null ? nav.getGroup(start) : this.navGroup;
  6746. this.navNode = this.navNode || nav.getNode(start, this.navGroup);
  6747. this.navNode = nav.clampStep(start, end, this.navGroup, this.navNode, clampedEnd);
  6748. el.object3D.position.copy(clampedEnd);
  6749. } else if (el.hasAttribute('velocity')) {
  6750. el.setAttribute('velocity', velocity);
  6751. } else {
  6752. el.object3D.position.x += velocity.x * dt / 1000;
  6753. el.object3D.position.y += velocity.y * dt / 1000;
  6754. el.object3D.position.z += velocity.z * dt / 1000;
  6755. }
  6756. };
  6757. }(),
  6758. /*******************************************************************
  6759. * Movement
  6760. */
  6761. updateVelocityCtrl: function updateVelocityCtrl() {
  6762. var data = this.data;
  6763. if (data.enabled) {
  6764. for (var i = 0, l = data.controls.length; i < l; i++) {
  6765. var control = this.el.components[data.controls[i] + COMPONENT_SUFFIX];
  6766. if (control && control.isVelocityActive()) {
  6767. this.velocityCtrl = control;
  6768. return;
  6769. }
  6770. }
  6771. this.velocityCtrl = null;
  6772. }
  6773. },
  6774. updateVelocity: function () {
  6775. var vector2 = new THREE.Vector2();
  6776. var quaternion = new THREE.Quaternion();
  6777. return function (dt) {
  6778. var dVelocity = void 0;
  6779. var el = this.el;
  6780. var control = this.velocityCtrl;
  6781. var velocity = this.velocity;
  6782. var data = this.data;
  6783. if (control) {
  6784. if (control.getVelocityDelta) {
  6785. dVelocity = control.getVelocityDelta(dt);
  6786. } else if (control.getVelocity) {
  6787. velocity.copy(control.getVelocity());
  6788. return;
  6789. } else if (control.getPositionDelta) {
  6790. velocity.copy(control.getPositionDelta(dt).multiplyScalar(1000 / dt));
  6791. return;
  6792. } else {
  6793. throw new Error('Incompatible movement controls: ', control);
  6794. }
  6795. }
  6796. if (el.hasAttribute('velocity') && !data.constrainToNavMesh) {
  6797. velocity.copy(this.el.getAttribute('velocity'));
  6798. }
  6799. if (dVelocity && data.enabled) {
  6800. var cameraEl = data.camera;
  6801. // Rotate to heading
  6802. quaternion.copy(cameraEl.object3D.quaternion);
  6803. quaternion.premultiply(el.object3D.quaternion);
  6804. dVelocity.applyQuaternion(quaternion);
  6805. var factor = dVelocity.length();
  6806. if (data.fly) {
  6807. velocity.copy(dVelocity);
  6808. velocity.multiplyScalar(this.data.speed * 16.66667);
  6809. } else {
  6810. vector2.set(dVelocity.x, dVelocity.z);
  6811. vector2.setLength(factor * this.data.speed * 16.66667);
  6812. velocity.x = vector2.x;
  6813. velocity.z = vector2.y;
  6814. }
  6815. }
  6816. };
  6817. }()
  6818. });
  6819. },{}],17:[function(require,module,exports){
  6820. 'use strict';
  6821. /**
  6822. * Touch-to-move-forward controls for mobile.
  6823. */
  6824. module.exports = AFRAME.registerComponent('touch-controls', {
  6825. schema: {
  6826. enabled: { default: true },
  6827. reverseEnabled: { default: true }
  6828. },
  6829. init: function init() {
  6830. this.dVelocity = new THREE.Vector3();
  6831. this.bindMethods();
  6832. this.direction = 0;
  6833. },
  6834. play: function play() {
  6835. this.addEventListeners();
  6836. },
  6837. pause: function pause() {
  6838. this.removeEventListeners();
  6839. this.dVelocity.set(0, 0, 0);
  6840. },
  6841. remove: function remove() {
  6842. this.pause();
  6843. },
  6844. addEventListeners: function addEventListeners() {
  6845. var sceneEl = this.el.sceneEl;
  6846. var canvasEl = sceneEl.canvas;
  6847. if (!canvasEl) {
  6848. sceneEl.addEventListener('render-target-loaded', this.addEventListeners.bind(this));
  6849. return;
  6850. }
  6851. canvasEl.addEventListener('touchstart', this.onTouchStart);
  6852. canvasEl.addEventListener('touchend', this.onTouchEnd);
  6853. },
  6854. removeEventListeners: function removeEventListeners() {
  6855. var canvasEl = this.el.sceneEl && this.el.sceneEl.canvas;
  6856. if (!canvasEl) {
  6857. return;
  6858. }
  6859. canvasEl.removeEventListener('touchstart', this.onTouchStart);
  6860. canvasEl.removeEventListener('touchend', this.onTouchEnd);
  6861. },
  6862. isVelocityActive: function isVelocityActive() {
  6863. return this.data.enabled && !!this.direction;
  6864. },
  6865. getVelocityDelta: function getVelocityDelta() {
  6866. this.dVelocity.z = this.direction;
  6867. return this.dVelocity.clone();
  6868. },
  6869. bindMethods: function bindMethods() {
  6870. this.onTouchStart = this.onTouchStart.bind(this);
  6871. this.onTouchEnd = this.onTouchEnd.bind(this);
  6872. },
  6873. onTouchStart: function onTouchStart(e) {
  6874. this.direction = -1;
  6875. if (this.data.reverseEnabled && e.touches.length === 2) {
  6876. this.direction = 1;
  6877. }
  6878. e.preventDefault();
  6879. },
  6880. onTouchEnd: function onTouchEnd(e) {
  6881. this.direction = 0;
  6882. e.preventDefault();
  6883. }
  6884. });
  6885. },{}],18:[function(require,module,exports){
  6886. 'use strict';
  6887. /**
  6888. * 3dof (Gear VR, Daydream) controls for mobile.
  6889. */
  6890. module.exports = AFRAME.registerComponent('trackpad-controls', {
  6891. schema: {
  6892. enabled: { default: true },
  6893. enableNegX: { default: true },
  6894. enablePosX: { default: true },
  6895. enableNegZ: { default: true },
  6896. enablePosZ: { default: true },
  6897. mode: { default: 'touch', oneOf: ['swipe', 'touch', 'press'] }
  6898. },
  6899. init: function init() {
  6900. this.dVelocity = new THREE.Vector3();
  6901. this.zVel = 0;
  6902. this.xVel = 0;
  6903. this.bindMethods();
  6904. },
  6905. play: function play() {
  6906. this.addEventListeners();
  6907. },
  6908. pause: function pause() {
  6909. this.removeEventListeners();
  6910. this.dVelocity.set(0, 0, 0);
  6911. },
  6912. remove: function remove() {
  6913. this.pause();
  6914. },
  6915. addEventListeners: function addEventListeners() {
  6916. var data = this.data;
  6917. var sceneEl = this.el.sceneEl;
  6918. sceneEl.addEventListener('axismove', this.onAxisMove);
  6919. switch (data.mode) {
  6920. case 'swipe':
  6921. case 'touch':
  6922. sceneEl.addEventListener('trackpadtouchstart', this.onTouchStart);
  6923. sceneEl.addEventListener('trackpadtouchend', this.onTouchEnd);
  6924. break;
  6925. case 'press':
  6926. sceneEl.addEventListener('trackpaddown', this.onTouchStart);
  6927. sceneEl.addEventListener('trackpadup', this.onTouchEnd);
  6928. break;
  6929. }
  6930. },
  6931. removeEventListeners: function removeEventListeners() {
  6932. var sceneEl = this.el.sceneEl;
  6933. sceneEl.removeEventListener('axismove', this.onAxisMove);
  6934. sceneEl.removeEventListener('trackpadtouchstart', this.onTouchStart);
  6935. sceneEl.removeEventListener('trackpadtouchend', this.onTouchEnd);
  6936. sceneEl.removeEventListener('trackpaddown', this.onTouchStart);
  6937. sceneEl.removeEventListener('trackpadup', this.onTouchEnd);
  6938. },
  6939. isVelocityActive: function isVelocityActive() {
  6940. return this.data.enabled && this.isMoving;
  6941. },
  6942. getVelocityDelta: function getVelocityDelta() {
  6943. this.dVelocity.z = this.isMoving ? -this.zVel : 1;
  6944. this.dVelocity.x = this.isMoving ? this.xVel : 1;
  6945. return this.dVelocity.clone();
  6946. },
  6947. bindMethods: function bindMethods() {
  6948. this.onTouchStart = this.onTouchStart.bind(this);
  6949. this.onTouchEnd = this.onTouchEnd.bind(this);
  6950. this.onAxisMove = this.onAxisMove.bind(this);
  6951. },
  6952. onTouchStart: function onTouchStart(e) {
  6953. switch (this.data.mode) {
  6954. case 'swipe':
  6955. this.canRecordAxis = true;
  6956. this.startingAxisData = [];
  6957. break;
  6958. case 'touch':
  6959. this.isMoving = true;
  6960. break;
  6961. case 'press':
  6962. this.isMoving = true;
  6963. break;
  6964. }
  6965. e.preventDefault();
  6966. },
  6967. onTouchEnd: function onTouchEnd(e) {
  6968. if (this.data.mode == 'swipe') {
  6969. this.startingAxisData = [];
  6970. }
  6971. this.isMoving = false;
  6972. e.preventDefault();
  6973. },
  6974. onAxisMove: function onAxisMove(e) {
  6975. switch (this.data.mode) {
  6976. case 'swipe':
  6977. return this.handleSwipeAxis(e);
  6978. case 'touch':
  6979. case 'press':
  6980. return this.handleTouchAxis(e);
  6981. }
  6982. },
  6983. handleSwipeAxis: function handleSwipeAxis(e) {
  6984. var data = this.data;
  6985. var axisData = e.detail.axis;
  6986. if (this.startingAxisData.length === 0 && this.canRecordAxis) {
  6987. this.canRecordAxis = false;
  6988. this.startingAxisData[0] = axisData[0];
  6989. this.startingAxisData[1] = axisData[1];
  6990. }
  6991. if (this.startingAxisData.length > 0) {
  6992. var velX = 0;
  6993. var velZ = 0;
  6994. if (data.enableNegX && axisData[0] < this.startingAxisData[0]) {
  6995. velX = -1;
  6996. }
  6997. if (data.enablePosX && axisData[0] > this.startingAxisData[0]) {
  6998. velX = 1;
  6999. }
  7000. if (data.enablePosZ && axisData[1] > this.startingAxisData[1]) {
  7001. velZ = -1;
  7002. }
  7003. if (data.enableNegZ && axisData[1] < this.startingAxisData[1]) {
  7004. velZ = 1;
  7005. }
  7006. var absChangeZ = Math.abs(this.startingAxisData[1] - axisData[1]);
  7007. var absChangeX = Math.abs(this.startingAxisData[0] - axisData[0]);
  7008. if (absChangeX > absChangeZ) {
  7009. this.zVel = 0;
  7010. this.xVel = velX;
  7011. this.isMoving = true;
  7012. } else {
  7013. this.xVel = 0;
  7014. this.zVel = velZ;
  7015. this.isMoving = true;
  7016. }
  7017. }
  7018. },
  7019. handleTouchAxis: function handleTouchAxis(e) {
  7020. var data = this.data;
  7021. var axisData = e.detail.axis;
  7022. var velX = 0;
  7023. var velZ = 0;
  7024. if (data.enableNegX && axisData[0] < 0) {
  7025. velX = -1;
  7026. }
  7027. if (data.enablePosX && axisData[0] > 0) {
  7028. velX = 1;
  7029. }
  7030. if (data.enablePosZ && axisData[1] > 0) {
  7031. velZ = -1;
  7032. }
  7033. if (data.enableNegZ && axisData[1] < 0) {
  7034. velZ = 1;
  7035. }
  7036. if (Math.abs(axisData[0]) > Math.abs(axisData[1])) {
  7037. this.zVel = 0;
  7038. this.xVel = velX;
  7039. } else {
  7040. this.xVel = 0;
  7041. this.zVel = velZ;
  7042. }
  7043. }
  7044. });
  7045. },{}],19:[function(require,module,exports){
  7046. 'use strict';
  7047. var LoopMode = {
  7048. once: THREE.LoopOnce,
  7049. repeat: THREE.LoopRepeat,
  7050. pingpong: THREE.LoopPingPong
  7051. };
  7052. /**
  7053. * animation-mixer
  7054. *
  7055. * Player for animation clips. Intended to be compatible with any model format that supports
  7056. * skeletal or morph animations through THREE.AnimationMixer.
  7057. * See: https://threejs.org/docs/?q=animation#Reference/Animation/AnimationMixer
  7058. */
  7059. module.exports = AFRAME.registerComponent('animation-mixer', {
  7060. schema: {
  7061. clip: { default: '*' },
  7062. duration: { default: 0 },
  7063. clampWhenFinished: { default: false, type: 'boolean' },
  7064. crossFadeDuration: { default: 0 },
  7065. loop: { default: 'repeat', oneOf: Object.keys(LoopMode) },
  7066. repetitions: { default: Infinity, min: 0 },
  7067. timeScale: { default: 1 }
  7068. },
  7069. init: function init() {
  7070. var _this = this;
  7071. /** @type {THREE.Mesh} */
  7072. this.model = null;
  7073. /** @type {THREE.AnimationMixer} */
  7074. this.mixer = null;
  7075. /** @type {Array<THREE.AnimationAction>} */
  7076. this.activeActions = [];
  7077. var model = this.el.getObject3D('mesh');
  7078. if (model) {
  7079. this.load(model);
  7080. } else {
  7081. this.el.addEventListener('model-loaded', function (e) {
  7082. _this.load(e.detail.model);
  7083. });
  7084. }
  7085. },
  7086. load: function load(model) {
  7087. var el = this.el;
  7088. this.model = model;
  7089. this.mixer = new THREE.AnimationMixer(model);
  7090. this.mixer.addEventListener('loop', function (e) {
  7091. el.emit('animation-loop', { action: e.action, loopDelta: e.loopDelta });
  7092. });
  7093. this.mixer.addEventListener('finished', function (e) {
  7094. el.emit('animation-finished', { action: e.action, direction: e.direction });
  7095. });
  7096. if (this.data.clip) this.update({});
  7097. },
  7098. remove: function remove() {
  7099. if (this.mixer) this.mixer.stopAllAction();
  7100. },
  7101. update: function update(prevData) {
  7102. if (!prevData) return;
  7103. var data = this.data;
  7104. var changes = AFRAME.utils.diff(data, prevData);
  7105. // If selected clips have changed, restart animation.
  7106. if ('clip' in changes) {
  7107. this.stopAction();
  7108. if (data.clip) this.playAction();
  7109. return;
  7110. }
  7111. // Otherwise, modify running actions.
  7112. this.activeActions.forEach(function (action) {
  7113. if ('duration' in changes && data.duration) {
  7114. action.setDuration(data.duration);
  7115. }
  7116. if ('clampWhenFinished' in changes) {
  7117. action.clampWhenFinished = data.clampWhenFinished;
  7118. }
  7119. if ('loop' in changes || 'repetitions' in changes) {
  7120. action.setLoop(LoopMode[data.loop], data.repetitions);
  7121. }
  7122. if ('timeScale' in changes) {
  7123. action.setEffectiveTimeScale(data.timeScale);
  7124. }
  7125. });
  7126. },
  7127. stopAction: function stopAction() {
  7128. var data = this.data;
  7129. for (var i = 0; i < this.activeActions.length; i++) {
  7130. data.crossFadeDuration ? this.activeActions[i].fadeOut(data.crossFadeDuration) : this.activeActions[i].stop();
  7131. }
  7132. this.activeActions.length = 0;
  7133. },
  7134. playAction: function playAction() {
  7135. if (!this.mixer) return;
  7136. var model = this.model,
  7137. data = this.data,
  7138. clips = model.animations || (model.geometry || {}).animations || [];
  7139. if (!clips.length) return;
  7140. var re = wildcardToRegExp(data.clip);
  7141. for (var clip, i = 0; clip = clips[i]; i++) {
  7142. if (clip.name.match(re)) {
  7143. var action = this.mixer.clipAction(clip, model);
  7144. action.enabled = true;
  7145. action.clampWhenFinished = data.clampWhenFinished;
  7146. if (data.duration) action.setDuration(data.duration);
  7147. if (data.timeScale !== 1) action.setEffectiveTimeScale(data.timeScale);
  7148. action.setLoop(LoopMode[data.loop], data.repetitions).fadeIn(data.crossFadeDuration).play();
  7149. this.activeActions.push(action);
  7150. }
  7151. }
  7152. },
  7153. tick: function tick(t, dt) {
  7154. if (this.mixer && !isNaN(dt)) this.mixer.update(dt / 1000);
  7155. }
  7156. });
  7157. /**
  7158. * Creates a RegExp from the given string, converting asterisks to .* expressions,
  7159. * and escaping all other characters.
  7160. */
  7161. function wildcardToRegExp(s) {
  7162. return new RegExp('^' + s.split(/\*+/).map(regExpEscape).join('.*') + '$');
  7163. }
  7164. /**
  7165. * RegExp-escapes all characters in the given string.
  7166. */
  7167. function regExpEscape(s) {
  7168. return s.replace(/[|\\{}()[\]^$+*?.]/g, '\\$&');
  7169. }
  7170. },{}],20:[function(require,module,exports){
  7171. 'use strict';
  7172. THREE.ColladaLoader = require('../../lib/ColladaLoader');
  7173. /**
  7174. * collada-model-legacy
  7175. *
  7176. * Loader for COLLADA (.dae) format.
  7177. */
  7178. module.exports.Component = AFRAME.registerComponent('collada-model-legacy', {
  7179. schema: { type: 'asset' },
  7180. init: function init() {
  7181. this.model = null;
  7182. this.loader = new THREE.ColladaLoader();
  7183. },
  7184. update: function update() {
  7185. var self = this;
  7186. var el = this.el;
  7187. var src = this.data;
  7188. var rendererSystem = this.el.sceneEl.systems.renderer;
  7189. if (!src) {
  7190. return;
  7191. }
  7192. this.remove();
  7193. this.loader.load(src, function (colladaModel) {
  7194. self.model = colladaModel.scene;
  7195. self.model.traverse(function (object) {
  7196. if (object.isMesh) {
  7197. var material = object.material;
  7198. if (material.color) rendererSystem.applyColorCorrection(material.color);
  7199. if (material.map) rendererSystem.applyColorCorrection(material.map);
  7200. if (material.emissive) rendererSystem.applyColorCorrection(material.emissive);
  7201. if (material.emissiveMap) rendererSystem.applyColorCorrection(material.emissiveMap);
  7202. }
  7203. });
  7204. el.setObject3D('mesh', self.model);
  7205. el.emit('model-loaded', { format: 'collada', model: self.model });
  7206. });
  7207. },
  7208. remove: function remove() {
  7209. if (!this.model) {
  7210. return;
  7211. }
  7212. this.el.removeObject3D('mesh');
  7213. }
  7214. });
  7215. },{"../../lib/ColladaLoader":3}],21:[function(require,module,exports){
  7216. 'use strict';
  7217. THREE.FBXLoader = require('../../lib/FBXLoader');
  7218. /**
  7219. * fbx-model
  7220. *
  7221. * Loader for FBX format. Supports ASCII, but *not* binary, models.
  7222. */
  7223. module.exports = AFRAME.registerComponent('fbx-model', {
  7224. schema: {
  7225. src: { type: 'asset' },
  7226. crossorigin: { default: '' }
  7227. },
  7228. init: function init() {
  7229. this.model = null;
  7230. },
  7231. update: function update() {
  7232. var data = this.data;
  7233. if (!data.src) return;
  7234. this.remove();
  7235. var loader = new THREE.FBXLoader();
  7236. if (data.crossorigin) loader.setCrossOrigin(data.crossorigin);
  7237. loader.load(data.src, this.load.bind(this));
  7238. },
  7239. load: function load(model) {
  7240. this.model = model;
  7241. this.el.setObject3D('mesh', model);
  7242. this.el.emit('model-loaded', { format: 'fbx', model: model });
  7243. },
  7244. remove: function remove() {
  7245. if (this.model) this.el.removeObject3D('mesh');
  7246. }
  7247. });
  7248. },{"../../lib/FBXLoader":4}],22:[function(require,module,exports){
  7249. 'use strict';
  7250. var fetchScript = require('../../lib/fetch-script')();
  7251. var LOADER_SRC = 'https://cdn.jsdelivr.net/gh/mrdoob/three.js@r86/examples/js/loaders/GLTFLoader.js';
  7252. var loadLoader = function () {
  7253. var promise = void 0;
  7254. return function () {
  7255. promise = promise || fetchScript(LOADER_SRC);
  7256. return promise;
  7257. };
  7258. }();
  7259. /**
  7260. * Legacy loader for glTF 1.0 models.
  7261. * Asynchronously loads THREE.GLTFLoader from rawgit.
  7262. */
  7263. module.exports = AFRAME.registerComponent('gltf-model-legacy', {
  7264. schema: { type: 'model' },
  7265. init: function init() {
  7266. var _this = this;
  7267. this.model = null;
  7268. this.loader = null;
  7269. this.loaderPromise = loadLoader().then(function () {
  7270. _this.loader = new THREE.GLTFLoader();
  7271. _this.loader.setCrossOrigin('Anonymous');
  7272. });
  7273. },
  7274. update: function update() {
  7275. var _this2 = this;
  7276. var self = this;
  7277. var el = this.el;
  7278. var src = this.data;
  7279. if (!src) {
  7280. return;
  7281. }
  7282. this.remove();
  7283. this.loaderPromise.then(function () {
  7284. _this2.loader.load(src, function gltfLoaded(gltfModel) {
  7285. self.model = gltfModel.scene;
  7286. self.model.animations = gltfModel.animations;
  7287. el.setObject3D('mesh', self.model);
  7288. el.emit('model-loaded', { format: 'gltf', model: self.model });
  7289. });
  7290. });
  7291. },
  7292. remove: function remove() {
  7293. if (!this.model) {
  7294. return;
  7295. }
  7296. this.el.removeObject3D('mesh');
  7297. }
  7298. });
  7299. },{"../../lib/fetch-script":8}],23:[function(require,module,exports){
  7300. 'use strict';
  7301. require('./animation-mixer');
  7302. require('./collada-model-legacy');
  7303. require('./fbx-model');
  7304. require('./gltf-model-legacy');
  7305. require('./object-model');
  7306. },{"./animation-mixer":19,"./collada-model-legacy":20,"./fbx-model":21,"./gltf-model-legacy":22,"./object-model":24}],24:[function(require,module,exports){
  7307. 'use strict';
  7308. /**
  7309. * object-model
  7310. *
  7311. * Loader for THREE.js JSON format. Somewhat confusingly, there are two different THREE.js formats,
  7312. * both having the .json extension. This loader supports only THREE.ObjectLoader, which typically
  7313. * includes multiple meshes or an entire scene.
  7314. *
  7315. * Check the console for errors, if in doubt. You may need to use `json-model` or
  7316. * `blend-character-model` for some .js and .json files.
  7317. *
  7318. * See: https://clara.io/learn/user-guide/data_exchange/threejs_export
  7319. */
  7320. module.exports = AFRAME.registerComponent('object-model', {
  7321. schema: {
  7322. src: { type: 'asset' },
  7323. crossorigin: { default: '' }
  7324. },
  7325. init: function init() {
  7326. this.model = null;
  7327. },
  7328. update: function update() {
  7329. var _this = this;
  7330. var loader = void 0;
  7331. var data = this.data;
  7332. if (!data.src) return;
  7333. this.remove();
  7334. loader = new THREE.ObjectLoader();
  7335. if (data.crossorigin) loader.setCrossOrigin(data.crossorigin);
  7336. loader.load(data.src, function (object) {
  7337. // Enable skinning, if applicable.
  7338. object.traverse(function (o) {
  7339. if (o instanceof THREE.SkinnedMesh && o.material) {
  7340. o.material.skinning = !!(o.geometry && o.geometry.bones || []).length;
  7341. }
  7342. });
  7343. _this.load(object);
  7344. });
  7345. },
  7346. load: function load(model) {
  7347. this.model = model;
  7348. this.el.setObject3D('mesh', model);
  7349. this.el.emit('model-loaded', { format: 'json', model: model });
  7350. },
  7351. remove: function remove() {
  7352. if (this.model) this.el.removeObject3D('mesh');
  7353. }
  7354. });
  7355. },{}],25:[function(require,module,exports){
  7356. 'use strict';
  7357. module.exports = AFRAME.registerComponent('checkpoint', {
  7358. schema: {
  7359. offset: { default: { x: 0, y: 0, z: 0 }, type: 'vec3' }
  7360. },
  7361. init: function init() {
  7362. this.active = false;
  7363. this.targetEl = null;
  7364. this.fire = this.fire.bind(this);
  7365. this.offset = new THREE.Vector3();
  7366. },
  7367. update: function update() {
  7368. this.offset.copy(this.data.offset);
  7369. },
  7370. play: function play() {
  7371. this.el.addEventListener('click', this.fire);
  7372. },
  7373. pause: function pause() {
  7374. this.el.removeEventListener('click', this.fire);
  7375. },
  7376. remove: function remove() {
  7377. this.pause();
  7378. },
  7379. fire: function fire() {
  7380. var targetEl = this.el.sceneEl.querySelector('[checkpoint-controls]');
  7381. if (!targetEl) {
  7382. throw new Error('No `checkpoint-controls` component found.');
  7383. }
  7384. targetEl.components['checkpoint-controls'].setCheckpoint(this.el);
  7385. },
  7386. getOffset: function getOffset() {
  7387. return this.offset.copy(this.data.offset);
  7388. }
  7389. });
  7390. },{}],26:[function(require,module,exports){
  7391. 'use strict';
  7392. /**
  7393. * @param {Array<THREE.Material>|THREE.Material} material
  7394. * @return {Array<THREE.Material>}
  7395. */
  7396. function ensureMaterialArray(material) {
  7397. if (!material) {
  7398. return [];
  7399. } else if (Array.isArray(material)) {
  7400. return material;
  7401. } else if (material.materials) {
  7402. return material.materials;
  7403. } else {
  7404. return [material];
  7405. }
  7406. }
  7407. /**
  7408. * @param {THREE.Object3D} mesh
  7409. * @param {Array<string>} materialNames
  7410. * @param {THREE.Texture} envMap
  7411. * @param {number} reflectivity [description]
  7412. */
  7413. function applyEnvMap(mesh, materialNames, envMap, reflectivity) {
  7414. if (!mesh) return;
  7415. materialNames = materialNames || [];
  7416. mesh.traverse(function (node) {
  7417. if (!node.isMesh) return;
  7418. var meshMaterials = ensureMaterialArray(node.material);
  7419. meshMaterials.forEach(function (material) {
  7420. if (material && !('envMap' in material)) return;
  7421. if (materialNames.length && materialNames.indexOf(material.name) === -1) return;
  7422. material.envMap = envMap;
  7423. material.reflectivity = reflectivity;
  7424. material.needsUpdate = true;
  7425. });
  7426. });
  7427. }
  7428. /**
  7429. * Specifies an envMap on an entity, without replacing any existing material
  7430. * properties.
  7431. */
  7432. module.exports = AFRAME.registerComponent('cube-env-map', {
  7433. multiple: true,
  7434. schema: {
  7435. path: { default: '' },
  7436. extension: { default: 'jpg', oneOf: ['jpg', 'png'] },
  7437. format: { default: 'RGBFormat', oneOf: ['RGBFormat', 'RGBAFormat'] },
  7438. enableBackground: { default: false },
  7439. reflectivity: { default: 1, min: 0, max: 1 },
  7440. materials: { default: [] }
  7441. },
  7442. init: function init() {
  7443. var _this = this;
  7444. var data = this.data;
  7445. 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]);
  7446. this.texture.format = THREE[data.format];
  7447. this.object3dsetHandler = function () {
  7448. var mesh = _this.el.getObject3D('mesh');
  7449. var data = _this.data;
  7450. applyEnvMap(mesh, data.materials, _this.texture, data.reflectivity);
  7451. };
  7452. this.el.addEventListener('object3dset', this.object3dsetHandler);
  7453. },
  7454. update: function update(oldData) {
  7455. var data = this.data;
  7456. var mesh = this.el.getObject3D('mesh');
  7457. var addedMaterialNames = [];
  7458. var removedMaterialNames = [];
  7459. if (data.materials.length) {
  7460. if (oldData.materials) {
  7461. addedMaterialNames = data.materials.filter(function (name) {
  7462. return !oldData.materials.includes(name);
  7463. });
  7464. removedMaterialNames = oldData.materials.filter(function (name) {
  7465. return !data.materials.includes(name);
  7466. });
  7467. } else {
  7468. addedMaterialNames = data.materials;
  7469. }
  7470. }
  7471. if (addedMaterialNames.length) {
  7472. applyEnvMap(mesh, addedMaterialNames, this.texture, data.reflectivity);
  7473. }
  7474. if (removedMaterialNames.length) {
  7475. applyEnvMap(mesh, removedMaterialNames, null, 1);
  7476. }
  7477. if (oldData.materials && data.reflectivity !== oldData.reflectivity) {
  7478. var maintainedMaterialNames = data.materials.filter(function (name) {
  7479. return oldData.materials.includes(name);
  7480. });
  7481. if (maintainedMaterialNames.length) {
  7482. applyEnvMap(mesh, maintainedMaterialNames, this.texture, data.reflectivity);
  7483. }
  7484. }
  7485. if (this.data.enableBackground && !oldData.enableBackground) {
  7486. this.setBackground(this.texture);
  7487. } else if (!this.data.enableBackground && oldData.enableBackground) {
  7488. this.setBackground(null);
  7489. }
  7490. },
  7491. remove: function remove() {
  7492. this.el.removeEventListener('object3dset', this.object3dsetHandler);
  7493. var mesh = this.el.getObject3D('mesh');
  7494. var data = this.data;
  7495. applyEnvMap(mesh, data.materials, null, 1);
  7496. if (data.enableBackground) this.setBackground(null);
  7497. },
  7498. setBackground: function setBackground(texture) {
  7499. this.el.sceneEl.object3D.background = texture;
  7500. }
  7501. });
  7502. },{}],27:[function(require,module,exports){
  7503. 'use strict';
  7504. /* global CANNON */
  7505. /**
  7506. * Based on aframe/examples/showcase/tracked-controls.
  7507. *
  7508. * Handles events coming from the hand-controls.
  7509. * Determines if the entity is grabbed or released.
  7510. * Updates its position to move along the controller.
  7511. */
  7512. module.exports = AFRAME.registerComponent('grab', {
  7513. init: function init() {
  7514. this.system = this.el.sceneEl.systems.physics;
  7515. this.GRABBED_STATE = 'grabbed';
  7516. this.grabbing = false;
  7517. this.hitEl = /** @type {AFRAME.Element} */null;
  7518. this.physics = /** @type {AFRAME.System} */this.el.sceneEl.systems.physics;
  7519. this.constraint = /** @type {CANNON.Constraint} */null;
  7520. // Bind event handlers
  7521. this.onHit = this.onHit.bind(this);
  7522. this.onGripOpen = this.onGripOpen.bind(this);
  7523. this.onGripClose = this.onGripClose.bind(this);
  7524. },
  7525. play: function play() {
  7526. var el = this.el;
  7527. el.addEventListener('hit', this.onHit);
  7528. el.addEventListener('gripdown', this.onGripClose);
  7529. el.addEventListener('gripup', this.onGripOpen);
  7530. el.addEventListener('trackpaddown', this.onGripClose);
  7531. el.addEventListener('trackpadup', this.onGripOpen);
  7532. el.addEventListener('triggerdown', this.onGripClose);
  7533. el.addEventListener('triggerup', this.onGripOpen);
  7534. },
  7535. pause: function pause() {
  7536. var el = this.el;
  7537. el.removeEventListener('hit', this.onHit);
  7538. el.removeEventListener('gripdown', this.onGripClose);
  7539. el.removeEventListener('gripup', this.onGripOpen);
  7540. el.removeEventListener('trackpaddown', this.onGripClose);
  7541. el.removeEventListener('trackpadup', this.onGripOpen);
  7542. el.removeEventListener('triggerdown', this.onGripClose);
  7543. el.removeEventListener('triggerup', this.onGripOpen);
  7544. },
  7545. onGripClose: function onGripClose() {
  7546. this.grabbing = true;
  7547. },
  7548. onGripOpen: function onGripOpen() {
  7549. var hitEl = this.hitEl;
  7550. this.grabbing = false;
  7551. if (!hitEl) {
  7552. return;
  7553. }
  7554. hitEl.removeState(this.GRABBED_STATE);
  7555. this.hitEl = undefined;
  7556. this.system.removeConstraint(this.constraint);
  7557. this.constraint = null;
  7558. },
  7559. onHit: function onHit(evt) {
  7560. var hitEl = evt.detail.el;
  7561. // If the element is already grabbed (it could be grabbed by another controller).
  7562. // If the hand is not grabbing the element does not stick.
  7563. // If we're already grabbing something you can't grab again.
  7564. if (!hitEl || hitEl.is(this.GRABBED_STATE) || !this.grabbing || this.hitEl) {
  7565. return;
  7566. }
  7567. hitEl.addState(this.GRABBED_STATE);
  7568. this.hitEl = hitEl;
  7569. this.constraint = new CANNON.LockConstraint(this.el.body, hitEl.body);
  7570. this.system.addConstraint(this.constraint);
  7571. }
  7572. });
  7573. },{}],28:[function(require,module,exports){
  7574. 'use strict';
  7575. require('./checkpoint');
  7576. require('./cube-env-map');
  7577. require('./grab');
  7578. require('./jump-ability');
  7579. require('./kinematic-body');
  7580. require('./mesh-smooth');
  7581. require('./normal-material');
  7582. require('./sphere-collider');
  7583. },{"./checkpoint":25,"./cube-env-map":26,"./grab":27,"./jump-ability":29,"./kinematic-body":30,"./mesh-smooth":31,"./normal-material":32,"./sphere-collider":33}],29:[function(require,module,exports){
  7584. 'use strict';
  7585. var ACCEL_G = -9.8,
  7586. // m/s^2
  7587. EASING = -15; // m/s^2
  7588. /**
  7589. * Jump ability.
  7590. */
  7591. module.exports = AFRAME.registerComponent('jump-ability', {
  7592. dependencies: ['velocity'],
  7593. /* Schema
  7594. ——————————————————————————————————————————————*/
  7595. schema: {
  7596. on: { default: 'keydown:Space gamepadbuttondown:0' },
  7597. playerHeight: { default: 1.764 },
  7598. maxJumps: { default: 1 },
  7599. distance: { default: 5 },
  7600. debug: { default: false }
  7601. },
  7602. init: function init() {
  7603. this.velocity = 0;
  7604. this.numJumps = 0;
  7605. var beginJump = this.beginJump.bind(this),
  7606. events = this.data.on.split(' ');
  7607. this.bindings = {};
  7608. for (var i = 0; i < events.length; i++) {
  7609. this.bindings[events[i]] = beginJump;
  7610. this.el.addEventListener(events[i], beginJump);
  7611. }
  7612. this.bindings.collide = this.onCollide.bind(this);
  7613. this.el.addEventListener('collide', this.bindings.collide);
  7614. },
  7615. remove: function remove() {
  7616. for (var event in this.bindings) {
  7617. if (this.bindings.hasOwnProperty(event)) {
  7618. this.el.removeEventListener(event, this.bindings[event]);
  7619. delete this.bindings[event];
  7620. }
  7621. }
  7622. this.el.removeEventListener('collide', this.bindings.collide);
  7623. delete this.bindings.collide;
  7624. },
  7625. beginJump: function beginJump() {
  7626. if (this.numJumps < this.data.maxJumps) {
  7627. var data = this.data,
  7628. initialVelocity = Math.sqrt(-2 * data.distance * (ACCEL_G + EASING)),
  7629. v = this.el.getAttribute('velocity');
  7630. this.el.setAttribute('velocity', { x: v.x, y: initialVelocity, z: v.z });
  7631. this.numJumps++;
  7632. this.el.emit('jumpstart');
  7633. }
  7634. },
  7635. onCollide: function onCollide() {
  7636. if (this.numJumps > 0) this.el.emit('jumpend');
  7637. this.numJumps = 0;
  7638. }
  7639. });
  7640. },{}],30:[function(require,module,exports){
  7641. 'use strict';
  7642. /* global CANNON */
  7643. /**
  7644. * Kinematic body.
  7645. *
  7646. * Managed dynamic body, which moves but is not affected (directly) by the
  7647. * physics engine. This is not a true kinematic body, in the sense that we are
  7648. * letting the physics engine _compute_ collisions against it and selectively
  7649. * applying those collisions to the object. The physics engine does not decide
  7650. * the position/velocity/rotation of the element.
  7651. *
  7652. * Used for the camera object, because full physics simulation would create
  7653. * movement that feels unnatural to the player. Bipedal movement does not
  7654. * translate nicely to rigid body physics.
  7655. *
  7656. * See: http://www.learn-cocos2d.com/2013/08/physics-engine-platformer-terrible-idea/
  7657. * And: http://oxleygamedev.blogspot.com/2011/04/player-physics-part-2.html
  7658. */
  7659. var EPS = 0.000001;
  7660. module.exports = AFRAME.registerComponent('kinematic-body', {
  7661. dependencies: ['velocity'],
  7662. /*******************************************************************
  7663. * Schema
  7664. */
  7665. schema: {
  7666. mass: { default: 5 },
  7667. radius: { default: 1.3 },
  7668. linearDamping: { default: 0.05 },
  7669. enableSlopes: { default: true },
  7670. enableJumps: { default: false }
  7671. },
  7672. /*******************************************************************
  7673. * Lifecycle
  7674. */
  7675. init: function init() {
  7676. this.system = this.el.sceneEl.systems.physics;
  7677. this.system.addComponent(this);
  7678. var el = this.el,
  7679. data = this.data,
  7680. position = new CANNON.Vec3().copy(el.object3D.getWorldPosition(new THREE.Vector3()));
  7681. this.body = new CANNON.Body({
  7682. material: this.system.getMaterial('staticMaterial'),
  7683. position: position,
  7684. mass: data.mass,
  7685. linearDamping: data.linearDamping,
  7686. fixedRotation: true
  7687. });
  7688. this.body.addShape(new CANNON.Sphere(data.radius), new CANNON.Vec3(0, data.radius, 0));
  7689. this.body.el = this.el;
  7690. this.el.body = this.body;
  7691. this.system.addBody(this.body);
  7692. if (el.hasAttribute('wasd-controls')) {
  7693. console.warn('[kinematic-body] Not compatible with wasd-controls, use movement-controls.');
  7694. }
  7695. },
  7696. remove: function remove() {
  7697. this.system.removeBody(this.body);
  7698. this.system.removeComponent(this);
  7699. delete this.el.body;
  7700. },
  7701. /*******************************************************************
  7702. * Update
  7703. */
  7704. /**
  7705. * Checks CANNON.World for collisions and attempts to apply them to the
  7706. * element automatically, in a player-friendly way.
  7707. *
  7708. * There's extra logic for horizontal surfaces here. The basic requirements:
  7709. * (1) Only apply gravity when not in contact with _any_ horizontal surface.
  7710. * (2) When moving, project the velocity against exactly one ground surface.
  7711. * If in contact with two ground surfaces (e.g. ground + ramp), choose
  7712. * the one that collides with current velocity, if any.
  7713. */
  7714. beforeStep: function beforeStep(t, dt) {
  7715. if (!dt) return;
  7716. var el = this.el;
  7717. var data = this.data;
  7718. var body = this.body;
  7719. if (!data.enableJumps) body.velocity.set(0, 0, 0);
  7720. body.position.copy(el.getAttribute('position'));
  7721. },
  7722. step: function () {
  7723. var velocity = new THREE.Vector3(),
  7724. normalizedVelocity = new THREE.Vector3(),
  7725. currentSurfaceNormal = new THREE.Vector3(),
  7726. groundNormal = new THREE.Vector3();
  7727. return function (t, dt) {
  7728. if (!dt) return;
  7729. var body = this.body,
  7730. data = this.data,
  7731. didCollide = false,
  7732. height = void 0,
  7733. groundHeight = -Infinity,
  7734. groundBody = void 0,
  7735. contacts = this.system.getContacts();
  7736. dt = Math.min(dt, this.system.data.maxInterval * 1000);
  7737. groundNormal.set(0, 0, 0);
  7738. velocity.copy(this.el.getAttribute('velocity'));
  7739. body.velocity.copy(velocity);
  7740. for (var i = 0, contact; contact = contacts[i]; i++) {
  7741. // 1. Find any collisions involving this element. Get the contact
  7742. // normal, and make sure it's oriented _out_ of the other object and
  7743. // enabled (body.collisionReponse is true for both bodies)
  7744. if (!contact.enabled) {
  7745. continue;
  7746. }
  7747. if (body.id === contact.bi.id) {
  7748. contact.ni.negate(currentSurfaceNormal);
  7749. } else if (body.id === contact.bj.id) {
  7750. currentSurfaceNormal.copy(contact.ni);
  7751. } else {
  7752. continue;
  7753. }
  7754. didCollide = body.velocity.dot(currentSurfaceNormal) < -EPS;
  7755. if (didCollide && currentSurfaceNormal.y <= 0.5) {
  7756. // 2. If current trajectory attempts to move _through_ another
  7757. // object, project the velocity against the collision plane to
  7758. // prevent passing through.
  7759. velocity.projectOnPlane(currentSurfaceNormal);
  7760. } else if (currentSurfaceNormal.y > 0.5) {
  7761. // 3. If in contact with something roughly horizontal (+/- 45º) then
  7762. // consider that the current ground. Only the highest qualifying
  7763. // ground is retained.
  7764. height = body.id === contact.bi.id ? Math.abs(contact.rj.y + contact.bj.position.y) : Math.abs(contact.ri.y + contact.bi.position.y);
  7765. if (height > groundHeight) {
  7766. groundHeight = height;
  7767. groundNormal.copy(currentSurfaceNormal);
  7768. groundBody = body.id === contact.bi.id ? contact.bj : contact.bi;
  7769. }
  7770. }
  7771. }
  7772. normalizedVelocity.copy(velocity).normalize();
  7773. if (groundBody && (!data.enableJumps || normalizedVelocity.y < 0.5)) {
  7774. if (!data.enableSlopes) {
  7775. groundNormal.set(0, 1, 0);
  7776. } else if (groundNormal.y < 1 - EPS) {
  7777. groundNormal.copy(this.raycastToGround(groundBody, groundNormal));
  7778. }
  7779. // 4. Project trajectory onto the top-most ground object, unless
  7780. // trajectory is > 45º.
  7781. velocity.projectOnPlane(groundNormal);
  7782. } else if (this.system.driver.world) {
  7783. // 5. If not in contact with anything horizontal, apply world gravity.
  7784. // TODO - Why is the 4x scalar necessary.
  7785. // NOTE: Does not work if physics runs on a worker.
  7786. velocity.add(this.system.driver.world.gravity.scale(dt * 4.0 / 1000));
  7787. }
  7788. body.velocity.copy(velocity);
  7789. this.el.setAttribute('velocity', body.velocity);
  7790. this.el.setAttribute('position', body.position);
  7791. };
  7792. }(),
  7793. /**
  7794. * When walking on complex surfaces (trimeshes, borders between two shapes),
  7795. * the collision normals returned for the player sphere can be very
  7796. * inconsistent. To address this, raycast straight down, find the collision
  7797. * normal, and return whichever normal is more vertical.
  7798. * @param {CANNON.Body} groundBody
  7799. * @param {CANNON.Vec3} groundNormal
  7800. * @return {CANNON.Vec3}
  7801. */
  7802. raycastToGround: function raycastToGround(groundBody, groundNormal) {
  7803. var ray = void 0,
  7804. hitNormal = void 0,
  7805. vFrom = this.body.position,
  7806. vTo = this.body.position.clone();
  7807. ray = new CANNON.Ray(vFrom, vTo);
  7808. ray._updateDirection(); // TODO - Report bug.
  7809. ray.intersectBody(groundBody);
  7810. if (!ray.hasHit) return groundNormal;
  7811. // Compare ABS, in case we're projecting against the inside of the face.
  7812. hitNormal = ray.result.hitNormalWorld;
  7813. return Math.abs(hitNormal.y) > Math.abs(groundNormal.y) ? hitNormal : groundNormal;
  7814. }
  7815. });
  7816. },{}],31:[function(require,module,exports){
  7817. 'use strict';
  7818. /**
  7819. * Apply this component to models that looks "blocky", to have Three.js compute
  7820. * vertex normals on the fly for a "smoother" look.
  7821. */
  7822. module.exports = AFRAME.registerComponent('mesh-smooth', {
  7823. init: function init() {
  7824. this.el.addEventListener('model-loaded', function (e) {
  7825. e.detail.model.traverse(function (node) {
  7826. if (node.isMesh) node.geometry.computeVertexNormals();
  7827. });
  7828. });
  7829. }
  7830. });
  7831. },{}],32:[function(require,module,exports){
  7832. 'use strict';
  7833. /**
  7834. * Recursively applies a MeshNormalMaterial to the entity, such that
  7835. * face colors are determined by their orientation. Helpful for
  7836. * debugging geometry
  7837. */
  7838. module.exports = AFRAME.registerComponent('normal-material', {
  7839. init: function init() {
  7840. this.material = new THREE.MeshNormalMaterial({ flatShading: true });
  7841. this.applyMaterial = this.applyMaterial.bind(this);
  7842. this.el.addEventListener('object3dset', this.applyMaterial);
  7843. },
  7844. remove: function remove() {
  7845. this.el.removeEventListener('object3dset', this.applyMaterial);
  7846. },
  7847. applyMaterial: function applyMaterial() {
  7848. var _this = this;
  7849. this.el.object3D.traverse(function (node) {
  7850. if (node.isMesh) node.material = _this.material;
  7851. });
  7852. }
  7853. });
  7854. },{}],33:[function(require,module,exports){
  7855. 'use strict';
  7856. /**
  7857. * Based on aframe/examples/showcase/tracked-controls.
  7858. *
  7859. * Implement bounding sphere collision detection for entities with a mesh.
  7860. * Sets the specified state on the intersected entities.
  7861. *
  7862. * @property {string} objects - Selector of the entities to test for collision.
  7863. * @property {string} state - State to set on collided entities.
  7864. *
  7865. */
  7866. module.exports = AFRAME.registerComponent('sphere-collider', {
  7867. schema: {
  7868. objects: { default: '' },
  7869. state: { default: 'collided' },
  7870. radius: { default: 0.05 },
  7871. watch: { default: true }
  7872. },
  7873. init: function init() {
  7874. /** @type {MutationObserver} */
  7875. this.observer = null;
  7876. /** @type {Array<Element>} Elements to watch for collisions. */
  7877. this.els = [];
  7878. /** @type {Array<Element>} Elements currently in collision state. */
  7879. this.collisions = [];
  7880. this.handleHit = this.handleHit.bind(this);
  7881. this.handleHitEnd = this.handleHitEnd.bind(this);
  7882. },
  7883. remove: function remove() {
  7884. this.pause();
  7885. },
  7886. play: function play() {
  7887. var sceneEl = this.el.sceneEl;
  7888. if (this.data.watch) {
  7889. this.observer = new MutationObserver(this.update.bind(this, null));
  7890. this.observer.observe(sceneEl, { childList: true, subtree: true });
  7891. }
  7892. },
  7893. pause: function pause() {
  7894. if (this.observer) {
  7895. this.observer.disconnect();
  7896. this.observer = null;
  7897. }
  7898. },
  7899. /**
  7900. * Update list of entities to test for collision.
  7901. */
  7902. update: function update() {
  7903. var data = this.data;
  7904. var objectEls = void 0;
  7905. // Push entities into list of els to intersect.
  7906. if (data.objects) {
  7907. objectEls = this.el.sceneEl.querySelectorAll(data.objects);
  7908. } else {
  7909. // If objects not defined, intersect with everything.
  7910. objectEls = this.el.sceneEl.children;
  7911. }
  7912. // Convert from NodeList to Array
  7913. this.els = Array.prototype.slice.call(objectEls);
  7914. },
  7915. tick: function () {
  7916. var position = new THREE.Vector3(),
  7917. meshPosition = new THREE.Vector3(),
  7918. colliderScale = new THREE.Vector3(),
  7919. size = new THREE.Vector3(),
  7920. box = new THREE.Box3(),
  7921. distanceMap = new Map();
  7922. return function () {
  7923. var el = this.el,
  7924. data = this.data,
  7925. mesh = el.getObject3D('mesh'),
  7926. collisions = [];
  7927. var colliderRadius = void 0;
  7928. if (!mesh) {
  7929. return;
  7930. }
  7931. distanceMap.clear();
  7932. el.object3D.getWorldPosition(position);
  7933. el.object3D.getWorldScale(colliderScale);
  7934. colliderRadius = data.radius * scaleFactor(colliderScale);
  7935. // Update collision list.
  7936. this.els.forEach(intersect);
  7937. // Emit events and add collision states, in order of distance.
  7938. collisions.sort(function (a, b) {
  7939. return distanceMap.get(a) > distanceMap.get(b) ? 1 : -1;
  7940. }).forEach(this.handleHit);
  7941. // Remove collision state from current element.
  7942. if (collisions.length === 0) {
  7943. el.emit('hit', { el: null });
  7944. }
  7945. // Remove collision state from other elements.
  7946. this.collisions.filter(function (el) {
  7947. return !distanceMap.has(el);
  7948. }).forEach(this.handleHitEnd);
  7949. // Store new collisions
  7950. this.collisions = collisions;
  7951. // Bounding sphere collision detection
  7952. function intersect(el) {
  7953. var radius = void 0,
  7954. mesh = void 0,
  7955. distance = void 0,
  7956. extent = void 0;
  7957. if (!el.isEntity) {
  7958. return;
  7959. }
  7960. mesh = el.getObject3D('mesh');
  7961. if (!mesh) {
  7962. return;
  7963. }
  7964. box.setFromObject(mesh).getSize(size);
  7965. extent = Math.max(size.x, size.y, size.z) / 2;
  7966. radius = Math.sqrt(2 * extent * extent);
  7967. box.getCenter(meshPosition);
  7968. if (!radius) {
  7969. return;
  7970. }
  7971. distance = position.distanceTo(meshPosition);
  7972. if (distance < radius + colliderRadius) {
  7973. collisions.push(el);
  7974. distanceMap.set(el, distance);
  7975. }
  7976. }
  7977. // use max of scale factors to maintain bounding sphere collision
  7978. function scaleFactor(scaleVec) {
  7979. return Math.max.apply(null, scaleVec.toArray());
  7980. }
  7981. };
  7982. }(),
  7983. handleHit: function handleHit(targetEl) {
  7984. targetEl.emit('hit');
  7985. targetEl.addState(this.data.state);
  7986. this.el.emit('hit', { el: targetEl });
  7987. },
  7988. handleHitEnd: function handleHitEnd(targetEl) {
  7989. targetEl.emit('hitend');
  7990. targetEl.removeState(this.data.state);
  7991. this.el.emit('hitend', { el: targetEl });
  7992. }
  7993. });
  7994. },{}],34:[function(require,module,exports){
  7995. 'use strict';
  7996. require('./nav-mesh');
  7997. require('./nav-agent');
  7998. require('./system');
  7999. },{"./nav-agent":35,"./nav-mesh":36,"./system":37}],35:[function(require,module,exports){
  8000. 'use strict';
  8001. module.exports = AFRAME.registerComponent('nav-agent', {
  8002. schema: {
  8003. destination: { type: 'vec3' },
  8004. active: { default: false },
  8005. speed: { default: 2 }
  8006. },
  8007. init: function init() {
  8008. this.system = this.el.sceneEl.systems.nav;
  8009. this.system.addAgent(this);
  8010. this.group = null;
  8011. this.path = [];
  8012. this.raycaster = new THREE.Raycaster();
  8013. },
  8014. remove: function remove() {
  8015. this.system.removeAgent(this);
  8016. },
  8017. update: function update() {
  8018. this.path.length = 0;
  8019. },
  8020. updateNavLocation: function updateNavLocation() {
  8021. this.group = null;
  8022. this.path = [];
  8023. },
  8024. tick: function () {
  8025. var vDest = new THREE.Vector3();
  8026. var vDelta = new THREE.Vector3();
  8027. var vNext = new THREE.Vector3();
  8028. return function (t, dt) {
  8029. var el = this.el;
  8030. var data = this.data;
  8031. var raycaster = this.raycaster;
  8032. var speed = data.speed * dt / 1000;
  8033. if (!data.active) return;
  8034. // Use PatrolJS pathfinding system to get shortest path to target.
  8035. if (!this.path.length) {
  8036. var position = this.el.object3D.position;
  8037. this.group = this.group || this.system.getGroup(position);
  8038. this.path = this.system.getPath(position, vDest.copy(data.destination), this.group) || [];
  8039. el.emit('navigation-start');
  8040. }
  8041. // If no path is found, exit.
  8042. if (!this.path.length) {
  8043. console.warn('[nav] Unable to find path to %o.', data.destination);
  8044. this.el.setAttribute('nav-agent', { active: false });
  8045. el.emit('navigation-end');
  8046. return;
  8047. }
  8048. // Current segment is a vector from current position to next waypoint.
  8049. var vCurrent = el.object3D.position;
  8050. var vWaypoint = this.path[0];
  8051. vDelta.subVectors(vWaypoint, vCurrent);
  8052. var distance = vDelta.length();
  8053. var gazeTarget = void 0;
  8054. if (distance < speed) {
  8055. // If <1 step from current waypoint, discard it and move toward next.
  8056. this.path.shift();
  8057. // After discarding the last waypoint, exit pathfinding.
  8058. if (!this.path.length) {
  8059. this.el.setAttribute('nav-agent', { active: false });
  8060. el.emit('navigation-end');
  8061. return;
  8062. }
  8063. vNext.copy(vCurrent);
  8064. gazeTarget = this.path[0];
  8065. } else {
  8066. // If still far away from next waypoint, find next position for
  8067. // the current frame.
  8068. vNext.copy(vDelta.setLength(speed)).add(vCurrent);
  8069. gazeTarget = vWaypoint;
  8070. }
  8071. // Look at the next waypoint.
  8072. gazeTarget.y = vCurrent.y;
  8073. el.object3D.lookAt(gazeTarget);
  8074. // Raycast against the nav mesh, to keep the agent moving along the
  8075. // ground, not traveling in a straight line from higher to lower waypoints.
  8076. raycaster.ray.origin.copy(vNext);
  8077. raycaster.ray.origin.y += 1.5;
  8078. raycaster.ray.direction.y = -1;
  8079. var intersections = raycaster.intersectObject(this.system.getNavMesh());
  8080. if (!intersections.length) {
  8081. // Raycasting failed. Step toward the waypoint and hope for the best.
  8082. vCurrent.copy(vNext);
  8083. } else {
  8084. // Re-project next position onto nav mesh.
  8085. vDelta.subVectors(intersections[0].point, vCurrent);
  8086. vCurrent.add(vDelta.setLength(speed));
  8087. }
  8088. };
  8089. }()
  8090. });
  8091. },{}],36:[function(require,module,exports){
  8092. 'use strict';
  8093. /**
  8094. * nav-mesh
  8095. *
  8096. * Waits for a mesh to be loaded on the current entity, then sets it as the
  8097. * nav mesh in the pathfinding system.
  8098. */
  8099. module.exports = AFRAME.registerComponent('nav-mesh', {
  8100. init: function init() {
  8101. this.system = this.el.sceneEl.systems.nav;
  8102. this.hasLoadedNavMesh = false;
  8103. this.el.addEventListener('object3dset', this.loadNavMesh.bind(this));
  8104. },
  8105. play: function play() {
  8106. if (!this.hasLoadedNavMesh) this.loadNavMesh();
  8107. },
  8108. loadNavMesh: function loadNavMesh() {
  8109. var object = this.el.getObject3D('mesh');
  8110. var scene = this.el.sceneEl.object3D;
  8111. if (!object) return;
  8112. var navMesh = void 0;
  8113. object.traverse(function (node) {
  8114. if (node.isMesh) navMesh = node;
  8115. });
  8116. if (!navMesh) return;
  8117. var navMeshGeometry = navMesh.geometry.isBufferGeometry ? new THREE.Geometry().fromBufferGeometry(navMesh.geometry) : navMesh.geometry.clone();
  8118. scene.updateMatrixWorld();
  8119. navMeshGeometry.applyMatrix(navMesh.matrixWorld);
  8120. this.system.setNavMeshGeometry(navMeshGeometry);
  8121. this.hasLoadedNavMesh = true;
  8122. }
  8123. });
  8124. },{}],37:[function(require,module,exports){
  8125. 'use strict';
  8126. var _require = require('three-pathfinding'),
  8127. Pathfinding = _require.Pathfinding;
  8128. var pathfinder = new Pathfinding();
  8129. var ZONE = 'level';
  8130. /**
  8131. * nav
  8132. *
  8133. * Pathfinding system, using PatrolJS.
  8134. */
  8135. module.exports = AFRAME.registerSystem('nav', {
  8136. init: function init() {
  8137. this.navMesh = null;
  8138. this.agents = new Set();
  8139. },
  8140. /**
  8141. * @param {THREE.Geometry} geometry
  8142. */
  8143. setNavMeshGeometry: function setNavMeshGeometry(geometry) {
  8144. this.navMesh = new THREE.Mesh(geometry);
  8145. pathfinder.setZoneData(ZONE, Pathfinding.createZone(geometry));
  8146. Array.from(this.agents).forEach(function (agent) {
  8147. return agent.updateNavLocation();
  8148. });
  8149. },
  8150. /**
  8151. * @return {THREE.Mesh}
  8152. */
  8153. getNavMesh: function getNavMesh() {
  8154. return this.navMesh;
  8155. },
  8156. /**
  8157. * @param {NavAgent} ctrl
  8158. */
  8159. addAgent: function addAgent(ctrl) {
  8160. this.agents.add(ctrl);
  8161. },
  8162. /**
  8163. * @param {NavAgent} ctrl
  8164. */
  8165. removeAgent: function removeAgent(ctrl) {
  8166. this.agents.delete(ctrl);
  8167. },
  8168. /**
  8169. * @param {THREE.Vector3} start
  8170. * @param {THREE.Vector3} end
  8171. * @param {number} groupID
  8172. * @return {Array<THREE.Vector3>}
  8173. */
  8174. getPath: function getPath(start, end, groupID) {
  8175. return this.navMesh ? pathfinder.findPath(start, end, ZONE, groupID) : null;
  8176. },
  8177. /**
  8178. * @param {THREE.Vector3} position
  8179. * @return {number}
  8180. */
  8181. getGroup: function getGroup(position) {
  8182. return this.navMesh ? pathfinder.getGroup(ZONE, position) : null;
  8183. },
  8184. /**
  8185. * @param {THREE.Vector3} position
  8186. * @param {number} groupID
  8187. * @return {Node}
  8188. */
  8189. getNode: function getNode(position, groupID) {
  8190. return this.navMesh ? pathfinder.getClosestNode(position, ZONE, groupID, true) : null;
  8191. },
  8192. /**
  8193. * @param {THREE.Vector3} start Starting position.
  8194. * @param {THREE.Vector3} end Desired ending position.
  8195. * @param {number} groupID
  8196. * @param {Node} node
  8197. * @param {THREE.Vector3} endTarget (Output) Adjusted step end position.
  8198. * @return {Node} Current node, after step is taken.
  8199. */
  8200. clampStep: function clampStep(start, end, groupID, node, endTarget) {
  8201. if (!this.navMesh) {
  8202. endTarget.copy(end);
  8203. return null;
  8204. } else if (!node) {
  8205. endTarget.copy(end);
  8206. return this.getNode(end, groupID);
  8207. }
  8208. return pathfinder.clampStep(start, end, node, ZONE, groupID, endTarget);
  8209. }
  8210. });
  8211. },{"three-pathfinding":11}],38:[function(require,module,exports){
  8212. 'use strict';
  8213. /**
  8214. * Flat grid.
  8215. *
  8216. * Defaults to 75x75.
  8217. */
  8218. module.exports = AFRAME.registerPrimitive('a-grid', {
  8219. defaultComponents: {
  8220. geometry: {
  8221. primitive: 'plane',
  8222. width: 75,
  8223. height: 75
  8224. },
  8225. rotation: { x: -90, y: 0, z: 0 },
  8226. material: {
  8227. src: 'url(https://cdn.jsdelivr.net/gh/donmccurdy/aframe-extras@v1.16.3/assets/grid.png)',
  8228. repeat: '75 75'
  8229. }
  8230. },
  8231. mappings: {
  8232. width: 'geometry.width',
  8233. height: 'geometry.height',
  8234. src: 'material.src'
  8235. }
  8236. });
  8237. },{}],39:[function(require,module,exports){
  8238. 'use strict';
  8239. var vg = require('../../lib/hex-grid.min.js');
  8240. var defaultHexGrid = require('../../lib/default-hex-grid');
  8241. /**
  8242. * Hex grid.
  8243. */
  8244. module.exports.Primitive = AFRAME.registerPrimitive('a-hexgrid', {
  8245. defaultComponents: {
  8246. 'hexgrid': {}
  8247. },
  8248. mappings: {
  8249. src: 'hexgrid.src'
  8250. }
  8251. });
  8252. module.exports.Component = AFRAME.registerComponent('hexgrid', {
  8253. dependencies: ['material'],
  8254. schema: {
  8255. src: { type: 'asset' }
  8256. },
  8257. init: function init() {
  8258. var _this = this;
  8259. var data = this.data;
  8260. if (data.src) {
  8261. fetch(data.src).then(function (response) {
  8262. return response.json();
  8263. }).then(function (json) {
  8264. return _this.addMesh(json);
  8265. });
  8266. } else {
  8267. this.addMesh(defaultHexGrid);
  8268. }
  8269. },
  8270. addMesh: function addMesh(json) {
  8271. var grid = new vg.HexGrid();
  8272. grid.fromJSON(json);
  8273. var board = new vg.Board(grid);
  8274. board.generateTilemap();
  8275. this.el.setObject3D('mesh', board.group);
  8276. this.addMaterial();
  8277. },
  8278. addMaterial: function addMaterial() {
  8279. var materialComponent = this.el.components.material;
  8280. var material = (materialComponent || {}).material;
  8281. if (!material) return;
  8282. this.el.object3D.traverse(function (node) {
  8283. if (node.isMesh) {
  8284. node.material = material;
  8285. }
  8286. });
  8287. },
  8288. remove: function remove() {
  8289. this.el.removeObject3D('mesh');
  8290. }
  8291. });
  8292. },{"../../lib/default-hex-grid":7,"../../lib/hex-grid.min.js":9}],40:[function(require,module,exports){
  8293. 'use strict';
  8294. /**
  8295. * Flat-shaded ocean primitive.
  8296. *
  8297. * Based on a Codrops tutorial:
  8298. * http://tympanus.net/codrops/2016/04/26/the-aviator-animating-basic-3d-scene-threejs/
  8299. */
  8300. module.exports.Primitive = AFRAME.registerPrimitive('a-ocean', {
  8301. defaultComponents: {
  8302. ocean: {},
  8303. rotation: { x: -90, y: 0, z: 0 }
  8304. },
  8305. mappings: {
  8306. width: 'ocean.width',
  8307. depth: 'ocean.depth',
  8308. density: 'ocean.density',
  8309. amplitude: 'ocean.amplitude',
  8310. amplitudeVariance: 'ocean.amplitudeVariance',
  8311. speed: 'ocean.speed',
  8312. speedVariance: 'ocean.speedVariance',
  8313. color: 'ocean.color',
  8314. opacity: 'ocean.opacity'
  8315. }
  8316. });
  8317. module.exports.Component = AFRAME.registerComponent('ocean', {
  8318. schema: {
  8319. // Dimensions of the ocean area.
  8320. width: { default: 10, min: 0 },
  8321. depth: { default: 10, min: 0 },
  8322. // Density of waves.
  8323. density: { default: 10 },
  8324. // Wave amplitude and variance.
  8325. amplitude: { default: 0.1 },
  8326. amplitudeVariance: { default: 0.3 },
  8327. // Wave speed and variance.
  8328. speed: { default: 1 },
  8329. speedVariance: { default: 2 },
  8330. // Material.
  8331. color: { default: '#7AD2F7', type: 'color' },
  8332. opacity: { default: 0.8 }
  8333. },
  8334. /**
  8335. * Use play() instead of init(), because component mappings – unavailable as dependencies – are
  8336. * not guaranteed to have parsed when this component is initialized.
  8337. */
  8338. play: function play() {
  8339. var el = this.el,
  8340. data = this.data;
  8341. var material = el.components.material;
  8342. var geometry = new THREE.PlaneGeometry(data.width, data.depth, data.density, data.density);
  8343. geometry.mergeVertices();
  8344. this.waves = [];
  8345. for (var v, i = 0, l = geometry.vertices.length; i < l; i++) {
  8346. v = geometry.vertices[i];
  8347. this.waves.push({
  8348. z: v.z,
  8349. ang: Math.random() * Math.PI * 2,
  8350. amp: data.amplitude + Math.random() * data.amplitudeVariance,
  8351. speed: (data.speed + Math.random() * data.speedVariance) / 1000 // radians / frame
  8352. });
  8353. }
  8354. if (!material) {
  8355. material = {};
  8356. material.material = new THREE.MeshPhongMaterial({
  8357. color: data.color,
  8358. transparent: data.opacity < 1,
  8359. opacity: data.opacity,
  8360. shading: THREE.FlatShading
  8361. });
  8362. }
  8363. this.mesh = new THREE.Mesh(geometry, material.material);
  8364. el.setObject3D('mesh', this.mesh);
  8365. },
  8366. remove: function remove() {
  8367. this.el.removeObject3D('mesh');
  8368. },
  8369. tick: function tick(t, dt) {
  8370. if (!dt) return;
  8371. var verts = this.mesh.geometry.vertices;
  8372. for (var v, vprops, i = 0; v = verts[i]; i++) {
  8373. vprops = this.waves[i];
  8374. v.z = vprops.z + Math.sin(vprops.ang) * vprops.amp;
  8375. vprops.ang += vprops.speed * dt;
  8376. }
  8377. this.mesh.geometry.verticesNeedUpdate = true;
  8378. }
  8379. });
  8380. },{}],41:[function(require,module,exports){
  8381. 'use strict';
  8382. /**
  8383. * Tube following a custom path.
  8384. *
  8385. * Usage:
  8386. *
  8387. * ```html
  8388. * <a-tube path="5 0 5, 5 0 -5, -5 0 -5" radius="0.5"></a-tube>
  8389. * ```
  8390. */
  8391. module.exports.Primitive = AFRAME.registerPrimitive('a-tube', {
  8392. defaultComponents: {
  8393. tube: {}
  8394. },
  8395. mappings: {
  8396. path: 'tube.path',
  8397. segments: 'tube.segments',
  8398. radius: 'tube.radius',
  8399. 'radial-segments': 'tube.radialSegments',
  8400. closed: 'tube.closed'
  8401. }
  8402. });
  8403. module.exports.Component = AFRAME.registerComponent('tube', {
  8404. schema: {
  8405. path: { default: [] },
  8406. segments: { default: 64 },
  8407. radius: { default: 1 },
  8408. radialSegments: { default: 8 },
  8409. closed: { default: false }
  8410. },
  8411. init: function init() {
  8412. var el = this.el,
  8413. data = this.data;
  8414. var material = el.components.material;
  8415. if (!data.path.length) {
  8416. console.error('[a-tube] `path` property expected but not found.');
  8417. return;
  8418. }
  8419. var curve = new THREE.CatmullRomCurve3(data.path.map(function (point) {
  8420. point = point.split(' ');
  8421. return new THREE.Vector3(Number(point[0]), Number(point[1]), Number(point[2]));
  8422. }));
  8423. var geometry = new THREE.TubeGeometry(curve, data.segments, data.radius, data.radialSegments, data.closed);
  8424. if (!material) {
  8425. material = {};
  8426. material.material = new THREE.MeshPhongMaterial();
  8427. }
  8428. this.mesh = new THREE.Mesh(geometry, material.material);
  8429. this.el.setObject3D('mesh', this.mesh);
  8430. },
  8431. update: function update(prevData) {
  8432. if (!Object.keys(prevData).length) return;
  8433. this.remove();
  8434. this.init();
  8435. },
  8436. remove: function remove() {
  8437. if (this.mesh) this.el.removeObject3D('mesh');
  8438. }
  8439. });
  8440. },{}],42:[function(require,module,exports){
  8441. 'use strict';
  8442. require('./a-grid');
  8443. require('./a-hexgrid');
  8444. require('./a-ocean');
  8445. require('./a-tube');
  8446. },{"./a-grid":38,"./a-hexgrid":39,"./a-ocean":40,"./a-tube":41}]},{},[1]);