FBXLoader2.js 95 KB

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