FBXLoader.js 95 KB

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