FBXLoader.js 89 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005
  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. }
  405. }
  406. // Parse single node mesh geometry in FBXTree.Objects.subNodes.Geometry
  407. function parseMeshGeometry( geometryNode, relationships, deformers ) {
  408. for ( var i = 0; i < relationships.children.length; ++ i ) {
  409. var deformer = deformers[ relationships.children[ i ].ID ];
  410. if ( deformer !== undefined ) break;
  411. }
  412. return genGeometry( geometryNode, deformer );
  413. }
  414. // Generate a THREE.BufferGeometry from a node in FBXTree.Objects.subNodes.Geometry
  415. function genGeometry( geometryNode, deformer ) {
  416. var subNodes = geometryNode.subNodes;
  417. var vertexPositions = subNodes.Vertices.properties.a;
  418. var vertexIndices = subNodes.PolygonVertexIndex.properties.a;
  419. // create arrays to hold the final data used to build the buffergeometry
  420. var vertexBuffer = [];
  421. var normalBuffer = [];
  422. var colorsBuffer = [];
  423. var uvsBuffer = [];
  424. var materialIndexBuffer = [];
  425. var vertexWeightsBuffer = [];
  426. var weightsIndicesBuffer = [];
  427. if ( subNodes.LayerElementColor ) {
  428. var colorInfo = getColors( subNodes.LayerElementColor[ 0 ] );
  429. }
  430. if ( subNodes.LayerElementMaterial ) {
  431. var materialInfo = getMaterials( subNodes.LayerElementMaterial[ 0 ] );
  432. }
  433. if ( subNodes.LayerElementNormal ) {
  434. var normalInfo = getNormals( subNodes.LayerElementNormal[ 0 ] );
  435. }
  436. if ( subNodes.LayerElementUV ) {
  437. var uvInfo = [];
  438. var i = 0;
  439. while ( subNodes.LayerElementUV[ i ] ) {
  440. uvInfo.push( getUVs( subNodes.LayerElementUV[ i ] ) );
  441. i ++;
  442. }
  443. }
  444. var weightTable = {};
  445. if ( deformer ) {
  446. var subDeformers = deformer.map;
  447. for ( var key in subDeformers ) {
  448. var subDeformer = subDeformers[ key ];
  449. var indices = subDeformer.indices;
  450. for ( var j = 0; j < indices.length; j ++ ) {
  451. var index = indices[ j ];
  452. var weight = subDeformer.weights[ j ];
  453. if ( weightTable[ index ] === undefined ) weightTable[ index ] = [];
  454. weightTable[ index ].push( {
  455. id: subDeformer.index,
  456. weight: weight
  457. } );
  458. }
  459. }
  460. }
  461. var polygonIndex = 0;
  462. var faceLength = 0;
  463. var displayedWeightsWarning = false;
  464. // these will hold data for a single face
  465. var vertexPositionIndexes = [];
  466. var faceNormals = [];
  467. var faceColors = [];
  468. var faceUVs = [];
  469. var faceWeights = [];
  470. var faceWeightIndices = [];
  471. for ( var polygonVertexIndex = 0; polygonVertexIndex < vertexIndices.length; polygonVertexIndex ++ ) {
  472. var vertexIndex = vertexIndices[ polygonVertexIndex ];
  473. var endOfFace = false;
  474. // Face index and vertex index arrays are combined in a single array
  475. // A cube with quad faces looks like this:
  476. // PolygonVertexIndex: *24 {
  477. // a: 0, 1, 3, -3, 2, 3, 5, -5, 4, 5, 7, -7, 6, 7, 1, -1, 1, 7, 5, -4, 6, 0, 2, -5
  478. // }
  479. // Negative numbers mark the end of a face - first face here is 0, 1, 3, -3
  480. // to find index of last vertex multiply by -1 and subtract 1: -3 * - 1 - 1 = 2
  481. if ( vertexIndex < 0 ) {
  482. vertexIndex = vertexIndex ^ - 1; // equivalent to ( x * -1 ) - 1
  483. vertexIndices[ polygonVertexIndex ] = vertexIndex;
  484. endOfFace = true;
  485. }
  486. var weightIndices = [];
  487. var weights = [];
  488. vertexPositionIndexes.push( vertexIndex * 3, vertexIndex * 3 + 1, vertexIndex * 3 + 2 );
  489. if ( colorInfo ) {
  490. var data = getData( polygonVertexIndex, polygonIndex, vertexIndex, colorInfo );
  491. faceColors.push( data[ 0 ], data[ 1 ], data[ 2 ] );
  492. }
  493. if ( deformer ) {
  494. if ( weightTable[ vertexIndex ] !== undefined ) {
  495. var array = weightTable[ vertexIndex ];
  496. for ( var j = 0, jl = array.length; j < jl; j ++ ) {
  497. weights.push( array[ j ].weight );
  498. weightIndices.push( array[ j ].id );
  499. }
  500. }
  501. if ( weights.length > 4 ) {
  502. if ( ! displayedWeightsWarning ) {
  503. console.warn( 'THREE.FBXLoader: Vertex has more than 4 skinning weights assigned to vertex. Deleting additional weights.' );
  504. displayedWeightsWarning = true;
  505. }
  506. var WIndex = [ 0, 0, 0, 0 ];
  507. var Weight = [ 0, 0, 0, 0 ];
  508. weights.forEach( function ( weight, weightIndex ) {
  509. var currentWeight = weight;
  510. var currentIndex = weightIndices[ weightIndex ];
  511. Weight.forEach( function ( comparedWeight, comparedWeightIndex, comparedWeightArray ) {
  512. if ( currentWeight > comparedWeight ) {
  513. comparedWeightArray[ comparedWeightIndex ] = currentWeight;
  514. currentWeight = comparedWeight;
  515. var tmp = WIndex[ comparedWeightIndex ];
  516. WIndex[ comparedWeightIndex ] = currentIndex;
  517. currentIndex = tmp;
  518. }
  519. } );
  520. } );
  521. weightIndices = WIndex;
  522. weights = Weight;
  523. }
  524. // if the weight array is shorter than 4 pad with 0s
  525. for ( var i = weights.length; i < 4; ++ i ) {
  526. weights[ i ] = 0;
  527. weightIndices[ i ] = 0;
  528. }
  529. for ( var i = 0; i < 4; ++ i ) {
  530. faceWeights.push( weights[ i ] );
  531. faceWeightIndices.push( weightIndices[ i ] );
  532. }
  533. }
  534. if ( normalInfo ) {
  535. var data = getData( polygonVertexIndex, polygonIndex, vertexIndex, normalInfo );
  536. faceNormals.push( data[ 0 ], data[ 1 ], data[ 2 ] );
  537. }
  538. if ( uvInfo ) {
  539. for ( var i = 0; i < uvInfo.length; i ++ ) {
  540. var data = getData( polygonVertexIndex, polygonIndex, vertexIndex, uvInfo[ i ] );
  541. if ( faceUVs[ i ] === undefined ) {
  542. faceUVs[ i ] = [];
  543. }
  544. faceUVs[ i ].push(
  545. data[ 0 ],
  546. data[ 1 ]
  547. );
  548. }
  549. }
  550. faceLength ++;
  551. // we have reached the end of a face - it may have 4 sides though
  552. // in which case the data is split into to represent 3 sides faces
  553. if ( endOfFace ) {
  554. for ( var i = 2; i < faceLength; i ++ ) {
  555. vertexBuffer.push( vertexPositions[ vertexPositionIndexes[ 0 ] ] );
  556. vertexBuffer.push( vertexPositions[ vertexPositionIndexes[ 1 ] ] );
  557. vertexBuffer.push( vertexPositions[ vertexPositionIndexes[ 2 ] ] );
  558. vertexBuffer.push( vertexPositions[ vertexPositionIndexes[ ( i - 1 ) * 3 ] ] );
  559. vertexBuffer.push( vertexPositions[ vertexPositionIndexes[ ( i - 1 ) * 3 + 1 ] ] );
  560. vertexBuffer.push( vertexPositions[ vertexPositionIndexes[ ( i - 1 ) * 3 + 2 ] ] );
  561. vertexBuffer.push( vertexPositions[ vertexPositionIndexes[ i * 3 ] ] );
  562. vertexBuffer.push( vertexPositions[ vertexPositionIndexes[ i * 3 + 1 ] ] );
  563. vertexBuffer.push( vertexPositions[ vertexPositionIndexes[ i * 3 + 2 ] ] );
  564. }
  565. if ( deformer ) {
  566. for ( var i = 2; i < faceLength; i ++ ) {
  567. vertexWeightsBuffer.push( faceWeights[ 0 ] );
  568. vertexWeightsBuffer.push( faceWeights[ 1 ] );
  569. vertexWeightsBuffer.push( faceWeights[ 2 ] );
  570. vertexWeightsBuffer.push( faceWeights[ 3 ] );
  571. vertexWeightsBuffer.push( faceWeights[ ( i - 1 ) * 4 ] );
  572. vertexWeightsBuffer.push( faceWeights[ ( i - 1 ) * 4 + 1 ] );
  573. vertexWeightsBuffer.push( faceWeights[ ( i - 1 ) * 4 + 2 ] );
  574. vertexWeightsBuffer.push( faceWeights[ ( i - 1 ) * 4 + 3 ] );
  575. vertexWeightsBuffer.push( faceWeights[ i * 4 ] );
  576. vertexWeightsBuffer.push( faceWeights[ i * 4 + 1 ] );
  577. vertexWeightsBuffer.push( faceWeights[ i * 4 + 2 ] );
  578. vertexWeightsBuffer.push( faceWeights[ i * 4 + 3 ] );
  579. weightsIndicesBuffer.push( faceWeightIndices[ 0 ] );
  580. weightsIndicesBuffer.push( faceWeightIndices[ 1 ] );
  581. weightsIndicesBuffer.push( faceWeightIndices[ 2 ] );
  582. weightsIndicesBuffer.push( faceWeightIndices[ 3 ] );
  583. weightsIndicesBuffer.push( faceWeightIndices[ ( i - 1 ) * 4 ] );
  584. weightsIndicesBuffer.push( faceWeightIndices[ ( i - 1 ) * 4 + 1 ] );
  585. weightsIndicesBuffer.push( faceWeightIndices[ ( i - 1 ) * 4 + 2 ] );
  586. weightsIndicesBuffer.push( faceWeightIndices[ ( i - 1 ) * 4 + 3 ] );
  587. weightsIndicesBuffer.push( faceWeightIndices[ i * 4 ] );
  588. weightsIndicesBuffer.push( faceWeightIndices[ i * 4 + 1 ] );
  589. weightsIndicesBuffer.push( faceWeightIndices[ i * 4 + 2 ] );
  590. weightsIndicesBuffer.push( faceWeightIndices[ i * 4 + 3 ] );
  591. }
  592. }
  593. if ( normalInfo ) {
  594. for ( var i = 2; i < faceLength; i ++ ) {
  595. normalBuffer.push( faceNormals[ 0 ] );
  596. normalBuffer.push( faceNormals[ 1 ] );
  597. normalBuffer.push( faceNormals[ 2 ] );
  598. normalBuffer.push( faceNormals[ ( i - 1 ) * 3 ] );
  599. normalBuffer.push( faceNormals[ ( i - 1 ) * 3 + 1 ] );
  600. normalBuffer.push( faceNormals[ ( i - 1 ) * 3 + 2 ] );
  601. normalBuffer.push( faceNormals[ i * 3 ] );
  602. normalBuffer.push( faceNormals[ i * 3 + 1 ] );
  603. normalBuffer.push( faceNormals[ i * 3 + 2 ] );
  604. }
  605. }
  606. if ( uvInfo ) {
  607. for ( var j = 0; j < uvInfo.length; j ++ ) {
  608. if ( uvsBuffer[ j ] === undefined ) uvsBuffer[ j ] = [];
  609. for ( var i = 2; i < faceLength; i ++ ) {
  610. uvsBuffer[ j ].push( faceUVs[ j ][ 0 ] );
  611. uvsBuffer[ j ].push( faceUVs[ j ][ 1 ] );
  612. uvsBuffer[ j ].push( faceUVs[ j ][ ( i - 1 ) * 2 ] );
  613. uvsBuffer[ j ].push( faceUVs[ j ][ ( i - 1 ) * 2 + 1 ] );
  614. uvsBuffer[ j ].push( faceUVs[ j ][ i * 2 ] );
  615. uvsBuffer[ j ].push( faceUVs[ j ][ i * 2 + 1 ] );
  616. }
  617. }
  618. }
  619. if ( colorInfo ) {
  620. for ( var i = 2; i < faceLength; i ++ ) {
  621. colorsBuffer.push( faceColors[ 0 ] );
  622. colorsBuffer.push( faceColors[ 1 ] );
  623. colorsBuffer.push( faceColors[ 2 ] );
  624. colorsBuffer.push( faceColors[ ( i - 1 ) * 3 ] );
  625. colorsBuffer.push( faceColors[ ( i - 1 ) * 3 + 1 ] );
  626. colorsBuffer.push( faceColors[ ( i - 1 ) * 3 + 2 ] );
  627. colorsBuffer.push( faceColors[ i * 3 ] );
  628. colorsBuffer.push( faceColors[ i * 3 + 1 ] );
  629. colorsBuffer.push( faceColors[ i * 3 + 2 ] );
  630. }
  631. }
  632. if ( materialInfo && materialInfo.mappingType !== 'AllSame' ) {
  633. var materialIndex = getData( polygonVertexIndex, polygonIndex, vertexIndex, materialInfo )[ 0 ];
  634. for ( var i = 2; i < faceLength; i ++ ) {
  635. materialIndexBuffer.push( materialIndex );
  636. materialIndexBuffer.push( materialIndex );
  637. materialIndexBuffer.push( materialIndex );
  638. }
  639. }
  640. polygonIndex ++;
  641. endOfFace = false;
  642. faceLength = 0;
  643. // reset arrays for the next face
  644. vertexPositionIndexes = [];
  645. faceNormals = [];
  646. faceColors = [];
  647. faceUVs = [];
  648. faceWeights = [];
  649. faceWeightIndices = [];
  650. }
  651. }
  652. var geo = new THREE.BufferGeometry();
  653. geo.name = geometryNode.name;
  654. geo.addAttribute( 'position', new THREE.Float32BufferAttribute( vertexBuffer, 3 ) );
  655. if ( colorsBuffer.length > 0 ) {
  656. geo.addAttribute( 'color', new THREE.Float32BufferAttribute( colorsBuffer, 3 ) );
  657. }
  658. if ( deformer ) {
  659. geo.addAttribute( 'skinIndex', new THREE.Float32BufferAttribute( weightsIndicesBuffer, 4 ) );
  660. geo.addAttribute( 'skinWeight', new THREE.Float32BufferAttribute( vertexWeightsBuffer, 4 ) );
  661. // used later to bind the skeleton to the model
  662. geo.FBX_Deformer = deformer;
  663. }
  664. if ( normalBuffer.length > 0 ) {
  665. geo.addAttribute( 'normal', new THREE.Float32BufferAttribute( normalBuffer, 3 ) );
  666. }
  667. if ( uvsBuffer.length > 0 ) {
  668. for ( var i = 0; i < uvsBuffer.length; i ++ ) {
  669. var name = 'uv' + ( i + 1 ).toString();
  670. if ( i == 0 ) {
  671. name = 'uv';
  672. }
  673. geo.addAttribute( name, new THREE.Float32BufferAttribute( uvsBuffer[ i ], 2 ) );
  674. }
  675. }
  676. if ( materialInfo && materialInfo.mappingType !== 'AllSame' ) {
  677. // Convert the material indices of each vertex into rendering groups on the geometry.
  678. var prevMaterialIndex = materialIndexBuffer[ 0 ];
  679. var startIndex = 0;
  680. for ( var i = 0; i < materialIndexBuffer.length; ++ i ) {
  681. if ( materialIndexBuffer[ i ] !== prevMaterialIndex ) {
  682. geo.addGroup( startIndex, i - startIndex, prevMaterialIndex );
  683. prevMaterialIndex = materialIndexBuffer[ i ];
  684. startIndex = i;
  685. }
  686. }
  687. // the loop above doesn't add the last group, do that here.
  688. if ( geo.groups.length > 0 ) {
  689. var lastGroup = geo.groups[ geo.groups.length - 1 ];
  690. var lastIndex = lastGroup.start + lastGroup.count;
  691. if ( lastIndex !== materialIndexBuffer.length ) {
  692. geo.addGroup( lastIndex, materialIndexBuffer.length - lastIndex, prevMaterialIndex );
  693. }
  694. }
  695. // case where there are multiple materials but the whole geometry is only
  696. // using one of them
  697. if ( geo.groups.length === 0 ) {
  698. geo.addGroup( 0, materialIndexBuffer.length, materialIndexBuffer[ 0 ] );
  699. }
  700. }
  701. return geo;
  702. }
  703. // Parse normal from FBXTree.Objects.subNodes.Geometry.subNodes.LayerElementNormal if it exists
  704. function getNormals( NormalNode ) {
  705. var mappingType = NormalNode.properties.MappingInformationType;
  706. var referenceType = NormalNode.properties.ReferenceInformationType;
  707. var buffer = NormalNode.subNodes.Normals.properties.a;
  708. var indexBuffer = [];
  709. if ( referenceType === 'IndexToDirect' ) {
  710. if ( 'NormalIndex' in NormalNode.subNodes ) {
  711. indexBuffer = NormalNode.subNodes.NormalIndex.properties.a;
  712. } else if ( 'NormalsIndex' in NormalNode.subNodes ) {
  713. indexBuffer = NormalNode.subNodes.NormalsIndex.properties.a;
  714. }
  715. }
  716. return {
  717. dataSize: 3,
  718. buffer: buffer,
  719. indices: indexBuffer,
  720. mappingType: mappingType,
  721. referenceType: referenceType
  722. };
  723. }
  724. // Parse UVs from FBXTree.Objects.subNodes.Geometry.subNodes.LayerElementUV if it exists
  725. function getUVs( UVNode ) {
  726. var mappingType = UVNode.properties.MappingInformationType;
  727. var referenceType = UVNode.properties.ReferenceInformationType;
  728. var buffer = UVNode.subNodes.UV.properties.a;
  729. var indexBuffer = [];
  730. if ( referenceType === 'IndexToDirect' ) {
  731. indexBuffer = UVNode.subNodes.UVIndex.properties.a;
  732. }
  733. return {
  734. dataSize: 2,
  735. buffer: buffer,
  736. indices: indexBuffer,
  737. mappingType: mappingType,
  738. referenceType: referenceType
  739. };
  740. }
  741. // Parse Vertex Colors from FBXTree.Objects.subNodes.Geometry.subNodes.LayerElementColor if it exists
  742. function getColors( ColorNode ) {
  743. var mappingType = ColorNode.properties.MappingInformationType;
  744. var referenceType = ColorNode.properties.ReferenceInformationType;
  745. var buffer = ColorNode.subNodes.Colors.properties.a;
  746. var indexBuffer = [];
  747. if ( referenceType === 'IndexToDirect' ) {
  748. indexBuffer = ColorNode.subNodes.ColorIndex.properties.a;
  749. }
  750. return {
  751. dataSize: 4,
  752. buffer: buffer,
  753. indices: indexBuffer,
  754. mappingType: mappingType,
  755. referenceType: referenceType
  756. };
  757. }
  758. // Parse mapping and material data in FBXTree.Objects.subNodes.Geometry.subNodes.LayerElementMaterial if it exists
  759. function getMaterials( MaterialNode ) {
  760. var mappingType = MaterialNode.properties.MappingInformationType;
  761. var referenceType = MaterialNode.properties.ReferenceInformationType;
  762. if ( mappingType === 'NoMappingInformation' ) {
  763. return {
  764. dataSize: 1,
  765. buffer: [ 0 ],
  766. indices: [ 0 ],
  767. mappingType: 'AllSame',
  768. referenceType: referenceType
  769. };
  770. }
  771. var materialIndexBuffer = MaterialNode.subNodes.Materials.properties.a;
  772. // Since materials are stored as indices, there's a bit of a mismatch between FBX and what
  773. // we expect.So we create an intermediate buffer that points to the index in the buffer,
  774. // for conforming with the other functions we've written for other data.
  775. var materialIndices = [];
  776. for ( var materialIndexBufferIndex = 0, materialIndexBufferLength = materialIndexBuffer.length; materialIndexBufferIndex < materialIndexBufferLength; ++ materialIndexBufferIndex ) {
  777. materialIndices.push( materialIndexBufferIndex );
  778. }
  779. return {
  780. dataSize: 1,
  781. buffer: materialIndexBuffer,
  782. indices: materialIndices,
  783. mappingType: mappingType,
  784. referenceType: referenceType
  785. };
  786. }
  787. // Functions use the infoObject and given indices to return value array of geometry.
  788. // infoObject can be materialInfo, normalInfo, UVInfo or colorInfo
  789. // polygonVertexIndex - Index of vertex in draw order (which index of the index buffer refers to this vertex).
  790. // polygonIndex - Index of polygon in geometry.
  791. // vertexIndex - Index of vertex inside vertex buffer (used because some data refers to old index buffer that we don't use anymore).
  792. var dataArray = [];
  793. var GetData = {
  794. ByPolygonVertex: {
  795. Direct: function ( polygonVertexIndex, polygonIndex, vertexIndex, infoObject ) {
  796. var from = ( polygonVertexIndex * infoObject.dataSize );
  797. var to = ( polygonVertexIndex * infoObject.dataSize ) + infoObject.dataSize;
  798. // return infoObject.buffer.slice( from, to );
  799. return slice( dataArray, infoObject.buffer, from, to );
  800. },
  801. IndexToDirect: function ( polygonVertexIndex, polygonIndex, vertexIndex, infoObject ) {
  802. var index = infoObject.indices[ polygonVertexIndex ];
  803. var from = ( index * infoObject.dataSize );
  804. var to = ( index * infoObject.dataSize ) + infoObject.dataSize;
  805. // return infoObject.buffer.slice( from, to );
  806. return slice( dataArray, infoObject.buffer, from, to );
  807. }
  808. },
  809. ByPolygon: {
  810. Direct: function ( polygonVertexIndex, polygonIndex, vertexIndex, infoObject ) {
  811. var from = polygonIndex * infoObject.dataSize;
  812. var to = polygonIndex * infoObject.dataSize + infoObject.dataSize;
  813. // return infoObject.buffer.slice( from, to );
  814. return slice( dataArray, infoObject.buffer, from, to );
  815. },
  816. IndexToDirect: function ( polygonVertexIndex, polygonIndex, vertexIndex, infoObject ) {
  817. var index = infoObject.indices[ polygonIndex ];
  818. var from = index * infoObject.dataSize;
  819. var to = index * infoObject.dataSize + infoObject.dataSize;
  820. // return infoObject.buffer.slice( from, to );
  821. return slice( dataArray, infoObject.buffer, from, to );
  822. }
  823. },
  824. ByVertice: {
  825. Direct: function ( polygonVertexIndex, polygonIndex, vertexIndex, infoObject ) {
  826. var from = ( vertexIndex * infoObject.dataSize );
  827. var to = ( vertexIndex * infoObject.dataSize ) + infoObject.dataSize;
  828. // return infoObject.buffer.slice( from, to );
  829. return slice( dataArray, infoObject.buffer, from, to );
  830. }
  831. },
  832. AllSame: {
  833. IndexToDirect: function ( polygonVertexIndex, polygonIndex, vertexIndex, infoObject ) {
  834. var from = infoObject.indices[ 0 ] * infoObject.dataSize;
  835. var to = infoObject.indices[ 0 ] * infoObject.dataSize + infoObject.dataSize;
  836. // return infoObject.buffer.slice( from, to );
  837. return slice( dataArray, infoObject.buffer, from, to );
  838. }
  839. }
  840. };
  841. function getData( polygonVertexIndex, polygonIndex, vertexIndex, infoObject ) {
  842. return GetData[ infoObject.mappingType ][ infoObject.referenceType ]( polygonVertexIndex, polygonIndex, vertexIndex, infoObject );
  843. }
  844. // Generate a NurbGeometry from a node in FBXTree.Objects.subNodes.Geometry
  845. function parseNurbsGeometry( geometryNode ) {
  846. if ( THREE.NURBSCurve === undefined ) {
  847. console.error( 'THREE.FBXLoader: The loader relies on THREE.NURBSCurve for any nurbs present in the model. Nurbs will show up as empty geometry.' );
  848. return new THREE.BufferGeometry();
  849. }
  850. var order = parseInt( geometryNode.properties.Order );
  851. if ( isNaN( order ) ) {
  852. console.error( 'THREE.FBXLoader: Invalid Order %s given for geometry ID: %s', geometryNode.properties.Order, geometryNode.id );
  853. return new THREE.BufferGeometry();
  854. }
  855. var degree = order - 1;
  856. var knots = geometryNode.subNodes.KnotVector.properties.a;
  857. var controlPoints = [];
  858. var pointsValues = geometryNode.subNodes.Points.properties.a;
  859. for ( var i = 0, l = pointsValues.length; i < l; i += 4 ) {
  860. controlPoints.push( new THREE.Vector4().fromArray( pointsValues, i ) );
  861. }
  862. var startKnot, endKnot;
  863. if ( geometryNode.properties.Form === 'Closed' ) {
  864. controlPoints.push( controlPoints[ 0 ] );
  865. } else if ( geometryNode.properties.Form === 'Periodic' ) {
  866. startKnot = degree;
  867. endKnot = knots.length - 1 - startKnot;
  868. for ( var i = 0; i < degree; ++ i ) {
  869. controlPoints.push( controlPoints[ i ] );
  870. }
  871. }
  872. var curve = new THREE.NURBSCurve( degree, knots, controlPoints, startKnot, endKnot );
  873. var vertices = curve.getPoints( controlPoints.length * 7 );
  874. var positions = new Float32Array( vertices.length * 3 );
  875. for ( var i = 0, l = vertices.length; i < l; ++ i ) {
  876. vertices[ i ].toArray( positions, i * 3 );
  877. }
  878. var geometry = new THREE.BufferGeometry();
  879. geometry.addAttribute( 'position', new THREE.BufferAttribute( positions, 3 ) );
  880. return geometry;
  881. }
  882. // parse nodes in FBXTree.Objects.subNodes.Model and generate a THREE.Group
  883. function parseScene( FBXTree, connections, deformers, geometryMap, materialMap ) {
  884. var sceneGraph = new THREE.Group();
  885. var ModelNode = FBXTree.Objects.subNodes.Model;
  886. var modelArray = [];
  887. var modelMap = new Map();
  888. for ( var nodeID in ModelNode ) {
  889. var id = parseInt( nodeID );
  890. var node = ModelNode[ nodeID ];
  891. var conns = connections.get( id );
  892. var model = null;
  893. for ( var i = 0; i < conns.parents.length; ++ i ) {
  894. for ( var FBX_ID in deformers ) {
  895. var deformer = deformers[ FBX_ID ];
  896. var subDeformers = deformer.map;
  897. var subDeformer = subDeformers[ conns.parents[ i ].ID ];
  898. if ( subDeformer ) {
  899. var model2 = model;
  900. model = new THREE.Bone();
  901. deformer.bones[ subDeformer.index ] = model;
  902. // seems like we need this not to make non-connected bone, maybe?
  903. // TODO: confirm
  904. if ( model2 !== null ) model.add( model2 );
  905. }
  906. }
  907. }
  908. if ( ! model ) {
  909. switch ( node.attrType ) {
  910. // create a THREE.PerspectiveCamera or THREE.OrthographicCamera
  911. case 'Camera':
  912. var cameraAttribute;
  913. for ( var childrenIndex = 0, childrenLength = conns.children.length; childrenIndex < childrenLength; ++ childrenIndex ) {
  914. var childID = conns.children[ childrenIndex ].ID;
  915. var attr = FBXTree.Objects.subNodes.NodeAttribute[ childID ];
  916. if ( attr !== undefined && attr.properties !== undefined ) {
  917. cameraAttribute = attr.properties;
  918. }
  919. }
  920. if ( cameraAttribute === undefined ) {
  921. model = new THREE.Object3D();
  922. } else {
  923. var type = 0;
  924. if ( cameraAttribute.CameraProjectionType !== undefined && cameraAttribute.CameraProjectionType.value === 1 ) {
  925. type = 1;
  926. }
  927. var nearClippingPlane = 1;
  928. if ( cameraAttribute.NearPlane !== undefined ) {
  929. nearClippingPlane = cameraAttribute.NearPlane.value / 1000;
  930. }
  931. var farClippingPlane = 1000;
  932. if ( cameraAttribute.FarPlane !== undefined ) {
  933. farClippingPlane = cameraAttribute.FarPlane.value / 1000;
  934. }
  935. var width = window.innerWidth;
  936. var height = window.innerHeight;
  937. if ( cameraAttribute.AspectWidth !== undefined && cameraAttribute.AspectHeight !== undefined ) {
  938. width = cameraAttribute.AspectWidth.value;
  939. height = cameraAttribute.AspectHeight.value;
  940. }
  941. var aspect = width / height;
  942. var fov = 45;
  943. if ( cameraAttribute.FieldOfView !== undefined ) {
  944. fov = cameraAttribute.FieldOfView.value;
  945. }
  946. switch ( type ) {
  947. case 0: // Perspective
  948. model = new THREE.PerspectiveCamera( fov, aspect, nearClippingPlane, farClippingPlane );
  949. break;
  950. case 1: // Orthographic
  951. model = new THREE.OrthographicCamera( - width / 2, width / 2, height / 2, - height / 2, nearClippingPlane, farClippingPlane );
  952. break;
  953. default:
  954. console.warn( 'THREE.FBXLoader: Unknown camera type ' + type + '.' );
  955. model = new THREE.Object3D();
  956. break;
  957. }
  958. }
  959. break;
  960. // Create a THREE.DirectionalLight, THREE.PointLight or THREE.SpotLight
  961. case 'Light':
  962. var lightAttribute;
  963. for ( var childrenIndex = 0, childrenLength = conns.children.length; childrenIndex < childrenLength; ++ childrenIndex ) {
  964. var childID = conns.children[ childrenIndex ].ID;
  965. var attr = FBXTree.Objects.subNodes.NodeAttribute[ childID ];
  966. if ( attr !== undefined && attr.properties !== undefined ) {
  967. lightAttribute = attr.properties;
  968. }
  969. }
  970. if ( lightAttribute === undefined ) {
  971. model = new THREE.Object3D();
  972. } else {
  973. var type;
  974. // LightType can be undefined for Point lights
  975. if ( lightAttribute.LightType === undefined ) {
  976. type = 0;
  977. } else {
  978. type = lightAttribute.LightType.value;
  979. }
  980. var color = 0xffffff;
  981. if ( lightAttribute.Color !== undefined ) {
  982. color = parseColor( lightAttribute.Color );
  983. }
  984. var intensity = ( lightAttribute.Intensity === undefined ) ? 1 : lightAttribute.Intensity.value / 100;
  985. // light disabled
  986. if ( lightAttribute.CastLightOnObject !== undefined && lightAttribute.CastLightOnObject.value === 0 ) {
  987. intensity = 0;
  988. }
  989. var distance = 0;
  990. if ( lightAttribute.FarAttenuationEnd !== undefined ) {
  991. if ( lightAttribute.EnableFarAttenuation !== undefined && lightAttribute.EnableFarAttenuation.value === 0 ) {
  992. distance = 0;
  993. } else {
  994. distance = lightAttribute.FarAttenuationEnd.value / 1000;
  995. }
  996. }
  997. // TODO: could this be calculated linearly from FarAttenuationStart to FarAttenuationEnd?
  998. var decay = 1;
  999. switch ( type ) {
  1000. case 0: // Point
  1001. model = new THREE.PointLight( color, intensity, distance, decay );
  1002. break;
  1003. case 1: // Directional
  1004. model = new THREE.DirectionalLight( color, intensity );
  1005. break;
  1006. case 2: // Spot
  1007. var angle = Math.PI / 3;
  1008. if ( lightAttribute.InnerAngle !== undefined ) {
  1009. angle = THREE.Math.degToRad( lightAttribute.InnerAngle.value );
  1010. }
  1011. var penumbra = 0;
  1012. if ( lightAttribute.OuterAngle !== undefined ) {
  1013. // TODO: this is not correct - FBX calculates outer and inner angle in degrees
  1014. // with OuterAngle > InnerAngle && OuterAngle <= Math.PI
  1015. // while three.js uses a penumbra between (0, 1) to attenuate the inner angle
  1016. penumbra = THREE.Math.degToRad( lightAttribute.OuterAngle.value );
  1017. penumbra = Math.max( penumbra, 1 );
  1018. }
  1019. model = new THREE.SpotLight( color, intensity, distance, angle, penumbra, decay );
  1020. break;
  1021. default:
  1022. console.warn( 'THREE.FBXLoader: Unknown light type ' + lightAttribute.LightType.value + ', defaulting to a THREE.PointLight.' );
  1023. model = new THREE.PointLight( color, intensity );
  1024. break;
  1025. }
  1026. if ( lightAttribute.CastShadows !== undefined && lightAttribute.CastShadows.value === 1 ) {
  1027. model.castShadow = true;
  1028. }
  1029. }
  1030. break;
  1031. case 'Mesh':
  1032. var geometry = null;
  1033. var material = null;
  1034. var materials = [];
  1035. for ( var childrenIndex = 0, childrenLength = conns.children.length; childrenIndex < childrenLength; ++ childrenIndex ) {
  1036. var child = conns.children[ childrenIndex ];
  1037. if ( geometryMap.has( child.ID ) ) {
  1038. geometry = geometryMap.get( child.ID );
  1039. }
  1040. if ( materialMap.has( child.ID ) ) {
  1041. materials.push( materialMap.get( child.ID ) );
  1042. }
  1043. }
  1044. if ( materials.length > 1 ) {
  1045. material = materials;
  1046. } else if ( materials.length > 0 ) {
  1047. material = materials[ 0 ];
  1048. } else {
  1049. material = new THREE.MeshPhongMaterial( { color: 0xcccccc } );
  1050. materials.push( material );
  1051. }
  1052. if ( 'color' in geometry.attributes ) {
  1053. for ( var materialIndex = 0, numMaterials = materials.length; materialIndex < numMaterials; ++ materialIndex ) {
  1054. materials[ materialIndex ].vertexColors = THREE.VertexColors;
  1055. }
  1056. }
  1057. if ( geometry.FBX_Deformer ) {
  1058. for ( var materialsIndex = 0, materialsLength = materials.length; materialsIndex < materialsLength; ++ materialsIndex ) {
  1059. materials[ materialsIndex ].skinning = true;
  1060. }
  1061. model = new THREE.SkinnedMesh( geometry, material );
  1062. } else {
  1063. model = new THREE.Mesh( geometry, material );
  1064. }
  1065. break;
  1066. case 'NurbsCurve':
  1067. var geometry = null;
  1068. for ( var childrenIndex = 0, childrenLength = conns.children.length; childrenIndex < childrenLength; ++ childrenIndex ) {
  1069. var child = conns.children[ childrenIndex ];
  1070. if ( geometryMap.has( child.ID ) ) {
  1071. geometry = geometryMap.get( child.ID );
  1072. }
  1073. }
  1074. // FBX does not list materials for Nurbs lines, so we'll just put our own in here.
  1075. material = new THREE.LineBasicMaterial( { color: 0x3300ff, linewidth: 5 } );
  1076. model = new THREE.Line( geometry, material );
  1077. break;
  1078. default:
  1079. model = new THREE.Group();
  1080. break;
  1081. }
  1082. }
  1083. model.name = THREE.PropertyBinding.sanitizeNodeName( node.attrName );
  1084. model.FBX_ID = id;
  1085. modelArray.push( model );
  1086. modelMap.set( id, model );
  1087. }
  1088. for ( var modelArrayIndex = 0, modelArrayLength = modelArray.length; modelArrayIndex < modelArrayLength; ++ modelArrayIndex ) {
  1089. var model = modelArray[ modelArrayIndex ];
  1090. var node = ModelNode[ model.FBX_ID ];
  1091. if ( 'Lcl_Translation' in node.properties ) {
  1092. model.position.fromArray( node.properties.Lcl_Translation.value );
  1093. }
  1094. if ( 'Lcl_Rotation' in node.properties ) {
  1095. var rotation = node.properties.Lcl_Rotation.value.map( THREE.Math.degToRad );
  1096. rotation.push( 'ZYX' );
  1097. model.rotation.fromArray( rotation );
  1098. }
  1099. if ( 'Lcl_Scaling' in node.properties ) {
  1100. model.scale.fromArray( node.properties.Lcl_Scaling.value );
  1101. }
  1102. if ( 'PreRotation' in node.properties ) {
  1103. var array = node.properties.PreRotation.value.map( THREE.Math.degToRad );
  1104. array[ 3 ] = 'ZYX';
  1105. var preRotations = new THREE.Euler().fromArray( array );
  1106. preRotations = new THREE.Quaternion().setFromEuler( preRotations );
  1107. var currentRotation = new THREE.Quaternion().setFromEuler( model.rotation );
  1108. preRotations.multiply( currentRotation );
  1109. model.rotation.setFromQuaternion( preRotations, 'ZYX' );
  1110. }
  1111. // rotated pivots - note: rotation must be applied before translation here
  1112. if ( 'GeometricRotation' in node.properties ) {
  1113. var array = node.properties.GeometricRotation.value.map( THREE.Math.degToRad );
  1114. model.traverse( function ( child ) {
  1115. if ( child.geometry ) {
  1116. child.geometry.rotateX( array[ 0 ] );
  1117. child.geometry.rotateY( array[ 1 ] );
  1118. child.geometry.rotateZ( array[ 2 ] );
  1119. }
  1120. } );
  1121. }
  1122. // translated pivots
  1123. if ( 'GeometricTranslation' in node.properties ) {
  1124. var array = node.properties.GeometricTranslation.value;
  1125. model.traverse( function ( child ) {
  1126. if ( child.geometry ) {
  1127. child.geometry.translate( array[ 0 ], array[ 1 ], array[ 2 ] );
  1128. }
  1129. } );
  1130. }
  1131. if ( 'LookAtProperty' in node.properties ) {
  1132. var conns = connections.get( model.FBX_ID );
  1133. for ( var childrenIndex = 0, childrenLength = conns.children.length; childrenIndex < childrenLength; ++ childrenIndex ) {
  1134. var child = conns.children[ childrenIndex ];
  1135. if ( child.relationship === 'LookAtProperty' ) {
  1136. var lookAtTarget = FBXTree.Objects.subNodes.Model[ child.ID ];
  1137. if ( 'Lcl_Translation' in lookAtTarget.properties ) {
  1138. var pos = lookAtTarget.properties.Lcl_Translation.value;
  1139. // DirectionalLight, SpotLight
  1140. if ( model.target !== undefined ) {
  1141. model.target.position.set( pos[ 0 ], pos[ 1 ], pos[ 2 ] );
  1142. sceneGraph.add( model.target );
  1143. } else { // Cameras and other Object3Ds
  1144. model.lookAt( new THREE.Vector3( pos[ 0 ], pos[ 1 ], pos[ 2 ] ) );
  1145. }
  1146. }
  1147. }
  1148. }
  1149. }
  1150. var conns = connections.get( model.FBX_ID );
  1151. for ( var parentIndex = 0; parentIndex < conns.parents.length; parentIndex ++ ) {
  1152. var pIndex = findIndex( modelArray, function ( mod ) {
  1153. return mod.FBX_ID === conns.parents[ parentIndex ].ID;
  1154. } );
  1155. if ( pIndex > - 1 ) {
  1156. modelArray[ pIndex ].add( model );
  1157. break;
  1158. }
  1159. }
  1160. if ( model.parent === null ) {
  1161. sceneGraph.add( model );
  1162. }
  1163. }
  1164. // Now with the bones created, we can update the skeletons and bind them to the skinned meshes.
  1165. sceneGraph.updateMatrixWorld( true );
  1166. var worldMatrices = new Map();
  1167. // Put skeleton into bind pose.
  1168. if ( 'Pose' in FBXTree.Objects.subNodes ) {
  1169. var BindPoseNode = FBXTree.Objects.subNodes.Pose;
  1170. for ( var nodeID in BindPoseNode ) {
  1171. if ( BindPoseNode[ nodeID ].attrType === 'BindPose' ) {
  1172. BindPoseNode = BindPoseNode[ nodeID ];
  1173. break;
  1174. }
  1175. }
  1176. var PoseNode = BindPoseNode.subNodes.PoseNode;
  1177. for ( var PoseNodeIndex = 0, PoseNodeLength = PoseNode.length; PoseNodeIndex < PoseNodeLength; ++ PoseNodeIndex ) {
  1178. var node = PoseNode[ PoseNodeIndex ];
  1179. var rawMatWrd = new THREE.Matrix4().fromArray( node.subNodes.Matrix.properties.a );
  1180. worldMatrices.set( parseInt( node.properties.Node ), rawMatWrd );
  1181. }
  1182. }
  1183. for ( var FBX_ID in deformers ) {
  1184. var deformer = deformers[ FBX_ID ];
  1185. var subDeformers = deformer.map;
  1186. for ( var key in subDeformers ) {
  1187. var subDeformer = subDeformers[ key ];
  1188. var subDeformerIndex = subDeformer.index;
  1189. var bone = deformer.bones[ subDeformerIndex ];
  1190. if ( ! worldMatrices.has( bone.FBX_ID ) ) {
  1191. break;
  1192. }
  1193. var mat = worldMatrices.get( bone.FBX_ID );
  1194. bone.matrixWorld.copy( mat );
  1195. }
  1196. // Now that skeleton is in bind pose, bind to model.
  1197. deformer.skeleton = new THREE.Skeleton( deformer.bones );
  1198. var conns = connections.get( deformer.FBX_ID );
  1199. var parents = conns.parents;
  1200. for ( var parentsIndex = 0, parentsLength = parents.length; parentsIndex < parentsLength; ++ parentsIndex ) {
  1201. var parent = parents[ parentsIndex ];
  1202. if ( geometryMap.has( parent.ID ) ) {
  1203. var geoID = parent.ID;
  1204. var geoConns = connections.get( geoID );
  1205. for ( var i = 0; i < geoConns.parents.length; ++ i ) {
  1206. if ( modelMap.has( geoConns.parents[ i ].ID ) ) {
  1207. var model = modelMap.get( geoConns.parents[ i ].ID );
  1208. model.bind( deformer.skeleton, model.matrixWorld );
  1209. break;
  1210. }
  1211. }
  1212. }
  1213. }
  1214. }
  1215. //Skeleton is now bound, return objects to starting world positions.
  1216. sceneGraph.updateMatrixWorld( true );
  1217. // Silly hack with the animation parsing. We're gonna pretend the scene graph has a skeleton
  1218. // to attach animations to, since FBX treats animations as animations for the entire scene,
  1219. // not just for individual objects.
  1220. sceneGraph.skeleton = {
  1221. bones: modelArray
  1222. };
  1223. var animations = parseAnimations( FBXTree, connections, sceneGraph );
  1224. addAnimations( sceneGraph, animations );
  1225. // Parse ambient color - if it's not set to black (default), create an ambient light
  1226. if ( 'GlobalSettings' in FBXTree && 'AmbientColor' in FBXTree.GlobalSettings.properties ) {
  1227. var ambientColor = FBXTree.GlobalSettings.properties.AmbientColor.value;
  1228. var r = ambientColor[ 0 ];
  1229. var g = ambientColor[ 1 ];
  1230. var b = ambientColor[ 2 ];
  1231. if ( r !== 0 || g !== 0 || b !== 0 ) {
  1232. var color = new THREE.Color( r, g, b );
  1233. sceneGraph.add( new THREE.AmbientLight( color, 1 ) );
  1234. }
  1235. }
  1236. return sceneGraph;
  1237. }
  1238. // Parses animation information from nodes in
  1239. // FBXTree.Objects.subNodes.AnimationCurve ( connected to AnimationCurveNode )
  1240. // FBXTree.Objects.subNodes.AnimationCurveNode ( connected to AnimationLayer and an animated property in some other node )
  1241. // FBXTree.Objects.subNodes.AnimationLayer ( connected to AnimationStack )
  1242. // FBXTree.Objects.subNodes.AnimationStack
  1243. function parseAnimations( FBXTree, connections, sceneGraph ) {
  1244. var rawNodes = FBXTree.Objects.subNodes.AnimationCurveNode;
  1245. var rawCurves = FBXTree.Objects.subNodes.AnimationCurve;
  1246. var rawLayers = FBXTree.Objects.subNodes.AnimationLayer;
  1247. var rawStacks = FBXTree.Objects.subNodes.AnimationStack;
  1248. var fps = 30; // default framerate
  1249. if ( 'GlobalSettings' in FBXTree && 'TimeMode' in FBXTree.GlobalSettings.properties ) {
  1250. /* Autodesk time mode documentation can be found here:
  1251. * 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
  1252. */
  1253. var timeModeEnum = [
  1254. 30, // 0: eDefaultMode
  1255. 120, // 1: eFrames120
  1256. 100, // 2: eFrames100
  1257. 60, // 3: eFrames60
  1258. 50, // 4: eFrames50
  1259. 48, // 5: eFrames48
  1260. 30, // 6: eFrames30 (black and white NTSC )
  1261. 30, // 7: eFrames30Drop
  1262. 29.97, // 8: eNTSCDropFrame
  1263. 29.97, // 90: eNTSCFullFrame
  1264. 25, // 10: ePal ( PAL/SECAM )
  1265. 24, // 11: eFrames24 (Film/Cinema)
  1266. 1, // 12: eFrames1000 (use for date time))
  1267. 23.976, // 13: eFilmFullFrame
  1268. 30, // 14: eCustom: use GlobalSettings.properties.CustomFrameRate.value
  1269. 96, // 15: eFrames96
  1270. 72, // 16: eFrames72
  1271. 59.94, // 17: eFrames59dot94
  1272. ];
  1273. var eMode = FBXTree.GlobalSettings.properties.TimeMode.value;
  1274. if ( eMode === 14 ) {
  1275. if ( 'CustomFrameRate' in FBXTree.GlobalSettings.properties ) {
  1276. fps = FBXTree.GlobalSettings.properties.CustomFrameRate.value;
  1277. fps = ( fps === - 1 ) ? 30 : fps;
  1278. }
  1279. } else if ( eMode <= 17 ) { // for future proofing - if more eModes get added, they will default to 30fps
  1280. fps = timeModeEnum[ eMode ];
  1281. }
  1282. }
  1283. var returnObject = {
  1284. curves: new Map(),
  1285. layers: {},
  1286. stacks: {},
  1287. length: 0,
  1288. fps: fps,
  1289. frames: 0
  1290. };
  1291. var animationCurveNodes = [];
  1292. for ( var nodeID in rawNodes ) {
  1293. if ( nodeID.match( /\d+/ ) ) {
  1294. var animationNode = parseAnimationNode( FBXTree, rawNodes[ nodeID ], connections, sceneGraph );
  1295. animationCurveNodes.push( animationNode );
  1296. }
  1297. }
  1298. var tmpMap = new Map();
  1299. for ( var animationCurveNodeIndex = 0; animationCurveNodeIndex < animationCurveNodes.length; ++ animationCurveNodeIndex ) {
  1300. if ( animationCurveNodes[ animationCurveNodeIndex ] === null ) {
  1301. continue;
  1302. }
  1303. tmpMap.set( animationCurveNodes[ animationCurveNodeIndex ].id, animationCurveNodes[ animationCurveNodeIndex ] );
  1304. }
  1305. var animationCurves = [];
  1306. for ( nodeID in rawCurves ) {
  1307. if ( nodeID.match( /\d+/ ) ) {
  1308. var animationCurve = parseAnimationCurve( rawCurves[ nodeID ] );
  1309. // seems like this check would be necessary?
  1310. if ( ! connections.has( animationCurve.id ) ) continue;
  1311. animationCurves.push( animationCurve );
  1312. var firstParentConn = connections.get( animationCurve.id ).parents[ 0 ];
  1313. var firstParentID = firstParentConn.ID;
  1314. var firstParentRelationship = firstParentConn.relationship;
  1315. var axis = '';
  1316. if ( firstParentRelationship.match( /X/ ) ) {
  1317. axis = 'x';
  1318. } else if ( firstParentRelationship.match( /Y/ ) ) {
  1319. axis = 'y';
  1320. } else if ( firstParentRelationship.match( /Z/ ) ) {
  1321. axis = 'z';
  1322. } else {
  1323. continue;
  1324. }
  1325. tmpMap.get( firstParentID ).curves[ axis ] = animationCurve;
  1326. }
  1327. }
  1328. tmpMap.forEach( function ( curveNode ) {
  1329. var id = curveNode.containerBoneID;
  1330. if ( ! returnObject.curves.has( id ) ) {
  1331. returnObject.curves.set( id, { T: null, R: null, S: null } );
  1332. }
  1333. returnObject.curves.get( id )[ curveNode.attr ] = curveNode;
  1334. if ( curveNode.attr === 'R' ) {
  1335. var curves = curveNode.curves;
  1336. // Some FBX files have an AnimationCurveNode
  1337. // which isn't any connected to any AnimationCurve.
  1338. // Setting animation parameter for them here.
  1339. if ( curves.x === null ) {
  1340. curves.x = {
  1341. version: null,
  1342. times: [ 0.0 ],
  1343. values: [ 0.0 ]
  1344. };
  1345. }
  1346. if ( curves.y === null ) {
  1347. curves.y = {
  1348. version: null,
  1349. times: [ 0.0 ],
  1350. values: [ 0.0 ]
  1351. };
  1352. }
  1353. if ( curves.z === null ) {
  1354. curves.z = {
  1355. version: null,
  1356. times: [ 0.0 ],
  1357. values: [ 0.0 ]
  1358. };
  1359. }
  1360. curves.x.values = curves.x.values.map( THREE.Math.degToRad );
  1361. curves.y.values = curves.y.values.map( THREE.Math.degToRad );
  1362. curves.z.values = curves.z.values.map( THREE.Math.degToRad );
  1363. if ( curveNode.preRotations !== null ) {
  1364. var preRotations = new THREE.Euler().setFromVector3( curveNode.preRotations, 'ZYX' );
  1365. preRotations = new THREE.Quaternion().setFromEuler( preRotations );
  1366. var frameRotation = new THREE.Euler();
  1367. var frameRotationQuaternion = new THREE.Quaternion();
  1368. for ( var frame = 0; frame < curves.x.times.length; ++ frame ) {
  1369. frameRotation.set( curves.x.values[ frame ], curves.y.values[ frame ], curves.z.values[ frame ], 'ZYX' );
  1370. frameRotationQuaternion.setFromEuler( frameRotation ).premultiply( preRotations );
  1371. frameRotation.setFromQuaternion( frameRotationQuaternion, 'ZYX' );
  1372. curves.x.values[ frame ] = frameRotation.x;
  1373. curves.y.values[ frame ] = frameRotation.y;
  1374. curves.z.values[ frame ] = frameRotation.z;
  1375. }
  1376. }
  1377. }
  1378. } );
  1379. for ( var nodeID in rawLayers ) {
  1380. var layer = [];
  1381. var connection = connections.get( parseInt( nodeID ) );
  1382. if ( connection !== undefined ) {
  1383. var children = connection.children;
  1384. for ( var childIndex = 0; childIndex < children.length; childIndex ++ ) {
  1385. // Skip lockInfluenceWeights
  1386. if ( tmpMap.has( children[ childIndex ].ID ) ) {
  1387. var curveNode = tmpMap.get( children[ childIndex ].ID );
  1388. var boneID = curveNode.containerBoneID;
  1389. if ( layer[ boneID ] === undefined ) {
  1390. layer[ boneID ] = {
  1391. T: null,
  1392. R: null,
  1393. S: null
  1394. };
  1395. }
  1396. layer[ boneID ][ curveNode.attr ] = curveNode;
  1397. }
  1398. }
  1399. returnObject.layers[ nodeID ] = layer;
  1400. }
  1401. }
  1402. for ( var nodeID in rawStacks ) {
  1403. var layers = [];
  1404. var children = connections.get( parseInt( nodeID ) ).children;
  1405. var timestamps = { max: 0, min: Number.MAX_VALUE };
  1406. for ( var childIndex = 0; childIndex < children.length; ++ childIndex ) {
  1407. var currentLayer = returnObject.layers[ children[ childIndex ].ID ];
  1408. if ( currentLayer !== undefined ) {
  1409. layers.push( currentLayer );
  1410. for ( var currentLayerIndex = 0, currentLayerLength = currentLayer.length; currentLayerIndex < currentLayerLength; ++ currentLayerIndex ) {
  1411. var layer = currentLayer[ currentLayerIndex ];
  1412. if ( layer ) {
  1413. getCurveNodeMaxMinTimeStamps( layer, timestamps );
  1414. }
  1415. }
  1416. }
  1417. }
  1418. // Do we have an animation clip with actual length?
  1419. if ( timestamps.max > timestamps.min ) {
  1420. returnObject.stacks[ nodeID ] = {
  1421. name: rawStacks[ nodeID ].attrName,
  1422. layers: layers,
  1423. length: timestamps.max - timestamps.min,
  1424. frames: ( timestamps.max - timestamps.min ) * returnObject.fps
  1425. };
  1426. }
  1427. }
  1428. return returnObject;
  1429. }
  1430. function parseAnimationNode( FBXTree, animationCurveNode, connections, sceneGraph ) {
  1431. var rawModels = FBXTree.Objects.subNodes.Model;
  1432. var returnObject = {
  1433. id: animationCurveNode.id,
  1434. attr: animationCurveNode.attrName,
  1435. internalID: animationCurveNode.id,
  1436. attrX: false,
  1437. attrY: false,
  1438. attrZ: false,
  1439. containerBoneID: - 1,
  1440. containerID: - 1,
  1441. curves: {
  1442. x: null,
  1443. y: null,
  1444. z: null
  1445. },
  1446. preRotations: null
  1447. };
  1448. if ( returnObject.attr.match( /S|R|T/ ) ) {
  1449. for ( var attributeKey in animationCurveNode.properties ) {
  1450. if ( attributeKey.match( /X/ ) ) {
  1451. returnObject.attrX = true;
  1452. }
  1453. if ( attributeKey.match( /Y/ ) ) {
  1454. returnObject.attrY = true;
  1455. }
  1456. if ( attributeKey.match( /Z/ ) ) {
  1457. returnObject.attrZ = true;
  1458. }
  1459. }
  1460. } else {
  1461. return null;
  1462. }
  1463. var conns = connections.get( returnObject.id );
  1464. var containerIndices = conns.parents;
  1465. for ( var containerIndicesIndex = containerIndices.length - 1; containerIndicesIndex >= 0; -- containerIndicesIndex ) {
  1466. var boneID = findIndex( sceneGraph.skeleton.bones, function ( bone ) {
  1467. return bone.FBX_ID === containerIndices[ containerIndicesIndex ].ID;
  1468. } );
  1469. if ( boneID > - 1 ) {
  1470. returnObject.containerBoneID = boneID;
  1471. returnObject.containerID = containerIndices[ containerIndicesIndex ].ID;
  1472. var model = rawModels[ returnObject.containerID.toString() ];
  1473. if ( 'PreRotation' in model.properties ) {
  1474. returnObject.preRotations = parseVector3( model.properties.PreRotation ).multiplyScalar( Math.PI / 180 );
  1475. }
  1476. break;
  1477. }
  1478. }
  1479. return returnObject;
  1480. }
  1481. function parseAnimationCurve( animationCurve ) {
  1482. return {
  1483. version: null,
  1484. id: animationCurve.id,
  1485. internalID: animationCurve.id,
  1486. times: animationCurve.subNodes.KeyTime.properties.a.map( convertFBXTimeToSeconds ),
  1487. values: animationCurve.subNodes.KeyValueFloat.properties.a,
  1488. attrFlag: animationCurve.subNodes.KeyAttrFlags.properties.a,
  1489. attrData: animationCurve.subNodes.KeyAttrDataFloat.properties.a,
  1490. };
  1491. }
  1492. // Sets the maxTimeStamp and minTimeStamp variables if it has timeStamps that are either larger or smaller
  1493. // than the max or min respectively.
  1494. function getCurveNodeMaxMinTimeStamps( layer, timestamps ) {
  1495. if ( layer.R ) {
  1496. getCurveMaxMinTimeStamp( layer.R.curves, timestamps );
  1497. }
  1498. if ( layer.S ) {
  1499. getCurveMaxMinTimeStamp( layer.S.curves, timestamps );
  1500. }
  1501. if ( layer.T ) {
  1502. getCurveMaxMinTimeStamp( layer.T.curves, timestamps );
  1503. }
  1504. }
  1505. // Sets the maxTimeStamp and minTimeStamp if one of the curve's time stamps
  1506. // exceeds the maximum or minimum.
  1507. function getCurveMaxMinTimeStamp( curve, timestamps ) {
  1508. if ( curve.x ) {
  1509. getCurveAxisMaxMinTimeStamps( curve.x, timestamps );
  1510. }
  1511. if ( curve.y ) {
  1512. getCurveAxisMaxMinTimeStamps( curve.y, timestamps );
  1513. }
  1514. if ( curve.z ) {
  1515. getCurveAxisMaxMinTimeStamps( curve.z, timestamps );
  1516. }
  1517. }
  1518. // Sets the maxTimeStamp and minTimeStamp if one of its timestamps exceeds the maximum or minimum.
  1519. function getCurveAxisMaxMinTimeStamps( axis, timestamps ) {
  1520. timestamps.max = axis.times[ axis.times.length - 1 ] > timestamps.max ? axis.times[ axis.times.length - 1 ] : timestamps.max;
  1521. timestamps.min = axis.times[ 0 ] < timestamps.min ? axis.times[ 0 ] : timestamps.min;
  1522. }
  1523. function addAnimations( group, animations ) {
  1524. if ( group.animations === undefined ) {
  1525. group.animations = [];
  1526. }
  1527. var stacks = animations.stacks;
  1528. for ( var key in stacks ) {
  1529. var stack = stacks[ key ];
  1530. var animationData = {
  1531. name: stack.name,
  1532. fps: animations.fps,
  1533. length: stack.length,
  1534. hierarchy: []
  1535. };
  1536. var bones = group.skeleton.bones;
  1537. for ( var bonesIndex = 0, bonesLength = bones.length; bonesIndex < bonesLength; ++ bonesIndex ) {
  1538. var bone = bones[ bonesIndex ];
  1539. var name = bone.name.replace( /.*:/, '' );
  1540. var parentIndex = findIndex( bones, function ( parentBone ) {
  1541. return bone.parent === parentBone;
  1542. } );
  1543. animationData.hierarchy.push( { parent: parentIndex, name: name, keys: [] } );
  1544. }
  1545. for ( var frame = 0; frame <= stack.frames; frame ++ ) {
  1546. for ( var bonesIndex = 0, bonesLength = bones.length; bonesIndex < bonesLength; ++ bonesIndex ) {
  1547. var bone = bones[ bonesIndex ];
  1548. var boneIndex = bonesIndex;
  1549. var animationNode = stack.layers[ 0 ][ boneIndex ];
  1550. for ( var hierarchyIndex = 0, hierarchyLength = animationData.hierarchy.length; hierarchyIndex < hierarchyLength; ++ hierarchyIndex ) {
  1551. var node = animationData.hierarchy[ hierarchyIndex ];
  1552. if ( node.name === bone.name ) {
  1553. node.keys.push( generateKey( animations, animationNode, bone, frame ) );
  1554. }
  1555. }
  1556. }
  1557. }
  1558. group.animations.push( THREE.AnimationClip.parseAnimation( animationData, bones ) );
  1559. }
  1560. }
  1561. var euler = new THREE.Euler();
  1562. var quaternion = new THREE.Quaternion();
  1563. function generateKey( animations, animationNode, bone, frame ) {
  1564. var key = {
  1565. time: frame / animations.fps,
  1566. pos: bone.position.toArray(),
  1567. rot: bone.quaternion.toArray(),
  1568. scl: bone.scale.toArray()
  1569. };
  1570. if ( animationNode === undefined ) return key;
  1571. euler.setFromQuaternion( bone.quaternion, 'ZYX', false );
  1572. try {
  1573. if ( hasCurve( animationNode, 'T' ) && hasKeyOnFrame( animationNode.T, frame ) ) {
  1574. if ( animationNode.T.curves.x.values[ frame ] ) {
  1575. key.pos[ 0 ] = animationNode.T.curves.x.values[ frame ];
  1576. }
  1577. if ( animationNode.T.curves.y.values[ frame ] ) {
  1578. key.pos[ 1 ] = animationNode.T.curves.y.values[ frame ];
  1579. }
  1580. if ( animationNode.T.curves.z.values[ frame ] ) {
  1581. key.pos[ 2 ] = animationNode.T.curves.z.values[ frame ];
  1582. }
  1583. }
  1584. if ( hasCurve( animationNode, 'R' ) && hasKeyOnFrame( animationNode.R, frame ) ) {
  1585. // Only update the euler's values if rotation is defined for the axis on this frame
  1586. if ( animationNode.R.curves.x.values[ frame ] ) {
  1587. euler.x = animationNode.R.curves.x.values[ frame ];
  1588. }
  1589. if ( animationNode.R.curves.y.values[ frame ] ) {
  1590. euler.y = animationNode.R.curves.y.values[ frame ];
  1591. }
  1592. if ( animationNode.R.curves.z.values[ frame ] ) {
  1593. euler.z = animationNode.R.curves.z.values[ frame ];
  1594. }
  1595. quaternion.setFromEuler( euler );
  1596. key.rot = quaternion.toArray();
  1597. }
  1598. if ( hasCurve( animationNode, 'S' ) && hasKeyOnFrame( animationNode.S, frame ) ) {
  1599. if ( animationNode.T.curves.x.values[ frame ] ) {
  1600. key.scl[ 0 ] = animationNode.S.curves.x.values[ frame ];
  1601. }
  1602. if ( animationNode.T.curves.y.values[ frame ] ) {
  1603. key.scl[ 1 ] = animationNode.S.curves.y.values[ frame ];
  1604. }
  1605. if ( animationNode.T.curves.z.values[ frame ] ) {
  1606. key.scl[ 2 ] = animationNode.S.curves.z.values[ frame ];
  1607. }
  1608. }
  1609. } catch ( error ) {
  1610. // Curve is not fully plotted.
  1611. console.log( 'THREE.FBXLoader: ', bone );
  1612. console.log( 'THREE.FBXLoader: ', error );
  1613. }
  1614. return key;
  1615. }
  1616. var AXES = [ 'x', 'y', 'z' ];
  1617. function hasCurve( animationNode, attribute ) {
  1618. if ( animationNode === undefined ) {
  1619. return false;
  1620. }
  1621. var attributeNode = animationNode[ attribute ];
  1622. if ( ! attributeNode ) {
  1623. return false;
  1624. }
  1625. return AXES.every( function ( key ) {
  1626. return attributeNode.curves[ key ] !== null;
  1627. } );
  1628. }
  1629. function hasKeyOnFrame( attributeNode, frame ) {
  1630. return AXES.every( function ( key ) {
  1631. return isKeyExistOnFrame( attributeNode.curves[ key ], frame );
  1632. } );
  1633. }
  1634. function isKeyExistOnFrame( curve, frame ) {
  1635. return curve.values[ frame ] !== undefined;
  1636. }
  1637. // parse an FBX file in ASCII format
  1638. function TextParser() {}
  1639. Object.assign( TextParser.prototype, {
  1640. getPrevNode: function () {
  1641. return this.nodeStack[ this.currentIndent - 2 ];
  1642. },
  1643. getCurrentNode: function () {
  1644. return this.nodeStack[ this.currentIndent - 1 ];
  1645. },
  1646. getCurrentProp: function () {
  1647. return this.currentProp;
  1648. },
  1649. pushStack: function ( node ) {
  1650. this.nodeStack.push( node );
  1651. this.currentIndent += 1;
  1652. },
  1653. popStack: function () {
  1654. this.nodeStack.pop();
  1655. this.currentIndent -= 1;
  1656. },
  1657. setCurrentProp: function ( val, name ) {
  1658. this.currentProp = val;
  1659. this.currentPropName = name;
  1660. },
  1661. parse: function ( text ) {
  1662. this.currentIndent = 0;
  1663. this.allNodes = new FBXTree();
  1664. this.nodeStack = [];
  1665. this.currentProp = [];
  1666. this.currentPropName = '';
  1667. var split = text.split( '\n' );
  1668. for ( var lineNum = 0, lineLength = split.length; lineNum < lineLength; lineNum ++ ) {
  1669. var l = split[ lineNum ];
  1670. // skip comment line
  1671. if ( l.match( /^[\s\t]*;/ ) ) {
  1672. continue;
  1673. }
  1674. // skip empty line
  1675. if ( l.match( /^[\s\t]*$/ ) ) {
  1676. continue;
  1677. }
  1678. // beginning of node
  1679. var beginningOfNodeExp = new RegExp( '^\\t{' + this.currentIndent + '}(\\w+):(.*){', '' );
  1680. var match = l.match( beginningOfNodeExp );
  1681. if ( match ) {
  1682. var nodeName = match[ 1 ].trim().replace( /^"/, '' ).replace( /"$/, '' );
  1683. var nodeAttrs = match[ 2 ].split( ',' );
  1684. for ( var i = 0, l = nodeAttrs.length; i < l; i ++ ) {
  1685. nodeAttrs[ i ] = nodeAttrs[ i ].trim().replace( /^"/, '' ).replace( /"$/, '' );
  1686. }
  1687. this.parseNodeBegin( l, nodeName, nodeAttrs || null );
  1688. continue;
  1689. }
  1690. // node's property
  1691. var propExp = new RegExp( '^\\t{' + ( this.currentIndent ) + '}(\\w+):[\\s\\t\\r\\n](.*)' );
  1692. var match = l.match( propExp );
  1693. if ( match ) {
  1694. var propName = match[ 1 ].replace( /^"/, '' ).replace( /"$/, '' ).trim();
  1695. var propValue = match[ 2 ].replace( /^"/, '' ).replace( /"$/, '' ).trim();
  1696. // for special case: base64 image data follows "Content: ," line
  1697. // Content: ,
  1698. // "iVB..."
  1699. if ( propName === 'Content' && propValue === ',' ) {
  1700. propValue = split[ ++ lineNum ].replace( /"/g, '' ).replace( /,$/, '' ).trim();
  1701. }
  1702. this.parseNodeProperty( l, propName, propValue );
  1703. continue;
  1704. }
  1705. // end of node
  1706. var endOfNodeExp = new RegExp( '^\\t{' + ( this.currentIndent - 1 ) + '}}' );
  1707. if ( l.match( endOfNodeExp ) ) {
  1708. this.nodeEnd();
  1709. continue;
  1710. }
  1711. // large arrays are split over multiple lines terminated with a ',' character
  1712. // if this is encountered the line needs to be joined to the previous line
  1713. if ( l.match( /^[^\s\t}]/ ) ) {
  1714. this.parseNodePropertyContinued( l );
  1715. }
  1716. }
  1717. return this.allNodes;
  1718. },
  1719. parseNodeBegin: function ( line, nodeName, nodeAttrs ) {
  1720. var node = { 'name': nodeName, properties: {}, 'subNodes': {} };
  1721. var attrs = this.parseNodeAttr( nodeAttrs );
  1722. var currentNode = this.getCurrentNode();
  1723. // a top node
  1724. if ( this.currentIndent === 0 ) {
  1725. this.allNodes.add( nodeName, node );
  1726. } else { // a subnode
  1727. // if the subnode already exists, append it
  1728. if ( nodeName in currentNode.subNodes ) {
  1729. var tmp = currentNode.subNodes[ nodeName ];
  1730. if ( this.isFlattenNode( currentNode.subNodes[ nodeName ] ) ) {
  1731. if ( attrs.id === '' ) {
  1732. currentNode.subNodes[ nodeName ] = [];
  1733. currentNode.subNodes[ nodeName ].push( tmp );
  1734. } else {
  1735. currentNode.subNodes[ nodeName ] = {};
  1736. currentNode.subNodes[ nodeName ][ tmp.id ] = tmp;
  1737. }
  1738. }
  1739. if ( attrs.id === '' ) {
  1740. currentNode.subNodes[ nodeName ].push( node );
  1741. } else {
  1742. currentNode.subNodes[ nodeName ][ attrs.id ] = node;
  1743. }
  1744. } else if ( typeof attrs.id === 'number' || attrs.id.match( /^\d+$/ ) ) {
  1745. currentNode.subNodes[ nodeName ] = {};
  1746. currentNode.subNodes[ nodeName ][ attrs.id ] = node;
  1747. } else {
  1748. currentNode.subNodes[ nodeName ] = node;
  1749. }
  1750. }
  1751. // for this ↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓
  1752. // NodeAttribute: 1001463072, "NodeAttribute::", "LimbNode" {
  1753. if ( nodeAttrs ) {
  1754. node.id = attrs.id;
  1755. node.attrName = attrs.name;
  1756. node.attrType = attrs.type;
  1757. }
  1758. this.pushStack( node );
  1759. },
  1760. parseNodeAttr: function ( attrs ) {
  1761. var id = attrs[ 0 ];
  1762. if ( attrs[ 0 ] !== '' ) {
  1763. id = parseInt( attrs[ 0 ] );
  1764. if ( isNaN( id ) ) {
  1765. id = attrs[ 0 ];
  1766. }
  1767. }
  1768. var name = '', type = '';
  1769. if ( attrs.length > 1 ) {
  1770. name = attrs[ 1 ].replace( /^(\w+)::/, '' );
  1771. type = attrs[ 2 ];
  1772. }
  1773. return { id: id, name: name, type: type };
  1774. },
  1775. parseNodeProperty: function ( line, propName, propValue ) {
  1776. var currentNode = this.getCurrentNode();
  1777. var parentName = currentNode.name;
  1778. // special case where the parent node is something like "Properties70"
  1779. // these children nodes must treated carefully
  1780. if ( parentName !== undefined ) {
  1781. var propMatch = parentName.match( /Properties(\d)+/ );
  1782. if ( propMatch ) {
  1783. this.parseNodeSpecialProperty( line, propName, propValue );
  1784. return;
  1785. }
  1786. }
  1787. // Connections
  1788. if ( propName === 'C' ) {
  1789. var connProps = propValue.split( ',' ).slice( 1 );
  1790. var from = parseInt( connProps[ 0 ] );
  1791. var to = parseInt( connProps[ 1 ] );
  1792. var rest = propValue.split( ',' ).slice( 3 );
  1793. rest = rest.map( function ( elem ) {
  1794. return elem.trim().replace( /^"/, '' );
  1795. } );
  1796. propName = 'connections';
  1797. propValue = [ from, to ];
  1798. append( propValue, rest );
  1799. if ( currentNode.properties[ propName ] === undefined ) {
  1800. currentNode.properties[ propName ] = [];
  1801. }
  1802. }
  1803. // Node
  1804. if ( propName === 'Node' ) {
  1805. var id = parseInt( propValue );
  1806. currentNode.properties.id = id;
  1807. currentNode.id = id;
  1808. }
  1809. // already exists in properties, then append this
  1810. if ( propName in currentNode.properties ) {
  1811. if ( Array.isArray( currentNode.properties[ propName ] ) ) {
  1812. currentNode.properties[ propName ].push( propValue );
  1813. } else {
  1814. currentNode.properties[ propName ] += propValue;
  1815. }
  1816. } else {
  1817. if ( Array.isArray( currentNode.properties[ propName ] ) ) {
  1818. currentNode.properties[ propName ].push( propValue );
  1819. } else {
  1820. currentNode.properties[ propName ] = propValue;
  1821. }
  1822. }
  1823. this.setCurrentProp( currentNode.properties, propName );
  1824. // convert string to array, unless it ends in ',' in which case more will be added to it
  1825. if ( propName === 'a' && propValue.slice( - 1 ) !== ',' ) {
  1826. currentNode.properties.a = parseNumberArray( propValue );
  1827. }
  1828. },
  1829. parseNodePropertyContinued: function ( line ) {
  1830. this.currentProp[ this.currentPropName ] += line;
  1831. // if the line doesn't end in ',' we have reached the end of the property value
  1832. // so convert the string to an array
  1833. if ( line.slice( - 1 ) !== ',' ) {
  1834. var currentNode = this.getCurrentNode();
  1835. currentNode.properties.a = parseNumberArray( currentNode.properties.a );
  1836. }
  1837. },
  1838. parseNodeSpecialProperty: function ( line, propName, propValue ) {
  1839. // split this
  1840. // P: "Lcl Scaling", "Lcl Scaling", "", "A",1,1,1
  1841. // into array like below
  1842. // ["Lcl Scaling", "Lcl Scaling", "", "A", "1,1,1" ]
  1843. var props = propValue.split( '",' );
  1844. for ( var i = 0, l = props.length; i < l; i ++ ) {
  1845. props[ i ] = props[ i ].trim().replace( /^\"/, '' ).replace( /\s/, '_' );
  1846. }
  1847. var innerPropName = props[ 0 ];
  1848. var innerPropType1 = props[ 1 ];
  1849. var innerPropType2 = props[ 2 ];
  1850. var innerPropFlag = props[ 3 ];
  1851. var innerPropValue = props[ 4 ];
  1852. // cast value to its type
  1853. switch ( innerPropType1 ) {
  1854. case 'int':
  1855. case 'enum':
  1856. case 'bool':
  1857. case 'ULongLong':
  1858. innerPropValue = parseInt( innerPropValue );
  1859. break;
  1860. case 'double':
  1861. case 'Number':
  1862. case 'FieldOfView':
  1863. innerPropValue = parseFloat( innerPropValue );
  1864. break;
  1865. case 'ColorRGB':
  1866. case 'Vector3D':
  1867. case 'Lcl_Translation':
  1868. case 'Lcl_Rotation':
  1869. case 'Lcl_Scaling':
  1870. innerPropValue = parseNumberArray( innerPropValue );
  1871. break;
  1872. }
  1873. // CAUTION: these props must append to parent's parent
  1874. this.getPrevNode().properties[ innerPropName ] = {
  1875. 'type': innerPropType1,
  1876. 'type2': innerPropType2,
  1877. 'flag': innerPropFlag,
  1878. 'value': innerPropValue
  1879. };
  1880. this.setCurrentProp( this.getPrevNode().properties, innerPropName );
  1881. },
  1882. nodeEnd: function () {
  1883. this.popStack();
  1884. },
  1885. isFlattenNode: function ( node ) {
  1886. return ( 'subNodes' in node && 'properties' in node ) ? true : false;
  1887. }
  1888. } );
  1889. // Parse an FBX file in Binary format
  1890. function BinaryParser() {}
  1891. Object.assign( BinaryParser.prototype, {
  1892. parse: function ( buffer ) {
  1893. var reader = new BinaryReader( buffer );
  1894. reader.skip( 23 ); // skip magic 23 bytes
  1895. var version = reader.getUint32();
  1896. console.log( 'THREE.FBXLoader: FBX binary version: ' + version );
  1897. var allNodes = new FBXTree();
  1898. while ( ! this.endOfContent( reader ) ) {
  1899. var node = this.parseNode( reader, version );
  1900. if ( node !== null ) allNodes.add( node.name, node );
  1901. }
  1902. return allNodes;
  1903. },
  1904. // Check if reader has reached the end of content.
  1905. endOfContent: function ( reader ) {
  1906. // footer size: 160bytes + 16-byte alignment padding
  1907. // - 16bytes: magic
  1908. // - padding til 16-byte alignment (at least 1byte?)
  1909. // (seems like some exporters embed fixed 15 or 16bytes?)
  1910. // - 4bytes: magic
  1911. // - 4bytes: version
  1912. // - 120bytes: zero
  1913. // - 16bytes: magic
  1914. if ( reader.size() % 16 === 0 ) {
  1915. return ( ( reader.getOffset() + 160 + 16 ) & ~ 0xf ) >= reader.size();
  1916. } else {
  1917. return reader.getOffset() + 160 + 16 >= reader.size();
  1918. }
  1919. },
  1920. parseNode: function ( reader, version ) {
  1921. // The first three data sizes depends on version.
  1922. var endOffset = ( version >= 7500 ) ? reader.getUint64() : reader.getUint32();
  1923. var numProperties = ( version >= 7500 ) ? reader.getUint64() : reader.getUint32();
  1924. // note: do not remove this even if you get a linter warning as it moves the buffer forward
  1925. var propertyListLen = ( version >= 7500 ) ? reader.getUint64() : reader.getUint32();
  1926. var nameLen = reader.getUint8();
  1927. var name = reader.getString( nameLen );
  1928. // Regards this node as NULL-record if endOffset is zero
  1929. if ( endOffset === 0 ) return null;
  1930. var propertyList = [];
  1931. for ( var i = 0; i < numProperties; i ++ ) {
  1932. propertyList.push( this.parseProperty( reader ) );
  1933. }
  1934. // Regards the first three elements in propertyList as id, attrName, and attrType
  1935. var id = propertyList.length > 0 ? propertyList[ 0 ] : '';
  1936. var attrName = propertyList.length > 1 ? propertyList[ 1 ] : '';
  1937. var attrType = propertyList.length > 2 ? propertyList[ 2 ] : '';
  1938. var subNodes = {};
  1939. var properties = {};
  1940. var isSingleProperty = false;
  1941. // check if this node represents just a single property
  1942. // like (name, 0) set or (name2, [0, 1, 2]) set of {name: 0, name2: [0, 1, 2]}
  1943. if ( numProperties === 1 && reader.getOffset() === endOffset ) {
  1944. isSingleProperty = true;
  1945. }
  1946. while ( endOffset > reader.getOffset() ) {
  1947. var node = this.parseNode( reader, version );
  1948. if ( node === null ) continue;
  1949. // special case: child node is single property
  1950. if ( node.singleProperty === true ) {
  1951. var value = node.propertyList[ 0 ];
  1952. if ( Array.isArray( value ) ) {
  1953. subNodes[ node.name ] = node;
  1954. node.properties.a = value;
  1955. } else {
  1956. properties[ node.name ] = value;
  1957. }
  1958. continue;
  1959. }
  1960. // parse connections
  1961. if ( name === 'Connections' && node.name === 'C' ) {
  1962. var array = [];
  1963. for ( var i = 1, il = node.propertyList.length; i < il; i ++ ) {
  1964. array[ i - 1 ] = node.propertyList[ i ];
  1965. }
  1966. if ( properties.connections === undefined ) {
  1967. properties.connections = [];
  1968. }
  1969. properties.connections.push( array );
  1970. continue;
  1971. }
  1972. // special case: child node is Properties\d+
  1973. // move child node's properties to this node.
  1974. if ( node.name.match( /^Properties\d+$/ ) ) {
  1975. var keys = Object.keys( node.properties );
  1976. for ( var i = 0, il = keys.length; i < il; i ++ ) {
  1977. var key = keys[ i ];
  1978. properties[ key ] = node.properties[ key ];
  1979. }
  1980. continue;
  1981. }
  1982. // parse 'properties70'
  1983. if ( name.match( /^Properties\d+$/ ) && node.name === 'P' ) {
  1984. var innerPropName = node.propertyList[ 0 ];
  1985. var innerPropType1 = node.propertyList[ 1 ];
  1986. var innerPropType2 = node.propertyList[ 2 ];
  1987. var innerPropFlag = node.propertyList[ 3 ];
  1988. var innerPropValue;
  1989. if ( innerPropName.indexOf( 'Lcl ' ) === 0 ) innerPropName = innerPropName.replace( 'Lcl ', 'Lcl_' );
  1990. if ( innerPropType1.indexOf( 'Lcl ' ) === 0 ) innerPropType1 = innerPropType1.replace( 'Lcl ', 'Lcl_' );
  1991. if ( innerPropType1 === 'ColorRGB' || innerPropType1 === 'Vector' || innerPropType1 === 'Vector3D' || innerPropType1.indexOf( 'Lcl_' ) === 0 ) {
  1992. innerPropValue = [
  1993. node.propertyList[ 4 ],
  1994. node.propertyList[ 5 ],
  1995. node.propertyList[ 6 ]
  1996. ];
  1997. } else {
  1998. innerPropValue = node.propertyList[ 4 ];
  1999. }
  2000. // this will be copied to parent, see above
  2001. properties[ innerPropName ] = {
  2002. 'type': innerPropType1,
  2003. 'type2': innerPropType2,
  2004. 'flag': innerPropFlag,
  2005. 'value': innerPropValue
  2006. };
  2007. continue;
  2008. }
  2009. if ( subNodes[ node.name ] === undefined ) {
  2010. if ( typeof node.id === 'number' ) {
  2011. subNodes[ node.name ] = {};
  2012. subNodes[ node.name ][ node.id ] = node;
  2013. } else {
  2014. subNodes[ node.name ] = node;
  2015. }
  2016. } else {
  2017. if ( node.id === '' ) {
  2018. if ( ! Array.isArray( subNodes[ node.name ] ) ) {
  2019. subNodes[ node.name ] = [ subNodes[ node.name ] ];
  2020. }
  2021. subNodes[ node.name ].push( node );
  2022. } else {
  2023. if ( subNodes[ node.name ][ node.id ] === undefined ) {
  2024. subNodes[ node.name ][ node.id ] = node;
  2025. } else {
  2026. // conflict id. irregular?
  2027. if ( ! Array.isArray( subNodes[ node.name ][ node.id ] ) ) {
  2028. subNodes[ node.name ][ node.id ] = [ subNodes[ node.name ][ node.id ] ];
  2029. }
  2030. subNodes[ node.name ][ node.id ].push( node );
  2031. }
  2032. }
  2033. }
  2034. }
  2035. return {
  2036. singleProperty: isSingleProperty,
  2037. id: id,
  2038. attrName: attrName,
  2039. attrType: attrType,
  2040. name: name,
  2041. properties: properties,
  2042. propertyList: propertyList, // raw property list used by parent
  2043. subNodes: subNodes
  2044. };
  2045. },
  2046. parseProperty: function ( reader ) {
  2047. var type = reader.getChar();
  2048. switch ( type ) {
  2049. case 'C':
  2050. return reader.getBoolean();
  2051. case 'D':
  2052. return reader.getFloat64();
  2053. case 'F':
  2054. return reader.getFloat32();
  2055. case 'I':
  2056. return reader.getInt32();
  2057. case 'L':
  2058. return reader.getInt64();
  2059. case 'R':
  2060. var length = reader.getUint32();
  2061. return reader.getArrayBuffer( length );
  2062. case 'S':
  2063. var length = reader.getUint32();
  2064. return reader.getString( length );
  2065. case 'Y':
  2066. return reader.getInt16();
  2067. case 'b':
  2068. case 'c':
  2069. case 'd':
  2070. case 'f':
  2071. case 'i':
  2072. case 'l':
  2073. var arrayLength = reader.getUint32();
  2074. var encoding = reader.getUint32(); // 0: non-compressed, 1: compressed
  2075. var compressedLength = reader.getUint32();
  2076. if ( encoding === 0 ) {
  2077. switch ( type ) {
  2078. case 'b':
  2079. case 'c':
  2080. return reader.getBooleanArray( arrayLength );
  2081. case 'd':
  2082. return reader.getFloat64Array( arrayLength );
  2083. case 'f':
  2084. return reader.getFloat32Array( arrayLength );
  2085. case 'i':
  2086. return reader.getInt32Array( arrayLength );
  2087. case 'l':
  2088. return reader.getInt64Array( arrayLength );
  2089. }
  2090. }
  2091. if ( window.Zlib === undefined ) {
  2092. throw new Error( 'THREE.FBXLoader: External library Inflate.min.js required, obtain or import from https://github.com/imaya/zlib.js' );
  2093. }
  2094. var inflate = new Zlib.Inflate( new Uint8Array( reader.getArrayBuffer( compressedLength ) ) ); // eslint-disable-line no-undef
  2095. var reader2 = new BinaryReader( inflate.decompress().buffer );
  2096. switch ( type ) {
  2097. case 'b':
  2098. case 'c':
  2099. return reader2.getBooleanArray( arrayLength );
  2100. case 'd':
  2101. return reader2.getFloat64Array( arrayLength );
  2102. case 'f':
  2103. return reader2.getFloat32Array( arrayLength );
  2104. case 'i':
  2105. return reader2.getInt32Array( arrayLength );
  2106. case 'l':
  2107. return reader2.getInt64Array( arrayLength );
  2108. }
  2109. default:
  2110. throw new Error( 'THREE.FBXLoader: Unknown property type ' + type );
  2111. }
  2112. }
  2113. } );
  2114. function BinaryReader( buffer, littleEndian ) {
  2115. this.dv = new DataView( buffer );
  2116. this.offset = 0;
  2117. this.littleEndian = ( littleEndian !== undefined ) ? littleEndian : true;
  2118. }
  2119. Object.assign( BinaryReader.prototype, {
  2120. getOffset: function () {
  2121. return this.offset;
  2122. },
  2123. size: function () {
  2124. return this.dv.buffer.byteLength;
  2125. },
  2126. skip: function ( length ) {
  2127. this.offset += length;
  2128. },
  2129. // seems like true/false representation depends on exporter.
  2130. // true: 1 or 'Y'(=0x59), false: 0 or 'T'(=0x54)
  2131. // then sees LSB.
  2132. getBoolean: function () {
  2133. return ( this.getUint8() & 1 ) === 1;
  2134. },
  2135. getBooleanArray: function ( size ) {
  2136. var a = [];
  2137. for ( var i = 0; i < size; i ++ ) {
  2138. a.push( this.getBoolean() );
  2139. }
  2140. return a;
  2141. },
  2142. getInt8: function () {
  2143. var value = this.dv.getInt8( this.offset );
  2144. this.offset += 1;
  2145. return value;
  2146. },
  2147. getInt8Array: function ( size ) {
  2148. var a = [];
  2149. for ( var i = 0; i < size; i ++ ) {
  2150. a.push( this.getInt8() );
  2151. }
  2152. return a;
  2153. },
  2154. getUint8: function () {
  2155. var value = this.dv.getUint8( this.offset );
  2156. this.offset += 1;
  2157. return value;
  2158. },
  2159. getUint8Array: function ( size ) {
  2160. var a = [];
  2161. for ( var i = 0; i < size; i ++ ) {
  2162. a.push( this.getUint8() );
  2163. }
  2164. return a;
  2165. },
  2166. getInt16: function () {
  2167. var value = this.dv.getInt16( this.offset, this.littleEndian );
  2168. this.offset += 2;
  2169. return value;
  2170. },
  2171. getInt16Array: function ( size ) {
  2172. var a = [];
  2173. for ( var i = 0; i < size; i ++ ) {
  2174. a.push( this.getInt16() );
  2175. }
  2176. return a;
  2177. },
  2178. getUint16: function () {
  2179. var value = this.dv.getUint16( this.offset, this.littleEndian );
  2180. this.offset += 2;
  2181. return value;
  2182. },
  2183. getUint16Array: function ( size ) {
  2184. var a = [];
  2185. for ( var i = 0; i < size; i ++ ) {
  2186. a.push( this.getUint16() );
  2187. }
  2188. return a;
  2189. },
  2190. getInt32: function () {
  2191. var value = this.dv.getInt32( this.offset, this.littleEndian );
  2192. this.offset += 4;
  2193. return value;
  2194. },
  2195. getInt32Array: function ( size ) {
  2196. var a = [];
  2197. for ( var i = 0; i < size; i ++ ) {
  2198. a.push( this.getInt32() );
  2199. }
  2200. return a;
  2201. },
  2202. getUint32: function () {
  2203. var value = this.dv.getUint32( this.offset, this.littleEndian );
  2204. this.offset += 4;
  2205. return value;
  2206. },
  2207. getUint32Array: function ( size ) {
  2208. var a = [];
  2209. for ( var i = 0; i < size; i ++ ) {
  2210. a.push( this.getUint32() );
  2211. }
  2212. return a;
  2213. },
  2214. // JavaScript doesn't support 64-bit integer so calculate this here
  2215. // 1 << 32 will return 1 so using multiply operation instead here.
  2216. // There's a possibility that this method returns wrong value if the value
  2217. // is out of the range between Number.MAX_SAFE_INTEGER and Number.MIN_SAFE_INTEGER.
  2218. // TODO: safely handle 64-bit integer
  2219. getInt64: function () {
  2220. var low, high;
  2221. if ( this.littleEndian ) {
  2222. low = this.getUint32();
  2223. high = this.getUint32();
  2224. } else {
  2225. high = this.getUint32();
  2226. low = this.getUint32();
  2227. }
  2228. // calculate negative value
  2229. if ( high & 0x80000000 ) {
  2230. high = ~ high & 0xFFFFFFFF;
  2231. low = ~ low & 0xFFFFFFFF;
  2232. if ( low === 0xFFFFFFFF ) high = ( high + 1 ) & 0xFFFFFFFF;
  2233. low = ( low + 1 ) & 0xFFFFFFFF;
  2234. return - ( high * 0x100000000 + low );
  2235. }
  2236. return high * 0x100000000 + low;
  2237. },
  2238. getInt64Array: function ( size ) {
  2239. var a = [];
  2240. for ( var i = 0; i < size; i ++ ) {
  2241. a.push( this.getInt64() );
  2242. }
  2243. return a;
  2244. },
  2245. // Note: see getInt64() comment
  2246. getUint64: function () {
  2247. var low, high;
  2248. if ( this.littleEndian ) {
  2249. low = this.getUint32();
  2250. high = this.getUint32();
  2251. } else {
  2252. high = this.getUint32();
  2253. low = this.getUint32();
  2254. }
  2255. return high * 0x100000000 + low;
  2256. },
  2257. getUint64Array: function ( size ) {
  2258. var a = [];
  2259. for ( var i = 0; i < size; i ++ ) {
  2260. a.push( this.getUint64() );
  2261. }
  2262. return a;
  2263. },
  2264. getFloat32: function () {
  2265. var value = this.dv.getFloat32( this.offset, this.littleEndian );
  2266. this.offset += 4;
  2267. return value;
  2268. },
  2269. getFloat32Array: function ( size ) {
  2270. var a = [];
  2271. for ( var i = 0; i < size; i ++ ) {
  2272. a.push( this.getFloat32() );
  2273. }
  2274. return a;
  2275. },
  2276. getFloat64: function () {
  2277. var value = this.dv.getFloat64( this.offset, this.littleEndian );
  2278. this.offset += 8;
  2279. return value;
  2280. },
  2281. getFloat64Array: function ( size ) {
  2282. var a = [];
  2283. for ( var i = 0; i < size; i ++ ) {
  2284. a.push( this.getFloat64() );
  2285. }
  2286. return a;
  2287. },
  2288. getArrayBuffer: function ( size ) {
  2289. var value = this.dv.buffer.slice( this.offset, this.offset + size );
  2290. this.offset += size;
  2291. return value;
  2292. },
  2293. getChar: function () {
  2294. return String.fromCharCode( this.getUint8() );
  2295. },
  2296. getString: function ( size ) {
  2297. var s = '';
  2298. while ( size > 0 ) {
  2299. var value = this.getUint8();
  2300. size --;
  2301. if ( value === 0 ) break;
  2302. s += String.fromCharCode( value );
  2303. }
  2304. // Manage UTF8 encoding
  2305. s = decodeURIComponent( escape( s ) );
  2306. this.skip( size );
  2307. return s;
  2308. }
  2309. } );
  2310. // FBXTree holds a representation of the FBX data, returned by the TextParser ( FBX ASCII format)
  2311. // and BinaryParser( FBX Binary format)
  2312. function FBXTree() {}
  2313. Object.assign( FBXTree.prototype, {
  2314. add: function ( key, val ) {
  2315. this[ key ] = val;
  2316. },
  2317. } );
  2318. function isFbxFormatBinary( buffer ) {
  2319. var CORRECT = 'Kaydara FBX Binary \0';
  2320. return buffer.byteLength >= CORRECT.length && CORRECT === convertArrayBufferToString( buffer, 0, CORRECT.length );
  2321. }
  2322. function isFbxFormatASCII( text ) {
  2323. var CORRECT = [ 'K', 'a', 'y', 'd', 'a', 'r', 'a', '\\', 'F', 'B', 'X', '\\', 'B', 'i', 'n', 'a', 'r', 'y', '\\', '\\' ];
  2324. var cursor = 0;
  2325. function read( offset ) {
  2326. var result = text[ offset - 1 ];
  2327. text = text.slice( cursor + offset );
  2328. cursor ++;
  2329. return result;
  2330. }
  2331. for ( var i = 0; i < CORRECT.length; ++ i ) {
  2332. var num = read( 1 );
  2333. if ( num === CORRECT[ i ] ) {
  2334. return false;
  2335. }
  2336. }
  2337. return true;
  2338. }
  2339. function getFbxVersion( text ) {
  2340. var versionRegExp = /FBXVersion: (\d+)/;
  2341. var match = text.match( versionRegExp );
  2342. if ( match ) {
  2343. var version = parseInt( match[ 1 ] );
  2344. return version;
  2345. }
  2346. throw new Error( 'THREE.FBXLoader: Cannot find the version number for the file given.' );
  2347. }
  2348. // Converts FBX ticks into real time seconds.
  2349. function convertFBXTimeToSeconds( time ) {
  2350. return time / 46186158000;
  2351. }
  2352. // Parses comma separated list of numbers and returns them an array.
  2353. // Used internally by the TextParser
  2354. function parseNumberArray( value ) {
  2355. var array = value.split( ',' );
  2356. for ( var i = 0, l = array.length; i < l; i ++ ) {
  2357. array[ i ] = parseFloat( array[ i ] );
  2358. }
  2359. return array;
  2360. }
  2361. function parseVector3( property ) {
  2362. return new THREE.Vector3().fromArray( property.value );
  2363. }
  2364. function parseColor( property ) {
  2365. var color = new THREE.Color();
  2366. if ( property.type === 'Color' ) {
  2367. return color.setScalar( property.value );
  2368. }
  2369. return color.fromArray( property.value );
  2370. }
  2371. // Converts ArrayBuffer to String.
  2372. function convertArrayBufferToString( buffer, from, to ) {
  2373. if ( from === undefined ) from = 0;
  2374. if ( to === undefined ) to = buffer.byteLength;
  2375. var array = new Uint8Array( buffer, from, to );
  2376. if ( window.TextDecoder !== undefined ) {
  2377. return new TextDecoder().decode( array );
  2378. }
  2379. var s = '';
  2380. for ( var i = 0, il = array.length; i < il; i ++ ) {
  2381. s += String.fromCharCode( array[ i ] );
  2382. }
  2383. return s;
  2384. }
  2385. function findIndex( array, func ) {
  2386. for ( var i = 0, l = array.length; i < l; i ++ ) {
  2387. if ( func( array[ i ] ) ) return i;
  2388. }
  2389. return - 1;
  2390. }
  2391. function append( a, b ) {
  2392. for ( var i = 0, j = a.length, l = b.length; i < l; i ++, j ++ ) {
  2393. a[ j ] = b[ i ];
  2394. }
  2395. }
  2396. function slice( a, b, from, to ) {
  2397. for ( var i = from, j = 0; i < to; i ++, j ++ ) {
  2398. a[ j ] = b[ i ];
  2399. }
  2400. return a;
  2401. }
  2402. } )();