FBXLoader.js 96 KB

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