less copy protection, more size visualization
Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.
 
 
 

630 строки
19 KiB

  1. let selected = null;
  2. let selectedEntity = null;
  3. let entityIndex = 0;
  4. let clicked = null;
  5. let dragging = false;
  6. let clickTimeout = null;
  7. let dragOffsetX = null;
  8. let dragOffsetY = null;
  9. let altHeld = false;
  10. const unitChoices = {
  11. length: [
  12. "meters",
  13. "kilometers",
  14. "feet",
  15. "miles",
  16. ],
  17. mass: [
  18. "kilograms"
  19. ]
  20. }
  21. const config = {
  22. height: math.unit(10, "meters"),
  23. minLineSize: 50,
  24. maxLineSize: 250
  25. }
  26. const entities = {
  27. }
  28. function constrainRel(coords) {
  29. return {
  30. x: Math.min(Math.max(coords.x, 0), 1),
  31. y: Math.min(Math.max(coords.y, 0), 1)
  32. }
  33. }
  34. function snapRel(coords) {
  35. return constrainRel({
  36. x: coords.x,
  37. y: altHeld ? coords.y : (Math.abs(coords.y - 1) < 0.05 ? 1 : coords.y)
  38. });
  39. }
  40. function adjustAbs(coords, oldHeight, newHeight) {
  41. return { x: coords.x, y: 1 + (coords.y - 1) * math.divide(oldHeight, newHeight) };
  42. }
  43. function rel2abs(coords) {
  44. const canvasWidth = document.querySelector("#display").clientWidth - 50;
  45. const canvasHeight = document.querySelector("#display").clientHeight - 50;
  46. return { x: coords.x * canvasWidth, y: coords.y * canvasHeight };
  47. }
  48. function abs2rel(coords) {
  49. const canvasWidth = document.querySelector("#display").clientWidth - 50;
  50. const canvasHeight = document.querySelector("#display").clientHeight - 50;
  51. return { x: coords.x / canvasWidth, y: coords.y / canvasHeight };
  52. }
  53. function updateEntityElement(entity, element) {
  54. const position = rel2abs({ x: element.dataset.x, y: element.dataset.y });
  55. const view = element.dataset.view;
  56. element.style.left = position.x + "px";
  57. element.style.top = position.y + "px";
  58. const canvasHeight = document.querySelector("#display").clientHeight;
  59. const pixels = math.divide(entity.views[view].height, config.height) * (canvasHeight - 100);
  60. element.style.setProperty("--height", pixels + "px");
  61. element.querySelector(".entity-name").innerText = entity.name;
  62. const bottomName = document.querySelector("#bottom-name-" + element.dataset.key);
  63. let entX = document.querySelector("#entities").getBoundingClientRect().x;
  64. bottomName.style.left = position.x + entX + "px";
  65. bottomName.style.top = "95vh";
  66. bottomName.innerText = entity.name;
  67. }
  68. function updateSizes() {
  69. drawScale();
  70. Object.entries(entities).forEach(([key, entity]) => {
  71. const element = document.querySelector("#entity-" + key);
  72. updateEntityElement(entity, element);
  73. });
  74. }
  75. function drawScale() {
  76. function drawTicks(/** @type {CanvasRenderingContext2D} */ ctx, pixelsPer, heightPer) {
  77. let total = heightPer.clone();
  78. total.value = 0;
  79. for (let y = ctx.canvas.clientHeight - 50; y >= 50; y -= pixelsPer) {
  80. drawTick(ctx, 50, y, total);
  81. total = math.add(total, heightPer);
  82. }
  83. }
  84. function drawTick(/** @type {CanvasRenderingContext2D} */ ctx, x, y, value) {
  85. const oldStroke = ctx.strokeStyle;
  86. const oldFill = ctx.fillStyle;
  87. ctx.beginPath();
  88. ctx.moveTo(x, y);
  89. ctx.lineTo(x + 20, y);
  90. ctx.strokeStyle = "#000000";
  91. ctx.stroke();
  92. ctx.beginPath();
  93. ctx.moveTo(x + 20, y);
  94. ctx.lineTo(ctx.canvas.clientWidth - 70, y);
  95. ctx.strokeStyle = "#aaaaaa";
  96. ctx.stroke();
  97. ctx.beginPath();
  98. ctx.moveTo(ctx.canvas.clientWidth - 70, y);
  99. ctx.lineTo(ctx.canvas.clientWidth - 50, y);
  100. ctx.strokeStyle = "#000000";
  101. ctx.stroke();
  102. const oldFont = ctx.font;
  103. ctx.font = 'normal 24pt coda';
  104. ctx.fillStyle = "#dddddd";
  105. ctx.beginPath();
  106. ctx.fillText(value.format({ precision: 3 }), x + 20, y + 35);
  107. ctx.font = oldFont;
  108. ctx.strokeStyle = oldStroke;
  109. ctx.fillStyle = oldFill;
  110. }
  111. const canvas = document.querySelector("#display");
  112. /** @type {CanvasRenderingContext2D} */
  113. const ctx = canvas.getContext("2d");
  114. let pixelsPer = (ctx.canvas.clientHeight - 100) / config.height.value;
  115. let heightPer = config.height.clone();
  116. heightPer.value = 1;
  117. if (pixelsPer < config.minLineSize) {
  118. heightPer.value /= pixelsPer / config.minLineSize;
  119. pixelsPer = config.minLineSize;
  120. }
  121. if (pixelsPer > config.maxLineSize) {
  122. heightPer.value /= pixelsPer / config.maxLineSize;
  123. pixelsPer = config.maxLineSize;
  124. }
  125. ctx.clearRect(0, 0, canvas.width, canvas.height);
  126. ctx.scale(1, 1);
  127. ctx.canvas.width = canvas.clientWidth;
  128. ctx.canvas.height = canvas.clientHeight;
  129. ctx.beginPath();
  130. ctx.moveTo(50, 50);
  131. ctx.lineTo(50, ctx.canvas.clientHeight - 50);
  132. ctx.stroke();
  133. ctx.beginPath();
  134. ctx.moveTo(ctx.canvas.clientWidth - 50, 50);
  135. ctx.lineTo(ctx.canvas.clientWidth - 50, ctx.canvas.clientHeight - 50);
  136. ctx.stroke();
  137. drawTicks(ctx, pixelsPer, heightPer);
  138. }
  139. function makeFen() {
  140. const views = {
  141. body: {
  142. attributes: {
  143. height: {
  144. name: "Height",
  145. power: 1,
  146. type: "length",
  147. base: math.unit(1, "meter")
  148. },
  149. weight: {
  150. name: "Weight",
  151. power: 3,
  152. type: "mass",
  153. base: math.unit(80, "kg")
  154. }
  155. },
  156. image: "./silhouette.png",
  157. name: "Body"
  158. },
  159. pepper: {
  160. attributes: {
  161. height: {
  162. name: "Height",
  163. power: 1,
  164. type: "length",
  165. base: math.unit(50, "centimeter")
  166. },
  167. weight: {
  168. name: "Weight",
  169. power: 3,
  170. type: "mass",
  171. base: math.unit(1, "kg")
  172. }
  173. },
  174. image: "./pepper.png",
  175. name: "Pepper"
  176. }
  177. };
  178. return makeEntity("Fen", "Fen", views);
  179. }
  180. function makeEntity(name, author, views) {
  181. const entityTemplate = {
  182. name: name,
  183. author: author,
  184. scale: 1,
  185. views: views,
  186. init: function () {
  187. Object.values(this.views).forEach(view => {
  188. view.parent = this;
  189. Object.entries(view.attributes).forEach(([key, val]) => {
  190. Object.defineProperty(
  191. view,
  192. key,
  193. {
  194. get: function() {
  195. return math.multiply(Math.pow(this.parent.scale, this.attributes[key].power), this.attributes[key].base);
  196. },
  197. set: function(value) {
  198. const newScale = Math.pow(math.divide(value, this.attributes[key].base), 1 / this.attributes[key].power);
  199. this.parent.scale = newScale;
  200. }
  201. }
  202. )
  203. });
  204. });
  205. delete this.init;
  206. return this;
  207. }
  208. }.init();
  209. return entityTemplate;
  210. }
  211. function clickDown(target, x, y) {
  212. clicked = target;
  213. const rect = target.getBoundingClientRect();
  214. let entX = document.querySelector("#entities").getBoundingClientRect().x;
  215. let entY = document.querySelector("#entities").getBoundingClientRect().y;
  216. dragOffsetX = x - rect.left + entX;
  217. dragOffsetY = y - rect.top + entY;
  218. clickTimeout = setTimeout(() => { dragging = true }, 200)
  219. }
  220. function clickUp() {
  221. clearTimeout(clickTimeout);
  222. if (clicked) {
  223. if (dragging) {
  224. dragging = false;
  225. } else {
  226. select(clicked);
  227. }
  228. clicked = null;
  229. }
  230. }
  231. function deselect() {
  232. if (selected) {
  233. selected.classList.remove("selected");
  234. }
  235. selected = null;
  236. clearViewList();
  237. clearEntityOptions();
  238. clearViewOptions();
  239. }
  240. function select(target) {
  241. deselect();
  242. selected = target;
  243. selectedEntity = entities[target.dataset.key];
  244. selected.classList.add("selected");
  245. entityInfo(selectedEntity, target.dataset.view);
  246. configViewList(selectedEntity, target.dataset.view);
  247. configEntityOptions(selectedEntity, target.dataset.view);
  248. configViewOptions(selectedEntity, target.dataset.view);
  249. }
  250. function entityInfo(entity, view) {
  251. document.querySelector("#entity-name").innerText = "Name: " + entity.name;
  252. document.querySelector("#entity-author").innerText = "Author: " + entity.author;
  253. document.querySelector("#entity-height").innerText = "Height: " + entity.views[view].height.format({ precision: 3 });
  254. }
  255. function configViewList(entity, selectedView) {
  256. const list = document.querySelector("#entity-view");
  257. list.innerHTML = "";
  258. list.style.display = "block";
  259. Object.keys(entity.views).forEach(view => {
  260. const option = document.createElement("option");
  261. option.innerText = entity.views[view].name;
  262. option.value = view;
  263. if (view === selectedView) {
  264. option.selected = true;
  265. }
  266. list.appendChild(option);
  267. });
  268. }
  269. function clearViewList() {
  270. const list = document.querySelector("#entity-view");
  271. list.innerHTML = "";
  272. list.style.display = "none";
  273. }
  274. function configEntityOptions(entity, view) {
  275. const holder = document.querySelector("#options-entity");
  276. holder.innerHTML = "";
  277. const scaleLabel = document.createElement("div");
  278. scaleLabel.classList.add("options-label");
  279. scaleLabel.innerText = "Scale";
  280. const scaleRow = document.createElement("div");
  281. scaleRow.classList.add("options-row");
  282. const scaleInput = document.createElement("input");
  283. scaleInput.classList.add("options-field-numeric");
  284. scaleInput.id = "options-entity-scale";
  285. scaleInput.addEventListener("input", e => {
  286. entity.scale = e.target.value;
  287. updateSizes();
  288. updateEntityOptions(entity, view);
  289. updateViewOptions(entity, view);
  290. });
  291. scaleInput.setAttribute("min", 1);
  292. scaleInput.setAttribute("type", "number");
  293. scaleInput.value = entity.scale;
  294. scaleRow.appendChild(scaleInput);
  295. holder.appendChild(scaleLabel);
  296. holder.appendChild(scaleRow);
  297. const nameLabel = document.createElement("div");
  298. nameLabel.classList.add("options-label");
  299. nameLabel.innerText = "Name";
  300. const nameRow = document.createElement("div");
  301. nameRow.classList.add("options-row");
  302. const nameInput = document.createElement("input");
  303. nameInput.classList.add("options-field-text");
  304. nameInput.value = entity.name;
  305. nameInput.addEventListener("input", e => {
  306. entity.name = e.target.value;
  307. updateSizes();
  308. })
  309. nameRow.appendChild(nameInput);
  310. holder.appendChild(nameLabel);
  311. holder.appendChild(nameRow);
  312. }
  313. function updateEntityOptions(entity, view) {
  314. const scaleInput = document.querySelector("#options-entity-scale");
  315. scaleInput.value = entity.scale;
  316. }
  317. function clearEntityOptions() {
  318. const holder = document.querySelector("#options-entity");
  319. holder.innerHTML = "";
  320. }
  321. function configViewOptions(entity, view) {
  322. const holder = document.querySelector("#options-view");
  323. holder.innerHTML = "";
  324. Object.entries(entity.views[view].attributes).forEach(([key, val]) => {
  325. const label = document.createElement("div");
  326. label.classList.add("options-label");
  327. label.innerText = val.name;
  328. holder.appendChild(label);
  329. const row = document.createElement("div");
  330. row.classList.add("options-row");
  331. holder.appendChild(row);
  332. const input = document.createElement("input");
  333. input.classList.add("options-field-numeric");
  334. input.id = "options-view-" + key + "-input";
  335. input.setAttribute("type", "number");
  336. input.setAttribute("min", 1);
  337. input.value = entity.views[view][key].value;
  338. const select = document.createElement("select");
  339. select.id = "options-view-" + key + "-select"
  340. unitChoices[val.type].forEach(name => {
  341. const option = document.createElement("option");
  342. option.innerText = name;
  343. select.appendChild(option);
  344. });
  345. input.addEventListener("input", e => {
  346. entity.views[view][key] = math.unit(input.value, select.value);
  347. updateSizes();
  348. updateEntityOptions(entity, view);
  349. updateViewOptions(entity, view, key);
  350. });
  351. select.addEventListener("input", e => {
  352. entity.views[view][key] = math.unit(input.value, select.value);
  353. updateSizes();
  354. updateEntityOptions(entity, view);
  355. updateViewOptions(entity, view, key);
  356. });
  357. row.appendChild(input);
  358. row.appendChild(select);
  359. });
  360. }
  361. function updateViewOptions(entity, view, changed) {
  362. Object.entries(entity.views[view].attributes).forEach(([key, val]) => {
  363. if (key != changed) {
  364. const input = document.querySelector("#options-view-" + key + "-input");
  365. const select = document.querySelector("#options-view-" + key + "-select");
  366. const currentUnit = select.value;
  367. const convertedAmount = entity.views[view][key].to(currentUnit);
  368. console.log(convertedAmount);
  369. input.value = math.round(convertedAmount.value, 5);
  370. }
  371. });
  372. }
  373. function clearViewOptions() {
  374. const holder = document.querySelector("#options-view");
  375. holder.innerHTML = "";
  376. }
  377. // this is a crime against humanity, and also stolen from
  378. // stack overflow
  379. // https://stackoverflow.com/questions/38487569/click-through-png-image-only-if-clicked-coordinate-is-transparent
  380. const testCanvas = document.createElement("canvas");
  381. testCanvas.id = "test-canvas";
  382. const testCtx = testCanvas.getContext("2d");
  383. function testClick(event) {
  384. const target = event.target;
  385. // Get click coordinates
  386. var x = event.clientX - target.getBoundingClientRect().x,
  387. y = event.clientY - target.getBoundingClientRect().y,
  388. w = testCtx.canvas.width = target.width,
  389. h = testCtx.canvas.height = target.height,
  390. alpha;
  391. // Draw image to canvas
  392. // and read Alpha channel value
  393. testCtx.drawImage(target, 0, 0, w, h);
  394. alpha = testCtx.getImageData(x, y, 1, 1).data[3]; // [0]R [1]G [2]B [3]A
  395. // If pixel is transparent,
  396. // retrieve the element underneath and trigger it's click event
  397. if (alpha === 0) {
  398. const oldDisplay = target.style.display;
  399. target.style.display = "none";
  400. const newTarget = document.elementFromPoint(event.clientX, event.clientY);
  401. newTarget.dispatchEvent(new MouseEvent(event.type, {
  402. "clientX": event.clientX,
  403. "clientY": event.clientY
  404. }));
  405. target.style.display = oldDisplay;
  406. } else {
  407. clickDown(target.parentElement, event.clientX, event.clientY);
  408. }
  409. }
  410. function displayEntity(entity, view, x, y) {
  411. const box = document.createElement("div");
  412. box.classList.add("entity-box");
  413. const img = document.createElement("img");
  414. img.classList.add("entity-image");
  415. const nameTag = document.createElement("div");
  416. nameTag.classList.add("entity-name");
  417. nameTag.innerText = entity.name;
  418. box.appendChild(img);
  419. box.appendChild(nameTag);
  420. img.src = entity.views[view].image
  421. box.dataset.x = x;
  422. box.dataset.y = y;
  423. img.addEventListener("mousedown", e => { testClick(e); e.stopPropagation() });
  424. img.addEventListener("touchstart", e => {
  425. const fakeEvent = {
  426. target: e.target,
  427. clientX: e.touches[0].clientX,
  428. clientY: e.touches[0].clientY
  429. };
  430. testClick(fakeEvent);});
  431. box.id = "entity-" + entityIndex;
  432. box.dataset.key = entityIndex;
  433. box.dataset.view = view;
  434. entities[entityIndex] = entity;
  435. const world = document.querySelector("#entities");
  436. world.appendChild(box);
  437. const bottomName = document.createElement("div");
  438. bottomName.classList.add("bottom-name");
  439. bottomName.id = "bottom-name-" + entityIndex;
  440. bottomName.innerText = entity.name;
  441. bottomName.addEventListener("click", () => select(box));
  442. world.appendChild(bottomName);
  443. entityIndex += 1;
  444. updateEntityElement(entity, box);
  445. }
  446. document.addEventListener("DOMContentLoaded", () => {
  447. for (let x = 0; x < 5; x++) {
  448. const entity = makeFen();
  449. const x = 0.25 + Math.random() * 0.5;
  450. const y = 0.25 + Math.random() * 0.5;
  451. displayEntity(entity, "body", x, y);
  452. }
  453. document.querySelector("body").appendChild(testCtx.canvas);
  454. updateSizes();
  455. document.querySelector("#options-height-value").addEventListener("input", e => {
  456. updateWorldHeight();
  457. })
  458. document.querySelector("#options-height-unit").addEventListener("input", e => {
  459. updateWorldHeight();
  460. })
  461. world.addEventListener("mousedown", e => deselect());
  462. document.addEventListener("mouseup", e => clickUp());
  463. document.addEventListener("touchend", e => clickUp());
  464. document.querySelector("#entity-view").addEventListener("input", e => {
  465. selected.dataset.view = e.target.value
  466. selected.querySelector(".entity-image").src = entities[selected.dataset.key].views[e.target.value].image;
  467. updateSizes();
  468. updateEntityOptions(entities[selected.dataset.key], e.target.value);
  469. updateViewOptions(entities[selected.dataset.key], e.target.value);
  470. });
  471. clearViewList();
  472. });
  473. window.addEventListener("resize", () => {
  474. updateSizes();
  475. })
  476. document.addEventListener("mousemove", (e) => {
  477. if (clicked) {
  478. const position = snapRel(abs2rel({ x: e.clientX - dragOffsetX, y: e.clientY - dragOffsetY }));
  479. clicked.dataset.x = position.x;
  480. clicked.dataset.y = position.y;
  481. updateEntityElement(entities[clicked.dataset.key], clicked);
  482. }
  483. });
  484. document.addEventListener("touchmove", (e) => {
  485. if (clicked) {
  486. e.preventDefault();
  487. let x = e.touches[0].clientX;
  488. let y = e.touches[0].clientY;
  489. const position = snapRel(abs2rel({ x: x - dragOffsetX, y: y - dragOffsetY }));
  490. clicked.dataset.x = position.x;
  491. clicked.dataset.y = position.y;
  492. updateEntityElement(entities[clicked.dataset.key], clicked);
  493. }
  494. }, {passive: false});
  495. function updateWorldHeight() {
  496. const value = Math.max(1, document.querySelector("#options-height-value").value);
  497. const unit = document.querySelector("#options-height-unit").value;
  498. const oldHeight = config.height;
  499. config.height = math.unit(value + " " + unit)
  500. Object.entries(entities).forEach(([key, entity]) => {
  501. const element = document.querySelector("#entity-" + key);
  502. const newPosition = adjustAbs({ x: element.dataset.x, y: element.dataset.y }, oldHeight, config.height);
  503. element.dataset.x = newPosition.x;
  504. element.dataset.y = newPosition.y;
  505. });
  506. updateSizes();
  507. }