FBXLoader.js 126 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518
  1. /**
  2. * @author Kyle-Larson https://github.com/Kyle-Larson
  3. * @author Takahiro https://github.com/takahirox
  4. *
  5. * Loader loads FBX file and generates Group representing FBX scene.
  6. * Requires FBX file to be >= 7.0 and in ASCII or to be any version in Binary format.
  7. *
  8. * Supports:
  9. * Mesh Generation (Positional Data)
  10. * Normal Data (Per Vertex Drawing Instance)
  11. * UV Data (Per Vertex Drawing Instance)
  12. * Skinning
  13. * Animation
  14. * - Separated Animations based on stacks.
  15. * - Skeletal & Non-Skeletal Animations
  16. * NURBS (Open, Closed and Periodic forms)
  17. *
  18. * Needs Support:
  19. * Indexed Buffers
  20. * PreRotation support.
  21. */
  22. ( function () {
  23. /**
  24. * Generates a loader for loading FBX files from URL and parsing into
  25. * a THREE.Group.
  26. * @param {THREE.LoadingManager} manager - Loading Manager for loader to use.
  27. */
  28. THREE.FBXLoader = function ( manager ) {
  29. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  30. };
  31. Object.assign( THREE.FBXLoader.prototype, {
  32. /**
  33. * Loads an ASCII/Binary FBX file from URL and parses into a THREE.Group.
  34. * THREE.Group will have an animations property of AnimationClips
  35. * of the different animations exported with the FBX.
  36. * @param {string} url - URL of the FBX file.
  37. * @param {function(THREE.Group):void} onLoad - Callback for when FBX file is loaded and parsed.
  38. * @param {function(ProgressEvent):void} onProgress - Callback fired periodically when file is being retrieved from server.
  39. * @param {function(Event):void} onError - Callback fired when error occurs (Currently only with retrieving file, not with parsing errors).
  40. */
  41. load: function ( url, onLoad, onProgress, onError ) {
  42. var self = this;
  43. var resourceDirectory = THREE.Loader.prototype.extractUrlBase( url );
  44. var loader = new THREE.FileLoader( this.manager );
  45. loader.setResponseType( 'arraybuffer' );
  46. loader.load( url, function ( buffer ) {
  47. try {
  48. var scene = self.parse( buffer, resourceDirectory );
  49. onLoad( scene );
  50. } catch ( error ) {
  51. window.setTimeout( function () {
  52. if ( onError ) onError( error );
  53. self.manager.itemError( url );
  54. }, 0 );
  55. }
  56. }, onProgress, onError );
  57. },
  58. /**
  59. * Parses an ASCII/Binary FBX file and returns a THREE.Group.
  60. * THREE.Group will have an animations property of AnimationClips
  61. * of the different animations within the FBX file.
  62. * @param {ArrayBuffer} FBXBuffer - Contents of FBX file to parse.
  63. * @param {string} resourceDirectory - Directory to load external assets (e.g. textures ) from.
  64. * @returns {THREE.Group}
  65. */
  66. parse: function ( FBXBuffer, resourceDirectory ) {
  67. var FBXTree;
  68. if ( isFbxFormatBinary( FBXBuffer ) ) {
  69. FBXTree = new BinaryParser().parse( FBXBuffer );
  70. } else {
  71. var FBXText = convertArrayBufferToString( FBXBuffer );
  72. if ( ! isFbxFormatASCII( FBXText ) ) {
  73. throw new Error( 'THREE.FBXLoader: Unknown format.' );
  74. }
  75. if ( getFbxVersion( FBXText ) < 7000 ) {
  76. throw new Error( 'THREE.FBXLoader: FBX version not supported, FileVersion: ' + getFbxVersion( FBXText ) );
  77. }
  78. FBXTree = new TextParser().parse( FBXText );
  79. }
  80. // console.log( FBXTree );
  81. var connections = parseConnections( FBXTree );
  82. var images = parseImages( FBXTree );
  83. var textures = parseTextures( FBXTree, new THREE.TextureLoader( this.manager ).setPath( resourceDirectory ), images, connections );
  84. var materials = parseMaterials( FBXTree, textures, connections );
  85. var deformers = parseDeformers( FBXTree, connections );
  86. var geometryMap = parseGeometries( FBXTree, connections, deformers );
  87. var sceneGraph = parseScene( FBXTree, connections, deformers, geometryMap, materials );
  88. return sceneGraph;
  89. }
  90. } );
  91. /**
  92. * Parses map of relationships between objects.
  93. * @param {{Connections: { properties: { connections: [number, number, string][]}}}} FBXTree
  94. * @returns {Map<number, {parents: {ID: number, relationship: string}[], children: {ID: number, relationship: string}[]}>}
  95. */
  96. function parseConnections( FBXTree ) {
  97. /**
  98. * @type {Map<number, { parents: {ID: number, relationship: string}[], children: {ID: number, relationship: string}[]}>}
  99. */
  100. var connectionMap = new Map();
  101. if ( 'Connections' in FBXTree ) {
  102. /**
  103. * @type {[number, number, string][]}
  104. */
  105. var connectionArray = FBXTree.Connections.properties.connections;
  106. for ( var connectionArrayIndex = 0, connectionArrayLength = connectionArray.length; connectionArrayIndex < connectionArrayLength; ++ connectionArrayIndex ) {
  107. var connection = connectionArray[ connectionArrayIndex ];
  108. if ( ! connectionMap.has( connection[ 0 ] ) ) {
  109. connectionMap.set( connection[ 0 ], {
  110. parents: [],
  111. children: []
  112. } );
  113. }
  114. var parentRelationship = { ID: connection[ 1 ], relationship: connection[ 2 ] };
  115. connectionMap.get( connection[ 0 ] ).parents.push( parentRelationship );
  116. if ( ! connectionMap.has( connection[ 1 ] ) ) {
  117. connectionMap.set( connection[ 1 ], {
  118. parents: [],
  119. children: []
  120. } );
  121. }
  122. var childRelationship = { ID: connection[ 0 ], relationship: connection[ 2 ] };
  123. connectionMap.get( connection[ 1 ] ).children.push( childRelationship );
  124. }
  125. }
  126. return connectionMap;
  127. }
  128. /**
  129. * Parses map of images referenced in FBXTree.
  130. * @param {{Objects: {subNodes: {Texture: Object.<string, FBXTextureNode>}}}} FBXTree
  131. * @returns {Map<number, string(image blob/data URL)>}
  132. */
  133. function parseImages( FBXTree ) {
  134. /**
  135. * @type {Map<number, string(image blob/data URL)>}
  136. */
  137. var imageMap = new Map();
  138. if ( 'Video' in FBXTree.Objects.subNodes ) {
  139. var videoNodes = FBXTree.Objects.subNodes.Video;
  140. for ( var nodeID in videoNodes ) {
  141. var videoNode = videoNodes[ nodeID ];
  142. // raw image data is in videoNode.properties.Content
  143. if ( 'Content' in videoNode.properties ) {
  144. var image = parseImage( videoNodes[ nodeID ] );
  145. imageMap.set( parseInt( nodeID ), image );
  146. }
  147. }
  148. }
  149. return imageMap;
  150. }
  151. /**
  152. * @param {videoNode} videoNode - Node to get texture image information from.
  153. * @returns {string} - image blob/data URL
  154. */
  155. function parseImage( videoNode ) {
  156. var content = videoNode.properties.Content;
  157. var fileName = videoNode.properties.RelativeFilename || videoNode.properties.Filename;
  158. var extension = fileName.slice( fileName.lastIndexOf( '.' ) + 1 ).toLowerCase();
  159. var type;
  160. switch ( extension ) {
  161. case 'bmp':
  162. type = 'image/bmp';
  163. break;
  164. case 'jpg':
  165. type = 'image/jpeg';
  166. break;
  167. case 'png':
  168. type = 'image/png';
  169. break;
  170. case 'tif':
  171. type = 'image/tiff';
  172. break;
  173. default:
  174. console.warn( 'FBXLoader: No support image type ' + extension );
  175. return;
  176. }
  177. if ( typeof content === 'string' ) {
  178. return 'data:' + type + ';base64,' + content;
  179. } else {
  180. var array = new Uint8Array( content );
  181. return window.URL.createObjectURL( new Blob( [ array ], { type: type } ) );
  182. }
  183. }
  184. /**
  185. * Parses map of textures referenced in FBXTree.
  186. * @param {{Objects: {subNodes: {Texture: Object.<string, FBXTextureNode>}}}} FBXTree
  187. * @param {THREE.TextureLoader} loader
  188. * @param {Map<number, string(image blob/data URL)>} imageMap
  189. * @param {Map<number, {parents: {ID: number, relationship: string}[], children: {ID: number, relationship: string}[]}>} connections
  190. * @returns {Map<number, THREE.Texture>}
  191. */
  192. function parseTextures( FBXTree, loader, imageMap, connections ) {
  193. /**
  194. * @type {Map<number, THREE.Texture>}
  195. */
  196. var textureMap = new Map();
  197. if ( 'Texture' in FBXTree.Objects.subNodes ) {
  198. var textureNodes = FBXTree.Objects.subNodes.Texture;
  199. for ( var nodeID in textureNodes ) {
  200. var texture = parseTexture( textureNodes[ nodeID ], loader, imageMap, connections );
  201. textureMap.set( parseInt( nodeID ), texture );
  202. }
  203. }
  204. return textureMap;
  205. }
  206. /**
  207. * @param {textureNode} textureNode - Node to get texture information from.
  208. * @param {THREE.TextureLoader} loader
  209. * @param {Map<number, string(image blob/data URL)>} imageMap
  210. * @param {Map<number, {parents: {ID: number, relationship: string}[], children: {ID: number, relationship: string}[]}>} connections
  211. * @returns {THREE.Texture}
  212. */
  213. function parseTexture( textureNode, loader, imageMap, connections ) {
  214. var FBX_ID = textureNode.id;
  215. var name = textureNode.attrName;
  216. var fileName;
  217. var filePath = textureNode.properties.FileName;
  218. var relativeFilePath = textureNode.properties.RelativeFilename;
  219. var children = connections.get( FBX_ID ).children;
  220. if ( children !== undefined && children.length > 0 && imageMap.has( children[ 0 ].ID ) ) {
  221. fileName = imageMap.get( children[ 0 ].ID );
  222. } else if ( relativeFilePath !== undefined && relativeFilePath[ 0 ] !== '/' &&
  223. relativeFilePath.match( /^[a-zA-Z]:/ ) === null ) {
  224. // use textureNode.properties.RelativeFilename
  225. // if it exists and it doesn't seem an absolute path
  226. fileName = relativeFilePath;
  227. } else {
  228. var split = filePath.split( /[\\\/]/ );
  229. if ( split.length > 0 ) {
  230. fileName = split[ split.length - 1 ];
  231. } else {
  232. fileName = filePath;
  233. }
  234. }
  235. var currentPath = loader.path;
  236. if ( fileName.indexOf( 'blob:' ) === 0 || fileName.indexOf( 'data:' ) === 0 ) {
  237. loader.setPath( undefined );
  238. }
  239. /**
  240. * @type {THREE.Texture}
  241. */
  242. var texture = loader.load( fileName );
  243. texture.name = name;
  244. texture.FBX_ID = FBX_ID;
  245. var wrapModeU = textureNode.properties.WrapModeU;
  246. var wrapModeV = textureNode.properties.WrapModeV;
  247. var valueU = wrapModeU !== undefined ? wrapModeU.value : 0;
  248. var valueV = wrapModeV !== undefined ? wrapModeV.value : 0;
  249. // http://download.autodesk.com/us/fbx/SDKdocs/FBX_SDK_Help/files/fbxsdkref/class_k_fbx_texture.html#889640e63e2e681259ea81061b85143a
  250. // 0: repeat(default), 1: clamp
  251. texture.wrapS = valueU === 0 ? THREE.RepeatWrapping : THREE.ClampToEdgeWrapping;
  252. texture.wrapT = valueV === 0 ? THREE.RepeatWrapping : THREE.ClampToEdgeWrapping;
  253. loader.setPath( currentPath );
  254. return texture;
  255. }
  256. /**
  257. * Parses map of Material information.
  258. * @param {{Objects: {subNodes: {Material: Object.<number, FBXMaterialNode>}}}} FBXTree
  259. * @param {Map<number, THREE.Texture>} textureMap
  260. * @param {Map<number, {parents: {ID: number, relationship: string}[], children: {ID: number, relationship: string}[]}>} connections
  261. * @returns {Map<number, THREE.Material>}
  262. */
  263. function parseMaterials( FBXTree, textureMap, connections ) {
  264. var materialMap = new Map();
  265. if ( 'Material' in FBXTree.Objects.subNodes ) {
  266. var materialNodes = FBXTree.Objects.subNodes.Material;
  267. for ( var nodeID in materialNodes ) {
  268. var material = parseMaterial( materialNodes[ nodeID ], textureMap, connections );
  269. if ( material !== null ) materialMap.set( parseInt( nodeID ), material );
  270. }
  271. }
  272. return materialMap;
  273. }
  274. /**
  275. * Takes information from Material node and returns a generated THREE.Material
  276. * @param {FBXMaterialNode} materialNode
  277. * @param {Map<number, THREE.Texture>} textureMap
  278. * @param {Map<number, {parents: {ID: number, relationship: string}[], children: {ID: number, relationship: string}[]}>} connections
  279. * @returns {THREE.Material}
  280. */
  281. function parseMaterial( materialNode, textureMap, connections ) {
  282. var FBX_ID = materialNode.id;
  283. var name = materialNode.attrName;
  284. var type = materialNode.properties.ShadingModel;
  285. //Case where FBXs wrap shading model in property object.
  286. if ( typeof type === 'object' ) {
  287. type = type.value;
  288. }
  289. // Seems like FBX can include unused materials which don't have any connections.
  290. // Ignores them so far.
  291. if ( ! connections.has( FBX_ID ) ) return null;
  292. var children = connections.get( FBX_ID ).children;
  293. var parameters = parseParameters( materialNode.properties, textureMap, children );
  294. var material;
  295. switch ( type.toLowerCase() ) {
  296. case 'phong':
  297. material = new THREE.MeshPhongMaterial();
  298. break;
  299. case 'lambert':
  300. material = new THREE.MeshLambertMaterial();
  301. break;
  302. default:
  303. console.warn( 'THREE.FBXLoader: No implementation given for material type %s in FBXLoader.js. Defaulting to standard material.', type );
  304. material = new THREE.MeshStandardMaterial( { color: 0x3300ff } );
  305. break;
  306. }
  307. material.setValues( parameters );
  308. material.name = name;
  309. return material;
  310. }
  311. /**
  312. * @typedef {{Diffuse: FBXVector3, Specular: FBXVector3, Shininess: FBXValue, Emissive: FBXVector3, EmissiveFactor: FBXValue, Opacity: FBXValue}} FBXMaterialProperties
  313. */
  314. /**
  315. * @typedef {{color: THREE.Color=, specular: THREE.Color=, shininess: number=, emissive: THREE.Color=, emissiveIntensity: number=, opacity: number=, transparent: boolean=, map: THREE.Texture=}} THREEMaterialParameterPack
  316. */
  317. /**
  318. * @param {FBXMaterialProperties} properties
  319. * @param {Map<number, THREE.Texture>} textureMap
  320. * @param {{ID: number, relationship: string}[]} childrenRelationships
  321. * @returns {THREEMaterialParameterPack}
  322. */
  323. function parseParameters( properties, textureMap, childrenRelationships ) {
  324. var parameters = {};
  325. if ( properties.BumpFactor ) {
  326. parameters.bumpScale = parseFloat( properties.BumpFactor.value );
  327. }
  328. if ( properties.Diffuse ) {
  329. parameters.color = parseColor( properties.Diffuse );
  330. }
  331. if ( properties.DisplacementFactor ) {
  332. parameters.displacementScale = parseFloat( properties.DisplacementFactor.value );
  333. }
  334. if ( properties.ReflectionFactor ) {
  335. parameters.envMapIntensity = parseFloat( properties.ReflectionFactor.value );
  336. parameters.reflectivity = parseFloat( properties.ReflectionFactor.value );
  337. }
  338. if ( properties.Specular ) {
  339. parameters.specular = parseColor( properties.Specular );
  340. }
  341. if ( properties.Shininess ) {
  342. parameters.shininess = parseFloat( properties.Shininess.value );
  343. }
  344. if ( properties.Emissive ) {
  345. parameters.emissive = parseColor( properties.Emissive );
  346. }
  347. if ( properties.EmissiveFactor ) {
  348. parameters.emissiveIntensity = parseFloat( properties.EmissiveFactor.value );
  349. }
  350. if ( properties.Opacity ) {
  351. parameters.opacity = parseFloat( properties.Opacity.value );
  352. }
  353. if ( parameters.opacity < 1.0 ) {
  354. parameters.transparent = true;
  355. }
  356. for ( var childrenRelationshipsIndex = 0, childrenRelationshipsLength = childrenRelationships.length; childrenRelationshipsIndex < childrenRelationshipsLength; ++ childrenRelationshipsIndex ) {
  357. var relationship = childrenRelationships[ childrenRelationshipsIndex ];
  358. var type = relationship.relationship;
  359. switch ( type ) {
  360. case 'Bump':
  361. case ' "Bump':
  362. parameters.bumpMap = textureMap.get( relationship.ID );
  363. break;
  364. case 'DiffuseColor':
  365. case ' "DiffuseColor':
  366. parameters.map = textureMap.get( relationship.ID );
  367. break;
  368. case 'DisplacementColor':
  369. case ' "DisplacementColor':
  370. parameters.displacementMap = textureMap.get( relationship.ID );
  371. break;
  372. case 'EmissiveColor':
  373. case ' "EmissiveColor':
  374. parameters.emissiveMap = textureMap.get( relationship.ID );
  375. break;
  376. case 'NormalMap':
  377. case ' "NormalMap':
  378. parameters.normalMap = textureMap.get( relationship.ID );
  379. break;
  380. case 'ReflectionColor':
  381. case ' "ReflectionColor':
  382. parameters.envMap = textureMap.get( relationship.ID );
  383. parameters.envMap.mapping = THREE.EquirectangularReflectionMapping;
  384. break;
  385. case 'SpecularColor':
  386. case ' "SpecularColor':
  387. parameters.specularMap = textureMap.get( relationship.ID );
  388. break;
  389. case 'TransparentColor':
  390. case ' "TransparentColor':
  391. parameters.alphaMap = textureMap.get( relationship.ID );
  392. parameters.transparent = true;
  393. break;
  394. case 'AmbientColor':
  395. case ' "AmbientColor':
  396. case 'ShininessExponent': // AKA glossiness map
  397. case ' "ShininessExponent':
  398. case 'SpecularFactor': // AKA specularLevel
  399. case ' "SpecularFactor':
  400. case 'VectorDisplacementColor': // NOTE: Seems to be a copy of DisplacementColor
  401. case ' "VectorDisplacementColor':
  402. default:
  403. console.warn( 'THREE.FBXLoader: %s map is not supported in three.js, skipping texture.', type );
  404. break;
  405. }
  406. }
  407. return parameters;
  408. }
  409. /**
  410. * Generates map of Skeleton-like objects for use later when generating and binding skeletons.
  411. * @param {{Objects: {subNodes: {Deformer: Object.<number, FBXSubDeformerNode>}}}} FBXTree
  412. * @param {Map<number, {parents: {ID: number, relationship: string}[], children: {ID: number, relationship: string}[]}>} connections
  413. * @returns {Map<number, {map: Map<number, {FBX_ID: number, indices: number[], weights: number[], transform: number[], transformLink: number[], linkMode: string}>, array: {FBX_ID: number, indices: number[], weights: number[], transform: number[], transformLink: number[], linkMode: string}[], skeleton: THREE.Skeleton|null}>}
  414. */
  415. function parseDeformers( FBXTree, connections ) {
  416. var deformers = {};
  417. if ( 'Deformer' in FBXTree.Objects.subNodes ) {
  418. var DeformerNodes = FBXTree.Objects.subNodes.Deformer;
  419. for ( var nodeID in DeformerNodes ) {
  420. var deformerNode = DeformerNodes[ nodeID ];
  421. if ( deformerNode.attrType === 'Skin' ) {
  422. var conns = connections.get( parseInt( nodeID ) );
  423. var skeleton = parseSkeleton( conns, DeformerNodes );
  424. skeleton.FBX_ID = parseInt( nodeID );
  425. deformers[ nodeID ] = skeleton;
  426. }
  427. }
  428. }
  429. return deformers;
  430. }
  431. /**
  432. * Generates a "Skeleton Representation" of FBX nodes based on an FBX Skin Deformer's connections and an object containing SubDeformer nodes.
  433. * @param {{parents: {ID: number, relationship: string}[], children: {ID: number, relationship: string}[]}} connections
  434. * @param {Object.<number, FBXSubDeformerNode>} DeformerNodes
  435. * @returns {{map: Map<number, {FBX_ID: number, indices: number[], weights: number[], transform: number[], transformLink: number[], linkMode: string}>, array: {FBX_ID: number, indices: number[], weights: number[], transform: number[], transformLink: number[], linkMode: string}[], skeleton: THREE.Skeleton|null}}
  436. */
  437. function parseSkeleton( connections, DeformerNodes ) {
  438. var subDeformers = {};
  439. var children = connections.children;
  440. for ( var i = 0, l = children.length; i < l; ++ i ) {
  441. var child = children[ i ];
  442. var subDeformerNode = DeformerNodes[ child.ID ];
  443. var subDeformer = {
  444. FBX_ID: child.ID,
  445. index: i,
  446. indices: [],
  447. weights: [],
  448. transform: parseMatrixArray( subDeformerNode.subNodes.Transform.properties.a ),
  449. transformLink: parseMatrixArray( subDeformerNode.subNodes.TransformLink.properties.a ),
  450. linkMode: subDeformerNode.properties.Mode
  451. };
  452. if ( 'Indexes' in subDeformerNode.subNodes ) {
  453. subDeformer.indices = parseIntArray( subDeformerNode.subNodes.Indexes.properties.a );
  454. subDeformer.weights = parseFloatArray( subDeformerNode.subNodes.Weights.properties.a );
  455. }
  456. subDeformers[ child.ID ] = subDeformer;
  457. }
  458. return {
  459. map: subDeformers,
  460. bones: []
  461. };
  462. }
  463. /**
  464. * Generates Buffer geometries from geometry information in FBXTree, and generates map of THREE.BufferGeometries
  465. * @param {{Objects: {subNodes: {Geometry: Object.<number, FBXGeometryNode}}}} FBXTree
  466. * @param {Map<number, {parents: {ID: number, relationship: string}[], children: {ID: number, relationship: string}[]}>} connections
  467. * @param {Map<number, {map: Map<number, {FBX_ID: number, indices: number[], weights: number[], transform: number[], transformLink: number[], linkMode: string}>, array: {FBX_ID: number, indices: number[], weights: number[], transform: number[], transformLink: number[], linkMode: string}[], skeleton: THREE.Skeleton|null}>} deformers
  468. * @returns {Map<number, THREE.BufferGeometry>}
  469. */
  470. function parseGeometries( FBXTree, connections, deformers ) {
  471. var geometryMap = new Map();
  472. if ( 'Geometry' in FBXTree.Objects.subNodes ) {
  473. var geometryNodes = FBXTree.Objects.subNodes.Geometry;
  474. for ( var nodeID in geometryNodes ) {
  475. var relationships = connections.get( parseInt( nodeID ) );
  476. var geo = parseGeometry( geometryNodes[ nodeID ], relationships, deformers );
  477. geometryMap.set( parseInt( nodeID ), geo );
  478. }
  479. }
  480. return geometryMap;
  481. }
  482. /**
  483. * Generates BufferGeometry from FBXGeometryNode.
  484. * @param {FBXGeometryNode} geometryNode
  485. * @param {{parents: {ID: number, relationship: string}[], children: {ID: number, relationship: string}[]}} relationships
  486. * @param {Map<number, {map: Map<number, {FBX_ID: number, indices: number[], weights: number[], transform: number[], transformLink: number[], linkMode: string}>, array: {FBX_ID: number, indices: number[], weights: number[], transform: number[], transformLink: number[], linkMode: string}[]}>} deformers
  487. * @returns {THREE.BufferGeometry}
  488. */
  489. function parseGeometry( geometryNode, relationships, deformers ) {
  490. switch ( geometryNode.attrType ) {
  491. case 'Mesh':
  492. return parseMeshGeometry( geometryNode, relationships, deformers );
  493. break;
  494. case 'NurbsCurve':
  495. return parseNurbsGeometry( geometryNode );
  496. break;
  497. }
  498. }
  499. /**
  500. * Specialty function for parsing Mesh based Geometry Nodes.
  501. * @param {FBXGeometryNode} geometryNode
  502. * @param {{parents: {ID: number, relationship: string}[], children: {ID: number, relationship: string}[]}} relationships - Object representing relationships between specific geometry node and other nodes.
  503. * @param {Map<number, {map: Map<number, {FBX_ID: number, indices: number[], weights: number[], transform: number[], transformLink: number[], linkMode: string}>, array: {FBX_ID: number, indices: number[], weights: number[], transform: number[], transformLink: number[], linkMode: string}[]}>} deformers - Map object of deformers and subDeformers by ID.
  504. * @returns {THREE.BufferGeometry}
  505. */
  506. function parseMeshGeometry( geometryNode, relationships, deformers ) {
  507. for ( var i = 0; i < relationships.children.length; ++ i ) {
  508. var deformer = deformers[ relationships.children[ i ].ID ];
  509. if ( deformer !== undefined ) break;
  510. }
  511. return genGeometry( geometryNode, deformer );
  512. }
  513. /**
  514. * @param {{map: Map<number, {FBX_ID: number, indices: number[], weights: number[], transform: number[], transformLink: number[], linkMode: string}>, array: {FBX_ID: number, indices: number[], weights: number[], transform: number[], transformLink: number[], linkMode: string}[]}} deformer - Skeleton representation for geometry instance.
  515. * @returns {THREE.BufferGeometry}
  516. */
  517. function genGeometry( geometryNode, deformer ) {
  518. var geometry = new Geometry();
  519. var subNodes = geometryNode.subNodes;
  520. // First, each index is going to be its own vertex.
  521. var vertexBuffer = parseFloatArray( subNodes.Vertices.properties.a );
  522. var indexBuffer = parseIntArray( subNodes.PolygonVertexIndex.properties.a );
  523. if ( subNodes.LayerElementNormal ) {
  524. var normalInfo = getNormals( subNodes.LayerElementNormal[ 0 ] );
  525. }
  526. if ( subNodes.LayerElementUV ) {
  527. var uvInfo = [];
  528. var i = 0;
  529. while ( subNodes.LayerElementUV[ i ] ) {
  530. uvInfo.push( getUVs( subNodes.LayerElementUV[ i ] ) );
  531. i ++;
  532. }
  533. }
  534. if ( subNodes.LayerElementColor ) {
  535. var colorInfo = getColors( subNodes.LayerElementColor[ 0 ] );
  536. }
  537. if ( subNodes.LayerElementMaterial ) {
  538. var materialInfo = getMaterials( subNodes.LayerElementMaterial[ 0 ] );
  539. }
  540. var weightTable = {};
  541. if ( deformer ) {
  542. var subDeformers = deformer.map;
  543. for ( var key in subDeformers ) {
  544. var subDeformer = subDeformers[ key ];
  545. var indices = subDeformer.indices;
  546. for ( var j = 0; j < indices.length; j ++ ) {
  547. var index = indices[ j ];
  548. var weight = subDeformer.weights[ j ];
  549. if ( weightTable[ index ] === undefined ) weightTable[ index ] = [];
  550. weightTable[ index ].push( {
  551. id: subDeformer.index,
  552. weight: weight
  553. } );
  554. }
  555. }
  556. }
  557. var faceVertexBuffer = [];
  558. var polygonIndex = 0;
  559. var displayedWeightsWarning = false;
  560. for ( var polygonVertexIndex = 0; polygonVertexIndex < indexBuffer.length; polygonVertexIndex ++ ) {
  561. var vertexIndex = indexBuffer[ polygonVertexIndex ];
  562. var endOfFace = false;
  563. if ( vertexIndex < 0 ) {
  564. vertexIndex = vertexIndex ^ - 1;
  565. indexBuffer[ polygonVertexIndex ] = vertexIndex;
  566. endOfFace = true;
  567. }
  568. var vertex = new Vertex();
  569. var weightIndices = [];
  570. var weights = [];
  571. vertex.position.fromArray( vertexBuffer, vertexIndex * 3 );
  572. if ( deformer ) {
  573. if ( weightTable[ vertexIndex ] !== undefined ) {
  574. var array = weightTable[ vertexIndex ];
  575. for ( var j = 0, jl = array.length; j < jl; j ++ ) {
  576. weights.push( array[ j ].weight );
  577. weightIndices.push( array[ j ].id );
  578. }
  579. }
  580. if ( weights.length > 4 ) {
  581. if ( ! displayedWeightsWarning ) {
  582. console.warn( 'THREE.FBXLoader: Vertex has more than 4 skinning weights assigned to vertex. Deleting additional weights.' );
  583. displayedWeightsWarning = true;
  584. }
  585. var WIndex = [ 0, 0, 0, 0 ];
  586. var Weight = [ 0, 0, 0, 0 ];
  587. weights.forEach( function ( weight, weightIndex ) {
  588. var currentWeight = weight;
  589. var currentIndex = weightIndices[ weightIndex ];
  590. Weight.forEach( function ( comparedWeight, comparedWeightIndex, comparedWeightArray ) {
  591. if ( currentWeight > comparedWeight ) {
  592. comparedWeightArray[ comparedWeightIndex ] = currentWeight;
  593. currentWeight = comparedWeight;
  594. var tmp = WIndex[ comparedWeightIndex ];
  595. WIndex[ comparedWeightIndex ] = currentIndex;
  596. currentIndex = tmp;
  597. }
  598. } );
  599. } );
  600. weightIndices = WIndex;
  601. weights = Weight;
  602. }
  603. for ( var i = weights.length; i < 4; ++ i ) {
  604. weights[ i ] = 0;
  605. weightIndices[ i ] = 0;
  606. }
  607. vertex.skinWeights.fromArray( weights );
  608. vertex.skinIndices.fromArray( weightIndices );
  609. }
  610. if ( normalInfo ) {
  611. vertex.normal.fromArray( getData( polygonVertexIndex, polygonIndex, vertexIndex, normalInfo ) );
  612. }
  613. if ( uvInfo ) {
  614. var uvTemp = new THREE.Vector2();
  615. for ( var i = 0; i < uvInfo.length; i ++ ) {
  616. vertex.uv.push( uvTemp.fromArray( getData( polygonVertexIndex, polygonIndex, vertexIndex, uvInfo[ i ] ) ) );
  617. }
  618. }
  619. if ( colorInfo ) {
  620. vertex.color.fromArray( getData( polygonVertexIndex, polygonIndex, vertexIndex, colorInfo ) );
  621. }
  622. faceVertexBuffer.push( vertex );
  623. if ( endOfFace ) {
  624. var face = new Face();
  625. face.genTrianglesFromVertices( faceVertexBuffer );
  626. if ( materialInfo !== undefined ) {
  627. var materials = getData( polygonVertexIndex, polygonIndex, vertexIndex, materialInfo );
  628. face.materialIndex = materials[ 0 ];
  629. } else {
  630. // Seems like some models don't have materialInfo(subNodes.LayerElementMaterial).
  631. // Set 0 in such a case.
  632. face.materialIndex = 0;
  633. }
  634. geometry.faces.push( face );
  635. faceVertexBuffer = [];
  636. polygonIndex ++;
  637. endOfFace = false;
  638. }
  639. }
  640. /**
  641. * @type {{vertexBuffer: number[], normalBuffer: number[], uvBuffer: number[], skinIndexBuffer: number[], skinWeightBuffer: number[], materialIndexBuffer: number[]}}
  642. */
  643. var bufferInfo = geometry.flattenToBuffers();
  644. var geo = new THREE.BufferGeometry();
  645. geo.name = geometryNode.name;
  646. geo.addAttribute( 'position', new THREE.Float32BufferAttribute( bufferInfo.vertexBuffer, 3 ) );
  647. if ( bufferInfo.normalBuffer.length > 0 ) {
  648. geo.addAttribute( 'normal', new THREE.Float32BufferAttribute( bufferInfo.normalBuffer, 3 ) );
  649. }
  650. if ( bufferInfo.uvBuffers.length > 0 ) {
  651. for ( var i = 0; i < bufferInfo.uvBuffers.length; i ++ ) {
  652. var name = 'uv' + ( i + 1 ).toString();
  653. if ( i == 0 ) {
  654. name = 'uv';
  655. }
  656. geo.addAttribute( name, new THREE.Float32BufferAttribute( bufferInfo.uvBuffers[ i ], 2 ) );
  657. }
  658. }
  659. if ( subNodes.LayerElementColor ) {
  660. geo.addAttribute( 'color', new THREE.Float32BufferAttribute( bufferInfo.colorBuffer, 3 ) );
  661. }
  662. if ( deformer ) {
  663. geo.addAttribute( 'skinIndex', new THREE.Float32BufferAttribute( bufferInfo.skinIndexBuffer, 4 ) );
  664. geo.addAttribute( 'skinWeight', new THREE.Float32BufferAttribute( bufferInfo.skinWeightBuffer, 4 ) );
  665. geo.FBX_Deformer = deformer;
  666. }
  667. // Convert the material indices of each vertex into rendering groups on the geometry.
  668. var materialIndexBuffer = bufferInfo.materialIndexBuffer;
  669. var prevMaterialIndex = materialIndexBuffer[ 0 ];
  670. var startIndex = 0;
  671. for ( var i = 0; i < materialIndexBuffer.length; ++ i ) {
  672. if ( materialIndexBuffer[ i ] !== prevMaterialIndex ) {
  673. geo.addGroup( startIndex, i - startIndex, prevMaterialIndex );
  674. prevMaterialIndex = materialIndexBuffer[ i ];
  675. startIndex = i;
  676. }
  677. }
  678. return geo;
  679. }
  680. /**
  681. * Parses normal information for geometry.
  682. * @param {FBXGeometryNode} geometryNode
  683. * @returns {{dataSize: number, buffer: number[], indices: number[], mappingType: string, referenceType: string}}
  684. */
  685. function getNormals( NormalNode ) {
  686. var mappingType = NormalNode.properties.MappingInformationType;
  687. var referenceType = NormalNode.properties.ReferenceInformationType;
  688. var buffer = parseFloatArray( NormalNode.subNodes.Normals.properties.a );
  689. var indexBuffer = [];
  690. if ( referenceType === 'IndexToDirect' ) {
  691. if ( 'NormalIndex' in NormalNode.subNodes ) {
  692. indexBuffer = parseIntArray( NormalNode.subNodes.NormalIndex.properties.a );
  693. } else if ( 'NormalsIndex' in NormalNode.subNodes ) {
  694. indexBuffer = parseIntArray( NormalNode.subNodes.NormalsIndex.properties.a );
  695. }
  696. }
  697. return {
  698. dataSize: 3,
  699. buffer: buffer,
  700. indices: indexBuffer,
  701. mappingType: mappingType,
  702. referenceType: referenceType
  703. };
  704. }
  705. /**
  706. * Parses UV information for geometry.
  707. * @param {FBXGeometryNode} geometryNode
  708. * @returns {{dataSize: number, buffer: number[], indices: number[], mappingType: string, referenceType: string}}
  709. */
  710. function getUVs( UVNode ) {
  711. var mappingType = UVNode.properties.MappingInformationType;
  712. var referenceType = UVNode.properties.ReferenceInformationType;
  713. var buffer = parseFloatArray( UVNode.subNodes.UV.properties.a );
  714. var indexBuffer = [];
  715. if ( referenceType === 'IndexToDirect' ) {
  716. indexBuffer = parseIntArray( UVNode.subNodes.UVIndex.properties.a );
  717. }
  718. return {
  719. dataSize: 2,
  720. buffer: buffer,
  721. indices: indexBuffer,
  722. mappingType: mappingType,
  723. referenceType: referenceType
  724. };
  725. }
  726. /**
  727. * Parses Vertex Color information for geometry.
  728. * @param {FBXGeometryNode} geometryNode
  729. * @returns {{dataSize: number, buffer: number[], indices: number[], mappingType: string, referenceType: string}}
  730. */
  731. function getColors( ColorNode ) {
  732. var mappingType = ColorNode.properties.MappingInformationType;
  733. var referenceType = ColorNode.properties.ReferenceInformationType;
  734. var buffer = parseFloatArray( ColorNode.subNodes.Colors.properties.a );
  735. var indexBuffer = [];
  736. if ( referenceType === 'IndexToDirect' ) {
  737. indexBuffer = parseFloatArray( ColorNode.subNodes.ColorIndex.properties.a );
  738. }
  739. return {
  740. dataSize: 4,
  741. buffer: buffer,
  742. indices: indexBuffer,
  743. mappingType: mappingType,
  744. referenceType: referenceType
  745. };
  746. }
  747. /**
  748. * Parses material application information for geometry.
  749. * @param {FBXGeometryNode}
  750. * @returns {{dataSize: number, buffer: number[], indices: number[], mappingType: string, referenceType: string}}
  751. */
  752. function getMaterials( MaterialNode ) {
  753. var mappingType = MaterialNode.properties.MappingInformationType;
  754. var referenceType = MaterialNode.properties.ReferenceInformationType;
  755. if ( mappingType === 'NoMappingInformation' ) {
  756. return {
  757. dataSize: 1,
  758. buffer: [ 0 ],
  759. indices: [ 0 ],
  760. mappingType: 'AllSame',
  761. referenceType: referenceType
  762. };
  763. }
  764. var materialIndexBuffer = parseIntArray( MaterialNode.subNodes.Materials.properties.a );
  765. // Since materials are stored as indices, there's a bit of a mismatch between FBX and what
  766. // we expect. So we create an intermediate buffer that points to the index in the buffer,
  767. // for conforming with the other functions we've written for other data.
  768. var materialIndices = [];
  769. for ( var materialIndexBufferIndex = 0, materialIndexBufferLength = materialIndexBuffer.length; materialIndexBufferIndex < materialIndexBufferLength; ++ materialIndexBufferIndex ) {
  770. materialIndices.push( materialIndexBufferIndex );
  771. }
  772. return {
  773. dataSize: 1,
  774. buffer: materialIndexBuffer,
  775. indices: materialIndices,
  776. mappingType: mappingType,
  777. referenceType: referenceType
  778. };
  779. }
  780. /**
  781. * Function uses the infoObject and given indices to return value array of object.
  782. * @param {number} polygonVertexIndex - Index of vertex in draw order (which index of the index buffer refers to this vertex).
  783. * @param {number} polygonIndex - Index of polygon in geometry.
  784. * @param {number} vertexIndex - Index of vertex inside vertex buffer (used because some data refers to old index buffer that we don't use anymore).
  785. * @param {{datasize: number, buffer: number[], indices: number[], mappingType: string, referenceType: string}} infoObject - Object containing data and how to access data.
  786. * @returns {number[]}
  787. */
  788. var dataArray = [];
  789. var GetData = {
  790. ByPolygonVertex: {
  791. /**
  792. * Function uses the infoObject and given indices to return value array of object.
  793. * @param {number} polygonVertexIndex - Index of vertex in draw order (which index of the index buffer refers to this vertex).
  794. * @param {number} polygonIndex - Index of polygon in geometry.
  795. * @param {number} vertexIndex - Index of vertex inside vertex buffer (used because some data refers to old index buffer that we don't use anymore).
  796. * @param {{datasize: number, buffer: number[], indices: number[], mappingType: string, referenceType: string}} infoObject - Object containing data and how to access data.
  797. * @returns {number[]}
  798. */
  799. Direct: function ( polygonVertexIndex, polygonIndex, vertexIndex, infoObject ) {
  800. var from = ( polygonVertexIndex * infoObject.dataSize );
  801. var to = ( polygonVertexIndex * infoObject.dataSize ) + infoObject.dataSize;
  802. // return infoObject.buffer.slice( from, to );
  803. return slice( dataArray, infoObject.buffer, from, to );
  804. },
  805. /**
  806. * Function uses the infoObject and given indices to return value array of object.
  807. * @param {number} polygonVertexIndex - Index of vertex in draw order (which index of the index buffer refers to this vertex).
  808. * @param {number} polygonIndex - Index of polygon in geometry.
  809. * @param {number} vertexIndex - Index of vertex inside vertex buffer (used because some data refers to old index buffer that we don't use anymore).
  810. * @param {{datasize: number, buffer: number[], indices: number[], mappingType: string, referenceType: string}} infoObject - Object containing data and how to access data.
  811. * @returns {number[]}
  812. */
  813. IndexToDirect: function ( polygonVertexIndex, polygonIndex, vertexIndex, infoObject ) {
  814. var index = infoObject.indices[ polygonVertexIndex ];
  815. var from = ( index * infoObject.dataSize );
  816. var to = ( index * infoObject.dataSize ) + infoObject.dataSize;
  817. // return infoObject.buffer.slice( from, to );
  818. return slice( dataArray, infoObject.buffer, from, to );
  819. }
  820. },
  821. ByPolygon: {
  822. /**
  823. * Function uses the infoObject and given indices to return value array of object.
  824. * @param {number} polygonVertexIndex - Index of vertex in draw order (which index of the index buffer refers to this vertex).
  825. * @param {number} polygonIndex - Index of polygon in geometry.
  826. * @param {number} vertexIndex - Index of vertex inside vertex buffer (used because some data refers to old index buffer that we don't use anymore).
  827. * @param {{datasize: number, buffer: number[], indices: number[], mappingType: string, referenceType: string}} infoObject - Object containing data and how to access data.
  828. * @returns {number[]}
  829. */
  830. Direct: function ( polygonVertexIndex, polygonIndex, vertexIndex, infoObject ) {
  831. var from = polygonIndex * infoObject.dataSize;
  832. var to = polygonIndex * infoObject.dataSize + infoObject.dataSize;
  833. // return infoObject.buffer.slice( from, to );
  834. return slice( dataArray, infoObject.buffer, from, to );
  835. },
  836. /**
  837. * Function uses the infoObject and given indices to return value array of object.
  838. * @param {number} polygonVertexIndex - Index of vertex in draw order (which index of the index buffer refers to this vertex).
  839. * @param {number} polygonIndex - Index of polygon in geometry.
  840. * @param {number} vertexIndex - Index of vertex inside vertex buffer (used because some data refers to old index buffer that we don't use anymore).
  841. * @param {{datasize: number, buffer: number[], indices: number[], mappingType: string, referenceType: string}} infoObject - Object containing data and how to access data.
  842. * @returns {number[]}
  843. */
  844. IndexToDirect: function ( polygonVertexIndex, polygonIndex, vertexIndex, infoObject ) {
  845. var index = infoObject.indices[ polygonIndex ];
  846. var from = index * infoObject.dataSize;
  847. var to = index * infoObject.dataSize + infoObject.dataSize;
  848. // return infoObject.buffer.slice( from, to );
  849. return slice( dataArray, infoObject.buffer, from, to );
  850. }
  851. },
  852. ByVertice: {
  853. Direct: function ( polygonVertexIndex, polygonIndex, vertexIndex, infoObject ) {
  854. var from = ( vertexIndex * infoObject.dataSize );
  855. var to = ( vertexIndex * infoObject.dataSize ) + infoObject.dataSize;
  856. // return infoObject.buffer.slice( from, to );
  857. return slice( dataArray, infoObject.buffer, from, to );
  858. }
  859. },
  860. AllSame: {
  861. /**
  862. * Function uses the infoObject and given indices to return value array of object.
  863. * @param {number} polygonVertexIndex - Index of vertex in draw order (which index of the index buffer refers to this vertex).
  864. * @param {number} polygonIndex - Index of polygon in geometry.
  865. * @param {number} vertexIndex - Index of vertex inside vertex buffer (used because some data refers to old index buffer that we don't use anymore).
  866. * @param {{datasize: number, buffer: number[], indices: number[], mappingType: string, referenceType: string}} infoObject - Object containing data and how to access data.
  867. * @returns {number[]}
  868. */
  869. IndexToDirect: function ( polygonVertexIndex, polygonIndex, vertexIndex, infoObject ) {
  870. var from = infoObject.indices[ 0 ] * infoObject.dataSize;
  871. var to = infoObject.indices[ 0 ] * infoObject.dataSize + infoObject.dataSize;
  872. // return infoObject.buffer.slice( from, to );
  873. return slice( dataArray, infoObject.buffer, from, to );
  874. }
  875. }
  876. };
  877. function getData( polygonVertexIndex, polygonIndex, vertexIndex, infoObject ) {
  878. return GetData[ infoObject.mappingType ][ infoObject.referenceType ]( polygonVertexIndex, polygonIndex, vertexIndex, infoObject );
  879. }
  880. /**
  881. * Specialty function for parsing NurbsCurve based Geometry Nodes.
  882. * @param {FBXGeometryNode} geometryNode
  883. * @param {{parents: {ID: number, relationship: string}[], children: {ID: number, relationship: string}[]}} relationships
  884. * @returns {THREE.BufferGeometry}
  885. */
  886. function parseNurbsGeometry( geometryNode ) {
  887. if ( THREE.NURBSCurve === undefined ) {
  888. console.error( 'THREE.FBXLoader: The loader relies on THREE.NURBSCurve for any nurbs present in the model. Nurbs will show up as empty geometry.' );
  889. return new THREE.BufferGeometry();
  890. }
  891. var order = parseInt( geometryNode.properties.Order );
  892. if ( isNaN( order ) ) {
  893. console.error( 'THREE.FBXLoader: Invalid Order %s given for geometry ID: %s', geometryNode.properties.Order, geometryNode.id );
  894. return new THREE.BufferGeometry();
  895. }
  896. var degree = order - 1;
  897. var knots = parseFloatArray( geometryNode.subNodes.KnotVector.properties.a );
  898. var controlPoints = [];
  899. var pointsValues = parseFloatArray( geometryNode.subNodes.Points.properties.a );
  900. for ( var i = 0, l = pointsValues.length; i < l; i += 4 ) {
  901. controlPoints.push( new THREE.Vector4().fromArray( pointsValues, i ) );
  902. }
  903. var startKnot, endKnot;
  904. if ( geometryNode.properties.Form === 'Closed' ) {
  905. controlPoints.push( controlPoints[ 0 ] );
  906. } else if ( geometryNode.properties.Form === 'Periodic' ) {
  907. startKnot = degree;
  908. endKnot = knots.length - 1 - startKnot;
  909. for ( var i = 0; i < degree; ++ i ) {
  910. controlPoints.push( controlPoints[ i ] );
  911. }
  912. }
  913. var curve = new THREE.NURBSCurve( degree, knots, controlPoints, startKnot, endKnot );
  914. var vertices = curve.getPoints( controlPoints.length * 7 );
  915. var positions = new Float32Array( vertices.length * 3 );
  916. for ( var i = 0, l = vertices.length; i < l; ++ i ) {
  917. vertices[ i ].toArray( positions, i * 3 );
  918. }
  919. var geometry = new THREE.BufferGeometry();
  920. geometry.addAttribute( 'position', new THREE.BufferAttribute( positions, 3 ) );
  921. return geometry;
  922. }
  923. /**
  924. * Finally generates Scene graph and Scene graph Objects.
  925. * @param {{Objects: {subNodes: {Model: Object.<number, FBXModelNode>}}}} FBXTree
  926. * @param {Map<number, {parents: {ID: number, relationship: string}[], children: {ID: number, relationship: string}[]}>} connections
  927. * @param {Map<number, {map: Map<number, {FBX_ID: number, indices: number[], weights: number[], transform: number[], transformLink: number[], linkMode: string}>, array: {FBX_ID: number, indices: number[], weights: number[], transform: number[], transformLink: number[], linkMode: string}[], skeleton: THREE.Skeleton|null}>} deformers
  928. * @param {Map<number, THREE.BufferGeometry>} geometryMap
  929. * @param {Map<number, THREE.Material>} materialMap
  930. * @returns {THREE.Group}
  931. */
  932. function parseScene( FBXTree, connections, deformers, geometryMap, materialMap ) {
  933. var sceneGraph = new THREE.Group();
  934. var ModelNode = FBXTree.Objects.subNodes.Model;
  935. /**
  936. * @type {Array.<THREE.Object3D>}
  937. */
  938. var modelArray = [];
  939. /**
  940. * @type {Map.<number, THREE.Object3D>}
  941. */
  942. var modelMap = new Map();
  943. for ( var nodeID in ModelNode ) {
  944. var id = parseInt( nodeID );
  945. var node = ModelNode[ nodeID ];
  946. var conns = connections.get( id );
  947. var model = null;
  948. for ( var i = 0; i < conns.parents.length; ++ i ) {
  949. for ( var FBX_ID in deformers ) {
  950. var deformer = deformers[ FBX_ID ];
  951. var subDeformers = deformer.map;
  952. var subDeformer = subDeformers[ conns.parents[ i ].ID ];
  953. if ( subDeformer ) {
  954. var model2 = model;
  955. model = new THREE.Bone();
  956. deformer.bones[ subDeformer.index ] = model;
  957. // seems like we need this not to make non-connected bone, maybe?
  958. // TODO: confirm
  959. if ( model2 !== null ) model.add( model2 );
  960. }
  961. }
  962. }
  963. if ( ! model ) {
  964. switch ( node.attrType ) {
  965. case 'Camera':
  966. /* ***********
  967. * Supported camera types:
  968. * PerspectiveCamera
  969. * OrthographicCamera
  970. ************** */
  971. var cameraAttribute;
  972. for ( var childrenIndex = 0, childrenLength = conns.children.length; childrenIndex < childrenLength; ++ childrenIndex ) {
  973. var childID = conns.children[ childrenIndex ].ID;
  974. var attr = FBXTree.Objects.subNodes.NodeAttribute[ childID ];
  975. if ( attr !== undefined && attr.properties !== undefined ) {
  976. cameraAttribute = attr.properties;
  977. }
  978. }
  979. if ( cameraAttribute === undefined ) {
  980. model = new THREE.Object3D();
  981. } else {
  982. var type = 0;
  983. if ( cameraAttribute.CameraProjectionType !== undefined && ( cameraAttribute.CameraProjectionType.value === '1' || cameraAttribute.CameraProjectionType.value === 1 ) ) {
  984. type = 1;
  985. }
  986. var nearClippingPlane = 1;
  987. if ( cameraAttribute.NearPlane !== undefined ) {
  988. nearClippingPlane = cameraAttribute.NearPlane.value / 1000;
  989. }
  990. var farClippingPlane = 1000;
  991. if ( cameraAttribute.FarPlane !== undefined ) {
  992. farClippingPlane = cameraAttribute.FarPlane.value / 1000;
  993. }
  994. var width = window.innerWidth;
  995. var height = window.innerHeight;
  996. if ( cameraAttribute.AspectWidth !== undefined && cameraAttribute.AspectHeight !== undefined ) {
  997. width = parseFloat( cameraAttribute.AspectWidth.value );
  998. height = parseFloat( cameraAttribute.AspectHeight.value );
  999. }
  1000. var aspect = width / height;
  1001. var fov = 45;
  1002. if ( cameraAttribute.FieldOfView !== undefined ) {
  1003. fov = parseFloat( cameraAttribute.FieldOfView.value );
  1004. }
  1005. switch ( type ) {
  1006. case '0': // Perspective
  1007. case 0:
  1008. model = new THREE.PerspectiveCamera( fov, aspect, nearClippingPlane, farClippingPlane );
  1009. break;
  1010. case '1': // Orthographic
  1011. case 1:
  1012. model = new THREE.OrthographicCamera( - width / 2, width / 2, height / 2, - height / 2, nearClippingPlane, farClippingPlane );
  1013. break;
  1014. default:
  1015. console.warn( 'THREE.FBXLoader: Unknown camera type ' + type + '.' );
  1016. model = new THREE.Object3D();
  1017. break;
  1018. }
  1019. }
  1020. break;
  1021. case 'Light':
  1022. /* ***********
  1023. * Supported light types:
  1024. * DirectionalLight
  1025. * PointLight
  1026. * SpotLight
  1027. ************** */
  1028. var lightAttribute;
  1029. for ( var childrenIndex = 0, childrenLength = conns.children.length; childrenIndex < childrenLength; ++ childrenIndex ) {
  1030. var childID = conns.children[ childrenIndex ].ID;
  1031. var attr = FBXTree.Objects.subNodes.NodeAttribute[ childID ];
  1032. if ( attr !== undefined && attr.properties !== undefined ) {
  1033. lightAttribute = attr.properties;
  1034. }
  1035. }
  1036. if ( lightAttribute === undefined ) {
  1037. model = new THREE.Object3D();
  1038. } else {
  1039. var type;
  1040. // LightType can be undefined for Point lights
  1041. if ( lightAttribute.LightType === undefined ) {
  1042. type = 0;
  1043. } else {
  1044. type = lightAttribute.LightType.value;
  1045. }
  1046. var color = 0xffffff;
  1047. if ( lightAttribute.Color !== undefined ) {
  1048. var temp = lightAttribute.Color.value.split( ',' );
  1049. var r = parseFloat( temp[ 0 ] );
  1050. var g = parseFloat( temp[ 1 ] );
  1051. var b = parseFloat( temp[ 1 ] );
  1052. color = new THREE.Color( r, g, b );
  1053. }
  1054. var intensity = ( lightAttribute.Intensity === undefined ) ? 1 : lightAttribute.Intensity.value / 100;
  1055. // light disabled
  1056. if ( lightAttribute.CastLightOnObject !== undefined && ( lightAttribute.CastLightOnObject.value === '0' || lightAttribute.CastLightOnObject.value === 0 ) ) {
  1057. intensity = 0;
  1058. }
  1059. var distance = 0;
  1060. if ( lightAttribute.FarAttenuationEnd !== undefined ) {
  1061. if ( lightAttribute.EnableFarAttenuation !== undefined && ( lightAttribute.EnableFarAttenuation.value === '0' || lightAttribute.EnableFarAttenuation.value === 0 ) ) {
  1062. distance = 0;
  1063. } else {
  1064. distance = lightAttribute.FarAttenuationEnd.value / 1000;
  1065. }
  1066. }
  1067. // TODO
  1068. // could be calculated linearly from FarAttenuationStart to FarAttenuationEnd?
  1069. var decay = 1;
  1070. switch ( type ) {
  1071. case '0': // Point
  1072. case 0:
  1073. model = new THREE.PointLight( color, intensity, distance, decay );
  1074. break;
  1075. case '1': // Directional
  1076. case 1:
  1077. model = new THREE.DirectionalLight( color, intensity );
  1078. break;
  1079. case '2': // Spot
  1080. case 2:
  1081. var angle = Math.PI / 3;
  1082. if ( lightAttribute.InnerAngle !== undefined ) {
  1083. angle = THREE.Math.degToRad( lightAttribute.InnerAngle.value );
  1084. }
  1085. var penumbra = 0;
  1086. if ( lightAttribute.OuterAngle !== undefined ) {
  1087. // TODO: this is not correct - FBX calculates outer and inner angle in degrees
  1088. // with OuterAngle > InnerAngle && OuterAngle <= Math.PI
  1089. // while three.js uses a penumbra between (0, 1) to attenuate the inner angle
  1090. penumbra = THREE.Math.degToRad( lightAttribute.OuterAngle.value );
  1091. penumbra = Math.max( penumbra, 1 );
  1092. }
  1093. model = new THREE.SpotLight( color, intensity, distance, angle, penumbra, decay );
  1094. break;
  1095. default:
  1096. console.warn( 'THREE.FBXLoader: Unknown light type ' + lightAttribute.LightType.value + ', defaulting to a THREE.PointLight.' );
  1097. model = new THREE.PointLight( color, intensity );
  1098. break;
  1099. }
  1100. if ( lightAttribute.CastShadows !== undefined && ( lightAttribute.CastShadows.value === '1' || lightAttribute.CastShadows.value === 1 ) ) {
  1101. model.castShadow = true;
  1102. }
  1103. }
  1104. break;
  1105. case 'Mesh':
  1106. /**
  1107. * @type {?THREE.BufferGeometry}
  1108. */
  1109. var geometry = null;
  1110. /**
  1111. * @type {THREE.MultiMaterial|THREE.Material}
  1112. */
  1113. var material = null;
  1114. /**
  1115. * @type {Array.<THREE.Material>}
  1116. */
  1117. var materials = [];
  1118. for ( var childrenIndex = 0, childrenLength = conns.children.length; childrenIndex < childrenLength; ++ childrenIndex ) {
  1119. var child = conns.children[ childrenIndex ];
  1120. if ( geometryMap.has( child.ID ) ) {
  1121. geometry = geometryMap.get( child.ID );
  1122. }
  1123. if ( materialMap.has( child.ID ) ) {
  1124. materials.push( materialMap.get( child.ID ) );
  1125. }
  1126. }
  1127. if ( materials.length > 1 ) {
  1128. material = materials;
  1129. } else if ( materials.length > 0 ) {
  1130. material = materials[ 0 ];
  1131. } else {
  1132. material = new THREE.MeshStandardMaterial( { color: 0x3300ff } );
  1133. materials.push( material );
  1134. }
  1135. if ( 'color' in geometry.attributes ) {
  1136. for ( var materialIndex = 0, numMaterials = materials.length; materialIndex < numMaterials; ++ materialIndex ) {
  1137. materials[ materialIndex ].vertexColors = THREE.VertexColors;
  1138. }
  1139. }
  1140. if ( geometry.FBX_Deformer ) {
  1141. for ( var materialsIndex = 0, materialsLength = materials.length; materialsIndex < materialsLength; ++ materialsIndex ) {
  1142. materials[ materialsIndex ].skinning = true;
  1143. }
  1144. model = new THREE.SkinnedMesh( geometry, material );
  1145. } else {
  1146. model = new THREE.Mesh( geometry, material );
  1147. }
  1148. break;
  1149. case 'NurbsCurve':
  1150. var geometry = null;
  1151. for ( var childrenIndex = 0, childrenLength = conns.children.length; childrenIndex < childrenLength; ++ childrenIndex ) {
  1152. var child = conns.children[ childrenIndex ];
  1153. if ( geometryMap.has( child.ID ) ) {
  1154. geometry = geometryMap.get( child.ID );
  1155. }
  1156. }
  1157. // FBX does not list materials for Nurbs lines, so we'll just put our own in here.
  1158. material = new THREE.LineBasicMaterial( { color: 0x3300ff, linewidth: 5 } );
  1159. model = new THREE.Line( geometry, material );
  1160. break;
  1161. default:
  1162. model = new THREE.Group();
  1163. break;
  1164. }
  1165. }
  1166. model.name = THREE.PropertyBinding.sanitizeNodeName( node.attrName );
  1167. model.FBX_ID = id;
  1168. modelArray.push( model );
  1169. modelMap.set( id, model );
  1170. }
  1171. for ( var modelArrayIndex = 0, modelArrayLength = modelArray.length; modelArrayIndex < modelArrayLength; ++ modelArrayIndex ) {
  1172. var model = modelArray[ modelArrayIndex ];
  1173. var node = ModelNode[ model.FBX_ID ];
  1174. if ( 'Lcl_Translation' in node.properties ) {
  1175. model.position.fromArray( parseFloatArray( node.properties.Lcl_Translation.value ) );
  1176. }
  1177. if ( 'Lcl_Rotation' in node.properties ) {
  1178. var rotation = parseFloatArray( node.properties.Lcl_Rotation.value ).map( degreeToRadian );
  1179. rotation.push( 'ZYX' );
  1180. model.rotation.fromArray( rotation );
  1181. }
  1182. if ( 'Lcl_Scaling' in node.properties ) {
  1183. model.scale.fromArray( parseFloatArray( node.properties.Lcl_Scaling.value ) );
  1184. }
  1185. if ( 'PreRotation' in node.properties ) {
  1186. var preRotations = new THREE.Euler().setFromVector3( parseVector3( node.properties.PreRotation ).multiplyScalar( DEG2RAD ), 'ZYX' );
  1187. preRotations = new THREE.Quaternion().setFromEuler( preRotations );
  1188. var currentRotation = new THREE.Quaternion().setFromEuler( model.rotation );
  1189. preRotations.multiply( currentRotation );
  1190. model.rotation.setFromQuaternion( preRotations, 'ZYX' );
  1191. }
  1192. // allow transformed pivots - see https://github.com/mrdoob/three.js/issues/11895
  1193. if ( 'GeometricTranslation' in node.properties ) {
  1194. var array = node.properties.GeometricTranslation.value;
  1195. model.traverse( function ( child ) {
  1196. if ( child.geometry ) {
  1197. child.geometry.translate( array[ 0 ], array[ 1 ], array[ 2 ] );
  1198. }
  1199. } );
  1200. }
  1201. if ( 'LookAtProperty' in node.properties ) {
  1202. var conns = connections.get( model.FBX_ID );
  1203. for ( var childrenIndex = 0, childrenLength = conns.children.length; childrenIndex < childrenLength; ++ childrenIndex ) {
  1204. var child = conns.children[ childrenIndex ];
  1205. if ( child.relationship === 'LookAtProperty' || child.relationship === ' "LookAtProperty' ) {
  1206. var lookAtTarget = FBXTree.Objects.subNodes.Model[ child.ID ];
  1207. if ( 'Lcl_Translation' in lookAtTarget.properties ) {
  1208. var pos = lookAtTarget.properties.Lcl_Translation.value.split( ',' ).map( function ( val ) {
  1209. return parseFloat( val );
  1210. } );
  1211. // DirectionalLight, SpotLight
  1212. if ( model.target !== undefined ) {
  1213. model.target.position.set( pos[ 0 ], pos[ 1 ], pos[ 2 ] );
  1214. sceneGraph.add( model.target );
  1215. } else { // Cameras and other Object3Ds
  1216. model.lookAt( new THREE.Vector3( pos[ 0 ], pos[ 1 ], pos[ 2 ] ) );
  1217. }
  1218. }
  1219. }
  1220. }
  1221. }
  1222. var conns = connections.get( model.FBX_ID );
  1223. for ( var parentIndex = 0; parentIndex < conns.parents.length; parentIndex ++ ) {
  1224. var pIndex = findIndex( modelArray, function ( mod ) {
  1225. return mod.FBX_ID === conns.parents[ parentIndex ].ID;
  1226. } );
  1227. if ( pIndex > - 1 ) {
  1228. modelArray[ pIndex ].add( model );
  1229. break;
  1230. }
  1231. }
  1232. if ( model.parent === null ) {
  1233. sceneGraph.add( model );
  1234. }
  1235. }
  1236. // Now with the bones created, we can update the skeletons and bind them to the skinned meshes.
  1237. sceneGraph.updateMatrixWorld( true );
  1238. // Put skeleton into bind pose.
  1239. var BindPoseNode = FBXTree.Objects.subNodes.Pose;
  1240. for ( var nodeID in BindPoseNode ) {
  1241. if ( BindPoseNode[ nodeID ].attrType === 'BindPose' ) {
  1242. BindPoseNode = BindPoseNode[ nodeID ];
  1243. break;
  1244. }
  1245. }
  1246. if ( BindPoseNode ) {
  1247. var PoseNode = BindPoseNode.subNodes.PoseNode;
  1248. var worldMatrices = new Map();
  1249. for ( var PoseNodeIndex = 0, PoseNodeLength = PoseNode.length; PoseNodeIndex < PoseNodeLength; ++ PoseNodeIndex ) {
  1250. var node = PoseNode[ PoseNodeIndex ];
  1251. var rawMatWrd = parseMatrixArray( node.subNodes.Matrix.properties.a );
  1252. worldMatrices.set( parseInt( node.id ), rawMatWrd );
  1253. }
  1254. }
  1255. for ( var FBX_ID in deformers ) {
  1256. var deformer = deformers[ FBX_ID ];
  1257. var subDeformers = deformer.map;
  1258. for ( var key in subDeformers ) {
  1259. var subDeformer = subDeformers[ key ];
  1260. var subDeformerIndex = subDeformer.index;
  1261. /**
  1262. * @type {THREE.Bone}
  1263. */
  1264. var bone = deformer.bones[ subDeformerIndex ];
  1265. if ( ! worldMatrices.has( bone.FBX_ID ) ) {
  1266. break;
  1267. }
  1268. var mat = worldMatrices.get( bone.FBX_ID );
  1269. bone.matrixWorld.copy( mat );
  1270. }
  1271. // Now that skeleton is in bind pose, bind to model.
  1272. deformer.skeleton = new THREE.Skeleton( deformer.bones );
  1273. var conns = connections.get( deformer.FBX_ID );
  1274. var parents = conns.parents;
  1275. for ( var parentsIndex = 0, parentsLength = parents.length; parentsIndex < parentsLength; ++ parentsIndex ) {
  1276. var parent = parents[ parentsIndex ];
  1277. if ( geometryMap.has( parent.ID ) ) {
  1278. var geoID = parent.ID;
  1279. var geoConns = connections.get( geoID );
  1280. for ( var i = 0; i < geoConns.parents.length; ++ i ) {
  1281. if ( modelMap.has( geoConns.parents[ i ].ID ) ) {
  1282. var model = modelMap.get( geoConns.parents[ i ].ID );
  1283. //ASSERT model typeof SkinnedMesh
  1284. model.bind( deformer.skeleton, model.matrixWorld );
  1285. break;
  1286. }
  1287. }
  1288. }
  1289. }
  1290. }
  1291. //Skeleton is now bound, return objects to starting
  1292. //world positions.
  1293. sceneGraph.updateMatrixWorld( true );
  1294. // Silly hack with the animation parsing. We're gonna pretend the scene graph has a skeleton
  1295. // to attach animations to, since FBXs treat animations as animations for the entire scene,
  1296. // not just for individual objects.
  1297. sceneGraph.skeleton = {
  1298. bones: modelArray
  1299. };
  1300. var animations = parseAnimations( FBXTree, connections, sceneGraph );
  1301. addAnimations( sceneGraph, animations );
  1302. // Parse ambient color - if it's not set to black (default), create an ambient light
  1303. if ( 'GlobalSettings' in FBXTree && 'AmbientColor' in FBXTree.GlobalSettings.properties ) {
  1304. var ambientColor = FBXTree.GlobalSettings.properties.AmbientColor.value;
  1305. var r = ambientColor[ 0 ];
  1306. var g = ambientColor[ 1 ];
  1307. var b = ambientColor[ 2 ];
  1308. if ( r !== 0 || g !== 0 || b !== 0 ) {
  1309. var color = new THREE.Color( r, g, b );
  1310. sceneGraph.add( new THREE.AmbientLight( color, 1 ) );
  1311. }
  1312. }
  1313. return sceneGraph;
  1314. }
  1315. /**
  1316. * Parses animation information from FBXTree and generates an AnimationInfoObject.
  1317. * @param {{Objects: {subNodes: {AnimationCurveNode: any, AnimationCurve: any, AnimationLayer: any, AnimationStack: any}}}} FBXTree
  1318. * @param {Map<number, {parents: {ID: number, relationship: string}[], children: {ID: number, relationship: string}[]}>} connections
  1319. */
  1320. function parseAnimations( FBXTree, connections, sceneGraph ) {
  1321. var rawNodes = FBXTree.Objects.subNodes.AnimationCurveNode;
  1322. var rawCurves = FBXTree.Objects.subNodes.AnimationCurve;
  1323. var rawLayers = FBXTree.Objects.subNodes.AnimationLayer;
  1324. var rawStacks = FBXTree.Objects.subNodes.AnimationStack;
  1325. /**
  1326. * @type {{
  1327. curves: Map<number, {
  1328. T: {
  1329. id: number;
  1330. attr: string;
  1331. internalID: number;
  1332. attrX: boolean;
  1333. attrY: boolean;
  1334. attrZ: boolean;
  1335. containerBoneID: number;
  1336. containerID: number;
  1337. curves: {
  1338. x: {
  1339. version: any;
  1340. id: number;
  1341. internalID: number;
  1342. times: number[];
  1343. values: number[];
  1344. attrFlag: number[];
  1345. attrData: number[];
  1346. };
  1347. y: {
  1348. version: any;
  1349. id: number;
  1350. internalID: number;
  1351. times: number[];
  1352. values: number[];
  1353. attrFlag: number[];
  1354. attrData: number[];
  1355. };
  1356. z: {
  1357. version: any;
  1358. id: number;
  1359. internalID: number;
  1360. times: number[];
  1361. values: number[];
  1362. attrFlag: number[];
  1363. attrData: number[];
  1364. };
  1365. };
  1366. },
  1367. R: {
  1368. id: number;
  1369. attr: string;
  1370. internalID: number;
  1371. attrX: boolean;
  1372. attrY: boolean;
  1373. attrZ: boolean;
  1374. containerBoneID: number;
  1375. containerID: number;
  1376. curves: {
  1377. x: {
  1378. version: any;
  1379. id: number;
  1380. internalID: number;
  1381. times: number[];
  1382. values: number[];
  1383. attrFlag: number[];
  1384. attrData: number[];
  1385. };
  1386. y: {
  1387. version: any;
  1388. id: number;
  1389. internalID: number;
  1390. times: number[];
  1391. values: number[];
  1392. attrFlag: number[];
  1393. attrData: number[];
  1394. };
  1395. z: {
  1396. version: any;
  1397. id: number;
  1398. internalID: number;
  1399. times: number[];
  1400. values: number[];
  1401. attrFlag: number[];
  1402. attrData: number[];
  1403. };
  1404. };
  1405. },
  1406. S: {
  1407. id: number;
  1408. attr: string;
  1409. internalID: number;
  1410. attrX: boolean;
  1411. attrY: boolean;
  1412. attrZ: boolean;
  1413. containerBoneID: number;
  1414. containerID: number;
  1415. curves: {
  1416. x: {
  1417. version: any;
  1418. id: number;
  1419. internalID: number;
  1420. times: number[];
  1421. values: number[];
  1422. attrFlag: number[];
  1423. attrData: number[];
  1424. };
  1425. y: {
  1426. version: any;
  1427. id: number;
  1428. internalID: number;
  1429. times: number[];
  1430. values: number[];
  1431. attrFlag: number[];
  1432. attrData: number[];
  1433. };
  1434. z: {
  1435. version: any;
  1436. id: number;
  1437. internalID: number;
  1438. times: number[];
  1439. values: number[];
  1440. attrFlag: number[];
  1441. attrData: number[];
  1442. };
  1443. };
  1444. }
  1445. }>,
  1446. layers: Map<number, {
  1447. T: {
  1448. id: number;
  1449. attr: string;
  1450. internalID: number;
  1451. attrX: boolean;
  1452. attrY: boolean;
  1453. attrZ: boolean;
  1454. containerBoneID: number;
  1455. containerID: number;
  1456. curves: {
  1457. x: {
  1458. version: any;
  1459. id: number;
  1460. internalID: number;
  1461. times: number[];
  1462. values: number[];
  1463. attrFlag: number[];
  1464. attrData: number[];
  1465. };
  1466. y: {
  1467. version: any;
  1468. id: number;
  1469. internalID: number;
  1470. times: number[];
  1471. values: number[];
  1472. attrFlag: number[];
  1473. attrData: number[];
  1474. };
  1475. z: {
  1476. version: any;
  1477. id: number;
  1478. internalID: number;
  1479. times: number[];
  1480. values: number[];
  1481. attrFlag: number[];
  1482. attrData: number[];
  1483. };
  1484. },
  1485. },
  1486. R: {
  1487. id: number;
  1488. attr: string;
  1489. internalID: number;
  1490. attrX: boolean;
  1491. attrY: boolean;
  1492. attrZ: boolean;
  1493. containerBoneID: number;
  1494. containerID: number;
  1495. curves: {
  1496. x: {
  1497. version: any;
  1498. id: number;
  1499. internalID: number;
  1500. times: number[];
  1501. values: number[];
  1502. attrFlag: number[];
  1503. attrData: number[];
  1504. };
  1505. y: {
  1506. version: any;
  1507. id: number;
  1508. internalID: number;
  1509. times: number[];
  1510. values: number[];
  1511. attrFlag: number[];
  1512. attrData: number[];
  1513. };
  1514. z: {
  1515. version: any;
  1516. id: number;
  1517. internalID: number;
  1518. times: number[];
  1519. values: number[];
  1520. attrFlag: number[];
  1521. attrData: number[];
  1522. };
  1523. },
  1524. },
  1525. S: {
  1526. id: number;
  1527. attr: string;
  1528. internalID: number;
  1529. attrX: boolean;
  1530. attrY: boolean;
  1531. attrZ: boolean;
  1532. containerBoneID: number;
  1533. containerID: number;
  1534. curves: {
  1535. x: {
  1536. version: any;
  1537. id: number;
  1538. internalID: number;
  1539. times: number[];
  1540. values: number[];
  1541. attrFlag: number[];
  1542. attrData: number[];
  1543. };
  1544. y: {
  1545. version: any;
  1546. id: number;
  1547. internalID: number;
  1548. times: number[];
  1549. values: number[];
  1550. attrFlag: number[];
  1551. attrData: number[];
  1552. };
  1553. z: {
  1554. version: any;
  1555. id: number;
  1556. internalID: number;
  1557. times: number[];
  1558. values: number[];
  1559. attrFlag: number[];
  1560. attrData: number[];
  1561. };
  1562. },
  1563. }
  1564. }[]>,
  1565. stacks: Map<number, {
  1566. name: string,
  1567. layers: {
  1568. T: {
  1569. id: number;
  1570. attr: string;
  1571. internalID: number;
  1572. attrX: boolean;
  1573. attrY: boolean;
  1574. attrZ: boolean;
  1575. containerBoneID: number;
  1576. containerID: number;
  1577. curves: {
  1578. x: {
  1579. version: any;
  1580. id: number;
  1581. internalID: number;
  1582. times: number[];
  1583. values: number[];
  1584. attrFlag: number[];
  1585. attrData: number[];
  1586. };
  1587. y: {
  1588. version: any;
  1589. id: number;
  1590. internalID: number;
  1591. times: number[];
  1592. values: number[];
  1593. attrFlag: number[];
  1594. attrData: number[];
  1595. };
  1596. z: {
  1597. version: any;
  1598. id: number;
  1599. internalID: number;
  1600. times: number[];
  1601. values: number[];
  1602. attrFlag: number[];
  1603. attrData: number[];
  1604. };
  1605. };
  1606. };
  1607. R: {
  1608. id: number;
  1609. attr: string;
  1610. internalID: number;
  1611. attrX: boolean;
  1612. attrY: boolean;
  1613. attrZ: boolean;
  1614. containerBoneID: number;
  1615. containerID: number;
  1616. curves: {
  1617. x: {
  1618. version: any;
  1619. id: number;
  1620. internalID: number;
  1621. times: number[];
  1622. values: number[];
  1623. attrFlag: number[];
  1624. attrData: number[];
  1625. };
  1626. y: {
  1627. version: any;
  1628. id: number;
  1629. internalID: number;
  1630. times: number[];
  1631. values: number[];
  1632. attrFlag: number[];
  1633. attrData: number[];
  1634. };
  1635. z: {
  1636. version: any;
  1637. id: number;
  1638. internalID: number;
  1639. times: number[];
  1640. values: number[];
  1641. attrFlag: number[];
  1642. attrData: number[];
  1643. };
  1644. };
  1645. };
  1646. S: {
  1647. id: number;
  1648. attr: string;
  1649. internalID: number;
  1650. attrX: boolean;
  1651. attrY: boolean;
  1652. attrZ: boolean;
  1653. containerBoneID: number;
  1654. containerID: number;
  1655. curves: {
  1656. x: {
  1657. version: any;
  1658. id: number;
  1659. internalID: number;
  1660. times: number[];
  1661. values: number[];
  1662. attrFlag: number[];
  1663. attrData: number[];
  1664. };
  1665. y: {
  1666. version: any;
  1667. id: number;
  1668. internalID: number;
  1669. times: number[];
  1670. values: number[];
  1671. attrFlag: number[];
  1672. attrData: number[];
  1673. };
  1674. z: {
  1675. version: any;
  1676. id: number;
  1677. internalID: number;
  1678. times: number[];
  1679. values: number[];
  1680. attrFlag: number[];
  1681. attrData: number[];
  1682. };
  1683. };
  1684. };
  1685. }[][],
  1686. length: number,
  1687. frames: number }>,
  1688. length: number,
  1689. fps: number,
  1690. frames: number
  1691. }}
  1692. */
  1693. var returnObject = {
  1694. curves: new Map(),
  1695. layers: {},
  1696. stacks: {},
  1697. length: 0,
  1698. fps: 30,
  1699. frames: 0
  1700. };
  1701. /**
  1702. * @type {Array.<{
  1703. id: number;
  1704. attr: string;
  1705. internalID: number;
  1706. attrX: boolean;
  1707. attrY: boolean;
  1708. attrZ: boolean;
  1709. containerBoneID: number;
  1710. containerID: number;
  1711. }>}
  1712. */
  1713. var animationCurveNodes = [];
  1714. for ( var nodeID in rawNodes ) {
  1715. if ( nodeID.match( /\d+/ ) ) {
  1716. var animationNode = parseAnimationNode( FBXTree, rawNodes[ nodeID ], connections, sceneGraph );
  1717. animationCurveNodes.push( animationNode );
  1718. }
  1719. }
  1720. /**
  1721. * @type {Map.<number, {
  1722. id: number,
  1723. attr: string,
  1724. internalID: number,
  1725. attrX: boolean,
  1726. attrY: boolean,
  1727. attrZ: boolean,
  1728. containerBoneID: number,
  1729. containerID: number,
  1730. curves: {
  1731. x: {
  1732. version: any,
  1733. id: number,
  1734. internalID: number,
  1735. times: number[],
  1736. values: number[],
  1737. attrFlag: number[],
  1738. attrData: number[],
  1739. },
  1740. y: {
  1741. version: any,
  1742. id: number,
  1743. internalID: number,
  1744. times: number[],
  1745. values: number[],
  1746. attrFlag: number[],
  1747. attrData: number[],
  1748. },
  1749. z: {
  1750. version: any,
  1751. id: number,
  1752. internalID: number,
  1753. times: number[],
  1754. values: number[],
  1755. attrFlag: number[],
  1756. attrData: number[],
  1757. }
  1758. }
  1759. }>}
  1760. */
  1761. var tmpMap = new Map();
  1762. for ( var animationCurveNodeIndex = 0; animationCurveNodeIndex < animationCurveNodes.length; ++ animationCurveNodeIndex ) {
  1763. if ( animationCurveNodes[ animationCurveNodeIndex ] === null ) {
  1764. continue;
  1765. }
  1766. tmpMap.set( animationCurveNodes[ animationCurveNodeIndex ].id, animationCurveNodes[ animationCurveNodeIndex ] );
  1767. }
  1768. /**
  1769. * @type {{
  1770. version: any,
  1771. id: number,
  1772. internalID: number,
  1773. times: number[],
  1774. values: number[],
  1775. attrFlag: number[],
  1776. attrData: number[],
  1777. }[]}
  1778. */
  1779. var animationCurves = [];
  1780. for ( nodeID in rawCurves ) {
  1781. if ( nodeID.match( /\d+/ ) ) {
  1782. var animationCurve = parseAnimationCurve( rawCurves[ nodeID ] );
  1783. // seems like this check would be necessary?
  1784. if ( ! connections.has( animationCurve.id ) ) continue;
  1785. animationCurves.push( animationCurve );
  1786. var firstParentConn = connections.get( animationCurve.id ).parents[ 0 ];
  1787. var firstParentID = firstParentConn.ID;
  1788. var firstParentRelationship = firstParentConn.relationship;
  1789. var axis = '';
  1790. if ( firstParentRelationship.match( /X/ ) ) {
  1791. axis = 'x';
  1792. } else if ( firstParentRelationship.match( /Y/ ) ) {
  1793. axis = 'y';
  1794. } else if ( firstParentRelationship.match( /Z/ ) ) {
  1795. axis = 'z';
  1796. } else {
  1797. continue;
  1798. }
  1799. tmpMap.get( firstParentID ).curves[ axis ] = animationCurve;
  1800. }
  1801. }
  1802. tmpMap.forEach( function ( curveNode ) {
  1803. var id = curveNode.containerBoneID;
  1804. if ( ! returnObject.curves.has( id ) ) {
  1805. returnObject.curves.set( id, { T: null, R: null, S: null } );
  1806. }
  1807. returnObject.curves.get( id )[ curveNode.attr ] = curveNode;
  1808. if ( curveNode.attr === 'R' ) {
  1809. var curves = curveNode.curves;
  1810. // Seems like some FBX files have AnimationCurveNode
  1811. // which doesn't have any connected AnimationCurve.
  1812. // Setting animation parameter for them here.
  1813. if ( curves.x === null ) {
  1814. curves.x = {
  1815. version: null,
  1816. times: [ 0.0 ],
  1817. values: [ 0.0 ]
  1818. };
  1819. }
  1820. if ( curves.y === null ) {
  1821. curves.y = {
  1822. version: null,
  1823. times: [ 0.0 ],
  1824. values: [ 0.0 ]
  1825. };
  1826. }
  1827. if ( curves.z === null ) {
  1828. curves.z = {
  1829. version: null,
  1830. times: [ 0.0 ],
  1831. values: [ 0.0 ]
  1832. };
  1833. }
  1834. curves.x.values = curves.x.values.map( degreeToRadian );
  1835. curves.y.values = curves.y.values.map( degreeToRadian );
  1836. curves.z.values = curves.z.values.map( degreeToRadian );
  1837. if ( curveNode.preRotations !== null ) {
  1838. var preRotations = new THREE.Euler().setFromVector3( curveNode.preRotations, 'ZYX' );
  1839. preRotations = new THREE.Quaternion().setFromEuler( preRotations );
  1840. var frameRotation = new THREE.Euler();
  1841. var frameRotationQuaternion = new THREE.Quaternion();
  1842. for ( var frame = 0; frame < curves.x.times.length; ++ frame ) {
  1843. frameRotation.set( curves.x.values[ frame ], curves.y.values[ frame ], curves.z.values[ frame ], 'ZYX' );
  1844. frameRotationQuaternion.setFromEuler( frameRotation ).premultiply( preRotations );
  1845. frameRotation.setFromQuaternion( frameRotationQuaternion, 'ZYX' );
  1846. curves.x.values[ frame ] = frameRotation.x;
  1847. curves.y.values[ frame ] = frameRotation.y;
  1848. curves.z.values[ frame ] = frameRotation.z;
  1849. }
  1850. }
  1851. }
  1852. } );
  1853. for ( var nodeID in rawLayers ) {
  1854. /**
  1855. * @type {{
  1856. T: {
  1857. id: number;
  1858. attr: string;
  1859. internalID: number;
  1860. attrX: boolean;
  1861. attrY: boolean;
  1862. attrZ: boolean;
  1863. containerBoneID: number;
  1864. containerID: number;
  1865. curves: {
  1866. x: {
  1867. version: any;
  1868. id: number;
  1869. internalID: number;
  1870. times: number[];
  1871. values: number[];
  1872. attrFlag: number[];
  1873. attrData: number[];
  1874. };
  1875. y: {
  1876. version: any;
  1877. id: number;
  1878. internalID: number;
  1879. times: number[];
  1880. values: number[];
  1881. attrFlag: number[];
  1882. attrData: number[];
  1883. };
  1884. z: {
  1885. version: any;
  1886. id: number;
  1887. internalID: number;
  1888. times: number[];
  1889. values: number[];
  1890. attrFlag: number[];
  1891. attrData: number[];
  1892. };
  1893. },
  1894. },
  1895. R: {
  1896. id: number;
  1897. attr: string;
  1898. internalID: number;
  1899. attrX: boolean;
  1900. attrY: boolean;
  1901. attrZ: boolean;
  1902. containerBoneID: number;
  1903. containerID: number;
  1904. curves: {
  1905. x: {
  1906. version: any;
  1907. id: number;
  1908. internalID: number;
  1909. times: number[];
  1910. values: number[];
  1911. attrFlag: number[];
  1912. attrData: number[];
  1913. };
  1914. y: {
  1915. version: any;
  1916. id: number;
  1917. internalID: number;
  1918. times: number[];
  1919. values: number[];
  1920. attrFlag: number[];
  1921. attrData: number[];
  1922. };
  1923. z: {
  1924. version: any;
  1925. id: number;
  1926. internalID: number;
  1927. times: number[];
  1928. values: number[];
  1929. attrFlag: number[];
  1930. attrData: number[];
  1931. };
  1932. },
  1933. },
  1934. S: {
  1935. id: number;
  1936. attr: string;
  1937. internalID: number;
  1938. attrX: boolean;
  1939. attrY: boolean;
  1940. attrZ: boolean;
  1941. containerBoneID: number;
  1942. containerID: number;
  1943. curves: {
  1944. x: {
  1945. version: any;
  1946. id: number;
  1947. internalID: number;
  1948. times: number[];
  1949. values: number[];
  1950. attrFlag: number[];
  1951. attrData: number[];
  1952. };
  1953. y: {
  1954. version: any;
  1955. id: number;
  1956. internalID: number;
  1957. times: number[];
  1958. values: number[];
  1959. attrFlag: number[];
  1960. attrData: number[];
  1961. };
  1962. z: {
  1963. version: any;
  1964. id: number;
  1965. internalID: number;
  1966. times: number[];
  1967. values: number[];
  1968. attrFlag: number[];
  1969. attrData: number[];
  1970. };
  1971. },
  1972. }
  1973. }[]}
  1974. */
  1975. var layer = [];
  1976. var children = connections.get( parseInt( nodeID ) ).children;
  1977. for ( var childIndex = 0; childIndex < children.length; childIndex ++ ) {
  1978. // Skip lockInfluenceWeights
  1979. if ( tmpMap.has( children[ childIndex ].ID ) ) {
  1980. var curveNode = tmpMap.get( children[ childIndex ].ID );
  1981. var boneID = curveNode.containerBoneID;
  1982. if ( layer[ boneID ] === undefined ) {
  1983. layer[ boneID ] = {
  1984. T: null,
  1985. R: null,
  1986. S: null
  1987. };
  1988. }
  1989. layer[ boneID ][ curveNode.attr ] = curveNode;
  1990. }
  1991. }
  1992. returnObject.layers[ nodeID ] = layer;
  1993. }
  1994. for ( var nodeID in rawStacks ) {
  1995. var layers = [];
  1996. var children = connections.get( parseInt( nodeID ) ).children;
  1997. var timestamps = { max: 0, min: Number.MAX_VALUE };
  1998. for ( var childIndex = 0; childIndex < children.length; ++ childIndex ) {
  1999. var currentLayer = returnObject.layers[ children[ childIndex ].ID ];
  2000. if ( currentLayer !== undefined ) {
  2001. layers.push( currentLayer );
  2002. for ( var currentLayerIndex = 0, currentLayerLength = currentLayer.length; currentLayerIndex < currentLayerLength; ++ currentLayerIndex ) {
  2003. var layer = currentLayer[ currentLayerIndex ];
  2004. if ( layer ) {
  2005. getCurveNodeMaxMinTimeStamps( layer, timestamps );
  2006. }
  2007. }
  2008. }
  2009. }
  2010. // Do we have an animation clip with actual length?
  2011. if ( timestamps.max > timestamps.min ) {
  2012. returnObject.stacks[ nodeID ] = {
  2013. name: rawStacks[ nodeID ].attrName,
  2014. layers: layers,
  2015. length: timestamps.max - timestamps.min,
  2016. frames: ( timestamps.max - timestamps.min ) * 30
  2017. };
  2018. }
  2019. }
  2020. return returnObject;
  2021. }
  2022. /**
  2023. * @param {Object} FBXTree
  2024. * @param {{id: number, attrName: string, properties: Object<string, any>}} animationCurveNode
  2025. * @param {Map<number, {parents: {ID: number, relationship: string}[], children: {ID: number, relationship: string}[]}>} connections
  2026. * @param {{skeleton: {bones: {FBX_ID: number}[]}}} sceneGraph
  2027. */
  2028. function parseAnimationNode( FBXTree, animationCurveNode, connections, sceneGraph ) {
  2029. var rawModels = FBXTree.Objects.subNodes.Model;
  2030. var returnObject = {
  2031. /**
  2032. * @type {number}
  2033. */
  2034. id: animationCurveNode.id,
  2035. /**
  2036. * @type {string}
  2037. */
  2038. attr: animationCurveNode.attrName,
  2039. /**
  2040. * @type {number}
  2041. */
  2042. internalID: animationCurveNode.id,
  2043. /**
  2044. * @type {boolean}
  2045. */
  2046. attrX: false,
  2047. /**
  2048. * @type {boolean}
  2049. */
  2050. attrY: false,
  2051. /**
  2052. * @type {boolean}
  2053. */
  2054. attrZ: false,
  2055. /**
  2056. * @type {number}
  2057. */
  2058. containerBoneID: - 1,
  2059. /**
  2060. * @type {number}
  2061. */
  2062. containerID: - 1,
  2063. curves: {
  2064. x: null,
  2065. y: null,
  2066. z: null
  2067. },
  2068. /**
  2069. * @type {number[]}
  2070. */
  2071. preRotations: null
  2072. };
  2073. if ( returnObject.attr.match( /S|R|T/ ) ) {
  2074. for ( var attributeKey in animationCurveNode.properties ) {
  2075. if ( attributeKey.match( /X/ ) ) {
  2076. returnObject.attrX = true;
  2077. }
  2078. if ( attributeKey.match( /Y/ ) ) {
  2079. returnObject.attrY = true;
  2080. }
  2081. if ( attributeKey.match( /Z/ ) ) {
  2082. returnObject.attrZ = true;
  2083. }
  2084. }
  2085. } else {
  2086. return null;
  2087. }
  2088. var conns = connections.get( returnObject.id );
  2089. var containerIndices = conns.parents;
  2090. for ( var containerIndicesIndex = containerIndices.length - 1; containerIndicesIndex >= 0; -- containerIndicesIndex ) {
  2091. var boneID = findIndex( sceneGraph.skeleton.bones, function ( bone ) {
  2092. return bone.FBX_ID === containerIndices[ containerIndicesIndex ].ID;
  2093. } );
  2094. if ( boneID > - 1 ) {
  2095. returnObject.containerBoneID = boneID;
  2096. returnObject.containerID = containerIndices[ containerIndicesIndex ].ID;
  2097. var model = rawModels[ returnObject.containerID.toString() ];
  2098. if ( 'PreRotation' in model.properties ) {
  2099. returnObject.preRotations = parseVector3( model.properties.PreRotation ).multiplyScalar( Math.PI / 180 );
  2100. }
  2101. break;
  2102. }
  2103. }
  2104. return returnObject;
  2105. }
  2106. /**
  2107. * @param {{id: number, subNodes: {KeyTime: {properties: {a: string}}, KeyValueFloat: {properties: {a: string}}, KeyAttrFlags: {properties: {a: string}}, KeyAttrDataFloat: {properties: {a: string}}}}} animationCurve
  2108. */
  2109. function parseAnimationCurve( animationCurve ) {
  2110. return {
  2111. version: null,
  2112. id: animationCurve.id,
  2113. internalID: animationCurve.id,
  2114. times: parseFloatArray( animationCurve.subNodes.KeyTime.properties.a ).map( convertFBXTimeToSeconds ),
  2115. values: parseFloatArray( animationCurve.subNodes.KeyValueFloat.properties.a ),
  2116. attrFlag: parseIntArray( animationCurve.subNodes.KeyAttrFlags.properties.a ),
  2117. attrData: parseFloatArray( animationCurve.subNodes.KeyAttrDataFloat.properties.a )
  2118. };
  2119. }
  2120. /**
  2121. * Sets the maxTimeStamp and minTimeStamp variables if it has timeStamps that are either larger or smaller
  2122. * than the max or min respectively.
  2123. * @param {{
  2124. T: {
  2125. id: number,
  2126. attr: string,
  2127. internalID: number,
  2128. attrX: boolean,
  2129. attrY: boolean,
  2130. attrZ: boolean,
  2131. containerBoneID: number,
  2132. containerID: number,
  2133. curves: {
  2134. x: {
  2135. version: any,
  2136. id: number,
  2137. internalID: number,
  2138. times: number[],
  2139. values: number[],
  2140. attrFlag: number[],
  2141. attrData: number[],
  2142. },
  2143. y: {
  2144. version: any,
  2145. id: number,
  2146. internalID: number,
  2147. times: number[],
  2148. values: number[],
  2149. attrFlag: number[],
  2150. attrData: number[],
  2151. },
  2152. z: {
  2153. version: any,
  2154. id: number,
  2155. internalID: number,
  2156. times: number[],
  2157. values: number[],
  2158. attrFlag: number[],
  2159. attrData: number[],
  2160. },
  2161. },
  2162. },
  2163. R: {
  2164. id: number,
  2165. attr: string,
  2166. internalID: number,
  2167. attrX: boolean,
  2168. attrY: boolean,
  2169. attrZ: boolean,
  2170. containerBoneID: number,
  2171. containerID: number,
  2172. curves: {
  2173. x: {
  2174. version: any,
  2175. id: number,
  2176. internalID: number,
  2177. times: number[],
  2178. values: number[],
  2179. attrFlag: number[],
  2180. attrData: number[],
  2181. },
  2182. y: {
  2183. version: any,
  2184. id: number,
  2185. internalID: number,
  2186. times: number[],
  2187. values: number[],
  2188. attrFlag: number[],
  2189. attrData: number[],
  2190. },
  2191. z: {
  2192. version: any,
  2193. id: number,
  2194. internalID: number,
  2195. times: number[],
  2196. values: number[],
  2197. attrFlag: number[],
  2198. attrData: number[],
  2199. },
  2200. },
  2201. },
  2202. S: {
  2203. id: number,
  2204. attr: string,
  2205. internalID: number,
  2206. attrX: boolean,
  2207. attrY: boolean,
  2208. attrZ: boolean,
  2209. containerBoneID: number,
  2210. containerID: number,
  2211. curves: {
  2212. x: {
  2213. version: any,
  2214. id: number,
  2215. internalID: number,
  2216. times: number[],
  2217. values: number[],
  2218. attrFlag: number[],
  2219. attrData: number[],
  2220. },
  2221. y: {
  2222. version: any,
  2223. id: number,
  2224. internalID: number,
  2225. times: number[],
  2226. values: number[],
  2227. attrFlag: number[],
  2228. attrData: number[],
  2229. },
  2230. z: {
  2231. version: any,
  2232. id: number,
  2233. internalID: number,
  2234. times: number[],
  2235. values: number[],
  2236. attrFlag: number[],
  2237. attrData: number[],
  2238. },
  2239. },
  2240. },
  2241. }} layer
  2242. */
  2243. function getCurveNodeMaxMinTimeStamps( layer, timestamps ) {
  2244. if ( layer.R ) {
  2245. getCurveMaxMinTimeStamp( layer.R.curves, timestamps );
  2246. }
  2247. if ( layer.S ) {
  2248. getCurveMaxMinTimeStamp( layer.S.curves, timestamps );
  2249. }
  2250. if ( layer.T ) {
  2251. getCurveMaxMinTimeStamp( layer.T.curves, timestamps );
  2252. }
  2253. }
  2254. /**
  2255. * Sets the maxTimeStamp and minTimeStamp if one of the curve's time stamps
  2256. * exceeds the maximum or minimum.
  2257. * @param {{
  2258. x: {
  2259. version: any,
  2260. id: number,
  2261. internalID: number,
  2262. times: number[],
  2263. values: number[],
  2264. attrFlag: number[],
  2265. attrData: number[],
  2266. },
  2267. y: {
  2268. version: any,
  2269. id: number,
  2270. internalID: number,
  2271. times: number[],
  2272. values: number[],
  2273. attrFlag: number[],
  2274. attrData: number[],
  2275. },
  2276. z: {
  2277. version: any,
  2278. id: number,
  2279. internalID: number,
  2280. times: number[],
  2281. values: number[],
  2282. attrFlag: number[],
  2283. attrData: number[],
  2284. }
  2285. }} curve
  2286. */
  2287. function getCurveMaxMinTimeStamp( curve, timestamps ) {
  2288. if ( curve.x ) {
  2289. getCurveAxisMaxMinTimeStamps( curve.x, timestamps );
  2290. }
  2291. if ( curve.y ) {
  2292. getCurveAxisMaxMinTimeStamps( curve.y, timestamps );
  2293. }
  2294. if ( curve.z ) {
  2295. getCurveAxisMaxMinTimeStamps( curve.z, timestamps );
  2296. }
  2297. }
  2298. /**
  2299. * Sets the maxTimeStamp and minTimeStamp if one of its timestamps exceeds the maximum or minimum.
  2300. * @param {{times: number[]}} axis
  2301. */
  2302. function getCurveAxisMaxMinTimeStamps( axis, timestamps ) {
  2303. timestamps.max = axis.times[ axis.times.length - 1 ] > timestamps.max ? axis.times[ axis.times.length - 1 ] : timestamps.max;
  2304. timestamps.min = axis.times[ 0 ] < timestamps.min ? axis.times[ 0 ] : timestamps.min;
  2305. }
  2306. /**
  2307. * @param {{
  2308. curves: Map<number, {
  2309. T: {
  2310. id: number;
  2311. attr: string;
  2312. internalID: number;
  2313. attrX: boolean;
  2314. attrY: boolean;
  2315. attrZ: boolean;
  2316. containerBoneID: number;
  2317. containerID: number;
  2318. curves: {
  2319. x: {
  2320. version: any;
  2321. id: number;
  2322. internalID: number;
  2323. times: number[];
  2324. values: number[];
  2325. attrFlag: number[];
  2326. attrData: number[];
  2327. };
  2328. y: {
  2329. version: any;
  2330. id: number;
  2331. internalID: number;
  2332. times: number[];
  2333. values: number[];
  2334. attrFlag: number[];
  2335. attrData: number[];
  2336. };
  2337. z: {
  2338. version: any;
  2339. id: number;
  2340. internalID: number;
  2341. times: number[];
  2342. values: number[];
  2343. attrFlag: number[];
  2344. attrData: number[];
  2345. };
  2346. };
  2347. };
  2348. R: {
  2349. id: number;
  2350. attr: string;
  2351. internalID: number;
  2352. attrX: boolean;
  2353. attrY: boolean;
  2354. attrZ: boolean;
  2355. containerBoneID: number;
  2356. containerID: number;
  2357. curves: {
  2358. x: {
  2359. version: any;
  2360. id: number;
  2361. internalID: number;
  2362. times: number[];
  2363. values: number[];
  2364. attrFlag: number[];
  2365. attrData: number[];
  2366. };
  2367. y: {
  2368. version: any;
  2369. id: number;
  2370. internalID: number;
  2371. times: number[];
  2372. values: number[];
  2373. attrFlag: number[];
  2374. attrData: number[];
  2375. };
  2376. z: {
  2377. version: any;
  2378. id: number;
  2379. internalID: number;
  2380. times: number[];
  2381. values: number[];
  2382. attrFlag: number[];
  2383. attrData: number[];
  2384. };
  2385. };
  2386. };
  2387. S: {
  2388. id: number;
  2389. attr: string;
  2390. internalID: number;
  2391. attrX: boolean;
  2392. attrY: boolean;
  2393. attrZ: boolean;
  2394. containerBoneID: number;
  2395. containerID: number;
  2396. curves: {
  2397. x: {
  2398. version: any;
  2399. id: number;
  2400. internalID: number;
  2401. times: number[];
  2402. values: number[];
  2403. attrFlag: number[];
  2404. attrData: number[];
  2405. };
  2406. y: {
  2407. version: any;
  2408. id: number;
  2409. internalID: number;
  2410. times: number[];
  2411. values: number[];
  2412. attrFlag: number[];
  2413. attrData: number[];
  2414. };
  2415. z: {
  2416. version: any;
  2417. id: number;
  2418. internalID: number;
  2419. times: number[];
  2420. values: number[];
  2421. attrFlag: number[];
  2422. attrData: number[];
  2423. };
  2424. };
  2425. };
  2426. }>;
  2427. layers: Map<number, {
  2428. T: {
  2429. id: number;
  2430. attr: string;
  2431. internalID: number;
  2432. attrX: boolean;
  2433. attrY: boolean;
  2434. attrZ: boolean;
  2435. containerBoneID: number;
  2436. containerID: number;
  2437. curves: {
  2438. x: {
  2439. version: any;
  2440. id: number;
  2441. internalID: number;
  2442. times: number[];
  2443. values: number[];
  2444. attrFlag: number[];
  2445. attrData: number[];
  2446. };
  2447. y: {
  2448. version: any;
  2449. id: number;
  2450. internalID: number;
  2451. times: number[];
  2452. values: number[];
  2453. attrFlag: number[];
  2454. attrData: number[];
  2455. };
  2456. z: {
  2457. version: any;
  2458. id: number;
  2459. internalID: number;
  2460. times: number[];
  2461. values: number[];
  2462. attrFlag: number[];
  2463. attrData: number[];
  2464. };
  2465. };
  2466. };
  2467. R: {
  2468. id: number;
  2469. attr: string;
  2470. internalID: number;
  2471. attrX: boolean;
  2472. attrY: boolean;
  2473. attrZ: boolean;
  2474. containerBoneID: number;
  2475. containerID: number;
  2476. curves: {
  2477. x: {
  2478. version: any;
  2479. id: number;
  2480. internalID: number;
  2481. times: number[];
  2482. values: number[];
  2483. attrFlag: number[];
  2484. attrData: number[];
  2485. };
  2486. y: {
  2487. version: any;
  2488. id: number;
  2489. internalID: number;
  2490. times: number[];
  2491. values: number[];
  2492. attrFlag: number[];
  2493. attrData: number[];
  2494. };
  2495. z: {
  2496. version: any;
  2497. id: number;
  2498. internalID: number;
  2499. times: number[];
  2500. values: number[];
  2501. attrFlag: number[];
  2502. attrData: number[];
  2503. };
  2504. };
  2505. };
  2506. S: {
  2507. id: number;
  2508. attr: string;
  2509. internalID: number;
  2510. attrX: boolean;
  2511. attrY: boolean;
  2512. attrZ: boolean;
  2513. containerBoneID: number;
  2514. containerID: number;
  2515. curves: {
  2516. x: {
  2517. version: any;
  2518. id: number;
  2519. internalID: number;
  2520. times: number[];
  2521. values: number[];
  2522. attrFlag: number[];
  2523. attrData: number[];
  2524. };
  2525. y: {
  2526. version: any;
  2527. id: number;
  2528. internalID: number;
  2529. times: number[];
  2530. values: number[];
  2531. attrFlag: number[];
  2532. attrData: number[];
  2533. };
  2534. z: {
  2535. version: any;
  2536. id: number;
  2537. internalID: number;
  2538. times: number[];
  2539. values: number[];
  2540. attrFlag: number[];
  2541. attrData: number[];
  2542. };
  2543. };
  2544. };
  2545. }[]>;
  2546. stacks: Map<number, {
  2547. name: string;
  2548. layers: {
  2549. T: {
  2550. id: number;
  2551. attr: string;
  2552. internalID: number;
  2553. attrX: boolean;
  2554. attrY: boolean;
  2555. attrZ: boolean;
  2556. containerBoneID: number;
  2557. containerID: number;
  2558. curves: {
  2559. x: {
  2560. version: any;
  2561. id: number;
  2562. internalID: number;
  2563. times: number[];
  2564. values: number[];
  2565. attrFlag: number[];
  2566. attrData: number[];
  2567. };
  2568. y: {
  2569. version: any;
  2570. id: number;
  2571. internalID: number;
  2572. times: number[];
  2573. values: number[];
  2574. attrFlag: number[];
  2575. attrData: number[];
  2576. };
  2577. z: {
  2578. version: any;
  2579. id: number;
  2580. internalID: number;
  2581. times: number[];
  2582. values: number[];
  2583. attrFlag: number[];
  2584. attrData: number[];
  2585. };
  2586. };
  2587. };
  2588. R: {
  2589. id: number;
  2590. attr: string;
  2591. internalID: number;
  2592. attrX: boolean;
  2593. attrY: boolean;
  2594. attrZ: boolean;
  2595. containerBoneID: number;
  2596. containerID: number;
  2597. curves: {
  2598. x: {
  2599. version: any;
  2600. id: number;
  2601. internalID: number;
  2602. times: number[];
  2603. values: number[];
  2604. attrFlag: number[];
  2605. attrData: number[];
  2606. };
  2607. y: {
  2608. version: any;
  2609. id: number;
  2610. internalID: number;
  2611. times: number[];
  2612. values: number[];
  2613. attrFlag: number[];
  2614. attrData: number[];
  2615. };
  2616. z: {
  2617. version: any;
  2618. id: number;
  2619. internalID: number;
  2620. times: number[];
  2621. values: number[];
  2622. attrFlag: number[];
  2623. attrData: number[];
  2624. };
  2625. };
  2626. };
  2627. S: {
  2628. id: number;
  2629. attr: string;
  2630. internalID: number;
  2631. attrX: boolean;
  2632. attrY: boolean;
  2633. attrZ: boolean;
  2634. containerBoneID: number;
  2635. containerID: number;
  2636. curves: {
  2637. x: {
  2638. version: any;
  2639. id: number;
  2640. internalID: number;
  2641. times: number[];
  2642. values: number[];
  2643. attrFlag: number[];
  2644. attrData: number[];
  2645. };
  2646. y: {
  2647. version: any;
  2648. id: number;
  2649. internalID: number;
  2650. times: number[];
  2651. values: number[];
  2652. attrFlag: number[];
  2653. attrData: number[];
  2654. };
  2655. z: {
  2656. version: any;
  2657. id: number;
  2658. internalID: number;
  2659. times: number[];
  2660. values: number[];
  2661. attrFlag: number[];
  2662. attrData: number[];
  2663. };
  2664. };
  2665. };
  2666. }[][];
  2667. length: number;
  2668. frames: number;
  2669. }>;
  2670. length: number;
  2671. fps: number;
  2672. frames: number;
  2673. }} animations,
  2674. * @param {{skeleton: { bones: THREE.Bone[]}}} group
  2675. */
  2676. function addAnimations( group, animations ) {
  2677. if ( group.animations === undefined ) {
  2678. group.animations = [];
  2679. }
  2680. var stacks = animations.stacks;
  2681. for ( var key in stacks ) {
  2682. var stack = stacks[ key ];
  2683. /**
  2684. * @type {{
  2685. * name: string,
  2686. * fps: number,
  2687. * length: number,
  2688. * hierarchy: Array.<{
  2689. * parent: number,
  2690. * name: string,
  2691. * keys: Array.<{
  2692. * time: number,
  2693. * pos: Array.<number>,
  2694. * rot: Array.<number>,
  2695. * scl: Array.<number>
  2696. * }>
  2697. * }>
  2698. * }}
  2699. */
  2700. var animationData = {
  2701. name: stack.name,
  2702. fps: 30,
  2703. length: stack.length,
  2704. hierarchy: []
  2705. };
  2706. var bones = group.skeleton.bones;
  2707. for ( var bonesIndex = 0, bonesLength = bones.length; bonesIndex < bonesLength; ++ bonesIndex ) {
  2708. var bone = bones[ bonesIndex ];
  2709. var name = bone.name.replace( /.*:/, '' );
  2710. var parentIndex = findIndex( bones, function ( parentBone ) {
  2711. return bone.parent === parentBone;
  2712. } );
  2713. animationData.hierarchy.push( { parent: parentIndex, name: name, keys: [] } );
  2714. }
  2715. for ( var frame = 0; frame <= stack.frames; frame ++ ) {
  2716. for ( var bonesIndex = 0, bonesLength = bones.length; bonesIndex < bonesLength; ++ bonesIndex ) {
  2717. var bone = bones[ bonesIndex ];
  2718. var boneIndex = bonesIndex;
  2719. var animationNode = stack.layers[ 0 ][ boneIndex ];
  2720. for ( var hierarchyIndex = 0, hierarchyLength = animationData.hierarchy.length; hierarchyIndex < hierarchyLength; ++ hierarchyIndex ) {
  2721. var node = animationData.hierarchy[ hierarchyIndex ];
  2722. if ( node.name === bone.name ) {
  2723. node.keys.push( generateKey( animations, animationNode, bone, frame ) );
  2724. }
  2725. }
  2726. }
  2727. }
  2728. group.animations.push( THREE.AnimationClip.parseAnimation( animationData, bones ) );
  2729. }
  2730. }
  2731. var euler = new THREE.Euler();
  2732. var quaternion = new THREE.Quaternion();
  2733. /**
  2734. * @param {THREE.Bone} bone
  2735. */
  2736. function generateKey( animations, animationNode, bone, frame ) {
  2737. var key = {
  2738. time: frame / animations.fps,
  2739. pos: bone.position.toArray(),
  2740. rot: bone.quaternion.toArray(),
  2741. scl: bone.scale.toArray()
  2742. };
  2743. if ( animationNode === undefined ) return key;
  2744. try {
  2745. if ( hasCurve( animationNode, 'T' ) && hasKeyOnFrame( animationNode.T, frame ) ) {
  2746. key.pos = [ animationNode.T.curves.x.values[ frame ], animationNode.T.curves.y.values[ frame ], animationNode.T.curves.z.values[ frame ] ];
  2747. }
  2748. if ( hasCurve( animationNode, 'R' ) && hasKeyOnFrame( animationNode.R, frame ) ) {
  2749. var rotationX = animationNode.R.curves.x.values[ frame ];
  2750. var rotationY = animationNode.R.curves.y.values[ frame ];
  2751. var rotationZ = animationNode.R.curves.z.values[ frame ];
  2752. quaternion.setFromEuler( euler.set( rotationX, rotationY, rotationZ, 'ZYX' ) );
  2753. key.rot = quaternion.toArray();
  2754. }
  2755. if ( hasCurve( animationNode, 'S' ) && hasKeyOnFrame( animationNode.S, frame ) ) {
  2756. key.scl = [ animationNode.S.curves.x.values[ frame ], animationNode.S.curves.y.values[ frame ], animationNode.S.curves.z.values[ frame ] ];
  2757. }
  2758. } catch ( error ) {
  2759. // Curve is not fully plotted.
  2760. console.log( 'THREE.FBXLoader: ', bone );
  2761. console.log( 'THREE.FBXLoader: ', error );
  2762. }
  2763. return key;
  2764. }
  2765. var AXES = [ 'x', 'y', 'z' ];
  2766. function hasCurve( animationNode, attribute ) {
  2767. if ( animationNode === undefined ) {
  2768. return false;
  2769. }
  2770. var attributeNode = animationNode[ attribute ];
  2771. if ( ! attributeNode ) {
  2772. return false;
  2773. }
  2774. return AXES.every( function ( key ) {
  2775. return attributeNode.curves[ key ] !== null;
  2776. } );
  2777. }
  2778. function hasKeyOnFrame( attributeNode, frame ) {
  2779. return AXES.every( function ( key ) {
  2780. return isKeyExistOnFrame( attributeNode.curves[ key ], frame );
  2781. } );
  2782. }
  2783. function isKeyExistOnFrame( curve, frame ) {
  2784. return curve.values[ frame ] !== undefined;
  2785. }
  2786. /**
  2787. * An instance of a Vertex with data for drawing vertices to the screen.
  2788. * @constructor
  2789. */
  2790. function Vertex() {
  2791. /**
  2792. * Position of the vertex.
  2793. * @type {THREE.Vector3}
  2794. */
  2795. this.position = new THREE.Vector3();
  2796. /**
  2797. * Normal of the vertex
  2798. * @type {THREE.Vector3}
  2799. */
  2800. this.normal = new THREE.Vector3();
  2801. /**
  2802. * Array of UV coordinates of the vertex.
  2803. * @type {Array of THREE.Vector2}
  2804. */
  2805. this.uv = [];
  2806. /**
  2807. * Color of the vertex
  2808. * @type {THREE.Vector3}
  2809. */
  2810. this.color = new THREE.Vector3();
  2811. /**
  2812. * Indices of the bones vertex is influenced by.
  2813. * @type {THREE.Vector4}
  2814. */
  2815. this.skinIndices = new THREE.Vector4( 0, 0, 0, 0 );
  2816. /**
  2817. * Weights that each bone influences the vertex.
  2818. * @type {THREE.Vector4}
  2819. */
  2820. this.skinWeights = new THREE.Vector4( 0, 0, 0, 0 );
  2821. }
  2822. Object.assign( Vertex.prototype, {
  2823. copy: function ( target ) {
  2824. var returnVar = target || new Vertex();
  2825. returnVar.position.copy( this.position );
  2826. returnVar.normal.copy( this.normal );
  2827. returnVar.uv.copy( this.uv );
  2828. returnVar.skinIndices.copy( this.skinIndices );
  2829. returnVar.skinWeights.copy( this.skinWeights );
  2830. return returnVar;
  2831. },
  2832. flattenToBuffers: function ( vertexBuffer, normalBuffer, uvBuffers, colorBuffer, skinIndexBuffer, skinWeightBuffer ) {
  2833. this.position.toArray( vertexBuffer, vertexBuffer.length );
  2834. this.normal.toArray( normalBuffer, normalBuffer.length );
  2835. for ( var i = 0; i < this.uv.length; i ++ ) {
  2836. this.uv[ i ].toArray( uvBuffers[ i ], uvBuffers[ i ].length );
  2837. }
  2838. this.color.toArray( colorBuffer, colorBuffer.length );
  2839. this.skinIndices.toArray( skinIndexBuffer, skinIndexBuffer.length );
  2840. this.skinWeights.toArray( skinWeightBuffer, skinWeightBuffer.length );
  2841. }
  2842. } );
  2843. /**
  2844. * @constructor
  2845. */
  2846. function Triangle() {
  2847. /**
  2848. * @type {{position: THREE.Vector3, normal: THREE.Vector3, uv: THREE.Vector2, skinIndices: THREE.Vector4, skinWeights: THREE.Vector4}[]}
  2849. */
  2850. this.vertices = [];
  2851. }
  2852. Object.assign( Triangle.prototype, {
  2853. copy: function ( target ) {
  2854. var returnVar = target || new Triangle();
  2855. for ( var i = 0; i < this.vertices.length; ++ i ) {
  2856. this.vertices[ i ].copy( returnVar.vertices[ i ] );
  2857. }
  2858. return returnVar;
  2859. },
  2860. flattenToBuffers: function ( vertexBuffer, normalBuffer, uvBuffers, colorBuffer, skinIndexBuffer, skinWeightBuffer ) {
  2861. var vertices = this.vertices;
  2862. for ( var i = 0, l = vertices.length; i < l; ++ i ) {
  2863. vertices[ i ].flattenToBuffers( vertexBuffer, normalBuffer, uvBuffers, colorBuffer, skinIndexBuffer, skinWeightBuffer );
  2864. }
  2865. }
  2866. } );
  2867. /**
  2868. * @constructor
  2869. */
  2870. function Face() {
  2871. /**
  2872. * @type {{vertices: {position: THREE.Vector3, normal: THREE.Vector3, uv: THREE.Vector2, skinIndices: THREE.Vector4, skinWeights: THREE.Vector4}[]}[]}
  2873. */
  2874. this.triangles = [];
  2875. this.materialIndex = 0;
  2876. }
  2877. Object.assign( Face.prototype, {
  2878. copy: function ( target ) {
  2879. var returnVar = target || new Face();
  2880. for ( var i = 0; i < this.triangles.length; ++ i ) {
  2881. this.triangles[ i ].copy( returnVar.triangles[ i ] );
  2882. }
  2883. returnVar.materialIndex = this.materialIndex;
  2884. return returnVar;
  2885. },
  2886. genTrianglesFromVertices: function ( vertexArray ) {
  2887. for ( var i = 2; i < vertexArray.length; ++ i ) {
  2888. var triangle = new Triangle();
  2889. triangle.vertices[ 0 ] = vertexArray[ 0 ];
  2890. triangle.vertices[ 1 ] = vertexArray[ i - 1 ];
  2891. triangle.vertices[ 2 ] = vertexArray[ i ];
  2892. this.triangles.push( triangle );
  2893. }
  2894. },
  2895. flattenToBuffers: function ( vertexBuffer, normalBuffer, uvBuffers, colorBuffer, skinIndexBuffer, skinWeightBuffer, materialIndexBuffer ) {
  2896. var triangles = this.triangles;
  2897. var materialIndex = this.materialIndex;
  2898. for ( var i = 0, l = triangles.length; i < l; ++ i ) {
  2899. triangles[ i ].flattenToBuffers( vertexBuffer, normalBuffer, uvBuffers, colorBuffer, skinIndexBuffer, skinWeightBuffer );
  2900. append( materialIndexBuffer, [ materialIndex, materialIndex, materialIndex ] );
  2901. }
  2902. }
  2903. } );
  2904. /**
  2905. * @constructor
  2906. */
  2907. function Geometry() {
  2908. /**
  2909. * @type {{triangles: {vertices: {position: THREE.Vector3, normal: THREE.Vector3, uv: Array of THREE.Vector2, skinIndices: THREE.Vector4, skinWeights: THREE.Vector4}[]}[], materialIndex: number}[]}
  2910. */
  2911. this.faces = [];
  2912. /**
  2913. * @type {{}|THREE.Skeleton}
  2914. */
  2915. this.skeleton = null;
  2916. }
  2917. Object.assign( Geometry.prototype, {
  2918. /**
  2919. * @returns {{vertexBuffer: number[], normalBuffer: number[], uvBuffers: Array of number[], skinIndexBuffer: number[], skinWeightBuffer: number[], materialIndexBuffer: number[]}}
  2920. */
  2921. flattenToBuffers: function () {
  2922. var vertexBuffer = [];
  2923. var normalBuffer = [];
  2924. var uvBuffers = [];
  2925. var colorBuffer = [];
  2926. var skinIndexBuffer = [];
  2927. var skinWeightBuffer = [];
  2928. var materialIndexBuffer = [];
  2929. var faces = this.faces;
  2930. for ( var i = 0; i < faces[ 0 ].triangles[ 0 ].vertices[ 0 ].uv.length; i ++ ) {
  2931. uvBuffers.push( [] );
  2932. }
  2933. for ( var i = 0, l = faces.length; i < l; ++ i ) {
  2934. faces[ i ].flattenToBuffers( vertexBuffer, normalBuffer, uvBuffers, colorBuffer, skinIndexBuffer, skinWeightBuffer, materialIndexBuffer );
  2935. }
  2936. return {
  2937. vertexBuffer: vertexBuffer,
  2938. normalBuffer: normalBuffer,
  2939. uvBuffers: uvBuffers,
  2940. colorBuffer: colorBuffer,
  2941. skinIndexBuffer: skinIndexBuffer,
  2942. skinWeightBuffer: skinWeightBuffer,
  2943. materialIndexBuffer: materialIndexBuffer
  2944. };
  2945. }
  2946. } );
  2947. function TextParser() {}
  2948. Object.assign( TextParser.prototype, {
  2949. getPrevNode: function () {
  2950. return this.nodeStack[ this.currentIndent - 2 ];
  2951. },
  2952. getCurrentNode: function () {
  2953. return this.nodeStack[ this.currentIndent - 1 ];
  2954. },
  2955. getCurrentProp: function () {
  2956. return this.currentProp;
  2957. },
  2958. pushStack: function ( node ) {
  2959. this.nodeStack.push( node );
  2960. this.currentIndent += 1;
  2961. },
  2962. popStack: function () {
  2963. this.nodeStack.pop();
  2964. this.currentIndent -= 1;
  2965. },
  2966. setCurrentProp: function ( val, name ) {
  2967. this.currentProp = val;
  2968. this.currentPropName = name;
  2969. },
  2970. // ----------parse ---------------------------------------------------
  2971. parse: function ( text ) {
  2972. this.currentIndent = 0;
  2973. this.allNodes = new FBXTree();
  2974. this.nodeStack = [];
  2975. this.currentProp = [];
  2976. this.currentPropName = '';
  2977. var split = text.split( '\n' );
  2978. for ( var lineNum = 0, lineLength = split.length; lineNum < lineLength; lineNum ++ ) {
  2979. var l = split[ lineNum ];
  2980. // skip comment line
  2981. if ( l.match( /^[\s\t]*;/ ) ) {
  2982. continue;
  2983. }
  2984. // skip empty line
  2985. if ( l.match( /^[\s\t]*$/ ) ) {
  2986. continue;
  2987. }
  2988. // beginning of node
  2989. var beginningOfNodeExp = new RegExp( '^\\t{' + this.currentIndent + '}(\\w+):(.*){', '' );
  2990. var match = l.match( beginningOfNodeExp );
  2991. if ( match ) {
  2992. var nodeName = match[ 1 ].trim().replace( /^"/, '' ).replace( /"$/, '' );
  2993. var nodeAttrs = match[ 2 ].split( ',' );
  2994. for ( var i = 0, l = nodeAttrs.length; i < l; i ++ ) {
  2995. nodeAttrs[ i ] = nodeAttrs[ i ].trim().replace( /^"/, '' ).replace( /"$/, '' );
  2996. }
  2997. this.parseNodeBegin( l, nodeName, nodeAttrs || null );
  2998. continue;
  2999. }
  3000. // node's property
  3001. var propExp = new RegExp( '^\\t{' + ( this.currentIndent ) + '}(\\w+):[\\s\\t\\r\\n](.*)' );
  3002. var match = l.match( propExp );
  3003. if ( match ) {
  3004. var propName = match[ 1 ].replace( /^"/, '' ).replace( /"$/, '' ).trim();
  3005. var propValue = match[ 2 ].replace( /^"/, '' ).replace( /"$/, '' ).trim();
  3006. // for special case: base64 image data follows "Content: ," line
  3007. // Content: ,
  3008. // "iVB..."
  3009. if ( propName === 'Content' && propValue === ',' ) {
  3010. propValue = split[ ++ lineNum ].replace( /"/g, '' ).trim();
  3011. }
  3012. this.parseNodeProperty( l, propName, propValue );
  3013. continue;
  3014. }
  3015. // end of node
  3016. var endOfNodeExp = new RegExp( '^\\t{' + ( this.currentIndent - 1 ) + '}}' );
  3017. if ( l.match( endOfNodeExp ) ) {
  3018. this.nodeEnd();
  3019. continue;
  3020. }
  3021. // for special case,
  3022. //
  3023. // Vertices: *8670 {
  3024. // a: 0.0356229953467846,13.9599733352661,-0.399196773.....(snip)
  3025. // -0.0612030513584614,13.960485458374,-0.409748703241348,-0.10.....
  3026. // 0.12490539252758,13.7450733184814,-0.454119384288788,0.09272.....
  3027. // 0.0836158767342567,13.5432004928589,-0.435397416353226,0.028.....
  3028. //
  3029. // these case the lines must contiue with previous line
  3030. if ( l.match( /^[^\s\t}]/ ) ) {
  3031. this.parseNodePropertyContinued( l );
  3032. }
  3033. }
  3034. return this.allNodes;
  3035. },
  3036. parseNodeBegin: function ( line, nodeName, nodeAttrs ) {
  3037. // var nodeName = match[1];
  3038. var node = { 'name': nodeName, properties: {}, 'subNodes': {} };
  3039. var attrs = this.parseNodeAttr( nodeAttrs );
  3040. var currentNode = this.getCurrentNode();
  3041. // a top node
  3042. if ( this.currentIndent === 0 ) {
  3043. this.allNodes.add( nodeName, node );
  3044. } else {
  3045. // a subnode
  3046. // already exists subnode, then append it
  3047. if ( nodeName in currentNode.subNodes ) {
  3048. var tmp = currentNode.subNodes[ nodeName ];
  3049. // console.log( "duped entry found\nkey: " + nodeName + "\nvalue: " + propValue );
  3050. if ( this.isFlattenNode( currentNode.subNodes[ nodeName ] ) ) {
  3051. if ( attrs.id === '' ) {
  3052. currentNode.subNodes[ nodeName ] = [];
  3053. currentNode.subNodes[ nodeName ].push( tmp );
  3054. } else {
  3055. currentNode.subNodes[ nodeName ] = {};
  3056. currentNode.subNodes[ nodeName ][ tmp.id ] = tmp;
  3057. }
  3058. }
  3059. if ( attrs.id === '' ) {
  3060. currentNode.subNodes[ nodeName ].push( node );
  3061. } else {
  3062. currentNode.subNodes[ nodeName ][ attrs.id ] = node;
  3063. }
  3064. } else if ( typeof attrs.id === 'number' || attrs.id.match( /^\d+$/ ) ) {
  3065. currentNode.subNodes[ nodeName ] = {};
  3066. currentNode.subNodes[ nodeName ][ attrs.id ] = node;
  3067. } else {
  3068. currentNode.subNodes[ nodeName ] = node;
  3069. }
  3070. }
  3071. // for this ↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓
  3072. // NodeAttribute: 1001463072, "NodeAttribute::", "LimbNode" {
  3073. if ( nodeAttrs ) {
  3074. node.id = attrs.id;
  3075. node.attrName = attrs.name;
  3076. node.attrType = attrs.type;
  3077. }
  3078. this.pushStack( node );
  3079. },
  3080. parseNodeAttr: function ( attrs ) {
  3081. var id = attrs[ 0 ];
  3082. if ( attrs[ 0 ] !== '' ) {
  3083. id = parseInt( attrs[ 0 ] );
  3084. if ( isNaN( id ) ) {
  3085. // PolygonVertexIndex: *16380 {
  3086. id = attrs[ 0 ];
  3087. }
  3088. }
  3089. var name = '', type = '';
  3090. if ( attrs.length > 1 ) {
  3091. name = attrs[ 1 ].replace( /^(\w+)::/, '' );
  3092. type = attrs[ 2 ];
  3093. }
  3094. return { id: id, name: name, type: type };
  3095. },
  3096. parseNodeProperty: function ( line, propName, propValue ) {
  3097. var currentNode = this.getCurrentNode();
  3098. var parentName = currentNode.name;
  3099. // special case parent node's is like "Properties70"
  3100. // these children nodes must treat with careful
  3101. if ( parentName !== undefined ) {
  3102. var propMatch = parentName.match( /Properties(\d)+/ );
  3103. if ( propMatch ) {
  3104. this.parseNodeSpecialProperty( line, propName, propValue );
  3105. return;
  3106. }
  3107. }
  3108. // special case Connections
  3109. if ( propName === 'C' ) {
  3110. var connProps = propValue.split( ',' ).slice( 1 );
  3111. var from = parseInt( connProps[ 0 ] );
  3112. var to = parseInt( connProps[ 1 ] );
  3113. var rest = propValue.split( ',' ).slice( 3 );
  3114. propName = 'connections';
  3115. propValue = [ from, to ];
  3116. append( propValue, rest );
  3117. if ( currentNode.properties[ propName ] === undefined ) {
  3118. currentNode.properties[ propName ] = [];
  3119. }
  3120. }
  3121. // special case Connections
  3122. if ( propName === 'Node' ) {
  3123. var id = parseInt( propValue );
  3124. currentNode.properties.id = id;
  3125. currentNode.id = id;
  3126. }
  3127. // already exists in properties, then append this
  3128. if ( propName in currentNode.properties ) {
  3129. // console.log( "duped entry found\nkey: " + propName + "\nvalue: " + propValue );
  3130. if ( Array.isArray( currentNode.properties[ propName ] ) ) {
  3131. currentNode.properties[ propName ].push( propValue );
  3132. } else {
  3133. currentNode.properties[ propName ] += propValue;
  3134. }
  3135. } else {
  3136. // console.log( propName + ": " + propValue );
  3137. if ( Array.isArray( currentNode.properties[ propName ] ) ) {
  3138. currentNode.properties[ propName ].push( propValue );
  3139. } else {
  3140. currentNode.properties[ propName ] = propValue;
  3141. }
  3142. }
  3143. this.setCurrentProp( currentNode.properties, propName );
  3144. },
  3145. // TODO:
  3146. parseNodePropertyContinued: function ( line ) {
  3147. this.currentProp[ this.currentPropName ] += line;
  3148. },
  3149. parseNodeSpecialProperty: function ( line, propName, propValue ) {
  3150. // split this
  3151. // P: "Lcl Scaling", "Lcl Scaling", "", "A",1,1,1
  3152. // into array like below
  3153. // ["Lcl Scaling", "Lcl Scaling", "", "A", "1,1,1" ]
  3154. var props = propValue.split( '",' );
  3155. for ( var i = 0, l = props.length; i < l; i ++ ) {
  3156. props[ i ] = props[ i ].trim().replace( /^\"/, '' ).replace( /\s/, '_' );
  3157. }
  3158. var innerPropName = props[ 0 ];
  3159. var innerPropType1 = props[ 1 ];
  3160. var innerPropType2 = props[ 2 ];
  3161. var innerPropFlag = props[ 3 ];
  3162. var innerPropValue = props[ 4 ];
  3163. /*
  3164. if ( innerPropValue === undefined ) {
  3165. innerPropValue = props[3];
  3166. }
  3167. */
  3168. // cast value in its type
  3169. switch ( innerPropType1 ) {
  3170. case 'int':
  3171. innerPropValue = parseInt( innerPropValue );
  3172. break;
  3173. case 'double':
  3174. innerPropValue = parseFloat( innerPropValue );
  3175. break;
  3176. case 'ColorRGB':
  3177. case 'Vector3D':
  3178. innerPropValue = parseFloatArray( innerPropValue );
  3179. break;
  3180. }
  3181. // CAUTION: these props must append to parent's parent
  3182. this.getPrevNode().properties[ innerPropName ] = {
  3183. 'type': innerPropType1,
  3184. 'type2': innerPropType2,
  3185. 'flag': innerPropFlag,
  3186. 'value': innerPropValue
  3187. };
  3188. this.setCurrentProp( this.getPrevNode().properties, innerPropName );
  3189. },
  3190. nodeEnd: function () {
  3191. this.popStack();
  3192. },
  3193. /* ---------------------------------------------------------------- */
  3194. /* util */
  3195. isFlattenNode: function ( node ) {
  3196. return ( 'subNodes' in node && 'properties' in node ) ? true : false;
  3197. }
  3198. } );
  3199. // Binary format specification:
  3200. // https://code.blender.org/2013/08/fbx-binary-file-format-specification/
  3201. // https://wiki.rogiken.org/specifications/file-format/fbx/ (more detail but Japanese)
  3202. function BinaryParser() {}
  3203. Object.assign( BinaryParser.prototype, {
  3204. /**
  3205. * Parses binary data and builds FBXTree as much compatible as possible with the one built by TextParser.
  3206. * @param {ArrayBuffer} buffer
  3207. * @returns {THREE.FBXTree}
  3208. */
  3209. parse: function ( buffer ) {
  3210. var reader = new BinaryReader( buffer );
  3211. reader.skip( 23 ); // skip magic 23 bytes
  3212. var version = reader.getUint32();
  3213. console.log( 'THREE.FBXLoader: FBX binary version: ' + version );
  3214. var allNodes = new FBXTree();
  3215. while ( ! this.endOfContent( reader ) ) {
  3216. var node = this.parseNode( reader, version );
  3217. if ( node !== null ) allNodes.add( node.name, node );
  3218. }
  3219. return allNodes;
  3220. },
  3221. /**
  3222. * Checks if reader has reached the end of content.
  3223. * @param {BinaryReader} reader
  3224. * @returns {boolean}
  3225. */
  3226. endOfContent: function ( reader ) {
  3227. // footer size: 160bytes + 16-byte alignment padding
  3228. // - 16bytes: magic
  3229. // - padding til 16-byte alignment (at least 1byte?)
  3230. // (seems like some exporters embed fixed 15 or 16bytes?)
  3231. // - 4bytes: magic
  3232. // - 4bytes: version
  3233. // - 120bytes: zero
  3234. // - 16bytes: magic
  3235. if ( reader.size() % 16 === 0 ) {
  3236. return ( ( reader.getOffset() + 160 + 16 ) & ~ 0xf ) >= reader.size();
  3237. } else {
  3238. return reader.getOffset() + 160 + 16 >= reader.size();
  3239. }
  3240. },
  3241. /**
  3242. * Parses Node as much compatible as possible with the one parsed by TextParser
  3243. * TODO: could be optimized more?
  3244. * @param {BinaryReader} reader
  3245. * @param {number} version
  3246. * @returns {Object} - Returns an Object as node, or null if NULL-record.
  3247. */
  3248. parseNode: function ( reader, version ) {
  3249. // The first three data sizes depends on version.
  3250. var endOffset = ( version >= 7500 ) ? reader.getUint64() : reader.getUint32();
  3251. var numProperties = ( version >= 7500 ) ? reader.getUint64() : reader.getUint32();
  3252. var propertyListLen = ( version >= 7500 ) ? reader.getUint64() : reader.getUint32();
  3253. var nameLen = reader.getUint8();
  3254. var name = reader.getString( nameLen );
  3255. // Regards this node as NULL-record if endOffset is zero
  3256. if ( endOffset === 0 ) return null;
  3257. var propertyList = [];
  3258. for ( var i = 0; i < numProperties; i ++ ) {
  3259. propertyList.push( this.parseProperty( reader ) );
  3260. }
  3261. // Regards the first three elements in propertyList as id, attrName, and attrType
  3262. var id = propertyList.length > 0 ? propertyList[ 0 ] : '';
  3263. var attrName = propertyList.length > 1 ? propertyList[ 1 ] : '';
  3264. var attrType = propertyList.length > 2 ? propertyList[ 2 ] : '';
  3265. var subNodes = {};
  3266. var properties = {};
  3267. var isSingleProperty = false;
  3268. // if this node represents just a single property
  3269. // like (name, 0) set or (name2, [0, 1, 2]) set of {name: 0, name2: [0, 1, 2]}
  3270. if ( numProperties === 1 && reader.getOffset() === endOffset ) {
  3271. isSingleProperty = true;
  3272. }
  3273. while ( endOffset > reader.getOffset() ) {
  3274. var node = this.parseNode( reader, version );
  3275. if ( node === null ) continue;
  3276. // special case: child node is single property
  3277. if ( node.singleProperty === true ) {
  3278. var value = node.propertyList[ 0 ];
  3279. if ( Array.isArray( value ) ) {
  3280. // node represents
  3281. // Vertices: *3 {
  3282. // a: 0.01, 0.02, 0.03
  3283. // }
  3284. // of text format here.
  3285. node.properties[ node.name ] = node.propertyList[ 0 ];
  3286. subNodes[ node.name ] = node;
  3287. // Later phase expects single property array is in node.properties.a as String.
  3288. // TODO: optimize
  3289. node.properties.a = value.toString();
  3290. } else {
  3291. // node represents
  3292. // Version: 100
  3293. // of text format here.
  3294. properties[ node.name ] = value;
  3295. }
  3296. continue;
  3297. }
  3298. // special case: connections
  3299. if ( name === 'Connections' && node.name === 'C' ) {
  3300. var array = [];
  3301. // node.propertyList would be like
  3302. // ["OO", 111264976, 144038752, "d|x"] (?, from, to, additional values)
  3303. for ( var i = 1, il = node.propertyList.length; i < il; i ++ ) {
  3304. array[ i - 1 ] = node.propertyList[ i ];
  3305. }
  3306. if ( properties.connections === undefined ) {
  3307. properties.connections = [];
  3308. }
  3309. properties.connections.push( array );
  3310. continue;
  3311. }
  3312. // special case: child node is Properties\d+
  3313. if ( node.name.match( /^Properties\d+$/ ) ) {
  3314. // move child node's properties to this node.
  3315. var keys = Object.keys( node.properties );
  3316. for ( var i = 0, il = keys.length; i < il; i ++ ) {
  3317. var key = keys[ i ];
  3318. properties[ key ] = node.properties[ key ];
  3319. }
  3320. continue;
  3321. }
  3322. // special case: properties
  3323. if ( name.match( /^Properties\d+$/ ) && node.name === 'P' ) {
  3324. var innerPropName = node.propertyList[ 0 ];
  3325. var innerPropType1 = node.propertyList[ 1 ];
  3326. var innerPropType2 = node.propertyList[ 2 ];
  3327. var innerPropFlag = node.propertyList[ 3 ];
  3328. var innerPropValue;
  3329. if ( innerPropName.indexOf( 'Lcl ' ) === 0 ) innerPropName = innerPropName.replace( 'Lcl ', 'Lcl_' );
  3330. if ( innerPropType1.indexOf( 'Lcl ' ) === 0 ) innerPropType1 = innerPropType1.replace( 'Lcl ', 'Lcl_' );
  3331. if ( innerPropType1 === 'ColorRGB' || innerPropType1 === 'Vector' ||
  3332. innerPropType1 === 'Vector3D' || innerPropType1.indexOf( 'Lcl_' ) === 0 ) {
  3333. innerPropValue = [
  3334. node.propertyList[ 4 ],
  3335. node.propertyList[ 5 ],
  3336. node.propertyList[ 6 ]
  3337. ];
  3338. } else {
  3339. innerPropValue = node.propertyList[ 4 ];
  3340. }
  3341. if ( innerPropType1.indexOf( 'Lcl_' ) === 0 ) {
  3342. innerPropValue = innerPropValue.toString();
  3343. }
  3344. // this will be copied to parent. see above.
  3345. properties[ innerPropName ] = {
  3346. 'type': innerPropType1,
  3347. 'type2': innerPropType2,
  3348. 'flag': innerPropFlag,
  3349. 'value': innerPropValue
  3350. };
  3351. continue;
  3352. }
  3353. // standard case
  3354. // follows TextParser's manner.
  3355. if ( subNodes[ node.name ] === undefined ) {
  3356. if ( typeof node.id === 'number' ) {
  3357. subNodes[ node.name ] = {};
  3358. subNodes[ node.name ][ node.id ] = node;
  3359. } else {
  3360. subNodes[ node.name ] = node;
  3361. }
  3362. } else {
  3363. if ( node.id === '' ) {
  3364. if ( ! Array.isArray( subNodes[ node.name ] ) ) {
  3365. subNodes[ node.name ] = [ subNodes[ node.name ] ];
  3366. }
  3367. subNodes[ node.name ].push( node );
  3368. } else {
  3369. if ( subNodes[ node.name ][ node.id ] === undefined ) {
  3370. subNodes[ node.name ][ node.id ] = node;
  3371. } else {
  3372. // conflict id. irregular?
  3373. if ( ! Array.isArray( subNodes[ node.name ][ node.id ] ) ) {
  3374. subNodes[ node.name ][ node.id ] = [ subNodes[ node.name ][ node.id ] ];
  3375. }
  3376. subNodes[ node.name ][ node.id ].push( node );
  3377. }
  3378. }
  3379. }
  3380. }
  3381. return {
  3382. singleProperty: isSingleProperty,
  3383. id: id,
  3384. attrName: attrName,
  3385. attrType: attrType,
  3386. name: name,
  3387. properties: properties,
  3388. propertyList: propertyList, // raw property list, would be used by parent
  3389. subNodes: subNodes
  3390. };
  3391. },
  3392. parseProperty: function ( reader ) {
  3393. var type = reader.getChar();
  3394. switch ( type ) {
  3395. case 'F':
  3396. return reader.getFloat32();
  3397. case 'D':
  3398. return reader.getFloat64();
  3399. case 'L':
  3400. return reader.getInt64();
  3401. case 'I':
  3402. return reader.getInt32();
  3403. case 'Y':
  3404. return reader.getInt16();
  3405. case 'C':
  3406. return reader.getBoolean();
  3407. case 'f':
  3408. case 'd':
  3409. case 'l':
  3410. case 'i':
  3411. case 'b':
  3412. var arrayLength = reader.getUint32();
  3413. var encoding = reader.getUint32(); // 0: non-compressed, 1: compressed
  3414. var compressedLength = reader.getUint32();
  3415. if ( encoding === 0 ) {
  3416. switch ( type ) {
  3417. case 'f':
  3418. return reader.getFloat32Array( arrayLength );
  3419. case 'd':
  3420. return reader.getFloat64Array( arrayLength );
  3421. case 'l':
  3422. return reader.getInt64Array( arrayLength );
  3423. case 'i':
  3424. return reader.getInt32Array( arrayLength );
  3425. case 'b':
  3426. return reader.getBooleanArray( arrayLength );
  3427. }
  3428. }
  3429. if ( window.Zlib === undefined ) {
  3430. throw new Error( 'THREE.FBXLoader: External library Inflate.min.js required, obtain or import from https://github.com/imaya/zlib.js' );
  3431. }
  3432. var inflate = new Zlib.Inflate( new Uint8Array( reader.getArrayBuffer( compressedLength ) ) ); // eslint-disable-line no-undef
  3433. var reader2 = new BinaryReader( inflate.decompress().buffer );
  3434. switch ( type ) {
  3435. case 'f':
  3436. return reader2.getFloat32Array( arrayLength );
  3437. case 'd':
  3438. return reader2.getFloat64Array( arrayLength );
  3439. case 'l':
  3440. return reader2.getInt64Array( arrayLength );
  3441. case 'i':
  3442. return reader2.getInt32Array( arrayLength );
  3443. case 'b':
  3444. return reader2.getBooleanArray( arrayLength );
  3445. }
  3446. case 'S':
  3447. var length = reader.getUint32();
  3448. return reader.getString( length );
  3449. case 'R':
  3450. var length = reader.getUint32();
  3451. return reader.getArrayBuffer( length );
  3452. default:
  3453. throw new Error( 'THREE.FBXLoader: Unknown property type ' + type );
  3454. }
  3455. }
  3456. } );
  3457. function BinaryReader( buffer, littleEndian ) {
  3458. this.dv = new DataView( buffer );
  3459. this.offset = 0;
  3460. this.littleEndian = ( littleEndian !== undefined ) ? littleEndian : true;
  3461. }
  3462. Object.assign( BinaryReader.prototype, {
  3463. getOffset: function () {
  3464. return this.offset;
  3465. },
  3466. size: function () {
  3467. return this.dv.buffer.byteLength;
  3468. },
  3469. skip: function ( length ) {
  3470. this.offset += length;
  3471. },
  3472. // seems like true/false representation depends on exporter.
  3473. // true: 1 or 'Y'(=0x59), false: 0 or 'T'(=0x54)
  3474. // then sees LSB.
  3475. getBoolean: function () {
  3476. return ( this.getUint8() & 1 ) === 1;
  3477. },
  3478. getBooleanArray: function ( size ) {
  3479. var a = [];
  3480. for ( var i = 0; i < size; i ++ ) {
  3481. a.push( this.getBoolean() );
  3482. }
  3483. return a;
  3484. },
  3485. getInt8: function () {
  3486. var value = this.dv.getInt8( this.offset );
  3487. this.offset += 1;
  3488. return value;
  3489. },
  3490. getInt8Array: function ( size ) {
  3491. var a = [];
  3492. for ( var i = 0; i < size; i ++ ) {
  3493. a.push( this.getInt8() );
  3494. }
  3495. return a;
  3496. },
  3497. getUint8: function () {
  3498. var value = this.dv.getUint8( this.offset );
  3499. this.offset += 1;
  3500. return value;
  3501. },
  3502. getUint8Array: function ( size ) {
  3503. var a = [];
  3504. for ( var i = 0; i < size; i ++ ) {
  3505. a.push( this.getUint8() );
  3506. }
  3507. return a;
  3508. },
  3509. getInt16: function () {
  3510. var value = this.dv.getInt16( this.offset, this.littleEndian );
  3511. this.offset += 2;
  3512. return value;
  3513. },
  3514. getInt16Array: function ( size ) {
  3515. var a = [];
  3516. for ( var i = 0; i < size; i ++ ) {
  3517. a.push( this.getInt16() );
  3518. }
  3519. return a;
  3520. },
  3521. getUint16: function () {
  3522. var value = this.dv.getUint16( this.offset, this.littleEndian );
  3523. this.offset += 2;
  3524. return value;
  3525. },
  3526. getUint16Array: function ( size ) {
  3527. var a = [];
  3528. for ( var i = 0; i < size; i ++ ) {
  3529. a.push( this.getUint16() );
  3530. }
  3531. return a;
  3532. },
  3533. getInt32: function () {
  3534. var value = this.dv.getInt32( this.offset, this.littleEndian );
  3535. this.offset += 4;
  3536. return value;
  3537. },
  3538. getInt32Array: function ( size ) {
  3539. var a = [];
  3540. for ( var i = 0; i < size; i ++ ) {
  3541. a.push( this.getInt32() );
  3542. }
  3543. return a;
  3544. },
  3545. getUint32: function () {
  3546. var value = this.dv.getUint32( this.offset, this.littleEndian );
  3547. this.offset += 4;
  3548. return value;
  3549. },
  3550. getUint32Array: function ( size ) {
  3551. var a = [];
  3552. for ( var i = 0; i < size; i ++ ) {
  3553. a.push( this.getUint32() );
  3554. }
  3555. return a;
  3556. },
  3557. // JavaScript doesn't support 64-bit integer so attempting to calculate by ourselves.
  3558. // 1 << 32 will return 1 so using multiply operation instead here.
  3559. // There'd be a possibility that this method returns wrong value if the value
  3560. // is out of the range between Number.MAX_SAFE_INTEGER and Number.MIN_SAFE_INTEGER.
  3561. // TODO: safely handle 64-bit integer
  3562. getInt64: function () {
  3563. var low, high;
  3564. if ( this.littleEndian ) {
  3565. low = this.getUint32();
  3566. high = this.getUint32();
  3567. } else {
  3568. high = this.getUint32();
  3569. low = this.getUint32();
  3570. }
  3571. // calculate negative value
  3572. if ( high & 0x80000000 ) {
  3573. high = ~ high & 0xFFFFFFFF;
  3574. low = ~ low & 0xFFFFFFFF;
  3575. if ( low === 0xFFFFFFFF ) high = ( high + 1 ) & 0xFFFFFFFF;
  3576. low = ( low + 1 ) & 0xFFFFFFFF;
  3577. return - ( high * 0x100000000 + low );
  3578. }
  3579. return high * 0x100000000 + low;
  3580. },
  3581. getInt64Array: function ( size ) {
  3582. var a = [];
  3583. for ( var i = 0; i < size; i ++ ) {
  3584. a.push( this.getInt64() );
  3585. }
  3586. return a;
  3587. },
  3588. // Note: see getInt64() comment
  3589. getUint64: function () {
  3590. var low, high;
  3591. if ( this.littleEndian ) {
  3592. low = this.getUint32();
  3593. high = this.getUint32();
  3594. } else {
  3595. high = this.getUint32();
  3596. low = this.getUint32();
  3597. }
  3598. return high * 0x100000000 + low;
  3599. },
  3600. getUint64Array: function ( size ) {
  3601. var a = [];
  3602. for ( var i = 0; i < size; i ++ ) {
  3603. a.push( this.getUint64() );
  3604. }
  3605. return a;
  3606. },
  3607. getFloat32: function () {
  3608. var value = this.dv.getFloat32( this.offset, this.littleEndian );
  3609. this.offset += 4;
  3610. return value;
  3611. },
  3612. getFloat32Array: function ( size ) {
  3613. var a = [];
  3614. for ( var i = 0; i < size; i ++ ) {
  3615. a.push( this.getFloat32() );
  3616. }
  3617. return a;
  3618. },
  3619. getFloat64: function () {
  3620. var value = this.dv.getFloat64( this.offset, this.littleEndian );
  3621. this.offset += 8;
  3622. return value;
  3623. },
  3624. getFloat64Array: function ( size ) {
  3625. var a = [];
  3626. for ( var i = 0; i < size; i ++ ) {
  3627. a.push( this.getFloat64() );
  3628. }
  3629. return a;
  3630. },
  3631. getArrayBuffer: function ( size ) {
  3632. var value = this.dv.buffer.slice( this.offset, this.offset + size );
  3633. this.offset += size;
  3634. return value;
  3635. },
  3636. getChar: function () {
  3637. return String.fromCharCode( this.getUint8() );
  3638. },
  3639. getString: function ( size ) {
  3640. var s = '';
  3641. while ( size > 0 ) {
  3642. var value = this.getUint8();
  3643. size --;
  3644. if ( value === 0 ) break;
  3645. s += String.fromCharCode( value );
  3646. }
  3647. // Manage UTF8 encoding
  3648. s = decodeURIComponent( escape( s ) );
  3649. this.skip( size );
  3650. return s;
  3651. }
  3652. } );
  3653. function FBXTree() {}
  3654. Object.assign( FBXTree.prototype, {
  3655. add: function ( key, val ) {
  3656. this[ key ] = val;
  3657. },
  3658. searchConnectionParent: function ( id ) {
  3659. if ( this.__cache_search_connection_parent === undefined ) {
  3660. this.__cache_search_connection_parent = [];
  3661. }
  3662. if ( this.__cache_search_connection_parent[ id ] !== undefined ) {
  3663. return this.__cache_search_connection_parent[ id ];
  3664. } else {
  3665. this.__cache_search_connection_parent[ id ] = [];
  3666. }
  3667. var conns = this.Connections.properties.connections;
  3668. var results = [];
  3669. for ( var i = 0; i < conns.length; ++ i ) {
  3670. if ( conns[ i ][ 0 ] == id ) {
  3671. // 0 means scene root
  3672. var res = conns[ i ][ 1 ] === 0 ? - 1 : conns[ i ][ 1 ];
  3673. results.push( res );
  3674. }
  3675. }
  3676. if ( results.length > 0 ) {
  3677. append( this.__cache_search_connection_parent[ id ], results );
  3678. return results;
  3679. } else {
  3680. this.__cache_search_connection_parent[ id ] = [ - 1 ];
  3681. return [ - 1 ];
  3682. }
  3683. },
  3684. searchConnectionChildren: function ( id ) {
  3685. if ( this.__cache_search_connection_children === undefined ) {
  3686. this.__cache_search_connection_children = [];
  3687. }
  3688. if ( this.__cache_search_connection_children[ id ] !== undefined ) {
  3689. return this.__cache_search_connection_children[ id ];
  3690. } else {
  3691. this.__cache_search_connection_children[ id ] = [];
  3692. }
  3693. var conns = this.Connections.properties.connections;
  3694. var res = [];
  3695. for ( var i = 0; i < conns.length; ++ i ) {
  3696. if ( conns[ i ][ 1 ] == id ) {
  3697. // 0 means scene root
  3698. res.push( conns[ i ][ 0 ] === 0 ? - 1 : conns[ i ][ 0 ] );
  3699. // there may more than one kid, then search to the end
  3700. }
  3701. }
  3702. if ( res.length > 0 ) {
  3703. append( this.__cache_search_connection_children[ id ], res );
  3704. return res;
  3705. } else {
  3706. this.__cache_search_connection_children[ id ] = [ ];
  3707. return [ ];
  3708. }
  3709. },
  3710. searchConnectionType: function ( id, to ) {
  3711. var key = id + ',' + to; // TODO: to hash
  3712. if ( this.__cache_search_connection_type === undefined ) {
  3713. this.__cache_search_connection_type = {};
  3714. }
  3715. if ( this.__cache_search_connection_type[ key ] !== undefined ) {
  3716. return this.__cache_search_connection_type[ key ];
  3717. } else {
  3718. this.__cache_search_connection_type[ key ] = '';
  3719. }
  3720. var conns = this.Connections.properties.connections;
  3721. for ( var i = 0; i < conns.length; ++ i ) {
  3722. if ( conns[ i ][ 0 ] == id && conns[ i ][ 1 ] == to ) {
  3723. // 0 means scene root
  3724. this.__cache_search_connection_type[ key ] = conns[ i ][ 2 ];
  3725. return conns[ i ][ 2 ];
  3726. }
  3727. }
  3728. this.__cache_search_connection_type[ id ] = null;
  3729. return null;
  3730. }
  3731. } );
  3732. /**
  3733. * @param {ArrayBuffer} buffer
  3734. * @returns {boolean}
  3735. */
  3736. function isFbxFormatBinary( buffer ) {
  3737. var CORRECT = 'Kaydara FBX Binary \0';
  3738. return buffer.byteLength >= CORRECT.length && CORRECT === convertArrayBufferToString( buffer, 0, CORRECT.length );
  3739. }
  3740. /**
  3741. * @returns {boolean}
  3742. */
  3743. function isFbxFormatASCII( text ) {
  3744. var CORRECT = [ 'K', 'a', 'y', 'd', 'a', 'r', 'a', '\\', 'F', 'B', 'X', '\\', 'B', 'i', 'n', 'a', 'r', 'y', '\\', '\\' ];
  3745. var cursor = 0;
  3746. function read( offset ) {
  3747. var result = text[ offset - 1 ];
  3748. text = text.slice( cursor + offset );
  3749. cursor ++;
  3750. return result;
  3751. }
  3752. for ( var i = 0; i < CORRECT.length; ++ i ) {
  3753. var num = read( 1 );
  3754. if ( num === CORRECT[ i ] ) {
  3755. return false;
  3756. }
  3757. }
  3758. return true;
  3759. }
  3760. /**
  3761. * @returns {number}
  3762. */
  3763. function getFbxVersion( text ) {
  3764. var versionRegExp = /FBXVersion: (\d+)/;
  3765. var match = text.match( versionRegExp );
  3766. if ( match ) {
  3767. var version = parseInt( match[ 1 ] );
  3768. return version;
  3769. }
  3770. throw new Error( 'THREE.FBXLoader: Cannot find the version number for the file given.' );
  3771. }
  3772. /**
  3773. * Converts FBX ticks into real time seconds.
  3774. * @param {number} time - FBX tick timestamp to convert.
  3775. * @returns {number} - FBX tick in real world time.
  3776. */
  3777. function convertFBXTimeToSeconds( time ) {
  3778. // Constant is FBX ticks per second.
  3779. return time / 46186158000;
  3780. }
  3781. /**
  3782. * Parses comma separated list of float numbers and returns them in an array.
  3783. * @example
  3784. * // Returns [ 5.6, 9.4, 2.5, 1.4 ]
  3785. * parseFloatArray( "5.6,9.4,2.5,1.4" )
  3786. * @returns {number[]}
  3787. */
  3788. function parseFloatArray( string ) {
  3789. var array = string.split( ',' );
  3790. for ( var i = 0, l = array.length; i < l; i ++ ) {
  3791. array[ i ] = parseFloat( array[ i ] );
  3792. }
  3793. return array;
  3794. }
  3795. /**
  3796. * Parses comma separated list of int numbers and returns them in an array.
  3797. * @example
  3798. * // Returns [ 5, 8, 2, 3 ]
  3799. * parseFloatArray( "5,8,2,3" )
  3800. * @returns {number[]}
  3801. */
  3802. function parseIntArray( string ) {
  3803. var array = string.split( ',' );
  3804. for ( var i = 0, l = array.length; i < l; i ++ ) {
  3805. array[ i ] = parseInt( array[ i ] );
  3806. }
  3807. return array;
  3808. }
  3809. /**
  3810. * Parses Vector3 property from FBXTree. Property is given as .value.x, .value.y, etc.
  3811. * @param {FBXVector3} property - Property to parse as Vector3.
  3812. * @returns {THREE.Vector3}
  3813. */
  3814. function parseVector3( property ) {
  3815. return new THREE.Vector3().fromArray( property.value );
  3816. }
  3817. /**
  3818. * Parses Color property from FBXTree. Property is given as .value.x, .value.y, etc.
  3819. * @param {FBXVector3} property - Property to parse as Color.
  3820. * @returns {THREE.Color}
  3821. */
  3822. function parseColor( property ) {
  3823. return new THREE.Color().fromArray( property.value );
  3824. }
  3825. function parseMatrixArray( floatString ) {
  3826. return new THREE.Matrix4().fromArray( parseFloatArray( floatString ) );
  3827. }
  3828. /**
  3829. * Converts ArrayBuffer to String.
  3830. * @param {ArrayBuffer} buffer
  3831. * @param {number} from
  3832. * @param {number} to
  3833. * @returns {String}
  3834. */
  3835. function convertArrayBufferToString( buffer, from, to ) {
  3836. if ( from === undefined ) from = 0;
  3837. if ( to === undefined ) to = buffer.byteLength;
  3838. var array = new Uint8Array( buffer, from, to );
  3839. if ( window.TextDecoder !== undefined ) {
  3840. return new TextDecoder().decode( array );
  3841. }
  3842. var s = '';
  3843. for ( var i = 0, il = array.length; i < il; i ++ ) {
  3844. s += String.fromCharCode( array[ i ] );
  3845. }
  3846. return s;
  3847. }
  3848. /**
  3849. * Converts number from degrees into radians.
  3850. * @param {number} value
  3851. * @returns {number}
  3852. */
  3853. function degreeToRadian( value ) {
  3854. return value * DEG2RAD;
  3855. }
  3856. var DEG2RAD = Math.PI / 180;
  3857. //
  3858. function findIndex( array, func ) {
  3859. for ( var i = 0, l = array.length; i < l; i ++ ) {
  3860. if ( func( array[ i ] ) ) return i;
  3861. }
  3862. return - 1;
  3863. }
  3864. function append( a, b ) {
  3865. for ( var i = 0, j = a.length, l = b.length; i < l; i ++, j ++ ) {
  3866. a[ j ] = b[ i ];
  3867. }
  3868. }
  3869. function slice( a, b, from, to ) {
  3870. for ( var i = from, j = 0; i < to; i ++, j ++ ) {
  3871. a[ j ] = b[ i ];
  3872. }
  3873. return a;
  3874. }
  3875. } )();