FBXLoader.js 99 KB

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