FBXLoader.js 82 KB

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