FBXLoader.js 99 KB

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