FBXLoader.js 80 KB

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