ObJS.js 17 KB

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