FBXLoader.js 99 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134
  1. console.warn( "THREE.FBXLoader: As part of the transition to ES6 Modules, the files in 'examples/js' were deprecated in May 2020 (r117) and will be deleted in December 2020 (r124). You can find more information about developing using ES6 Modules in https://threejs.org/docs/#manual/en/introduction/Installation." );
  2. /**
  3. * @author Kyle-Larson https://github.com/Kyle-Larson
  4. * @author Takahiro https://github.com/takahirox
  5. * @author Lewy Blue https://github.com/looeee
  6. *
  7. * Loader loads FBX file and generates Group representing FBX scene.
  8. * Requires FBX file to be >= 7.0 and in ASCII or >= 6400 in Binary format
  9. * Versions lower than this may load but will probably have errors
  10. *
  11. * Needs Support:
  12. * Morph normals / blend shape normals
  13. *
  14. * FBX format references:
  15. * https://wiki.blender.org/index.php/User:Mont29/Foundation/FBX_File_Structure
  16. * http://help.autodesk.com/view/FBX/2017/ENU/?guid=__cpp_ref_index_html (C++ SDK reference)
  17. *
  18. * Binary format specification:
  19. * https://code.blender.org/2013/08/fbx-binary-file-format-specification/
  20. */
  21. THREE.FBXLoader = ( function () {
  22. var fbxTree;
  23. var connections;
  24. var sceneGraph;
  25. function FBXLoader( manager ) {
  26. THREE.Loader.call( this, manager );
  27. }
  28. FBXLoader.prototype = Object.assign( Object.create( THREE.Loader.prototype ), {
  29. constructor: FBXLoader,
  30. load: function ( url, onLoad, onProgress, onError ) {
  31. var scope = this;
  32. var path = ( scope.path === '' ) ? THREE.LoaderUtils.extractUrlBase( url ) : scope.path;
  33. var loader = new THREE.FileLoader( this.manager );
  34. loader.setPath( scope.path );
  35. loader.setResponseType( 'arraybuffer' );
  36. loader.setRequestHeader( scope.requestHeader );
  37. loader.load( url, function ( buffer ) {
  38. try {
  39. onLoad( scope.parse( buffer, path ) );
  40. } catch ( e ) {
  41. if ( onError ) {
  42. onError( e );
  43. } else {
  44. console.error( e );
  45. }
  46. scope.manager.itemError( url );
  47. }
  48. }, onProgress, onError );
  49. },
  50. parse: function ( FBXBuffer, path ) {
  51. if ( isFbxFormatBinary( FBXBuffer ) ) {
  52. fbxTree = new BinaryParser().parse( FBXBuffer );
  53. } else {
  54. var FBXText = convertArrayBufferToString( FBXBuffer );
  55. if ( ! isFbxFormatASCII( FBXText ) ) {
  56. throw new Error( 'THREE.FBXLoader: Unknown format.' );
  57. }
  58. if ( getFbxVersion( FBXText ) < 7000 ) {
  59. throw new Error( 'THREE.FBXLoader: FBX version not supported, FileVersion: ' + getFbxVersion( FBXText ) );
  60. }
  61. fbxTree = new TextParser().parse( FBXText );
  62. }
  63. // console.log( fbxTree );
  64. var textureLoader = new THREE.TextureLoader( this.manager ).setPath( this.resourcePath || path ).setCrossOrigin( this.crossOrigin );
  65. return new FBXTreeParser( textureLoader, this.manager ).parse( fbxTree );
  66. }
  67. } );
  68. // Parse the FBXTree object returned by the BinaryParser or TextParser and return a THREE.Group
  69. function FBXTreeParser( textureLoader, manager ) {
  70. this.textureLoader = textureLoader;
  71. this.manager = manager;
  72. }
  73. FBXTreeParser.prototype = {
  74. constructor: FBXTreeParser,
  75. parse: function () {
  76. connections = this.parseConnections();
  77. var images = this.parseImages();
  78. var textures = this.parseTextures( images );
  79. var materials = this.parseMaterials( textures );
  80. var deformers = this.parseDeformers();
  81. var geometryMap = new GeometryParser().parse( deformers );
  82. this.parseScene( deformers, geometryMap, materials );
  83. return sceneGraph;
  84. },
  85. // Parses FBXTree.Connections which holds parent-child connections between objects (e.g. material -> texture, model->geometry )
  86. // and details the connection type
  87. parseConnections: function () {
  88. var connectionMap = new Map();
  89. if ( 'Connections' in fbxTree ) {
  90. var rawConnections = fbxTree.Connections.connections;
  91. rawConnections.forEach( function ( rawConnection ) {
  92. var fromID = rawConnection[ 0 ];
  93. var toID = rawConnection[ 1 ];
  94. var relationship = rawConnection[ 2 ];
  95. if ( ! connectionMap.has( fromID ) ) {
  96. connectionMap.set( fromID, {
  97. parents: [],
  98. children: []
  99. } );
  100. }
  101. var parentRelationship = { ID: toID, relationship: relationship };
  102. connectionMap.get( fromID ).parents.push( parentRelationship );
  103. if ( ! connectionMap.has( toID ) ) {
  104. connectionMap.set( toID, {
  105. parents: [],
  106. children: []
  107. } );
  108. }
  109. var childRelationship = { ID: fromID, relationship: relationship };
  110. connectionMap.get( toID ).children.push( childRelationship );
  111. } );
  112. }
  113. return connectionMap;
  114. },
  115. // Parse FBXTree.Objects.Video for embedded image data
  116. // These images are connected to textures in FBXTree.Objects.Textures
  117. // via FBXTree.Connections.
  118. parseImages: function () {
  119. var images = {};
  120. var blobs = {};
  121. if ( 'Video' in fbxTree.Objects ) {
  122. var videoNodes = fbxTree.Objects.Video;
  123. for ( var nodeID in videoNodes ) {
  124. var videoNode = videoNodes[ nodeID ];
  125. var id = parseInt( nodeID );
  126. images[ id ] = videoNode.RelativeFilename || videoNode.Filename;
  127. // raw image data is in videoNode.Content
  128. if ( 'Content' in videoNode ) {
  129. var arrayBufferContent = ( videoNode.Content instanceof ArrayBuffer ) && ( videoNode.Content.byteLength > 0 );
  130. var base64Content = ( typeof videoNode.Content === 'string' ) && ( videoNode.Content !== '' );
  131. if ( arrayBufferContent || base64Content ) {
  132. var image = this.parseImage( videoNodes[ nodeID ] );
  133. blobs[ videoNode.RelativeFilename || videoNode.Filename ] = image;
  134. }
  135. }
  136. }
  137. }
  138. for ( var id in images ) {
  139. var filename = images[ id ];
  140. if ( blobs[ filename ] !== undefined ) images[ id ] = blobs[ filename ];
  141. else images[ id ] = images[ id ].split( '\\' ).pop();
  142. }
  143. return images;
  144. },
  145. // Parse embedded image data in FBXTree.Video.Content
  146. parseImage: function ( videoNode ) {
  147. var content = videoNode.Content;
  148. var fileName = videoNode.RelativeFilename || videoNode.Filename;
  149. var extension = fileName.slice( fileName.lastIndexOf( '.' ) + 1 ).toLowerCase();
  150. var type;
  151. switch ( extension ) {
  152. case 'bmp':
  153. type = 'image/bmp';
  154. break;
  155. case 'jpg':
  156. case 'jpeg':
  157. type = 'image/jpeg';
  158. break;
  159. case 'png':
  160. type = 'image/png';
  161. break;
  162. case 'tif':
  163. type = 'image/tiff';
  164. break;
  165. case 'tga':
  166. if ( this.manager.getHandler( '.tga' ) === null ) {
  167. console.warn( 'FBXLoader: TGA loader not found, skipping ', fileName );
  168. }
  169. type = 'image/tga';
  170. break;
  171. default:
  172. console.warn( 'FBXLoader: Image type "' + extension + '" is not supported.' );
  173. return;
  174. }
  175. if ( typeof content === 'string' ) { // ASCII format
  176. return 'data:' + type + ';base64,' + content;
  177. } else { // Binary Format
  178. var array = new Uint8Array( content );
  179. return window.URL.createObjectURL( new Blob( [ array ], { type: type } ) );
  180. }
  181. },
  182. // Parse nodes in FBXTree.Objects.Texture
  183. // These contain details such as UV scaling, cropping, rotation etc and are connected
  184. // to images in FBXTree.Objects.Video
  185. parseTextures: function ( images ) {
  186. var textureMap = new Map();
  187. if ( 'Texture' in fbxTree.Objects ) {
  188. var textureNodes = fbxTree.Objects.Texture;
  189. for ( var nodeID in textureNodes ) {
  190. var texture = this.parseTexture( textureNodes[ nodeID ], images );
  191. textureMap.set( parseInt( nodeID ), texture );
  192. }
  193. }
  194. return textureMap;
  195. },
  196. // Parse individual node in FBXTree.Objects.Texture
  197. parseTexture: function ( textureNode, images ) {
  198. var texture = this.loadTexture( textureNode, images );
  199. texture.ID = textureNode.id;
  200. texture.name = textureNode.attrName;
  201. var wrapModeU = textureNode.WrapModeU;
  202. var wrapModeV = textureNode.WrapModeV;
  203. var valueU = wrapModeU !== undefined ? wrapModeU.value : 0;
  204. var valueV = wrapModeV !== undefined ? wrapModeV.value : 0;
  205. // http://download.autodesk.com/us/fbx/SDKdocs/FBX_SDK_Help/files/fbxsdkref/class_k_fbx_texture.html#889640e63e2e681259ea81061b85143a
  206. // 0: repeat(default), 1: clamp
  207. texture.wrapS = valueU === 0 ? THREE.RepeatWrapping : THREE.ClampToEdgeWrapping;
  208. texture.wrapT = valueV === 0 ? THREE.RepeatWrapping : THREE.ClampToEdgeWrapping;
  209. if ( 'Scaling' in textureNode ) {
  210. var values = textureNode.Scaling.value;
  211. texture.repeat.x = values[ 0 ];
  212. texture.repeat.y = values[ 1 ];
  213. }
  214. return texture;
  215. },
  216. // load a texture specified as a blob or data URI, or via an external URL using THREE.TextureLoader
  217. loadTexture: function ( textureNode, images ) {
  218. var fileName;
  219. var currentPath = this.textureLoader.path;
  220. var children = connections.get( textureNode.id ).children;
  221. if ( children !== undefined && children.length > 0 && images[ children[ 0 ].ID ] !== undefined ) {
  222. fileName = images[ children[ 0 ].ID ];
  223. if ( fileName.indexOf( 'blob:' ) === 0 || fileName.indexOf( 'data:' ) === 0 ) {
  224. this.textureLoader.setPath( undefined );
  225. }
  226. }
  227. var texture;
  228. var extension = textureNode.FileName.slice( - 3 ).toLowerCase();
  229. if ( extension === 'tga' ) {
  230. var loader = this.manager.getHandler( '.tga' );
  231. if ( loader === null ) {
  232. console.warn( 'FBXLoader: TGA loader not found, creating placeholder texture for', textureNode.RelativeFilename );
  233. texture = new THREE.Texture();
  234. } else {
  235. texture = loader.load( fileName );
  236. }
  237. } else if ( extension === 'psd' ) {
  238. console.warn( 'FBXLoader: PSD textures are not supported, creating placeholder texture for', textureNode.RelativeFilename );
  239. texture = new THREE.Texture();
  240. } else {
  241. texture = this.textureLoader.load( fileName );
  242. }
  243. this.textureLoader.setPath( currentPath );
  244. return texture;
  245. },
  246. // Parse nodes in FBXTree.Objects.Material
  247. parseMaterials: function ( textureMap ) {
  248. var materialMap = new Map();
  249. if ( 'Material' in fbxTree.Objects ) {
  250. var materialNodes = fbxTree.Objects.Material;
  251. for ( var nodeID in materialNodes ) {
  252. var material = this.parseMaterial( materialNodes[ nodeID ], textureMap );
  253. if ( material !== null ) materialMap.set( parseInt( nodeID ), material );
  254. }
  255. }
  256. return materialMap;
  257. },
  258. // Parse single node in FBXTree.Objects.Material
  259. // Materials are connected to texture maps in FBXTree.Objects.Textures
  260. // FBX format currently only supports Lambert and Phong shading models
  261. parseMaterial: function ( materialNode, textureMap ) {
  262. var ID = materialNode.id;
  263. var name = materialNode.attrName;
  264. var type = materialNode.ShadingModel;
  265. // Case where FBX wraps shading model in property object.
  266. if ( typeof type === 'object' ) {
  267. type = type.value;
  268. }
  269. // Ignore unused materials which don't have any connections.
  270. if ( ! connections.has( ID ) ) return null;
  271. var parameters = this.parseParameters( materialNode, textureMap, ID );
  272. var material;
  273. switch ( type.toLowerCase() ) {
  274. case 'phong':
  275. material = new THREE.MeshPhongMaterial();
  276. break;
  277. case 'lambert':
  278. material = new THREE.MeshLambertMaterial();
  279. break;
  280. default:
  281. console.warn( 'THREE.FBXLoader: unknown material type "%s". Defaulting to MeshPhongMaterial.', type );
  282. material = new THREE.MeshPhongMaterial();
  283. break;
  284. }
  285. material.setValues( parameters );
  286. material.name = name;
  287. return material;
  288. },
  289. // Parse FBX material and return parameters suitable for a three.js material
  290. // Also parse the texture map and return any textures associated with the material
  291. parseParameters: function ( materialNode, textureMap, ID ) {
  292. var parameters = {};
  293. if ( materialNode.BumpFactor ) {
  294. parameters.bumpScale = materialNode.BumpFactor.value;
  295. }
  296. if ( materialNode.Diffuse ) {
  297. parameters.color = new THREE.Color().fromArray( materialNode.Diffuse.value );
  298. } else if ( materialNode.DiffuseColor && materialNode.DiffuseColor.type === 'Color' ) {
  299. // The blender exporter exports diffuse here instead of in materialNode.Diffuse
  300. parameters.color = new THREE.Color().fromArray( materialNode.DiffuseColor.value );
  301. }
  302. if ( materialNode.DisplacementFactor ) {
  303. parameters.displacementScale = materialNode.DisplacementFactor.value;
  304. }
  305. if ( materialNode.Emissive ) {
  306. parameters.emissive = new THREE.Color().fromArray( materialNode.Emissive.value );
  307. } else if ( materialNode.EmissiveColor && materialNode.EmissiveColor.type === 'Color' ) {
  308. // The blender exporter exports emissive color here instead of in materialNode.Emissive
  309. parameters.emissive = new THREE.Color().fromArray( materialNode.EmissiveColor.value );
  310. }
  311. if ( materialNode.EmissiveFactor ) {
  312. parameters.emissiveIntensity = parseFloat( materialNode.EmissiveFactor.value );
  313. }
  314. if ( materialNode.Opacity ) {
  315. parameters.opacity = parseFloat( materialNode.Opacity.value );
  316. }
  317. if ( parameters.opacity < 1.0 ) {
  318. parameters.transparent = true;
  319. }
  320. if ( materialNode.ReflectionFactor ) {
  321. parameters.reflectivity = materialNode.ReflectionFactor.value;
  322. }
  323. if ( materialNode.Shininess ) {
  324. parameters.shininess = materialNode.Shininess.value;
  325. }
  326. if ( materialNode.Specular ) {
  327. parameters.specular = new THREE.Color().fromArray( materialNode.Specular.value );
  328. } else if ( materialNode.SpecularColor && materialNode.SpecularColor.type === 'Color' ) {
  329. // The blender exporter exports specular color here instead of in materialNode.Specular
  330. parameters.specular = new THREE.Color().fromArray( materialNode.SpecularColor.value );
  331. }
  332. var scope = this;
  333. connections.get( ID ).children.forEach( function ( child ) {
  334. var type = child.relationship;
  335. switch ( type ) {
  336. case 'Bump':
  337. parameters.bumpMap = scope.getTexture( textureMap, child.ID );
  338. break;
  339. case 'Maya|TEX_ao_map':
  340. parameters.aoMap = scope.getTexture( textureMap, child.ID );
  341. break;
  342. case 'DiffuseColor':
  343. case 'Maya|TEX_color_map':
  344. parameters.map = scope.getTexture( textureMap, child.ID );
  345. parameters.map.encoding = THREE.sRGBEncoding;
  346. break;
  347. case 'DisplacementColor':
  348. parameters.displacementMap = scope.getTexture( textureMap, child.ID );
  349. break;
  350. case 'EmissiveColor':
  351. parameters.emissiveMap = scope.getTexture( textureMap, child.ID );
  352. parameters.emissiveMap.encoding = THREE.sRGBEncoding;
  353. break;
  354. case 'NormalMap':
  355. case 'Maya|TEX_normal_map':
  356. parameters.normalMap = scope.getTexture( textureMap, child.ID );
  357. break;
  358. case 'ReflectionColor':
  359. parameters.envMap = scope.getTexture( textureMap, child.ID );
  360. parameters.envMap.mapping = THREE.EquirectangularReflectionMapping;
  361. parameters.envMap.encoding = THREE.sRGBEncoding;
  362. break;
  363. case 'SpecularColor':
  364. parameters.specularMap = scope.getTexture( textureMap, child.ID );
  365. parameters.specularMap.encoding = THREE.sRGBEncoding;
  366. break;
  367. case 'TransparentColor':
  368. case 'TransparencyFactor':
  369. parameters.alphaMap = scope.getTexture( textureMap, child.ID );
  370. parameters.transparent = true;
  371. break;
  372. case 'AmbientColor':
  373. case 'ShininessExponent': // AKA glossiness map
  374. case 'SpecularFactor': // AKA specularLevel
  375. case 'VectorDisplacementColor': // NOTE: Seems to be a copy of DisplacementColor
  376. default:
  377. console.warn( 'THREE.FBXLoader: %s map is not supported in three.js, skipping texture.', type );
  378. break;
  379. }
  380. } );
  381. return parameters;
  382. },
  383. // get a texture from the textureMap for use by a material.
  384. getTexture: function ( textureMap, id ) {
  385. // if the texture is a layered texture, just use the first layer and issue a warning
  386. if ( 'LayeredTexture' in fbxTree.Objects && id in fbxTree.Objects.LayeredTexture ) {
  387. console.warn( 'THREE.FBXLoader: layered textures are not supported in three.js. Discarding all but first layer.' );
  388. id = connections.get( id ).children[ 0 ].ID;
  389. }
  390. return textureMap.get( id );
  391. },
  392. // Parse nodes in FBXTree.Objects.Deformer
  393. // Deformer node can contain skinning or Vertex Cache animation data, however only skinning is supported here
  394. // Generates map of Skeleton-like objects for use later when generating and binding skeletons.
  395. parseDeformers: function () {
  396. var skeletons = {};
  397. var morphTargets = {};
  398. if ( 'Deformer' in fbxTree.Objects ) {
  399. var DeformerNodes = fbxTree.Objects.Deformer;
  400. for ( var nodeID in DeformerNodes ) {
  401. var deformerNode = DeformerNodes[ nodeID ];
  402. var relationships = connections.get( parseInt( nodeID ) );
  403. if ( deformerNode.attrType === 'Skin' ) {
  404. var skeleton = this.parseSkeleton( relationships, DeformerNodes );
  405. skeleton.ID = nodeID;
  406. if ( relationships.parents.length > 1 ) console.warn( 'THREE.FBXLoader: skeleton attached to more than one geometry is not supported.' );
  407. skeleton.geometryID = relationships.parents[ 0 ].ID;
  408. skeletons[ nodeID ] = skeleton;
  409. } else if ( deformerNode.attrType === 'BlendShape' ) {
  410. var morphTarget = {
  411. id: nodeID,
  412. };
  413. morphTarget.rawTargets = this.parseMorphTargets( relationships, DeformerNodes );
  414. morphTarget.id = nodeID;
  415. if ( relationships.parents.length > 1 ) console.warn( 'THREE.FBXLoader: morph target attached to more than one geometry is not supported.' );
  416. morphTargets[ nodeID ] = morphTarget;
  417. }
  418. }
  419. }
  420. return {
  421. skeletons: skeletons,
  422. morphTargets: morphTargets,
  423. };
  424. },
  425. // Parse single nodes in FBXTree.Objects.Deformer
  426. // The top level skeleton node has type 'Skin' and sub nodes have type 'Cluster'
  427. // Each skin node represents a skeleton and each cluster node represents a bone
  428. parseSkeleton: function ( relationships, deformerNodes ) {
  429. var rawBones = [];
  430. relationships.children.forEach( function ( child ) {
  431. var boneNode = deformerNodes[ child.ID ];
  432. if ( boneNode.attrType !== 'Cluster' ) return;
  433. var rawBone = {
  434. ID: child.ID,
  435. indices: [],
  436. weights: [],
  437. transformLink: new THREE.Matrix4().fromArray( boneNode.TransformLink.a ),
  438. // transform: new THREE.Matrix4().fromArray( boneNode.Transform.a ),
  439. // linkMode: boneNode.Mode,
  440. };
  441. if ( 'Indexes' in boneNode ) {
  442. rawBone.indices = boneNode.Indexes.a;
  443. rawBone.weights = boneNode.Weights.a;
  444. }
  445. rawBones.push( rawBone );
  446. } );
  447. return {
  448. rawBones: rawBones,
  449. bones: []
  450. };
  451. },
  452. // The top level morph deformer node has type "BlendShape" and sub nodes have type "BlendShapeChannel"
  453. parseMorphTargets: function ( relationships, deformerNodes ) {
  454. var rawMorphTargets = [];
  455. for ( var i = 0; i < relationships.children.length; i ++ ) {
  456. var child = relationships.children[ i ];
  457. var morphTargetNode = deformerNodes[ child.ID ];
  458. var rawMorphTarget = {
  459. name: morphTargetNode.attrName,
  460. initialWeight: morphTargetNode.DeformPercent,
  461. id: morphTargetNode.id,
  462. fullWeights: morphTargetNode.FullWeights.a
  463. };
  464. if ( morphTargetNode.attrType !== 'BlendShapeChannel' ) return;
  465. rawMorphTarget.geoID = connections.get( parseInt( child.ID ) ).children.filter( function ( child ) {
  466. return child.relationship === undefined;
  467. } )[ 0 ].ID;
  468. rawMorphTargets.push( rawMorphTarget );
  469. }
  470. return rawMorphTargets;
  471. },
  472. // create the main THREE.Group() to be returned by the loader
  473. parseScene: function ( deformers, geometryMap, materialMap ) {
  474. sceneGraph = new THREE.Group();
  475. var modelMap = this.parseModels( deformers.skeletons, geometryMap, materialMap );
  476. var modelNodes = fbxTree.Objects.Model;
  477. var scope = this;
  478. modelMap.forEach( function ( model ) {
  479. var modelNode = modelNodes[ model.ID ];
  480. scope.setLookAtProperties( model, modelNode );
  481. var parentConnections = connections.get( model.ID ).parents;
  482. parentConnections.forEach( function ( connection ) {
  483. var parent = modelMap.get( connection.ID );
  484. if ( parent !== undefined ) parent.add( model );
  485. } );
  486. if ( model.parent === null ) {
  487. sceneGraph.add( model );
  488. }
  489. } );
  490. this.bindSkeleton( deformers.skeletons, geometryMap, modelMap );
  491. this.createAmbientLight();
  492. this.setupMorphMaterials();
  493. sceneGraph.traverse( function ( node ) {
  494. if ( node.userData.transformData ) {
  495. if ( node.parent ) node.userData.transformData.parentMatrixWorld = node.parent.matrix;
  496. var transform = generateTransform( node.userData.transformData );
  497. node.applyMatrix4( transform );
  498. }
  499. } );
  500. var animations = new AnimationParser().parse();
  501. // if all the models where already combined in a single group, just return that
  502. if ( sceneGraph.children.length === 1 && sceneGraph.children[ 0 ].isGroup ) {
  503. sceneGraph.children[ 0 ].animations = animations;
  504. sceneGraph = sceneGraph.children[ 0 ];
  505. }
  506. sceneGraph.animations = animations;
  507. },
  508. // parse nodes in FBXTree.Objects.Model
  509. parseModels: function ( skeletons, geometryMap, materialMap ) {
  510. var modelMap = new Map();
  511. var modelNodes = fbxTree.Objects.Model;
  512. for ( var nodeID in modelNodes ) {
  513. var id = parseInt( nodeID );
  514. var node = modelNodes[ nodeID ];
  515. var relationships = connections.get( id );
  516. var model = this.buildSkeleton( relationships, skeletons, id, node.attrName );
  517. if ( ! model ) {
  518. switch ( node.attrType ) {
  519. case 'Camera':
  520. model = this.createCamera( relationships );
  521. break;
  522. case 'Light':
  523. model = this.createLight( relationships );
  524. break;
  525. case 'Mesh':
  526. model = this.createMesh( relationships, geometryMap, materialMap );
  527. break;
  528. case 'NurbsCurve':
  529. model = this.createCurve( relationships, geometryMap );
  530. break;
  531. case 'LimbNode':
  532. case 'Root':
  533. model = new THREE.Bone();
  534. break;
  535. case 'Null':
  536. default:
  537. model = new THREE.Group();
  538. break;
  539. }
  540. model.name = node.attrName ? THREE.PropertyBinding.sanitizeNodeName( node.attrName ) : '';
  541. model.ID = id;
  542. }
  543. this.getTransformData( model, node );
  544. modelMap.set( id, model );
  545. }
  546. return modelMap;
  547. },
  548. buildSkeleton: function ( relationships, skeletons, id, name ) {
  549. var bone = null;
  550. relationships.parents.forEach( function ( parent ) {
  551. for ( var ID in skeletons ) {
  552. var skeleton = skeletons[ ID ];
  553. skeleton.rawBones.forEach( function ( rawBone, i ) {
  554. if ( rawBone.ID === parent.ID ) {
  555. var subBone = bone;
  556. bone = new THREE.Bone();
  557. bone.matrixWorld.copy( rawBone.transformLink );
  558. // set name and id here - otherwise in cases where "subBone" is created it will not have a name / id
  559. bone.name = name ? THREE.PropertyBinding.sanitizeNodeName( name ) : '';
  560. bone.ID = id;
  561. skeleton.bones[ i ] = bone;
  562. // In cases where a bone is shared between multiple meshes
  563. // duplicate the bone here and and it as a child of the first bone
  564. if ( subBone !== null ) {
  565. bone.add( subBone );
  566. }
  567. }
  568. } );
  569. }
  570. } );
  571. return bone;
  572. },
  573. // create a THREE.PerspectiveCamera or THREE.OrthographicCamera
  574. createCamera: function ( relationships ) {
  575. var model;
  576. var cameraAttribute;
  577. relationships.children.forEach( function ( child ) {
  578. var attr = fbxTree.Objects.NodeAttribute[ child.ID ];
  579. if ( attr !== undefined ) {
  580. cameraAttribute = attr;
  581. }
  582. } );
  583. if ( cameraAttribute === undefined ) {
  584. model = new THREE.Object3D();
  585. } else {
  586. var type = 0;
  587. if ( cameraAttribute.CameraProjectionType !== undefined && cameraAttribute.CameraProjectionType.value === 1 ) {
  588. type = 1;
  589. }
  590. var nearClippingPlane = 1;
  591. if ( cameraAttribute.NearPlane !== undefined ) {
  592. nearClippingPlane = cameraAttribute.NearPlane.value / 1000;
  593. }
  594. var farClippingPlane = 1000;
  595. if ( cameraAttribute.FarPlane !== undefined ) {
  596. farClippingPlane = cameraAttribute.FarPlane.value / 1000;
  597. }
  598. var width = window.innerWidth;
  599. var height = window.innerHeight;
  600. if ( cameraAttribute.AspectWidth !== undefined && cameraAttribute.AspectHeight !== undefined ) {
  601. width = cameraAttribute.AspectWidth.value;
  602. height = cameraAttribute.AspectHeight.value;
  603. }
  604. var aspect = width / height;
  605. var fov = 45;
  606. if ( cameraAttribute.FieldOfView !== undefined ) {
  607. fov = cameraAttribute.FieldOfView.value;
  608. }
  609. var focalLength = cameraAttribute.FocalLength ? cameraAttribute.FocalLength.value : null;
  610. switch ( type ) {
  611. case 0: // Perspective
  612. model = new THREE.PerspectiveCamera( fov, aspect, nearClippingPlane, farClippingPlane );
  613. if ( focalLength !== null ) model.setFocalLength( focalLength );
  614. break;
  615. case 1: // Orthographic
  616. model = new THREE.OrthographicCamera( - width / 2, width / 2, height / 2, - height / 2, nearClippingPlane, farClippingPlane );
  617. break;
  618. default:
  619. console.warn( 'THREE.FBXLoader: Unknown camera type ' + type + '.' );
  620. model = new THREE.Object3D();
  621. break;
  622. }
  623. }
  624. return model;
  625. },
  626. // Create a THREE.DirectionalLight, THREE.PointLight or THREE.SpotLight
  627. createLight: function ( relationships ) {
  628. var model;
  629. var lightAttribute;
  630. relationships.children.forEach( function ( child ) {
  631. var attr = fbxTree.Objects.NodeAttribute[ child.ID ];
  632. if ( attr !== undefined ) {
  633. lightAttribute = attr;
  634. }
  635. } );
  636. if ( lightAttribute === undefined ) {
  637. model = new THREE.Object3D();
  638. } else {
  639. var type;
  640. // LightType can be undefined for Point lights
  641. if ( lightAttribute.LightType === undefined ) {
  642. type = 0;
  643. } else {
  644. type = lightAttribute.LightType.value;
  645. }
  646. var color = 0xffffff;
  647. if ( lightAttribute.Color !== undefined ) {
  648. color = new THREE.Color().fromArray( lightAttribute.Color.value );
  649. }
  650. var intensity = ( lightAttribute.Intensity === undefined ) ? 1 : lightAttribute.Intensity.value / 100;
  651. // light disabled
  652. if ( lightAttribute.CastLightOnObject !== undefined && lightAttribute.CastLightOnObject.value === 0 ) {
  653. intensity = 0;
  654. }
  655. var distance = 0;
  656. if ( lightAttribute.FarAttenuationEnd !== undefined ) {
  657. if ( lightAttribute.EnableFarAttenuation !== undefined && lightAttribute.EnableFarAttenuation.value === 0 ) {
  658. distance = 0;
  659. } else {
  660. distance = lightAttribute.FarAttenuationEnd.value;
  661. }
  662. }
  663. // TODO: could this be calculated linearly from FarAttenuationStart to FarAttenuationEnd?
  664. var decay = 1;
  665. switch ( type ) {
  666. case 0: // Point
  667. model = new THREE.PointLight( color, intensity, distance, decay );
  668. break;
  669. case 1: // Directional
  670. model = new THREE.DirectionalLight( color, intensity );
  671. break;
  672. case 2: // Spot
  673. var angle = Math.PI / 3;
  674. if ( lightAttribute.InnerAngle !== undefined ) {
  675. angle = THREE.MathUtils.degToRad( lightAttribute.InnerAngle.value );
  676. }
  677. var penumbra = 0;
  678. if ( lightAttribute.OuterAngle !== undefined ) {
  679. // TODO: this is not correct - FBX calculates outer and inner angle in degrees
  680. // with OuterAngle > InnerAngle && OuterAngle <= Math.PI
  681. // while three.js uses a penumbra between (0, 1) to attenuate the inner angle
  682. penumbra = THREE.MathUtils.degToRad( lightAttribute.OuterAngle.value );
  683. penumbra = Math.max( penumbra, 1 );
  684. }
  685. model = new THREE.SpotLight( color, intensity, distance, angle, penumbra, decay );
  686. break;
  687. default:
  688. console.warn( 'THREE.FBXLoader: Unknown light type ' + lightAttribute.LightType.value + ', defaulting to a THREE.PointLight.' );
  689. model = new THREE.PointLight( color, intensity );
  690. break;
  691. }
  692. if ( lightAttribute.CastShadows !== undefined && lightAttribute.CastShadows.value === 1 ) {
  693. model.castShadow = true;
  694. }
  695. }
  696. return model;
  697. },
  698. createMesh: function ( relationships, geometryMap, materialMap ) {
  699. var model;
  700. var geometry = null;
  701. var material = null;
  702. var materials = [];
  703. // get geometry and materials(s) from connections
  704. relationships.children.forEach( function ( child ) {
  705. if ( geometryMap.has( child.ID ) ) {
  706. geometry = geometryMap.get( child.ID );
  707. }
  708. if ( materialMap.has( child.ID ) ) {
  709. materials.push( materialMap.get( child.ID ) );
  710. }
  711. } );
  712. if ( materials.length > 1 ) {
  713. material = materials;
  714. } else if ( materials.length > 0 ) {
  715. material = materials[ 0 ];
  716. } else {
  717. material = new THREE.MeshPhongMaterial( { color: 0xcccccc } );
  718. materials.push( material );
  719. }
  720. if ( 'color' in geometry.attributes ) {
  721. materials.forEach( function ( material ) {
  722. material.vertexColors = true;
  723. } );
  724. }
  725. if ( geometry.FBX_Deformer ) {
  726. materials.forEach( function ( material ) {
  727. material.skinning = true;
  728. } );
  729. model = new THREE.SkinnedMesh( geometry, material );
  730. model.normalizeSkinWeights();
  731. } else {
  732. model = new THREE.Mesh( geometry, material );
  733. }
  734. return model;
  735. },
  736. createCurve: function ( relationships, geometryMap ) {
  737. var geometry = relationships.children.reduce( function ( geo, child ) {
  738. if ( geometryMap.has( child.ID ) ) geo = geometryMap.get( child.ID );
  739. return geo;
  740. }, null );
  741. // FBX does not list materials for Nurbs lines, so we'll just put our own in here.
  742. var material = new THREE.LineBasicMaterial( { color: 0x3300ff, linewidth: 1 } );
  743. return new THREE.Line( geometry, material );
  744. },
  745. // parse the model node for transform data
  746. getTransformData: function ( model, modelNode ) {
  747. var transformData = {};
  748. if ( 'InheritType' in modelNode ) transformData.inheritType = parseInt( modelNode.InheritType.value );
  749. if ( 'RotationOrder' in modelNode ) transformData.eulerOrder = getEulerOrder( modelNode.RotationOrder.value );
  750. else transformData.eulerOrder = 'ZYX';
  751. if ( 'Lcl_Translation' in modelNode ) transformData.translation = modelNode.Lcl_Translation.value;
  752. if ( 'PreRotation' in modelNode ) transformData.preRotation = modelNode.PreRotation.value;
  753. if ( 'Lcl_Rotation' in modelNode ) transformData.rotation = modelNode.Lcl_Rotation.value;
  754. if ( 'PostRotation' in modelNode ) transformData.postRotation = modelNode.PostRotation.value;
  755. if ( 'Lcl_Scaling' in modelNode ) transformData.scale = modelNode.Lcl_Scaling.value;
  756. if ( 'ScalingOffset' in modelNode ) transformData.scalingOffset = modelNode.ScalingOffset.value;
  757. if ( 'ScalingPivot' in modelNode ) transformData.scalingPivot = modelNode.ScalingPivot.value;
  758. if ( 'RotationOffset' in modelNode ) transformData.rotationOffset = modelNode.RotationOffset.value;
  759. if ( 'RotationPivot' in modelNode ) transformData.rotationPivot = modelNode.RotationPivot.value;
  760. model.userData.transformData = transformData;
  761. },
  762. setLookAtProperties: function ( model, modelNode ) {
  763. if ( 'LookAtProperty' in modelNode ) {
  764. var children = connections.get( model.ID ).children;
  765. children.forEach( function ( child ) {
  766. if ( child.relationship === 'LookAtProperty' ) {
  767. var lookAtTarget = fbxTree.Objects.Model[ child.ID ];
  768. if ( 'Lcl_Translation' in lookAtTarget ) {
  769. var pos = lookAtTarget.Lcl_Translation.value;
  770. // DirectionalLight, SpotLight
  771. if ( model.target !== undefined ) {
  772. model.target.position.fromArray( pos );
  773. sceneGraph.add( model.target );
  774. } else { // Cameras and other Object3Ds
  775. model.lookAt( new THREE.Vector3().fromArray( pos ) );
  776. }
  777. }
  778. }
  779. } );
  780. }
  781. },
  782. bindSkeleton: function ( skeletons, geometryMap, modelMap ) {
  783. var bindMatrices = this.parsePoseNodes();
  784. for ( var ID in skeletons ) {
  785. var skeleton = skeletons[ ID ];
  786. var parents = connections.get( parseInt( skeleton.ID ) ).parents;
  787. parents.forEach( function ( parent ) {
  788. if ( geometryMap.has( parent.ID ) ) {
  789. var geoID = parent.ID;
  790. var geoRelationships = connections.get( geoID );
  791. geoRelationships.parents.forEach( function ( geoConnParent ) {
  792. if ( modelMap.has( geoConnParent.ID ) ) {
  793. var model = modelMap.get( geoConnParent.ID );
  794. model.bind( new THREE.Skeleton( skeleton.bones ), bindMatrices[ geoConnParent.ID ] );
  795. }
  796. } );
  797. }
  798. } );
  799. }
  800. },
  801. parsePoseNodes: function () {
  802. var bindMatrices = {};
  803. if ( 'Pose' in fbxTree.Objects ) {
  804. var BindPoseNode = fbxTree.Objects.Pose;
  805. for ( var nodeID in BindPoseNode ) {
  806. if ( BindPoseNode[ nodeID ].attrType === 'BindPose' ) {
  807. var poseNodes = BindPoseNode[ nodeID ].PoseNode;
  808. if ( Array.isArray( poseNodes ) ) {
  809. poseNodes.forEach( function ( poseNode ) {
  810. bindMatrices[ poseNode.Node ] = new THREE.Matrix4().fromArray( poseNode.Matrix.a );
  811. } );
  812. } else {
  813. bindMatrices[ poseNodes.Node ] = new THREE.Matrix4().fromArray( poseNodes.Matrix.a );
  814. }
  815. }
  816. }
  817. }
  818. return bindMatrices;
  819. },
  820. // Parse ambient color in FBXTree.GlobalSettings - if it's not set to black (default), create an ambient light
  821. createAmbientLight: function () {
  822. if ( 'GlobalSettings' in fbxTree && 'AmbientColor' in fbxTree.GlobalSettings ) {
  823. var ambientColor = fbxTree.GlobalSettings.AmbientColor.value;
  824. var r = ambientColor[ 0 ];
  825. var g = ambientColor[ 1 ];
  826. var b = ambientColor[ 2 ];
  827. if ( r !== 0 || g !== 0 || b !== 0 ) {
  828. var color = new THREE.Color( r, g, b );
  829. sceneGraph.add( new THREE.AmbientLight( color, 1 ) );
  830. }
  831. }
  832. },
  833. setupMorphMaterials: function () {
  834. var scope = this;
  835. sceneGraph.traverse( function ( child ) {
  836. if ( child.isMesh ) {
  837. if ( child.geometry.morphAttributes.position && child.geometry.morphAttributes.position.length ) {
  838. if ( Array.isArray( child.material ) ) {
  839. child.material.forEach( function ( material, i ) {
  840. scope.setupMorphMaterial( child, material, i );
  841. } );
  842. } else {
  843. scope.setupMorphMaterial( child, child.material );
  844. }
  845. }
  846. }
  847. } );
  848. },
  849. setupMorphMaterial: function ( child, material, index ) {
  850. var uuid = child.uuid;
  851. var matUuid = material.uuid;
  852. // if a geometry has morph targets, it cannot share the material with other geometries
  853. var sharedMat = false;
  854. sceneGraph.traverse( function ( node ) {
  855. if ( node.isMesh ) {
  856. if ( Array.isArray( node.material ) ) {
  857. node.material.forEach( function ( mat ) {
  858. if ( mat.uuid === matUuid && node.uuid !== uuid ) sharedMat = true;
  859. } );
  860. } else if ( node.material.uuid === matUuid && node.uuid !== uuid ) sharedMat = true;
  861. }
  862. } );
  863. if ( sharedMat === true ) {
  864. var clonedMat = material.clone();
  865. clonedMat.morphTargets = true;
  866. if ( index === undefined ) child.material = clonedMat;
  867. else child.material[ index ] = clonedMat;
  868. } else material.morphTargets = true;
  869. }
  870. };
  871. // parse Geometry data from FBXTree and return map of BufferGeometries
  872. function GeometryParser() {}
  873. GeometryParser.prototype = {
  874. constructor: GeometryParser,
  875. // Parse nodes in FBXTree.Objects.Geometry
  876. parse: function ( deformers ) {
  877. var geometryMap = new Map();
  878. if ( 'Geometry' in fbxTree.Objects ) {
  879. var geoNodes = fbxTree.Objects.Geometry;
  880. for ( var nodeID in geoNodes ) {
  881. var relationships = connections.get( parseInt( nodeID ) );
  882. var geo = this.parseGeometry( relationships, geoNodes[ nodeID ], deformers );
  883. geometryMap.set( parseInt( nodeID ), geo );
  884. }
  885. }
  886. return geometryMap;
  887. },
  888. // Parse single node in FBXTree.Objects.Geometry
  889. parseGeometry: function ( relationships, geoNode, deformers ) {
  890. switch ( geoNode.attrType ) {
  891. case 'Mesh':
  892. return this.parseMeshGeometry( relationships, geoNode, deformers );
  893. break;
  894. case 'NurbsCurve':
  895. return this.parseNurbsGeometry( geoNode );
  896. break;
  897. }
  898. },
  899. // Parse single node mesh geometry in FBXTree.Objects.Geometry
  900. parseMeshGeometry: function ( relationships, geoNode, deformers ) {
  901. var skeletons = deformers.skeletons;
  902. var morphTargets = [];
  903. var modelNodes = relationships.parents.map( function ( parent ) {
  904. return fbxTree.Objects.Model[ parent.ID ];
  905. } );
  906. // don't create geometry if it is not associated with any models
  907. if ( modelNodes.length === 0 ) return;
  908. var skeleton = relationships.children.reduce( function ( skeleton, child ) {
  909. if ( skeletons[ child.ID ] !== undefined ) skeleton = skeletons[ child.ID ];
  910. return skeleton;
  911. }, null );
  912. relationships.children.forEach( function ( child ) {
  913. if ( deformers.morphTargets[ child.ID ] !== undefined ) {
  914. morphTargets.push( deformers.morphTargets[ child.ID ] );
  915. }
  916. } );
  917. // Assume one model and get the preRotation from that
  918. // if there is more than one model associated with the geometry this may cause problems
  919. var modelNode = modelNodes[ 0 ];
  920. var transformData = {};
  921. if ( 'RotationOrder' in modelNode ) transformData.eulerOrder = getEulerOrder( modelNode.RotationOrder.value );
  922. if ( 'InheritType' in modelNode ) transformData.inheritType = parseInt( modelNode.InheritType.value );
  923. if ( 'GeometricTranslation' in modelNode ) transformData.translation = modelNode.GeometricTranslation.value;
  924. if ( 'GeometricRotation' in modelNode ) transformData.rotation = modelNode.GeometricRotation.value;
  925. if ( 'GeometricScaling' in modelNode ) transformData.scale = modelNode.GeometricScaling.value;
  926. var transform = generateTransform( transformData );
  927. return this.genGeometry( geoNode, skeleton, morphTargets, transform );
  928. },
  929. // Generate a THREE.BufferGeometry from a node in FBXTree.Objects.Geometry
  930. genGeometry: function ( geoNode, skeleton, morphTargets, preTransform ) {
  931. var geo = new THREE.BufferGeometry();
  932. if ( geoNode.attrName ) geo.name = geoNode.attrName;
  933. var geoInfo = this.parseGeoNode( geoNode, skeleton );
  934. var buffers = this.genBuffers( geoInfo );
  935. var positionAttribute = new THREE.Float32BufferAttribute( buffers.vertex, 3 );
  936. positionAttribute.applyMatrix4( preTransform );
  937. geo.setAttribute( 'position', positionAttribute );
  938. if ( buffers.colors.length > 0 ) {
  939. geo.setAttribute( 'color', new THREE.Float32BufferAttribute( buffers.colors, 3 ) );
  940. }
  941. if ( skeleton ) {
  942. geo.setAttribute( 'skinIndex', new THREE.Uint16BufferAttribute( buffers.weightsIndices, 4 ) );
  943. geo.setAttribute( 'skinWeight', new THREE.Float32BufferAttribute( buffers.vertexWeights, 4 ) );
  944. // used later to bind the skeleton to the model
  945. geo.FBX_Deformer = skeleton;
  946. }
  947. if ( buffers.normal.length > 0 ) {
  948. var normalMatrix = new THREE.Matrix3().getNormalMatrix( preTransform );
  949. var normalAttribute = new THREE.Float32BufferAttribute( buffers.normal, 3 );
  950. normalAttribute.applyNormalMatrix( normalMatrix );
  951. geo.setAttribute( 'normal', normalAttribute );
  952. }
  953. buffers.uvs.forEach( function ( uvBuffer, i ) {
  954. // subsequent uv buffers are called 'uv1', 'uv2', ...
  955. var name = 'uv' + ( i + 1 ).toString();
  956. // the first uv buffer is just called 'uv'
  957. if ( i === 0 ) {
  958. name = 'uv';
  959. }
  960. geo.setAttribute( name, new THREE.Float32BufferAttribute( buffers.uvs[ i ], 2 ) );
  961. } );
  962. if ( geoInfo.material && geoInfo.material.mappingType !== 'AllSame' ) {
  963. // Convert the material indices of each vertex into rendering groups on the geometry.
  964. var prevMaterialIndex = buffers.materialIndex[ 0 ];
  965. var startIndex = 0;
  966. buffers.materialIndex.forEach( function ( currentIndex, i ) {
  967. if ( currentIndex !== prevMaterialIndex ) {
  968. geo.addGroup( startIndex, i - startIndex, prevMaterialIndex );
  969. prevMaterialIndex = currentIndex;
  970. startIndex = i;
  971. }
  972. } );
  973. // the loop above doesn't add the last group, do that here.
  974. if ( geo.groups.length > 0 ) {
  975. var lastGroup = geo.groups[ geo.groups.length - 1 ];
  976. var lastIndex = lastGroup.start + lastGroup.count;
  977. if ( lastIndex !== buffers.materialIndex.length ) {
  978. geo.addGroup( lastIndex, buffers.materialIndex.length - lastIndex, prevMaterialIndex );
  979. }
  980. }
  981. // case where there are multiple materials but the whole geometry is only
  982. // using one of them
  983. if ( geo.groups.length === 0 ) {
  984. geo.addGroup( 0, buffers.materialIndex.length, buffers.materialIndex[ 0 ] );
  985. }
  986. }
  987. this.addMorphTargets( geo, geoNode, morphTargets, preTransform );
  988. return geo;
  989. },
  990. parseGeoNode: function ( geoNode, skeleton ) {
  991. var geoInfo = {};
  992. geoInfo.vertexPositions = ( geoNode.Vertices !== undefined ) ? geoNode.Vertices.a : [];
  993. geoInfo.vertexIndices = ( geoNode.PolygonVertexIndex !== undefined ) ? geoNode.PolygonVertexIndex.a : [];
  994. if ( geoNode.LayerElementColor ) {
  995. geoInfo.color = this.parseVertexColors( geoNode.LayerElementColor[ 0 ] );
  996. }
  997. if ( geoNode.LayerElementMaterial ) {
  998. geoInfo.material = this.parseMaterialIndices( geoNode.LayerElementMaterial[ 0 ] );
  999. }
  1000. if ( geoNode.LayerElementNormal ) {
  1001. geoInfo.normal = this.parseNormals( geoNode.LayerElementNormal[ 0 ] );
  1002. }
  1003. if ( geoNode.LayerElementUV ) {
  1004. geoInfo.uv = [];
  1005. var i = 0;
  1006. while ( geoNode.LayerElementUV[ i ] ) {
  1007. geoInfo.uv.push( this.parseUVs( geoNode.LayerElementUV[ i ] ) );
  1008. i ++;
  1009. }
  1010. }
  1011. geoInfo.weightTable = {};
  1012. if ( skeleton !== null ) {
  1013. geoInfo.skeleton = skeleton;
  1014. skeleton.rawBones.forEach( function ( rawBone, i ) {
  1015. // loop over the bone's vertex indices and weights
  1016. rawBone.indices.forEach( function ( index, j ) {
  1017. if ( geoInfo.weightTable[ index ] === undefined ) geoInfo.weightTable[ index ] = [];
  1018. geoInfo.weightTable[ index ].push( {
  1019. id: i,
  1020. weight: rawBone.weights[ j ],
  1021. } );
  1022. } );
  1023. } );
  1024. }
  1025. return geoInfo;
  1026. },
  1027. genBuffers: function ( geoInfo ) {
  1028. var buffers = {
  1029. vertex: [],
  1030. normal: [],
  1031. colors: [],
  1032. uvs: [],
  1033. materialIndex: [],
  1034. vertexWeights: [],
  1035. weightsIndices: [],
  1036. };
  1037. var polygonIndex = 0;
  1038. var faceLength = 0;
  1039. var displayedWeightsWarning = false;
  1040. // these will hold data for a single face
  1041. var facePositionIndexes = [];
  1042. var faceNormals = [];
  1043. var faceColors = [];
  1044. var faceUVs = [];
  1045. var faceWeights = [];
  1046. var faceWeightIndices = [];
  1047. var scope = this;
  1048. geoInfo.vertexIndices.forEach( function ( vertexIndex, polygonVertexIndex ) {
  1049. var endOfFace = false;
  1050. // Face index and vertex index arrays are combined in a single array
  1051. // A cube with quad faces looks like this:
  1052. // PolygonVertexIndex: *24 {
  1053. // 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
  1054. // }
  1055. // Negative numbers mark the end of a face - first face here is 0, 1, 3, -3
  1056. // to find index of last vertex bit shift the index: ^ - 1
  1057. if ( vertexIndex < 0 ) {
  1058. vertexIndex = vertexIndex ^ - 1; // equivalent to ( x * -1 ) - 1
  1059. endOfFace = true;
  1060. }
  1061. var weightIndices = [];
  1062. var weights = [];
  1063. facePositionIndexes.push( vertexIndex * 3, vertexIndex * 3 + 1, vertexIndex * 3 + 2 );
  1064. if ( geoInfo.color ) {
  1065. var data = getData( polygonVertexIndex, polygonIndex, vertexIndex, geoInfo.color );
  1066. faceColors.push( data[ 0 ], data[ 1 ], data[ 2 ] );
  1067. }
  1068. if ( geoInfo.skeleton ) {
  1069. if ( geoInfo.weightTable[ vertexIndex ] !== undefined ) {
  1070. geoInfo.weightTable[ vertexIndex ].forEach( function ( wt ) {
  1071. weights.push( wt.weight );
  1072. weightIndices.push( wt.id );
  1073. } );
  1074. }
  1075. if ( weights.length > 4 ) {
  1076. if ( ! displayedWeightsWarning ) {
  1077. console.warn( 'THREE.FBXLoader: Vertex has more than 4 skinning weights assigned to vertex. Deleting additional weights.' );
  1078. displayedWeightsWarning = true;
  1079. }
  1080. var wIndex = [ 0, 0, 0, 0 ];
  1081. var Weight = [ 0, 0, 0, 0 ];
  1082. weights.forEach( function ( weight, weightIndex ) {
  1083. var currentWeight = weight;
  1084. var currentIndex = weightIndices[ weightIndex ];
  1085. Weight.forEach( function ( comparedWeight, comparedWeightIndex, comparedWeightArray ) {
  1086. if ( currentWeight > comparedWeight ) {
  1087. comparedWeightArray[ comparedWeightIndex ] = currentWeight;
  1088. currentWeight = comparedWeight;
  1089. var tmp = wIndex[ comparedWeightIndex ];
  1090. wIndex[ comparedWeightIndex ] = currentIndex;
  1091. currentIndex = tmp;
  1092. }
  1093. } );
  1094. } );
  1095. weightIndices = wIndex;
  1096. weights = Weight;
  1097. }
  1098. // if the weight array is shorter than 4 pad with 0s
  1099. while ( weights.length < 4 ) {
  1100. weights.push( 0 );
  1101. weightIndices.push( 0 );
  1102. }
  1103. for ( var i = 0; i < 4; ++ i ) {
  1104. faceWeights.push( weights[ i ] );
  1105. faceWeightIndices.push( weightIndices[ i ] );
  1106. }
  1107. }
  1108. if ( geoInfo.normal ) {
  1109. var data = getData( polygonVertexIndex, polygonIndex, vertexIndex, geoInfo.normal );
  1110. faceNormals.push( data[ 0 ], data[ 1 ], data[ 2 ] );
  1111. }
  1112. if ( geoInfo.material && geoInfo.material.mappingType !== 'AllSame' ) {
  1113. var materialIndex = getData( polygonVertexIndex, polygonIndex, vertexIndex, geoInfo.material )[ 0 ];
  1114. }
  1115. if ( geoInfo.uv ) {
  1116. geoInfo.uv.forEach( function ( uv, i ) {
  1117. var data = getData( polygonVertexIndex, polygonIndex, vertexIndex, uv );
  1118. if ( faceUVs[ i ] === undefined ) {
  1119. faceUVs[ i ] = [];
  1120. }
  1121. faceUVs[ i ].push( data[ 0 ] );
  1122. faceUVs[ i ].push( data[ 1 ] );
  1123. } );
  1124. }
  1125. faceLength ++;
  1126. if ( endOfFace ) {
  1127. scope.genFace( buffers, geoInfo, facePositionIndexes, materialIndex, faceNormals, faceColors, faceUVs, faceWeights, faceWeightIndices, faceLength );
  1128. polygonIndex ++;
  1129. faceLength = 0;
  1130. // reset arrays for the next face
  1131. facePositionIndexes = [];
  1132. faceNormals = [];
  1133. faceColors = [];
  1134. faceUVs = [];
  1135. faceWeights = [];
  1136. faceWeightIndices = [];
  1137. }
  1138. } );
  1139. return buffers;
  1140. },
  1141. // Generate data for a single face in a geometry. If the face is a quad then split it into 2 tris
  1142. genFace: function ( buffers, geoInfo, facePositionIndexes, materialIndex, faceNormals, faceColors, faceUVs, faceWeights, faceWeightIndices, faceLength ) {
  1143. for ( var i = 2; i < faceLength; i ++ ) {
  1144. buffers.vertex.push( geoInfo.vertexPositions[ facePositionIndexes[ 0 ] ] );
  1145. buffers.vertex.push( geoInfo.vertexPositions[ facePositionIndexes[ 1 ] ] );
  1146. buffers.vertex.push( geoInfo.vertexPositions[ facePositionIndexes[ 2 ] ] );
  1147. buffers.vertex.push( geoInfo.vertexPositions[ facePositionIndexes[ ( i - 1 ) * 3 ] ] );
  1148. buffers.vertex.push( geoInfo.vertexPositions[ facePositionIndexes[ ( i - 1 ) * 3 + 1 ] ] );
  1149. buffers.vertex.push( geoInfo.vertexPositions[ facePositionIndexes[ ( i - 1 ) * 3 + 2 ] ] );
  1150. buffers.vertex.push( geoInfo.vertexPositions[ facePositionIndexes[ i * 3 ] ] );
  1151. buffers.vertex.push( geoInfo.vertexPositions[ facePositionIndexes[ i * 3 + 1 ] ] );
  1152. buffers.vertex.push( geoInfo.vertexPositions[ facePositionIndexes[ i * 3 + 2 ] ] );
  1153. if ( geoInfo.skeleton ) {
  1154. buffers.vertexWeights.push( faceWeights[ 0 ] );
  1155. buffers.vertexWeights.push( faceWeights[ 1 ] );
  1156. buffers.vertexWeights.push( faceWeights[ 2 ] );
  1157. buffers.vertexWeights.push( faceWeights[ 3 ] );
  1158. buffers.vertexWeights.push( faceWeights[ ( i - 1 ) * 4 ] );
  1159. buffers.vertexWeights.push( faceWeights[ ( i - 1 ) * 4 + 1 ] );
  1160. buffers.vertexWeights.push( faceWeights[ ( i - 1 ) * 4 + 2 ] );
  1161. buffers.vertexWeights.push( faceWeights[ ( i - 1 ) * 4 + 3 ] );
  1162. buffers.vertexWeights.push( faceWeights[ i * 4 ] );
  1163. buffers.vertexWeights.push( faceWeights[ i * 4 + 1 ] );
  1164. buffers.vertexWeights.push( faceWeights[ i * 4 + 2 ] );
  1165. buffers.vertexWeights.push( faceWeights[ i * 4 + 3 ] );
  1166. buffers.weightsIndices.push( faceWeightIndices[ 0 ] );
  1167. buffers.weightsIndices.push( faceWeightIndices[ 1 ] );
  1168. buffers.weightsIndices.push( faceWeightIndices[ 2 ] );
  1169. buffers.weightsIndices.push( faceWeightIndices[ 3 ] );
  1170. buffers.weightsIndices.push( faceWeightIndices[ ( i - 1 ) * 4 ] );
  1171. buffers.weightsIndices.push( faceWeightIndices[ ( i - 1 ) * 4 + 1 ] );
  1172. buffers.weightsIndices.push( faceWeightIndices[ ( i - 1 ) * 4 + 2 ] );
  1173. buffers.weightsIndices.push( faceWeightIndices[ ( i - 1 ) * 4 + 3 ] );
  1174. buffers.weightsIndices.push( faceWeightIndices[ i * 4 ] );
  1175. buffers.weightsIndices.push( faceWeightIndices[ i * 4 + 1 ] );
  1176. buffers.weightsIndices.push( faceWeightIndices[ i * 4 + 2 ] );
  1177. buffers.weightsIndices.push( faceWeightIndices[ i * 4 + 3 ] );
  1178. }
  1179. if ( geoInfo.color ) {
  1180. buffers.colors.push( faceColors[ 0 ] );
  1181. buffers.colors.push( faceColors[ 1 ] );
  1182. buffers.colors.push( faceColors[ 2 ] );
  1183. buffers.colors.push( faceColors[ ( i - 1 ) * 3 ] );
  1184. buffers.colors.push( faceColors[ ( i - 1 ) * 3 + 1 ] );
  1185. buffers.colors.push( faceColors[ ( i - 1 ) * 3 + 2 ] );
  1186. buffers.colors.push( faceColors[ i * 3 ] );
  1187. buffers.colors.push( faceColors[ i * 3 + 1 ] );
  1188. buffers.colors.push( faceColors[ i * 3 + 2 ] );
  1189. }
  1190. if ( geoInfo.material && geoInfo.material.mappingType !== 'AllSame' ) {
  1191. buffers.materialIndex.push( materialIndex );
  1192. buffers.materialIndex.push( materialIndex );
  1193. buffers.materialIndex.push( materialIndex );
  1194. }
  1195. if ( geoInfo.normal ) {
  1196. buffers.normal.push( faceNormals[ 0 ] );
  1197. buffers.normal.push( faceNormals[ 1 ] );
  1198. buffers.normal.push( faceNormals[ 2 ] );
  1199. buffers.normal.push( faceNormals[ ( i - 1 ) * 3 ] );
  1200. buffers.normal.push( faceNormals[ ( i - 1 ) * 3 + 1 ] );
  1201. buffers.normal.push( faceNormals[ ( i - 1 ) * 3 + 2 ] );
  1202. buffers.normal.push( faceNormals[ i * 3 ] );
  1203. buffers.normal.push( faceNormals[ i * 3 + 1 ] );
  1204. buffers.normal.push( faceNormals[ i * 3 + 2 ] );
  1205. }
  1206. if ( geoInfo.uv ) {
  1207. geoInfo.uv.forEach( function ( uv, j ) {
  1208. if ( buffers.uvs[ j ] === undefined ) buffers.uvs[ j ] = [];
  1209. buffers.uvs[ j ].push( faceUVs[ j ][ 0 ] );
  1210. buffers.uvs[ j ].push( faceUVs[ j ][ 1 ] );
  1211. buffers.uvs[ j ].push( faceUVs[ j ][ ( i - 1 ) * 2 ] );
  1212. buffers.uvs[ j ].push( faceUVs[ j ][ ( i - 1 ) * 2 + 1 ] );
  1213. buffers.uvs[ j ].push( faceUVs[ j ][ i * 2 ] );
  1214. buffers.uvs[ j ].push( faceUVs[ j ][ i * 2 + 1 ] );
  1215. } );
  1216. }
  1217. }
  1218. },
  1219. addMorphTargets: function ( parentGeo, parentGeoNode, morphTargets, preTransform ) {
  1220. if ( morphTargets.length === 0 ) return;
  1221. parentGeo.morphTargetsRelative = true;
  1222. parentGeo.morphAttributes.position = [];
  1223. // parentGeo.morphAttributes.normal = []; // not implemented
  1224. var scope = this;
  1225. morphTargets.forEach( function ( morphTarget ) {
  1226. morphTarget.rawTargets.forEach( function ( rawTarget ) {
  1227. var morphGeoNode = fbxTree.Objects.Geometry[ rawTarget.geoID ];
  1228. if ( morphGeoNode !== undefined ) {
  1229. scope.genMorphGeometry( parentGeo, parentGeoNode, morphGeoNode, preTransform, rawTarget.name );
  1230. }
  1231. } );
  1232. } );
  1233. },
  1234. // a morph geometry node is similar to a standard node, and the node is also contained
  1235. // in FBXTree.Objects.Geometry, however it can only have attributes for position, normal
  1236. // and a special attribute Index defining which vertices of the original geometry are affected
  1237. // Normal and position attributes only have data for the vertices that are affected by the morph
  1238. genMorphGeometry: function ( parentGeo, parentGeoNode, morphGeoNode, preTransform, name ) {
  1239. var vertexIndices = ( parentGeoNode.PolygonVertexIndex !== undefined ) ? parentGeoNode.PolygonVertexIndex.a : [];
  1240. var morphPositionsSparse = ( morphGeoNode.Vertices !== undefined ) ? morphGeoNode.Vertices.a : [];
  1241. var indices = ( morphGeoNode.Indexes !== undefined ) ? morphGeoNode.Indexes.a : [];
  1242. var length = parentGeo.attributes.position.count * 3;
  1243. var morphPositions = new Float32Array( length );
  1244. for ( var i = 0; i < indices.length; i ++ ) {
  1245. var morphIndex = indices[ i ] * 3;
  1246. morphPositions[ morphIndex ] = morphPositionsSparse[ i * 3 ];
  1247. morphPositions[ morphIndex + 1 ] = morphPositionsSparse[ i * 3 + 1 ];
  1248. morphPositions[ morphIndex + 2 ] = morphPositionsSparse[ i * 3 + 2 ];
  1249. }
  1250. // TODO: add morph normal support
  1251. var morphGeoInfo = {
  1252. vertexIndices: vertexIndices,
  1253. vertexPositions: morphPositions,
  1254. };
  1255. var morphBuffers = this.genBuffers( morphGeoInfo );
  1256. var positionAttribute = new THREE.Float32BufferAttribute( morphBuffers.vertex, 3 );
  1257. positionAttribute.name = name || morphGeoNode.attrName;
  1258. positionAttribute.applyMatrix4( preTransform );
  1259. parentGeo.morphAttributes.position.push( positionAttribute );
  1260. },
  1261. // Parse normal from FBXTree.Objects.Geometry.LayerElementNormal if it exists
  1262. parseNormals: function ( NormalNode ) {
  1263. var mappingType = NormalNode.MappingInformationType;
  1264. var referenceType = NormalNode.ReferenceInformationType;
  1265. var buffer = NormalNode.Normals.a;
  1266. var indexBuffer = [];
  1267. if ( referenceType === 'IndexToDirect' ) {
  1268. if ( 'NormalIndex' in NormalNode ) {
  1269. indexBuffer = NormalNode.NormalIndex.a;
  1270. } else if ( 'NormalsIndex' in NormalNode ) {
  1271. indexBuffer = NormalNode.NormalsIndex.a;
  1272. }
  1273. }
  1274. return {
  1275. dataSize: 3,
  1276. buffer: buffer,
  1277. indices: indexBuffer,
  1278. mappingType: mappingType,
  1279. referenceType: referenceType
  1280. };
  1281. },
  1282. // Parse UVs from FBXTree.Objects.Geometry.LayerElementUV if it exists
  1283. parseUVs: function ( UVNode ) {
  1284. var mappingType = UVNode.MappingInformationType;
  1285. var referenceType = UVNode.ReferenceInformationType;
  1286. var buffer = UVNode.UV.a;
  1287. var indexBuffer = [];
  1288. if ( referenceType === 'IndexToDirect' ) {
  1289. indexBuffer = UVNode.UVIndex.a;
  1290. }
  1291. return {
  1292. dataSize: 2,
  1293. buffer: buffer,
  1294. indices: indexBuffer,
  1295. mappingType: mappingType,
  1296. referenceType: referenceType
  1297. };
  1298. },
  1299. // Parse Vertex Colors from FBXTree.Objects.Geometry.LayerElementColor if it exists
  1300. parseVertexColors: function ( ColorNode ) {
  1301. var mappingType = ColorNode.MappingInformationType;
  1302. var referenceType = ColorNode.ReferenceInformationType;
  1303. var buffer = ColorNode.Colors.a;
  1304. var indexBuffer = [];
  1305. if ( referenceType === 'IndexToDirect' ) {
  1306. indexBuffer = ColorNode.ColorIndex.a;
  1307. }
  1308. return {
  1309. dataSize: 4,
  1310. buffer: buffer,
  1311. indices: indexBuffer,
  1312. mappingType: mappingType,
  1313. referenceType: referenceType
  1314. };
  1315. },
  1316. // Parse mapping and material data in FBXTree.Objects.Geometry.LayerElementMaterial if it exists
  1317. parseMaterialIndices: function ( MaterialNode ) {
  1318. var mappingType = MaterialNode.MappingInformationType;
  1319. var referenceType = MaterialNode.ReferenceInformationType;
  1320. if ( mappingType === 'NoMappingInformation' ) {
  1321. return {
  1322. dataSize: 1,
  1323. buffer: [ 0 ],
  1324. indices: [ 0 ],
  1325. mappingType: 'AllSame',
  1326. referenceType: referenceType
  1327. };
  1328. }
  1329. var materialIndexBuffer = MaterialNode.Materials.a;
  1330. // Since materials are stored as indices, there's a bit of a mismatch between FBX and what
  1331. // we expect.So we create an intermediate buffer that points to the index in the buffer,
  1332. // for conforming with the other functions we've written for other data.
  1333. var materialIndices = [];
  1334. for ( var i = 0; i < materialIndexBuffer.length; ++ i ) {
  1335. materialIndices.push( i );
  1336. }
  1337. return {
  1338. dataSize: 1,
  1339. buffer: materialIndexBuffer,
  1340. indices: materialIndices,
  1341. mappingType: mappingType,
  1342. referenceType: referenceType
  1343. };
  1344. },
  1345. // Generate a NurbGeometry from a node in FBXTree.Objects.Geometry
  1346. parseNurbsGeometry: function ( geoNode ) {
  1347. if ( THREE.NURBSCurve === undefined ) {
  1348. console.error( 'THREE.FBXLoader: The loader relies on THREE.NURBSCurve for any nurbs present in the model. Nurbs will show up as empty geometry.' );
  1349. return new THREE.BufferGeometry();
  1350. }
  1351. var order = parseInt( geoNode.Order );
  1352. if ( isNaN( order ) ) {
  1353. console.error( 'THREE.FBXLoader: Invalid Order %s given for geometry ID: %s', geoNode.Order, geoNode.id );
  1354. return new THREE.BufferGeometry();
  1355. }
  1356. var degree = order - 1;
  1357. var knots = geoNode.KnotVector.a;
  1358. var controlPoints = [];
  1359. var pointsValues = geoNode.Points.a;
  1360. for ( var i = 0, l = pointsValues.length; i < l; i += 4 ) {
  1361. controlPoints.push( new THREE.Vector4().fromArray( pointsValues, i ) );
  1362. }
  1363. var startKnot, endKnot;
  1364. if ( geoNode.Form === 'Closed' ) {
  1365. controlPoints.push( controlPoints[ 0 ] );
  1366. } else if ( geoNode.Form === 'Periodic' ) {
  1367. startKnot = degree;
  1368. endKnot = knots.length - 1 - startKnot;
  1369. for ( var i = 0; i < degree; ++ i ) {
  1370. controlPoints.push( controlPoints[ i ] );
  1371. }
  1372. }
  1373. var curve = new THREE.NURBSCurve( degree, knots, controlPoints, startKnot, endKnot );
  1374. var vertices = curve.getPoints( controlPoints.length * 7 );
  1375. var positions = new Float32Array( vertices.length * 3 );
  1376. vertices.forEach( function ( vertex, i ) {
  1377. vertex.toArray( positions, i * 3 );
  1378. } );
  1379. var geometry = new THREE.BufferGeometry();
  1380. geometry.setAttribute( 'position', new THREE.BufferAttribute( positions, 3 ) );
  1381. return geometry;
  1382. },
  1383. };
  1384. // parse animation data from FBXTree
  1385. function AnimationParser() {}
  1386. AnimationParser.prototype = {
  1387. constructor: AnimationParser,
  1388. // take raw animation clips and turn them into three.js animation clips
  1389. parse: function () {
  1390. var animationClips = [];
  1391. var rawClips = this.parseClips();
  1392. if ( rawClips !== undefined ) {
  1393. for ( var key in rawClips ) {
  1394. var rawClip = rawClips[ key ];
  1395. var clip = this.addClip( rawClip );
  1396. animationClips.push( clip );
  1397. }
  1398. }
  1399. return animationClips;
  1400. },
  1401. parseClips: function () {
  1402. // since the actual transformation data is stored in FBXTree.Objects.AnimationCurve,
  1403. // if this is undefined we can safely assume there are no animations
  1404. if ( fbxTree.Objects.AnimationCurve === undefined ) return undefined;
  1405. var curveNodesMap = this.parseAnimationCurveNodes();
  1406. this.parseAnimationCurves( curveNodesMap );
  1407. var layersMap = this.parseAnimationLayers( curveNodesMap );
  1408. var rawClips = this.parseAnimStacks( layersMap );
  1409. return rawClips;
  1410. },
  1411. // parse nodes in FBXTree.Objects.AnimationCurveNode
  1412. // each AnimationCurveNode holds data for an animation transform for a model (e.g. left arm rotation )
  1413. // and is referenced by an AnimationLayer
  1414. parseAnimationCurveNodes: function () {
  1415. var rawCurveNodes = fbxTree.Objects.AnimationCurveNode;
  1416. var curveNodesMap = new Map();
  1417. for ( var nodeID in rawCurveNodes ) {
  1418. var rawCurveNode = rawCurveNodes[ nodeID ];
  1419. if ( rawCurveNode.attrName.match( /S|R|T|DeformPercent/ ) !== null ) {
  1420. var curveNode = {
  1421. id: rawCurveNode.id,
  1422. attr: rawCurveNode.attrName,
  1423. curves: {},
  1424. };
  1425. curveNodesMap.set( curveNode.id, curveNode );
  1426. }
  1427. }
  1428. return curveNodesMap;
  1429. },
  1430. // parse nodes in FBXTree.Objects.AnimationCurve and connect them up to
  1431. // previously parsed AnimationCurveNodes. Each AnimationCurve holds data for a single animated
  1432. // axis ( e.g. times and values of x rotation)
  1433. parseAnimationCurves: function ( curveNodesMap ) {
  1434. var rawCurves = fbxTree.Objects.AnimationCurve;
  1435. // TODO: Many values are identical up to roundoff error, but won't be optimised
  1436. // e.g. position times: [0, 0.4, 0. 8]
  1437. // position values: [7.23538335023477e-7, 93.67518615722656, -0.9982695579528809, 7.23538335023477e-7, 93.67518615722656, -0.9982695579528809, 7.235384487103147e-7, 93.67520904541016, -0.9982695579528809]
  1438. // clearly, this should be optimised to
  1439. // times: [0], positions [7.23538335023477e-7, 93.67518615722656, -0.9982695579528809]
  1440. // this shows up in nearly every FBX file, and generally time array is length > 100
  1441. for ( var nodeID in rawCurves ) {
  1442. var animationCurve = {
  1443. id: rawCurves[ nodeID ].id,
  1444. times: rawCurves[ nodeID ].KeyTime.a.map( convertFBXTimeToSeconds ),
  1445. values: rawCurves[ nodeID ].KeyValueFloat.a,
  1446. };
  1447. var relationships = connections.get( animationCurve.id );
  1448. if ( relationships !== undefined ) {
  1449. var animationCurveID = relationships.parents[ 0 ].ID;
  1450. var animationCurveRelationship = relationships.parents[ 0 ].relationship;
  1451. if ( animationCurveRelationship.match( /X/ ) ) {
  1452. curveNodesMap.get( animationCurveID ).curves[ 'x' ] = animationCurve;
  1453. } else if ( animationCurveRelationship.match( /Y/ ) ) {
  1454. curveNodesMap.get( animationCurveID ).curves[ 'y' ] = animationCurve;
  1455. } else if ( animationCurveRelationship.match( /Z/ ) ) {
  1456. curveNodesMap.get( animationCurveID ).curves[ 'z' ] = animationCurve;
  1457. } else if ( animationCurveRelationship.match( /d|DeformPercent/ ) && curveNodesMap.has( animationCurveID ) ) {
  1458. curveNodesMap.get( animationCurveID ).curves[ 'morph' ] = animationCurve;
  1459. }
  1460. }
  1461. }
  1462. },
  1463. // parse nodes in FBXTree.Objects.AnimationLayer. Each layers holds references
  1464. // to various AnimationCurveNodes and is referenced by an AnimationStack node
  1465. // note: theoretically a stack can have multiple layers, however in practice there always seems to be one per stack
  1466. parseAnimationLayers: function ( curveNodesMap ) {
  1467. var rawLayers = fbxTree.Objects.AnimationLayer;
  1468. var layersMap = new Map();
  1469. for ( var nodeID in rawLayers ) {
  1470. var layerCurveNodes = [];
  1471. var connection = connections.get( parseInt( nodeID ) );
  1472. if ( connection !== undefined ) {
  1473. // all the animationCurveNodes used in the layer
  1474. var children = connection.children;
  1475. children.forEach( function ( child, i ) {
  1476. if ( curveNodesMap.has( child.ID ) ) {
  1477. var curveNode = curveNodesMap.get( child.ID );
  1478. // check that the curves are defined for at least one axis, otherwise ignore the curveNode
  1479. if ( curveNode.curves.x !== undefined || curveNode.curves.y !== undefined || curveNode.curves.z !== undefined ) {
  1480. if ( layerCurveNodes[ i ] === undefined ) {
  1481. var modelID = connections.get( child.ID ).parents.filter( function ( parent ) {
  1482. return parent.relationship !== undefined;
  1483. } )[ 0 ].ID;
  1484. if ( modelID !== undefined ) {
  1485. var rawModel = fbxTree.Objects.Model[ modelID.toString() ];
  1486. if ( rawModel === undefined ) {
  1487. console.warn( 'THREE.FBXLoader: Encountered a unused curve.', child );
  1488. return;
  1489. }
  1490. var node = {
  1491. modelName: rawModel.attrName ? THREE.PropertyBinding.sanitizeNodeName( rawModel.attrName ) : '',
  1492. ID: rawModel.id,
  1493. initialPosition: [ 0, 0, 0 ],
  1494. initialRotation: [ 0, 0, 0 ],
  1495. initialScale: [ 1, 1, 1 ],
  1496. };
  1497. sceneGraph.traverse( function ( child ) {
  1498. if ( child.ID === rawModel.id ) {
  1499. node.transform = child.matrix;
  1500. if ( child.userData.transformData ) node.eulerOrder = child.userData.transformData.eulerOrder;
  1501. }
  1502. } );
  1503. if ( ! node.transform ) node.transform = new THREE.Matrix4();
  1504. // if the animated model is pre rotated, we'll have to apply the pre rotations to every
  1505. // animation value as well
  1506. if ( 'PreRotation' in rawModel ) node.preRotation = rawModel.PreRotation.value;
  1507. if ( 'PostRotation' in rawModel ) node.postRotation = rawModel.PostRotation.value;
  1508. layerCurveNodes[ i ] = node;
  1509. }
  1510. }
  1511. if ( layerCurveNodes[ i ] ) layerCurveNodes[ i ][ curveNode.attr ] = curveNode;
  1512. } else if ( curveNode.curves.morph !== undefined ) {
  1513. if ( layerCurveNodes[ i ] === undefined ) {
  1514. var deformerID = connections.get( child.ID ).parents.filter( function ( parent ) {
  1515. return parent.relationship !== undefined;
  1516. } )[ 0 ].ID;
  1517. var morpherID = connections.get( deformerID ).parents[ 0 ].ID;
  1518. var geoID = connections.get( morpherID ).parents[ 0 ].ID;
  1519. // assuming geometry is not used in more than one model
  1520. var modelID = connections.get( geoID ).parents[ 0 ].ID;
  1521. var rawModel = fbxTree.Objects.Model[ modelID ];
  1522. var node = {
  1523. modelName: rawModel.attrName ? THREE.PropertyBinding.sanitizeNodeName( rawModel.attrName ) : '',
  1524. morphName: fbxTree.Objects.Deformer[ deformerID ].attrName,
  1525. };
  1526. layerCurveNodes[ i ] = node;
  1527. }
  1528. layerCurveNodes[ i ][ curveNode.attr ] = curveNode;
  1529. }
  1530. }
  1531. } );
  1532. layersMap.set( parseInt( nodeID ), layerCurveNodes );
  1533. }
  1534. }
  1535. return layersMap;
  1536. },
  1537. // parse nodes in FBXTree.Objects.AnimationStack. These are the top level node in the animation
  1538. // hierarchy. Each Stack node will be used to create a THREE.AnimationClip
  1539. parseAnimStacks: function ( layersMap ) {
  1540. var rawStacks = fbxTree.Objects.AnimationStack;
  1541. // connect the stacks (clips) up to the layers
  1542. var rawClips = {};
  1543. for ( var nodeID in rawStacks ) {
  1544. var children = connections.get( parseInt( nodeID ) ).children;
  1545. if ( children.length > 1 ) {
  1546. // it seems like stacks will always be associated with a single layer. But just in case there are files
  1547. // where there are multiple layers per stack, we'll display a warning
  1548. console.warn( 'THREE.FBXLoader: Encountered an animation stack with multiple layers, this is currently not supported. Ignoring subsequent layers.' );
  1549. }
  1550. var layer = layersMap.get( children[ 0 ].ID );
  1551. rawClips[ nodeID ] = {
  1552. name: rawStacks[ nodeID ].attrName,
  1553. layer: layer,
  1554. };
  1555. }
  1556. return rawClips;
  1557. },
  1558. addClip: function ( rawClip ) {
  1559. var tracks = [];
  1560. var scope = this;
  1561. rawClip.layer.forEach( function ( rawTracks ) {
  1562. tracks = tracks.concat( scope.generateTracks( rawTracks ) );
  1563. } );
  1564. return new THREE.AnimationClip( rawClip.name, - 1, tracks );
  1565. },
  1566. generateTracks: function ( rawTracks ) {
  1567. var tracks = [];
  1568. var initialPosition = new THREE.Vector3();
  1569. var initialRotation = new THREE.Quaternion();
  1570. var initialScale = new THREE.Vector3();
  1571. if ( rawTracks.transform ) rawTracks.transform.decompose( initialPosition, initialRotation, initialScale );
  1572. initialPosition = initialPosition.toArray();
  1573. initialRotation = new THREE.Euler().setFromQuaternion( initialRotation, rawTracks.eulerOrder ).toArray();
  1574. initialScale = initialScale.toArray();
  1575. if ( rawTracks.T !== undefined && Object.keys( rawTracks.T.curves ).length > 0 ) {
  1576. var positionTrack = this.generateVectorTrack( rawTracks.modelName, rawTracks.T.curves, initialPosition, 'position' );
  1577. if ( positionTrack !== undefined ) tracks.push( positionTrack );
  1578. }
  1579. if ( rawTracks.R !== undefined && Object.keys( rawTracks.R.curves ).length > 0 ) {
  1580. var rotationTrack = this.generateRotationTrack( rawTracks.modelName, rawTracks.R.curves, initialRotation, rawTracks.preRotation, rawTracks.postRotation, rawTracks.eulerOrder );
  1581. if ( rotationTrack !== undefined ) tracks.push( rotationTrack );
  1582. }
  1583. if ( rawTracks.S !== undefined && Object.keys( rawTracks.S.curves ).length > 0 ) {
  1584. var scaleTrack = this.generateVectorTrack( rawTracks.modelName, rawTracks.S.curves, initialScale, 'scale' );
  1585. if ( scaleTrack !== undefined ) tracks.push( scaleTrack );
  1586. }
  1587. if ( rawTracks.DeformPercent !== undefined ) {
  1588. var morphTrack = this.generateMorphTrack( rawTracks );
  1589. if ( morphTrack !== undefined ) tracks.push( morphTrack );
  1590. }
  1591. return tracks;
  1592. },
  1593. generateVectorTrack: function ( modelName, curves, initialValue, type ) {
  1594. var times = this.getTimesForAllAxes( curves );
  1595. var values = this.getKeyframeTrackValues( times, curves, initialValue );
  1596. return new THREE.VectorKeyframeTrack( modelName + '.' + type, times, values );
  1597. },
  1598. generateRotationTrack: function ( modelName, curves, initialValue, preRotation, postRotation, eulerOrder ) {
  1599. if ( curves.x !== undefined ) {
  1600. this.interpolateRotations( curves.x );
  1601. curves.x.values = curves.x.values.map( THREE.MathUtils.degToRad );
  1602. }
  1603. if ( curves.y !== undefined ) {
  1604. this.interpolateRotations( curves.y );
  1605. curves.y.values = curves.y.values.map( THREE.MathUtils.degToRad );
  1606. }
  1607. if ( curves.z !== undefined ) {
  1608. this.interpolateRotations( curves.z );
  1609. curves.z.values = curves.z.values.map( THREE.MathUtils.degToRad );
  1610. }
  1611. var times = this.getTimesForAllAxes( curves );
  1612. var values = this.getKeyframeTrackValues( times, curves, initialValue );
  1613. if ( preRotation !== undefined ) {
  1614. preRotation = preRotation.map( THREE.MathUtils.degToRad );
  1615. preRotation.push( eulerOrder );
  1616. preRotation = new THREE.Euler().fromArray( preRotation );
  1617. preRotation = new THREE.Quaternion().setFromEuler( preRotation );
  1618. }
  1619. if ( postRotation !== undefined ) {
  1620. postRotation = postRotation.map( THREE.MathUtils.degToRad );
  1621. postRotation.push( eulerOrder );
  1622. postRotation = new THREE.Euler().fromArray( postRotation );
  1623. postRotation = new THREE.Quaternion().setFromEuler( postRotation ).inverse();
  1624. }
  1625. var quaternion = new THREE.Quaternion();
  1626. var euler = new THREE.Euler();
  1627. var quaternionValues = [];
  1628. for ( var i = 0; i < values.length; i += 3 ) {
  1629. euler.set( values[ i ], values[ i + 1 ], values[ i + 2 ], eulerOrder );
  1630. quaternion.setFromEuler( euler );
  1631. if ( preRotation !== undefined ) quaternion.premultiply( preRotation );
  1632. if ( postRotation !== undefined ) quaternion.multiply( postRotation );
  1633. quaternion.toArray( quaternionValues, ( i / 3 ) * 4 );
  1634. }
  1635. return new THREE.QuaternionKeyframeTrack( modelName + '.quaternion', times, quaternionValues );
  1636. },
  1637. generateMorphTrack: function ( rawTracks ) {
  1638. var curves = rawTracks.DeformPercent.curves.morph;
  1639. var values = curves.values.map( function ( val ) {
  1640. return val / 100;
  1641. } );
  1642. var morphNum = sceneGraph.getObjectByName( rawTracks.modelName ).morphTargetDictionary[ rawTracks.morphName ];
  1643. return new THREE.NumberKeyframeTrack( rawTracks.modelName + '.morphTargetInfluences[' + morphNum + ']', curves.times, values );
  1644. },
  1645. // For all animated objects, times are defined separately for each axis
  1646. // Here we'll combine the times into one sorted array without duplicates
  1647. getTimesForAllAxes: function ( curves ) {
  1648. var times = [];
  1649. // first join together the times for each axis, if defined
  1650. if ( curves.x !== undefined ) times = times.concat( curves.x.times );
  1651. if ( curves.y !== undefined ) times = times.concat( curves.y.times );
  1652. if ( curves.z !== undefined ) times = times.concat( curves.z.times );
  1653. // then sort them and remove duplicates
  1654. times = times.sort( function ( a, b ) {
  1655. return a - b;
  1656. } ).filter( function ( elem, index, array ) {
  1657. return array.indexOf( elem ) == index;
  1658. } );
  1659. return times;
  1660. },
  1661. getKeyframeTrackValues: function ( times, curves, initialValue ) {
  1662. var prevValue = initialValue;
  1663. var values = [];
  1664. var xIndex = - 1;
  1665. var yIndex = - 1;
  1666. var zIndex = - 1;
  1667. times.forEach( function ( time ) {
  1668. if ( curves.x ) xIndex = curves.x.times.indexOf( time );
  1669. if ( curves.y ) yIndex = curves.y.times.indexOf( time );
  1670. if ( curves.z ) zIndex = curves.z.times.indexOf( time );
  1671. // if there is an x value defined for this frame, use that
  1672. if ( xIndex !== - 1 ) {
  1673. var xValue = curves.x.values[ xIndex ];
  1674. values.push( xValue );
  1675. prevValue[ 0 ] = xValue;
  1676. } else {
  1677. // otherwise use the x value from the previous frame
  1678. values.push( prevValue[ 0 ] );
  1679. }
  1680. if ( yIndex !== - 1 ) {
  1681. var yValue = curves.y.values[ yIndex ];
  1682. values.push( yValue );
  1683. prevValue[ 1 ] = yValue;
  1684. } else {
  1685. values.push( prevValue[ 1 ] );
  1686. }
  1687. if ( zIndex !== - 1 ) {
  1688. var zValue = curves.z.values[ zIndex ];
  1689. values.push( zValue );
  1690. prevValue[ 2 ] = zValue;
  1691. } else {
  1692. values.push( prevValue[ 2 ] );
  1693. }
  1694. } );
  1695. return values;
  1696. },
  1697. // Rotations are defined as Euler angles which can have values of any size
  1698. // These will be converted to quaternions which don't support values greater than
  1699. // PI, so we'll interpolate large rotations
  1700. interpolateRotations: function ( curve ) {
  1701. for ( var i = 1; i < curve.values.length; i ++ ) {
  1702. var initialValue = curve.values[ i - 1 ];
  1703. var valuesSpan = curve.values[ i ] - initialValue;
  1704. var absoluteSpan = Math.abs( valuesSpan );
  1705. if ( absoluteSpan >= 180 ) {
  1706. var numSubIntervals = absoluteSpan / 180;
  1707. var step = valuesSpan / numSubIntervals;
  1708. var nextValue = initialValue + step;
  1709. var initialTime = curve.times[ i - 1 ];
  1710. var timeSpan = curve.times[ i ] - initialTime;
  1711. var interval = timeSpan / numSubIntervals;
  1712. var nextTime = initialTime + interval;
  1713. var interpolatedTimes = [];
  1714. var interpolatedValues = [];
  1715. while ( nextTime < curve.times[ i ] ) {
  1716. interpolatedTimes.push( nextTime );
  1717. nextTime += interval;
  1718. interpolatedValues.push( nextValue );
  1719. nextValue += step;
  1720. }
  1721. curve.times = inject( curve.times, i, interpolatedTimes );
  1722. curve.values = inject( curve.values, i, interpolatedValues );
  1723. }
  1724. }
  1725. },
  1726. };
  1727. // parse an FBX file in ASCII format
  1728. function TextParser() {}
  1729. TextParser.prototype = {
  1730. constructor: TextParser,
  1731. getPrevNode: function () {
  1732. return this.nodeStack[ this.currentIndent - 2 ];
  1733. },
  1734. getCurrentNode: function () {
  1735. return this.nodeStack[ this.currentIndent - 1 ];
  1736. },
  1737. getCurrentProp: function () {
  1738. return this.currentProp;
  1739. },
  1740. pushStack: function ( node ) {
  1741. this.nodeStack.push( node );
  1742. this.currentIndent += 1;
  1743. },
  1744. popStack: function () {
  1745. this.nodeStack.pop();
  1746. this.currentIndent -= 1;
  1747. },
  1748. setCurrentProp: function ( val, name ) {
  1749. this.currentProp = val;
  1750. this.currentPropName = name;
  1751. },
  1752. parse: function ( text ) {
  1753. this.currentIndent = 0;
  1754. this.allNodes = new FBXTree();
  1755. this.nodeStack = [];
  1756. this.currentProp = [];
  1757. this.currentPropName = '';
  1758. var scope = this;
  1759. var split = text.split( /[\r\n]+/ );
  1760. split.forEach( function ( line, i ) {
  1761. var matchComment = line.match( /^[\s\t]*;/ );
  1762. var matchEmpty = line.match( /^[\s\t]*$/ );
  1763. if ( matchComment || matchEmpty ) return;
  1764. var matchBeginning = line.match( '^\\t{' + scope.currentIndent + '}(\\w+):(.*){', '' );
  1765. var matchProperty = line.match( '^\\t{' + ( scope.currentIndent ) + '}(\\w+):[\\s\\t\\r\\n](.*)' );
  1766. var matchEnd = line.match( '^\\t{' + ( scope.currentIndent - 1 ) + '}}' );
  1767. if ( matchBeginning ) {
  1768. scope.parseNodeBegin( line, matchBeginning );
  1769. } else if ( matchProperty ) {
  1770. scope.parseNodeProperty( line, matchProperty, split[ ++ i ] );
  1771. } else if ( matchEnd ) {
  1772. scope.popStack();
  1773. } else if ( line.match( /^[^\s\t}]/ ) ) {
  1774. // large arrays are split over multiple lines terminated with a ',' character
  1775. // if this is encountered the line needs to be joined to the previous line
  1776. scope.parseNodePropertyContinued( line );
  1777. }
  1778. } );
  1779. return this.allNodes;
  1780. },
  1781. parseNodeBegin: function ( line, property ) {
  1782. var nodeName = property[ 1 ].trim().replace( /^"/, '' ).replace( /"$/, '' );
  1783. var nodeAttrs = property[ 2 ].split( ',' ).map( function ( attr ) {
  1784. return attr.trim().replace( /^"/, '' ).replace( /"$/, '' );
  1785. } );
  1786. var node = { name: nodeName };
  1787. var attrs = this.parseNodeAttr( nodeAttrs );
  1788. var currentNode = this.getCurrentNode();
  1789. // a top node
  1790. if ( this.currentIndent === 0 ) {
  1791. this.allNodes.add( nodeName, node );
  1792. } else { // a subnode
  1793. // if the subnode already exists, append it
  1794. if ( nodeName in currentNode ) {
  1795. // special case Pose needs PoseNodes as an array
  1796. if ( nodeName === 'PoseNode' ) {
  1797. currentNode.PoseNode.push( node );
  1798. } else if ( currentNode[ nodeName ].id !== undefined ) {
  1799. currentNode[ nodeName ] = {};
  1800. currentNode[ nodeName ][ currentNode[ nodeName ].id ] = currentNode[ nodeName ];
  1801. }
  1802. if ( attrs.id !== '' ) currentNode[ nodeName ][ attrs.id ] = node;
  1803. } else if ( typeof attrs.id === 'number' ) {
  1804. currentNode[ nodeName ] = {};
  1805. currentNode[ nodeName ][ attrs.id ] = node;
  1806. } else if ( nodeName !== 'Properties70' ) {
  1807. if ( nodeName === 'PoseNode' ) currentNode[ nodeName ] = [ node ];
  1808. else currentNode[ nodeName ] = node;
  1809. }
  1810. }
  1811. if ( typeof attrs.id === 'number' ) node.id = attrs.id;
  1812. if ( attrs.name !== '' ) node.attrName = attrs.name;
  1813. if ( attrs.type !== '' ) node.attrType = attrs.type;
  1814. this.pushStack( node );
  1815. },
  1816. parseNodeAttr: function ( attrs ) {
  1817. var id = attrs[ 0 ];
  1818. if ( attrs[ 0 ] !== '' ) {
  1819. id = parseInt( attrs[ 0 ] );
  1820. if ( isNaN( id ) ) {
  1821. id = attrs[ 0 ];
  1822. }
  1823. }
  1824. var name = '', type = '';
  1825. if ( attrs.length > 1 ) {
  1826. name = attrs[ 1 ].replace( /^(\w+)::/, '' );
  1827. type = attrs[ 2 ];
  1828. }
  1829. return { id: id, name: name, type: type };
  1830. },
  1831. parseNodeProperty: function ( line, property, contentLine ) {
  1832. var propName = property[ 1 ].replace( /^"/, '' ).replace( /"$/, '' ).trim();
  1833. var propValue = property[ 2 ].replace( /^"/, '' ).replace( /"$/, '' ).trim();
  1834. // for special case: base64 image data follows "Content: ," line
  1835. // Content: ,
  1836. // "/9j/4RDaRXhpZgAATU0A..."
  1837. if ( propName === 'Content' && propValue === ',' ) {
  1838. propValue = contentLine.replace( /"/g, '' ).replace( /,$/, '' ).trim();
  1839. }
  1840. var currentNode = this.getCurrentNode();
  1841. var parentName = currentNode.name;
  1842. if ( parentName === 'Properties70' ) {
  1843. this.parseNodeSpecialProperty( line, propName, propValue );
  1844. return;
  1845. }
  1846. // Connections
  1847. if ( propName === 'C' ) {
  1848. var connProps = propValue.split( ',' ).slice( 1 );
  1849. var from = parseInt( connProps[ 0 ] );
  1850. var to = parseInt( connProps[ 1 ] );
  1851. var rest = propValue.split( ',' ).slice( 3 );
  1852. rest = rest.map( function ( elem ) {
  1853. return elem.trim().replace( /^"/, '' );
  1854. } );
  1855. propName = 'connections';
  1856. propValue = [ from, to ];
  1857. append( propValue, rest );
  1858. if ( currentNode[ propName ] === undefined ) {
  1859. currentNode[ propName ] = [];
  1860. }
  1861. }
  1862. // Node
  1863. if ( propName === 'Node' ) currentNode.id = propValue;
  1864. // connections
  1865. if ( propName in currentNode && Array.isArray( currentNode[ propName ] ) ) {
  1866. currentNode[ propName ].push( propValue );
  1867. } else {
  1868. if ( propName !== 'a' ) currentNode[ propName ] = propValue;
  1869. else currentNode.a = propValue;
  1870. }
  1871. this.setCurrentProp( currentNode, propName );
  1872. // convert string to array, unless it ends in ',' in which case more will be added to it
  1873. if ( propName === 'a' && propValue.slice( - 1 ) !== ',' ) {
  1874. currentNode.a = parseNumberArray( propValue );
  1875. }
  1876. },
  1877. parseNodePropertyContinued: function ( line ) {
  1878. var currentNode = this.getCurrentNode();
  1879. currentNode.a += line;
  1880. // if the line doesn't end in ',' we have reached the end of the property value
  1881. // so convert the string to an array
  1882. if ( line.slice( - 1 ) !== ',' ) {
  1883. currentNode.a = parseNumberArray( currentNode.a );
  1884. }
  1885. },
  1886. // parse "Property70"
  1887. parseNodeSpecialProperty: function ( line, propName, propValue ) {
  1888. // split this
  1889. // P: "Lcl Scaling", "Lcl Scaling", "", "A",1,1,1
  1890. // into array like below
  1891. // ["Lcl Scaling", "Lcl Scaling", "", "A", "1,1,1" ]
  1892. var props = propValue.split( '",' ).map( function ( prop ) {
  1893. return prop.trim().replace( /^\"/, '' ).replace( /\s/, '_' );
  1894. } );
  1895. var innerPropName = props[ 0 ];
  1896. var innerPropType1 = props[ 1 ];
  1897. var innerPropType2 = props[ 2 ];
  1898. var innerPropFlag = props[ 3 ];
  1899. var innerPropValue = props[ 4 ];
  1900. // cast values where needed, otherwise leave as strings
  1901. switch ( innerPropType1 ) {
  1902. case 'int':
  1903. case 'enum':
  1904. case 'bool':
  1905. case 'ULongLong':
  1906. case 'double':
  1907. case 'Number':
  1908. case 'FieldOfView':
  1909. innerPropValue = parseFloat( innerPropValue );
  1910. break;
  1911. case 'Color':
  1912. case 'ColorRGB':
  1913. case 'Vector3D':
  1914. case 'Lcl_Translation':
  1915. case 'Lcl_Rotation':
  1916. case 'Lcl_Scaling':
  1917. innerPropValue = parseNumberArray( innerPropValue );
  1918. break;
  1919. }
  1920. // CAUTION: these props must append to parent's parent
  1921. this.getPrevNode()[ innerPropName ] = {
  1922. 'type': innerPropType1,
  1923. 'type2': innerPropType2,
  1924. 'flag': innerPropFlag,
  1925. 'value': innerPropValue
  1926. };
  1927. this.setCurrentProp( this.getPrevNode(), innerPropName );
  1928. },
  1929. };
  1930. // Parse an FBX file in Binary format
  1931. function BinaryParser() {}
  1932. BinaryParser.prototype = {
  1933. constructor: BinaryParser,
  1934. parse: function ( buffer ) {
  1935. var reader = new BinaryReader( buffer );
  1936. reader.skip( 23 ); // skip magic 23 bytes
  1937. var version = reader.getUint32();
  1938. if ( version < 6400 ) {
  1939. throw new Error( 'THREE.FBXLoader: FBX version not supported, FileVersion: ' + version );
  1940. }
  1941. var allNodes = new FBXTree();
  1942. while ( ! this.endOfContent( reader ) ) {
  1943. var node = this.parseNode( reader, version );
  1944. if ( node !== null ) allNodes.add( node.name, node );
  1945. }
  1946. return allNodes;
  1947. },
  1948. // Check if reader has reached the end of content.
  1949. endOfContent: function ( reader ) {
  1950. // footer size: 160bytes + 16-byte alignment padding
  1951. // - 16bytes: magic
  1952. // - padding til 16-byte alignment (at least 1byte?)
  1953. // (seems like some exporters embed fixed 15 or 16bytes?)
  1954. // - 4bytes: magic
  1955. // - 4bytes: version
  1956. // - 120bytes: zero
  1957. // - 16bytes: magic
  1958. if ( reader.size() % 16 === 0 ) {
  1959. return ( ( reader.getOffset() + 160 + 16 ) & ~ 0xf ) >= reader.size();
  1960. } else {
  1961. return reader.getOffset() + 160 + 16 >= reader.size();
  1962. }
  1963. },
  1964. // recursively parse nodes until the end of the file is reached
  1965. parseNode: function ( reader, version ) {
  1966. var node = {};
  1967. // The first three data sizes depends on version.
  1968. var endOffset = ( version >= 7500 ) ? reader.getUint64() : reader.getUint32();
  1969. var numProperties = ( version >= 7500 ) ? reader.getUint64() : reader.getUint32();
  1970. ( version >= 7500 ) ? reader.getUint64() : reader.getUint32(); // the returned propertyListLen is not used
  1971. var nameLen = reader.getUint8();
  1972. var name = reader.getString( nameLen );
  1973. // Regards this node as NULL-record if endOffset is zero
  1974. if ( endOffset === 0 ) return null;
  1975. var propertyList = [];
  1976. for ( var i = 0; i < numProperties; i ++ ) {
  1977. propertyList.push( this.parseProperty( reader ) );
  1978. }
  1979. // Regards the first three elements in propertyList as id, attrName, and attrType
  1980. var id = propertyList.length > 0 ? propertyList[ 0 ] : '';
  1981. var attrName = propertyList.length > 1 ? propertyList[ 1 ] : '';
  1982. var attrType = propertyList.length > 2 ? propertyList[ 2 ] : '';
  1983. // check if this node represents just a single property
  1984. // like (name, 0) set or (name2, [0, 1, 2]) set of {name: 0, name2: [0, 1, 2]}
  1985. node.singleProperty = ( numProperties === 1 && reader.getOffset() === endOffset ) ? true : false;
  1986. while ( endOffset > reader.getOffset() ) {
  1987. var subNode = this.parseNode( reader, version );
  1988. if ( subNode !== null ) this.parseSubNode( name, node, subNode );
  1989. }
  1990. node.propertyList = propertyList; // raw property list used by parent
  1991. if ( typeof id === 'number' ) node.id = id;
  1992. if ( attrName !== '' ) node.attrName = attrName;
  1993. if ( attrType !== '' ) node.attrType = attrType;
  1994. if ( name !== '' ) node.name = name;
  1995. return node;
  1996. },
  1997. parseSubNode: function ( name, node, subNode ) {
  1998. // special case: child node is single property
  1999. if ( subNode.singleProperty === true ) {
  2000. var value = subNode.propertyList[ 0 ];
  2001. if ( Array.isArray( value ) ) {
  2002. node[ subNode.name ] = subNode;
  2003. subNode.a = value;
  2004. } else {
  2005. node[ subNode.name ] = value;
  2006. }
  2007. } else if ( name === 'Connections' && subNode.name === 'C' ) {
  2008. var array = [];
  2009. subNode.propertyList.forEach( function ( property, i ) {
  2010. // first Connection is FBX type (OO, OP, etc.). We'll discard these
  2011. if ( i !== 0 ) array.push( property );
  2012. } );
  2013. if ( node.connections === undefined ) {
  2014. node.connections = [];
  2015. }
  2016. node.connections.push( array );
  2017. } else if ( subNode.name === 'Properties70' ) {
  2018. var keys = Object.keys( subNode );
  2019. keys.forEach( function ( key ) {
  2020. node[ key ] = subNode[ key ];
  2021. } );
  2022. } else if ( name === 'Properties70' && subNode.name === 'P' ) {
  2023. var innerPropName = subNode.propertyList[ 0 ];
  2024. var innerPropType1 = subNode.propertyList[ 1 ];
  2025. var innerPropType2 = subNode.propertyList[ 2 ];
  2026. var innerPropFlag = subNode.propertyList[ 3 ];
  2027. var innerPropValue;
  2028. if ( innerPropName.indexOf( 'Lcl ' ) === 0 ) innerPropName = innerPropName.replace( 'Lcl ', 'Lcl_' );
  2029. if ( innerPropType1.indexOf( 'Lcl ' ) === 0 ) innerPropType1 = innerPropType1.replace( 'Lcl ', 'Lcl_' );
  2030. if ( innerPropType1 === 'Color' || innerPropType1 === 'ColorRGB' || innerPropType1 === 'Vector' || innerPropType1 === 'Vector3D' || innerPropType1.indexOf( 'Lcl_' ) === 0 ) {
  2031. innerPropValue = [
  2032. subNode.propertyList[ 4 ],
  2033. subNode.propertyList[ 5 ],
  2034. subNode.propertyList[ 6 ]
  2035. ];
  2036. } else {
  2037. innerPropValue = subNode.propertyList[ 4 ];
  2038. }
  2039. // this will be copied to parent, see above
  2040. node[ innerPropName ] = {
  2041. 'type': innerPropType1,
  2042. 'type2': innerPropType2,
  2043. 'flag': innerPropFlag,
  2044. 'value': innerPropValue
  2045. };
  2046. } else if ( node[ subNode.name ] === undefined ) {
  2047. if ( typeof subNode.id === 'number' ) {
  2048. node[ subNode.name ] = {};
  2049. node[ subNode.name ][ subNode.id ] = subNode;
  2050. } else {
  2051. node[ subNode.name ] = subNode;
  2052. }
  2053. } else {
  2054. if ( subNode.name === 'PoseNode' ) {
  2055. if ( ! Array.isArray( node[ subNode.name ] ) ) {
  2056. node[ subNode.name ] = [ node[ subNode.name ] ];
  2057. }
  2058. node[ subNode.name ].push( subNode );
  2059. } else if ( node[ subNode.name ][ subNode.id ] === undefined ) {
  2060. node[ subNode.name ][ subNode.id ] = subNode;
  2061. }
  2062. }
  2063. },
  2064. parseProperty: function ( reader ) {
  2065. var type = reader.getString( 1 );
  2066. switch ( type ) {
  2067. case 'C':
  2068. return reader.getBoolean();
  2069. case 'D':
  2070. return reader.getFloat64();
  2071. case 'F':
  2072. return reader.getFloat32();
  2073. case 'I':
  2074. return reader.getInt32();
  2075. case 'L':
  2076. return reader.getInt64();
  2077. case 'R':
  2078. var length = reader.getUint32();
  2079. return reader.getArrayBuffer( length );
  2080. case 'S':
  2081. var length = reader.getUint32();
  2082. return reader.getString( length );
  2083. case 'Y':
  2084. return reader.getInt16();
  2085. case 'b':
  2086. case 'c':
  2087. case 'd':
  2088. case 'f':
  2089. case 'i':
  2090. case 'l':
  2091. var arrayLength = reader.getUint32();
  2092. var encoding = reader.getUint32(); // 0: non-compressed, 1: compressed
  2093. var compressedLength = reader.getUint32();
  2094. if ( encoding === 0 ) {
  2095. switch ( type ) {
  2096. case 'b':
  2097. case 'c':
  2098. return reader.getBooleanArray( arrayLength );
  2099. case 'd':
  2100. return reader.getFloat64Array( arrayLength );
  2101. case 'f':
  2102. return reader.getFloat32Array( arrayLength );
  2103. case 'i':
  2104. return reader.getInt32Array( arrayLength );
  2105. case 'l':
  2106. return reader.getInt64Array( arrayLength );
  2107. }
  2108. }
  2109. if ( typeof Inflate === 'undefined' ) {
  2110. console.error( 'THREE.FBXLoader: External library Inflate.min.js required, obtain or import from https://github.com/imaya/zlib.js' );
  2111. }
  2112. var inflate = new Inflate( new Uint8Array( reader.getArrayBuffer( compressedLength ) ) ); // eslint-disable-line no-undef
  2113. var reader2 = new BinaryReader( inflate.decompress().buffer );
  2114. switch ( type ) {
  2115. case 'b':
  2116. case 'c':
  2117. return reader2.getBooleanArray( arrayLength );
  2118. case 'd':
  2119. return reader2.getFloat64Array( arrayLength );
  2120. case 'f':
  2121. return reader2.getFloat32Array( arrayLength );
  2122. case 'i':
  2123. return reader2.getInt32Array( arrayLength );
  2124. case 'l':
  2125. return reader2.getInt64Array( arrayLength );
  2126. }
  2127. default:
  2128. throw new Error( 'THREE.FBXLoader: Unknown property type ' + type );
  2129. }
  2130. }
  2131. };
  2132. function BinaryReader( buffer, littleEndian ) {
  2133. this.dv = new DataView( buffer );
  2134. this.offset = 0;
  2135. this.littleEndian = ( littleEndian !== undefined ) ? littleEndian : true;
  2136. }
  2137. BinaryReader.prototype = {
  2138. constructor: BinaryReader,
  2139. getOffset: function () {
  2140. return this.offset;
  2141. },
  2142. size: function () {
  2143. return this.dv.buffer.byteLength;
  2144. },
  2145. skip: function ( length ) {
  2146. this.offset += length;
  2147. },
  2148. // seems like true/false representation depends on exporter.
  2149. // true: 1 or 'Y'(=0x59), false: 0 or 'T'(=0x54)
  2150. // then sees LSB.
  2151. getBoolean: function () {
  2152. return ( this.getUint8() & 1 ) === 1;
  2153. },
  2154. getBooleanArray: function ( size ) {
  2155. var a = [];
  2156. for ( var i = 0; i < size; i ++ ) {
  2157. a.push( this.getBoolean() );
  2158. }
  2159. return a;
  2160. },
  2161. getUint8: function () {
  2162. var value = this.dv.getUint8( this.offset );
  2163. this.offset += 1;
  2164. return value;
  2165. },
  2166. getInt16: function () {
  2167. var value = this.dv.getInt16( this.offset, this.littleEndian );
  2168. this.offset += 2;
  2169. return value;
  2170. },
  2171. getInt32: function () {
  2172. var value = this.dv.getInt32( this.offset, this.littleEndian );
  2173. this.offset += 4;
  2174. return value;
  2175. },
  2176. getInt32Array: function ( size ) {
  2177. var a = [];
  2178. for ( var i = 0; i < size; i ++ ) {
  2179. a.push( this.getInt32() );
  2180. }
  2181. return a;
  2182. },
  2183. getUint32: function () {
  2184. var value = this.dv.getUint32( this.offset, this.littleEndian );
  2185. this.offset += 4;
  2186. return value;
  2187. },
  2188. // JavaScript doesn't support 64-bit integer so calculate this here
  2189. // 1 << 32 will return 1 so using multiply operation instead here.
  2190. // There's a possibility that this method returns wrong value if the value
  2191. // is out of the range between Number.MAX_SAFE_INTEGER and Number.MIN_SAFE_INTEGER.
  2192. // TODO: safely handle 64-bit integer
  2193. getInt64: function () {
  2194. var low, high;
  2195. if ( this.littleEndian ) {
  2196. low = this.getUint32();
  2197. high = this.getUint32();
  2198. } else {
  2199. high = this.getUint32();
  2200. low = this.getUint32();
  2201. }
  2202. // calculate negative value
  2203. if ( high & 0x80000000 ) {
  2204. high = ~ high & 0xFFFFFFFF;
  2205. low = ~ low & 0xFFFFFFFF;
  2206. if ( low === 0xFFFFFFFF ) high = ( high + 1 ) & 0xFFFFFFFF;
  2207. low = ( low + 1 ) & 0xFFFFFFFF;
  2208. return - ( high * 0x100000000 + low );
  2209. }
  2210. return high * 0x100000000 + low;
  2211. },
  2212. getInt64Array: function ( size ) {
  2213. var a = [];
  2214. for ( var i = 0; i < size; i ++ ) {
  2215. a.push( this.getInt64() );
  2216. }
  2217. return a;
  2218. },
  2219. // Note: see getInt64() comment
  2220. getUint64: function () {
  2221. var low, high;
  2222. if ( this.littleEndian ) {
  2223. low = this.getUint32();
  2224. high = this.getUint32();
  2225. } else {
  2226. high = this.getUint32();
  2227. low = this.getUint32();
  2228. }
  2229. return high * 0x100000000 + low;
  2230. },
  2231. getFloat32: function () {
  2232. var value = this.dv.getFloat32( this.offset, this.littleEndian );
  2233. this.offset += 4;
  2234. return value;
  2235. },
  2236. getFloat32Array: function ( size ) {
  2237. var a = [];
  2238. for ( var i = 0; i < size; i ++ ) {
  2239. a.push( this.getFloat32() );
  2240. }
  2241. return a;
  2242. },
  2243. getFloat64: function () {
  2244. var value = this.dv.getFloat64( this.offset, this.littleEndian );
  2245. this.offset += 8;
  2246. return value;
  2247. },
  2248. getFloat64Array: function ( size ) {
  2249. var a = [];
  2250. for ( var i = 0; i < size; i ++ ) {
  2251. a.push( this.getFloat64() );
  2252. }
  2253. return a;
  2254. },
  2255. getArrayBuffer: function ( size ) {
  2256. var value = this.dv.buffer.slice( this.offset, this.offset + size );
  2257. this.offset += size;
  2258. return value;
  2259. },
  2260. getString: function ( size ) {
  2261. // note: safari 9 doesn't support Uint8Array.indexOf; create intermediate array instead
  2262. var a = [];
  2263. for ( var i = 0; i < size; i ++ ) {
  2264. a[ i ] = this.getUint8();
  2265. }
  2266. var nullByte = a.indexOf( 0 );
  2267. if ( nullByte >= 0 ) a = a.slice( 0, nullByte );
  2268. return THREE.LoaderUtils.decodeText( new Uint8Array( a ) );
  2269. }
  2270. };
  2271. // FBXTree holds a representation of the FBX data, returned by the TextParser ( FBX ASCII format)
  2272. // and BinaryParser( FBX Binary format)
  2273. function FBXTree() {}
  2274. FBXTree.prototype = {
  2275. constructor: FBXTree,
  2276. add: function ( key, val ) {
  2277. this[ key ] = val;
  2278. },
  2279. };
  2280. // ************** UTILITY FUNCTIONS **************
  2281. function isFbxFormatBinary( buffer ) {
  2282. var CORRECT = 'Kaydara FBX Binary \0';
  2283. return buffer.byteLength >= CORRECT.length && CORRECT === convertArrayBufferToString( buffer, 0, CORRECT.length );
  2284. }
  2285. function isFbxFormatASCII( text ) {
  2286. var CORRECT = [ 'K', 'a', 'y', 'd', 'a', 'r', 'a', '\\', 'F', 'B', 'X', '\\', 'B', 'i', 'n', 'a', 'r', 'y', '\\', '\\' ];
  2287. var cursor = 0;
  2288. function read( offset ) {
  2289. var result = text[ offset - 1 ];
  2290. text = text.slice( cursor + offset );
  2291. cursor ++;
  2292. return result;
  2293. }
  2294. for ( var i = 0; i < CORRECT.length; ++ i ) {
  2295. var num = read( 1 );
  2296. if ( num === CORRECT[ i ] ) {
  2297. return false;
  2298. }
  2299. }
  2300. return true;
  2301. }
  2302. function getFbxVersion( text ) {
  2303. var versionRegExp = /FBXVersion: (\d+)/;
  2304. var match = text.match( versionRegExp );
  2305. if ( match ) {
  2306. var version = parseInt( match[ 1 ] );
  2307. return version;
  2308. }
  2309. throw new Error( 'THREE.FBXLoader: Cannot find the version number for the file given.' );
  2310. }
  2311. // Converts FBX ticks into real time seconds.
  2312. function convertFBXTimeToSeconds( time ) {
  2313. return time / 46186158000;
  2314. }
  2315. var dataArray = [];
  2316. // extracts the data from the correct position in the FBX array based on indexing type
  2317. function getData( polygonVertexIndex, polygonIndex, vertexIndex, infoObject ) {
  2318. var index;
  2319. switch ( infoObject.mappingType ) {
  2320. case 'ByPolygonVertex' :
  2321. index = polygonVertexIndex;
  2322. break;
  2323. case 'ByPolygon' :
  2324. index = polygonIndex;
  2325. break;
  2326. case 'ByVertice' :
  2327. index = vertexIndex;
  2328. break;
  2329. case 'AllSame' :
  2330. index = infoObject.indices[ 0 ];
  2331. break;
  2332. default :
  2333. console.warn( 'THREE.FBXLoader: unknown attribute mapping type ' + infoObject.mappingType );
  2334. }
  2335. if ( infoObject.referenceType === 'IndexToDirect' ) index = infoObject.indices[ index ];
  2336. var from = index * infoObject.dataSize;
  2337. var to = from + infoObject.dataSize;
  2338. return slice( dataArray, infoObject.buffer, from, to );
  2339. }
  2340. var tempEuler = new THREE.Euler();
  2341. var tempVec = new THREE.Vector3();
  2342. // generate transformation from FBX transform data
  2343. // ref: https://help.autodesk.com/view/FBX/2017/ENU/?guid=__files_GUID_10CDD63C_79C1_4F2D_BB28_AD2BE65A02ED_htm
  2344. // ref: http://docs.autodesk.com/FBX/2014/ENU/FBX-SDK-Documentation/index.html?url=cpp_ref/_transformations_2main_8cxx-example.html,topicNumber=cpp_ref__transformations_2main_8cxx_example_htmlfc10a1e1-b18d-4e72-9dc0-70d0f1959f5e
  2345. function generateTransform( transformData ) {
  2346. var lTranslationM = new THREE.Matrix4();
  2347. var lPreRotationM = new THREE.Matrix4();
  2348. var lRotationM = new THREE.Matrix4();
  2349. var lPostRotationM = new THREE.Matrix4();
  2350. var lScalingM = new THREE.Matrix4();
  2351. var lScalingPivotM = new THREE.Matrix4();
  2352. var lScalingOffsetM = new THREE.Matrix4();
  2353. var lRotationOffsetM = new THREE.Matrix4();
  2354. var lRotationPivotM = new THREE.Matrix4();
  2355. var lParentGX = new THREE.Matrix4();
  2356. var lGlobalT = new THREE.Matrix4();
  2357. var inheritType = ( transformData.inheritType ) ? transformData.inheritType : 0;
  2358. if ( transformData.translation ) lTranslationM.setPosition( tempVec.fromArray( transformData.translation ) );
  2359. if ( transformData.preRotation ) {
  2360. var array = transformData.preRotation.map( THREE.MathUtils.degToRad );
  2361. array.push( transformData.eulerOrder );
  2362. lPreRotationM.makeRotationFromEuler( tempEuler.fromArray( array ) );
  2363. }
  2364. if ( transformData.rotation ) {
  2365. var array = transformData.rotation.map( THREE.MathUtils.degToRad );
  2366. array.push( transformData.eulerOrder );
  2367. lRotationM.makeRotationFromEuler( tempEuler.fromArray( array ) );
  2368. }
  2369. if ( transformData.postRotation ) {
  2370. var array = transformData.postRotation.map( THREE.MathUtils.degToRad );
  2371. array.push( transformData.eulerOrder );
  2372. lPostRotationM.makeRotationFromEuler( tempEuler.fromArray( array ) );
  2373. }
  2374. if ( transformData.scale ) lScalingM.scale( tempVec.fromArray( transformData.scale ) );
  2375. // Pivots and offsets
  2376. if ( transformData.scalingOffset ) lScalingOffsetM.setPosition( tempVec.fromArray( transformData.scalingOffset ) );
  2377. if ( transformData.scalingPivot ) lScalingPivotM.setPosition( tempVec.fromArray( transformData.scalingPivot ) );
  2378. if ( transformData.rotationOffset ) lRotationOffsetM.setPosition( tempVec.fromArray( transformData.rotationOffset ) );
  2379. if ( transformData.rotationPivot ) lRotationPivotM.setPosition( tempVec.fromArray( transformData.rotationPivot ) );
  2380. // parent transform
  2381. if ( transformData.parentMatrixWorld ) lParentGX = transformData.parentMatrixWorld;
  2382. // Global Rotation
  2383. var lLRM = lPreRotationM.multiply( lRotationM ).multiply( lPostRotationM );
  2384. var lParentGRM = new THREE.Matrix4();
  2385. lParentGX.extractRotation( lParentGRM );
  2386. // Global Shear*Scaling
  2387. var lParentTM = new THREE.Matrix4();
  2388. lParentTM.copyPosition( lParentGX );
  2389. var lParentGSM = new THREE.Matrix4();
  2390. lParentGSM.getInverse( lParentGRM ).multiply( lParentGX );
  2391. var lGlobalRS = new THREE.Matrix4();
  2392. if ( inheritType === 0 ) {
  2393. lGlobalRS.copy( lParentGRM ).multiply( lLRM ).multiply( lParentGSM ).multiply( lScalingM );
  2394. } else if ( inheritType === 1 ) {
  2395. lGlobalRS.copy( lParentGRM ).multiply( lParentGSM ).multiply( lLRM ).multiply( lScalingM );
  2396. } else {
  2397. var lParentLSM_inv = new THREE.Matrix4().getInverse( lScalingM );
  2398. var lParentGSM_noLocal = new THREE.Matrix4().multiply( lParentGSM ).multiply( lParentLSM_inv );
  2399. lGlobalRS.copy( lParentGRM ).multiply( lLRM ).multiply( lParentGSM_noLocal ).multiply( lScalingM );
  2400. }
  2401. var lRotationPivotM_inv = new THREE.Matrix4().getInverse( lRotationPivotM );
  2402. var lScalingPivotM_inv = new THREE.Matrix4().getInverse( lScalingPivotM );
  2403. // Calculate the local transform matrix
  2404. var lTransform = new THREE.Matrix4();
  2405. lTransform.copy( lTranslationM ).multiply( lRotationOffsetM ).multiply( lRotationPivotM ).multiply( lPreRotationM ).multiply( lRotationM ).multiply( lPostRotationM ).multiply( lRotationPivotM_inv ).multiply( lScalingOffsetM ).multiply( lScalingPivotM ).multiply( lScalingM ).multiply( lScalingPivotM_inv );
  2406. var lLocalTWithAllPivotAndOffsetInfo = new THREE.Matrix4().copyPosition( lTransform );
  2407. var lGlobalTranslation = new THREE.Matrix4().copy( lParentGX ).multiply( lLocalTWithAllPivotAndOffsetInfo );
  2408. lGlobalT.copyPosition( lGlobalTranslation );
  2409. lTransform = new THREE.Matrix4().multiply( lGlobalT ).multiply( lGlobalRS );
  2410. return lTransform;
  2411. }
  2412. // Returns the three.js intrinsic Euler order corresponding to FBX extrinsic Euler order
  2413. // ref: http://help.autodesk.com/view/FBX/2017/ENU/?guid=__cpp_ref_class_fbx_euler_html
  2414. function getEulerOrder( order ) {
  2415. order = order || 0;
  2416. var enums = [
  2417. 'ZYX', // -> XYZ extrinsic
  2418. 'YZX', // -> XZY extrinsic
  2419. 'XZY', // -> YZX extrinsic
  2420. 'ZXY', // -> YXZ extrinsic
  2421. 'YXZ', // -> ZXY extrinsic
  2422. 'XYZ', // -> ZYX extrinsic
  2423. //'SphericXYZ', // not possible to support
  2424. ];
  2425. if ( order === 6 ) {
  2426. console.warn( 'THREE.FBXLoader: unsupported Euler Order: Spherical XYZ. Animations and rotations may be incorrect.' );
  2427. return enums[ 0 ];
  2428. }
  2429. return enums[ order ];
  2430. }
  2431. // Parses comma separated list of numbers and returns them an array.
  2432. // Used internally by the TextParser
  2433. function parseNumberArray( value ) {
  2434. var array = value.split( ',' ).map( function ( val ) {
  2435. return parseFloat( val );
  2436. } );
  2437. return array;
  2438. }
  2439. function convertArrayBufferToString( buffer, from, to ) {
  2440. if ( from === undefined ) from = 0;
  2441. if ( to === undefined ) to = buffer.byteLength;
  2442. return THREE.LoaderUtils.decodeText( new Uint8Array( buffer, from, to ) );
  2443. }
  2444. function append( a, b ) {
  2445. for ( var i = 0, j = a.length, l = b.length; i < l; i ++, j ++ ) {
  2446. a[ j ] = b[ i ];
  2447. }
  2448. }
  2449. function slice( a, b, from, to ) {
  2450. for ( var i = from, j = 0; i < to; i ++, j ++ ) {
  2451. a[ j ] = b[ i ];
  2452. }
  2453. return a;
  2454. }
  2455. // inject array a2 into array a1 at index
  2456. function inject( a1, index, a2 ) {
  2457. return a1.slice( 0, index ).concat( a2 ).concat( a1.slice( index ) );
  2458. }
  2459. return FBXLoader;
  2460. } )();