FBXLoader.js 95 KB

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