ObJS.js 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503
  1. /********************************************************************
  2. * The ObJS objectnitializes the canvas, assignin it to the HTML *
  3. * element, and set the required mouse events. *
  4. * #parameters: none *
  5. * #return: nothing *
  6. ********************************************************************/
  7. function ObJS(file, canv){
  8. /********************************************************************
  9. * Parameters for costumization. *
  10. ********************************************************************/
  11. var backColor = "rgba(200, 200, 200, 1)";
  12. var vertColor = "rgba(10, 10, 10, 1)";
  13. var edgeColor = "rgba(100, 70, 70, 1)";
  14. var faceColor = "rgba(180, 180, 255, .6)";
  15. var faceAlpha = .6;
  16. var textColor = "rgba(0, 0, 0, 1)";
  17. var vertSize = 4; //Make it even: at small scales will look better
  18. var rotationSpeed = 100; //Smaller = faster. 100 is a good speed
  19. var zoomSpeed = 0.2; //0-1. 0.2 or 0.3 are good speeds
  20. /********************************************************************
  21. * Variable containing this object, to be refered from nested *
  22. * functions. *
  23. ********************************************************************/
  24. var thisObJS;
  25. /********************************************************************
  26. * Parameter used to scale the measures in the .obj file. Can be *
  27. * integer or float, greater than 0. 50 is a good default. *
  28. ********************************************************************/
  29. var scale;
  30. /********************************************************************
  31. * Variable to determine if the canvas has been initialized. *
  32. ********************************************************************/
  33. var canvasInitialized = false;
  34. /********************************************************************
  35. * Variable to determine if the mouse button is being holded down. *
  36. ********************************************************************/
  37. var mDown = false;
  38. /********************************************************************
  39. * Variables containing the canvas and its context. *
  40. ********************************************************************/
  41. var canvas;
  42. var ctx;
  43. /********************************************************************
  44. * Variables containing the number of elements. *
  45. ********************************************************************/
  46. var totalVert;
  47. var totalEdge;//TODO: I dont know how to calculate. And I dont need it
  48. var totalFace
  49. /********************************************************************
  50. * Arrays containing the vertices, edges and faces. *
  51. ********************************************************************/
  52. var obj; //Unused
  53. var vert;
  54. var face;
  55. /********************************************************************
  56. * Booleans to determine wich elements are to draw. *
  57. ********************************************************************/
  58. var dVerts = true;
  59. var dEdges = true;
  60. var dFaces = true;
  61. var dBackg = true;
  62. /********************************************************************
  63. * Global variables that will contain the position of the mouse in *
  64. * the previous frame to calculate rotation. *
  65. ********************************************************************/
  66. var pX = null;
  67. var pY = null;
  68. /********************************************************************
  69. * Function that initializes the canvas, assignin it to the HTML *
  70. * element, and set the required mouse events. *
  71. * #parameters: *
  72. * canv (canvas): canvas to use. If omited, the one named *
  73. * named "ObJSCanvas" will be used. *
  74. * #return: nothing *
  75. * #scope: public *
  76. ********************************************************************/
  77. this.initCanvas = function(canv){
  78. console.log(canvasInitialized);
  79. if (!canvasInitialized){
  80. if (canv!= null)
  81. canvas = canv;
  82. else
  83. canvas = document.getElementById("ObJSCanvas");
  84. ctx = canvas.getContext("2d");
  85. ctx.translate(canvas.width / 2, canvas.height / 2);
  86. canvas.onmousedown = function(e){
  87. pX = e.offsetX==undefined?e.layerX:e.offsetX;
  88. pY = e.offsetY==undefined?e.layerY:e.offsetY;
  89. mDown = true;
  90. };
  91. canvas.onmouseup = function(e){
  92. if(mDown)
  93. mouseClick(e);
  94. pX = null;
  95. pY = null;
  96. mDown = false;
  97. };
  98. canvas.onmousemove = function(e){
  99. if(!mDown)
  100. return;
  101. var x = e.offsetX==undefined?e.layerX:e.offsetX;
  102. var y = e.offsetY==undefined?e.layerY:e.offsetY;
  103. thisObJS.rotateY(x - pX);
  104. thisObJS.rotateX(y - pY);
  105. pX = x;
  106. pY = y;
  107. draw();
  108. return false;
  109. };
  110. canvas.addEventListener('mousewheel',function(event){
  111. if (event.wheelDelta > 0)
  112. thisObJS.zoom("-");
  113. else
  114. thisObJS.zoom("+");
  115. return false;
  116. }, false);
  117. canvasInitialized = true;
  118. }
  119. };
  120. /********************************************************************
  121. * Main function, called every time a file is to be loaded. *
  122. * #parameters: *
  123. * file (string): name of the file, without path or extension. *
  124. * #return: nothing *
  125. * #scope: public *
  126. ********************************************************************/
  127. this.load = function(file){
  128. //Get file
  129. xmlhttp = new XMLHttpRequest();
  130. xmlhttp.open("GET",file, false);
  131. xmlhttp.send();
  132. var fileContent = xmlhttp.responseText;
  133. initArrays();
  134. readVerts(fileContent);
  135. readFaces(fileContent);
  136. draw();
  137. };
  138. /********************************************************************
  139. * Function switching the elements to draw (dVerts, dEdges, dFaces) *
  140. * #parameters: *
  141. * name (string): key to the element to draw. *
  142. * value (boolean): indicating if the element is to be drawn. *
  143. * #return: nothing *
  144. * #scope: public *
  145. ********************************************************************/
  146. this.drawElement = function(name, value){
  147. switch (name){
  148. case "verts":
  149. dVerts = value;
  150. break;
  151. case "edges":
  152. dEdges = value;
  153. break;
  154. case "faces":
  155. dFaces = value;
  156. break;
  157. case "backg":
  158. dBackg = value;
  159. break;
  160. }
  161. draw();
  162. };
  163. /********************************************************************
  164. * Function that turns a hex color code in RGB. *
  165. * stackoverflow.com/questions/5623838/rgb-to-hex-and-hex-to-rgb *
  166. * #parameters: *
  167. * hex (string): color code, for example "#33ff99" *
  168. * #return: (Array) r, g, b, with their correspondent color. *
  169. * #scope: private *
  170. ********************************************************************/
  171. var hexToRgb = function(hex) {
  172. var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
  173. return result ? {
  174. r: parseInt(result[1], 16),
  175. g: parseInt(result[2], 16),
  176. b: parseInt(result[3], 16)
  177. } : null;
  178. };
  179. /********************************************************************
  180. * Function switching the color of the elements. *
  181. * #parameters: *
  182. * name (string): key to the element to colorize. *
  183. * value (boolean): indicating if the element is to be drawn. *
  184. * #return: nothing *
  185. * #scope: public *
  186. ********************************************************************/
  187. this.colorElement = function(name, value){
  188. var color = hexToRgb(value)
  189. var str = "rgba(" + color.r + ", " + color.g + ", " + color.b + ", 1)"
  190. switch (name){
  191. case "backg":
  192. backColor = "rgba(" + color.r + ", " + color.g + ", " + color.b + ", 1)";
  193. break;
  194. case "verts":
  195. vertColor = "rgba(" + color.r + ", " + color.g + ", " + color.b + ", 1)";
  196. break;
  197. case "edges":
  198. edgeColor = "rgba(" + color.r + ", " + color.g + ", " + color.b + ", 1)";
  199. break;
  200. case "faces":
  201. faceColor = "rgba(" + color.r + ", " + color.g + ", " + color.b + ", " + faceAlpha + ")";
  202. break;
  203. }
  204. draw();
  205. };
  206. /********************************************************************
  207. * Function switching the alpha value of the faces. *
  208. * #parameters: *
  209. * percent (int): Value (0-100) of alpha. Must be processed (0-1) *
  210. * #return: nothing *
  211. * #scope: public *
  212. ********************************************************************/
  213. this.setAlpha = function(percent){
  214. faceAlpha = percent / 100;
  215. faceColor = faceColor.substring(0, faceColor.lastIndexOf(",") + 2) + faceAlpha + ")";
  216. draw();
  217. };
  218. /********************************************************************
  219. * Function that rotates elements in the canvas along the Y axis, *
  220. * calculating the new position for each vertex in the vert array. *
  221. * #parameters: *
  222. * des (int): mouse displacement from the last frame. *
  223. * #return: nothing *
  224. * #scope: public *
  225. ********************************************************************/
  226. this.rotateY = function(des){
  227. for (var i = 0; i < vert.length; i ++) {
  228. var x = vert[i][0];
  229. var z = vert[i][2];
  230. vert[i][0] = x * Math.cos(des / rotationSpeed) - z * Math.sin(des / rotationSpeed);
  231. vert[i][2] = z * Math.cos(des / rotationSpeed) + x * Math.sin(des / rotationSpeed);
  232. }
  233. };
  234. /********************************************************************
  235. * Function that rotates elements in the canvas along the X axis, *
  236. * calculating the new position for each vertex in the vert array. *
  237. * #parameters: *
  238. * des (int): mouse displacement from the last frame. *
  239. * #return: nothing *
  240. * #scope: public *
  241. ********************************************************************/
  242. this.rotateX = function(des){
  243. for (var i = 0; i < vert.length; i ++) {
  244. var y = vert[i][1];
  245. var z = vert[i][2];
  246. vert[i][1] = y * Math.cos(des / rotationSpeed) - z * Math.sin(des / rotationSpeed);
  247. vert[i][2] = z * Math.cos(des / rotationSpeed) + y * Math.sin(des / rotationSpeed);
  248. }
  249. };
  250. /********************************************************************
  251. * Function that changes the scale variable, witch results in a *
  252. * zoom in or zoom out effect. *
  253. * #parameters: none *
  254. * #return: nothing *
  255. * #scope: public *
  256. ********************************************************************/
  257. this.zoom = function(dir){
  258. if (dir == "-")
  259. scale = Math.round(scale * (1 + zoomSpeed));
  260. if (dir == "+")
  261. scale = Math.round(scale * (1 - zoomSpeed));
  262. draw();
  263. };
  264. this.clear = function(){
  265. initArrays();
  266. clearCanvas();
  267. }
  268. /********************************************************************
  269. * Function that clears the canvas and gets it ready to draw on it. *
  270. * #parameters: none *
  271. * #return: nothing *
  272. * #scope: public *
  273. ********************************************************************/
  274. var clearCanvas = function(){
  275. ctx.clearRect(0, 0, canvas.width, canvas.height);
  276. if (dBackg)
  277. ctx.fillStyle = backColor;
  278. else
  279. ctx.fillStyle = "#ffffff";
  280. ctx.fillRect(-canvas.width / 2, -canvas.height / 2, canvas.width, canvas.height);
  281. };
  282. /********************************************************************
  283. * Function initializing the arrays obj, vert and face as empty *
  284. * arrays. *
  285. * #parameters: none *
  286. * #return: nothing *
  287. * #scope: private *
  288. ********************************************************************/
  289. var initArrays = function(){
  290. obj = null;
  291. vert = null;
  292. face = null;
  293. obj = new Array();
  294. vert = new Array();
  295. face = new Array();
  296. };
  297. /********************************************************************
  298. * Function tat populates the vert[] array with and array of three *
  299. * elements, containig the coordinates, with the scale applied. *
  300. * #parameters: *
  301. * text (string): the content of the obj file. *
  302. * #return: nothing *
  303. * #scope: private *
  304. ********************************************************************/
  305. var readVerts = function(text){
  306. var line;
  307. var i = 0;
  308. var max = 0;
  309. var dist;
  310. while (text.indexOf("v ") != -1){
  311. line = text.substring(text.indexOf("v "), text.indexOf("\n", text.indexOf("v ")));
  312. vert[i] = new Array(3);
  313. line = line.substring(2);
  314. vert[i][0] = line.substring(0, line.indexOf(" "));
  315. line = line.substring(line.indexOf(" ") + 1);
  316. vert[i][1] = line.substring(0, line.indexOf(" "));
  317. line = line.substring(line.indexOf(" ") + 1);
  318. vert[i][2] = line;
  319. text = text.substring(text.indexOf("v ") + 1)
  320. dist = Math.sqrt(vert[i][0] * vert[i][0] + vert[i][1] * vert[i][1] + vert[i][2] * vert[i][2]);
  321. if (dist > max)
  322. max = dist;
  323. i = i + 1;
  324. }
  325. scale = calculateScale(max);
  326. totalVert = vert.length;
  327. };
  328. /********************************************************************
  329. * Function that automatically calculates the best scale for the *
  330. * modelermined number of elements, containing the verices that *
  331. * form a face, so the bigest dimension from the object can fit in *
  332. * the smallest dimension of the canvas. *
  333. * #parameters: *
  334. * text (int): the farthest vertex, from the center. *
  335. * #return: (int) The scale to be aplied. *
  336. * #scope: private *
  337. ********************************************************************/
  338. var calculateScale = function(max){
  339. var dim;
  340. if (canvas.width < canvas.height)
  341. dim = canvas.width;
  342. else
  343. dim = canvas.height;
  344. var sc = Math.round((0.95 * dim) / (2 * max));
  345. return sc;
  346. };
  347. /********************************************************************
  348. * Function that populates the face[] array with and array of an *
  349. * undetermined number of elements, containing the verices that *
  350. * form a face. *
  351. * #parameters: *
  352. * text (string): the content of the obj file. *
  353. * #return: nothing *
  354. * #scope: private *
  355. ********************************************************************/
  356. var readFaces = function(text){
  357. var finish = false;
  358. var line;
  359. var i = 0;
  360. var j;
  361. while (text.indexOf("f ") != -1){
  362. line = text.substring(text.indexOf("f "), text.indexOf("\n", text.indexOf("f ")));
  363. line = line.substring(2);
  364. face[i] = new Array();
  365. j = 0;
  366. while(line.indexOf(" ") != -1){
  367. face[i][j] = line.substring(0, line.indexOf(" ")) - 1;
  368. line = line.substring(line.indexOf(" ") + 1);
  369. j = j + 1;
  370. }
  371. face[i][j] = line - 1;
  372. i = i + 1;
  373. text = text.substring(text.indexOf("f ") + 1)
  374. }
  375. totalFace = face.length;
  376. };
  377. /********************************************************************
  378. * Function that compares the average Z coordinate of two faces. *
  379. * Must be used when sorting the face array. *
  380. * #parameters: *
  381. * a (Array): One face. *
  382. * b (Array): The other face. *
  383. * #return: (int) -1, 1 or 0. *
  384. * #scope: private *
  385. ********************************************************************/
  386. var faceComparator = function(a,b){
  387. var aZ;
  388. var bZ;
  389. var i = 0;
  390. var sum = 0.0;
  391. while (i < a.length){
  392. sum = sum + parseFloat(vert[a[i]][2]);
  393. i = i + 1;
  394. }
  395. aZ = sum / parseFloat(i);
  396. i = 0;
  397. sum = 0;
  398. while (i < b.length){
  399. sum = sum + parseFloat(1 * vert[b[i]][2]);
  400. i = i + 1;
  401. }
  402. bZ = sum / parseFloat(i);
  403. if (aZ < bZ) return -1;
  404. if (aZ > bZ) return 1;
  405. return 0;
  406. };
  407. /********************************************************************
  408. * Function that writes text in the corner of the canvas. Must be *
  409. * called when everithing has been drawn. *
  410. * #parameters: none *
  411. * #return: nothing *
  412. * #scope: private *
  413. ********************************************************************/
  414. var writeCredits = function(){
  415. ctx.fillStyle = textColor;
  416. ctx.font = "12px Arial";
  417. var h = canvas.height / 2 - 14;
  418. var w = 10 - (canvas.height / 2);
  419. ctx.fillText("ObJS " + totalVert + " vertizes " + totalFace + " faces", w, h);
  420. };
  421. /********************************************************************
  422. * Function that draws th vertizes, faces and edges in the canvas. *
  423. * #parameters: none *
  424. * #return: nothing *
  425. * #scope: private *
  426. ********************************************************************/
  427. var draw = function(){
  428. face = face.sort(faceComparator).reverse();
  429. clearCanvas();
  430. for (var i = 0; i < face.length; i++){
  431. ctx.strokeStyle = edgeColor;
  432. ctx.fillStyle = vertColor;
  433. ctx.beginPath();
  434. ctx.moveTo(scale * vert[face[i][0]][0], scale * vert[face[i][0]][1]);
  435. for (var j = 1; j < face[i].length; j++) {
  436. ctx.lineTo(scale * vert[face[i][j]][0], scale * vert[face[i][j]][1]);
  437. if(dEdges)
  438. ctx.stroke();
  439. if(dVerts){
  440. var x = scale * vert[face[i][j]][0] - (vertSize / 2);
  441. var w = vertSize;
  442. var y = scale * vert[face[i][j]][1] - (vertSize / 2);
  443. var h = vertSize;
  444. ctx.fillRect(x, y, w, h);
  445. }
  446. }
  447. ctx.closePath();
  448. ctx.fillStyle = faceColor;
  449. if(dFaces)
  450. ctx.fill();
  451. }
  452. writeCredits();
  453. };
  454. /********************************************************************
  455. * TODO: Function used when something in the canvas is clicked. *
  456. * #parameters: none *
  457. * #return: nothing *
  458. * #scope: private *
  459. ********************************************************************/
  460. var mouseClick = function(){
  461. };
  462. thisObJS = this;
  463. return this;
  464. }