FBXLoader.js 116 KB

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