FBXLoader.js 95 KB

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