FBXLoader.js 68 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255
  1. /**
  2. * @author yamahigashi https://github.com/yamahigashi
  3. * @author Kyle-Larson https://github.com/Kyle-Larson
  4. *
  5. * This loader loads FBX file in *ASCII and version 7 format*.
  6. *
  7. * Support
  8. * - mesh
  9. * - skinning
  10. * - normal / uv
  11. * - material (Multi-Material too)
  12. * - textures (Must be in same directory)
  13. * - nurbs (Open, Closed and Periodic forms)
  14. *
  15. * No Support
  16. * - morph
  17. */
  18. ( function () {
  19. THREE.FBXLoader = function ( manager ) {
  20. THREE.Loader.call( this );
  21. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  22. this.textureLoader = null;
  23. this.textureBasePath = null;
  24. };
  25. THREE.FBXLoader.prototype = Object.create( THREE.Loader.prototype );
  26. THREE.FBXLoader.prototype.constructor = THREE.FBXLoader;
  27. Object.assign( THREE.FBXLoader.prototype, {
  28. load: function ( url, onLoad, onProgress, onError ) {
  29. var scope = this;
  30. var loader = new THREE.FileLoader( scope.manager );
  31. // loader.setCrossOrigin( this.crossOrigin );
  32. loader.load( url, function ( text ) {
  33. if ( ! scope.isFbxFormatASCII( text ) ) {
  34. console.warn( 'FBXLoader: !!! FBX Binary format not supported !!!' );
  35. } else if ( ! scope.isFbxVersionSupported( text ) ) {
  36. console.warn( 'FBXLoader: !!! FBX Version below 7 not supported !!!' );
  37. } else {
  38. scope.textureBasePath = scope.extractUrlBase( url );
  39. onLoad( scope.parse( text ) );
  40. }
  41. }, onProgress, onError );
  42. },
  43. setCrossOrigin: function ( value ) {
  44. this.crossOrigin = value;
  45. },
  46. isFbxFormatASCII: function ( body ) {
  47. var CORRECT = [ 'K', 'a', 'y', 'd', 'a', 'r', 'a', '\\', 'F', 'B', 'X', '\\', 'B', 'i', 'n', 'a', 'r', 'y', '\\', '\\' ];
  48. var cursor = 0;
  49. var read = function ( offset ) {
  50. var result = body[ offset - 1 ];
  51. body = body.slice( cursor + offset );
  52. cursor ++;
  53. return result;
  54. };
  55. for ( var i = 0; i < CORRECT.length; ++ i ) {
  56. var num = read( 1 );
  57. if ( num == CORRECT[ i ] ) {
  58. return false;
  59. }
  60. }
  61. return true;
  62. },
  63. isFbxVersionSupported: function ( body ) {
  64. var versionExp = /FBXVersion: (\d+)/;
  65. var match = body.match( versionExp );
  66. if ( match ) {
  67. var version = parseInt( match[ 1 ] );
  68. console.log( 'FBXLoader: FBX version ' + version );
  69. return version >= 7000;
  70. }
  71. return false;
  72. },
  73. parse: function ( text ) {
  74. var scope = this;
  75. console.time( 'FBXLoader' );
  76. console.time( 'FBXLoader: TextParser' );
  77. var nodes = new FBXParser().parse( text );
  78. console.timeEnd( 'FBXLoader: TextParser' );
  79. console.time( 'FBXLoader: ObjectParser' );
  80. scope.hierarchy = ( new Bones() ).parseHierarchy( nodes );
  81. scope.weights = ( new Weights() ).parse( nodes, scope.hierarchy );
  82. scope.animations = ( new Animation() ).parse( nodes, scope.hierarchy );
  83. scope.textures = ( new Textures() ).parse( nodes, scope.hierarchy );
  84. scope.materials = ( new Materials() ).parse( nodes, scope.hierarchy );
  85. scope.geometries = ( new Geometries() ).parse( nodes, scope.hierarchy );
  86. console.timeEnd( 'FBXLoader: ObjectParser' );
  87. this.texture_cache = {};
  88. this.material_cache = {};
  89. this.geometry_cache = {};
  90. console.time( 'FBXLoader: MeshParser' );
  91. var meshes = this.parseMeshes( nodes );
  92. console.timeEnd( 'FBXLoader: MeshParser' );
  93. var container = new THREE.Group();
  94. for ( var i = 0; i < meshes.length; ++ i ) {
  95. if ( meshes[ i ] === undefined ) {
  96. continue;
  97. }
  98. container.add( meshes[ i ] );
  99. //wireframe = new THREE.WireframeHelper( geometries[i], 0x00ff00 );
  100. //container.add( wireframe );
  101. //vnh = new THREE.VertexNormalsHelper( geometries[i], 0.6 );
  102. //container.add( vnh );
  103. //skh = new THREE.SkeletonHelper( geometries[i] );
  104. //container.add( skh );
  105. // container.add( new THREE.BoxHelper( geometries[i] ) );
  106. }
  107. console.timeEnd( 'FBXLoader' );
  108. return container;
  109. },
  110. getTexture: function ( texNode ) {
  111. if ( ! ( texNode.id in this.texture_cache ) ) {
  112. if ( this.textureLoader === null ) {
  113. this.textureLoader = new THREE.TextureLoader();
  114. }
  115. this.texture_cache[ texNode.id ] = this.textureLoader.load( this.textureBasePath + '/' + texNode.fileName );
  116. }
  117. return this.texture_cache[ texNode.id ];
  118. },
  119. getMaterial: function ( matNode, nodes ) {
  120. if ( ! ( matNode.id in this.material_cache ) ) {
  121. // TODO:
  122. // Cannot find a list of possible ShadingModel values.
  123. // If someone finds a list, please add additional cases
  124. // and map to appropriate materials.
  125. var tmpMat;
  126. switch ( matNode.type ) {
  127. case "phong":
  128. tmpMat = new THREE.MeshPhongMaterial();
  129. break;
  130. case "lambert":
  131. tmpMat = new THREE.MeshLambertMaterial();
  132. break;
  133. default:
  134. console.warn( "No implementation given for material type " + matNode.type + " in FBXLoader.js. Defaulting to basic material" );
  135. tmpMat = new THREE.MeshBasicMaterial( { color: 0x3300ff } );
  136. break;
  137. }
  138. var children = nodes.searchConnectionChildren( matNode.id );
  139. for ( var i = 0; i < children.length; ++ i ) {
  140. var type = nodes.searchConnectionType( children[ i ], matNode.id );
  141. switch ( type ) {
  142. case " \"AmbientColor":
  143. //TODO: Support AmbientColor textures
  144. break;
  145. case " \"DiffuseColor":
  146. matNode.parameters.map = this.getTexture( this.textures.textures[ children[ i ] ] );
  147. break;
  148. default:
  149. console.warn( 'Unknown texture application of type ' + type + ', skipping texture' );
  150. break;
  151. }
  152. }
  153. tmpMat.setValues( matNode.parameters );
  154. this.material_cache[ matNode.id ] = tmpMat;
  155. }
  156. return this.material_cache[ matNode.id ];
  157. },
  158. getGeometry: function ( geoNode ) {
  159. if ( ! ( geoNode.id in this.geometry_cache ) ) {
  160. var tmpGeo = new THREE.BufferGeometry();
  161. tmpGeo.name = geoNode.name;
  162. tmpGeo.addAttribute( 'position', new THREE.BufferAttribute( new Float32Array( geoNode.vertices ), 3 ) );
  163. if ( geoNode.normals !== undefined && geoNode.normals.length > 0 ) {
  164. tmpGeo.addAttribute( 'normal', new THREE.BufferAttribute( new Float32Array( geoNode.normals ), 3 ) );
  165. }
  166. if ( geoNode.uvs !== undefined && geoNode.uvs.length > 0 ) {
  167. tmpGeo.addAttribute( 'uv', new THREE.BufferAttribute( new Float32Array( geoNode.uvs ), 2 ) );
  168. }
  169. if ( geoNode.indices !== undefined && geoNode.indices.length > 0 ) {
  170. tmpGeo.setIndex( geoNode.indices );
  171. }
  172. tmpGeo.verticesNeedUpdate = true;
  173. tmpGeo.computeBoundingSphere();
  174. tmpGeo.computeBoundingBox();
  175. //Material groupings
  176. if ( geoNode.materialIndices.length > 1 ) {
  177. tmpGeo.groups = [];
  178. for ( var i = 0, prevIndex = - 1; i < geoNode.materialIndices.length; ++ i ) {
  179. if ( geoNode.materialIndices[ i ] !== prevIndex ) {
  180. tmpGeo.groups.push( { start: i * 3, count: 0, materialIndex: geoNode.materialIndices[ i ] } );
  181. prevIndex = geoNode.materialIndices[ i ];
  182. }
  183. tmpGeo.groups[ tmpGeo.groups.length - 1 ].count += 3;
  184. }
  185. }
  186. this.geometry_cache[ geoNode.id ] = new THREE.Geometry().fromBufferGeometry( tmpGeo );
  187. this.geometry_cache[ geoNode.id ].bones = geoNode.bones;
  188. this.geometry_cache[ geoNode.id ].skinIndices = this.weights.skinIndices;
  189. this.geometry_cache[ geoNode.id ].skinWeights = this.weights.skinWeights;
  190. }
  191. return this.geometry_cache[ geoNode.id ];
  192. },
  193. parseMeshes: function ( node ) {
  194. var modelNode = node.Objects.subNodes.Model;
  195. var meshes = [];
  196. for ( var ID in modelNode ) {
  197. if ( modelNode[ ID ].attrType === 'Mesh' ) {
  198. //Parse Mesh
  199. meshes.push( this.parseMesh( modelNode[ ID ], node ) );
  200. } else if ( modelNode[ ID ].attrType === 'NurbsCurve' ) {
  201. //Parse NURBS
  202. meshes.push( this.parseNURBS( modelNode[ ID ], node ) );
  203. }
  204. }
  205. return meshes;
  206. },
  207. parseFloatList: function ( floatList ) {
  208. return floatList.split( ',' ).map( function ( number ) {
  209. return parseFloat( number );
  210. } );
  211. },
  212. parseNURBS: function ( meshNode, FBXNodes ) {
  213. if ( THREE.NURBSCurve === undefined ) {
  214. console.error( "THREE.FBXLoader relies on THREE.NURBSCurve" );
  215. return;
  216. }
  217. var geoNodes = FBXNodes.Objects.subNodes.Geometry;
  218. var children = FBXNodes.searchConnectionChildren( meshNode.id );
  219. var nurbsInfo;
  220. for ( var i = 0; i < children.length; ++ i ) {
  221. if ( children[ i ] in geoNodes ) {
  222. nurbsInfo = geoNodes[ children[ i ] ];
  223. break;
  224. }
  225. }
  226. if ( nurbsInfo === undefined ) {
  227. return;
  228. }
  229. var order = parseInt( nurbsInfo.properties.Order );
  230. if ( isNaN( order ) ) {
  231. console.error( "Invalid Order: `" + nurbsInfo.properties.Order + "` (should be an integer)" );
  232. return;
  233. }
  234. var degree = order - 1;
  235. var knots = this.parseFloatList( nurbsInfo.subNodes.KnotVector.properties.a );
  236. var controlPoints = [];
  237. var pointsValues = this.parseFloatList( nurbsInfo.subNodes.Points.properties.a );
  238. for ( var i = 0; i < pointsValues.length; i += 4 ) {
  239. // NURBSCurve recreates a Vector4, so no need to construct it twice
  240. controlPoints.push( { x: pointsValues[ i ], y: pointsValues[ i + 1 ], z: pointsValues[ i + 2 ], w: pointsValues[ i + 3 ] } );
  241. }
  242. var startKnot, endKnot;
  243. if ( nurbsInfo.properties.Form == "Closed" ) {
  244. controlPoints.push( controlPoints[ 0 ] );
  245. } else if ( nurbsInfo.properties.Form === 'Periodic' ) {
  246. startKnot = degree;
  247. endKnot = knots.length - 1 - startKnot;
  248. for ( var i = 0; i < degree; ++ i ) {
  249. controlPoints.push( controlPoints[ i ] );
  250. }
  251. }
  252. var curve = new THREE.NURBSCurve( degree, knots, controlPoints, startKnot, endKnot );
  253. // Pre-generate a geometry
  254. var geometry = new THREE.Geometry();
  255. geometry.vertices = curve.getPoints( controlPoints.length * 7 );
  256. var mesh = new THREE.Line( geometry );
  257. // Store the THREE.NURBSCurve class so the user can recreate a new geometry with a different number of points
  258. mesh.userData.curve = curve;
  259. return mesh;
  260. },
  261. parseMesh: function ( meshNode, FBXNodes ) {
  262. var geoNodes = FBXNodes.Objects.subNodes.Geometry;
  263. var matNodes = FBXNodes.Objects.subNodes.Material;
  264. var children = FBXNodes.searchConnectionChildren( meshNode.id );
  265. var geometry;
  266. var materials = [];
  267. var material;
  268. var mesh;
  269. for ( var i = 0; i < children.length; ++ i ) {
  270. if ( children[ i ] in geoNodes ) {
  271. geometry = this.getGeometry( this.geometries.geometries[ children[ i ] ] );
  272. continue;
  273. }
  274. if ( children[ i ] in matNodes ) {
  275. materials.push( this.getMaterial( this.materials.materials[ children[ i ] ], FBXNodes ) );
  276. continue;
  277. }
  278. }
  279. if ( materials.length > 1 ) {
  280. material = new THREE.MultiMaterial( materials );
  281. //material = materials[ 0 ];
  282. } else {
  283. material = materials[ 0 ];
  284. }
  285. if ( geometry.bones !== undefined && geometry.skinWeights !== undefined && geometry.skinWeights.length > 0 ) {
  286. if ( material instanceof THREE.MultiMaterial ) {
  287. for ( var i = 0; i < material.materials.length; ++ i ) {
  288. material.materials[ i ].skinning = true;
  289. }
  290. } else {
  291. material.skinning = true;
  292. }
  293. mesh = new THREE.SkinnedMesh( geometry, material );
  294. } else {
  295. mesh = new THREE.Mesh( geometry, material );
  296. }
  297. if ( this.animations !== undefined ) {
  298. this.addAnimation( mesh, this.weights.matrices, this.animations );
  299. }
  300. return mesh;
  301. },
  302. addAnimation: function ( mesh, matrices, animations ) {
  303. for ( var key in animations.stacks ) {
  304. var animationData = {
  305. name: animations.stacks[ key ].name,
  306. fps: 30,
  307. length: animations.stacks[ key ].length,
  308. hierarchy: []
  309. };
  310. for ( var i = 0; i < mesh.geometry.bones.length; ++ i ) {
  311. var name = mesh.geometry.bones[ i ].name;
  312. name = name.replace( /.*:/, '' );
  313. animationData.hierarchy.push( { parent: mesh.geometry.bones[ i ].parent, name: name, keys: [] } );
  314. }
  315. function hasCurve( animNode, attr ) {
  316. if ( animNode === undefined ) {
  317. return false;
  318. }
  319. var attrNode;
  320. switch ( attr ) {
  321. case 'S':
  322. if ( ! ( animNode.S ) ) {
  323. return false;
  324. }
  325. attrNode = animNode.S;
  326. break;
  327. case 'R':
  328. if ( ! ( animNode.R ) ) {
  329. return false;
  330. }
  331. attrNode = animNode.R;
  332. break;
  333. case 'T':
  334. if ( ! ( animNode.T ) ) {
  335. return false;
  336. }
  337. attrNode = animNode.T;
  338. break;
  339. }
  340. if ( attrNode.curves.x === undefined ) {
  341. return false;
  342. }
  343. if ( attrNode.curves.y === undefined ) {
  344. return false;
  345. }
  346. if ( attrNode.curves.z === undefined ) {
  347. return false;
  348. }
  349. return true;
  350. }
  351. function hasKeyOnFrame( attrNode, frame ) {
  352. var x = isKeyExistOnFrame( attrNode.curves.x, frame );
  353. var y = isKeyExistOnFrame( attrNode.curves.y, frame );
  354. var z = isKeyExistOnFrame( attrNode.curves.z, frame );
  355. return x && y && z;
  356. }
  357. function isKeyExistOnFrame( curve, frame ) {
  358. var value = curve.values[ frame ];
  359. return value !== undefined;
  360. }
  361. function genKey( animNode, bone ) {
  362. // key initialize with its bone's bind pose at first
  363. var key = {};
  364. key.time = frame / animations.fps; // TODO:
  365. key.pos = bone.pos;
  366. key.rot = bone.rotq;
  367. key.scl = bone.scl;
  368. if ( animNode === undefined ) {
  369. return key;
  370. }
  371. try {
  372. if ( hasCurve( animNode, 'T' ) && hasKeyOnFrame( animNode.T, frame ) ) {
  373. var pos = new THREE.Vector3(
  374. animNode.T.curves.x.values[ frame ],
  375. animNode.T.curves.y.values[ frame ],
  376. animNode.T.curves.z.values[ frame ] );
  377. key.pos = [ pos.x, pos.y, pos.z ];
  378. }
  379. if ( hasCurve( animNode, 'R' ) && hasKeyOnFrame( animNode.R, frame ) ) {
  380. var rx = degToRad( animNode.R.curves.x.values[ frame ] );
  381. var ry = degToRad( animNode.R.curves.y.values[ frame ] );
  382. var rz = degToRad( animNode.R.curves.z.values[ frame ] );
  383. var eul = new THREE.Vector3( rx, ry, rz );
  384. var rot = quatFromVec( eul.x, eul.y, eul.z );
  385. key.rot = [ rot.x, rot.y, rot.z, rot.w ];
  386. }
  387. if ( hasCurve( animNode, 'S' ) && hasKeyOnFrame( animNode.S, frame ) ) {
  388. var scl = new THREE.Vector3(
  389. animNode.S.curves.x.values[ frame ],
  390. animNode.S.curves.y.values[ frame ],
  391. animNode.S.curves.z.values[ frame ] );
  392. key.scl = [ scl.x, scl.y, scl.z ];
  393. }
  394. } catch ( e ) {
  395. // curve is not full plotted
  396. console.log( bone );
  397. console.log( e );
  398. }
  399. return key;
  400. }
  401. var bones = mesh.geometry.bones;
  402. for ( var frame = 0; frame < animations.stacks[ key ].frames; frame ++ ) {
  403. for ( i = 0; i < bones.length; i ++ ) {
  404. var bone = bones[ i ];
  405. var animNode = animations.stacks[ key ].layers[ 0 ][ i ];
  406. for ( var j = 0; j < animationData.hierarchy.length; j ++ ) {
  407. if ( animationData.hierarchy[ j ].name === bone.name ) {
  408. animationData.hierarchy[ j ].keys.push( genKey( animNode, bone ) );
  409. }
  410. }
  411. }
  412. }
  413. if ( mesh.geometry.animations === undefined ) {
  414. mesh.geometry.animations = [];
  415. }
  416. mesh.geometry.animations.push( THREE.AnimationClip.parseAnimation( animationData, mesh.geometry.bones ) );
  417. }
  418. },
  419. loadFile: function ( url, onLoad, onProgress, onError, responseType ) {
  420. var loader = new THREE.FileLoader( this.manager );
  421. loader.setResponseType( responseType );
  422. var request = loader.load( url, onLoad, onProgress, onError );
  423. return request;
  424. },
  425. loadFileAsBuffer: function ( url, onLoad, onProgress, onError ) {
  426. this.loadFile( url, onLoad, onProgress, onError, 'arraybuffer' );
  427. },
  428. loadFileAsText: function ( url, onLoad, onProgress, onError ) {
  429. this.loadFile( url, onLoad, onProgress, onError, 'text' );
  430. }
  431. } );
  432. /* ----------------------------------------------------------------- */
  433. function FBXNodes() {}
  434. Object.assign( FBXNodes.prototype, {
  435. add: function ( key, val ) {
  436. this[ key ] = val;
  437. },
  438. searchConnectionParent: function ( id ) {
  439. if ( this.__cache_search_connection_parent === undefined ) {
  440. this.__cache_search_connection_parent = [];
  441. }
  442. if ( this.__cache_search_connection_parent[ id ] !== undefined ) {
  443. return this.__cache_search_connection_parent[ id ];
  444. } else {
  445. this.__cache_search_connection_parent[ id ] = [];
  446. }
  447. var conns = this.Connections.properties.connections;
  448. var results = [];
  449. for ( var i = 0; i < conns.length; ++ i ) {
  450. if ( conns[ i ][ 0 ] == id ) {
  451. // 0 means scene root
  452. var res = conns[ i ][ 1 ] === 0 ? - 1 : conns[ i ][ 1 ];
  453. results.push( res );
  454. }
  455. }
  456. if ( results.length > 0 ) {
  457. this.__cache_search_connection_parent[ id ] = this.__cache_search_connection_parent[ id ].concat( results );
  458. return results;
  459. } else {
  460. this.__cache_search_connection_parent[ id ] = [ - 1 ];
  461. return [ - 1 ];
  462. }
  463. },
  464. searchConnectionChildren: function ( id ) {
  465. if ( this.__cache_search_connection_children === undefined ) {
  466. this.__cache_search_connection_children = [];
  467. }
  468. if ( this.__cache_search_connection_children[ id ] !== undefined ) {
  469. return this.__cache_search_connection_children[ id ];
  470. } else {
  471. this.__cache_search_connection_children[ id ] = [];
  472. }
  473. var conns = this.Connections.properties.connections;
  474. var res = [];
  475. for ( var i = 0; i < conns.length; ++ i ) {
  476. if ( conns[ i ][ 1 ] == id ) {
  477. // 0 means scene root
  478. res.push( conns[ i ][ 0 ] === 0 ? - 1 : conns[ i ][ 0 ] );
  479. // there may more than one kid, then search to the end
  480. }
  481. }
  482. if ( res.length > 0 ) {
  483. this.__cache_search_connection_children[ id ] = this.__cache_search_connection_children[ id ].concat( res );
  484. return res;
  485. } else {
  486. this.__cache_search_connection_children[ id ] = [ ];
  487. return [ ];
  488. }
  489. },
  490. searchConnectionType: function ( id, to ) {
  491. var key = id + ',' + to; // TODO: to hash
  492. if ( this.__cache_search_connection_type === undefined ) {
  493. this.__cache_search_connection_type = {};
  494. }
  495. if ( this.__cache_search_connection_type[ key ] !== undefined ) {
  496. return this.__cache_search_connection_type[ key ];
  497. } else {
  498. this.__cache_search_connection_type[ key ] = '';
  499. }
  500. var conns = this.Connections.properties.connections;
  501. for ( var i = 0; i < conns.length; ++ i ) {
  502. if ( conns[ i ][ 0 ] == id && conns[ i ][ 1 ] == to ) {
  503. // 0 means scene root
  504. this.__cache_search_connection_type[ key ] = conns[ i ][ 2 ];
  505. return conns[ i ][ 2 ];
  506. }
  507. }
  508. this.__cache_search_connection_type[ id ] = null;
  509. return null;
  510. }
  511. } );
  512. function FBXParser() {}
  513. Object.assign( FBXParser.prototype, {
  514. getPrevNode: function () {
  515. return this.nodeStack[ this.currentIndent - 2 ];
  516. },
  517. getCurrentNode: function () {
  518. return this.nodeStack[ this.currentIndent - 1 ];
  519. },
  520. getCurrentProp: function () {
  521. return this.currentProp;
  522. },
  523. pushStack: function ( node ) {
  524. this.nodeStack.push( node );
  525. this.currentIndent += 1;
  526. },
  527. popStack: function () {
  528. this.nodeStack.pop();
  529. this.currentIndent -= 1;
  530. },
  531. setCurrentProp: function ( val, name ) {
  532. this.currentProp = val;
  533. this.currentPropName = name;
  534. },
  535. // ----------parse ---------------------------------------------------
  536. parse: function ( text ) {
  537. this.currentIndent = 0;
  538. this.allNodes = new FBXNodes();
  539. this.nodeStack = [];
  540. this.currentProp = [];
  541. this.currentPropName = '';
  542. var split = text.split( "\n" );
  543. for ( var line in split ) {
  544. var l = split[ line ];
  545. // short cut
  546. if ( l.match( /^[\s\t]*;/ ) ) {
  547. continue;
  548. } // skip comment line
  549. if ( l.match( /^[\s\t]*$/ ) ) {
  550. continue;
  551. } // skip empty line
  552. // beginning of node
  553. var beginningOfNodeExp = new RegExp( "^\\t{" + this.currentIndent + "}(\\w+):(.*){", '' );
  554. var match = l.match( beginningOfNodeExp );
  555. if ( match ) {
  556. var nodeName = match[ 1 ].trim().replace( /^"/, '' ).replace( /"$/, "" );
  557. var nodeAttrs = match[ 2 ].split( ',' ).map( function ( element ) {
  558. return element.trim().replace( /^"/, '' ).replace( /"$/, '' );
  559. } );
  560. this.parseNodeBegin( l, nodeName, nodeAttrs || null );
  561. continue;
  562. }
  563. // node's property
  564. var propExp = new RegExp( "^\\t{" + ( this.currentIndent ) + "}(\\w+):[\\s\\t\\r\\n](.*)" );
  565. var match = l.match( propExp );
  566. if ( match ) {
  567. var propName = match[ 1 ].replace( /^"/, '' ).replace( /"$/, "" ).trim();
  568. var propValue = match[ 2 ].replace( /^"/, '' ).replace( /"$/, "" ).trim();
  569. this.parseNodeProperty( l, propName, propValue );
  570. continue;
  571. }
  572. // end of node
  573. var endOfNodeExp = new RegExp( "^\\t{" + ( this.currentIndent - 1 ) + "}}" );
  574. if ( l.match( endOfNodeExp ) ) {
  575. this.nodeEnd();
  576. continue;
  577. }
  578. // for special case,
  579. //
  580. // Vertices: *8670 {
  581. // a: 0.0356229953467846,13.9599733352661,-0.399196773.....(snip)
  582. // -0.0612030513584614,13.960485458374,-0.409748703241348,-0.10.....
  583. // 0.12490539252758,13.7450733184814,-0.454119384288788,0.09272.....
  584. // 0.0836158767342567,13.5432004928589,-0.435397416353226,0.028.....
  585. //
  586. // these case the lines must contiue with previous line
  587. if ( l.match( /^[^\s\t}]/ ) ) {
  588. this.parseNodePropertyContinued( l );
  589. }
  590. }
  591. return this.allNodes;
  592. },
  593. parseNodeBegin: function ( line, nodeName, nodeAttrs ) {
  594. // var nodeName = match[1];
  595. var node = { 'name': nodeName, properties: {}, 'subNodes': {} };
  596. var attrs = this.parseNodeAttr( nodeAttrs );
  597. var currentNode = this.getCurrentNode();
  598. // a top node
  599. if ( this.currentIndent === 0 ) {
  600. this.allNodes.add( nodeName, node );
  601. } else {
  602. // a subnode
  603. // already exists subnode, then append it
  604. if ( nodeName in currentNode.subNodes ) {
  605. var tmp = currentNode.subNodes[ nodeName ];
  606. // console.log( "duped entry found\nkey: " + nodeName + "\nvalue: " + propValue );
  607. if ( this.isFlattenNode( currentNode.subNodes[ nodeName ] ) ) {
  608. if ( attrs.id === '' ) {
  609. currentNode.subNodes[ nodeName ] = [];
  610. currentNode.subNodes[ nodeName ].push( tmp );
  611. } else {
  612. currentNode.subNodes[ nodeName ] = {};
  613. currentNode.subNodes[ nodeName ][ tmp.id ] = tmp;
  614. }
  615. }
  616. if ( attrs.id === '' ) {
  617. currentNode.subNodes[ nodeName ].push( node );
  618. } else {
  619. currentNode.subNodes[ nodeName ][ attrs.id ] = node;
  620. }
  621. } else if ( typeof attrs.id === 'number' || attrs.id.match( /^\d+$/ ) ) {
  622. currentNode.subNodes[ nodeName ] = {};
  623. currentNode.subNodes[ nodeName ][ attrs.id ] = node;
  624. } else {
  625. currentNode.subNodes[ nodeName ] = node;
  626. }
  627. }
  628. // for this ↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓
  629. // NodeAttribute: 1001463072, "NodeAttribute::", "LimbNode" {
  630. if ( nodeAttrs ) {
  631. node.id = attrs.id;
  632. node.attrName = attrs.name;
  633. node.attrType = attrs.type;
  634. }
  635. this.pushStack( node );
  636. },
  637. parseNodeAttr: function ( attrs ) {
  638. var id = attrs[ 0 ];
  639. if ( attrs[ 0 ] !== "" ) {
  640. id = parseInt( attrs[ 0 ] );
  641. if ( isNaN( id ) ) {
  642. // PolygonVertexIndex: *16380 {
  643. id = attrs[ 0 ];
  644. }
  645. }
  646. var name;
  647. var type;
  648. if ( attrs.length > 1 ) {
  649. name = attrs[ 1 ].replace( /^(\w+)::/, '' );
  650. type = attrs[ 2 ];
  651. }
  652. return { id: id, name: name || '', type: type || '' };
  653. },
  654. parseNodeProperty: function ( line, propName, propValue ) {
  655. var currentNode = this.getCurrentNode();
  656. var parentName = currentNode.name;
  657. // special case parent node's is like "Properties70"
  658. // these chilren nodes must treat with careful
  659. if ( parentName !== undefined ) {
  660. var propMatch = parentName.match( /Properties(\d)+/ );
  661. if ( propMatch ) {
  662. this.parseNodeSpecialProperty( line, propName, propValue );
  663. return;
  664. }
  665. }
  666. // special case Connections
  667. if ( propName == 'C' ) {
  668. var connProps = propValue.split( ',' ).slice( 1 );
  669. var from = parseInt( connProps[ 0 ] );
  670. var to = parseInt( connProps[ 1 ] );
  671. var rest = propValue.split( ',' ).slice( 3 );
  672. propName = 'connections';
  673. propValue = [ from, to ];
  674. propValue = propValue.concat( rest );
  675. if ( currentNode.properties[ propName ] === undefined ) {
  676. currentNode.properties[ propName ] = [];
  677. }
  678. }
  679. // special case Connections
  680. if ( propName == 'Node' ) {
  681. var id = parseInt( propValue );
  682. currentNode.properties.id = id;
  683. currentNode.id = id;
  684. }
  685. // already exists in properties, then append this
  686. if ( propName in currentNode.properties ) {
  687. // console.log( "duped entry found\nkey: " + propName + "\nvalue: " + propValue );
  688. if ( Array.isArray( currentNode.properties[ propName ] ) ) {
  689. currentNode.properties[ propName ].push( propValue );
  690. } else {
  691. currentNode.properties[ propName ] += propValue;
  692. }
  693. } else {
  694. // console.log( propName + ": " + propValue );
  695. if ( Array.isArray( currentNode.properties[ propName ] ) ) {
  696. currentNode.properties[ propName ].push( propValue );
  697. } else {
  698. currentNode.properties[ propName ] = propValue;
  699. }
  700. }
  701. this.setCurrentProp( currentNode.properties, propName );
  702. },
  703. // TODO:
  704. parseNodePropertyContinued: function ( line ) {
  705. this.currentProp[ this.currentPropName ] += line;
  706. },
  707. parseNodeSpecialProperty: function ( line, propName, propValue ) {
  708. // split this
  709. // P: "Lcl Scaling", "Lcl Scaling", "", "A",1,1,1
  710. // into array like below
  711. // ["Lcl Scaling", "Lcl Scaling", "", "A", "1,1,1" ]
  712. var props = propValue.split( '",' ).map( function ( element ) {
  713. return element.trim().replace( /^\"/, '' ).replace( /\s/, '_' );
  714. } );
  715. var innerPropName = props[ 0 ];
  716. var innerPropType1 = props[ 1 ];
  717. var innerPropType2 = props[ 2 ];
  718. var innerPropFlag = props[ 3 ];
  719. var innerPropValue = props[ 4 ];
  720. /*
  721. if ( innerPropValue === undefined ) {
  722. innerPropValue = props[3];
  723. }
  724. */
  725. // cast value in its type
  726. switch ( innerPropType1 ) {
  727. case "int":
  728. innerPropValue = parseInt( innerPropValue );
  729. break;
  730. case "double":
  731. innerPropValue = parseFloat( innerPropValue );
  732. break;
  733. case "ColorRGB":
  734. case "Vector3D":
  735. var tmp = innerPropValue.split( ',' );
  736. innerPropValue = new THREE.Vector3( tmp[ 0 ], tmp[ 1 ], tmp[ 2 ] );
  737. break;
  738. }
  739. // CAUTION: these props must append to parent's parent
  740. this.getPrevNode().properties[ innerPropName ] = {
  741. 'type': innerPropType1,
  742. 'type2': innerPropType2,
  743. 'flag': innerPropFlag,
  744. 'value': innerPropValue
  745. };
  746. this.setCurrentProp( this.getPrevNode().properties, innerPropName );
  747. },
  748. nodeEnd: function () {
  749. this.popStack();
  750. },
  751. /* ---------------------------------------------------------------- */
  752. /* util */
  753. isFlattenNode: function ( node ) {
  754. return ( 'subNodes' in node && 'properties' in node ) ? true : false;
  755. }
  756. } );
  757. // generate skinIndices, skinWeights
  758. // @skinIndices: per vertex data, this represents the bone indexes affects that vertex
  759. // @skinWeights: per vertex data, this represents the Weight Values affects that vertex
  760. // @matrices: per `bones` data
  761. function Weights() {
  762. this.skinIndices = [];
  763. this.skinWeights = [];
  764. this.matrices = [];
  765. }
  766. Weights.prototype.parseCluster = function ( node, id, entry ) {
  767. var _p = node.searchConnectionParent( id );
  768. var _indices = parseArrayToInt( entry.subNodes.Indexes.properties.a );
  769. var _weights = parseArrayToFloat( entry.subNodes.Weights.properties.a );
  770. var _transform = parseArrayToMatrix( entry.subNodes.Transform.properties.a );
  771. var _link = parseArrayToMatrix( entry.subNodes.TransformLink.properties.a );
  772. return {
  773. 'parent': _p,
  774. 'id': parseInt( id ),
  775. 'indices': _indices,
  776. 'weights': _weights,
  777. 'transform': _transform,
  778. 'transformlink': _link,
  779. 'linkMode': entry.properties.Mode
  780. };
  781. };
  782. Weights.prototype.parse = function ( node, bones ) {
  783. this.skinIndices = [];
  784. this.skinWeights = [];
  785. this.matrices = [];
  786. var deformers = node.Objects.subNodes.Deformer;
  787. var clusters = {};
  788. for ( var id in deformers ) {
  789. if ( deformers[ id ].attrType === 'Cluster' ) {
  790. if ( ! ( 'Indexes' in deformers[ id ].subNodes ) ) {
  791. continue;
  792. }
  793. //clusters.push( this.parseCluster( node, id, deformers[id] ) );
  794. var cluster = this.parseCluster( node, id, deformers[ id ] );
  795. var boneId = node.searchConnectionChildren( cluster.id )[ 0 ];
  796. clusters[ boneId ] = cluster;
  797. }
  798. }
  799. // this clusters is per Bone data, thus we make this into per vertex data
  800. var weights = [];
  801. var hi = bones.hierarchy;
  802. for ( var b = 0; b < hi.length; ++ b ) {
  803. var bid = hi[ b ].internalId;
  804. if ( clusters[ bid ] === undefined ) {
  805. //console.log( bid );
  806. this.matrices.push( new THREE.Matrix4() );
  807. continue;
  808. }
  809. var clst = clusters[ bid ];
  810. // store transform matrix per bones
  811. this.matrices.push( clst.transform );
  812. //this.matrices.push( clst.transformlink );
  813. for ( var v = 0; v < clst.indices.length; ++ v ) {
  814. if ( weights[ clst.indices[ v ] ] === undefined ) {
  815. weights[ clst.indices[ v ] ] = {};
  816. weights[ clst.indices[ v ] ].joint = [];
  817. weights[ clst.indices[ v ] ].weight = [];
  818. }
  819. // indices
  820. var affect = node.searchConnectionChildren( clst.id );
  821. if ( affect.length > 1 ) {
  822. console.warn( "FBXLoader: node " + clst.id + " have many weight kids: " + affect );
  823. }
  824. weights[ clst.indices[ v ] ].joint.push( bones.getBoneIdfromInternalId( node, affect[ 0 ] ) );
  825. // weight value
  826. weights[ clst.indices[ v ] ].weight.push( clst.weights[ v ] );
  827. }
  828. }
  829. // normalize the skin weights
  830. // TODO - this might be a good place to choose greatest 4 weights
  831. for ( var i = 0; i < weights.length; i ++ ) {
  832. if ( weights[ i ] === undefined ) {
  833. this.skinIndices.push( new THREE.Vector4( 0, 0, 0, 0 ) );
  834. this.skinWeights.push( new THREE.Vector4( 0, 0, 0, 0 ) );
  835. continue;
  836. }
  837. var indicies = new THREE.Vector4(
  838. weights[ i ].joint[ 0 ] ? weights[ i ].joint[ 0 ] : 0,
  839. weights[ i ].joint[ 1 ] ? weights[ i ].joint[ 1 ] : 0,
  840. weights[ i ].joint[ 2 ] ? weights[ i ].joint[ 2 ] : 0,
  841. weights[ i ].joint[ 3 ] ? weights[ i ].joint[ 3 ] : 0 );
  842. var weight = new THREE.Vector4(
  843. weights[ i ].weight[ 0 ] ? weights[ i ].weight[ 0 ] : 0,
  844. weights[ i ].weight[ 1 ] ? weights[ i ].weight[ 1 ] : 0,
  845. weights[ i ].weight[ 2 ] ? weights[ i ].weight[ 2 ] : 0,
  846. weights[ i ].weight[ 3 ] ? weights[ i ].weight[ 3 ] : 0 );
  847. this.skinIndices.push( indicies );
  848. this.skinWeights.push( weight );
  849. }
  850. //console.log( this );
  851. return this;
  852. };
  853. function Bones() {
  854. // returns bones hierarchy tree.
  855. // [
  856. // {
  857. // "parent": id,
  858. // "name": name,
  859. // "pos": pos,
  860. // "rotq": quat
  861. // },
  862. // ...
  863. // {},
  864. // ...
  865. // ]
  866. //
  867. /* sample response
  868. "bones" : [
  869. {"parent":-1, "name":"Fbx01", "pos":[-0.002, 98.739, 1.6e-05], "rotq":[0, 0, 0, 1]},
  870. {"parent":0, "name":"Fbx01_Pelvis", "pos":[0.00015963, 0, 7.33107e-08], "rotq":[0, 0, 0, 1]},
  871. {"parent":1, "name":"Fbx01_Spine", "pos":[6.577e-06, 10.216, 0.0106811], "rotq":[0, 0, 0, 1]},
  872. {"parent":2, "name":"Fbx01_R_Thigh", "pos":[14.6537, -10.216, -0.00918758], "rotq":[0, 0, 0, 1]},
  873. {"parent":3, "name":"Fbx01_R_Calf", "pos":[-3.70047, -42.9681, -7.78158], "rotq":[0, 0, 0, 1]},
  874. {"parent":4, "name":"Fbx01_R_Foot", "pos":[-2.0696, -46.0488, 9.42052], "rotq":[0, 0, 0, 1]},
  875. {"parent":5, "name":"Fbx01_R_Toe0", "pos":[-0.0234785, -9.46233, -15.3187], "rotq":[0, 0, 0, 1]},
  876. {"parent":2, "name":"Fbx01_L_Thigh", "pos":[-14.6537, -10.216, -0.00918314], "rotq":[0, 0, 0, 1]},
  877. {"parent":7, "name":"Fbx01_L_Calf", "pos":[3.70037, -42.968, -7.78155], "rotq":[0, 0, 0, 1]},
  878. {"parent":8, "name":"Fbx01_L_Foot", "pos":[2.06954, -46.0488, 9.42052], "rotq":[0, 0, 0, 1]},
  879. {"parent":9, "name":"Fbx01_L_Toe0", "pos":[0.0234566, -9.46235, -15.3187], "rotq":[0, 0, 0, 1]},
  880. {"parent":2, "name":"Fbx01_Spine1", "pos":[-2.97523e-05, 11.5892, -9.81027e-05], "rotq":[0, 0, 0, 1]},
  881. {"parent":11, "name":"Fbx01_Spine2", "pos":[-2.91292e-05, 11.4685, 8.27126e-05], "rotq":[0, 0, 0, 1]},
  882. {"parent":12, "name":"Fbx01_Spine3", "pos":[-4.48857e-05, 11.5783, 8.35108e-05], "rotq":[0, 0, 0, 1]},
  883. {"parent":13, "name":"Fbx01_Neck", "pos":[1.22987e-05, 11.5582, -0.0044775], "rotq":[0, 0, 0, 1]},
  884. {"parent":14, "name":"Fbx01_Head", "pos":[-3.50709e-05, 6.62915, -0.00523254], "rotq":[0, 0, 0, 1]},
  885. {"parent":15, "name":"Fbx01_R_Eye", "pos":[3.31681, 12.739, -10.5267], "rotq":[0, 0, 0, 1]},
  886. {"parent":15, "name":"Fbx01_L_Eye", "pos":[-3.32038, 12.7391, -10.5267], "rotq":[0, 0, 0, 1]},
  887. {"parent":15, "name":"Jaw", "pos":[-0.0017738, 7.43481, -4.08114], "rotq":[0, 0, 0, 1]},
  888. {"parent":14, "name":"Fbx01_R_Clavicle", "pos":[3.10919, 2.46577, -0.0115284], "rotq":[0, 0, 0, 1]},
  889. {"parent":19, "name":"Fbx01_R_UpperArm", "pos":[16.014, 4.57764e-05, 3.10405], "rotq":[0, 0, 0, 1]},
  890. {"parent":20, "name":"Fbx01_R_Forearm", "pos":[22.7068, -1.66322, -2.13803], "rotq":[0, 0, 0, 1]},
  891. {"parent":21, "name":"Fbx01_R_Hand", "pos":[25.5881, -0.80249, -6.37307], "rotq":[0, 0, 0, 1]},
  892. ...
  893. {"parent":27, "name":"Fbx01_R_Finger32", "pos":[2.15572, -0.548737, -0.539604], "rotq":[0, 0, 0, 1]},
  894. {"parent":22, "name":"Fbx01_R_Finger2", "pos":[9.79318, 0.132553, -2.97845], "rotq":[0, 0, 0, 1]},
  895. {"parent":29, "name":"Fbx01_R_Finger21", "pos":[2.74037, 0.0483093, -0.650531], "rotq":[0, 0, 0, 1]},
  896. {"parent":55, "name":"Fbx01_L_Finger02", "pos":[-1.65308, -1.43208, -1.82885], "rotq":[0, 0, 0, 1]}
  897. ]
  898. */
  899. this.hierarchy = [];
  900. }
  901. Bones.prototype.parseHierarchy = function ( node ) {
  902. var objects = node.Objects;
  903. var models = objects.subNodes.Model;
  904. var bones = [];
  905. for ( var id in models ) {
  906. if ( models[ id ].attrType === undefined ) {
  907. continue;
  908. }
  909. bones.push( models[ id ] );
  910. }
  911. this.hierarchy = [];
  912. for ( var i = 0; i < bones.length; ++ i ) {
  913. var bone = bones[ i ];
  914. var p = node.searchConnectionParent( bone.id )[ 0 ];
  915. var t = [ 0.0, 0.0, 0.0 ];
  916. var r = [ 0.0, 0.0, 0.0, 1.0 ];
  917. var s = [ 1.0, 1.0, 1.0 ];
  918. if ( 'Lcl_Translation' in bone.properties ) {
  919. t = parseArrayToFloat( bone.properties.Lcl_Translation.value );
  920. }
  921. if ( 'Lcl_Rotation' in bone.properties ) {
  922. r = parseArrayToRadians( bone.properties.Lcl_Rotation.value );
  923. var q = new THREE.Quaternion();
  924. q.setFromEuler( new THREE.Euler( r[ 0 ], r[ 1 ], r[ 2 ], 'ZYX' ) );
  925. r = [ q.x, q.y, q.z, q.w ];
  926. }
  927. if ( 'Lcl_Scaling' in bone.properties ) {
  928. s = parseArrayToFloat( bone.properties.Lcl_Scaling.value );
  929. }
  930. // replace unsafe character
  931. var name = bone.attrName;
  932. name = name.replace( /:/, '' );
  933. name = name.replace( /_/, '' );
  934. name = name.replace( /-/, '' );
  935. this.hierarchy.push( { "parent": p, "name": name, "pos": t, "rotq": r, "scl": s, "internalId": bone.id } );
  936. }
  937. this.reindexParentId();
  938. this.restoreBindPose( node );
  939. return this;
  940. };
  941. Bones.prototype.reindexParentId = function () {
  942. for ( var h = 0; h < this.hierarchy.length; h ++ ) {
  943. for ( var ii = 0; ii < this.hierarchy.length; ++ ii ) {
  944. if ( this.hierarchy[ h ].parent == this.hierarchy[ ii ].internalId ) {
  945. this.hierarchy[ h ].parent = ii;
  946. break;
  947. }
  948. }
  949. }
  950. };
  951. Bones.prototype.restoreBindPose = function ( node ) {
  952. var bindPoseNode = node.Objects.subNodes.Pose;
  953. if ( bindPoseNode === undefined ) {
  954. return;
  955. }
  956. for ( var key in bindPoseNode ) {
  957. if ( bindPoseNode[ key ].attrType === 'BindPose' ) {
  958. bindPoseNode = bindPoseNode[ key ];
  959. break;
  960. }
  961. }
  962. var poseNode = bindPoseNode.subNodes.PoseNode;
  963. var localMatrices = {}; // store local matrices, modified later( initialy world space )
  964. var worldMatrices = {}; // store world matrices
  965. for ( var i = 0; i < poseNode.length; ++ i ) {
  966. var rawMatLcl = parseArrayToMatrix( poseNode[ i ].subNodes.Matrix.properties.a );
  967. var rawMatWrd = parseArrayToMatrix( poseNode[ i ].subNodes.Matrix.properties.a );
  968. localMatrices[ poseNode[ i ].id ] = rawMatLcl;
  969. worldMatrices[ poseNode[ i ].id ] = rawMatWrd;
  970. }
  971. for ( var h = 0; h < this.hierarchy.length; ++ h ) {
  972. var bone = this.hierarchy[ h ];
  973. var inId = bone.internalId;
  974. if ( worldMatrices[ inId ] === undefined ) {
  975. // has no bind pose node, possibly be mesh
  976. // console.log( bone );
  977. continue;
  978. }
  979. var t = new THREE.Vector3( 0, 0, 0 );
  980. var r = new THREE.Quaternion();
  981. var s = new THREE.Vector3( 1, 1, 1 );
  982. var parentId;
  983. var parentNodes = node.searchConnectionParent( inId );
  984. for ( var pn = 0; pn < parentNodes.length; ++ pn ) {
  985. if ( this.isBoneNode( parentNodes[ pn ] ) ) {
  986. parentId = parentNodes[ pn ];
  987. break;
  988. }
  989. }
  990. if ( parentId !== undefined && localMatrices[ parentId ] !== undefined ) {
  991. // convert world space matrix into local space
  992. var inv = new THREE.Matrix4();
  993. inv.getInverse( worldMatrices[ parentId ] );
  994. inv.multiply( localMatrices[ inId ] );
  995. localMatrices[ inId ] = inv;
  996. } else {
  997. //console.log( bone );
  998. }
  999. localMatrices[ inId ].decompose( t, r, s );
  1000. bone.pos = [ t.x, t.y, t.z ];
  1001. bone.rotq = [ r.x, r.y, r.z, r.w ];
  1002. bone.scl = [ s.x, s.y, s.z ];
  1003. }
  1004. };
  1005. Bones.prototype.searchRealId = function ( internalId ) {
  1006. for ( var h = 0; h < this.hierarchy.length; h ++ ) {
  1007. if ( internalId == this.hierarchy[ h ].internalId ) {
  1008. return h;
  1009. }
  1010. }
  1011. // console.warn( 'FBXLoader: notfound internalId in bones: ' + internalId);
  1012. return - 1;
  1013. };
  1014. Bones.prototype.getByInternalId = function ( internalId ) {
  1015. for ( var h = 0; h < this.hierarchy.length; h ++ ) {
  1016. if ( internalId == this.hierarchy[ h ].internalId ) {
  1017. return this.hierarchy[ h ];
  1018. }
  1019. }
  1020. return null;
  1021. };
  1022. Bones.prototype.isBoneNode = function ( id ) {
  1023. for ( var i = 0; i < this.hierarchy.length; ++ i ) {
  1024. if ( id === this.hierarchy[ i ].internalId ) {
  1025. return true;
  1026. }
  1027. }
  1028. return false;
  1029. };
  1030. Bones.prototype.getBoneIdfromInternalId = function ( node, id ) {
  1031. if ( node.__cache_get_boneid_from_internalid === undefined ) {
  1032. node.__cache_get_boneid_from_internalid = [];
  1033. }
  1034. if ( node.__cache_get_boneid_from_internalid[ id ] !== undefined ) {
  1035. return node.__cache_get_boneid_from_internalid[ id ];
  1036. }
  1037. for ( var i = 0; i < this.hierarchy.length; ++ i ) {
  1038. if ( this.hierarchy[ i ].internalId == id ) {
  1039. node.__cache_get_boneid_from_internalid[ id ] = i;
  1040. return i;
  1041. }
  1042. }
  1043. // console.warn( 'FBXLoader: bone internalId(' + id + ') not found in bone hierarchy' );
  1044. return - 1;
  1045. };
  1046. function Geometries() {
  1047. this.geometries = {};
  1048. }
  1049. Object.assign( Geometries.prototype, {
  1050. parse: function ( FBXNodes, hierarchy ) {
  1051. if ( ! ( 'Geometry' in FBXNodes.Objects.subNodes ) ) {
  1052. return this;
  1053. }
  1054. for ( var geo in FBXNodes.Objects.subNodes.Geometry ) {
  1055. if ( FBXNodes.Objects.subNodes.Geometry[ geo ].attrType === 'Mesh' ) {
  1056. this.geometries[ geo ] = ( new Geometry() ).parse( FBXNodes.Objects.subNodes.Geometry[ geo ] );
  1057. this.geometries[ geo ].addBones( hierarchy.hierarchy );
  1058. }
  1059. }
  1060. return this;
  1061. }
  1062. } );
  1063. function Geometry() {
  1064. this.node = null;
  1065. this.name = null;
  1066. this.id = null;
  1067. this.vertices = [];
  1068. this.indices = [];
  1069. this.normals = [];
  1070. this.uvs = [];
  1071. this.bones = [];
  1072. }
  1073. Geometry.prototype.parse = function ( geoNode ) {
  1074. this.node = geoNode;
  1075. this.name = geoNode.attrName;
  1076. this.id = geoNode.id;
  1077. this.vertices = this.getVertices();
  1078. if ( this.vertices === undefined ) {
  1079. console.log( 'FBXLoader: Geometry.parse(): pass' + this.node.id );
  1080. return;
  1081. }
  1082. this.indices = this.getPolygonVertexIndices();
  1083. this.uvs = ( new UV() ).parse( this.node, this );
  1084. this.normals = ( new Normal() ).parse( this.node, this );
  1085. this.materialIndices = ( new MaterialIndex() ).parse( this.node );
  1086. if ( this.getPolygonTopologyMax() > 3 ) {
  1087. var indexInfo = this.convertPolyIndicesToTri(
  1088. this.indices,
  1089. this.materialIndices,
  1090. this.getPolygonTopologyArray() );
  1091. this.indices = indexInfo.res;
  1092. this.materialIndices = indexInfo.materialIndices;
  1093. this.polyIndices = indexInfo.polyIndices;
  1094. }
  1095. return this;
  1096. };
  1097. Geometry.prototype.getVertices = function () {
  1098. if ( this.node.__cache_vertices ) {
  1099. return this.node.__cache_vertices;
  1100. }
  1101. if ( this.node.subNodes.Vertices === undefined ) {
  1102. console.warn( 'this.node: ' + this.node.attrName + "(" + this.node.id + ") does not have Vertices" );
  1103. this.node.__cache_vertices = undefined;
  1104. return null;
  1105. }
  1106. var rawTextVert = this.node.subNodes.Vertices.properties.a;
  1107. var vertices = rawTextVert.split( ',' ).map( function ( element ) {
  1108. return parseFloat( element );
  1109. } );
  1110. this.node.__cache_vertices = vertices;
  1111. return this.node.__cache_vertices;
  1112. };
  1113. Geometry.prototype.getPolygonVertexIndices = function () {
  1114. if ( this.node.__cache_indices && this.node.__cache_poly_topology_max ) {
  1115. return this.node.__cache_indices;
  1116. }
  1117. if ( this.node.subNodes === undefined ) {
  1118. console.error( 'this.node.subNodes undefined' );
  1119. console.log( this.node );
  1120. return;
  1121. }
  1122. if ( this.node.subNodes.PolygonVertexIndex === undefined ) {
  1123. console.warn( 'this.node: ' + this.node.attrName + "(" + this.node.id + ") does not have PolygonVertexIndex " );
  1124. this.node.__cache_indices = undefined;
  1125. return;
  1126. }
  1127. var rawTextIndices = this.node.subNodes.PolygonVertexIndex.properties.a;
  1128. var indices = rawTextIndices.split( ',' );
  1129. var currentTopo = 1;
  1130. var topologyN = null;
  1131. var topologyArr = [];
  1132. // The indices that make up the polygon are in order and a negative index
  1133. // means that it’s the last index of the polygon. That index needs
  1134. // to be made positive and then you have to subtract 1 from it!
  1135. for ( var i = 0; i < indices.length; ++ i ) {
  1136. var tmpI = parseInt( indices[ i ] );
  1137. // found n
  1138. if ( tmpI < 0 ) {
  1139. if ( currentTopo > topologyN ) {
  1140. topologyN = currentTopo;
  1141. }
  1142. indices[ i ] = tmpI ^ - 1;
  1143. topologyArr.push( currentTopo );
  1144. currentTopo = 1;
  1145. } else {
  1146. indices[ i ] = tmpI;
  1147. currentTopo ++;
  1148. }
  1149. }
  1150. if ( topologyN === null ) {
  1151. console.warn( "FBXLoader: topology N not found: " + this.node.attrName );
  1152. console.warn( this.node );
  1153. topologyN = 3;
  1154. }
  1155. this.node.__cache_poly_topology_max = topologyN;
  1156. this.node.__cache_poly_topology_arr = topologyArr;
  1157. this.node.__cache_indices = indices;
  1158. return this.node.__cache_indices;
  1159. };
  1160. Geometry.prototype.getPolygonTopologyMax = function () {
  1161. if ( this.node.__cache_indices && this.node.__cache_poly_topology_max ) {
  1162. return this.node.__cache_poly_topology_max;
  1163. }
  1164. this.getPolygonVertexIndices( this.node );
  1165. return this.node.__cache_poly_topology_max;
  1166. };
  1167. Geometry.prototype.getPolygonTopologyArray = function () {
  1168. if ( this.node.__cache_indices && this.node.__cache_poly_topology_max ) {
  1169. return this.node.__cache_poly_topology_arr;
  1170. }
  1171. this.getPolygonVertexIndices( this.node );
  1172. return this.node.__cache_poly_topology_arr;
  1173. };
  1174. // a - d
  1175. // | |
  1176. // b - c
  1177. //
  1178. // [( a, b, c, d ) ...........
  1179. // [( a, b, c ), (a, c, d )....
  1180. // Also keep track of original poly index.
  1181. Geometry.prototype.convertPolyIndicesToTri = function ( indices, materialIndices, strides ) {
  1182. var res = [];
  1183. var i = 0;
  1184. var currentPolyNum = 0;
  1185. var currentStride = 0;
  1186. var polyIndices = [];
  1187. while ( i < indices.length ) {
  1188. currentStride = strides[ currentPolyNum ];
  1189. // CAUTIN: NG over 6gon
  1190. for ( var j = 0; j <= ( currentStride - 3 ); j ++ ) {
  1191. res.push( indices[ i ] );
  1192. res.push( indices[ i + ( currentStride - 2 - j ) ] );
  1193. res.push( indices[ i + ( currentStride - 1 - j ) ] );
  1194. polyIndices.push( currentPolyNum );
  1195. }
  1196. currentPolyNum ++;
  1197. i += currentStride;
  1198. }
  1199. var newMaterialIndices = [ materialIndices[ 0 ] ];
  1200. if ( materialIndices.length > 1 ) {
  1201. for ( var i = 0; i < polyIndices.length; ++ i ) {
  1202. newMaterialIndices[ i ] = materialIndices[ polyIndices[ i ] ];
  1203. }
  1204. }
  1205. return {
  1206. res: res,
  1207. materialIndices: newMaterialIndices,
  1208. polyIndices: polyIndices };
  1209. };
  1210. Geometry.prototype.addBones = function ( bones ) {
  1211. this.bones = bones;
  1212. };
  1213. function UV() {
  1214. this.uv = null;
  1215. this.map = null;
  1216. this.ref = null;
  1217. this.node = null;
  1218. this.index = null;
  1219. }
  1220. UV.prototype.getUV = function ( node ) {
  1221. if ( this.node && this.uv && this.map && this.ref ) {
  1222. return this.uv;
  1223. } else {
  1224. return this._parseText( node );
  1225. }
  1226. };
  1227. UV.prototype.getMap = function ( node ) {
  1228. if ( this.node && this.uv && this.map && this.ref ) {
  1229. return this.map;
  1230. } else {
  1231. this._parseText( node );
  1232. return this.map;
  1233. }
  1234. };
  1235. UV.prototype.getRef = function ( node ) {
  1236. if ( this.node && this.uv && this.map && this.ref ) {
  1237. return this.ref;
  1238. } else {
  1239. this._parseText( node );
  1240. return this.ref;
  1241. }
  1242. };
  1243. UV.prototype.getIndex = function ( node ) {
  1244. if ( this.node && this.uv && this.map && this.ref ) {
  1245. return this.index;
  1246. } else {
  1247. this._parseText( node );
  1248. return this.index;
  1249. }
  1250. };
  1251. UV.prototype.getNode = function ( topnode ) {
  1252. if ( this.node !== null ) {
  1253. return this.node;
  1254. }
  1255. this.node = topnode.subNodes.LayerElementUV;
  1256. return this.node;
  1257. };
  1258. UV.prototype._parseText = function ( node ) {
  1259. var uvNode = this.getNode( node )[ 0 ];
  1260. if ( uvNode === undefined ) {
  1261. // console.log( node.attrName + "(" + node.id + ")" + " has no LayerElementUV." );
  1262. return [];
  1263. }
  1264. var count = 0;
  1265. for ( var n in uvNode ) {
  1266. if ( n.match( /^\d+$/ ) ) {
  1267. count ++;
  1268. }
  1269. }
  1270. if ( count > 0 ) {
  1271. console.warn( 'multi uv not supported' );
  1272. uvNode = uvNode[ n ];
  1273. }
  1274. var uvIndex = uvNode.subNodes.UVIndex.properties.a;
  1275. var uvs = uvNode.subNodes.UV.properties.a;
  1276. var uvMap = uvNode.properties.MappingInformationType;
  1277. var uvRef = uvNode.properties.ReferenceInformationType;
  1278. this.uv = parseArrayToFloat( uvs );
  1279. this.index = parseArrayToInt( uvIndex );
  1280. this.map = uvMap; // TODO: normalize notation shaking... FOR BLENDER
  1281. this.ref = uvRef;
  1282. return this.uv;
  1283. };
  1284. UV.prototype.parse = function ( node, geo ) {
  1285. if ( ! ( 'LayerElementUV' in node.subNodes ) ) {
  1286. return;
  1287. }
  1288. this.uvNode = this.getNode( node );
  1289. this.uv = this.getUV( node );
  1290. var mappingType = this.getMap( node );
  1291. var refType = this.getRef( node );
  1292. var indices = this.getIndex( node );
  1293. var strides = geo.getPolygonTopologyArray();
  1294. // it means that there is a normal for every vertex of every polygon of the model.
  1295. // For example, if the models has 8 vertices that make up four quads, then there
  1296. // will be 16 normals (one normal * 4 polygons * 4 vertices of the polygon). Note
  1297. // that generally a game engine needs the vertices to have only one normal defined.
  1298. // So, if you find a vertex has more tha one normal, you can either ignore the normals
  1299. // you find after the first, or calculate the mean from all of them (normal smoothing).
  1300. //if ( mappingType == "ByPolygonVertex" ){
  1301. switch ( mappingType ) {
  1302. case "ByPolygonVertex":
  1303. switch ( refType ) {
  1304. // Direct
  1305. // The this.uv are in order.
  1306. case "Direct":
  1307. this.uv = this.parseUV_ByPolygonVertex_Direct( this.uv, indices, strides, 2 );
  1308. break;
  1309. // IndexToDirect
  1310. // The order of the this.uv is given by the uvsIndex property.
  1311. case "IndexToDirect":
  1312. this.uv = this.parseUV_ByPolygonVertex_IndexToDirect( this.uv, indices );
  1313. break;
  1314. }
  1315. // convert from by polygon(vert) data into by verts data
  1316. this.uv = mapByPolygonVertexToByVertex( this.uv, geo.getPolygonVertexIndices( node ), 2 );
  1317. break;
  1318. case "ByPolygon":
  1319. switch ( refType ) {
  1320. // Direct
  1321. // The this.uv are in order.
  1322. case "Direct":
  1323. this.uv = this.parseUV_ByPolygon_Direct();
  1324. break;
  1325. // IndexToDirect
  1326. // The order of the this.uv is given by the uvsIndex property.
  1327. case "IndexToDirect":
  1328. this.uv = this.parseUV_ByPolygon_IndexToDirect();
  1329. break;
  1330. }
  1331. break;
  1332. }
  1333. return this.uv;
  1334. };
  1335. UV.prototype.parseUV_ByPolygonVertex_Direct = function ( node, indices, strides, itemSize ) {
  1336. return parse_Data_ByPolygonVertex_Direct( node, indices, strides, itemSize );
  1337. };
  1338. UV.prototype.parseUV_ByPolygonVertex_IndexToDirect = function ( node, indices ) {
  1339. return parse_Data_ByPolygonVertex_IndexToDirect( node, indices, 2 );
  1340. };
  1341. UV.prototype.parseUV_ByPolygon_Direct = function ( node ) {
  1342. console.warn( "not implemented" );
  1343. return node;
  1344. };
  1345. UV.prototype.parseUV_ByPolygon_IndexToDirect = function ( node ) {
  1346. console.warn( "not implemented" );
  1347. return node;
  1348. };
  1349. UV.prototype.parseUV_ByVertex_Direct = function ( node ) {
  1350. console.warn( "not implemented" );
  1351. return node;
  1352. };
  1353. function Normal() {
  1354. this.normal = null;
  1355. this.map = null;
  1356. this.ref = null;
  1357. this.node = null;
  1358. this.index = null;
  1359. }
  1360. Normal.prototype.getNormal = function ( node ) {
  1361. if ( this.node && this.normal && this.map && this.ref ) {
  1362. return this.normal;
  1363. } else {
  1364. this._parseText( node );
  1365. return this.normal;
  1366. }
  1367. };
  1368. // mappingType: possible variant
  1369. // ByPolygon
  1370. // ByPolygonVertex
  1371. // ByVertex (or also ByVertice, as the Blender exporter writes)
  1372. // ByEdge
  1373. // AllSame
  1374. // var mappingType = node.properties.MappingInformationType;
  1375. Normal.prototype.getMap = function ( node ) {
  1376. if ( this.node && this.normal && this.map && this.ref ) {
  1377. return this.map;
  1378. } else {
  1379. this._parseText( node );
  1380. return this.map;
  1381. }
  1382. };
  1383. // refType: possible variants
  1384. // Direct
  1385. // IndexToDirect (or Index for older versions)
  1386. // var refType = node.properties.ReferenceInformationType;
  1387. Normal.prototype.getRef = function ( node ) {
  1388. if ( this.node && this.normal && this.map && this.ref ) {
  1389. return this.ref;
  1390. } else {
  1391. this._parseText( node );
  1392. return this.ref;
  1393. }
  1394. };
  1395. Normal.prototype.getNode = function ( node ) {
  1396. if ( this.node ) {
  1397. return this.node;
  1398. }
  1399. this.node = node.subNodes.LayerElementNormal;
  1400. return this.node;
  1401. };
  1402. Normal.prototype._parseText = function ( node ) {
  1403. var normalNode = this.getNode( node )[ 0 ];
  1404. if ( normalNode === undefined ) {
  1405. console.warn( 'node: ' + node.attrName + "(" + node.id + ") does not have LayerElementNormal" );
  1406. return;
  1407. }
  1408. var mappingType = normalNode.properties.MappingInformationType;
  1409. var refType = normalNode.properties.ReferenceInformationType;
  1410. var rawTextNormals = normalNode.subNodes.Normals.properties.a;
  1411. this.normal = parseArrayToFloat( rawTextNormals );
  1412. // TODO: normalize notation shaking, vertex / vertice... blender...
  1413. this.map = mappingType;
  1414. this.ref = refType;
  1415. };
  1416. Normal.prototype.parse = function ( topnode, geo ) {
  1417. var normals = this.getNormal( topnode );
  1418. //var normalNode = this.getNode( topnode );
  1419. var mappingType = this.getMap( topnode );
  1420. var refType = this.getRef( topnode );
  1421. var indices = geo.getPolygonVertexIndices( topnode );
  1422. var strides = geo.getPolygonTopologyArray( topnode );
  1423. // it means that there is a normal for every vertex of every polygon of the model.
  1424. // For example, if the models has 8 vertices that make up four quads, then there
  1425. // will be 16 normals (one normal * 4 polygons * 4 vertices of the polygon). Note
  1426. // that generally a game engine needs the vertices to have only one normal defined.
  1427. // So, if you find a vertex has more tha one normal, you can either ignore the normals
  1428. // you find after the first, or calculate the mean from all of them (normal smoothing).
  1429. //if ( mappingType == "ByPolygonVertex" ){
  1430. switch ( mappingType ) {
  1431. case "ByPolygonVertex":
  1432. switch ( refType ) {
  1433. // Direct
  1434. // The normals are in order.
  1435. case "Direct":
  1436. normals = this.parseNormal_ByPolygonVertex_Direct( normals, indices, strides, 3 );
  1437. break;
  1438. // IndexToDirect
  1439. // The order of the normals is given by the NormalsIndex property.
  1440. case "IndexToDirect":
  1441. normals = this.parseNormal_ByPolygonVertex_IndexToDirect();
  1442. break;
  1443. }
  1444. break;
  1445. case "ByPolygon":
  1446. switch ( refType ) {
  1447. // Direct
  1448. // The normals are in order.
  1449. case "Direct":
  1450. normals = this.parseNormal_ByPolygon_Direct();
  1451. break;
  1452. // IndexToDirect
  1453. // The order of the normals is given by the NormalsIndex property.
  1454. case "IndexToDirect":
  1455. normals = this.parseNormal_ByPolygon_IndexToDirect();
  1456. break;
  1457. }
  1458. break;
  1459. }
  1460. return normals;
  1461. };
  1462. Normal.prototype.parseNormal_ByPolygonVertex_Direct = function ( node, indices, strides, itemSize ) {
  1463. return parse_Data_ByPolygonVertex_Direct( node, indices, strides, itemSize );
  1464. };
  1465. Normal.prototype.parseNormal_ByPolygonVertex_IndexToDirect = function ( node ) {
  1466. console.warn( "not implemented" );
  1467. return node;
  1468. };
  1469. Normal.prototype.parseNormal_ByPolygon_Direct = function ( node ) {
  1470. console.warn( "not implemented" );
  1471. return node;
  1472. };
  1473. Normal.prototype.parseNormal_ByPolygon_IndexToDirect = function ( node ) {
  1474. console.warn( "not implemented" );
  1475. return node;
  1476. };
  1477. Normal.prototype.parseNormal_ByVertex_Direct = function ( node ) {
  1478. console.warn( "not implemented" );
  1479. return node;
  1480. };
  1481. function MaterialIndex() {
  1482. this.indexBuffer = [];
  1483. }
  1484. Object.assign( MaterialIndex.prototype, {
  1485. parse: function ( node ) {
  1486. if ( ! ( 'LayerElementMaterial' in node.subNodes ) ) {
  1487. return;
  1488. }
  1489. var indexNode = node.subNodes.LayerElementMaterial[ 0 ];
  1490. var mappingType = indexNode.properties.MappingInformationType;
  1491. var refType = indexNode.properties.ReferenceInformationType;
  1492. var indices = parseArrayToInt( indexNode.subNodes.Materials.properties.a );
  1493. // it means that there is a normal for every vertex of every polygon of the model.
  1494. // For example, if the models has 8 vertices that make up four quads, then there
  1495. // will be 16 normals (one normal * 4 polygons * 4 vertices of the polygon). Note
  1496. // that generally a game engine needs the vertices to have only one normal defined.
  1497. // So, if you find a vertex has more tha one normal, you can either ignore the normals
  1498. // you find after the first, or calculate the mean from all of them (normal smoothing).
  1499. //if ( mappingType == "ByPolygonVertex" ){
  1500. switch ( mappingType ) {
  1501. case "ByPolygon":
  1502. switch ( refType ) {
  1503. // Direct
  1504. // The material indices are in order.
  1505. case "IndexToDirect":
  1506. this.indexBuffer = this.parse_ByPolygon_IndexToDirect( indices );
  1507. break;
  1508. default:
  1509. this.indexBuffer = [ 0 ];
  1510. break;
  1511. }
  1512. break;
  1513. default:
  1514. this.indexBuffer = [ 0 ];
  1515. break;
  1516. }
  1517. return this.indexBuffer;
  1518. },
  1519. parse_ByPolygon_IndexToDirect: function ( indices ) {
  1520. return indices;
  1521. },
  1522. } );
  1523. function AnimationCurve() {
  1524. this.version = null;
  1525. this.id = null;
  1526. this.internalId = null;
  1527. this.times = null;
  1528. this.values = null;
  1529. this.attrFlag = null; // tangeant
  1530. this.attrData = null; // slope, weight
  1531. }
  1532. AnimationCurve.prototype.fromNode = function ( curveNode ) {
  1533. this.id = curveNode.id;
  1534. this.internalId = curveNode.id;
  1535. this.times = curveNode.subNodes.KeyTime.properties.a;
  1536. this.values = curveNode.subNodes.KeyValueFloat.properties.a;
  1537. this.attrFlag = curveNode.subNodes.KeyAttrFlags.properties.a;
  1538. this.attrData = curveNode.subNodes.KeyAttrDataFloat.properties.a;
  1539. this.times = parseArrayToFloat( this.times );
  1540. this.values = parseArrayToFloat( this.values );
  1541. this.attrData = parseArrayToFloat( this.attrData );
  1542. this.attrFlag = parseArrayToInt( this.attrFlag );
  1543. this.times = this.times.map( function ( element ) {
  1544. return FBXTimeToSeconds( element );
  1545. } );
  1546. return this;
  1547. };
  1548. AnimationCurve.prototype.getLength = function () {
  1549. return this.times[ this.times.length - 1 ];
  1550. };
  1551. function AnimationNode() {
  1552. this.id = null;
  1553. this.attr = null; // S, R, T
  1554. this.attrX = false;
  1555. this.attrY = false;
  1556. this.attrZ = false;
  1557. this.internalId = null;
  1558. this.containerInternalId = null; // bone, null etc Id
  1559. this.containerBoneId = null; // bone, null etc Id
  1560. this.curveIdx = null; // AnimationCurve's indices
  1561. this.curves = {}; // AnimationCurve refs
  1562. }
  1563. AnimationNode.prototype.fromNode = function ( allNodes, node, bones ) {
  1564. this.id = node.id;
  1565. this.attr = node.attrName;
  1566. this.internalId = node.id;
  1567. if ( this.attr.match( /S|R|T/ ) ) {
  1568. for ( var attrKey in node.properties ) {
  1569. if ( attrKey.match( /X/ ) ) {
  1570. this.attrX = true;
  1571. }
  1572. if ( attrKey.match( /Y/ ) ) {
  1573. this.attrY = true;
  1574. }
  1575. if ( attrKey.match( /Z/ ) ) {
  1576. this.attrZ = true;
  1577. }
  1578. }
  1579. } else {
  1580. // may be deform percent nodes
  1581. return null;
  1582. }
  1583. this.containerIndices = allNodes.searchConnectionParent( this.id );
  1584. this.curveIdx = allNodes.searchConnectionChildren( this.id );
  1585. for ( var i = this.containerIndices.length - 1; i >= 0; -- i ) {
  1586. var boneId = bones.searchRealId( this.containerIndices[ i ] );
  1587. if ( boneId >= 0 ) {
  1588. this.containerBoneId = boneId;
  1589. this.containerId = this.containerIndices[ i ];
  1590. }
  1591. if ( boneId >= 0 ) {
  1592. break;
  1593. }
  1594. }
  1595. // this.containerBoneId = bones.searchRealId( this.containerIndices );
  1596. return this;
  1597. };
  1598. AnimationNode.prototype.setCurve = function ( curve ) {
  1599. this.curves.push( curve );
  1600. };
  1601. function Animation() {
  1602. this.curves = {};
  1603. this.length = 0.0;
  1604. this.fps = 30.0;
  1605. this.frames = 0.0;
  1606. }
  1607. Animation.prototype.parse = function ( node, bones ) {
  1608. var rawNodes = node.Objects.subNodes.AnimationCurveNode;
  1609. var rawCurves = node.Objects.subNodes.AnimationCurve;
  1610. var rawLayers = node.Objects.subNodes.AnimationLayer;
  1611. var rawStacks = node.Objects.subNodes.AnimationStack;
  1612. // first: expand AnimationCurveNode into curve nodes
  1613. var curveNodes = [];
  1614. for ( var key in rawNodes ) {
  1615. if ( key.match( /\d+/ ) ) {
  1616. var a = ( new AnimationNode() ).fromNode( node, rawNodes[ key ], bones );
  1617. curveNodes.push( a );
  1618. }
  1619. }
  1620. // second: gen dict, mapped by internalId
  1621. var tmp = {};
  1622. for ( var i = 0; i < curveNodes.length; ++ i ) {
  1623. if ( curveNodes[ i ] === null ) {
  1624. continue;
  1625. }
  1626. tmp[ curveNodes[ i ].id ] = curveNodes[ i ];
  1627. }
  1628. // third: insert curves into the dict
  1629. var ac = [];
  1630. for ( key in rawCurves ) {
  1631. if ( key.match( /\d+/ ) ) {
  1632. var c = ( new AnimationCurve() ).fromNode( rawCurves[ key ] );
  1633. ac.push( c );
  1634. var parentId = node.searchConnectionParent( c.id )[ 0 ];
  1635. var axis = node.searchConnectionType( c.id, parentId );
  1636. if ( axis.match( /X/ ) ) {
  1637. axis = 'x';
  1638. } else if ( axis.match( /Y/ ) ) {
  1639. axis = 'y';
  1640. } else if ( axis.match( /Z/ ) ) {
  1641. axis = 'z';
  1642. } else {
  1643. continue;
  1644. }
  1645. tmp[ parentId ].curves[ axis ] = c;
  1646. }
  1647. }
  1648. // forth:
  1649. for ( var t in tmp ) {
  1650. var id = tmp[ t ].containerBoneId;
  1651. if ( this.curves[ id ] === undefined ) {
  1652. this.curves[ id ] = {
  1653. T: null,
  1654. R: null,
  1655. S: null
  1656. };
  1657. }
  1658. this.curves[ id ][ tmp[ t ].attr ] = tmp[ t ];
  1659. }
  1660. //Layers
  1661. this.layers = {};
  1662. for ( var key in rawLayers ) {
  1663. var layer = [];
  1664. var children = node.searchConnectionChildren( key );
  1665. for ( var i = 0; i < children.length; ++ i ) {
  1666. //Skip lockInfluenceWeights
  1667. if ( tmp[ children[ i ] ] ) {
  1668. if ( layer[ tmp[ children[ i ] ].containerBoneId ] === undefined ) {
  1669. layer[ tmp[ children[ i ] ].containerBoneId ] = {
  1670. T: null,
  1671. R: null,
  1672. S: null
  1673. };
  1674. }
  1675. layer[ tmp[ children[ i ] ].containerBoneId ][ tmp[ children[ i ] ].attr ] = tmp[ children[ i ] ];
  1676. }
  1677. }
  1678. this.layers[ key ] = layer;
  1679. }
  1680. //Takes
  1681. this.stacks = {};
  1682. for ( var key in rawStacks ) {
  1683. var layers = [];
  1684. var children = node.searchConnectionChildren( key );
  1685. var max = 0.0;
  1686. var min = Number.MAX_VALUE;
  1687. for ( var i = 0; i < children.length; ++ i ) {
  1688. if ( children[ i ] in this.layers ) {
  1689. layers.push( this.layers[ children[ i ] ] );
  1690. for ( var j = 0; j < this.layers[ children[ i ] ].length; ++ j ) {
  1691. function getMaxMin( layer ) {
  1692. function _getMaxMin( curves ) {
  1693. if ( curves.x ) {
  1694. max = curves.x.getLength() > max ? curves.x.getLength() : max;
  1695. min = curves.x.times[ 0 ] < min ? curves.x.times[ 0 ] : min;
  1696. }
  1697. if ( curves.y ) {
  1698. max = curves.y.getLength() > max ? curves.y.getLength() : max;
  1699. min = curves.y.times[ 0 ] < min ? curves.y.times[ 0 ] : min;
  1700. }
  1701. if ( curves.z ) {
  1702. max = curves.z.getLength() > max ? curves.z.getLength() : max;
  1703. min = curves.z.times[ 0 ] < min ? curves.z.times[ 0 ] : min;
  1704. }
  1705. }
  1706. if ( layer.R ) {
  1707. _getMaxMin( layer.R.curves );
  1708. }
  1709. if ( layer.S ) {
  1710. _getMaxMin( layer.S.curves );
  1711. }
  1712. if ( layer.T ) {
  1713. _getMaxMin( layer.T.curves );
  1714. }
  1715. }
  1716. var layer = this.layers[ children[ i ] ][ j ];
  1717. if ( layer ) {
  1718. getMaxMin( layer );
  1719. }
  1720. }
  1721. }
  1722. }
  1723. //Do we have an animation clip with an actual length?
  1724. if ( max > min ) {
  1725. this.stacks[ key ] = {
  1726. name: rawStacks[ key ].attrName,
  1727. layers: layers,
  1728. length: max - min,
  1729. frames: ( max - min ) * 30,
  1730. };
  1731. }
  1732. }
  1733. return this;
  1734. };
  1735. function Textures() {
  1736. this.textures = {};
  1737. //this.perGeoMap = {};
  1738. }
  1739. Textures.prototype.add = function ( tex ) {
  1740. debugger;
  1741. if ( this.textures === undefined ) {
  1742. this.textures = [];
  1743. }
  1744. this.textures.push( tex );
  1745. for ( var i = 0; i < tex.parentIds.length; ++ i ) {
  1746. if ( this.perGeoMap[ tex.parentIds[ i ] ] === undefined ) {
  1747. this.perGeoMap[ tex.parentIds[ i ] ] = [];
  1748. }
  1749. this.perGeoMap[ tex.parentIds[ i ] ].push( this.textures[ this.textures.length - 1 ] );
  1750. }
  1751. };
  1752. Textures.prototype.parse = function ( node ) {
  1753. var rawNodes = node.Objects.subNodes.Texture;
  1754. for ( var n in rawNodes ) {
  1755. var tex = ( new Texture() ).parse( rawNodes[ n ], node );
  1756. this.textures[ n ] = tex;
  1757. }
  1758. return this;
  1759. };
  1760. Textures.prototype.getById = function ( id ) {
  1761. return this.perGeoMap[ id ];
  1762. };
  1763. function Texture() {
  1764. this.fileName = "";
  1765. this.name = "";
  1766. this.id = null;
  1767. this.parentIds = [];
  1768. }
  1769. Texture.prototype.parse = function ( node, nodes ) {
  1770. this.id = node.id;
  1771. this.name = node.attrName;
  1772. this.fileName = this.parseFileName( node.properties.FileName );
  1773. this.parentIds = this.searchParents( this.id, nodes );
  1774. return this;
  1775. };
  1776. // TODO: support directory
  1777. Texture.prototype.parseFileName = function ( fname ) {
  1778. if ( fname === undefined ) {
  1779. return "";
  1780. }
  1781. // ignore directory structure, flatten path
  1782. var splitted = fname.split( /[\\\/]/ );
  1783. if ( splitted.length > 0 ) {
  1784. return splitted[ splitted.length - 1 ];
  1785. } else {
  1786. return fname;
  1787. }
  1788. };
  1789. Texture.prototype.searchParents = function ( id, nodes ) {
  1790. var p = nodes.searchConnectionParent( id );
  1791. return p;
  1792. };
  1793. function Materials() {
  1794. this.materials = {};
  1795. this.perGeoMap = {};
  1796. }
  1797. Object.assign( Materials.prototype, {
  1798. parse: function ( node ) {
  1799. var rawNodes = node.Objects.subNodes.Material;
  1800. for ( var n in rawNodes ) {
  1801. var mat = ( new Material() ).parse( rawNodes[ n ], node );
  1802. this.materials[ n ] = mat;
  1803. }
  1804. return this;
  1805. }
  1806. } );
  1807. function Material() {
  1808. this.fileName = "";
  1809. this.name = "";
  1810. this.id = null;
  1811. this.parentIds = [];
  1812. }
  1813. Object.assign( Material.prototype, {
  1814. parse: function ( node, nodes ) {
  1815. this.id = node.id;
  1816. this.name = node.attrName;
  1817. this.type = node.properties.ShadingModel;
  1818. this.parameters = this.parseParameters( node.properties );
  1819. this.parentIds = this.searchParents( this.id, nodes );
  1820. return this;
  1821. },
  1822. parseParameters: function ( properties ) {
  1823. var parameters = {};
  1824. //TODO: Missing parameters:
  1825. // - Ambient
  1826. // - MultiLayer
  1827. // - ShininessExponent (Same vals as Shininess)
  1828. // - Specular (Same vals as SpecularColor)
  1829. // - TransparencyFactor (Maybe same as Opacity?).
  1830. if ( properties.Diffuse ) {
  1831. parameters.color = new THREE.Color().fromArray( [ parseFloat( properties.Diffuse.value.x ), parseFloat( properties.Diffuse.value.y ), parseFloat( properties.Diffuse.value.z ) ] );
  1832. }
  1833. if ( properties.Specular ) {
  1834. parameters.specular = new THREE.Color().fromArray( [ parseFloat( properties.Specular.value.x ), parseFloat( properties.Specular.value.y ), parseFloat( properties.Specular.value.z ) ] );
  1835. }
  1836. if ( properties.Shininess ) {
  1837. parameters.shininess = properties.Shininess.value;
  1838. }
  1839. if ( properties.Emissive ) {
  1840. parameters.emissive = new THREE.Color().fromArray( [ parseFloat( properties.Emissive.value.x ), parseFloat( properties.Emissive.value.y ), parseFloat( properties.Emissive.value.z ) ] );
  1841. }
  1842. if ( properties.EmissiveFactor ) {
  1843. parameters.emissiveIntensity = properties.EmissiveFactor.value;
  1844. }
  1845. if ( properties.Reflectivity ) {
  1846. parameters.reflectivity = properties.Reflectivity.value;
  1847. }
  1848. if ( properties.Opacity ) {
  1849. parameters.opacity = properties.Opacity.value;
  1850. }
  1851. if ( parameters.opacity < 1.0 ) {
  1852. parameters.transparent = true;
  1853. }
  1854. //Assigning textures
  1855. return parameters;
  1856. },
  1857. searchParents: function ( id, nodes ) {
  1858. return nodes.searchConnectionParent( id );
  1859. }
  1860. } );
  1861. /* --------------------------------------------------------------------- */
  1862. /* --------------------------------------------------------------------- */
  1863. /* --------------------------------------------------------------------- */
  1864. /* --------------------------------------------------------------------- */
  1865. // LayerElementUV: 0 {
  1866. // Version: 101
  1867. // Name: "Texture_Projection"
  1868. // MappingInformationType: "ByPolygonVertex"
  1869. // ReferenceInformationType: "IndexToDirect"
  1870. // UV: *1746 {
  1871. // UVIndex: *7068 {
  1872. //
  1873. // The order of the uvs is given by the UVIndex property.
  1874. function parse_Data_ByPolygonVertex_IndexToDirect( node, indices, itemSize ) {
  1875. var res = [];
  1876. for ( var i = 0; i < indices.length; ++ i ) {
  1877. for ( var j = 0; j < itemSize; ++ j ) {
  1878. res.push( node[ ( indices[ i ] * itemSize ) + j ] );
  1879. }
  1880. }
  1881. return res;
  1882. }
  1883. // what want: normal per vertex, order vertice
  1884. // i have: normal per polygon
  1885. // i have: indice per polygon
  1886. function parse_Data_ByPolygonVertex_Direct( node, indices, strides, itemSize ) {
  1887. // *21204 > 3573
  1888. // Geometry: 690680816, "Geometry::", "Mesh" {
  1889. // Vertices: *3573 {
  1890. // PolygonVertexIndex: *7068 {
  1891. var tmp = [];
  1892. var currentIndex = 0;
  1893. // first: sort to per vertex
  1894. for ( var i = 0; i < indices.length; ++ i ) {
  1895. tmp[ indices[ i ] ] = [];
  1896. // TODO: duped entry? blend or something?
  1897. for ( var s = 0; s < itemSize; ++ s ) {
  1898. tmp[ indices[ i ] ][ s ] = node[ currentIndex + s ];
  1899. }
  1900. currentIndex += itemSize;
  1901. }
  1902. // second: expand x,y,z into serial array
  1903. var res = [];
  1904. for ( var jj = 0; jj < tmp.length; ++ jj ) {
  1905. if ( tmp[ jj ] === undefined ) {
  1906. continue;
  1907. }
  1908. for ( var t = 0; t < itemSize; ++ t ) {
  1909. if ( tmp[ jj ][ t ] === undefined ) {
  1910. continue;
  1911. }
  1912. res.push( tmp[ jj ][ t ] );
  1913. }
  1914. }
  1915. return res;
  1916. }
  1917. // convert from by polygon(vert) data into by verts data
  1918. function mapByPolygonVertexToByVertex( data, indices, stride ) {
  1919. var tmp = {};
  1920. var res = [];
  1921. var max = 0;
  1922. for ( var i = 0; i < indices.length; ++ i ) {
  1923. if ( indices[ i ] in tmp ) {
  1924. continue;
  1925. }
  1926. tmp[ indices[ i ] ] = {};
  1927. for ( var j = 0; j < stride; ++ j ) {
  1928. tmp[ indices[ i ] ][ j ] = data[ i * stride + j ];
  1929. }
  1930. max = max < indices[ i ] ? indices[ i ] : max;
  1931. }
  1932. try {
  1933. for ( i = 0; i <= max; i ++ ) {
  1934. for ( var s = 0; s < stride; s ++ ) {
  1935. res.push( tmp[ i ][ s ] );
  1936. }
  1937. }
  1938. } catch ( e ) {
  1939. //console.log( max );
  1940. //console.log( tmp );
  1941. //console.log( i );
  1942. //console.log( e );
  1943. }
  1944. return res;
  1945. }
  1946. // AUTODESK uses broken clock. i guess
  1947. function FBXTimeToSeconds( adskTime ) {
  1948. return adskTime / 46186158000;
  1949. }
  1950. function degToRad( degrees ) {
  1951. return degrees * Math.PI / 180;
  1952. }
  1953. function quatFromVec( x, y, z ) {
  1954. var euler = new THREE.Euler( x, y, z, 'ZYX' );
  1955. var quat = new THREE.Quaternion();
  1956. quat.setFromEuler( euler );
  1957. return quat;
  1958. }
  1959. function parseArrayToInt( string ) {
  1960. return string.split( ',' ).map( function ( element ) {
  1961. return parseInt( element );
  1962. } );
  1963. }
  1964. function parseArrayToFloat( string ) {
  1965. return string.split( ',' ).map( function ( element ) {
  1966. return parseFloat( element );
  1967. } );
  1968. }
  1969. function parseArrayToRadians( string ) {
  1970. return string.split( ',' ).map( function ( element ) {
  1971. return degToRad( parseFloat( element ) );
  1972. } );
  1973. }
  1974. function parseArrayToMatrix( string ) {
  1975. var arr = parseArrayToFloat( string );
  1976. return new THREE.Matrix4().fromArray( arr );
  1977. }
  1978. } )();