FBXLoader.js 99 KB

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