2
0

FBXLoader.js 96 KB

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