FBXLoader.js 95 KB

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