FBXLoader.js 95 KB

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