FBXLoader.js 91 KB

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