FBXLoader.js 90 KB

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