FBXLoader.js 95 KB

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