FBXLoader.js 57 KB

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