FBXLoader.js 57 KB

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