FBXLoader.js 80 KB

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