FBXLoader.js 96 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342
  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. * Euler rotation order
  22. *
  23. * FBX format references:
  24. * https://wiki.blender.org/index.php/User:Mont29/Foundation/FBX_File_Structure
  25. *
  26. * Binary format specification:
  27. * https://code.blender.org/2013/08/fbx-binary-file-format-specification/
  28. * https://wiki.rogiken.org/specifications/file-format/fbx/ (more detail but Japanese)
  29. */
  30. ( function () {
  31. THREE.FBXLoader = function ( manager ) {
  32. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  33. };
  34. Object.assign( THREE.FBXLoader.prototype, {
  35. load: function ( url, onLoad, onProgress, onError ) {
  36. var self = this;
  37. var resourceDirectory = THREE.Loader.prototype.extractUrlBase( url );
  38. var loader = new THREE.FileLoader( this.manager );
  39. loader.setResponseType( 'arraybuffer' );
  40. loader.load( url, function ( buffer ) {
  41. try {
  42. var scene = self.parse( buffer, resourceDirectory );
  43. onLoad( scene );
  44. } catch ( error ) {
  45. window.setTimeout( function () {
  46. if ( onError ) onError( error );
  47. self.manager.itemError( url );
  48. }, 0 );
  49. }
  50. }, onProgress, onError );
  51. },
  52. parse: function ( FBXBuffer, resourceDirectory ) {
  53. var FBXTree;
  54. if ( isFbxFormatBinary( FBXBuffer ) ) {
  55. FBXTree = new BinaryParser().parse( FBXBuffer );
  56. } else {
  57. var FBXText = convertArrayBufferToString( FBXBuffer );
  58. if ( ! isFbxFormatASCII( FBXText ) ) {
  59. throw new Error( 'THREE.FBXLoader: Unknown format.' );
  60. }
  61. if ( getFbxVersion( FBXText ) < 7000 ) {
  62. throw new Error( 'THREE.FBXLoader: FBX version not supported, FileVersion: ' + getFbxVersion( FBXText ) );
  63. }
  64. FBXTree = new TextParser().parse( FBXText );
  65. }
  66. // console.log( FBXTree );
  67. var connections = parseConnections( FBXTree );
  68. var images = parseImages( FBXTree );
  69. var textures = parseTextures( FBXTree, new THREE.TextureLoader( this.manager ).setPath( resourceDirectory ), images, connections );
  70. var materials = parseMaterials( FBXTree, textures, connections );
  71. var deformers = parseDeformers( FBXTree, connections );
  72. var geometryMap = parseGeometries( FBXTree, connections, deformers );
  73. var sceneGraph = parseScene( FBXTree, connections, deformers, geometryMap, materials );
  74. return sceneGraph;
  75. }
  76. } );
  77. // Parses FBXTree.Connections which holds parent-child connections between objects (e.g. material -> texture, model->geometry )
  78. // and details the connection type
  79. function parseConnections( FBXTree ) {
  80. var connectionMap = new Map();
  81. if ( 'Connections' in FBXTree ) {
  82. var connectionArray = FBXTree.Connections.properties.connections;
  83. for ( var connectionArrayIndex = 0, connectionArrayLength = connectionArray.length; connectionArrayIndex < connectionArrayLength; ++ connectionArrayIndex ) {
  84. var connection = connectionArray[ connectionArrayIndex ];
  85. if ( ! connectionMap.has( connection[ 0 ] ) ) {
  86. connectionMap.set( connection[ 0 ], {
  87. parents: [],
  88. children: []
  89. } );
  90. }
  91. var parentRelationship = { ID: connection[ 1 ], relationship: connection[ 2 ] };
  92. connectionMap.get( connection[ 0 ] ).parents.push( parentRelationship );
  93. if ( ! connectionMap.has( connection[ 1 ] ) ) {
  94. connectionMap.set( connection[ 1 ], {
  95. parents: [],
  96. children: []
  97. } );
  98. }
  99. var childRelationship = { ID: connection[ 0 ], relationship: connection[ 2 ] };
  100. connectionMap.get( connection[ 1 ] ).children.push( childRelationship );
  101. }
  102. }
  103. return connectionMap;
  104. }
  105. // Parses map of images referenced in FBXTree.Objects.subNodes.Video
  106. // Images can either be referenced externally or embedded in the file
  107. // These images are connected to textures in FBXTree.Objects.subNodes.Textures
  108. // via FBXTree.Connections. Note that images can be duplicated here, in which case only one
  109. // will will have a .Content field
  110. function parseImages( FBXTree ) {
  111. var imageMap = new Map();
  112. if ( 'Video' in FBXTree.Objects.subNodes ) {
  113. var videoNodes = FBXTree.Objects.subNodes.Video;
  114. for ( var nodeID in videoNodes ) {
  115. var videoNode = videoNodes[ nodeID ];
  116. // raw image data is in videoNode.properties.Content
  117. if ( 'Content' in videoNode.properties ) {
  118. var image = parseImage( videoNodes[ nodeID ] );
  119. imageMap.set( parseInt( nodeID ), image );
  120. }
  121. }
  122. }
  123. return imageMap;
  124. }
  125. // Parse embedded image data in FBXTree.Video.properties.Content
  126. function parseImage( videoNode ) {
  127. var content = videoNode.properties.Content;
  128. var fileName = videoNode.properties.RelativeFilename || videoNode.properties.Filename;
  129. var extension = fileName.slice( fileName.lastIndexOf( '.' ) + 1 ).toLowerCase();
  130. var type;
  131. switch ( extension ) {
  132. case 'bmp':
  133. type = 'image/bmp';
  134. break;
  135. case 'jpg':
  136. case 'jpeg':
  137. type = 'image/jpeg';
  138. break;
  139. case 'png':
  140. type = 'image/png';
  141. break;
  142. case 'tif':
  143. type = 'image/tiff';
  144. break;
  145. default:
  146. console.warn( 'FBXLoader: Image type "' + extension + '" is not supported.' );
  147. return;
  148. }
  149. if ( typeof content === 'string' ) {
  150. return 'data:' + type + ';base64,' + content;
  151. } else {
  152. var array = new Uint8Array( content );
  153. return window.URL.createObjectURL( new Blob( [ array ], { type: type } ) );
  154. }
  155. }
  156. // Parse nodes in FBXTree.Objects.subNodes.Texture
  157. // These contain details such as UV scaling, cropping, rotation etc and are connected
  158. // to images in FBXTree.Objects.subNodes.Video
  159. function parseTextures( FBXTree, loader, imageMap, connections ) {
  160. var textureMap = new Map();
  161. if ( 'Texture' in FBXTree.Objects.subNodes ) {
  162. var textureNodes = FBXTree.Objects.subNodes.Texture;
  163. for ( var nodeID in textureNodes ) {
  164. var texture = parseTexture( textureNodes[ nodeID ], loader, imageMap, connections );
  165. textureMap.set( parseInt( nodeID ), texture );
  166. }
  167. }
  168. return textureMap;
  169. }
  170. // Parse individual node in FBXTree.Objects.subNodes.Texture
  171. function parseTexture( textureNode, loader, imageMap, connections ) {
  172. var FBX_ID = textureNode.id;
  173. var name = textureNode.attrName;
  174. var fileName;
  175. var filePath = textureNode.properties.FileName;
  176. var relativeFilePath = textureNode.properties.RelativeFilename;
  177. var children = connections.get( FBX_ID ).children;
  178. if ( children !== undefined && children.length > 0 && imageMap.has( children[ 0 ].ID ) ) {
  179. fileName = imageMap.get( children[ 0 ].ID );
  180. } else if ( relativeFilePath !== undefined && relativeFilePath[ 0 ] !== '/' && relativeFilePath.match( /^[a-zA-Z]:/ ) === null ) {
  181. // use textureNode.properties.RelativeFilename
  182. // if it exists and it doesn't seem an absolute path
  183. fileName = relativeFilePath;
  184. } else {
  185. var split = filePath.split( /[\\\/]/ );
  186. if ( split.length > 0 ) {
  187. fileName = split[ split.length - 1 ];
  188. } else {
  189. fileName = filePath;
  190. }
  191. }
  192. var currentPath = loader.path;
  193. if ( fileName.indexOf( 'blob:' ) === 0 || fileName.indexOf( 'data:' ) === 0 ) {
  194. loader.setPath( undefined );
  195. }
  196. var texture = loader.load( fileName );
  197. texture.name = name;
  198. texture.FBX_ID = FBX_ID;
  199. var wrapModeU = textureNode.properties.WrapModeU;
  200. var wrapModeV = textureNode.properties.WrapModeV;
  201. var valueU = wrapModeU !== undefined ? wrapModeU.value : 0;
  202. var valueV = wrapModeV !== undefined ? wrapModeV.value : 0;
  203. // http://download.autodesk.com/us/fbx/SDKdocs/FBX_SDK_Help/files/fbxsdkref/class_k_fbx_texture.html#889640e63e2e681259ea81061b85143a
  204. // 0: repeat(default), 1: clamp
  205. texture.wrapS = valueU === 0 ? THREE.RepeatWrapping : THREE.ClampToEdgeWrapping;
  206. texture.wrapT = valueV === 0 ? THREE.RepeatWrapping : THREE.ClampToEdgeWrapping;
  207. if ( 'Scaling' in textureNode.properties ) {
  208. var values = textureNode.properties.Scaling.value;
  209. texture.repeat.x = values[ 0 ];
  210. texture.repeat.y = values[ 1 ];
  211. }
  212. loader.setPath( currentPath );
  213. return texture;
  214. }
  215. // Parse nodes in FBXTree.Objects.subNodes.Material
  216. function parseMaterials( FBXTree, textureMap, connections ) {
  217. var materialMap = new Map();
  218. if ( 'Material' in FBXTree.Objects.subNodes ) {
  219. var materialNodes = FBXTree.Objects.subNodes.Material;
  220. for ( var nodeID in materialNodes ) {
  221. var material = parseMaterial( materialNodes[ nodeID ], textureMap, connections );
  222. if ( material !== null ) materialMap.set( parseInt( nodeID ), material );
  223. }
  224. }
  225. return materialMap;
  226. }
  227. // Parse single node in FBXTree.Objects.subNodes.Material
  228. // Materials are connected to texture maps in FBXTree.Objects.subNodes.Textures
  229. // FBX format currently only supports Lambert and Phong shading models
  230. function parseMaterial( materialNode, textureMap, connections ) {
  231. var FBX_ID = materialNode.id;
  232. var name = materialNode.attrName;
  233. var type = materialNode.properties.ShadingModel;
  234. //Case where FBX wraps shading model in property object.
  235. if ( typeof type === 'object' ) {
  236. type = type.value;
  237. }
  238. // Ignore unused materials which don't have any connections.
  239. if ( ! connections.has( FBX_ID ) ) return null;
  240. var children = connections.get( FBX_ID ).children;
  241. var parameters = parseParameters( materialNode.properties, textureMap, children );
  242. var material;
  243. switch ( type.toLowerCase() ) {
  244. case 'phong':
  245. material = new THREE.MeshPhongMaterial();
  246. break;
  247. case 'lambert':
  248. material = new THREE.MeshLambertMaterial();
  249. break;
  250. default:
  251. console.warn( 'THREE.FBXLoader: unknown material type "%s". Defaulting to MeshPhongMaterial.', type );
  252. material = new THREE.MeshPhongMaterial( { color: 0x3300ff } );
  253. break;
  254. }
  255. material.setValues( parameters );
  256. material.name = name;
  257. return material;
  258. }
  259. // Parse FBX material and return parameters suitable for a three.js material
  260. // Also parse the texture map and return any textures associated with the material
  261. function parseParameters( properties, textureMap, childrenRelationships ) {
  262. var parameters = {};
  263. if ( properties.BumpFactor ) {
  264. parameters.bumpScale = properties.BumpFactor.value;
  265. }
  266. if ( properties.Diffuse ) {
  267. parameters.color = parseColor( properties.Diffuse );
  268. }
  269. if ( properties.DisplacementFactor ) {
  270. parameters.displacementScale = properties.DisplacementFactor.value;
  271. }
  272. if ( properties.ReflectionFactor ) {
  273. parameters.reflectivity = properties.ReflectionFactor.value;
  274. }
  275. if ( properties.Specular ) {
  276. parameters.specular = parseColor( properties.Specular );
  277. }
  278. if ( properties.Shininess ) {
  279. parameters.shininess = properties.Shininess.value;
  280. }
  281. if ( properties.Emissive ) {
  282. parameters.emissive = parseColor( properties.Emissive );
  283. }
  284. if ( properties.EmissiveFactor ) {
  285. parameters.emissiveIntensity = parseFloat( properties.EmissiveFactor.value );
  286. }
  287. if ( properties.Opacity ) {
  288. parameters.opacity = parseFloat( properties.Opacity.value );
  289. }
  290. if ( parameters.opacity < 1.0 ) {
  291. parameters.transparent = true;
  292. }
  293. for ( var childrenRelationshipsIndex = 0, childrenRelationshipsLength = childrenRelationships.length; childrenRelationshipsIndex < childrenRelationshipsLength; ++ childrenRelationshipsIndex ) {
  294. var relationship = childrenRelationships[ childrenRelationshipsIndex ];
  295. var type = relationship.relationship;
  296. switch ( type ) {
  297. case 'Bump':
  298. parameters.bumpMap = textureMap.get( relationship.ID );
  299. break;
  300. case 'DiffuseColor':
  301. parameters.map = textureMap.get( relationship.ID );
  302. break;
  303. case 'DisplacementColor':
  304. parameters.displacementMap = textureMap.get( relationship.ID );
  305. break;
  306. case 'EmissiveColor':
  307. parameters.emissiveMap = textureMap.get( relationship.ID );
  308. break;
  309. case 'NormalMap':
  310. parameters.normalMap = textureMap.get( relationship.ID );
  311. break;
  312. case 'ReflectionColor':
  313. parameters.envMap = textureMap.get( relationship.ID );
  314. parameters.envMap.mapping = THREE.EquirectangularReflectionMapping;
  315. break;
  316. case 'SpecularColor':
  317. parameters.specularMap = textureMap.get( relationship.ID );
  318. break;
  319. case 'TransparentColor':
  320. parameters.alphaMap = textureMap.get( relationship.ID );
  321. parameters.transparent = true;
  322. break;
  323. case 'AmbientColor':
  324. case 'ShininessExponent': // AKA glossiness map
  325. case 'SpecularFactor': // AKA specularLevel
  326. case 'VectorDisplacementColor': // NOTE: Seems to be a copy of DisplacementColor
  327. default:
  328. console.warn( 'THREE.FBXLoader: %s map is not supported in three.js, skipping texture.', type );
  329. break;
  330. }
  331. }
  332. return parameters;
  333. }
  334. // Parse nodes in FBXTree.Objects.subNodes.Deformer
  335. // Deformer node can contain skinning or Vertex Cache animation data, however only skinning is supported here
  336. // Generates map of Skeleton-like objects for use later when generating and binding skeletons.
  337. function parseDeformers( FBXTree, connections ) {
  338. var deformers = {};
  339. if ( 'Deformer' in FBXTree.Objects.subNodes ) {
  340. var DeformerNodes = FBXTree.Objects.subNodes.Deformer;
  341. for ( var nodeID in DeformerNodes ) {
  342. var deformerNode = DeformerNodes[ nodeID ];
  343. if ( deformerNode.attrType === 'Skin' ) {
  344. var conns = connections.get( parseInt( nodeID ) );
  345. var skeleton = parseSkeleton( conns, DeformerNodes );
  346. skeleton.FBX_ID = parseInt( nodeID );
  347. deformers[ nodeID ] = skeleton;
  348. }
  349. }
  350. }
  351. return deformers;
  352. }
  353. // Parse single nodes in FBXTree.Objects.subNodes.Deformer
  354. // Generates a "Skeleton Representation" of FBX nodes based on an FBX Skin Deformer's connections
  355. // and an object containing SubDeformer nodes.
  356. function parseSkeleton( connections, DeformerNodes ) {
  357. var subDeformers = {};
  358. var children = connections.children;
  359. for ( var i = 0, l = children.length; i < l; ++ i ) {
  360. var child = children[ i ];
  361. var subDeformerNode = DeformerNodes[ child.ID ];
  362. var subDeformer = {
  363. FBX_ID: child.ID,
  364. index: i,
  365. indices: [],
  366. weights: [],
  367. transform: new THREE.Matrix4().fromArray( subDeformerNode.subNodes.Transform.properties.a ),
  368. transformLink: new THREE.Matrix4().fromArray( subDeformerNode.subNodes.TransformLink.properties.a ),
  369. linkMode: subDeformerNode.properties.Mode
  370. };
  371. if ( 'Indexes' in subDeformerNode.subNodes ) {
  372. subDeformer.indices = subDeformerNode.subNodes.Indexes.properties.a;
  373. subDeformer.weights = subDeformerNode.subNodes.Weights.properties.a;
  374. }
  375. subDeformers[ child.ID ] = subDeformer;
  376. }
  377. return {
  378. map: subDeformers,
  379. bones: []
  380. };
  381. }
  382. // Parse nodes in FBXTree.Objects.subNodes.Geometry
  383. function parseGeometries( FBXTree, connections, deformers ) {
  384. var geometryMap = new Map();
  385. if ( 'Geometry' in FBXTree.Objects.subNodes ) {
  386. var geometryNodes = FBXTree.Objects.subNodes.Geometry;
  387. for ( var nodeID in geometryNodes ) {
  388. var relationships = connections.get( parseInt( nodeID ) );
  389. var geo = parseGeometry( geometryNodes[ nodeID ], relationships, deformers );
  390. geometryMap.set( parseInt( nodeID ), geo );
  391. }
  392. }
  393. return geometryMap;
  394. }
  395. // Parse single node in FBXTree.Objects.subNodes.Geometry
  396. function parseGeometry( geometryNode, relationships, deformers ) {
  397. switch ( geometryNode.attrType ) {
  398. case 'Mesh':
  399. return parseMeshGeometry( geometryNode, relationships, deformers );
  400. break;
  401. case 'NurbsCurve':
  402. return parseNurbsGeometry( geometryNode );
  403. break;
  404. }
  405. }
  406. // Parse single node mesh geometry in FBXTree.Objects.subNodes.Geometry
  407. function parseMeshGeometry( geometryNode, relationships, deformers ) {
  408. for ( var i = 0; i < relationships.children.length; ++ i ) {
  409. var deformer = deformers[ relationships.children[ i ].ID ];
  410. if ( deformer !== undefined ) break;
  411. }
  412. return genGeometry( geometryNode, deformer );
  413. }
  414. // Generate a THREE.BufferGeometry from a node in FBXTree.Objects.subNodes.Geometry
  415. function genGeometry( geometryNode, deformer ) {
  416. var subNodes = geometryNode.subNodes;
  417. var vertexPositions = subNodes.Vertices.properties.a;
  418. var vertexIndices = subNodes.PolygonVertexIndex.properties.a;
  419. // create arrays to hold the final data used to build the buffergeometry
  420. var vertexBuffer = [];
  421. var normalBuffer = [];
  422. var colorsBuffer = [];
  423. var uvsBuffer = [];
  424. var materialIndexBuffer = [];
  425. var vertexWeightsBuffer = [];
  426. var weightsIndicesBuffer = [];
  427. if ( subNodes.LayerElementColor ) {
  428. var colorInfo = getColors( subNodes.LayerElementColor[ 0 ] );
  429. }
  430. if ( subNodes.LayerElementMaterial ) {
  431. var materialInfo = getMaterials( subNodes.LayerElementMaterial[ 0 ] );
  432. }
  433. if ( subNodes.LayerElementNormal ) {
  434. var normalInfo = getNormals( subNodes.LayerElementNormal[ 0 ] );
  435. }
  436. if ( subNodes.LayerElementUV ) {
  437. var uvInfo = [];
  438. var i = 0;
  439. while ( subNodes.LayerElementUV[ i ] ) {
  440. uvInfo.push( getUVs( subNodes.LayerElementUV[ i ] ) );
  441. i ++;
  442. }
  443. }
  444. var weightTable = {};
  445. if ( deformer ) {
  446. var subDeformers = deformer.map;
  447. for ( var key in subDeformers ) {
  448. var subDeformer = subDeformers[ key ];
  449. var indices = subDeformer.indices;
  450. for ( var j = 0; j < indices.length; j ++ ) {
  451. var index = indices[ j ];
  452. var weight = subDeformer.weights[ j ];
  453. if ( weightTable[ index ] === undefined ) weightTable[ index ] = [];
  454. weightTable[ index ].push( {
  455. id: subDeformer.index,
  456. weight: weight
  457. } );
  458. }
  459. }
  460. }
  461. var polygonIndex = 0;
  462. var faceLength = 0;
  463. var displayedWeightsWarning = false;
  464. // these will hold data for a single face
  465. var vertexPositionIndexes = [];
  466. var faceNormals = [];
  467. var faceColors = [];
  468. var faceUVs = [];
  469. var faceWeights = [];
  470. var faceWeightIndices = [];
  471. for ( var polygonVertexIndex = 0; polygonVertexIndex < vertexIndices.length; polygonVertexIndex ++ ) {
  472. var vertexIndex = vertexIndices[ polygonVertexIndex ];
  473. var endOfFace = false;
  474. // Face index and vertex index arrays are combined in a single array
  475. // A cube with quad faces looks like this:
  476. // PolygonVertexIndex: *24 {
  477. // a: 0, 1, 3, -3, 2, 3, 5, -5, 4, 5, 7, -7, 6, 7, 1, -1, 1, 7, 5, -4, 6, 0, 2, -5
  478. // }
  479. // Negative numbers mark the end of a face - first face here is 0, 1, 3, -3
  480. // to find index of last vertex multiply by -1 and subtract 1: -3 * - 1 - 1 = 2
  481. if ( vertexIndex < 0 ) {
  482. vertexIndex = vertexIndex ^ - 1; // equivalent to ( x * -1 ) - 1
  483. vertexIndices[ polygonVertexIndex ] = vertexIndex;
  484. endOfFace = true;
  485. }
  486. var weightIndices = [];
  487. var weights = [];
  488. vertexPositionIndexes.push( vertexIndex * 3, vertexIndex * 3 + 1, vertexIndex * 3 + 2 );
  489. if ( colorInfo ) {
  490. var data = getData( polygonVertexIndex, polygonIndex, vertexIndex, colorInfo );
  491. faceColors.push( data[ 0 ], data[ 1 ], data[ 2 ] );
  492. }
  493. if ( deformer ) {
  494. if ( weightTable[ vertexIndex ] !== undefined ) {
  495. var array = weightTable[ vertexIndex ];
  496. for ( var j = 0, jl = array.length; j < jl; j ++ ) {
  497. weights.push( array[ j ].weight );
  498. weightIndices.push( array[ j ].id );
  499. }
  500. }
  501. if ( weights.length > 4 ) {
  502. if ( ! displayedWeightsWarning ) {
  503. console.warn( 'THREE.FBXLoader: Vertex has more than 4 skinning weights assigned to vertex. Deleting additional weights.' );
  504. displayedWeightsWarning = true;
  505. }
  506. var WIndex = [ 0, 0, 0, 0 ];
  507. var Weight = [ 0, 0, 0, 0 ];
  508. weights.forEach( function ( weight, weightIndex ) {
  509. var currentWeight = weight;
  510. var currentIndex = weightIndices[ weightIndex ];
  511. Weight.forEach( function ( comparedWeight, comparedWeightIndex, comparedWeightArray ) {
  512. if ( currentWeight > comparedWeight ) {
  513. comparedWeightArray[ comparedWeightIndex ] = currentWeight;
  514. currentWeight = comparedWeight;
  515. var tmp = WIndex[ comparedWeightIndex ];
  516. WIndex[ comparedWeightIndex ] = currentIndex;
  517. currentIndex = tmp;
  518. }
  519. } );
  520. } );
  521. weightIndices = WIndex;
  522. weights = Weight;
  523. }
  524. // if the weight array is shorter than 4 pad with 0s
  525. for ( var i = weights.length; i < 4; ++ i ) {
  526. weights[ i ] = 0;
  527. weightIndices[ i ] = 0;
  528. }
  529. for ( var i = 0; i < 4; ++ i ) {
  530. faceWeights.push( weights[ i ] );
  531. faceWeightIndices.push( weightIndices[ i ] );
  532. }
  533. }
  534. if ( normalInfo ) {
  535. var data = getData( polygonVertexIndex, polygonIndex, vertexIndex, normalInfo );
  536. faceNormals.push( data[ 0 ], data[ 1 ], data[ 2 ] );
  537. }
  538. if ( uvInfo ) {
  539. for ( var i = 0; i < uvInfo.length; i ++ ) {
  540. var data = getData( polygonVertexIndex, polygonIndex, vertexIndex, uvInfo[ i ] );
  541. if ( faceUVs[ i ] === undefined ) {
  542. faceUVs[ i ] = [];
  543. }
  544. faceUVs[ i ].push(
  545. data[ 0 ],
  546. data[ 1 ]
  547. );
  548. }
  549. }
  550. faceLength ++;
  551. // we have reached the end of a face - it may have 4 sides though
  552. // in which case the data is split into to represent 3 sides faces
  553. if ( endOfFace ) {
  554. for ( var i = 2; i < faceLength; i ++ ) {
  555. vertexBuffer.push( vertexPositions[ vertexPositionIndexes[ 0 ] ] );
  556. vertexBuffer.push( vertexPositions[ vertexPositionIndexes[ 1 ] ] );
  557. vertexBuffer.push( vertexPositions[ vertexPositionIndexes[ 2 ] ] );
  558. vertexBuffer.push( vertexPositions[ vertexPositionIndexes[ ( i - 1 ) * 3 ] ] );
  559. vertexBuffer.push( vertexPositions[ vertexPositionIndexes[ ( i - 1 ) * 3 + 1 ] ] );
  560. vertexBuffer.push( vertexPositions[ vertexPositionIndexes[ ( i - 1 ) * 3 + 2 ] ] );
  561. vertexBuffer.push( vertexPositions[ vertexPositionIndexes[ i * 3 ] ] );
  562. vertexBuffer.push( vertexPositions[ vertexPositionIndexes[ i * 3 + 1 ] ] );
  563. vertexBuffer.push( vertexPositions[ vertexPositionIndexes[ i * 3 + 2 ] ] );
  564. }
  565. if ( deformer ) {
  566. for ( var i = 2; i < faceLength; i ++ ) {
  567. vertexWeightsBuffer.push( faceWeights[ 0 ] );
  568. vertexWeightsBuffer.push( faceWeights[ 1 ] );
  569. vertexWeightsBuffer.push( faceWeights[ 2 ] );
  570. vertexWeightsBuffer.push( faceWeights[ 3 ] );
  571. vertexWeightsBuffer.push( faceWeights[ ( i - 1 ) * 4 ] );
  572. vertexWeightsBuffer.push( faceWeights[ ( i - 1 ) * 4 + 1 ] );
  573. vertexWeightsBuffer.push( faceWeights[ ( i - 1 ) * 4 + 2 ] );
  574. vertexWeightsBuffer.push( faceWeights[ ( i - 1 ) * 4 + 3 ] );
  575. vertexWeightsBuffer.push( faceWeights[ i * 4 ] );
  576. vertexWeightsBuffer.push( faceWeights[ i * 4 + 1 ] );
  577. vertexWeightsBuffer.push( faceWeights[ i * 4 + 2 ] );
  578. vertexWeightsBuffer.push( faceWeights[ i * 4 + 3 ] );
  579. weightsIndicesBuffer.push( faceWeightIndices[ 0 ] );
  580. weightsIndicesBuffer.push( faceWeightIndices[ 1 ] );
  581. weightsIndicesBuffer.push( faceWeightIndices[ 2 ] );
  582. weightsIndicesBuffer.push( faceWeightIndices[ 3 ] );
  583. weightsIndicesBuffer.push( faceWeightIndices[ ( i - 1 ) * 4 ] );
  584. weightsIndicesBuffer.push( faceWeightIndices[ ( i - 1 ) * 4 + 1 ] );
  585. weightsIndicesBuffer.push( faceWeightIndices[ ( i - 1 ) * 4 + 2 ] );
  586. weightsIndicesBuffer.push( faceWeightIndices[ ( i - 1 ) * 4 + 3 ] );
  587. weightsIndicesBuffer.push( faceWeightIndices[ i * 4 ] );
  588. weightsIndicesBuffer.push( faceWeightIndices[ i * 4 + 1 ] );
  589. weightsIndicesBuffer.push( faceWeightIndices[ i * 4 + 2 ] );
  590. weightsIndicesBuffer.push( faceWeightIndices[ i * 4 + 3 ] );
  591. }
  592. }
  593. if ( normalInfo ) {
  594. for ( var i = 2; i < faceLength; i ++ ) {
  595. normalBuffer.push( faceNormals[ 0 ] );
  596. normalBuffer.push( faceNormals[ 1 ] );
  597. normalBuffer.push( faceNormals[ 2 ] );
  598. normalBuffer.push( faceNormals[ ( i - 1 ) * 3 ] );
  599. normalBuffer.push( faceNormals[ ( i - 1 ) * 3 + 1 ] );
  600. normalBuffer.push( faceNormals[ ( i - 1 ) * 3 + 2 ] );
  601. normalBuffer.push( faceNormals[ i * 3 ] );
  602. normalBuffer.push( faceNormals[ i * 3 + 1 ] );
  603. normalBuffer.push( faceNormals[ i * 3 + 2 ] );
  604. }
  605. }
  606. if ( uvInfo ) {
  607. for ( var j = 0; j < uvInfo.length; j ++ ) {
  608. if ( uvsBuffer[ j ] === undefined ) uvsBuffer[ j ] = [];
  609. for ( var i = 2; i < faceLength; i ++ ) {
  610. uvsBuffer[ j ].push( faceUVs[ j ][ 0 ] );
  611. uvsBuffer[ j ].push( faceUVs[ j ][ 1 ] );
  612. uvsBuffer[ j ].push( faceUVs[ j ][ ( i - 1 ) * 2 ] );
  613. uvsBuffer[ j ].push( faceUVs[ j ][ ( i - 1 ) * 2 + 1 ] );
  614. uvsBuffer[ j ].push( faceUVs[ j ][ i * 2 ] );
  615. uvsBuffer[ j ].push( faceUVs[ j ][ i * 2 + 1 ] );
  616. }
  617. }
  618. }
  619. if ( colorInfo ) {
  620. for ( var i = 2; i < faceLength; i ++ ) {
  621. colorsBuffer.push( faceColors[ 0 ] );
  622. colorsBuffer.push( faceColors[ 1 ] );
  623. colorsBuffer.push( faceColors[ 2 ] );
  624. colorsBuffer.push( faceColors[ ( i - 1 ) * 3 ] );
  625. colorsBuffer.push( faceColors[ ( i - 1 ) * 3 + 1 ] );
  626. colorsBuffer.push( faceColors[ ( i - 1 ) * 3 + 2 ] );
  627. colorsBuffer.push( faceColors[ i * 3 ] );
  628. colorsBuffer.push( faceColors[ i * 3 + 1 ] );
  629. colorsBuffer.push( faceColors[ i * 3 + 2 ] );
  630. }
  631. }
  632. if ( materialInfo && materialInfo.mappingType !== 'AllSame' ) {
  633. var materialIndex = getData( polygonVertexIndex, polygonIndex, vertexIndex, materialInfo )[ 0 ];
  634. for ( var i = 2; i < faceLength; i ++ ) {
  635. materialIndexBuffer.push( materialIndex );
  636. materialIndexBuffer.push( materialIndex );
  637. materialIndexBuffer.push( materialIndex );
  638. }
  639. }
  640. polygonIndex ++;
  641. endOfFace = false;
  642. faceLength = 0;
  643. // reset arrays for the next face
  644. vertexPositionIndexes = [];
  645. faceNormals = [];
  646. faceColors = [];
  647. faceUVs = [];
  648. faceWeights = [];
  649. faceWeightIndices = [];
  650. }
  651. }
  652. var geo = new THREE.BufferGeometry();
  653. geo.name = geometryNode.name;
  654. geo.addAttribute( 'position', new THREE.Float32BufferAttribute( vertexBuffer, 3 ) );
  655. if ( colorsBuffer.length > 0 ) {
  656. geo.addAttribute( 'color', new THREE.Float32BufferAttribute( colorsBuffer, 3 ) );
  657. }
  658. if ( deformer ) {
  659. geo.addAttribute( 'skinIndex', new THREE.Float32BufferAttribute( weightsIndicesBuffer, 4 ) );
  660. geo.addAttribute( 'skinWeight', new THREE.Float32BufferAttribute( vertexWeightsBuffer, 4 ) );
  661. // used later to bind the skeleton to the model
  662. geo.FBX_Deformer = deformer;
  663. }
  664. if ( normalBuffer.length > 0 ) {
  665. geo.addAttribute( 'normal', new THREE.Float32BufferAttribute( normalBuffer, 3 ) );
  666. }
  667. if ( uvsBuffer.length > 0 ) {
  668. for ( var i = 0; i < uvsBuffer.length; i ++ ) {
  669. var name = 'uv' + ( i + 1 ).toString();
  670. if ( i == 0 ) {
  671. name = 'uv';
  672. }
  673. geo.addAttribute( name, new THREE.Float32BufferAttribute( uvsBuffer[ i ], 2 ) );
  674. }
  675. }
  676. if ( materialInfo && materialInfo.mappingType !== 'AllSame' ) {
  677. // Convert the material indices of each vertex into rendering groups on the geometry.
  678. var prevMaterialIndex = materialIndexBuffer[ 0 ];
  679. var startIndex = 0;
  680. for ( var i = 0; i < materialIndexBuffer.length; ++ i ) {
  681. if ( materialIndexBuffer[ i ] !== prevMaterialIndex ) {
  682. geo.addGroup( startIndex, i - startIndex, prevMaterialIndex );
  683. prevMaterialIndex = materialIndexBuffer[ i ];
  684. startIndex = i;
  685. }
  686. }
  687. // the loop above doesn't add the last group, do that here.
  688. if ( geo.groups.length > 0 ) {
  689. var lastGroup = geo.groups[ geo.groups.length - 1 ];
  690. var lastIndex = lastGroup.start + lastGroup.count;
  691. if ( lastIndex !== materialIndexBuffer.length ) {
  692. geo.addGroup( lastIndex, materialIndexBuffer.length - lastIndex, prevMaterialIndex );
  693. }
  694. }
  695. // case where there are multiple materials but the whole geometry is only
  696. // using one of them
  697. if ( geo.groups.length === 0 ) {
  698. geo.addGroup( 0, materialIndexBuffer.length, materialIndexBuffer[ 0 ] );
  699. }
  700. }
  701. return geo;
  702. }
  703. // Parse normal from FBXTree.Objects.subNodes.Geometry.subNodes.LayerElementNormal if it exists
  704. function getNormals( NormalNode ) {
  705. var mappingType = NormalNode.properties.MappingInformationType;
  706. var referenceType = NormalNode.properties.ReferenceInformationType;
  707. var buffer = NormalNode.subNodes.Normals.properties.a;
  708. var indexBuffer = [];
  709. if ( referenceType === 'IndexToDirect' ) {
  710. if ( 'NormalIndex' in NormalNode.subNodes ) {
  711. indexBuffer = NormalNode.subNodes.NormalIndex.properties.a;
  712. } else if ( 'NormalsIndex' in NormalNode.subNodes ) {
  713. indexBuffer = NormalNode.subNodes.NormalsIndex.properties.a;
  714. }
  715. }
  716. return {
  717. dataSize: 3,
  718. buffer: buffer,
  719. indices: indexBuffer,
  720. mappingType: mappingType,
  721. referenceType: referenceType
  722. };
  723. }
  724. // Parse UVs from FBXTree.Objects.subNodes.Geometry.subNodes.LayerElementUV if it exists
  725. function getUVs( UVNode ) {
  726. var mappingType = UVNode.properties.MappingInformationType;
  727. var referenceType = UVNode.properties.ReferenceInformationType;
  728. var buffer = UVNode.subNodes.UV.properties.a;
  729. var indexBuffer = [];
  730. if ( referenceType === 'IndexToDirect' ) {
  731. indexBuffer = UVNode.subNodes.UVIndex.properties.a;
  732. }
  733. return {
  734. dataSize: 2,
  735. buffer: buffer,
  736. indices: indexBuffer,
  737. mappingType: mappingType,
  738. referenceType: referenceType
  739. };
  740. }
  741. // Parse Vertex Colors from FBXTree.Objects.subNodes.Geometry.subNodes.LayerElementColor if it exists
  742. function getColors( ColorNode ) {
  743. var mappingType = ColorNode.properties.MappingInformationType;
  744. var referenceType = ColorNode.properties.ReferenceInformationType;
  745. var buffer = ColorNode.subNodes.Colors.properties.a;
  746. var indexBuffer = [];
  747. if ( referenceType === 'IndexToDirect' ) {
  748. indexBuffer = ColorNode.subNodes.ColorIndex.properties.a;
  749. }
  750. return {
  751. dataSize: 4,
  752. buffer: buffer,
  753. indices: indexBuffer,
  754. mappingType: mappingType,
  755. referenceType: referenceType
  756. };
  757. }
  758. // Parse mapping and material data in FBXTree.Objects.subNodes.Geometry.subNodes.LayerElementMaterial if it exists
  759. function getMaterials( MaterialNode ) {
  760. var mappingType = MaterialNode.properties.MappingInformationType;
  761. var referenceType = MaterialNode.properties.ReferenceInformationType;
  762. if ( mappingType === 'NoMappingInformation' ) {
  763. return {
  764. dataSize: 1,
  765. buffer: [ 0 ],
  766. indices: [ 0 ],
  767. mappingType: 'AllSame',
  768. referenceType: referenceType
  769. };
  770. }
  771. var materialIndexBuffer = MaterialNode.subNodes.Materials.properties.a;
  772. // Since materials are stored as indices, there's a bit of a mismatch between FBX and what
  773. // we expect.So we create an intermediate buffer that points to the index in the buffer,
  774. // for conforming with the other functions we've written for other data.
  775. var materialIndices = [];
  776. for ( var materialIndexBufferIndex = 0, materialIndexBufferLength = materialIndexBuffer.length; materialIndexBufferIndex < materialIndexBufferLength; ++ materialIndexBufferIndex ) {
  777. materialIndices.push( materialIndexBufferIndex );
  778. }
  779. return {
  780. dataSize: 1,
  781. buffer: materialIndexBuffer,
  782. indices: materialIndices,
  783. mappingType: mappingType,
  784. referenceType: referenceType
  785. };
  786. }
  787. // Functions use the infoObject and given indices to return value array of geometry.
  788. // infoObject can be materialInfo, normalInfo, UVInfo or colorInfo
  789. // polygonVertexIndex - Index of vertex in draw order (which index of the index buffer refers to this vertex).
  790. // polygonIndex - Index of polygon in geometry.
  791. // vertexIndex - Index of vertex inside vertex buffer (used because some data refers to old index buffer that we don't use anymore).
  792. var dataArray = [];
  793. var GetData = {
  794. ByPolygonVertex: {
  795. Direct: function ( polygonVertexIndex, polygonIndex, vertexIndex, infoObject ) {
  796. var from = ( polygonVertexIndex * infoObject.dataSize );
  797. var to = ( polygonVertexIndex * infoObject.dataSize ) + infoObject.dataSize;
  798. // return infoObject.buffer.slice( from, to );
  799. return slice( dataArray, infoObject.buffer, from, to );
  800. },
  801. IndexToDirect: function ( polygonVertexIndex, polygonIndex, vertexIndex, infoObject ) {
  802. var index = infoObject.indices[ polygonVertexIndex ];
  803. var from = ( index * infoObject.dataSize );
  804. var to = ( index * infoObject.dataSize ) + infoObject.dataSize;
  805. // return infoObject.buffer.slice( from, to );
  806. return slice( dataArray, infoObject.buffer, from, to );
  807. }
  808. },
  809. ByPolygon: {
  810. Direct: function ( polygonVertexIndex, polygonIndex, vertexIndex, infoObject ) {
  811. var from = polygonIndex * infoObject.dataSize;
  812. var to = polygonIndex * infoObject.dataSize + infoObject.dataSize;
  813. // return infoObject.buffer.slice( from, to );
  814. return slice( dataArray, infoObject.buffer, from, to );
  815. },
  816. IndexToDirect: function ( polygonVertexIndex, polygonIndex, vertexIndex, infoObject ) {
  817. var index = infoObject.indices[ polygonIndex ];
  818. var from = index * infoObject.dataSize;
  819. var to = index * infoObject.dataSize + infoObject.dataSize;
  820. // return infoObject.buffer.slice( from, to );
  821. return slice( dataArray, infoObject.buffer, from, to );
  822. }
  823. },
  824. ByVertice: {
  825. Direct: function ( polygonVertexIndex, polygonIndex, vertexIndex, infoObject ) {
  826. var from = ( vertexIndex * infoObject.dataSize );
  827. var to = ( vertexIndex * infoObject.dataSize ) + infoObject.dataSize;
  828. // return infoObject.buffer.slice( from, to );
  829. return slice( dataArray, infoObject.buffer, from, to );
  830. }
  831. },
  832. AllSame: {
  833. IndexToDirect: function ( polygonVertexIndex, polygonIndex, vertexIndex, infoObject ) {
  834. var from = infoObject.indices[ 0 ] * infoObject.dataSize;
  835. var to = infoObject.indices[ 0 ] * infoObject.dataSize + infoObject.dataSize;
  836. // return infoObject.buffer.slice( from, to );
  837. return slice( dataArray, infoObject.buffer, from, to );
  838. }
  839. }
  840. };
  841. function getData( polygonVertexIndex, polygonIndex, vertexIndex, infoObject ) {
  842. return GetData[ infoObject.mappingType ][ infoObject.referenceType ]( polygonVertexIndex, polygonIndex, vertexIndex, infoObject );
  843. }
  844. // Generate a NurbGeometry from a node in FBXTree.Objects.subNodes.Geometry
  845. function parseNurbsGeometry( geometryNode ) {
  846. if ( THREE.NURBSCurve === undefined ) {
  847. console.error( 'THREE.FBXLoader: The loader relies on THREE.NURBSCurve for any nurbs present in the model. Nurbs will show up as empty geometry.' );
  848. return new THREE.BufferGeometry();
  849. }
  850. var order = parseInt( geometryNode.properties.Order );
  851. if ( isNaN( order ) ) {
  852. console.error( 'THREE.FBXLoader: Invalid Order %s given for geometry ID: %s', geometryNode.properties.Order, geometryNode.id );
  853. return new THREE.BufferGeometry();
  854. }
  855. var degree = order - 1;
  856. var knots = geometryNode.subNodes.KnotVector.properties.a;
  857. var controlPoints = [];
  858. var pointsValues = geometryNode.subNodes.Points.properties.a;
  859. for ( var i = 0, l = pointsValues.length; i < l; i += 4 ) {
  860. controlPoints.push( new THREE.Vector4().fromArray( pointsValues, i ) );
  861. }
  862. var startKnot, endKnot;
  863. if ( geometryNode.properties.Form === 'Closed' ) {
  864. controlPoints.push( controlPoints[ 0 ] );
  865. } else if ( geometryNode.properties.Form === 'Periodic' ) {
  866. startKnot = degree;
  867. endKnot = knots.length - 1 - startKnot;
  868. for ( var i = 0; i < degree; ++ i ) {
  869. controlPoints.push( controlPoints[ i ] );
  870. }
  871. }
  872. var curve = new THREE.NURBSCurve( degree, knots, controlPoints, startKnot, endKnot );
  873. var vertices = curve.getPoints( controlPoints.length * 7 );
  874. var positions = new Float32Array( vertices.length * 3 );
  875. for ( var i = 0, l = vertices.length; i < l; ++ i ) {
  876. vertices[ i ].toArray( positions, i * 3 );
  877. }
  878. var geometry = new THREE.BufferGeometry();
  879. geometry.addAttribute( 'position', new THREE.BufferAttribute( positions, 3 ) );
  880. return geometry;
  881. }
  882. // parse nodes in FBXTree.Objects.subNodes.Model and generate a THREE.Group
  883. function parseScene( FBXTree, connections, deformers, geometryMap, materialMap ) {
  884. var sceneGraph = new THREE.Group();
  885. var ModelNode = FBXTree.Objects.subNodes.Model;
  886. var modelArray = [];
  887. var modelMap = new Map();
  888. for ( var nodeID in ModelNode ) {
  889. var id = parseInt( nodeID );
  890. var node = ModelNode[ nodeID ];
  891. var conns = connections.get( id );
  892. var model = null;
  893. for ( var i = 0; i < conns.parents.length; ++ i ) {
  894. for ( var FBX_ID in deformers ) {
  895. var deformer = deformers[ FBX_ID ];
  896. var subDeformers = deformer.map;
  897. var subDeformer = subDeformers[ conns.parents[ i ].ID ];
  898. if ( subDeformer ) {
  899. var model2 = model;
  900. model = new THREE.Bone();
  901. deformer.bones[ subDeformer.index ] = model;
  902. // seems like we need this not to make non-connected bone, maybe?
  903. // TODO: confirm
  904. if ( model2 !== null ) model.add( model2 );
  905. }
  906. }
  907. }
  908. if ( ! model ) {
  909. switch ( node.attrType ) {
  910. // create a THREE.PerspectiveCamera or THREE.OrthographicCamera
  911. case 'Camera':
  912. var cameraAttribute;
  913. for ( var childrenIndex = 0, childrenLength = conns.children.length; childrenIndex < childrenLength; ++ childrenIndex ) {
  914. var childID = conns.children[ childrenIndex ].ID;
  915. var attr = FBXTree.Objects.subNodes.NodeAttribute[ childID ];
  916. if ( attr !== undefined && attr.properties !== undefined ) {
  917. cameraAttribute = attr.properties;
  918. }
  919. }
  920. if ( cameraAttribute === undefined ) {
  921. model = new THREE.Object3D();
  922. } else {
  923. var type = 0;
  924. if ( cameraAttribute.CameraProjectionType !== undefined && cameraAttribute.CameraProjectionType.value === 1 ) {
  925. type = 1;
  926. }
  927. var nearClippingPlane = 1;
  928. if ( cameraAttribute.NearPlane !== undefined ) {
  929. nearClippingPlane = cameraAttribute.NearPlane.value / 1000;
  930. }
  931. var farClippingPlane = 1000;
  932. if ( cameraAttribute.FarPlane !== undefined ) {
  933. farClippingPlane = cameraAttribute.FarPlane.value / 1000;
  934. }
  935. var width = window.innerWidth;
  936. var height = window.innerHeight;
  937. if ( cameraAttribute.AspectWidth !== undefined && cameraAttribute.AspectHeight !== undefined ) {
  938. width = cameraAttribute.AspectWidth.value;
  939. height = cameraAttribute.AspectHeight.value;
  940. }
  941. var aspect = width / height;
  942. var fov = 45;
  943. if ( cameraAttribute.FieldOfView !== undefined ) {
  944. fov = cameraAttribute.FieldOfView.value;
  945. }
  946. switch ( type ) {
  947. case 0: // Perspective
  948. model = new THREE.PerspectiveCamera( fov, aspect, nearClippingPlane, farClippingPlane );
  949. break;
  950. case 1: // Orthographic
  951. model = new THREE.OrthographicCamera( - width / 2, width / 2, height / 2, - height / 2, nearClippingPlane, farClippingPlane );
  952. break;
  953. default:
  954. console.warn( 'THREE.FBXLoader: Unknown camera type ' + type + '.' );
  955. model = new THREE.Object3D();
  956. break;
  957. }
  958. }
  959. break;
  960. // Create a THREE.DirectionalLight, THREE.PointLight or THREE.SpotLight
  961. case 'Light':
  962. var lightAttribute;
  963. for ( var childrenIndex = 0, childrenLength = conns.children.length; childrenIndex < childrenLength; ++ childrenIndex ) {
  964. var childID = conns.children[ childrenIndex ].ID;
  965. var attr = FBXTree.Objects.subNodes.NodeAttribute[ childID ];
  966. if ( attr !== undefined && attr.properties !== undefined ) {
  967. lightAttribute = attr.properties;
  968. }
  969. }
  970. if ( lightAttribute === undefined ) {
  971. model = new THREE.Object3D();
  972. } else {
  973. var type;
  974. // LightType can be undefined for Point lights
  975. if ( lightAttribute.LightType === undefined ) {
  976. type = 0;
  977. } else {
  978. type = lightAttribute.LightType.value;
  979. }
  980. var color = 0xffffff;
  981. if ( lightAttribute.Color !== undefined ) {
  982. color = parseColor( lightAttribute.Color.value );
  983. }
  984. var intensity = ( lightAttribute.Intensity === undefined ) ? 1 : lightAttribute.Intensity.value / 100;
  985. // light disabled
  986. if ( lightAttribute.CastLightOnObject !== undefined && lightAttribute.CastLightOnObject.value === 0 ) {
  987. intensity = 0;
  988. }
  989. var distance = 0;
  990. if ( lightAttribute.FarAttenuationEnd !== undefined ) {
  991. if ( lightAttribute.EnableFarAttenuation !== undefined && lightAttribute.EnableFarAttenuation.value === 0 ) {
  992. distance = 0;
  993. } else {
  994. distance = lightAttribute.FarAttenuationEnd.value / 1000;
  995. }
  996. }
  997. // TODO: could this be calculated linearly from FarAttenuationStart to FarAttenuationEnd?
  998. var decay = 1;
  999. switch ( type ) {
  1000. case 0: // Point
  1001. model = new THREE.PointLight( color, intensity, distance, decay );
  1002. break;
  1003. case 1: // Directional
  1004. model = new THREE.DirectionalLight( color, intensity );
  1005. break;
  1006. case 2: // Spot
  1007. var angle = Math.PI / 3;
  1008. if ( lightAttribute.InnerAngle !== undefined ) {
  1009. angle = THREE.Math.degToRad( lightAttribute.InnerAngle.value );
  1010. }
  1011. var penumbra = 0;
  1012. if ( lightAttribute.OuterAngle !== undefined ) {
  1013. // TODO: this is not correct - FBX calculates outer and inner angle in degrees
  1014. // with OuterAngle > InnerAngle && OuterAngle <= Math.PI
  1015. // while three.js uses a penumbra between (0, 1) to attenuate the inner angle
  1016. penumbra = THREE.Math.degToRad( lightAttribute.OuterAngle.value );
  1017. penumbra = Math.max( penumbra, 1 );
  1018. }
  1019. model = new THREE.SpotLight( color, intensity, distance, angle, penumbra, decay );
  1020. break;
  1021. default:
  1022. console.warn( 'THREE.FBXLoader: Unknown light type ' + lightAttribute.LightType.value + ', defaulting to a THREE.PointLight.' );
  1023. model = new THREE.PointLight( color, intensity );
  1024. break;
  1025. }
  1026. if ( lightAttribute.CastShadows !== undefined && lightAttribute.CastShadows.value === 1 ) {
  1027. model.castShadow = true;
  1028. }
  1029. }
  1030. break;
  1031. case 'Mesh':
  1032. var geometry = null;
  1033. var material = null;
  1034. var materials = [];
  1035. for ( var childrenIndex = 0, childrenLength = conns.children.length; childrenIndex < childrenLength; ++ childrenIndex ) {
  1036. var child = conns.children[ childrenIndex ];
  1037. if ( geometryMap.has( child.ID ) ) {
  1038. geometry = geometryMap.get( child.ID );
  1039. }
  1040. if ( materialMap.has( child.ID ) ) {
  1041. materials.push( materialMap.get( child.ID ) );
  1042. }
  1043. }
  1044. if ( materials.length > 1 ) {
  1045. material = materials;
  1046. } else if ( materials.length > 0 ) {
  1047. material = materials[ 0 ];
  1048. } else {
  1049. material = new THREE.MeshPhongMaterial( { color: 0xcccccc } );
  1050. materials.push( material );
  1051. }
  1052. if ( 'color' in geometry.attributes ) {
  1053. for ( var materialIndex = 0, numMaterials = materials.length; materialIndex < numMaterials; ++ materialIndex ) {
  1054. materials[ materialIndex ].vertexColors = THREE.VertexColors;
  1055. }
  1056. }
  1057. if ( geometry.FBX_Deformer ) {
  1058. for ( var materialsIndex = 0, materialsLength = materials.length; materialsIndex < materialsLength; ++ materialsIndex ) {
  1059. materials[ materialsIndex ].skinning = true;
  1060. }
  1061. model = new THREE.SkinnedMesh( geometry, material );
  1062. } else {
  1063. model = new THREE.Mesh( geometry, material );
  1064. }
  1065. break;
  1066. case 'NurbsCurve':
  1067. var geometry = null;
  1068. for ( var childrenIndex = 0, childrenLength = conns.children.length; childrenIndex < childrenLength; ++ childrenIndex ) {
  1069. var child = conns.children[ childrenIndex ];
  1070. if ( geometryMap.has( child.ID ) ) {
  1071. geometry = geometryMap.get( child.ID );
  1072. }
  1073. }
  1074. // FBX does not list materials for Nurbs lines, so we'll just put our own in here.
  1075. material = new THREE.LineBasicMaterial( { color: 0x3300ff, linewidth: 5 } );
  1076. model = new THREE.Line( geometry, material );
  1077. break;
  1078. default:
  1079. model = new THREE.Group();
  1080. break;
  1081. }
  1082. }
  1083. model.name = THREE.PropertyBinding.sanitizeNodeName( node.attrName );
  1084. model.FBX_ID = id;
  1085. modelArray.push( model );
  1086. modelMap.set( id, model );
  1087. }
  1088. for ( var modelArrayIndex = 0, modelArrayLength = modelArray.length; modelArrayIndex < modelArrayLength; ++ modelArrayIndex ) {
  1089. var model = modelArray[ modelArrayIndex ];
  1090. var node = ModelNode[ model.FBX_ID ];
  1091. if ( 'Lcl_Translation' in node.properties ) {
  1092. model.position.fromArray( node.properties.Lcl_Translation.value );
  1093. }
  1094. if ( 'Lcl_Rotation' in node.properties ) {
  1095. var rotation = node.properties.Lcl_Rotation.value.map( THREE.Math.degToRad );
  1096. rotation.push( 'ZYX' );
  1097. model.rotation.fromArray( rotation );
  1098. }
  1099. if ( 'Lcl_Scaling' in node.properties ) {
  1100. model.scale.fromArray( node.properties.Lcl_Scaling.value );
  1101. }
  1102. if ( 'PreRotation' in node.properties ) {
  1103. var preRotations = new THREE.Euler().fromArray( node.properties.PreRotation.value.map( THREE.Math.degToRad ), 'ZYX' );
  1104. preRotations = new THREE.Quaternion().setFromEuler( preRotations );
  1105. var currentRotation = new THREE.Quaternion().setFromEuler( model.rotation );
  1106. preRotations.multiply( currentRotation );
  1107. model.rotation.setFromQuaternion( preRotations, 'ZYX' );
  1108. }
  1109. // allow transformed pivots - see https://github.com/mrdoob/three.js/issues/11895
  1110. if ( 'GeometricTranslation' in node.properties ) {
  1111. var array = node.properties.GeometricTranslation.value;
  1112. model.traverse( function ( child ) {
  1113. if ( child.geometry ) {
  1114. child.geometry.translate( array[ 0 ], array[ 1 ], array[ 2 ] );
  1115. }
  1116. } );
  1117. }
  1118. if ( 'LookAtProperty' in node.properties ) {
  1119. var conns = connections.get( model.FBX_ID );
  1120. for ( var childrenIndex = 0, childrenLength = conns.children.length; childrenIndex < childrenLength; ++ childrenIndex ) {
  1121. var child = conns.children[ childrenIndex ];
  1122. if ( child.relationship === 'LookAtProperty' ) {
  1123. var lookAtTarget = FBXTree.Objects.subNodes.Model[ child.ID ];
  1124. if ( 'Lcl_Translation' in lookAtTarget.properties ) {
  1125. var pos = lookAtTarget.properties.Lcl_Translation.value;
  1126. // DirectionalLight, SpotLight
  1127. if ( model.target !== undefined ) {
  1128. model.target.position.set( pos[ 0 ], pos[ 1 ], pos[ 2 ] );
  1129. sceneGraph.add( model.target );
  1130. } else { // Cameras and other Object3Ds
  1131. model.lookAt( new THREE.Vector3( pos[ 0 ], pos[ 1 ], pos[ 2 ] ) );
  1132. }
  1133. }
  1134. }
  1135. }
  1136. }
  1137. var conns = connections.get( model.FBX_ID );
  1138. for ( var parentIndex = 0; parentIndex < conns.parents.length; parentIndex ++ ) {
  1139. var pIndex = findIndex( modelArray, function ( mod ) {
  1140. return mod.FBX_ID === conns.parents[ parentIndex ].ID;
  1141. } );
  1142. if ( pIndex > - 1 ) {
  1143. modelArray[ pIndex ].add( model );
  1144. break;
  1145. }
  1146. }
  1147. if ( model.parent === null ) {
  1148. sceneGraph.add( model );
  1149. }
  1150. }
  1151. // Now with the bones created, we can update the skeletons and bind them to the skinned meshes.
  1152. sceneGraph.updateMatrixWorld( true );
  1153. var worldMatrices = new Map();
  1154. // Put skeleton into bind pose.
  1155. if ( 'Pose' in FBXTree.Objects.subNodes ) {
  1156. var BindPoseNode = FBXTree.Objects.subNodes.Pose;
  1157. for ( var nodeID in BindPoseNode ) {
  1158. if ( BindPoseNode[ nodeID ].attrType === 'BindPose' ) {
  1159. BindPoseNode = BindPoseNode[ nodeID ];
  1160. break;
  1161. }
  1162. }
  1163. var PoseNode = BindPoseNode.subNodes.PoseNode;
  1164. for ( var PoseNodeIndex = 0, PoseNodeLength = PoseNode.length; PoseNodeIndex < PoseNodeLength; ++ PoseNodeIndex ) {
  1165. var node = PoseNode[ PoseNodeIndex ];
  1166. var rawMatWrd = new THREE.Matrix4().fromArray( node.subNodes.Matrix.properties.a );
  1167. worldMatrices.set( parseInt( node.id ), rawMatWrd );
  1168. }
  1169. }
  1170. for ( var FBX_ID in deformers ) {
  1171. var deformer = deformers[ FBX_ID ];
  1172. var subDeformers = deformer.map;
  1173. for ( var key in subDeformers ) {
  1174. var subDeformer = subDeformers[ key ];
  1175. var subDeformerIndex = subDeformer.index;
  1176. var bone = deformer.bones[ subDeformerIndex ];
  1177. if ( ! worldMatrices.has( bone.FBX_ID ) ) {
  1178. break;
  1179. }
  1180. var mat = worldMatrices.get( bone.FBX_ID );
  1181. bone.matrixWorld.copy( mat );
  1182. }
  1183. // Now that skeleton is in bind pose, bind to model.
  1184. deformer.skeleton = new THREE.Skeleton( deformer.bones );
  1185. var conns = connections.get( deformer.FBX_ID );
  1186. var parents = conns.parents;
  1187. for ( var parentsIndex = 0, parentsLength = parents.length; parentsIndex < parentsLength; ++ parentsIndex ) {
  1188. var parent = parents[ parentsIndex ];
  1189. if ( geometryMap.has( parent.ID ) ) {
  1190. var geoID = parent.ID;
  1191. var geoConns = connections.get( geoID );
  1192. for ( var i = 0; i < geoConns.parents.length; ++ i ) {
  1193. if ( modelMap.has( geoConns.parents[ i ].ID ) ) {
  1194. var model = modelMap.get( geoConns.parents[ i ].ID );
  1195. model.bind( deformer.skeleton, model.matrixWorld );
  1196. break;
  1197. }
  1198. }
  1199. }
  1200. }
  1201. }
  1202. //Skeleton is now bound, return objects to starting world positions.
  1203. sceneGraph.updateMatrixWorld( true );
  1204. // Silly hack with the animation parsing. We're gonna pretend the scene graph has a skeleton
  1205. // to attach animations to, since FBX treats animations as animations for the entire scene,
  1206. // not just for individual objects.
  1207. sceneGraph.skeleton = {
  1208. bones: modelArray
  1209. };
  1210. var animations = parseAnimations( FBXTree, connections, sceneGraph );
  1211. addAnimations( sceneGraph, animations );
  1212. // Parse ambient color - if it's not set to black (default), create an ambient light
  1213. if ( 'GlobalSettings' in FBXTree && 'AmbientColor' in FBXTree.GlobalSettings.properties ) {
  1214. var ambientColor = FBXTree.GlobalSettings.properties.AmbientColor.value;
  1215. var r = ambientColor[ 0 ];
  1216. var g = ambientColor[ 1 ];
  1217. var b = ambientColor[ 2 ];
  1218. if ( r !== 0 || g !== 0 || b !== 0 ) {
  1219. var color = new THREE.Color( r, g, b );
  1220. sceneGraph.add( new THREE.AmbientLight( color, 1 ) );
  1221. }
  1222. }
  1223. return sceneGraph;
  1224. }
  1225. // Parses animation information from nodes in
  1226. // FBXTree.Objects.subNodes.AnimationCurve ( connected to AnimationCurveNode )
  1227. // FBXTree.Objects.subNodes.AnimationCurveNode ( connected to AnimationLayer and an animated property in some other node )
  1228. // FBXTree.Objects.subNodes.AnimationLayer ( connected to AnimationStack )
  1229. // FBXTree.Objects.subNodes.AnimationStack
  1230. function parseAnimations( FBXTree, connections, sceneGraph ) {
  1231. var rawNodes = FBXTree.Objects.subNodes.AnimationCurveNode;
  1232. var rawCurves = FBXTree.Objects.subNodes.AnimationCurve;
  1233. var rawLayers = FBXTree.Objects.subNodes.AnimationLayer;
  1234. var rawStacks = FBXTree.Objects.subNodes.AnimationStack;
  1235. var fps = 30; // default framerate
  1236. if ( 'GlobalSettings' in FBXTree && 'TimeMode' in FBXTree.GlobalSettings.properties ) {
  1237. /* Autodesk time mode documentation can be found here:
  1238. * http://docs.autodesk.com/FBX/2014/ENU/FBX-SDK-Documentation/index.html?url=cpp_ref/class_fbx_time.html,topicNumber=cpp_ref_class_fbx_time_html
  1239. */
  1240. var timeModeEnum = [
  1241. 30, // 0: eDefaultMode
  1242. 120, // 1: eFrames120
  1243. 100, // 2: eFrames100
  1244. 60, // 3: eFrames60
  1245. 50, // 4: eFrames50
  1246. 48, // 5: eFrames48
  1247. 30, // 6: eFrames30 (black and white NTSC )
  1248. 30, // 7: eFrames30Drop
  1249. 29.97, // 8: eNTSCDropFrame
  1250. 29.97, // 90: eNTSCFullFrame
  1251. 25, // 10: ePal ( PAL/SECAM )
  1252. 24, // 11: eFrames24 (Film/Cinema)
  1253. 1, // 12: eFrames1000 (use for date time))
  1254. 23.976, // 13: eFilmFullFrame
  1255. 30, // 14: eCustom: use GlobalSettings.properties.CustomFrameRate.value
  1256. 96, // 15: eFrames96
  1257. 72, // 16: eFrames72
  1258. 59.94, // 17: eFrames59dot94
  1259. ];
  1260. var eMode = FBXTree.GlobalSettings.properties.TimeMode.value;
  1261. if ( eMode === 14 ) {
  1262. if ( 'CustomFrameRate' in FBXTree.GlobalSettings.properties ) {
  1263. fps = FBXTree.GlobalSettings.properties.CustomFrameRate.value;
  1264. fps = ( fps === - 1 ) ? 30 : fps;
  1265. }
  1266. } else if ( eMode <= 17 ) { // for future proofing - if more eModes get added, they will default to 30fps
  1267. fps = timeModeEnum[ eMode ];
  1268. }
  1269. }
  1270. /**
  1271. * @type {{
  1272. curves: Map<number, {
  1273. T: {
  1274. id: number;
  1275. attr: string;
  1276. internalID: number;
  1277. attrX: boolean;
  1278. attrY: boolean;
  1279. attrZ: boolean;
  1280. containerBoneID: number;
  1281. containerID: number;
  1282. curves: {
  1283. x: {
  1284. version: any;
  1285. id: number;
  1286. internalID: number;
  1287. times: number[];
  1288. values: number[];
  1289. attrFlag: number[];
  1290. attrData: number[];
  1291. };
  1292. y: {
  1293. version: any;
  1294. id: number;
  1295. internalID: number;
  1296. times: number[];
  1297. values: number[];
  1298. attrFlag: number[];
  1299. attrData: number[];
  1300. };
  1301. z: {
  1302. version: any;
  1303. id: number;
  1304. internalID: number;
  1305. times: number[];
  1306. values: number[];
  1307. attrFlag: number[];
  1308. attrData: number[];
  1309. };
  1310. };
  1311. },
  1312. R: {
  1313. id: number;
  1314. attr: string;
  1315. internalID: number;
  1316. attrX: boolean;
  1317. attrY: boolean;
  1318. attrZ: boolean;
  1319. containerBoneID: number;
  1320. containerID: number;
  1321. curves: {
  1322. x: {
  1323. version: any;
  1324. id: number;
  1325. internalID: number;
  1326. times: number[];
  1327. values: number[];
  1328. attrFlag: number[];
  1329. attrData: number[];
  1330. };
  1331. y: {
  1332. version: any;
  1333. id: number;
  1334. internalID: number;
  1335. times: number[];
  1336. values: number[];
  1337. attrFlag: number[];
  1338. attrData: number[];
  1339. };
  1340. z: {
  1341. version: any;
  1342. id: number;
  1343. internalID: number;
  1344. times: number[];
  1345. values: number[];
  1346. attrFlag: number[];
  1347. attrData: number[];
  1348. };
  1349. };
  1350. },
  1351. S: {
  1352. id: number;
  1353. attr: string;
  1354. internalID: number;
  1355. attrX: boolean;
  1356. attrY: boolean;
  1357. attrZ: boolean;
  1358. containerBoneID: number;
  1359. containerID: number;
  1360. curves: {
  1361. x: {
  1362. version: any;
  1363. id: number;
  1364. internalID: number;
  1365. times: number[];
  1366. values: number[];
  1367. attrFlag: number[];
  1368. attrData: number[];
  1369. };
  1370. y: {
  1371. version: any;
  1372. id: number;
  1373. internalID: number;
  1374. times: number[];
  1375. values: number[];
  1376. attrFlag: number[];
  1377. attrData: number[];
  1378. };
  1379. z: {
  1380. version: any;
  1381. id: number;
  1382. internalID: number;
  1383. times: number[];
  1384. values: number[];
  1385. attrFlag: number[];
  1386. attrData: number[];
  1387. };
  1388. };
  1389. }
  1390. }>,
  1391. layers: Map<number, {
  1392. T: {
  1393. id: number;
  1394. attr: string;
  1395. internalID: number;
  1396. attrX: boolean;
  1397. attrY: boolean;
  1398. attrZ: boolean;
  1399. containerBoneID: number;
  1400. containerID: number;
  1401. curves: {
  1402. x: {
  1403. version: any;
  1404. id: number;
  1405. internalID: number;
  1406. times: number[];
  1407. values: number[];
  1408. attrFlag: number[];
  1409. attrData: number[];
  1410. };
  1411. y: {
  1412. version: any;
  1413. id: number;
  1414. internalID: number;
  1415. times: number[];
  1416. values: number[];
  1417. attrFlag: number[];
  1418. attrData: number[];
  1419. };
  1420. z: {
  1421. version: any;
  1422. id: number;
  1423. internalID: number;
  1424. times: number[];
  1425. values: number[];
  1426. attrFlag: number[];
  1427. attrData: number[];
  1428. };
  1429. },
  1430. },
  1431. R: {
  1432. id: number;
  1433. attr: string;
  1434. internalID: number;
  1435. attrX: boolean;
  1436. attrY: boolean;
  1437. attrZ: boolean;
  1438. containerBoneID: number;
  1439. containerID: number;
  1440. curves: {
  1441. x: {
  1442. version: any;
  1443. id: number;
  1444. internalID: number;
  1445. times: number[];
  1446. values: number[];
  1447. attrFlag: number[];
  1448. attrData: number[];
  1449. };
  1450. y: {
  1451. version: any;
  1452. id: number;
  1453. internalID: number;
  1454. times: number[];
  1455. values: number[];
  1456. attrFlag: number[];
  1457. attrData: number[];
  1458. };
  1459. z: {
  1460. version: any;
  1461. id: number;
  1462. internalID: number;
  1463. times: number[];
  1464. values: number[];
  1465. attrFlag: number[];
  1466. attrData: number[];
  1467. };
  1468. },
  1469. },
  1470. S: {
  1471. id: number;
  1472. attr: string;
  1473. internalID: number;
  1474. attrX: boolean;
  1475. attrY: boolean;
  1476. attrZ: boolean;
  1477. containerBoneID: number;
  1478. containerID: number;
  1479. curves: {
  1480. x: {
  1481. version: any;
  1482. id: number;
  1483. internalID: number;
  1484. times: number[];
  1485. values: number[];
  1486. attrFlag: number[];
  1487. attrData: number[];
  1488. };
  1489. y: {
  1490. version: any;
  1491. id: number;
  1492. internalID: number;
  1493. times: number[];
  1494. values: number[];
  1495. attrFlag: number[];
  1496. attrData: number[];
  1497. };
  1498. z: {
  1499. version: any;
  1500. id: number;
  1501. internalID: number;
  1502. times: number[];
  1503. values: number[];
  1504. attrFlag: number[];
  1505. attrData: number[];
  1506. };
  1507. },
  1508. }
  1509. }[]>,
  1510. stacks: Map<number, {
  1511. name: string,
  1512. layers: {
  1513. T: {
  1514. id: number;
  1515. attr: string;
  1516. internalID: number;
  1517. attrX: boolean;
  1518. attrY: boolean;
  1519. attrZ: boolean;
  1520. containerBoneID: number;
  1521. containerID: number;
  1522. curves: {
  1523. x: {
  1524. version: any;
  1525. id: number;
  1526. internalID: number;
  1527. times: number[];
  1528. values: number[];
  1529. attrFlag: number[];
  1530. attrData: number[];
  1531. };
  1532. y: {
  1533. version: any;
  1534. id: number;
  1535. internalID: number;
  1536. times: number[];
  1537. values: number[];
  1538. attrFlag: number[];
  1539. attrData: number[];
  1540. };
  1541. z: {
  1542. version: any;
  1543. id: number;
  1544. internalID: number;
  1545. times: number[];
  1546. values: number[];
  1547. attrFlag: number[];
  1548. attrData: number[];
  1549. };
  1550. };
  1551. };
  1552. R: {
  1553. id: number;
  1554. attr: string;
  1555. internalID: number;
  1556. attrX: boolean;
  1557. attrY: boolean;
  1558. attrZ: boolean;
  1559. containerBoneID: number;
  1560. containerID: number;
  1561. curves: {
  1562. x: {
  1563. version: any;
  1564. id: number;
  1565. internalID: number;
  1566. times: number[];
  1567. values: number[];
  1568. attrFlag: number[];
  1569. attrData: number[];
  1570. };
  1571. y: {
  1572. version: any;
  1573. id: number;
  1574. internalID: number;
  1575. times: number[];
  1576. values: number[];
  1577. attrFlag: number[];
  1578. attrData: number[];
  1579. };
  1580. z: {
  1581. version: any;
  1582. id: number;
  1583. internalID: number;
  1584. times: number[];
  1585. values: number[];
  1586. attrFlag: number[];
  1587. attrData: number[];
  1588. };
  1589. };
  1590. };
  1591. S: {
  1592. id: number;
  1593. attr: string;
  1594. internalID: number;
  1595. attrX: boolean;
  1596. attrY: boolean;
  1597. attrZ: boolean;
  1598. containerBoneID: number;
  1599. containerID: number;
  1600. curves: {
  1601. x: {
  1602. version: any;
  1603. id: number;
  1604. internalID: number;
  1605. times: number[];
  1606. values: number[];
  1607. attrFlag: number[];
  1608. attrData: number[];
  1609. };
  1610. y: {
  1611. version: any;
  1612. id: number;
  1613. internalID: number;
  1614. times: number[];
  1615. values: number[];
  1616. attrFlag: number[];
  1617. attrData: number[];
  1618. };
  1619. z: {
  1620. version: any;
  1621. id: number;
  1622. internalID: number;
  1623. times: number[];
  1624. values: number[];
  1625. attrFlag: number[];
  1626. attrData: number[];
  1627. };
  1628. };
  1629. };
  1630. }[][],
  1631. length: number,
  1632. frames: number }>,
  1633. length: number,
  1634. fps: number,
  1635. frames: number
  1636. }}
  1637. */
  1638. var returnObject = {
  1639. curves: new Map(),
  1640. layers: {},
  1641. stacks: {},
  1642. length: 0,
  1643. fps: fps,
  1644. frames: 0
  1645. };
  1646. var animationCurveNodes = [];
  1647. for ( var nodeID in rawNodes ) {
  1648. if ( nodeID.match( /\d+/ ) ) {
  1649. var animationNode = parseAnimationNode( FBXTree, rawNodes[ nodeID ], connections, sceneGraph );
  1650. animationCurveNodes.push( animationNode );
  1651. }
  1652. }
  1653. var tmpMap = new Map();
  1654. for ( var animationCurveNodeIndex = 0; animationCurveNodeIndex < animationCurveNodes.length; ++ animationCurveNodeIndex ) {
  1655. if ( animationCurveNodes[ animationCurveNodeIndex ] === null ) {
  1656. continue;
  1657. }
  1658. tmpMap.set( animationCurveNodes[ animationCurveNodeIndex ].id, animationCurveNodes[ animationCurveNodeIndex ] );
  1659. }
  1660. var animationCurves = [];
  1661. for ( nodeID in rawCurves ) {
  1662. if ( nodeID.match( /\d+/ ) ) {
  1663. var animationCurve = parseAnimationCurve( rawCurves[ nodeID ] );
  1664. // seems like this check would be necessary?
  1665. if ( ! connections.has( animationCurve.id ) ) continue;
  1666. animationCurves.push( animationCurve );
  1667. var firstParentConn = connections.get( animationCurve.id ).parents[ 0 ];
  1668. var firstParentID = firstParentConn.ID;
  1669. var firstParentRelationship = firstParentConn.relationship;
  1670. var axis = '';
  1671. if ( firstParentRelationship.match( /X/ ) ) {
  1672. axis = 'x';
  1673. } else if ( firstParentRelationship.match( /Y/ ) ) {
  1674. axis = 'y';
  1675. } else if ( firstParentRelationship.match( /Z/ ) ) {
  1676. axis = 'z';
  1677. } else {
  1678. continue;
  1679. }
  1680. tmpMap.get( firstParentID ).curves[ axis ] = animationCurve;
  1681. }
  1682. }
  1683. tmpMap.forEach( function ( curveNode ) {
  1684. var id = curveNode.containerBoneID;
  1685. if ( ! returnObject.curves.has( id ) ) {
  1686. returnObject.curves.set( id, { T: null, R: null, S: null } );
  1687. }
  1688. returnObject.curves.get( id )[ curveNode.attr ] = curveNode;
  1689. if ( curveNode.attr === 'R' ) {
  1690. var curves = curveNode.curves;
  1691. // Some FBX files have an AnimationCurveNode
  1692. // which isn't any connected to any AnimationCurve.
  1693. // Setting animation parameter for them here.
  1694. if ( curves.x === null ) {
  1695. curves.x = {
  1696. version: null,
  1697. times: [ 0.0 ],
  1698. values: [ 0.0 ]
  1699. };
  1700. }
  1701. if ( curves.y === null ) {
  1702. curves.y = {
  1703. version: null,
  1704. times: [ 0.0 ],
  1705. values: [ 0.0 ]
  1706. };
  1707. }
  1708. if ( curves.z === null ) {
  1709. curves.z = {
  1710. version: null,
  1711. times: [ 0.0 ],
  1712. values: [ 0.0 ]
  1713. };
  1714. }
  1715. curves.x.values = curves.x.values.map( THREE.Math.degToRad );
  1716. curves.y.values = curves.y.values.map( THREE.Math.degToRad );
  1717. curves.z.values = curves.z.values.map( THREE.Math.degToRad );
  1718. if ( curveNode.preRotations !== null ) {
  1719. var preRotations = new THREE.Euler().setFromVector3( curveNode.preRotations, 'ZYX' );
  1720. preRotations = new THREE.Quaternion().setFromEuler( preRotations );
  1721. var frameRotation = new THREE.Euler();
  1722. var frameRotationQuaternion = new THREE.Quaternion();
  1723. for ( var frame = 0; frame < curves.x.times.length; ++ frame ) {
  1724. frameRotation.set( curves.x.values[ frame ], curves.y.values[ frame ], curves.z.values[ frame ], 'ZYX' );
  1725. frameRotationQuaternion.setFromEuler( frameRotation ).premultiply( preRotations );
  1726. frameRotation.setFromQuaternion( frameRotationQuaternion, 'ZYX' );
  1727. curves.x.values[ frame ] = frameRotation.x;
  1728. curves.y.values[ frame ] = frameRotation.y;
  1729. curves.z.values[ frame ] = frameRotation.z;
  1730. }
  1731. }
  1732. }
  1733. } );
  1734. for ( var nodeID in rawLayers ) {
  1735. var layer = [];
  1736. var children = connections.get( parseInt( nodeID ) ).children;
  1737. for ( var childIndex = 0; childIndex < children.length; childIndex ++ ) {
  1738. // Skip lockInfluenceWeights
  1739. if ( tmpMap.has( children[ childIndex ].ID ) ) {
  1740. var curveNode = tmpMap.get( children[ childIndex ].ID );
  1741. var boneID = curveNode.containerBoneID;
  1742. if ( layer[ boneID ] === undefined ) {
  1743. layer[ boneID ] = {
  1744. T: null,
  1745. R: null,
  1746. S: null
  1747. };
  1748. }
  1749. layer[ boneID ][ curveNode.attr ] = curveNode;
  1750. }
  1751. }
  1752. returnObject.layers[ nodeID ] = layer;
  1753. }
  1754. for ( var nodeID in rawStacks ) {
  1755. var layers = [];
  1756. var children = connections.get( parseInt( nodeID ) ).children;
  1757. var timestamps = { max: 0, min: Number.MAX_VALUE };
  1758. for ( var childIndex = 0; childIndex < children.length; ++ childIndex ) {
  1759. var currentLayer = returnObject.layers[ children[ childIndex ].ID ];
  1760. if ( currentLayer !== undefined ) {
  1761. layers.push( currentLayer );
  1762. for ( var currentLayerIndex = 0, currentLayerLength = currentLayer.length; currentLayerIndex < currentLayerLength; ++ currentLayerIndex ) {
  1763. var layer = currentLayer[ currentLayerIndex ];
  1764. if ( layer ) {
  1765. getCurveNodeMaxMinTimeStamps( layer, timestamps );
  1766. }
  1767. }
  1768. }
  1769. }
  1770. // Do we have an animation clip with actual length?
  1771. if ( timestamps.max > timestamps.min ) {
  1772. returnObject.stacks[ nodeID ] = {
  1773. name: rawStacks[ nodeID ].attrName,
  1774. layers: layers,
  1775. length: timestamps.max - timestamps.min,
  1776. frames: ( timestamps.max - timestamps.min ) * returnObject.fps
  1777. };
  1778. }
  1779. }
  1780. return returnObject;
  1781. }
  1782. function parseAnimationNode( FBXTree, animationCurveNode, connections, sceneGraph ) {
  1783. var rawModels = FBXTree.Objects.subNodes.Model;
  1784. var returnObject = {
  1785. id: animationCurveNode.id,
  1786. attr: animationCurveNode.attrName,
  1787. internalID: animationCurveNode.id,
  1788. attrX: false,
  1789. attrY: false,
  1790. attrZ: false,
  1791. containerBoneID: - 1,
  1792. containerID: - 1,
  1793. curves: {
  1794. x: null,
  1795. y: null,
  1796. z: null
  1797. },
  1798. preRotations: null
  1799. };
  1800. if ( returnObject.attr.match( /S|R|T/ ) ) {
  1801. for ( var attributeKey in animationCurveNode.properties ) {
  1802. if ( attributeKey.match( /X/ ) ) {
  1803. returnObject.attrX = true;
  1804. }
  1805. if ( attributeKey.match( /Y/ ) ) {
  1806. returnObject.attrY = true;
  1807. }
  1808. if ( attributeKey.match( /Z/ ) ) {
  1809. returnObject.attrZ = true;
  1810. }
  1811. }
  1812. } else {
  1813. return null;
  1814. }
  1815. var conns = connections.get( returnObject.id );
  1816. var containerIndices = conns.parents;
  1817. for ( var containerIndicesIndex = containerIndices.length - 1; containerIndicesIndex >= 0; -- containerIndicesIndex ) {
  1818. var boneID = findIndex( sceneGraph.skeleton.bones, function ( bone ) {
  1819. return bone.FBX_ID === containerIndices[ containerIndicesIndex ].ID;
  1820. } );
  1821. if ( boneID > - 1 ) {
  1822. returnObject.containerBoneID = boneID;
  1823. returnObject.containerID = containerIndices[ containerIndicesIndex ].ID;
  1824. var model = rawModels[ returnObject.containerID.toString() ];
  1825. if ( 'PreRotation' in model.properties ) {
  1826. returnObject.preRotations = parseVector3( model.properties.PreRotation ).multiplyScalar( Math.PI / 180 );
  1827. }
  1828. break;
  1829. }
  1830. }
  1831. return returnObject;
  1832. }
  1833. function parseAnimationCurve( animationCurve ) {
  1834. return {
  1835. version: null,
  1836. id: animationCurve.id,
  1837. internalID: animationCurve.id,
  1838. times: animationCurve.subNodes.KeyTime.properties.a.map( convertFBXTimeToSeconds ),
  1839. values: animationCurve.subNodes.KeyValueFloat.properties.a,
  1840. attrFlag: animationCurve.subNodes.KeyAttrFlags.properties.a,
  1841. attrData: animationCurve.subNodes.KeyAttrDataFloat.properties.a,
  1842. };
  1843. }
  1844. // Sets the maxTimeStamp and minTimeStamp variables if it has timeStamps that are either larger or smaller
  1845. // than the max or min respectively.
  1846. function getCurveNodeMaxMinTimeStamps( layer, timestamps ) {
  1847. if ( layer.R ) {
  1848. getCurveMaxMinTimeStamp( layer.R.curves, timestamps );
  1849. }
  1850. if ( layer.S ) {
  1851. getCurveMaxMinTimeStamp( layer.S.curves, timestamps );
  1852. }
  1853. if ( layer.T ) {
  1854. getCurveMaxMinTimeStamp( layer.T.curves, timestamps );
  1855. }
  1856. }
  1857. // Sets the maxTimeStamp and minTimeStamp if one of the curve's time stamps
  1858. // exceeds the maximum or minimum.
  1859. function getCurveMaxMinTimeStamp( curve, timestamps ) {
  1860. if ( curve.x ) {
  1861. getCurveAxisMaxMinTimeStamps( curve.x, timestamps );
  1862. }
  1863. if ( curve.y ) {
  1864. getCurveAxisMaxMinTimeStamps( curve.y, timestamps );
  1865. }
  1866. if ( curve.z ) {
  1867. getCurveAxisMaxMinTimeStamps( curve.z, timestamps );
  1868. }
  1869. }
  1870. // Sets the maxTimeStamp and minTimeStamp if one of its timestamps exceeds the maximum or minimum.
  1871. function getCurveAxisMaxMinTimeStamps( axis, timestamps ) {
  1872. timestamps.max = axis.times[ axis.times.length - 1 ] > timestamps.max ? axis.times[ axis.times.length - 1 ] : timestamps.max;
  1873. timestamps.min = axis.times[ 0 ] < timestamps.min ? axis.times[ 0 ] : timestamps.min;
  1874. }
  1875. function addAnimations( group, animations ) {
  1876. if ( group.animations === undefined ) {
  1877. group.animations = [];
  1878. }
  1879. var stacks = animations.stacks;
  1880. for ( var key in stacks ) {
  1881. var stack = stacks[ key ];
  1882. var animationData = {
  1883. name: stack.name,
  1884. fps: animations.fps,
  1885. length: stack.length,
  1886. hierarchy: []
  1887. };
  1888. var bones = group.skeleton.bones;
  1889. for ( var bonesIndex = 0, bonesLength = bones.length; bonesIndex < bonesLength; ++ bonesIndex ) {
  1890. var bone = bones[ bonesIndex ];
  1891. var name = bone.name.replace( /.*:/, '' );
  1892. var parentIndex = findIndex( bones, function ( parentBone ) {
  1893. return bone.parent === parentBone;
  1894. } );
  1895. animationData.hierarchy.push( { parent: parentIndex, name: name, keys: [] } );
  1896. }
  1897. for ( var frame = 0; frame <= stack.frames; frame ++ ) {
  1898. for ( var bonesIndex = 0, bonesLength = bones.length; bonesIndex < bonesLength; ++ bonesIndex ) {
  1899. var bone = bones[ bonesIndex ];
  1900. var boneIndex = bonesIndex;
  1901. var animationNode = stack.layers[ 0 ][ boneIndex ];
  1902. for ( var hierarchyIndex = 0, hierarchyLength = animationData.hierarchy.length; hierarchyIndex < hierarchyLength; ++ hierarchyIndex ) {
  1903. var node = animationData.hierarchy[ hierarchyIndex ];
  1904. if ( node.name === bone.name ) {
  1905. node.keys.push( generateKey( animations, animationNode, bone, frame ) );
  1906. }
  1907. }
  1908. }
  1909. }
  1910. group.animations.push( THREE.AnimationClip.parseAnimation( animationData, bones ) );
  1911. }
  1912. }
  1913. var euler = new THREE.Euler();
  1914. var quaternion = new THREE.Quaternion();
  1915. function generateKey( animations, animationNode, bone, frame ) {
  1916. var key = {
  1917. time: frame / animations.fps,
  1918. pos: bone.position.toArray(),
  1919. rot: bone.quaternion.toArray(),
  1920. scl: bone.scale.toArray()
  1921. };
  1922. if ( animationNode === undefined ) return key;
  1923. euler.setFromQuaternion( bone.quaternion, 'ZYX', false );
  1924. try {
  1925. if ( hasCurve( animationNode, 'T' ) && hasKeyOnFrame( animationNode.T, frame ) ) {
  1926. if ( animationNode.T.curves.x.values[ frame ] ) {
  1927. key.pos[ 0 ] = animationNode.T.curves.x.values[ frame ];
  1928. }
  1929. if ( animationNode.T.curves.y.values[ frame ] ) {
  1930. key.pos[ 1 ] = animationNode.T.curves.y.values[ frame ];
  1931. }
  1932. if ( animationNode.T.curves.z.values[ frame ] ) {
  1933. key.pos[ 2 ] = animationNode.T.curves.z.values[ frame ];
  1934. }
  1935. }
  1936. if ( hasCurve( animationNode, 'R' ) && hasKeyOnFrame( animationNode.R, frame ) ) {
  1937. // Only update the euler's values if rotation is defined for the axis on this frame
  1938. if ( animationNode.R.curves.x.values[ frame ] ) {
  1939. euler.x = animationNode.R.curves.x.values[ frame ];
  1940. }
  1941. if ( animationNode.R.curves.y.values[ frame ] ) {
  1942. euler.y = animationNode.R.curves.y.values[ frame ];
  1943. }
  1944. if ( animationNode.R.curves.z.values[ frame ] ) {
  1945. euler.z = animationNode.R.curves.z.values[ frame ];
  1946. }
  1947. quaternion.setFromEuler( euler );
  1948. key.rot = quaternion.toArray();
  1949. }
  1950. if ( hasCurve( animationNode, 'S' ) && hasKeyOnFrame( animationNode.S, frame ) ) {
  1951. if ( animationNode.T.curves.x.values[ frame ] ) {
  1952. key.scl[ 0 ] = animationNode.S.curves.x.values[ frame ];
  1953. }
  1954. if ( animationNode.T.curves.y.values[ frame ] ) {
  1955. key.scl[ 1 ] = animationNode.S.curves.y.values[ frame ];
  1956. }
  1957. if ( animationNode.T.curves.z.values[ frame ] ) {
  1958. key.scl[ 2 ] = animationNode.S.curves.z.values[ frame ];
  1959. }
  1960. }
  1961. } catch ( error ) {
  1962. // Curve is not fully plotted.
  1963. console.log( 'THREE.FBXLoader: ', bone );
  1964. console.log( 'THREE.FBXLoader: ', error );
  1965. }
  1966. return key;
  1967. }
  1968. var AXES = [ 'x', 'y', 'z' ];
  1969. function hasCurve( animationNode, attribute ) {
  1970. if ( animationNode === undefined ) {
  1971. return false;
  1972. }
  1973. var attributeNode = animationNode[ attribute ];
  1974. if ( ! attributeNode ) {
  1975. return false;
  1976. }
  1977. return AXES.every( function ( key ) {
  1978. return attributeNode.curves[ key ] !== null;
  1979. } );
  1980. }
  1981. function hasKeyOnFrame( attributeNode, frame ) {
  1982. return AXES.every( function ( key ) {
  1983. return isKeyExistOnFrame( attributeNode.curves[ key ], frame );
  1984. } );
  1985. }
  1986. function isKeyExistOnFrame( curve, frame ) {
  1987. return curve.values[ frame ] !== undefined;
  1988. }
  1989. // parse an FBX file in ASCII format
  1990. function TextParser() {}
  1991. Object.assign( TextParser.prototype, {
  1992. getPrevNode: function () {
  1993. return this.nodeStack[ this.currentIndent - 2 ];
  1994. },
  1995. getCurrentNode: function () {
  1996. return this.nodeStack[ this.currentIndent - 1 ];
  1997. },
  1998. getCurrentProp: function () {
  1999. return this.currentProp;
  2000. },
  2001. pushStack: function ( node ) {
  2002. this.nodeStack.push( node );
  2003. this.currentIndent += 1;
  2004. },
  2005. popStack: function () {
  2006. this.nodeStack.pop();
  2007. this.currentIndent -= 1;
  2008. },
  2009. setCurrentProp: function ( val, name ) {
  2010. this.currentProp = val;
  2011. this.currentPropName = name;
  2012. },
  2013. parse: function ( text ) {
  2014. this.currentIndent = 0;
  2015. this.allNodes = new FBXTree();
  2016. this.nodeStack = [];
  2017. this.currentProp = [];
  2018. this.currentPropName = '';
  2019. var split = text.split( '\n' );
  2020. for ( var lineNum = 0, lineLength = split.length; lineNum < lineLength; lineNum ++ ) {
  2021. var l = split[ lineNum ];
  2022. // skip comment line
  2023. if ( l.match( /^[\s\t]*;/ ) ) {
  2024. continue;
  2025. }
  2026. // skip empty line
  2027. if ( l.match( /^[\s\t]*$/ ) ) {
  2028. continue;
  2029. }
  2030. // beginning of node
  2031. var beginningOfNodeExp = new RegExp( '^\\t{' + this.currentIndent + '}(\\w+):(.*){', '' );
  2032. var match = l.match( beginningOfNodeExp );
  2033. if ( match ) {
  2034. var nodeName = match[ 1 ].trim().replace( /^"/, '' ).replace( /"$/, '' );
  2035. var nodeAttrs = match[ 2 ].split( ',' );
  2036. for ( var i = 0, l = nodeAttrs.length; i < l; i ++ ) {
  2037. nodeAttrs[ i ] = nodeAttrs[ i ].trim().replace( /^"/, '' ).replace( /"$/, '' );
  2038. }
  2039. this.parseNodeBegin( l, nodeName, nodeAttrs || null );
  2040. continue;
  2041. }
  2042. // node's property
  2043. var propExp = new RegExp( '^\\t{' + ( this.currentIndent ) + '}(\\w+):[\\s\\t\\r\\n](.*)' );
  2044. var match = l.match( propExp );
  2045. if ( match ) {
  2046. var propName = match[ 1 ].replace( /^"/, '' ).replace( /"$/, '' ).trim();
  2047. var propValue = match[ 2 ].replace( /^"/, '' ).replace( /"$/, '' ).trim();
  2048. // for special case: base64 image data follows "Content: ," line
  2049. // Content: ,
  2050. // "iVB..."
  2051. if ( propName === 'Content' && propValue === ',' ) {
  2052. propValue = split[ ++ lineNum ].replace( /"/g, '' ).replace( /,$/, '' ).trim();
  2053. }
  2054. this.parseNodeProperty( l, propName, propValue );
  2055. continue;
  2056. }
  2057. // end of node
  2058. var endOfNodeExp = new RegExp( '^\\t{' + ( this.currentIndent - 1 ) + '}}' );
  2059. if ( l.match( endOfNodeExp ) ) {
  2060. this.nodeEnd();
  2061. continue;
  2062. }
  2063. // large arrays are split over multiple lines terminated with a ',' character
  2064. // if this is encountered the line needs to be joined to the previous line
  2065. if ( l.match( /^[^\s\t}]/ ) ) {
  2066. this.parseNodePropertyContinued( l );
  2067. }
  2068. }
  2069. return this.allNodes;
  2070. },
  2071. parseNodeBegin: function ( line, nodeName, nodeAttrs ) {
  2072. var node = { 'name': nodeName, properties: {}, 'subNodes': {} };
  2073. var attrs = this.parseNodeAttr( nodeAttrs );
  2074. var currentNode = this.getCurrentNode();
  2075. // a top node
  2076. if ( this.currentIndent === 0 ) {
  2077. this.allNodes.add( nodeName, node );
  2078. } else { // a subnode
  2079. // if the subnode already exists, append it
  2080. if ( nodeName in currentNode.subNodes ) {
  2081. var tmp = currentNode.subNodes[ nodeName ];
  2082. if ( this.isFlattenNode( currentNode.subNodes[ nodeName ] ) ) {
  2083. if ( attrs.id === '' ) {
  2084. currentNode.subNodes[ nodeName ] = [];
  2085. currentNode.subNodes[ nodeName ].push( tmp );
  2086. } else {
  2087. currentNode.subNodes[ nodeName ] = {};
  2088. currentNode.subNodes[ nodeName ][ tmp.id ] = tmp;
  2089. }
  2090. }
  2091. if ( attrs.id === '' ) {
  2092. currentNode.subNodes[ nodeName ].push( node );
  2093. } else {
  2094. currentNode.subNodes[ nodeName ][ attrs.id ] = node;
  2095. }
  2096. } else if ( typeof attrs.id === 'number' || attrs.id.match( /^\d+$/ ) ) {
  2097. currentNode.subNodes[ nodeName ] = {};
  2098. currentNode.subNodes[ nodeName ][ attrs.id ] = node;
  2099. } else {
  2100. currentNode.subNodes[ nodeName ] = node;
  2101. }
  2102. }
  2103. // for this ↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓
  2104. // NodeAttribute: 1001463072, "NodeAttribute::", "LimbNode" {
  2105. if ( nodeAttrs ) {
  2106. node.id = attrs.id;
  2107. node.attrName = attrs.name;
  2108. node.attrType = attrs.type;
  2109. }
  2110. this.pushStack( node );
  2111. },
  2112. parseNodeAttr: function ( attrs ) {
  2113. var id = attrs[ 0 ];
  2114. if ( attrs[ 0 ] !== '' ) {
  2115. id = parseInt( attrs[ 0 ] );
  2116. if ( isNaN( id ) ) {
  2117. id = attrs[ 0 ];
  2118. }
  2119. }
  2120. var name = '', type = '';
  2121. if ( attrs.length > 1 ) {
  2122. name = attrs[ 1 ].replace( /^(\w+)::/, '' );
  2123. type = attrs[ 2 ];
  2124. }
  2125. return { id: id, name: name, type: type };
  2126. },
  2127. parseNodeProperty: function ( line, propName, propValue ) {
  2128. var currentNode = this.getCurrentNode();
  2129. var parentName = currentNode.name;
  2130. // special case where the parent node is something like "Properties70"
  2131. // these children nodes must treated carefully
  2132. if ( parentName !== undefined ) {
  2133. var propMatch = parentName.match( /Properties(\d)+/ );
  2134. if ( propMatch ) {
  2135. this.parseNodeSpecialProperty( line, propName, propValue );
  2136. return;
  2137. }
  2138. }
  2139. // Connections
  2140. if ( propName === 'C' ) {
  2141. var connProps = propValue.split( ',' ).slice( 1 );
  2142. var from = parseInt( connProps[ 0 ] );
  2143. var to = parseInt( connProps[ 1 ] );
  2144. var rest = propValue.split( ',' ).slice( 3 );
  2145. rest = rest.map( function ( elem ) {
  2146. return elem.trim().replace( /^"/, '' );
  2147. } );
  2148. propName = 'connections';
  2149. propValue = [ from, to ];
  2150. append( propValue, rest );
  2151. if ( currentNode.properties[ propName ] === undefined ) {
  2152. currentNode.properties[ propName ] = [];
  2153. }
  2154. }
  2155. // Node
  2156. if ( propName === 'Node' ) {
  2157. var id = parseInt( propValue );
  2158. currentNode.properties.id = id;
  2159. currentNode.id = id;
  2160. }
  2161. // already exists in properties, then append this
  2162. if ( propName in currentNode.properties ) {
  2163. if ( Array.isArray( currentNode.properties[ propName ] ) ) {
  2164. currentNode.properties[ propName ].push( propValue );
  2165. } else {
  2166. currentNode.properties[ propName ] += propValue;
  2167. }
  2168. } else {
  2169. if ( Array.isArray( currentNode.properties[ propName ] ) ) {
  2170. currentNode.properties[ propName ].push( propValue );
  2171. } else {
  2172. currentNode.properties[ propName ] = propValue;
  2173. }
  2174. }
  2175. this.setCurrentProp( currentNode.properties, propName );
  2176. // convert string to array, unless it ends in ',' in which case more will be added to it
  2177. if ( propName === 'a' && propValue.slice( - 1 ) !== ',' ) {
  2178. currentNode.properties.a = parseNumberArray( propValue );
  2179. }
  2180. },
  2181. parseNodePropertyContinued: function ( line ) {
  2182. this.currentProp[ this.currentPropName ] += line;
  2183. // if the line doesn't end in ',' we have reached the end of the property value
  2184. // so convert the string to an array
  2185. if ( line.slice( - 1 ) !== ',' ) {
  2186. var currentNode = this.getCurrentNode();
  2187. currentNode.properties.a = parseNumberArray( currentNode.properties.a );
  2188. }
  2189. },
  2190. parseNodeSpecialProperty: function ( line, propName, propValue ) {
  2191. // split this
  2192. // P: "Lcl Scaling", "Lcl Scaling", "", "A",1,1,1
  2193. // into array like below
  2194. // ["Lcl Scaling", "Lcl Scaling", "", "A", "1,1,1" ]
  2195. var props = propValue.split( '",' );
  2196. for ( var i = 0, l = props.length; i < l; i ++ ) {
  2197. props[ i ] = props[ i ].trim().replace( /^\"/, '' ).replace( /\s/, '_' );
  2198. }
  2199. var innerPropName = props[ 0 ];
  2200. var innerPropType1 = props[ 1 ];
  2201. var innerPropType2 = props[ 2 ];
  2202. var innerPropFlag = props[ 3 ];
  2203. var innerPropValue = props[ 4 ];
  2204. /*
  2205. if ( innerPropValue === undefined ) {
  2206. innerPropValue = props[3];
  2207. }
  2208. */
  2209. // cast value to its type
  2210. switch ( innerPropType1 ) {
  2211. case 'int':
  2212. case 'enum':
  2213. case 'bool':
  2214. case 'ULongLong':
  2215. innerPropValue = parseInt( innerPropValue );
  2216. break;
  2217. case 'double':
  2218. case 'Number':
  2219. case 'FieldOfView':
  2220. innerPropValue = parseFloat( innerPropValue );
  2221. break;
  2222. case 'ColorRGB':
  2223. case 'Vector3D':
  2224. case 'Lcl_Translation':
  2225. case 'Lcl_Rotation':
  2226. case 'Lcl_Scaling':
  2227. innerPropValue = parseNumberArray( innerPropValue );
  2228. break;
  2229. }
  2230. // CAUTION: these props must append to parent's parent
  2231. this.getPrevNode().properties[ innerPropName ] = {
  2232. 'type': innerPropType1,
  2233. 'type2': innerPropType2,
  2234. 'flag': innerPropFlag,
  2235. 'value': innerPropValue
  2236. };
  2237. this.setCurrentProp( this.getPrevNode().properties, innerPropName );
  2238. },
  2239. nodeEnd: function () {
  2240. this.popStack();
  2241. },
  2242. isFlattenNode: function ( node ) {
  2243. return ( 'subNodes' in node && 'properties' in node ) ? true : false;
  2244. }
  2245. } );
  2246. // Parse an FBX file in Binary format
  2247. function BinaryParser() {}
  2248. Object.assign( BinaryParser.prototype, {
  2249. parse: function ( buffer ) {
  2250. var reader = new BinaryReader( buffer );
  2251. reader.skip( 23 ); // skip magic 23 bytes
  2252. var version = reader.getUint32();
  2253. console.log( 'THREE.FBXLoader: FBX binary version: ' + version );
  2254. var allNodes = new FBXTree();
  2255. while ( ! this.endOfContent( reader ) ) {
  2256. var node = this.parseNode( reader, version );
  2257. if ( node !== null ) allNodes.add( node.name, node );
  2258. }
  2259. return allNodes;
  2260. },
  2261. // Check if reader has reached the end of content.
  2262. endOfContent: function ( reader ) {
  2263. // footer size: 160bytes + 16-byte alignment padding
  2264. // - 16bytes: magic
  2265. // - padding til 16-byte alignment (at least 1byte?)
  2266. // (seems like some exporters embed fixed 15 or 16bytes?)
  2267. // - 4bytes: magic
  2268. // - 4bytes: version
  2269. // - 120bytes: zero
  2270. // - 16bytes: magic
  2271. if ( reader.size() % 16 === 0 ) {
  2272. return ( ( reader.getOffset() + 160 + 16 ) & ~ 0xf ) >= reader.size();
  2273. } else {
  2274. return reader.getOffset() + 160 + 16 >= reader.size();
  2275. }
  2276. },
  2277. parseNode: function ( reader, version ) {
  2278. // The first three data sizes depends on version.
  2279. var endOffset = ( version >= 7500 ) ? reader.getUint64() : reader.getUint32();
  2280. var numProperties = ( version >= 7500 ) ? reader.getUint64() : reader.getUint32();
  2281. // note: do not remove this even if you get a linter warning as it moves the buffer forward
  2282. var propertyListLen = ( version >= 7500 ) ? reader.getUint64() : reader.getUint32();
  2283. var nameLen = reader.getUint8();
  2284. var name = reader.getString( nameLen );
  2285. // Regards this node as NULL-record if endOffset is zero
  2286. if ( endOffset === 0 ) return null;
  2287. var propertyList = [];
  2288. for ( var i = 0; i < numProperties; i ++ ) {
  2289. propertyList.push( this.parseProperty( reader ) );
  2290. }
  2291. // Regards the first three elements in propertyList as id, attrName, and attrType
  2292. var id = propertyList.length > 0 ? propertyList[ 0 ] : '';
  2293. var attrName = propertyList.length > 1 ? propertyList[ 1 ] : '';
  2294. var attrType = propertyList.length > 2 ? propertyList[ 2 ] : '';
  2295. var subNodes = {};
  2296. var properties = {};
  2297. var isSingleProperty = false;
  2298. // check if this node represents just a single property
  2299. // like (name, 0) set or (name2, [0, 1, 2]) set of {name: 0, name2: [0, 1, 2]}
  2300. if ( numProperties === 1 && reader.getOffset() === endOffset ) {
  2301. isSingleProperty = true;
  2302. }
  2303. while ( endOffset > reader.getOffset() ) {
  2304. var node = this.parseNode( reader, version );
  2305. if ( node === null ) continue;
  2306. // special case: child node is single property
  2307. if ( node.singleProperty === true ) {
  2308. var value = node.propertyList[ 0 ];
  2309. if ( Array.isArray( value ) ) {
  2310. node.properties[ node.name ] = node.propertyList[ 0 ];
  2311. subNodes[ node.name ] = node;
  2312. node.properties.a = value;
  2313. } else {
  2314. properties[ node.name ] = value;
  2315. }
  2316. continue;
  2317. }
  2318. // parse connections
  2319. if ( name === 'Connections' && node.name === 'C' ) {
  2320. var array = [];
  2321. for ( var i = 1, il = node.propertyList.length; i < il; i ++ ) {
  2322. array[ i - 1 ] = node.propertyList[ i ];
  2323. }
  2324. if ( properties.connections === undefined ) {
  2325. properties.connections = [];
  2326. }
  2327. properties.connections.push( array );
  2328. continue;
  2329. }
  2330. // special case: child node is Properties\d+
  2331. // move child node's properties to this node.
  2332. if ( node.name.match( /^Properties\d+$/ ) ) {
  2333. var keys = Object.keys( node.properties );
  2334. for ( var i = 0, il = keys.length; i < il; i ++ ) {
  2335. var key = keys[ i ];
  2336. properties[ key ] = node.properties[ key ];
  2337. }
  2338. continue;
  2339. }
  2340. // parse 'properties70'
  2341. if ( name.match( /^Properties\d+$/ ) && node.name === 'P' ) {
  2342. var innerPropName = node.propertyList[ 0 ];
  2343. var innerPropType1 = node.propertyList[ 1 ];
  2344. var innerPropType2 = node.propertyList[ 2 ];
  2345. var innerPropFlag = node.propertyList[ 3 ];
  2346. var innerPropValue;
  2347. if ( innerPropName.indexOf( 'Lcl ' ) === 0 ) innerPropName = innerPropName.replace( 'Lcl ', 'Lcl_' );
  2348. if ( innerPropType1.indexOf( 'Lcl ' ) === 0 ) innerPropType1 = innerPropType1.replace( 'Lcl ', 'Lcl_' );
  2349. if ( innerPropType1 === 'ColorRGB' || innerPropType1 === 'Vector' || innerPropType1 === 'Vector3D' || innerPropType1.indexOf( 'Lcl_' ) === 0 ) {
  2350. innerPropValue = [
  2351. node.propertyList[ 4 ],
  2352. node.propertyList[ 5 ],
  2353. node.propertyList[ 6 ]
  2354. ];
  2355. } else {
  2356. innerPropValue = node.propertyList[ 4 ];
  2357. }
  2358. // this will be copied to parent, see above
  2359. properties[ innerPropName ] = {
  2360. 'type': innerPropType1,
  2361. 'type2': innerPropType2,
  2362. 'flag': innerPropFlag,
  2363. 'value': innerPropValue
  2364. };
  2365. continue;
  2366. }
  2367. if ( subNodes[ node.name ] === undefined ) {
  2368. if ( typeof node.id === 'number' ) {
  2369. subNodes[ node.name ] = {};
  2370. subNodes[ node.name ][ node.id ] = node;
  2371. } else {
  2372. subNodes[ node.name ] = node;
  2373. }
  2374. } else {
  2375. if ( node.id === '' ) {
  2376. if ( ! Array.isArray( subNodes[ node.name ] ) ) {
  2377. subNodes[ node.name ] = [ subNodes[ node.name ] ];
  2378. }
  2379. subNodes[ node.name ].push( node );
  2380. } else {
  2381. if ( subNodes[ node.name ][ node.id ] === undefined ) {
  2382. subNodes[ node.name ][ node.id ] = node;
  2383. } else {
  2384. // conflict id. irregular?
  2385. if ( ! Array.isArray( subNodes[ node.name ][ node.id ] ) ) {
  2386. subNodes[ node.name ][ node.id ] = [ subNodes[ node.name ][ node.id ] ];
  2387. }
  2388. subNodes[ node.name ][ node.id ].push( node );
  2389. }
  2390. }
  2391. }
  2392. }
  2393. return {
  2394. singleProperty: isSingleProperty,
  2395. id: id,
  2396. attrName: attrName,
  2397. attrType: attrType,
  2398. name: name,
  2399. properties: properties,
  2400. propertyList: propertyList, // raw property list used by parent
  2401. subNodes: subNodes
  2402. };
  2403. },
  2404. parseProperty: function ( reader ) {
  2405. var type = reader.getChar();
  2406. switch ( type ) {
  2407. case 'C':
  2408. return reader.getBoolean();
  2409. case 'D':
  2410. return reader.getFloat64();
  2411. case 'F':
  2412. return reader.getFloat32();
  2413. case 'I':
  2414. return reader.getInt32();
  2415. case 'L':
  2416. return reader.getInt64();
  2417. case 'R':
  2418. var length = reader.getUint32();
  2419. return reader.getArrayBuffer( length );
  2420. case 'S':
  2421. var length = reader.getUint32();
  2422. return reader.getString( length );
  2423. case 'Y':
  2424. return reader.getInt16();
  2425. case 'b':
  2426. case 'c':
  2427. case 'd':
  2428. case 'f':
  2429. case 'i':
  2430. case 'l':
  2431. var arrayLength = reader.getUint32();
  2432. var encoding = reader.getUint32(); // 0: non-compressed, 1: compressed
  2433. var compressedLength = reader.getUint32();
  2434. if ( encoding === 0 ) {
  2435. switch ( type ) {
  2436. case 'b':
  2437. case 'c':
  2438. return reader.getBooleanArray( arrayLength );
  2439. case 'd':
  2440. return reader.getFloat64Array( arrayLength );
  2441. case 'f':
  2442. return reader.getFloat32Array( arrayLength );
  2443. case 'i':
  2444. return reader.getInt32Array( arrayLength );
  2445. case 'l':
  2446. return reader.getInt64Array( arrayLength );
  2447. }
  2448. }
  2449. if ( window.Zlib === undefined ) {
  2450. throw new Error( 'THREE.FBXLoader: External library Inflate.min.js required, obtain or import from https://github.com/imaya/zlib.js' );
  2451. }
  2452. var inflate = new Zlib.Inflate( new Uint8Array( reader.getArrayBuffer( compressedLength ) ) ); // eslint-disable-line no-undef
  2453. var reader2 = new BinaryReader( inflate.decompress().buffer );
  2454. switch ( type ) {
  2455. case 'b':
  2456. case 'c':
  2457. return reader2.getBooleanArray( arrayLength );
  2458. case 'd':
  2459. return reader2.getFloat64Array( arrayLength );
  2460. case 'f':
  2461. return reader2.getFloat32Array( arrayLength );
  2462. case 'i':
  2463. return reader2.getInt32Array( arrayLength );
  2464. case 'l':
  2465. return reader2.getInt64Array( arrayLength );
  2466. }
  2467. default:
  2468. throw new Error( 'THREE.FBXLoader: Unknown property type ' + type );
  2469. }
  2470. }
  2471. } );
  2472. function BinaryReader( buffer, littleEndian ) {
  2473. this.dv = new DataView( buffer );
  2474. this.offset = 0;
  2475. this.littleEndian = ( littleEndian !== undefined ) ? littleEndian : true;
  2476. }
  2477. Object.assign( BinaryReader.prototype, {
  2478. getOffset: function () {
  2479. return this.offset;
  2480. },
  2481. size: function () {
  2482. return this.dv.buffer.byteLength;
  2483. },
  2484. skip: function ( length ) {
  2485. this.offset += length;
  2486. },
  2487. // seems like true/false representation depends on exporter.
  2488. // true: 1 or 'Y'(=0x59), false: 0 or 'T'(=0x54)
  2489. // then sees LSB.
  2490. getBoolean: function () {
  2491. return ( this.getUint8() & 1 ) === 1;
  2492. },
  2493. getBooleanArray: function ( size ) {
  2494. var a = [];
  2495. for ( var i = 0; i < size; i ++ ) {
  2496. a.push( this.getBoolean() );
  2497. }
  2498. return a;
  2499. },
  2500. getInt8: function () {
  2501. var value = this.dv.getInt8( this.offset );
  2502. this.offset += 1;
  2503. return value;
  2504. },
  2505. getInt8Array: function ( size ) {
  2506. var a = [];
  2507. for ( var i = 0; i < size; i ++ ) {
  2508. a.push( this.getInt8() );
  2509. }
  2510. return a;
  2511. },
  2512. getUint8: function () {
  2513. var value = this.dv.getUint8( this.offset );
  2514. this.offset += 1;
  2515. return value;
  2516. },
  2517. getUint8Array: function ( size ) {
  2518. var a = [];
  2519. for ( var i = 0; i < size; i ++ ) {
  2520. a.push( this.getUint8() );
  2521. }
  2522. return a;
  2523. },
  2524. getInt16: function () {
  2525. var value = this.dv.getInt16( this.offset, this.littleEndian );
  2526. this.offset += 2;
  2527. return value;
  2528. },
  2529. getInt16Array: function ( size ) {
  2530. var a = [];
  2531. for ( var i = 0; i < size; i ++ ) {
  2532. a.push( this.getInt16() );
  2533. }
  2534. return a;
  2535. },
  2536. getUint16: function () {
  2537. var value = this.dv.getUint16( this.offset, this.littleEndian );
  2538. this.offset += 2;
  2539. return value;
  2540. },
  2541. getUint16Array: function ( size ) {
  2542. var a = [];
  2543. for ( var i = 0; i < size; i ++ ) {
  2544. a.push( this.getUint16() );
  2545. }
  2546. return a;
  2547. },
  2548. getInt32: function () {
  2549. var value = this.dv.getInt32( this.offset, this.littleEndian );
  2550. this.offset += 4;
  2551. return value;
  2552. },
  2553. getInt32Array: function ( size ) {
  2554. var a = [];
  2555. for ( var i = 0; i < size; i ++ ) {
  2556. a.push( this.getInt32() );
  2557. }
  2558. return a;
  2559. },
  2560. getUint32: function () {
  2561. var value = this.dv.getUint32( this.offset, this.littleEndian );
  2562. this.offset += 4;
  2563. return value;
  2564. },
  2565. getUint32Array: function ( size ) {
  2566. var a = [];
  2567. for ( var i = 0; i < size; i ++ ) {
  2568. a.push( this.getUint32() );
  2569. }
  2570. return a;
  2571. },
  2572. // JavaScript doesn't support 64-bit integer so calculate this here
  2573. // 1 << 32 will return 1 so using multiply operation instead here.
  2574. // There's a possibility that this method returns wrong value if the value
  2575. // is out of the range between Number.MAX_SAFE_INTEGER and Number.MIN_SAFE_INTEGER.
  2576. // TODO: safely handle 64-bit integer
  2577. getInt64: function () {
  2578. var low, high;
  2579. if ( this.littleEndian ) {
  2580. low = this.getUint32();
  2581. high = this.getUint32();
  2582. } else {
  2583. high = this.getUint32();
  2584. low = this.getUint32();
  2585. }
  2586. // calculate negative value
  2587. if ( high & 0x80000000 ) {
  2588. high = ~ high & 0xFFFFFFFF;
  2589. low = ~ low & 0xFFFFFFFF;
  2590. if ( low === 0xFFFFFFFF ) high = ( high + 1 ) & 0xFFFFFFFF;
  2591. low = ( low + 1 ) & 0xFFFFFFFF;
  2592. return - ( high * 0x100000000 + low );
  2593. }
  2594. return high * 0x100000000 + low;
  2595. },
  2596. getInt64Array: function ( size ) {
  2597. var a = [];
  2598. for ( var i = 0; i < size; i ++ ) {
  2599. a.push( this.getInt64() );
  2600. }
  2601. return a;
  2602. },
  2603. // Note: see getInt64() comment
  2604. getUint64: function () {
  2605. var low, high;
  2606. if ( this.littleEndian ) {
  2607. low = this.getUint32();
  2608. high = this.getUint32();
  2609. } else {
  2610. high = this.getUint32();
  2611. low = this.getUint32();
  2612. }
  2613. return high * 0x100000000 + low;
  2614. },
  2615. getUint64Array: function ( size ) {
  2616. var a = [];
  2617. for ( var i = 0; i < size; i ++ ) {
  2618. a.push( this.getUint64() );
  2619. }
  2620. return a;
  2621. },
  2622. getFloat32: function () {
  2623. var value = this.dv.getFloat32( this.offset, this.littleEndian );
  2624. this.offset += 4;
  2625. return value;
  2626. },
  2627. getFloat32Array: function ( size ) {
  2628. var a = [];
  2629. for ( var i = 0; i < size; i ++ ) {
  2630. a.push( this.getFloat32() );
  2631. }
  2632. return a;
  2633. },
  2634. getFloat64: function () {
  2635. var value = this.dv.getFloat64( this.offset, this.littleEndian );
  2636. this.offset += 8;
  2637. return value;
  2638. },
  2639. getFloat64Array: function ( size ) {
  2640. var a = [];
  2641. for ( var i = 0; i < size; i ++ ) {
  2642. a.push( this.getFloat64() );
  2643. }
  2644. return a;
  2645. },
  2646. getArrayBuffer: function ( size ) {
  2647. var value = this.dv.buffer.slice( this.offset, this.offset + size );
  2648. this.offset += size;
  2649. return value;
  2650. },
  2651. getChar: function () {
  2652. return String.fromCharCode( this.getUint8() );
  2653. },
  2654. getString: function ( size ) {
  2655. var s = '';
  2656. while ( size > 0 ) {
  2657. var value = this.getUint8();
  2658. size --;
  2659. if ( value === 0 ) break;
  2660. s += String.fromCharCode( value );
  2661. }
  2662. // Manage UTF8 encoding
  2663. s = decodeURIComponent( escape( s ) );
  2664. this.skip( size );
  2665. return s;
  2666. }
  2667. } );
  2668. // FBXTree holds a representation of the FBX data, returned by the TextParser ( FBX ASCII format)
  2669. // and BinaryParser( FBX Binary format)
  2670. function FBXTree() {}
  2671. Object.assign( FBXTree.prototype, {
  2672. add: function ( key, val ) {
  2673. this[ key ] = val;
  2674. },
  2675. } );
  2676. function isFbxFormatBinary( buffer ) {
  2677. var CORRECT = 'Kaydara FBX Binary \0';
  2678. return buffer.byteLength >= CORRECT.length && CORRECT === convertArrayBufferToString( buffer, 0, CORRECT.length );
  2679. }
  2680. function isFbxFormatASCII( text ) {
  2681. var CORRECT = [ 'K', 'a', 'y', 'd', 'a', 'r', 'a', '\\', 'F', 'B', 'X', '\\', 'B', 'i', 'n', 'a', 'r', 'y', '\\', '\\' ];
  2682. var cursor = 0;
  2683. function read( offset ) {
  2684. var result = text[ offset - 1 ];
  2685. text = text.slice( cursor + offset );
  2686. cursor ++;
  2687. return result;
  2688. }
  2689. for ( var i = 0; i < CORRECT.length; ++ i ) {
  2690. var num = read( 1 );
  2691. if ( num === CORRECT[ i ] ) {
  2692. return false;
  2693. }
  2694. }
  2695. return true;
  2696. }
  2697. function getFbxVersion( text ) {
  2698. var versionRegExp = /FBXVersion: (\d+)/;
  2699. var match = text.match( versionRegExp );
  2700. if ( match ) {
  2701. var version = parseInt( match[ 1 ] );
  2702. return version;
  2703. }
  2704. throw new Error( 'THREE.FBXLoader: Cannot find the version number for the file given.' );
  2705. }
  2706. // Converts FBX ticks into real time seconds.
  2707. function convertFBXTimeToSeconds( time ) {
  2708. return time / 46186158000;
  2709. }
  2710. // Parses comma separated list of numbers and returns them an array.
  2711. // Used internally by the TextParser
  2712. function parseNumberArray( value ) {
  2713. var array = value.split( ',' );
  2714. for ( var i = 0, l = array.length; i < l; i ++ ) {
  2715. array[ i ] = parseFloat( array[ i ] );
  2716. }
  2717. return array;
  2718. }
  2719. function parseVector3( property ) {
  2720. return new THREE.Vector3().fromArray( property.value );
  2721. }
  2722. function parseColor( property ) {
  2723. return new THREE.Color().fromArray( property.value );
  2724. }
  2725. // Converts ArrayBuffer to String.
  2726. function convertArrayBufferToString( buffer, from, to ) {
  2727. if ( from === undefined ) from = 0;
  2728. if ( to === undefined ) to = buffer.byteLength;
  2729. var array = new Uint8Array( buffer, from, to );
  2730. if ( window.TextDecoder !== undefined ) {
  2731. return new TextDecoder().decode( array );
  2732. }
  2733. var s = '';
  2734. for ( var i = 0, il = array.length; i < il; i ++ ) {
  2735. s += String.fromCharCode( array[ i ] );
  2736. }
  2737. return s;
  2738. }
  2739. function findIndex( array, func ) {
  2740. for ( var i = 0, l = array.length; i < l; i ++ ) {
  2741. if ( func( array[ i ] ) ) return i;
  2742. }
  2743. return - 1;
  2744. }
  2745. function append( a, b ) {
  2746. for ( var i = 0, j = a.length, l = b.length; i < l; i ++, j ++ ) {
  2747. a[ j ] = b[ i ];
  2748. }
  2749. }
  2750. function slice( a, b, from, to ) {
  2751. for ( var i = from, j = 0; i < to; i ++, j ++ ) {
  2752. a[ j ] = b[ i ];
  2753. }
  2754. return a;
  2755. }
  2756. } )();