FBXLoader.js 99 KB

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