FBXLoader.js 99 KB

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