FBXLoader.js 95 KB

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