FBXLoader.js 95 KB

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