FBXLoader.js 95 KB

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