2
0

FBXLoader.js 98 KB

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