FBXLoader.js 97 KB

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