FBXLoader.js 102 KB

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