FBXLoader.js 88 KB

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