FBXLoader.js 81 KB

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