FBXLoader.js 99 KB

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