FBXLoader.js 95 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144
  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. SRGBColorSpace
  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 ).convertSRGBToLinear();
  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 ).convertSRGBToLinear();
  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 ).convertSRGBToLinear();
  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 ).convertSRGBToLinear();
  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 ).convertSRGBToLinear();
  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 ).convertSRGBToLinear();
  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.colorSpace = SRGBColorSpace;
  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.colorSpace = SRGBColorSpace;
  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.colorSpace = SRGBColorSpace;
  410. }
  411. break;
  412. case 'SpecularColor':
  413. parameters.specularMap = scope.getTexture( textureMap, child.ID );
  414. if ( parameters.specularMap !== undefined ) {
  415. parameters.specularMap.colorSpace = SRGBColorSpace;
  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.userData.originalName = node.attrName;
  596. model.ID = id;
  597. }
  598. this.getTransformData( model, node );
  599. modelMap.set( id, model );
  600. }
  601. return modelMap;
  602. }
  603. buildSkeleton( relationships, skeletons, id, name ) {
  604. let bone = null;
  605. relationships.parents.forEach( function ( parent ) {
  606. for ( const ID in skeletons ) {
  607. const skeleton = skeletons[ ID ];
  608. skeleton.rawBones.forEach( function ( rawBone, i ) {
  609. if ( rawBone.ID === parent.ID ) {
  610. const subBone = bone;
  611. bone = new Bone();
  612. bone.matrixWorld.copy( rawBone.transformLink );
  613. // set name and id here - otherwise in cases where "subBone" is created it will not have a name / id
  614. bone.name = name ? PropertyBinding.sanitizeNodeName( name ) : '';
  615. bone.userData.originalName = name;
  616. bone.ID = id;
  617. skeleton.bones[ i ] = bone;
  618. // In cases where a bone is shared between multiple meshes
  619. // duplicate the bone here and and it as a child of the first bone
  620. if ( subBone !== null ) {
  621. bone.add( subBone );
  622. }
  623. }
  624. } );
  625. }
  626. } );
  627. return bone;
  628. }
  629. // create a PerspectiveCamera or OrthographicCamera
  630. createCamera( relationships ) {
  631. let model;
  632. let cameraAttribute;
  633. relationships.children.forEach( function ( child ) {
  634. const attr = fbxTree.Objects.NodeAttribute[ child.ID ];
  635. if ( attr !== undefined ) {
  636. cameraAttribute = attr;
  637. }
  638. } );
  639. if ( cameraAttribute === undefined ) {
  640. model = new Object3D();
  641. } else {
  642. let type = 0;
  643. if ( cameraAttribute.CameraProjectionType !== undefined && cameraAttribute.CameraProjectionType.value === 1 ) {
  644. type = 1;
  645. }
  646. let nearClippingPlane = 1;
  647. if ( cameraAttribute.NearPlane !== undefined ) {
  648. nearClippingPlane = cameraAttribute.NearPlane.value / 1000;
  649. }
  650. let farClippingPlane = 1000;
  651. if ( cameraAttribute.FarPlane !== undefined ) {
  652. farClippingPlane = cameraAttribute.FarPlane.value / 1000;
  653. }
  654. let width = window.innerWidth;
  655. let height = window.innerHeight;
  656. if ( cameraAttribute.AspectWidth !== undefined && cameraAttribute.AspectHeight !== undefined ) {
  657. width = cameraAttribute.AspectWidth.value;
  658. height = cameraAttribute.AspectHeight.value;
  659. }
  660. const aspect = width / height;
  661. let fov = 45;
  662. if ( cameraAttribute.FieldOfView !== undefined ) {
  663. fov = cameraAttribute.FieldOfView.value;
  664. }
  665. const focalLength = cameraAttribute.FocalLength ? cameraAttribute.FocalLength.value : null;
  666. switch ( type ) {
  667. case 0: // Perspective
  668. model = new PerspectiveCamera( fov, aspect, nearClippingPlane, farClippingPlane );
  669. if ( focalLength !== null ) model.setFocalLength( focalLength );
  670. break;
  671. case 1: // Orthographic
  672. model = new OrthographicCamera( - width / 2, width / 2, height / 2, - height / 2, nearClippingPlane, farClippingPlane );
  673. break;
  674. default:
  675. console.warn( 'THREE.FBXLoader: Unknown camera type ' + type + '.' );
  676. model = new Object3D();
  677. break;
  678. }
  679. }
  680. return model;
  681. }
  682. // Create a DirectionalLight, PointLight or SpotLight
  683. createLight( relationships ) {
  684. let model;
  685. let lightAttribute;
  686. relationships.children.forEach( function ( child ) {
  687. const attr = fbxTree.Objects.NodeAttribute[ child.ID ];
  688. if ( attr !== undefined ) {
  689. lightAttribute = attr;
  690. }
  691. } );
  692. if ( lightAttribute === undefined ) {
  693. model = new Object3D();
  694. } else {
  695. let type;
  696. // LightType can be undefined for Point lights
  697. if ( lightAttribute.LightType === undefined ) {
  698. type = 0;
  699. } else {
  700. type = lightAttribute.LightType.value;
  701. }
  702. let color = 0xffffff;
  703. if ( lightAttribute.Color !== undefined ) {
  704. color = new Color().fromArray( lightAttribute.Color.value ).convertSRGBToLinear();
  705. }
  706. let intensity = ( lightAttribute.Intensity === undefined ) ? 1 : lightAttribute.Intensity.value / 100;
  707. // light disabled
  708. if ( lightAttribute.CastLightOnObject !== undefined && lightAttribute.CastLightOnObject.value === 0 ) {
  709. intensity = 0;
  710. }
  711. let distance = 0;
  712. if ( lightAttribute.FarAttenuationEnd !== undefined ) {
  713. if ( lightAttribute.EnableFarAttenuation !== undefined && lightAttribute.EnableFarAttenuation.value === 0 ) {
  714. distance = 0;
  715. } else {
  716. distance = lightAttribute.FarAttenuationEnd.value;
  717. }
  718. }
  719. // TODO: could this be calculated linearly from FarAttenuationStart to FarAttenuationEnd?
  720. const decay = 1;
  721. switch ( type ) {
  722. case 0: // Point
  723. model = new PointLight( color, intensity, distance, decay );
  724. break;
  725. case 1: // Directional
  726. model = new DirectionalLight( color, intensity );
  727. break;
  728. case 2: // Spot
  729. let angle = Math.PI / 3;
  730. if ( lightAttribute.InnerAngle !== undefined ) {
  731. angle = MathUtils.degToRad( lightAttribute.InnerAngle.value );
  732. }
  733. let penumbra = 0;
  734. if ( lightAttribute.OuterAngle !== undefined ) {
  735. // TODO: this is not correct - FBX calculates outer and inner angle in degrees
  736. // with OuterAngle > InnerAngle && OuterAngle <= Math.PI
  737. // while three.js uses a penumbra between (0, 1) to attenuate the inner angle
  738. penumbra = MathUtils.degToRad( lightAttribute.OuterAngle.value );
  739. penumbra = Math.max( penumbra, 1 );
  740. }
  741. model = new SpotLight( color, intensity, distance, angle, penumbra, decay );
  742. break;
  743. default:
  744. console.warn( 'THREE.FBXLoader: Unknown light type ' + lightAttribute.LightType.value + ', defaulting to a PointLight.' );
  745. model = new PointLight( color, intensity );
  746. break;
  747. }
  748. if ( lightAttribute.CastShadows !== undefined && lightAttribute.CastShadows.value === 1 ) {
  749. model.castShadow = true;
  750. }
  751. }
  752. return model;
  753. }
  754. createMesh( relationships, geometryMap, materialMap ) {
  755. let model;
  756. let geometry = null;
  757. let material = null;
  758. const materials = [];
  759. // get geometry and materials(s) from connections
  760. relationships.children.forEach( function ( child ) {
  761. if ( geometryMap.has( child.ID ) ) {
  762. geometry = geometryMap.get( child.ID );
  763. }
  764. if ( materialMap.has( child.ID ) ) {
  765. materials.push( materialMap.get( child.ID ) );
  766. }
  767. } );
  768. if ( materials.length > 1 ) {
  769. material = materials;
  770. } else if ( materials.length > 0 ) {
  771. material = materials[ 0 ];
  772. } else {
  773. material = new MeshPhongMaterial( {
  774. name: Loader.DEFAULT_MATERIAL_NAME,
  775. color: 0xcccccc
  776. } );
  777. materials.push( material );
  778. }
  779. if ( 'color' in geometry.attributes ) {
  780. materials.forEach( function ( material ) {
  781. material.vertexColors = true;
  782. } );
  783. }
  784. if ( geometry.FBX_Deformer ) {
  785. model = new SkinnedMesh( geometry, material );
  786. model.normalizeSkinWeights();
  787. } else {
  788. model = new Mesh( geometry, material );
  789. }
  790. return model;
  791. }
  792. createCurve( relationships, geometryMap ) {
  793. const geometry = relationships.children.reduce( function ( geo, child ) {
  794. if ( geometryMap.has( child.ID ) ) geo = geometryMap.get( child.ID );
  795. return geo;
  796. }, null );
  797. // FBX does not list materials for Nurbs lines, so we'll just put our own in here.
  798. const material = new LineBasicMaterial( {
  799. name: Loader.DEFAULT_MATERIAL_NAME,
  800. color: 0x3300ff,
  801. linewidth: 1
  802. } );
  803. return new Line( geometry, material );
  804. }
  805. // parse the model node for transform data
  806. getTransformData( model, modelNode ) {
  807. const transformData = {};
  808. if ( 'InheritType' in modelNode ) transformData.inheritType = parseInt( modelNode.InheritType.value );
  809. if ( 'RotationOrder' in modelNode ) transformData.eulerOrder = getEulerOrder( modelNode.RotationOrder.value );
  810. else transformData.eulerOrder = 'ZYX';
  811. if ( 'Lcl_Translation' in modelNode ) transformData.translation = modelNode.Lcl_Translation.value;
  812. if ( 'PreRotation' in modelNode ) transformData.preRotation = modelNode.PreRotation.value;
  813. if ( 'Lcl_Rotation' in modelNode ) transformData.rotation = modelNode.Lcl_Rotation.value;
  814. if ( 'PostRotation' in modelNode ) transformData.postRotation = modelNode.PostRotation.value;
  815. if ( 'Lcl_Scaling' in modelNode ) transformData.scale = modelNode.Lcl_Scaling.value;
  816. if ( 'ScalingOffset' in modelNode ) transformData.scalingOffset = modelNode.ScalingOffset.value;
  817. if ( 'ScalingPivot' in modelNode ) transformData.scalingPivot = modelNode.ScalingPivot.value;
  818. if ( 'RotationOffset' in modelNode ) transformData.rotationOffset = modelNode.RotationOffset.value;
  819. if ( 'RotationPivot' in modelNode ) transformData.rotationPivot = modelNode.RotationPivot.value;
  820. model.userData.transformData = transformData;
  821. }
  822. setLookAtProperties( model, modelNode ) {
  823. if ( 'LookAtProperty' in modelNode ) {
  824. const children = connections.get( model.ID ).children;
  825. children.forEach( function ( child ) {
  826. if ( child.relationship === 'LookAtProperty' ) {
  827. const lookAtTarget = fbxTree.Objects.Model[ child.ID ];
  828. if ( 'Lcl_Translation' in lookAtTarget ) {
  829. const pos = lookAtTarget.Lcl_Translation.value;
  830. // DirectionalLight, SpotLight
  831. if ( model.target !== undefined ) {
  832. model.target.position.fromArray( pos );
  833. sceneGraph.add( model.target );
  834. } else { // Cameras and other Object3Ds
  835. model.lookAt( new Vector3().fromArray( pos ) );
  836. }
  837. }
  838. }
  839. } );
  840. }
  841. }
  842. bindSkeleton( skeletons, geometryMap, modelMap ) {
  843. const bindMatrices = this.parsePoseNodes();
  844. for ( const ID in skeletons ) {
  845. const skeleton = skeletons[ ID ];
  846. const parents = connections.get( parseInt( skeleton.ID ) ).parents;
  847. parents.forEach( function ( parent ) {
  848. if ( geometryMap.has( parent.ID ) ) {
  849. const geoID = parent.ID;
  850. const geoRelationships = connections.get( geoID );
  851. geoRelationships.parents.forEach( function ( geoConnParent ) {
  852. if ( modelMap.has( geoConnParent.ID ) ) {
  853. const model = modelMap.get( geoConnParent.ID );
  854. model.bind( new Skeleton( skeleton.bones ), bindMatrices[ geoConnParent.ID ] );
  855. }
  856. } );
  857. }
  858. } );
  859. }
  860. }
  861. parsePoseNodes() {
  862. const bindMatrices = {};
  863. if ( 'Pose' in fbxTree.Objects ) {
  864. const BindPoseNode = fbxTree.Objects.Pose;
  865. for ( const nodeID in BindPoseNode ) {
  866. if ( BindPoseNode[ nodeID ].attrType === 'BindPose' && BindPoseNode[ nodeID ].NbPoseNodes > 0 ) {
  867. const poseNodes = BindPoseNode[ nodeID ].PoseNode;
  868. if ( Array.isArray( poseNodes ) ) {
  869. poseNodes.forEach( function ( poseNode ) {
  870. bindMatrices[ poseNode.Node ] = new Matrix4().fromArray( poseNode.Matrix.a );
  871. } );
  872. } else {
  873. bindMatrices[ poseNodes.Node ] = new Matrix4().fromArray( poseNodes.Matrix.a );
  874. }
  875. }
  876. }
  877. }
  878. return bindMatrices;
  879. }
  880. // Parse ambient color in FBXTree.GlobalSettings - if it's not set to black (default), create an ambient light
  881. createAmbientLight() {
  882. if ( 'GlobalSettings' in fbxTree && 'AmbientColor' in fbxTree.GlobalSettings ) {
  883. const ambientColor = fbxTree.GlobalSettings.AmbientColor.value;
  884. const r = ambientColor[ 0 ];
  885. const g = ambientColor[ 1 ];
  886. const b = ambientColor[ 2 ];
  887. if ( r !== 0 || g !== 0 || b !== 0 ) {
  888. const color = new Color( r, g, b ).convertSRGBToLinear();
  889. sceneGraph.add( new AmbientLight( color, 1 ) );
  890. }
  891. }
  892. }
  893. }
  894. // parse Geometry data from FBXTree and return map of BufferGeometries
  895. class GeometryParser {
  896. constructor() {
  897. this.negativeMaterialIndices = false;
  898. }
  899. // Parse nodes in FBXTree.Objects.Geometry
  900. parse( deformers ) {
  901. const geometryMap = new Map();
  902. if ( 'Geometry' in fbxTree.Objects ) {
  903. const geoNodes = fbxTree.Objects.Geometry;
  904. for ( const nodeID in geoNodes ) {
  905. const relationships = connections.get( parseInt( nodeID ) );
  906. const geo = this.parseGeometry( relationships, geoNodes[ nodeID ], deformers );
  907. geometryMap.set( parseInt( nodeID ), geo );
  908. }
  909. }
  910. // report warnings
  911. if ( this.negativeMaterialIndices === true ) {
  912. console.warn( 'THREE.FBXLoader: The FBX file contains invalid (negative) material indices. The asset might not render as expected.' );
  913. }
  914. return geometryMap;
  915. }
  916. // Parse single node in FBXTree.Objects.Geometry
  917. parseGeometry( relationships, geoNode, deformers ) {
  918. switch ( geoNode.attrType ) {
  919. case 'Mesh':
  920. return this.parseMeshGeometry( relationships, geoNode, deformers );
  921. break;
  922. case 'NurbsCurve':
  923. return this.parseNurbsGeometry( geoNode );
  924. break;
  925. }
  926. }
  927. // Parse single node mesh geometry in FBXTree.Objects.Geometry
  928. parseMeshGeometry( relationships, geoNode, deformers ) {
  929. const skeletons = deformers.skeletons;
  930. const morphTargets = [];
  931. const modelNodes = relationships.parents.map( function ( parent ) {
  932. return fbxTree.Objects.Model[ parent.ID ];
  933. } );
  934. // don't create geometry if it is not associated with any models
  935. if ( modelNodes.length === 0 ) return;
  936. const skeleton = relationships.children.reduce( function ( skeleton, child ) {
  937. if ( skeletons[ child.ID ] !== undefined ) skeleton = skeletons[ child.ID ];
  938. return skeleton;
  939. }, null );
  940. relationships.children.forEach( function ( child ) {
  941. if ( deformers.morphTargets[ child.ID ] !== undefined ) {
  942. morphTargets.push( deformers.morphTargets[ child.ID ] );
  943. }
  944. } );
  945. // Assume one model and get the preRotation from that
  946. // if there is more than one model associated with the geometry this may cause problems
  947. const modelNode = modelNodes[ 0 ];
  948. const transformData = {};
  949. if ( 'RotationOrder' in modelNode ) transformData.eulerOrder = getEulerOrder( modelNode.RotationOrder.value );
  950. if ( 'InheritType' in modelNode ) transformData.inheritType = parseInt( modelNode.InheritType.value );
  951. if ( 'GeometricTranslation' in modelNode ) transformData.translation = modelNode.GeometricTranslation.value;
  952. if ( 'GeometricRotation' in modelNode ) transformData.rotation = modelNode.GeometricRotation.value;
  953. if ( 'GeometricScaling' in modelNode ) transformData.scale = modelNode.GeometricScaling.value;
  954. const transform = generateTransform( transformData );
  955. return this.genGeometry( geoNode, skeleton, morphTargets, transform );
  956. }
  957. // Generate a BufferGeometry from a node in FBXTree.Objects.Geometry
  958. genGeometry( geoNode, skeleton, morphTargets, preTransform ) {
  959. const geo = new BufferGeometry();
  960. if ( geoNode.attrName ) geo.name = geoNode.attrName;
  961. const geoInfo = this.parseGeoNode( geoNode, skeleton );
  962. const buffers = this.genBuffers( geoInfo );
  963. const positionAttribute = new Float32BufferAttribute( buffers.vertex, 3 );
  964. positionAttribute.applyMatrix4( preTransform );
  965. geo.setAttribute( 'position', positionAttribute );
  966. if ( buffers.colors.length > 0 ) {
  967. geo.setAttribute( 'color', new Float32BufferAttribute( buffers.colors, 3 ) );
  968. }
  969. if ( skeleton ) {
  970. geo.setAttribute( 'skinIndex', new Uint16BufferAttribute( buffers.weightsIndices, 4 ) );
  971. geo.setAttribute( 'skinWeight', new Float32BufferAttribute( buffers.vertexWeights, 4 ) );
  972. // used later to bind the skeleton to the model
  973. geo.FBX_Deformer = skeleton;
  974. }
  975. if ( buffers.normal.length > 0 ) {
  976. const normalMatrix = new Matrix3().getNormalMatrix( preTransform );
  977. const normalAttribute = new Float32BufferAttribute( buffers.normal, 3 );
  978. normalAttribute.applyNormalMatrix( normalMatrix );
  979. geo.setAttribute( 'normal', normalAttribute );
  980. }
  981. buffers.uvs.forEach( function ( uvBuffer, i ) {
  982. const name = i === 0 ? 'uv' : `uv${ i }`;
  983. geo.setAttribute( name, new Float32BufferAttribute( buffers.uvs[ i ], 2 ) );
  984. } );
  985. if ( geoInfo.material && geoInfo.material.mappingType !== 'AllSame' ) {
  986. // Convert the material indices of each vertex into rendering groups on the geometry.
  987. let prevMaterialIndex = buffers.materialIndex[ 0 ];
  988. let startIndex = 0;
  989. buffers.materialIndex.forEach( function ( currentIndex, i ) {
  990. if ( currentIndex !== prevMaterialIndex ) {
  991. geo.addGroup( startIndex, i - startIndex, prevMaterialIndex );
  992. prevMaterialIndex = currentIndex;
  993. startIndex = i;
  994. }
  995. } );
  996. // the loop above doesn't add the last group, do that here.
  997. if ( geo.groups.length > 0 ) {
  998. const lastGroup = geo.groups[ geo.groups.length - 1 ];
  999. const lastIndex = lastGroup.start + lastGroup.count;
  1000. if ( lastIndex !== buffers.materialIndex.length ) {
  1001. geo.addGroup( lastIndex, buffers.materialIndex.length - lastIndex, prevMaterialIndex );
  1002. }
  1003. }
  1004. // case where there are multiple materials but the whole geometry is only
  1005. // using one of them
  1006. if ( geo.groups.length === 0 ) {
  1007. geo.addGroup( 0, buffers.materialIndex.length, buffers.materialIndex[ 0 ] );
  1008. }
  1009. }
  1010. this.addMorphTargets( geo, geoNode, morphTargets, preTransform );
  1011. return geo;
  1012. }
  1013. parseGeoNode( geoNode, skeleton ) {
  1014. const geoInfo = {};
  1015. geoInfo.vertexPositions = ( geoNode.Vertices !== undefined ) ? geoNode.Vertices.a : [];
  1016. geoInfo.vertexIndices = ( geoNode.PolygonVertexIndex !== undefined ) ? geoNode.PolygonVertexIndex.a : [];
  1017. if ( geoNode.LayerElementColor ) {
  1018. geoInfo.color = this.parseVertexColors( geoNode.LayerElementColor[ 0 ] );
  1019. }
  1020. if ( geoNode.LayerElementMaterial ) {
  1021. geoInfo.material = this.parseMaterialIndices( geoNode.LayerElementMaterial[ 0 ] );
  1022. }
  1023. if ( geoNode.LayerElementNormal ) {
  1024. geoInfo.normal = this.parseNormals( geoNode.LayerElementNormal[ 0 ] );
  1025. }
  1026. if ( geoNode.LayerElementUV ) {
  1027. geoInfo.uv = [];
  1028. let i = 0;
  1029. while ( geoNode.LayerElementUV[ i ] ) {
  1030. if ( geoNode.LayerElementUV[ i ].UV ) {
  1031. geoInfo.uv.push( this.parseUVs( geoNode.LayerElementUV[ i ] ) );
  1032. }
  1033. i ++;
  1034. }
  1035. }
  1036. geoInfo.weightTable = {};
  1037. if ( skeleton !== null ) {
  1038. geoInfo.skeleton = skeleton;
  1039. skeleton.rawBones.forEach( function ( rawBone, i ) {
  1040. // loop over the bone's vertex indices and weights
  1041. rawBone.indices.forEach( function ( index, j ) {
  1042. if ( geoInfo.weightTable[ index ] === undefined ) geoInfo.weightTable[ index ] = [];
  1043. geoInfo.weightTable[ index ].push( {
  1044. id: i,
  1045. weight: rawBone.weights[ j ],
  1046. } );
  1047. } );
  1048. } );
  1049. }
  1050. return geoInfo;
  1051. }
  1052. genBuffers( geoInfo ) {
  1053. const buffers = {
  1054. vertex: [],
  1055. normal: [],
  1056. colors: [],
  1057. uvs: [],
  1058. materialIndex: [],
  1059. vertexWeights: [],
  1060. weightsIndices: [],
  1061. };
  1062. let polygonIndex = 0;
  1063. let faceLength = 0;
  1064. let displayedWeightsWarning = false;
  1065. // these will hold data for a single face
  1066. let facePositionIndexes = [];
  1067. let faceNormals = [];
  1068. let faceColors = [];
  1069. let faceUVs = [];
  1070. let faceWeights = [];
  1071. let faceWeightIndices = [];
  1072. const scope = this;
  1073. geoInfo.vertexIndices.forEach( function ( vertexIndex, polygonVertexIndex ) {
  1074. let materialIndex;
  1075. let endOfFace = false;
  1076. // Face index and vertex index arrays are combined in a single array
  1077. // A cube with quad faces looks like this:
  1078. // PolygonVertexIndex: *24 {
  1079. // 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
  1080. // }
  1081. // Negative numbers mark the end of a face - first face here is 0, 1, 3, -3
  1082. // to find index of last vertex bit shift the index: ^ - 1
  1083. if ( vertexIndex < 0 ) {
  1084. vertexIndex = vertexIndex ^ - 1; // equivalent to ( x * -1 ) - 1
  1085. endOfFace = true;
  1086. }
  1087. let weightIndices = [];
  1088. let weights = [];
  1089. facePositionIndexes.push( vertexIndex * 3, vertexIndex * 3 + 1, vertexIndex * 3 + 2 );
  1090. if ( geoInfo.color ) {
  1091. const data = getData( polygonVertexIndex, polygonIndex, vertexIndex, geoInfo.color );
  1092. faceColors.push( data[ 0 ], data[ 1 ], data[ 2 ] );
  1093. }
  1094. if ( geoInfo.skeleton ) {
  1095. if ( geoInfo.weightTable[ vertexIndex ] !== undefined ) {
  1096. geoInfo.weightTable[ vertexIndex ].forEach( function ( wt ) {
  1097. weights.push( wt.weight );
  1098. weightIndices.push( wt.id );
  1099. } );
  1100. }
  1101. if ( weights.length > 4 ) {
  1102. if ( ! displayedWeightsWarning ) {
  1103. console.warn( 'THREE.FBXLoader: Vertex has more than 4 skinning weights assigned to vertex. Deleting additional weights.' );
  1104. displayedWeightsWarning = true;
  1105. }
  1106. const wIndex = [ 0, 0, 0, 0 ];
  1107. const Weight = [ 0, 0, 0, 0 ];
  1108. weights.forEach( function ( weight, weightIndex ) {
  1109. let currentWeight = weight;
  1110. let currentIndex = weightIndices[ weightIndex ];
  1111. Weight.forEach( function ( comparedWeight, comparedWeightIndex, comparedWeightArray ) {
  1112. if ( currentWeight > comparedWeight ) {
  1113. comparedWeightArray[ comparedWeightIndex ] = currentWeight;
  1114. currentWeight = comparedWeight;
  1115. const tmp = wIndex[ comparedWeightIndex ];
  1116. wIndex[ comparedWeightIndex ] = currentIndex;
  1117. currentIndex = tmp;
  1118. }
  1119. } );
  1120. } );
  1121. weightIndices = wIndex;
  1122. weights = Weight;
  1123. }
  1124. // if the weight array is shorter than 4 pad with 0s
  1125. while ( weights.length < 4 ) {
  1126. weights.push( 0 );
  1127. weightIndices.push( 0 );
  1128. }
  1129. for ( let i = 0; i < 4; ++ i ) {
  1130. faceWeights.push( weights[ i ] );
  1131. faceWeightIndices.push( weightIndices[ i ] );
  1132. }
  1133. }
  1134. if ( geoInfo.normal ) {
  1135. const data = getData( polygonVertexIndex, polygonIndex, vertexIndex, geoInfo.normal );
  1136. faceNormals.push( data[ 0 ], data[ 1 ], data[ 2 ] );
  1137. }
  1138. if ( geoInfo.material && geoInfo.material.mappingType !== 'AllSame' ) {
  1139. materialIndex = getData( polygonVertexIndex, polygonIndex, vertexIndex, geoInfo.material )[ 0 ];
  1140. if ( materialIndex < 0 ) {
  1141. scope.negativeMaterialIndices = true;
  1142. materialIndex = 0; // fallback
  1143. }
  1144. }
  1145. if ( geoInfo.uv ) {
  1146. geoInfo.uv.forEach( function ( uv, i ) {
  1147. const data = getData( polygonVertexIndex, polygonIndex, vertexIndex, uv );
  1148. if ( faceUVs[ i ] === undefined ) {
  1149. faceUVs[ i ] = [];
  1150. }
  1151. faceUVs[ i ].push( data[ 0 ] );
  1152. faceUVs[ i ].push( data[ 1 ] );
  1153. } );
  1154. }
  1155. faceLength ++;
  1156. if ( endOfFace ) {
  1157. if ( faceLength > 4 ) console.warn( 'THREE.FBXLoader: Polygons with more than four sides are not supported. Make sure to triangulate the geometry during export.' );
  1158. scope.genFace( buffers, geoInfo, facePositionIndexes, materialIndex, faceNormals, faceColors, faceUVs, faceWeights, faceWeightIndices, faceLength );
  1159. polygonIndex ++;
  1160. faceLength = 0;
  1161. // reset arrays for the next face
  1162. facePositionIndexes = [];
  1163. faceNormals = [];
  1164. faceColors = [];
  1165. faceUVs = [];
  1166. faceWeights = [];
  1167. faceWeightIndices = [];
  1168. }
  1169. } );
  1170. return buffers;
  1171. }
  1172. // Generate data for a single face in a geometry. If the face is a quad then split it into 2 tris
  1173. genFace( buffers, geoInfo, facePositionIndexes, materialIndex, faceNormals, faceColors, faceUVs, faceWeights, faceWeightIndices, faceLength ) {
  1174. for ( let i = 2; i < faceLength; i ++ ) {
  1175. buffers.vertex.push( geoInfo.vertexPositions[ facePositionIndexes[ 0 ] ] );
  1176. buffers.vertex.push( geoInfo.vertexPositions[ facePositionIndexes[ 1 ] ] );
  1177. buffers.vertex.push( geoInfo.vertexPositions[ facePositionIndexes[ 2 ] ] );
  1178. buffers.vertex.push( geoInfo.vertexPositions[ facePositionIndexes[ ( i - 1 ) * 3 ] ] );
  1179. buffers.vertex.push( geoInfo.vertexPositions[ facePositionIndexes[ ( i - 1 ) * 3 + 1 ] ] );
  1180. buffers.vertex.push( geoInfo.vertexPositions[ facePositionIndexes[ ( i - 1 ) * 3 + 2 ] ] );
  1181. buffers.vertex.push( geoInfo.vertexPositions[ facePositionIndexes[ i * 3 ] ] );
  1182. buffers.vertex.push( geoInfo.vertexPositions[ facePositionIndexes[ i * 3 + 1 ] ] );
  1183. buffers.vertex.push( geoInfo.vertexPositions[ facePositionIndexes[ i * 3 + 2 ] ] );
  1184. if ( geoInfo.skeleton ) {
  1185. buffers.vertexWeights.push( faceWeights[ 0 ] );
  1186. buffers.vertexWeights.push( faceWeights[ 1 ] );
  1187. buffers.vertexWeights.push( faceWeights[ 2 ] );
  1188. buffers.vertexWeights.push( faceWeights[ 3 ] );
  1189. buffers.vertexWeights.push( faceWeights[ ( i - 1 ) * 4 ] );
  1190. buffers.vertexWeights.push( faceWeights[ ( i - 1 ) * 4 + 1 ] );
  1191. buffers.vertexWeights.push( faceWeights[ ( i - 1 ) * 4 + 2 ] );
  1192. buffers.vertexWeights.push( faceWeights[ ( i - 1 ) * 4 + 3 ] );
  1193. buffers.vertexWeights.push( faceWeights[ i * 4 ] );
  1194. buffers.vertexWeights.push( faceWeights[ i * 4 + 1 ] );
  1195. buffers.vertexWeights.push( faceWeights[ i * 4 + 2 ] );
  1196. buffers.vertexWeights.push( faceWeights[ i * 4 + 3 ] );
  1197. buffers.weightsIndices.push( faceWeightIndices[ 0 ] );
  1198. buffers.weightsIndices.push( faceWeightIndices[ 1 ] );
  1199. buffers.weightsIndices.push( faceWeightIndices[ 2 ] );
  1200. buffers.weightsIndices.push( faceWeightIndices[ 3 ] );
  1201. buffers.weightsIndices.push( faceWeightIndices[ ( i - 1 ) * 4 ] );
  1202. buffers.weightsIndices.push( faceWeightIndices[ ( i - 1 ) * 4 + 1 ] );
  1203. buffers.weightsIndices.push( faceWeightIndices[ ( i - 1 ) * 4 + 2 ] );
  1204. buffers.weightsIndices.push( faceWeightIndices[ ( i - 1 ) * 4 + 3 ] );
  1205. buffers.weightsIndices.push( faceWeightIndices[ i * 4 ] );
  1206. buffers.weightsIndices.push( faceWeightIndices[ i * 4 + 1 ] );
  1207. buffers.weightsIndices.push( faceWeightIndices[ i * 4 + 2 ] );
  1208. buffers.weightsIndices.push( faceWeightIndices[ i * 4 + 3 ] );
  1209. }
  1210. if ( geoInfo.color ) {
  1211. buffers.colors.push( faceColors[ 0 ] );
  1212. buffers.colors.push( faceColors[ 1 ] );
  1213. buffers.colors.push( faceColors[ 2 ] );
  1214. buffers.colors.push( faceColors[ ( i - 1 ) * 3 ] );
  1215. buffers.colors.push( faceColors[ ( i - 1 ) * 3 + 1 ] );
  1216. buffers.colors.push( faceColors[ ( i - 1 ) * 3 + 2 ] );
  1217. buffers.colors.push( faceColors[ i * 3 ] );
  1218. buffers.colors.push( faceColors[ i * 3 + 1 ] );
  1219. buffers.colors.push( faceColors[ i * 3 + 2 ] );
  1220. }
  1221. if ( geoInfo.material && geoInfo.material.mappingType !== 'AllSame' ) {
  1222. buffers.materialIndex.push( materialIndex );
  1223. buffers.materialIndex.push( materialIndex );
  1224. buffers.materialIndex.push( materialIndex );
  1225. }
  1226. if ( geoInfo.normal ) {
  1227. buffers.normal.push( faceNormals[ 0 ] );
  1228. buffers.normal.push( faceNormals[ 1 ] );
  1229. buffers.normal.push( faceNormals[ 2 ] );
  1230. buffers.normal.push( faceNormals[ ( i - 1 ) * 3 ] );
  1231. buffers.normal.push( faceNormals[ ( i - 1 ) * 3 + 1 ] );
  1232. buffers.normal.push( faceNormals[ ( i - 1 ) * 3 + 2 ] );
  1233. buffers.normal.push( faceNormals[ i * 3 ] );
  1234. buffers.normal.push( faceNormals[ i * 3 + 1 ] );
  1235. buffers.normal.push( faceNormals[ i * 3 + 2 ] );
  1236. }
  1237. if ( geoInfo.uv ) {
  1238. geoInfo.uv.forEach( function ( uv, j ) {
  1239. if ( buffers.uvs[ j ] === undefined ) buffers.uvs[ j ] = [];
  1240. buffers.uvs[ j ].push( faceUVs[ j ][ 0 ] );
  1241. buffers.uvs[ j ].push( faceUVs[ j ][ 1 ] );
  1242. buffers.uvs[ j ].push( faceUVs[ j ][ ( i - 1 ) * 2 ] );
  1243. buffers.uvs[ j ].push( faceUVs[ j ][ ( i - 1 ) * 2 + 1 ] );
  1244. buffers.uvs[ j ].push( faceUVs[ j ][ i * 2 ] );
  1245. buffers.uvs[ j ].push( faceUVs[ j ][ i * 2 + 1 ] );
  1246. } );
  1247. }
  1248. }
  1249. }
  1250. addMorphTargets( parentGeo, parentGeoNode, morphTargets, preTransform ) {
  1251. if ( morphTargets.length === 0 ) return;
  1252. parentGeo.morphTargetsRelative = true;
  1253. parentGeo.morphAttributes.position = [];
  1254. // parentGeo.morphAttributes.normal = []; // not implemented
  1255. const scope = this;
  1256. morphTargets.forEach( function ( morphTarget ) {
  1257. morphTarget.rawTargets.forEach( function ( rawTarget ) {
  1258. const morphGeoNode = fbxTree.Objects.Geometry[ rawTarget.geoID ];
  1259. if ( morphGeoNode !== undefined ) {
  1260. scope.genMorphGeometry( parentGeo, parentGeoNode, morphGeoNode, preTransform, rawTarget.name );
  1261. }
  1262. } );
  1263. } );
  1264. }
  1265. // a morph geometry node is similar to a standard node, and the node is also contained
  1266. // in FBXTree.Objects.Geometry, however it can only have attributes for position, normal
  1267. // and a special attribute Index defining which vertices of the original geometry are affected
  1268. // Normal and position attributes only have data for the vertices that are affected by the morph
  1269. genMorphGeometry( parentGeo, parentGeoNode, morphGeoNode, preTransform, name ) {
  1270. const vertexIndices = ( parentGeoNode.PolygonVertexIndex !== undefined ) ? parentGeoNode.PolygonVertexIndex.a : [];
  1271. const morphPositionsSparse = ( morphGeoNode.Vertices !== undefined ) ? morphGeoNode.Vertices.a : [];
  1272. const indices = ( morphGeoNode.Indexes !== undefined ) ? morphGeoNode.Indexes.a : [];
  1273. const length = parentGeo.attributes.position.count * 3;
  1274. const morphPositions = new Float32Array( length );
  1275. for ( let i = 0; i < indices.length; i ++ ) {
  1276. const morphIndex = indices[ i ] * 3;
  1277. morphPositions[ morphIndex ] = morphPositionsSparse[ i * 3 ];
  1278. morphPositions[ morphIndex + 1 ] = morphPositionsSparse[ i * 3 + 1 ];
  1279. morphPositions[ morphIndex + 2 ] = morphPositionsSparse[ i * 3 + 2 ];
  1280. }
  1281. // TODO: add morph normal support
  1282. const morphGeoInfo = {
  1283. vertexIndices: vertexIndices,
  1284. vertexPositions: morphPositions,
  1285. };
  1286. const morphBuffers = this.genBuffers( morphGeoInfo );
  1287. const positionAttribute = new Float32BufferAttribute( morphBuffers.vertex, 3 );
  1288. positionAttribute.name = name || morphGeoNode.attrName;
  1289. positionAttribute.applyMatrix4( preTransform );
  1290. parentGeo.morphAttributes.position.push( positionAttribute );
  1291. }
  1292. // Parse normal from FBXTree.Objects.Geometry.LayerElementNormal if it exists
  1293. parseNormals( NormalNode ) {
  1294. const mappingType = NormalNode.MappingInformationType;
  1295. const referenceType = NormalNode.ReferenceInformationType;
  1296. const buffer = NormalNode.Normals.a;
  1297. let indexBuffer = [];
  1298. if ( referenceType === 'IndexToDirect' ) {
  1299. if ( 'NormalIndex' in NormalNode ) {
  1300. indexBuffer = NormalNode.NormalIndex.a;
  1301. } else if ( 'NormalsIndex' in NormalNode ) {
  1302. indexBuffer = NormalNode.NormalsIndex.a;
  1303. }
  1304. }
  1305. return {
  1306. dataSize: 3,
  1307. buffer: buffer,
  1308. indices: indexBuffer,
  1309. mappingType: mappingType,
  1310. referenceType: referenceType
  1311. };
  1312. }
  1313. // Parse UVs from FBXTree.Objects.Geometry.LayerElementUV if it exists
  1314. parseUVs( UVNode ) {
  1315. const mappingType = UVNode.MappingInformationType;
  1316. const referenceType = UVNode.ReferenceInformationType;
  1317. const buffer = UVNode.UV.a;
  1318. let indexBuffer = [];
  1319. if ( referenceType === 'IndexToDirect' ) {
  1320. indexBuffer = UVNode.UVIndex.a;
  1321. }
  1322. return {
  1323. dataSize: 2,
  1324. buffer: buffer,
  1325. indices: indexBuffer,
  1326. mappingType: mappingType,
  1327. referenceType: referenceType
  1328. };
  1329. }
  1330. // Parse Vertex Colors from FBXTree.Objects.Geometry.LayerElementColor if it exists
  1331. parseVertexColors( ColorNode ) {
  1332. const mappingType = ColorNode.MappingInformationType;
  1333. const referenceType = ColorNode.ReferenceInformationType;
  1334. const buffer = ColorNode.Colors.a;
  1335. let indexBuffer = [];
  1336. if ( referenceType === 'IndexToDirect' ) {
  1337. indexBuffer = ColorNode.ColorIndex.a;
  1338. }
  1339. for ( let i = 0, c = new Color(); i < buffer.length; i += 4 ) {
  1340. c.fromArray( buffer, i ).convertSRGBToLinear().toArray( buffer, i );
  1341. }
  1342. return {
  1343. dataSize: 4,
  1344. buffer: buffer,
  1345. indices: indexBuffer,
  1346. mappingType: mappingType,
  1347. referenceType: referenceType
  1348. };
  1349. }
  1350. // Parse mapping and material data in FBXTree.Objects.Geometry.LayerElementMaterial if it exists
  1351. parseMaterialIndices( MaterialNode ) {
  1352. const mappingType = MaterialNode.MappingInformationType;
  1353. const referenceType = MaterialNode.ReferenceInformationType;
  1354. if ( mappingType === 'NoMappingInformation' ) {
  1355. return {
  1356. dataSize: 1,
  1357. buffer: [ 0 ],
  1358. indices: [ 0 ],
  1359. mappingType: 'AllSame',
  1360. referenceType: referenceType
  1361. };
  1362. }
  1363. const materialIndexBuffer = MaterialNode.Materials.a;
  1364. // Since materials are stored as indices, there's a bit of a mismatch between FBX and what
  1365. // we expect.So we create an intermediate buffer that points to the index in the buffer,
  1366. // for conforming with the other functions we've written for other data.
  1367. const materialIndices = [];
  1368. for ( let i = 0; i < materialIndexBuffer.length; ++ i ) {
  1369. materialIndices.push( i );
  1370. }
  1371. return {
  1372. dataSize: 1,
  1373. buffer: materialIndexBuffer,
  1374. indices: materialIndices,
  1375. mappingType: mappingType,
  1376. referenceType: referenceType
  1377. };
  1378. }
  1379. // Generate a NurbGeometry from a node in FBXTree.Objects.Geometry
  1380. parseNurbsGeometry( geoNode ) {
  1381. const order = parseInt( geoNode.Order );
  1382. if ( isNaN( order ) ) {
  1383. console.error( 'THREE.FBXLoader: Invalid Order %s given for geometry ID: %s', geoNode.Order, geoNode.id );
  1384. return new BufferGeometry();
  1385. }
  1386. const degree = order - 1;
  1387. const knots = geoNode.KnotVector.a;
  1388. const controlPoints = [];
  1389. const pointsValues = geoNode.Points.a;
  1390. for ( let i = 0, l = pointsValues.length; i < l; i += 4 ) {
  1391. controlPoints.push( new Vector4().fromArray( pointsValues, i ) );
  1392. }
  1393. let startKnot, endKnot;
  1394. if ( geoNode.Form === 'Closed' ) {
  1395. controlPoints.push( controlPoints[ 0 ] );
  1396. } else if ( geoNode.Form === 'Periodic' ) {
  1397. startKnot = degree;
  1398. endKnot = knots.length - 1 - startKnot;
  1399. for ( let i = 0; i < degree; ++ i ) {
  1400. controlPoints.push( controlPoints[ i ] );
  1401. }
  1402. }
  1403. const curve = new NURBSCurve( degree, knots, controlPoints, startKnot, endKnot );
  1404. const points = curve.getPoints( controlPoints.length * 12 );
  1405. return new BufferGeometry().setFromPoints( points );
  1406. }
  1407. }
  1408. // parse animation data from FBXTree
  1409. class AnimationParser {
  1410. // take raw animation clips and turn them into three.js animation clips
  1411. parse() {
  1412. const animationClips = [];
  1413. const rawClips = this.parseClips();
  1414. if ( rawClips !== undefined ) {
  1415. for ( const key in rawClips ) {
  1416. const rawClip = rawClips[ key ];
  1417. const clip = this.addClip( rawClip );
  1418. animationClips.push( clip );
  1419. }
  1420. }
  1421. return animationClips;
  1422. }
  1423. parseClips() {
  1424. // since the actual transformation data is stored in FBXTree.Objects.AnimationCurve,
  1425. // if this is undefined we can safely assume there are no animations
  1426. if ( fbxTree.Objects.AnimationCurve === undefined ) return undefined;
  1427. const curveNodesMap = this.parseAnimationCurveNodes();
  1428. this.parseAnimationCurves( curveNodesMap );
  1429. const layersMap = this.parseAnimationLayers( curveNodesMap );
  1430. const rawClips = this.parseAnimStacks( layersMap );
  1431. return rawClips;
  1432. }
  1433. // parse nodes in FBXTree.Objects.AnimationCurveNode
  1434. // each AnimationCurveNode holds data for an animation transform for a model (e.g. left arm rotation )
  1435. // and is referenced by an AnimationLayer
  1436. parseAnimationCurveNodes() {
  1437. const rawCurveNodes = fbxTree.Objects.AnimationCurveNode;
  1438. const curveNodesMap = new Map();
  1439. for ( const nodeID in rawCurveNodes ) {
  1440. const rawCurveNode = rawCurveNodes[ nodeID ];
  1441. if ( rawCurveNode.attrName.match( /S|R|T|DeformPercent/ ) !== null ) {
  1442. const curveNode = {
  1443. id: rawCurveNode.id,
  1444. attr: rawCurveNode.attrName,
  1445. curves: {},
  1446. };
  1447. curveNodesMap.set( curveNode.id, curveNode );
  1448. }
  1449. }
  1450. return curveNodesMap;
  1451. }
  1452. // parse nodes in FBXTree.Objects.AnimationCurve and connect them up to
  1453. // previously parsed AnimationCurveNodes. Each AnimationCurve holds data for a single animated
  1454. // axis ( e.g. times and values of x rotation)
  1455. parseAnimationCurves( curveNodesMap ) {
  1456. const rawCurves = fbxTree.Objects.AnimationCurve;
  1457. // TODO: Many values are identical up to roundoff error, but won't be optimised
  1458. // e.g. position times: [0, 0.4, 0. 8]
  1459. // position values: [7.23538335023477e-7, 93.67518615722656, -0.9982695579528809, 7.23538335023477e-7, 93.67518615722656, -0.9982695579528809, 7.235384487103147e-7, 93.67520904541016, -0.9982695579528809]
  1460. // clearly, this should be optimised to
  1461. // times: [0], positions [7.23538335023477e-7, 93.67518615722656, -0.9982695579528809]
  1462. // this shows up in nearly every FBX file, and generally time array is length > 100
  1463. for ( const nodeID in rawCurves ) {
  1464. const animationCurve = {
  1465. id: rawCurves[ nodeID ].id,
  1466. times: rawCurves[ nodeID ].KeyTime.a.map( convertFBXTimeToSeconds ),
  1467. values: rawCurves[ nodeID ].KeyValueFloat.a,
  1468. };
  1469. const relationships = connections.get( animationCurve.id );
  1470. if ( relationships !== undefined ) {
  1471. const animationCurveID = relationships.parents[ 0 ].ID;
  1472. const animationCurveRelationship = relationships.parents[ 0 ].relationship;
  1473. if ( animationCurveRelationship.match( /X/ ) ) {
  1474. curveNodesMap.get( animationCurveID ).curves[ 'x' ] = animationCurve;
  1475. } else if ( animationCurveRelationship.match( /Y/ ) ) {
  1476. curveNodesMap.get( animationCurveID ).curves[ 'y' ] = animationCurve;
  1477. } else if ( animationCurveRelationship.match( /Z/ ) ) {
  1478. curveNodesMap.get( animationCurveID ).curves[ 'z' ] = animationCurve;
  1479. } else if ( animationCurveRelationship.match( /DeformPercent/ ) && curveNodesMap.has( animationCurveID ) ) {
  1480. curveNodesMap.get( animationCurveID ).curves[ 'morph' ] = animationCurve;
  1481. }
  1482. }
  1483. }
  1484. }
  1485. // parse nodes in FBXTree.Objects.AnimationLayer. Each layers holds references
  1486. // to various AnimationCurveNodes and is referenced by an AnimationStack node
  1487. // note: theoretically a stack can have multiple layers, however in practice there always seems to be one per stack
  1488. parseAnimationLayers( curveNodesMap ) {
  1489. const rawLayers = fbxTree.Objects.AnimationLayer;
  1490. const layersMap = new Map();
  1491. for ( const nodeID in rawLayers ) {
  1492. const layerCurveNodes = [];
  1493. const connection = connections.get( parseInt( nodeID ) );
  1494. if ( connection !== undefined ) {
  1495. // all the animationCurveNodes used in the layer
  1496. const children = connection.children;
  1497. children.forEach( function ( child, i ) {
  1498. if ( curveNodesMap.has( child.ID ) ) {
  1499. const curveNode = curveNodesMap.get( child.ID );
  1500. // check that the curves are defined for at least one axis, otherwise ignore the curveNode
  1501. if ( curveNode.curves.x !== undefined || curveNode.curves.y !== undefined || curveNode.curves.z !== undefined ) {
  1502. if ( layerCurveNodes[ i ] === undefined ) {
  1503. const modelID = connections.get( child.ID ).parents.filter( function ( parent ) {
  1504. return parent.relationship !== undefined;
  1505. } )[ 0 ].ID;
  1506. if ( modelID !== undefined ) {
  1507. const rawModel = fbxTree.Objects.Model[ modelID.toString() ];
  1508. if ( rawModel === undefined ) {
  1509. console.warn( 'THREE.FBXLoader: Encountered a unused curve.', child );
  1510. return;
  1511. }
  1512. const node = {
  1513. modelName: rawModel.attrName ? PropertyBinding.sanitizeNodeName( rawModel.attrName ) : '',
  1514. ID: rawModel.id,
  1515. initialPosition: [ 0, 0, 0 ],
  1516. initialRotation: [ 0, 0, 0 ],
  1517. initialScale: [ 1, 1, 1 ],
  1518. };
  1519. sceneGraph.traverse( function ( child ) {
  1520. if ( child.ID === rawModel.id ) {
  1521. node.transform = child.matrix;
  1522. if ( child.userData.transformData ) node.eulerOrder = child.userData.transformData.eulerOrder;
  1523. }
  1524. } );
  1525. if ( ! node.transform ) node.transform = new Matrix4();
  1526. // if the animated model is pre rotated, we'll have to apply the pre rotations to every
  1527. // animation value as well
  1528. if ( 'PreRotation' in rawModel ) node.preRotation = rawModel.PreRotation.value;
  1529. if ( 'PostRotation' in rawModel ) node.postRotation = rawModel.PostRotation.value;
  1530. layerCurveNodes[ i ] = node;
  1531. }
  1532. }
  1533. if ( layerCurveNodes[ i ] ) layerCurveNodes[ i ][ curveNode.attr ] = curveNode;
  1534. } else if ( curveNode.curves.morph !== undefined ) {
  1535. if ( layerCurveNodes[ i ] === undefined ) {
  1536. const deformerID = connections.get( child.ID ).parents.filter( function ( parent ) {
  1537. return parent.relationship !== undefined;
  1538. } )[ 0 ].ID;
  1539. const morpherID = connections.get( deformerID ).parents[ 0 ].ID;
  1540. const geoID = connections.get( morpherID ).parents[ 0 ].ID;
  1541. // assuming geometry is not used in more than one model
  1542. const modelID = connections.get( geoID ).parents[ 0 ].ID;
  1543. const rawModel = fbxTree.Objects.Model[ modelID ];
  1544. const node = {
  1545. modelName: rawModel.attrName ? PropertyBinding.sanitizeNodeName( rawModel.attrName ) : '',
  1546. morphName: fbxTree.Objects.Deformer[ deformerID ].attrName,
  1547. };
  1548. layerCurveNodes[ i ] = node;
  1549. }
  1550. layerCurveNodes[ i ][ curveNode.attr ] = curveNode;
  1551. }
  1552. }
  1553. } );
  1554. layersMap.set( parseInt( nodeID ), layerCurveNodes );
  1555. }
  1556. }
  1557. return layersMap;
  1558. }
  1559. // parse nodes in FBXTree.Objects.AnimationStack. These are the top level node in the animation
  1560. // hierarchy. Each Stack node will be used to create a AnimationClip
  1561. parseAnimStacks( layersMap ) {
  1562. const rawStacks = fbxTree.Objects.AnimationStack;
  1563. // connect the stacks (clips) up to the layers
  1564. const rawClips = {};
  1565. for ( const nodeID in rawStacks ) {
  1566. const children = connections.get( parseInt( nodeID ) ).children;
  1567. if ( children.length > 1 ) {
  1568. // it seems like stacks will always be associated with a single layer. But just in case there are files
  1569. // where there are multiple layers per stack, we'll display a warning
  1570. console.warn( 'THREE.FBXLoader: Encountered an animation stack with multiple layers, this is currently not supported. Ignoring subsequent layers.' );
  1571. }
  1572. const layer = layersMap.get( children[ 0 ].ID );
  1573. rawClips[ nodeID ] = {
  1574. name: rawStacks[ nodeID ].attrName,
  1575. layer: layer,
  1576. };
  1577. }
  1578. return rawClips;
  1579. }
  1580. addClip( rawClip ) {
  1581. let tracks = [];
  1582. const scope = this;
  1583. rawClip.layer.forEach( function ( rawTracks ) {
  1584. tracks = tracks.concat( scope.generateTracks( rawTracks ) );
  1585. } );
  1586. return new AnimationClip( rawClip.name, - 1, tracks );
  1587. }
  1588. generateTracks( rawTracks ) {
  1589. const tracks = [];
  1590. let initialPosition = new Vector3();
  1591. let initialRotation = new Quaternion();
  1592. let initialScale = new Vector3();
  1593. if ( rawTracks.transform ) rawTracks.transform.decompose( initialPosition, initialRotation, initialScale );
  1594. initialPosition = initialPosition.toArray();
  1595. initialRotation = new Euler().setFromQuaternion( initialRotation, rawTracks.eulerOrder ).toArray();
  1596. initialScale = initialScale.toArray();
  1597. if ( rawTracks.T !== undefined && Object.keys( rawTracks.T.curves ).length > 0 ) {
  1598. const positionTrack = this.generateVectorTrack( rawTracks.modelName, rawTracks.T.curves, initialPosition, 'position' );
  1599. if ( positionTrack !== undefined ) tracks.push( positionTrack );
  1600. }
  1601. if ( rawTracks.R !== undefined && Object.keys( rawTracks.R.curves ).length > 0 ) {
  1602. const rotationTrack = this.generateRotationTrack( rawTracks.modelName, rawTracks.R.curves, initialRotation, rawTracks.preRotation, rawTracks.postRotation, rawTracks.eulerOrder );
  1603. if ( rotationTrack !== undefined ) tracks.push( rotationTrack );
  1604. }
  1605. if ( rawTracks.S !== undefined && Object.keys( rawTracks.S.curves ).length > 0 ) {
  1606. const scaleTrack = this.generateVectorTrack( rawTracks.modelName, rawTracks.S.curves, initialScale, 'scale' );
  1607. if ( scaleTrack !== undefined ) tracks.push( scaleTrack );
  1608. }
  1609. if ( rawTracks.DeformPercent !== undefined ) {
  1610. const morphTrack = this.generateMorphTrack( rawTracks );
  1611. if ( morphTrack !== undefined ) tracks.push( morphTrack );
  1612. }
  1613. return tracks;
  1614. }
  1615. generateVectorTrack( modelName, curves, initialValue, type ) {
  1616. const times = this.getTimesForAllAxes( curves );
  1617. const values = this.getKeyframeTrackValues( times, curves, initialValue );
  1618. return new VectorKeyframeTrack( modelName + '.' + type, times, values );
  1619. }
  1620. generateRotationTrack( modelName, curves, initialValue, preRotation, postRotation, eulerOrder ) {
  1621. if ( curves.x !== undefined ) {
  1622. this.interpolateRotations( curves.x );
  1623. curves.x.values = curves.x.values.map( MathUtils.degToRad );
  1624. }
  1625. if ( curves.y !== undefined ) {
  1626. this.interpolateRotations( curves.y );
  1627. curves.y.values = curves.y.values.map( MathUtils.degToRad );
  1628. }
  1629. if ( curves.z !== undefined ) {
  1630. this.interpolateRotations( curves.z );
  1631. curves.z.values = curves.z.values.map( MathUtils.degToRad );
  1632. }
  1633. const times = this.getTimesForAllAxes( curves );
  1634. const values = this.getKeyframeTrackValues( times, curves, initialValue );
  1635. if ( preRotation !== undefined ) {
  1636. preRotation = preRotation.map( MathUtils.degToRad );
  1637. preRotation.push( eulerOrder );
  1638. preRotation = new Euler().fromArray( preRotation );
  1639. preRotation = new Quaternion().setFromEuler( preRotation );
  1640. }
  1641. if ( postRotation !== undefined ) {
  1642. postRotation = postRotation.map( MathUtils.degToRad );
  1643. postRotation.push( eulerOrder );
  1644. postRotation = new Euler().fromArray( postRotation );
  1645. postRotation = new Quaternion().setFromEuler( postRotation ).invert();
  1646. }
  1647. const quaternion = new Quaternion();
  1648. const euler = new Euler();
  1649. const quaternionValues = [];
  1650. for ( let i = 0; i < values.length; i += 3 ) {
  1651. euler.set( values[ i ], values[ i + 1 ], values[ i + 2 ], eulerOrder );
  1652. quaternion.setFromEuler( euler );
  1653. if ( preRotation !== undefined ) quaternion.premultiply( preRotation );
  1654. if ( postRotation !== undefined ) quaternion.multiply( postRotation );
  1655. quaternion.toArray( quaternionValues, ( i / 3 ) * 4 );
  1656. }
  1657. return new QuaternionKeyframeTrack( modelName + '.quaternion', times, quaternionValues );
  1658. }
  1659. generateMorphTrack( rawTracks ) {
  1660. const curves = rawTracks.DeformPercent.curves.morph;
  1661. const values = curves.values.map( function ( val ) {
  1662. return val / 100;
  1663. } );
  1664. const morphNum = sceneGraph.getObjectByName( rawTracks.modelName ).morphTargetDictionary[ rawTracks.morphName ];
  1665. return new NumberKeyframeTrack( rawTracks.modelName + '.morphTargetInfluences[' + morphNum + ']', curves.times, values );
  1666. }
  1667. // For all animated objects, times are defined separately for each axis
  1668. // Here we'll combine the times into one sorted array without duplicates
  1669. getTimesForAllAxes( curves ) {
  1670. let times = [];
  1671. // first join together the times for each axis, if defined
  1672. if ( curves.x !== undefined ) times = times.concat( curves.x.times );
  1673. if ( curves.y !== undefined ) times = times.concat( curves.y.times );
  1674. if ( curves.z !== undefined ) times = times.concat( curves.z.times );
  1675. // then sort them
  1676. times = times.sort( function ( a, b ) {
  1677. return a - b;
  1678. } );
  1679. // and remove duplicates
  1680. if ( times.length > 1 ) {
  1681. let targetIndex = 1;
  1682. let lastValue = times[ 0 ];
  1683. for ( let i = 1; i < times.length; i ++ ) {
  1684. const currentValue = times[ i ];
  1685. if ( currentValue !== lastValue ) {
  1686. times[ targetIndex ] = currentValue;
  1687. lastValue = currentValue;
  1688. targetIndex ++;
  1689. }
  1690. }
  1691. times = times.slice( 0, targetIndex );
  1692. }
  1693. return times;
  1694. }
  1695. getKeyframeTrackValues( times, curves, initialValue ) {
  1696. const prevValue = initialValue;
  1697. const values = [];
  1698. let xIndex = - 1;
  1699. let yIndex = - 1;
  1700. let zIndex = - 1;
  1701. times.forEach( function ( time ) {
  1702. if ( curves.x ) xIndex = curves.x.times.indexOf( time );
  1703. if ( curves.y ) yIndex = curves.y.times.indexOf( time );
  1704. if ( curves.z ) zIndex = curves.z.times.indexOf( time );
  1705. // if there is an x value defined for this frame, use that
  1706. if ( xIndex !== - 1 ) {
  1707. const xValue = curves.x.values[ xIndex ];
  1708. values.push( xValue );
  1709. prevValue[ 0 ] = xValue;
  1710. } else {
  1711. // otherwise use the x value from the previous frame
  1712. values.push( prevValue[ 0 ] );
  1713. }
  1714. if ( yIndex !== - 1 ) {
  1715. const yValue = curves.y.values[ yIndex ];
  1716. values.push( yValue );
  1717. prevValue[ 1 ] = yValue;
  1718. } else {
  1719. values.push( prevValue[ 1 ] );
  1720. }
  1721. if ( zIndex !== - 1 ) {
  1722. const zValue = curves.z.values[ zIndex ];
  1723. values.push( zValue );
  1724. prevValue[ 2 ] = zValue;
  1725. } else {
  1726. values.push( prevValue[ 2 ] );
  1727. }
  1728. } );
  1729. return values;
  1730. }
  1731. // Rotations are defined as Euler angles which can have values of any size
  1732. // These will be converted to quaternions which don't support values greater than
  1733. // PI, so we'll interpolate large rotations
  1734. interpolateRotations( curve ) {
  1735. for ( let i = 1; i < curve.values.length; i ++ ) {
  1736. const initialValue = curve.values[ i - 1 ];
  1737. const valuesSpan = curve.values[ i ] - initialValue;
  1738. const absoluteSpan = Math.abs( valuesSpan );
  1739. if ( absoluteSpan >= 180 ) {
  1740. const numSubIntervals = absoluteSpan / 180;
  1741. const step = valuesSpan / numSubIntervals;
  1742. let nextValue = initialValue + step;
  1743. const initialTime = curve.times[ i - 1 ];
  1744. const timeSpan = curve.times[ i ] - initialTime;
  1745. const interval = timeSpan / numSubIntervals;
  1746. let nextTime = initialTime + interval;
  1747. const interpolatedTimes = [];
  1748. const interpolatedValues = [];
  1749. while ( nextTime < curve.times[ i ] ) {
  1750. interpolatedTimes.push( nextTime );
  1751. nextTime += interval;
  1752. interpolatedValues.push( nextValue );
  1753. nextValue += step;
  1754. }
  1755. curve.times = inject( curve.times, i, interpolatedTimes );
  1756. curve.values = inject( curve.values, i, interpolatedValues );
  1757. }
  1758. }
  1759. }
  1760. }
  1761. // parse an FBX file in ASCII format
  1762. class TextParser {
  1763. getPrevNode() {
  1764. return this.nodeStack[ this.currentIndent - 2 ];
  1765. }
  1766. getCurrentNode() {
  1767. return this.nodeStack[ this.currentIndent - 1 ];
  1768. }
  1769. getCurrentProp() {
  1770. return this.currentProp;
  1771. }
  1772. pushStack( node ) {
  1773. this.nodeStack.push( node );
  1774. this.currentIndent += 1;
  1775. }
  1776. popStack() {
  1777. this.nodeStack.pop();
  1778. this.currentIndent -= 1;
  1779. }
  1780. setCurrentProp( val, name ) {
  1781. this.currentProp = val;
  1782. this.currentPropName = name;
  1783. }
  1784. parse( text ) {
  1785. this.currentIndent = 0;
  1786. this.allNodes = new FBXTree();
  1787. this.nodeStack = [];
  1788. this.currentProp = [];
  1789. this.currentPropName = '';
  1790. const scope = this;
  1791. const split = text.split( /[\r\n]+/ );
  1792. split.forEach( function ( line, i ) {
  1793. const matchComment = line.match( /^[\s\t]*;/ );
  1794. const matchEmpty = line.match( /^[\s\t]*$/ );
  1795. if ( matchComment || matchEmpty ) return;
  1796. const matchBeginning = line.match( '^\\t{' + scope.currentIndent + '}(\\w+):(.*){', '' );
  1797. const matchProperty = line.match( '^\\t{' + ( scope.currentIndent ) + '}(\\w+):[\\s\\t\\r\\n](.*)' );
  1798. const matchEnd = line.match( '^\\t{' + ( scope.currentIndent - 1 ) + '}}' );
  1799. if ( matchBeginning ) {
  1800. scope.parseNodeBegin( line, matchBeginning );
  1801. } else if ( matchProperty ) {
  1802. scope.parseNodeProperty( line, matchProperty, split[ ++ i ] );
  1803. } else if ( matchEnd ) {
  1804. scope.popStack();
  1805. } else if ( line.match( /^[^\s\t}]/ ) ) {
  1806. // large arrays are split over multiple lines terminated with a ',' character
  1807. // if this is encountered the line needs to be joined to the previous line
  1808. scope.parseNodePropertyContinued( line );
  1809. }
  1810. } );
  1811. return this.allNodes;
  1812. }
  1813. parseNodeBegin( line, property ) {
  1814. const nodeName = property[ 1 ].trim().replace( /^"/, '' ).replace( /"$/, '' );
  1815. const nodeAttrs = property[ 2 ].split( ',' ).map( function ( attr ) {
  1816. return attr.trim().replace( /^"/, '' ).replace( /"$/, '' );
  1817. } );
  1818. const node = { name: nodeName };
  1819. const attrs = this.parseNodeAttr( nodeAttrs );
  1820. const currentNode = this.getCurrentNode();
  1821. // a top node
  1822. if ( this.currentIndent === 0 ) {
  1823. this.allNodes.add( nodeName, node );
  1824. } else { // a subnode
  1825. // if the subnode already exists, append it
  1826. if ( nodeName in currentNode ) {
  1827. // special case Pose needs PoseNodes as an array
  1828. if ( nodeName === 'PoseNode' ) {
  1829. currentNode.PoseNode.push( node );
  1830. } else if ( currentNode[ nodeName ].id !== undefined ) {
  1831. currentNode[ nodeName ] = {};
  1832. currentNode[ nodeName ][ currentNode[ nodeName ].id ] = currentNode[ nodeName ];
  1833. }
  1834. if ( attrs.id !== '' ) currentNode[ nodeName ][ attrs.id ] = node;
  1835. } else if ( typeof attrs.id === 'number' ) {
  1836. currentNode[ nodeName ] = {};
  1837. currentNode[ nodeName ][ attrs.id ] = node;
  1838. } else if ( nodeName !== 'Properties70' ) {
  1839. if ( nodeName === 'PoseNode' ) currentNode[ nodeName ] = [ node ];
  1840. else currentNode[ nodeName ] = node;
  1841. }
  1842. }
  1843. if ( typeof attrs.id === 'number' ) node.id = attrs.id;
  1844. if ( attrs.name !== '' ) node.attrName = attrs.name;
  1845. if ( attrs.type !== '' ) node.attrType = attrs.type;
  1846. this.pushStack( node );
  1847. }
  1848. parseNodeAttr( attrs ) {
  1849. let id = attrs[ 0 ];
  1850. if ( attrs[ 0 ] !== '' ) {
  1851. id = parseInt( attrs[ 0 ] );
  1852. if ( isNaN( id ) ) {
  1853. id = attrs[ 0 ];
  1854. }
  1855. }
  1856. let name = '', type = '';
  1857. if ( attrs.length > 1 ) {
  1858. name = attrs[ 1 ].replace( /^(\w+)::/, '' );
  1859. type = attrs[ 2 ];
  1860. }
  1861. return { id: id, name: name, type: type };
  1862. }
  1863. parseNodeProperty( line, property, contentLine ) {
  1864. let propName = property[ 1 ].replace( /^"/, '' ).replace( /"$/, '' ).trim();
  1865. let propValue = property[ 2 ].replace( /^"/, '' ).replace( /"$/, '' ).trim();
  1866. // for special case: base64 image data follows "Content: ," line
  1867. // Content: ,
  1868. // "/9j/4RDaRXhpZgAATU0A..."
  1869. if ( propName === 'Content' && propValue === ',' ) {
  1870. propValue = contentLine.replace( /"/g, '' ).replace( /,$/, '' ).trim();
  1871. }
  1872. const currentNode = this.getCurrentNode();
  1873. const parentName = currentNode.name;
  1874. if ( parentName === 'Properties70' ) {
  1875. this.parseNodeSpecialProperty( line, propName, propValue );
  1876. return;
  1877. }
  1878. // Connections
  1879. if ( propName === 'C' ) {
  1880. const connProps = propValue.split( ',' ).slice( 1 );
  1881. const from = parseInt( connProps[ 0 ] );
  1882. const to = parseInt( connProps[ 1 ] );
  1883. let rest = propValue.split( ',' ).slice( 3 );
  1884. rest = rest.map( function ( elem ) {
  1885. return elem.trim().replace( /^"/, '' );
  1886. } );
  1887. propName = 'connections';
  1888. propValue = [ from, to ];
  1889. append( propValue, rest );
  1890. if ( currentNode[ propName ] === undefined ) {
  1891. currentNode[ propName ] = [];
  1892. }
  1893. }
  1894. // Node
  1895. if ( propName === 'Node' ) currentNode.id = propValue;
  1896. // connections
  1897. if ( propName in currentNode && Array.isArray( currentNode[ propName ] ) ) {
  1898. currentNode[ propName ].push( propValue );
  1899. } else {
  1900. if ( propName !== 'a' ) currentNode[ propName ] = propValue;
  1901. else currentNode.a = propValue;
  1902. }
  1903. this.setCurrentProp( currentNode, propName );
  1904. // convert string to array, unless it ends in ',' in which case more will be added to it
  1905. if ( propName === 'a' && propValue.slice( - 1 ) !== ',' ) {
  1906. currentNode.a = parseNumberArray( propValue );
  1907. }
  1908. }
  1909. parseNodePropertyContinued( line ) {
  1910. const currentNode = this.getCurrentNode();
  1911. currentNode.a += line;
  1912. // if the line doesn't end in ',' we have reached the end of the property value
  1913. // so convert the string to an array
  1914. if ( line.slice( - 1 ) !== ',' ) {
  1915. currentNode.a = parseNumberArray( currentNode.a );
  1916. }
  1917. }
  1918. // parse "Property70"
  1919. parseNodeSpecialProperty( line, propName, propValue ) {
  1920. // split this
  1921. // P: "Lcl Scaling", "Lcl Scaling", "", "A",1,1,1
  1922. // into array like below
  1923. // ["Lcl Scaling", "Lcl Scaling", "", "A", "1,1,1" ]
  1924. const props = propValue.split( '",' ).map( function ( prop ) {
  1925. return prop.trim().replace( /^\"/, '' ).replace( /\s/, '_' );
  1926. } );
  1927. const innerPropName = props[ 0 ];
  1928. const innerPropType1 = props[ 1 ];
  1929. const innerPropType2 = props[ 2 ];
  1930. const innerPropFlag = props[ 3 ];
  1931. let innerPropValue = props[ 4 ];
  1932. // cast values where needed, otherwise leave as strings
  1933. switch ( innerPropType1 ) {
  1934. case 'int':
  1935. case 'enum':
  1936. case 'bool':
  1937. case 'ULongLong':
  1938. case 'double':
  1939. case 'Number':
  1940. case 'FieldOfView':
  1941. innerPropValue = parseFloat( innerPropValue );
  1942. break;
  1943. case 'Color':
  1944. case 'ColorRGB':
  1945. case 'Vector3D':
  1946. case 'Lcl_Translation':
  1947. case 'Lcl_Rotation':
  1948. case 'Lcl_Scaling':
  1949. innerPropValue = parseNumberArray( innerPropValue );
  1950. break;
  1951. }
  1952. // CAUTION: these props must append to parent's parent
  1953. this.getPrevNode()[ innerPropName ] = {
  1954. 'type': innerPropType1,
  1955. 'type2': innerPropType2,
  1956. 'flag': innerPropFlag,
  1957. 'value': innerPropValue
  1958. };
  1959. this.setCurrentProp( this.getPrevNode(), innerPropName );
  1960. }
  1961. }
  1962. // Parse an FBX file in Binary format
  1963. class BinaryParser {
  1964. parse( buffer ) {
  1965. const reader = new BinaryReader( buffer );
  1966. reader.skip( 23 ); // skip magic 23 bytes
  1967. const version = reader.getUint32();
  1968. if ( version < 6400 ) {
  1969. throw new Error( 'THREE.FBXLoader: FBX version not supported, FileVersion: ' + version );
  1970. }
  1971. const allNodes = new FBXTree();
  1972. while ( ! this.endOfContent( reader ) ) {
  1973. const node = this.parseNode( reader, version );
  1974. if ( node !== null ) allNodes.add( node.name, node );
  1975. }
  1976. return allNodes;
  1977. }
  1978. // Check if reader has reached the end of content.
  1979. endOfContent( reader ) {
  1980. // footer size: 160bytes + 16-byte alignment padding
  1981. // - 16bytes: magic
  1982. // - padding til 16-byte alignment (at least 1byte?)
  1983. // (seems like some exporters embed fixed 15 or 16bytes?)
  1984. // - 4bytes: magic
  1985. // - 4bytes: version
  1986. // - 120bytes: zero
  1987. // - 16bytes: magic
  1988. if ( reader.size() % 16 === 0 ) {
  1989. return ( ( reader.getOffset() + 160 + 16 ) & ~ 0xf ) >= reader.size();
  1990. } else {
  1991. return reader.getOffset() + 160 + 16 >= reader.size();
  1992. }
  1993. }
  1994. // recursively parse nodes until the end of the file is reached
  1995. parseNode( reader, version ) {
  1996. const node = {};
  1997. // The first three data sizes depends on version.
  1998. const endOffset = ( version >= 7500 ) ? reader.getUint64() : reader.getUint32();
  1999. const numProperties = ( version >= 7500 ) ? reader.getUint64() : reader.getUint32();
  2000. ( version >= 7500 ) ? reader.getUint64() : reader.getUint32(); // the returned propertyListLen is not used
  2001. const nameLen = reader.getUint8();
  2002. const name = reader.getString( nameLen );
  2003. // Regards this node as NULL-record if endOffset is zero
  2004. if ( endOffset === 0 ) return null;
  2005. const propertyList = [];
  2006. for ( let i = 0; i < numProperties; i ++ ) {
  2007. propertyList.push( this.parseProperty( reader ) );
  2008. }
  2009. // Regards the first three elements in propertyList as id, attrName, and attrType
  2010. const id = propertyList.length > 0 ? propertyList[ 0 ] : '';
  2011. const attrName = propertyList.length > 1 ? propertyList[ 1 ] : '';
  2012. const attrType = propertyList.length > 2 ? propertyList[ 2 ] : '';
  2013. // check if this node represents just a single property
  2014. // like (name, 0) set or (name2, [0, 1, 2]) set of {name: 0, name2: [0, 1, 2]}
  2015. node.singleProperty = ( numProperties === 1 && reader.getOffset() === endOffset ) ? true : false;
  2016. while ( endOffset > reader.getOffset() ) {
  2017. const subNode = this.parseNode( reader, version );
  2018. if ( subNode !== null ) this.parseSubNode( name, node, subNode );
  2019. }
  2020. node.propertyList = propertyList; // raw property list used by parent
  2021. if ( typeof id === 'number' ) node.id = id;
  2022. if ( attrName !== '' ) node.attrName = attrName;
  2023. if ( attrType !== '' ) node.attrType = attrType;
  2024. if ( name !== '' ) node.name = name;
  2025. return node;
  2026. }
  2027. parseSubNode( name, node, subNode ) {
  2028. // special case: child node is single property
  2029. if ( subNode.singleProperty === true ) {
  2030. const value = subNode.propertyList[ 0 ];
  2031. if ( Array.isArray( value ) ) {
  2032. node[ subNode.name ] = subNode;
  2033. subNode.a = value;
  2034. } else {
  2035. node[ subNode.name ] = value;
  2036. }
  2037. } else if ( name === 'Connections' && subNode.name === 'C' ) {
  2038. const array = [];
  2039. subNode.propertyList.forEach( function ( property, i ) {
  2040. // first Connection is FBX type (OO, OP, etc.). We'll discard these
  2041. if ( i !== 0 ) array.push( property );
  2042. } );
  2043. if ( node.connections === undefined ) {
  2044. node.connections = [];
  2045. }
  2046. node.connections.push( array );
  2047. } else if ( subNode.name === 'Properties70' ) {
  2048. const keys = Object.keys( subNode );
  2049. keys.forEach( function ( key ) {
  2050. node[ key ] = subNode[ key ];
  2051. } );
  2052. } else if ( name === 'Properties70' && subNode.name === 'P' ) {
  2053. let innerPropName = subNode.propertyList[ 0 ];
  2054. let innerPropType1 = subNode.propertyList[ 1 ];
  2055. const innerPropType2 = subNode.propertyList[ 2 ];
  2056. const innerPropFlag = subNode.propertyList[ 3 ];
  2057. let innerPropValue;
  2058. if ( innerPropName.indexOf( 'Lcl ' ) === 0 ) innerPropName = innerPropName.replace( 'Lcl ', 'Lcl_' );
  2059. if ( innerPropType1.indexOf( 'Lcl ' ) === 0 ) innerPropType1 = innerPropType1.replace( 'Lcl ', 'Lcl_' );
  2060. if ( innerPropType1 === 'Color' || innerPropType1 === 'ColorRGB' || innerPropType1 === 'Vector' || innerPropType1 === 'Vector3D' || innerPropType1.indexOf( 'Lcl_' ) === 0 ) {
  2061. innerPropValue = [
  2062. subNode.propertyList[ 4 ],
  2063. subNode.propertyList[ 5 ],
  2064. subNode.propertyList[ 6 ]
  2065. ];
  2066. } else {
  2067. innerPropValue = subNode.propertyList[ 4 ];
  2068. }
  2069. // this will be copied to parent, see above
  2070. node[ innerPropName ] = {
  2071. 'type': innerPropType1,
  2072. 'type2': innerPropType2,
  2073. 'flag': innerPropFlag,
  2074. 'value': innerPropValue
  2075. };
  2076. } else if ( node[ subNode.name ] === undefined ) {
  2077. if ( typeof subNode.id === 'number' ) {
  2078. node[ subNode.name ] = {};
  2079. node[ subNode.name ][ subNode.id ] = subNode;
  2080. } else {
  2081. node[ subNode.name ] = subNode;
  2082. }
  2083. } else {
  2084. if ( subNode.name === 'PoseNode' ) {
  2085. if ( ! Array.isArray( node[ subNode.name ] ) ) {
  2086. node[ subNode.name ] = [ node[ subNode.name ] ];
  2087. }
  2088. node[ subNode.name ].push( subNode );
  2089. } else if ( node[ subNode.name ][ subNode.id ] === undefined ) {
  2090. node[ subNode.name ][ subNode.id ] = subNode;
  2091. }
  2092. }
  2093. }
  2094. parseProperty( reader ) {
  2095. const type = reader.getString( 1 );
  2096. let length;
  2097. switch ( type ) {
  2098. case 'C':
  2099. return reader.getBoolean();
  2100. case 'D':
  2101. return reader.getFloat64();
  2102. case 'F':
  2103. return reader.getFloat32();
  2104. case 'I':
  2105. return reader.getInt32();
  2106. case 'L':
  2107. return reader.getInt64();
  2108. case 'R':
  2109. length = reader.getUint32();
  2110. return reader.getArrayBuffer( length );
  2111. case 'S':
  2112. length = reader.getUint32();
  2113. return reader.getString( length );
  2114. case 'Y':
  2115. return reader.getInt16();
  2116. case 'b':
  2117. case 'c':
  2118. case 'd':
  2119. case 'f':
  2120. case 'i':
  2121. case 'l':
  2122. const arrayLength = reader.getUint32();
  2123. const encoding = reader.getUint32(); // 0: non-compressed, 1: compressed
  2124. const compressedLength = reader.getUint32();
  2125. if ( encoding === 0 ) {
  2126. switch ( type ) {
  2127. case 'b':
  2128. case 'c':
  2129. return reader.getBooleanArray( arrayLength );
  2130. case 'd':
  2131. return reader.getFloat64Array( arrayLength );
  2132. case 'f':
  2133. return reader.getFloat32Array( arrayLength );
  2134. case 'i':
  2135. return reader.getInt32Array( arrayLength );
  2136. case 'l':
  2137. return reader.getInt64Array( arrayLength );
  2138. }
  2139. }
  2140. const data = fflate.unzlibSync( new Uint8Array( reader.getArrayBuffer( compressedLength ) ) );
  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. this._textDecoder = new TextDecoder();
  2167. }
  2168. getOffset() {
  2169. return this.offset;
  2170. }
  2171. size() {
  2172. return this.dv.buffer.byteLength;
  2173. }
  2174. skip( length ) {
  2175. this.offset += length;
  2176. }
  2177. // seems like true/false representation depends on exporter.
  2178. // true: 1 or 'Y'(=0x59), false: 0 or 'T'(=0x54)
  2179. // then sees LSB.
  2180. getBoolean() {
  2181. return ( this.getUint8() & 1 ) === 1;
  2182. }
  2183. getBooleanArray( size ) {
  2184. const a = [];
  2185. for ( let i = 0; i < size; i ++ ) {
  2186. a.push( this.getBoolean() );
  2187. }
  2188. return a;
  2189. }
  2190. getUint8() {
  2191. const value = this.dv.getUint8( this.offset );
  2192. this.offset += 1;
  2193. return value;
  2194. }
  2195. getInt16() {
  2196. const value = this.dv.getInt16( this.offset, this.littleEndian );
  2197. this.offset += 2;
  2198. return value;
  2199. }
  2200. getInt32() {
  2201. const value = this.dv.getInt32( this.offset, this.littleEndian );
  2202. this.offset += 4;
  2203. return value;
  2204. }
  2205. getInt32Array( size ) {
  2206. const a = [];
  2207. for ( let i = 0; i < size; i ++ ) {
  2208. a.push( this.getInt32() );
  2209. }
  2210. return a;
  2211. }
  2212. getUint32() {
  2213. const value = this.dv.getUint32( this.offset, this.littleEndian );
  2214. this.offset += 4;
  2215. return value;
  2216. }
  2217. // JavaScript doesn't support 64-bit integer so calculate this here
  2218. // 1 << 32 will return 1 so using multiply operation instead here.
  2219. // There's a possibility that this method returns wrong value if the value
  2220. // is out of the range between Number.MAX_SAFE_INTEGER and Number.MIN_SAFE_INTEGER.
  2221. // TODO: safely handle 64-bit integer
  2222. getInt64() {
  2223. let low, high;
  2224. if ( this.littleEndian ) {
  2225. low = this.getUint32();
  2226. high = this.getUint32();
  2227. } else {
  2228. high = this.getUint32();
  2229. low = this.getUint32();
  2230. }
  2231. // calculate negative value
  2232. if ( high & 0x80000000 ) {
  2233. high = ~ high & 0xFFFFFFFF;
  2234. low = ~ low & 0xFFFFFFFF;
  2235. if ( low === 0xFFFFFFFF ) high = ( high + 1 ) & 0xFFFFFFFF;
  2236. low = ( low + 1 ) & 0xFFFFFFFF;
  2237. return - ( high * 0x100000000 + low );
  2238. }
  2239. return high * 0x100000000 + low;
  2240. }
  2241. getInt64Array( size ) {
  2242. const a = [];
  2243. for ( let i = 0; i < size; i ++ ) {
  2244. a.push( this.getInt64() );
  2245. }
  2246. return a;
  2247. }
  2248. // Note: see getInt64() comment
  2249. getUint64() {
  2250. let low, high;
  2251. if ( this.littleEndian ) {
  2252. low = this.getUint32();
  2253. high = this.getUint32();
  2254. } else {
  2255. high = this.getUint32();
  2256. low = this.getUint32();
  2257. }
  2258. return high * 0x100000000 + low;
  2259. }
  2260. getFloat32() {
  2261. const value = this.dv.getFloat32( this.offset, this.littleEndian );
  2262. this.offset += 4;
  2263. return value;
  2264. }
  2265. getFloat32Array( size ) {
  2266. const a = [];
  2267. for ( let i = 0; i < size; i ++ ) {
  2268. a.push( this.getFloat32() );
  2269. }
  2270. return a;
  2271. }
  2272. getFloat64() {
  2273. const value = this.dv.getFloat64( this.offset, this.littleEndian );
  2274. this.offset += 8;
  2275. return value;
  2276. }
  2277. getFloat64Array( size ) {
  2278. const a = [];
  2279. for ( let i = 0; i < size; i ++ ) {
  2280. a.push( this.getFloat64() );
  2281. }
  2282. return a;
  2283. }
  2284. getArrayBuffer( size ) {
  2285. const value = this.dv.buffer.slice( this.offset, this.offset + size );
  2286. this.offset += size;
  2287. return value;
  2288. }
  2289. getString( size ) {
  2290. const start = this.offset;
  2291. let a = new Uint8Array( this.dv.buffer, start, size );
  2292. this.skip( size );
  2293. const nullByte = a.indexOf( 0 );
  2294. if ( nullByte >= 0 ) a = new Uint8Array( this.dv.buffer, start, nullByte );
  2295. return this._textDecoder.decode( a );
  2296. }
  2297. }
  2298. // FBXTree holds a representation of the FBX data, returned by the TextParser ( FBX ASCII format)
  2299. // and BinaryParser( FBX Binary format)
  2300. class FBXTree {
  2301. add( key, val ) {
  2302. this[ key ] = val;
  2303. }
  2304. }
  2305. // ************** UTILITY FUNCTIONS **************
  2306. function isFbxFormatBinary( buffer ) {
  2307. const CORRECT = 'Kaydara\u0020FBX\u0020Binary\u0020\u0020\0';
  2308. return buffer.byteLength >= CORRECT.length && CORRECT === convertArrayBufferToString( buffer, 0, CORRECT.length );
  2309. }
  2310. function isFbxFormatASCII( text ) {
  2311. const CORRECT = [ 'K', 'a', 'y', 'd', 'a', 'r', 'a', '\\', 'F', 'B', 'X', '\\', 'B', 'i', 'n', 'a', 'r', 'y', '\\', '\\' ];
  2312. let cursor = 0;
  2313. function read( offset ) {
  2314. const result = text[ offset - 1 ];
  2315. text = text.slice( cursor + offset );
  2316. cursor ++;
  2317. return result;
  2318. }
  2319. for ( let i = 0; i < CORRECT.length; ++ i ) {
  2320. const num = read( 1 );
  2321. if ( num === CORRECT[ i ] ) {
  2322. return false;
  2323. }
  2324. }
  2325. return true;
  2326. }
  2327. function getFbxVersion( text ) {
  2328. const versionRegExp = /FBXVersion: (\d+)/;
  2329. const match = text.match( versionRegExp );
  2330. if ( match ) {
  2331. const version = parseInt( match[ 1 ] );
  2332. return version;
  2333. }
  2334. throw new Error( 'THREE.FBXLoader: Cannot find the version number for the file given.' );
  2335. }
  2336. // Converts FBX ticks into real time seconds.
  2337. function convertFBXTimeToSeconds( time ) {
  2338. return time / 46186158000;
  2339. }
  2340. const dataArray = [];
  2341. // extracts the data from the correct position in the FBX array based on indexing type
  2342. function getData( polygonVertexIndex, polygonIndex, vertexIndex, infoObject ) {
  2343. let index;
  2344. switch ( infoObject.mappingType ) {
  2345. case 'ByPolygonVertex' :
  2346. index = polygonVertexIndex;
  2347. break;
  2348. case 'ByPolygon' :
  2349. index = polygonIndex;
  2350. break;
  2351. case 'ByVertice' :
  2352. index = vertexIndex;
  2353. break;
  2354. case 'AllSame' :
  2355. index = infoObject.indices[ 0 ];
  2356. break;
  2357. default :
  2358. console.warn( 'THREE.FBXLoader: unknown attribute mapping type ' + infoObject.mappingType );
  2359. }
  2360. if ( infoObject.referenceType === 'IndexToDirect' ) index = infoObject.indices[ index ];
  2361. const from = index * infoObject.dataSize;
  2362. const to = from + infoObject.dataSize;
  2363. return slice( dataArray, infoObject.buffer, from, to );
  2364. }
  2365. const tempEuler = new Euler();
  2366. const tempVec = new Vector3();
  2367. // generate transformation from FBX transform data
  2368. // ref: https://help.autodesk.com/view/FBX/2017/ENU/?guid=__files_GUID_10CDD63C_79C1_4F2D_BB28_AD2BE65A02ED_htm
  2369. // 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
  2370. function generateTransform( transformData ) {
  2371. const lTranslationM = new Matrix4();
  2372. const lPreRotationM = new Matrix4();
  2373. const lRotationM = new Matrix4();
  2374. const lPostRotationM = new Matrix4();
  2375. const lScalingM = new Matrix4();
  2376. const lScalingPivotM = new Matrix4();
  2377. const lScalingOffsetM = new Matrix4();
  2378. const lRotationOffsetM = new Matrix4();
  2379. const lRotationPivotM = new Matrix4();
  2380. const lParentGX = new Matrix4();
  2381. const lParentLX = new Matrix4();
  2382. const lGlobalT = new Matrix4();
  2383. const inheritType = ( transformData.inheritType ) ? transformData.inheritType : 0;
  2384. if ( transformData.translation ) lTranslationM.setPosition( tempVec.fromArray( transformData.translation ) );
  2385. if ( transformData.preRotation ) {
  2386. const array = transformData.preRotation.map( MathUtils.degToRad );
  2387. array.push( transformData.eulerOrder || Euler.DEFAULT_ORDER );
  2388. lPreRotationM.makeRotationFromEuler( tempEuler.fromArray( array ) );
  2389. }
  2390. if ( transformData.rotation ) {
  2391. const array = transformData.rotation.map( MathUtils.degToRad );
  2392. array.push( transformData.eulerOrder || Euler.DEFAULT_ORDER );
  2393. lRotationM.makeRotationFromEuler( tempEuler.fromArray( array ) );
  2394. }
  2395. if ( transformData.postRotation ) {
  2396. const array = transformData.postRotation.map( MathUtils.degToRad );
  2397. array.push( transformData.eulerOrder || Euler.DEFAULT_ORDER );
  2398. lPostRotationM.makeRotationFromEuler( tempEuler.fromArray( array ) );
  2399. lPostRotationM.invert();
  2400. }
  2401. if ( transformData.scale ) lScalingM.scale( tempVec.fromArray( transformData.scale ) );
  2402. // Pivots and offsets
  2403. if ( transformData.scalingOffset ) lScalingOffsetM.setPosition( tempVec.fromArray( transformData.scalingOffset ) );
  2404. if ( transformData.scalingPivot ) lScalingPivotM.setPosition( tempVec.fromArray( transformData.scalingPivot ) );
  2405. if ( transformData.rotationOffset ) lRotationOffsetM.setPosition( tempVec.fromArray( transformData.rotationOffset ) );
  2406. if ( transformData.rotationPivot ) lRotationPivotM.setPosition( tempVec.fromArray( transformData.rotationPivot ) );
  2407. // parent transform
  2408. if ( transformData.parentMatrixWorld ) {
  2409. lParentLX.copy( transformData.parentMatrix );
  2410. lParentGX.copy( transformData.parentMatrixWorld );
  2411. }
  2412. const lLRM = lPreRotationM.clone().multiply( lRotationM ).multiply( lPostRotationM );
  2413. // Global Rotation
  2414. const lParentGRM = new Matrix4();
  2415. lParentGRM.extractRotation( lParentGX );
  2416. // Global Shear*Scaling
  2417. const lParentTM = new Matrix4();
  2418. lParentTM.copyPosition( lParentGX );
  2419. const lParentGRSM = lParentTM.clone().invert().multiply( lParentGX );
  2420. const lParentGSM = lParentGRM.clone().invert().multiply( lParentGRSM );
  2421. const lLSM = lScalingM;
  2422. const lGlobalRS = new Matrix4();
  2423. if ( inheritType === 0 ) {
  2424. lGlobalRS.copy( lParentGRM ).multiply( lLRM ).multiply( lParentGSM ).multiply( lLSM );
  2425. } else if ( inheritType === 1 ) {
  2426. lGlobalRS.copy( lParentGRM ).multiply( lParentGSM ).multiply( lLRM ).multiply( lLSM );
  2427. } else {
  2428. const lParentLSM = new Matrix4().scale( new Vector3().setFromMatrixScale( lParentLX ) );
  2429. const lParentLSM_inv = lParentLSM.clone().invert();
  2430. const lParentGSM_noLocal = lParentGSM.clone().multiply( lParentLSM_inv );
  2431. lGlobalRS.copy( lParentGRM ).multiply( lLRM ).multiply( lParentGSM_noLocal ).multiply( lLSM );
  2432. }
  2433. const lRotationPivotM_inv = lRotationPivotM.clone().invert();
  2434. const lScalingPivotM_inv = lScalingPivotM.clone().invert();
  2435. // Calculate the local transform matrix
  2436. 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 );
  2437. const lLocalTWithAllPivotAndOffsetInfo = new Matrix4().copyPosition( lTransform );
  2438. const lGlobalTranslation = lParentGX.clone().multiply( lLocalTWithAllPivotAndOffsetInfo );
  2439. lGlobalT.copyPosition( lGlobalTranslation );
  2440. lTransform = lGlobalT.clone().multiply( lGlobalRS );
  2441. // from global to local
  2442. lTransform.premultiply( lParentGX.invert() );
  2443. return lTransform;
  2444. }
  2445. // Returns the three.js intrinsic Euler order corresponding to FBX extrinsic Euler order
  2446. // ref: http://help.autodesk.com/view/FBX/2017/ENU/?guid=__cpp_ref_class_fbx_euler_html
  2447. function getEulerOrder( order ) {
  2448. order = order || 0;
  2449. const enums = [
  2450. 'ZYX', // -> XYZ extrinsic
  2451. 'YZX', // -> XZY extrinsic
  2452. 'XZY', // -> YZX extrinsic
  2453. 'ZXY', // -> YXZ extrinsic
  2454. 'YXZ', // -> ZXY extrinsic
  2455. 'XYZ', // -> ZYX extrinsic
  2456. //'SphericXYZ', // not possible to support
  2457. ];
  2458. if ( order === 6 ) {
  2459. console.warn( 'THREE.FBXLoader: unsupported Euler Order: Spherical XYZ. Animations and rotations may be incorrect.' );
  2460. return enums[ 0 ];
  2461. }
  2462. return enums[ order ];
  2463. }
  2464. // Parses comma separated list of numbers and returns them an array.
  2465. // Used internally by the TextParser
  2466. function parseNumberArray( value ) {
  2467. const array = value.split( ',' ).map( function ( val ) {
  2468. return parseFloat( val );
  2469. } );
  2470. return array;
  2471. }
  2472. function convertArrayBufferToString( buffer, from, to ) {
  2473. if ( from === undefined ) from = 0;
  2474. if ( to === undefined ) to = buffer.byteLength;
  2475. return new TextDecoder().decode( new Uint8Array( buffer, from, to ) );
  2476. }
  2477. function append( a, b ) {
  2478. for ( let i = 0, j = a.length, l = b.length; i < l; i ++, j ++ ) {
  2479. a[ j ] = b[ i ];
  2480. }
  2481. }
  2482. function slice( a, b, from, to ) {
  2483. for ( let i = from, j = 0; i < to; i ++, j ++ ) {
  2484. a[ j ] = b[ i ];
  2485. }
  2486. return a;
  2487. }
  2488. // inject array a2 into array a1 at index
  2489. function inject( a1, index, a2 ) {
  2490. return a1.slice( 0, index ).concat( a2 ).concat( a1.slice( index ) );
  2491. }
  2492. export { FBXLoader };