FBXLoader.js 92 KB

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