FBXLoader.js 72 KB

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