FBXLoader.js 99 KB

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