FBXLoader.js 102 KB

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