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

1085 строки
32 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 shiftHeld = false;
  10. let altHeld = false;
  11. const unitChoices = {
  12. length: [
  13. "meters",
  14. "millimeters",
  15. "centimeters",
  16. "kilometers",
  17. "inches",
  18. "feet",
  19. "stories",
  20. "miles",
  21. "parsecs",
  22. ],
  23. area: [
  24. "meters^2",
  25. "cm^2",
  26. "kilometers^2",
  27. "acres",
  28. "miles^2"
  29. ],
  30. mass: [
  31. "kilograms",
  32. "lbs",
  33. "tons"
  34. ]
  35. }
  36. const config = {
  37. height: math.unit(1500, "meters"),
  38. minLineSize: 50,
  39. maxLineSize: 250,
  40. autoFit: false
  41. }
  42. const availableEntities = {
  43. }
  44. const entities = {
  45. }
  46. function constrainRel(coords) {
  47. return {
  48. x: Math.min(Math.max(coords.x, 0), 1),
  49. y: Math.min(Math.max(coords.y, 0), 1)
  50. }
  51. }
  52. function snapRel(coords) {
  53. return constrainRel({
  54. x: coords.x,
  55. y: altHeld ? coords.y : (Math.abs(coords.y - 1) < 0.05 ? 1 : coords.y)
  56. });
  57. }
  58. function adjustAbs(coords, oldHeight, newHeight) {
  59. return { x: coords.x, y: 1 + (coords.y - 1) * math.divide(oldHeight, newHeight) };
  60. }
  61. function rel2abs(coords) {
  62. const canvasWidth = document.querySelector("#display").clientWidth - 100;
  63. const canvasHeight = document.querySelector("#display").clientHeight - 50;
  64. return { x: coords.x * canvasWidth + 50, y: coords.y * canvasHeight };
  65. }
  66. function abs2rel(coords) {
  67. const canvasWidth = document.querySelector("#display").clientWidth - 100;
  68. const canvasHeight = document.querySelector("#display").clientHeight - 50;
  69. return { x: (coords.x - 50) / canvasWidth, y: coords.y / canvasHeight };
  70. }
  71. function updateEntityElement(entity, element, zIndex) {
  72. const position = rel2abs({ x: element.dataset.x, y: element.dataset.y });
  73. const view = element.dataset.view;
  74. element.style.left = position.x + "px";
  75. element.style.top = position.y + "px";
  76. const canvasHeight = document.querySelector("#display").clientHeight;
  77. const pixels = math.divide(entity.views[view].height, config.height) * (canvasHeight - 100);
  78. const bonus = (entity.views[view].image.extra ? entity.views[view].image.extra : 1);
  79. element.style.setProperty("--height", pixels * bonus + "px");
  80. element.querySelector(".entity-name").innerText = entity.name;
  81. const bottomName = document.querySelector("#bottom-name-" + element.dataset.key);
  82. let entX = document.querySelector("#entities").getBoundingClientRect().x;
  83. bottomName.style.left = position.x + entX + "px";
  84. bottomName.style.top = "95vh";
  85. bottomName.innerText = entity.name;
  86. if (zIndex) {
  87. element.style.zIndex = zIndex;
  88. }
  89. }
  90. function updateSizes() {
  91. drawScale();
  92. let ordered = Object.entries(entities);
  93. ordered.sort((e1, e2) => {
  94. return e1[1].views[e1[1].view].height.toNumber("meters") - e2[1].views[e2[1].view].height.toNumber("meters")
  95. });
  96. let zIndex = ordered.length;
  97. ordered.forEach(entity => {
  98. const element = document.querySelector("#entity-" + entity[0]);
  99. updateEntityElement(entity[1], element, zIndex);
  100. zIndex -= 1;
  101. });
  102. }
  103. function drawScale() {
  104. function drawTicks(/** @type {CanvasRenderingContext2D} */ ctx, pixelsPer, heightPer) {
  105. let total = heightPer.clone();
  106. total.value = 0;
  107. for (let y = ctx.canvas.clientHeight - 50; y >= 50; y -= pixelsPer) {
  108. drawTick(ctx, 50, y, total);
  109. total = math.add(total, heightPer);
  110. }
  111. }
  112. function drawTick(/** @type {CanvasRenderingContext2D} */ ctx, x, y, value) {
  113. const oldStroke = ctx.strokeStyle;
  114. const oldFill = ctx.fillStyle;
  115. ctx.beginPath();
  116. ctx.moveTo(x, y);
  117. ctx.lineTo(x + 20, y);
  118. ctx.strokeStyle = "#000000";
  119. ctx.stroke();
  120. ctx.beginPath();
  121. ctx.moveTo(x + 20, y);
  122. ctx.lineTo(ctx.canvas.clientWidth - 70, y);
  123. ctx.strokeStyle = "#aaaaaa";
  124. ctx.stroke();
  125. ctx.beginPath();
  126. ctx.moveTo(ctx.canvas.clientWidth - 70, y);
  127. ctx.lineTo(ctx.canvas.clientWidth - 50, y);
  128. ctx.strokeStyle = "#000000";
  129. ctx.stroke();
  130. const oldFont = ctx.font;
  131. ctx.font = 'normal 24pt coda';
  132. ctx.fillStyle = "#dddddd";
  133. ctx.beginPath();
  134. ctx.fillText(value.format({ precision: 3 }), x + 20, y + 35);
  135. ctx.font = oldFont;
  136. ctx.strokeStyle = oldStroke;
  137. ctx.fillStyle = oldFill;
  138. }
  139. const canvas = document.querySelector("#display");
  140. /** @type {CanvasRenderingContext2D} */
  141. const ctx = canvas.getContext("2d");
  142. let pixelsPer = (ctx.canvas.clientHeight - 100) / config.height.value;
  143. let heightPer = config.height.clone();
  144. heightPer.value = 1;
  145. if (pixelsPer < config.minLineSize) {
  146. heightPer.value /= pixelsPer / config.minLineSize;
  147. pixelsPer = config.minLineSize;
  148. }
  149. if (pixelsPer > config.maxLineSize) {
  150. heightPer.value /= pixelsPer / config.maxLineSize;
  151. pixelsPer = config.maxLineSize;
  152. }
  153. ctx.clearRect(0, 0, canvas.width, canvas.height);
  154. ctx.scale(1, 1);
  155. ctx.canvas.width = canvas.clientWidth;
  156. ctx.canvas.height = canvas.clientHeight;
  157. ctx.beginPath();
  158. ctx.moveTo(50, 50);
  159. ctx.lineTo(50, ctx.canvas.clientHeight - 50);
  160. ctx.stroke();
  161. ctx.beginPath();
  162. ctx.moveTo(ctx.canvas.clientWidth - 50, 50);
  163. ctx.lineTo(ctx.canvas.clientWidth - 50, ctx.canvas.clientHeight - 50);
  164. ctx.stroke();
  165. drawTicks(ctx, pixelsPer, heightPer);
  166. }
  167. function makeEntity(name, author, views) {
  168. const entityTemplate = {
  169. name: name,
  170. identifier: name,
  171. author: author,
  172. scale: 1,
  173. views: views,
  174. defaults: [],
  175. init: function () {
  176. Object.entries(this.views).forEach(([viewKey, view]) => {
  177. view.parent = this;
  178. if (this.defaultView === undefined) {
  179. this.defaultView = viewKey;
  180. }
  181. Object.entries(view.attributes).forEach(([key, val]) => {
  182. Object.defineProperty(
  183. view,
  184. key,
  185. {
  186. get: function () {
  187. return math.multiply(Math.pow(this.parent.scale, this.attributes[key].power), this.attributes[key].base);
  188. },
  189. set: function (value) {
  190. const newScale = Math.pow(math.divide(value, this.attributes[key].base), 1 / this.attributes[key].power);
  191. this.parent.scale = newScale;
  192. }
  193. }
  194. )
  195. });
  196. });
  197. delete this.init;
  198. return this;
  199. }
  200. }.init();
  201. return entityTemplate;
  202. }
  203. function clickDown(target, x, y) {
  204. clicked = target;
  205. const rect = target.getBoundingClientRect();
  206. let entX = document.querySelector("#entities").getBoundingClientRect().x;
  207. let entY = document.querySelector("#entities").getBoundingClientRect().y;
  208. dragOffsetX = x - rect.left + entX;
  209. dragOffsetY = y - rect.top + entY;
  210. clickTimeout = setTimeout(() => { dragging = true }, 200)
  211. }
  212. // could we make this actually detect the menu area?
  213. function hoveringInDeleteArea(e) {
  214. return e.clientY < document.body.clientHeight / 10;
  215. }
  216. function clickUp(e) {
  217. clearTimeout(clickTimeout);
  218. if (clicked) {
  219. if (dragging) {
  220. dragging = false;
  221. if (hoveringInDeleteArea(e)) {
  222. removeEntity(clicked);
  223. document.querySelector("#menubar").classList.remove("hover-delete");
  224. }
  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. configViewList(selectedEntity, target.dataset.view);
  246. configEntityOptions(selectedEntity, target.dataset.view);
  247. configViewOptions(selectedEntity, target.dataset.view);
  248. }
  249. function configViewList(entity, selectedView) {
  250. const list = document.querySelector("#entity-view");
  251. list.innerHTML = "";
  252. list.style.display = "block";
  253. Object.keys(entity.views).forEach(view => {
  254. const option = document.createElement("option");
  255. option.innerText = entity.views[view].name;
  256. option.value = view;
  257. if (view === selectedView) {
  258. option.selected = true;
  259. }
  260. list.appendChild(option);
  261. });
  262. }
  263. function clearViewList() {
  264. const list = document.querySelector("#entity-view");
  265. list.innerHTML = "";
  266. list.style.display = "none";
  267. }
  268. function updateWorldOptions(entity, view) {
  269. const heightInput = document.querySelector("#options-height-value");
  270. const heightSelect = document.querySelector("#options-height-unit");
  271. const converted = config.height.toNumber(heightSelect.value);
  272. heightInput.value = math.round(converted, 3);
  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 == 0 ? 1 : e.target.value;
  287. if (config.autoFit) {
  288. fitWorld();
  289. }
  290. updateSizes();
  291. updateEntityOptions(entity, view);
  292. updateViewOptions(entity, view);
  293. });
  294. scaleInput.setAttribute("min", 1);
  295. scaleInput.setAttribute("type", "number");
  296. scaleInput.value = entity.scale;
  297. scaleRow.appendChild(scaleInput);
  298. holder.appendChild(scaleLabel);
  299. holder.appendChild(scaleRow);
  300. const nameLabel = document.createElement("div");
  301. nameLabel.classList.add("options-label");
  302. nameLabel.innerText = "Name";
  303. const nameRow = document.createElement("div");
  304. nameRow.classList.add("options-row");
  305. const nameInput = document.createElement("input");
  306. nameInput.classList.add("options-field-text");
  307. nameInput.value = entity.name;
  308. nameInput.addEventListener("input", e => {
  309. entity.name = e.target.value;
  310. updateSizes();
  311. })
  312. nameRow.appendChild(nameInput);
  313. holder.appendChild(nameLabel);
  314. holder.appendChild(nameRow);
  315. const defaultHolder = document.querySelector("#options-entity-defaults");
  316. defaultHolder.innerHTML = "";
  317. entity.defaults.forEach(defaultInfo => {
  318. const button = document.createElement("button");
  319. button.classList.add("options-button");
  320. button.innerText = defaultInfo.name;
  321. button.addEventListener("click", e => {
  322. entity.views[entity.defaultView].height = defaultInfo.height;
  323. updateEntityOptions(entity, view);
  324. updateViewOptions(entity, view);
  325. updateSizes();
  326. });
  327. defaultHolder.appendChild(button);
  328. });
  329. }
  330. function updateEntityOptions(entity, view) {
  331. const scaleInput = document.querySelector("#options-entity-scale");
  332. scaleInput.value = entity.scale;
  333. }
  334. function clearEntityOptions() {
  335. const holder = document.querySelector("#options-entity");
  336. holder.innerHTML = "";
  337. document.querySelector("#options-entity-defaults").innerHTML = "";
  338. }
  339. function configViewOptions(entity, view) {
  340. const holder = document.querySelector("#options-view");
  341. holder.innerHTML = "";
  342. Object.entries(entity.views[view].attributes).forEach(([key, val]) => {
  343. const label = document.createElement("div");
  344. label.classList.add("options-label");
  345. label.innerText = val.name;
  346. holder.appendChild(label);
  347. const row = document.createElement("div");
  348. row.classList.add("options-row");
  349. holder.appendChild(row);
  350. const input = document.createElement("input");
  351. input.classList.add("options-field-numeric");
  352. input.id = "options-view-" + key + "-input";
  353. input.setAttribute("type", "number");
  354. input.setAttribute("min", 1);
  355. input.value = entity.views[view][key].value;
  356. const select = document.createElement("select");
  357. select.id = "options-view-" + key + "-select"
  358. unitChoices[val.type].forEach(name => {
  359. const option = document.createElement("option");
  360. option.innerText = name;
  361. select.appendChild(option);
  362. });
  363. input.addEventListener("input", e => {
  364. const value = input.value == 0 ? 1 : input.value;
  365. entity.views[view][key] = math.unit(value, select.value);
  366. if (config.autoFit) {
  367. fitWorld();
  368. }
  369. updateSizes();
  370. updateEntityOptions(entity, view);
  371. updateViewOptions(entity, view, key);
  372. });
  373. select.setAttribute("oldUnit", select.value);
  374. select.addEventListener("input", e => {
  375. const value = input.value == 0 ? 1 : input.value;
  376. const oldUnit = select.getAttribute("oldUnit");
  377. entity.views[view][key] = math.unit(value, oldUnit).to(select.value);
  378. input.value = entity.views[view][key].toNumber(select.value);
  379. select.setAttribute("oldUnit", select.value);
  380. if (config.autoFit) {
  381. fitWorld();
  382. }
  383. updateSizes();
  384. updateEntityOptions(entity, view);
  385. updateViewOptions(entity, view, key);
  386. });
  387. row.appendChild(input);
  388. row.appendChild(select);
  389. });
  390. }
  391. function updateViewOptions(entity, view, changed) {
  392. Object.entries(entity.views[view].attributes).forEach(([key, val]) => {
  393. if (key != changed) {
  394. const input = document.querySelector("#options-view-" + key + "-input");
  395. const select = document.querySelector("#options-view-" + key + "-select");
  396. const currentUnit = select.value;
  397. const convertedAmount = entity.views[view][key].toNumber(currentUnit);
  398. input.value = math.round(convertedAmount, 5);
  399. }
  400. });
  401. }
  402. function clearViewOptions() {
  403. const holder = document.querySelector("#options-view");
  404. holder.innerHTML = "";
  405. }
  406. // this is a crime against humanity, and also stolen from
  407. // stack overflow
  408. // https://stackoverflow.com/questions/38487569/click-through-png-image-only-if-clicked-coordinate-is-transparent
  409. const testCanvas = document.createElement("canvas");
  410. testCanvas.id = "test-canvas";
  411. const testCtx = testCanvas.getContext("2d");
  412. function testClick(event) {
  413. // oh my god I can't believe I'm doing this
  414. const target = event.target;
  415. if (navigator.userAgent.indexOf("Firefox") != -1) {
  416. clickDown(target.parentElement, event.clientX, event.clientY);
  417. return;
  418. }
  419. // Get click coordinates
  420. let w = target.width;
  421. let h = target.height;
  422. let ratioW = 1, ratioH = 1;
  423. // Limit the size of the canvas so that very large images don't cause problems)
  424. if (w > 4000) {
  425. ratioW = w / 4000;
  426. w /= ratioW;
  427. h /= ratioW;
  428. }
  429. if (h > 4000) {
  430. ratioH = h / 4000;
  431. w /= ratioH;
  432. h /= ratioH;
  433. }
  434. const ratio = ratioW * ratioH;
  435. var x = event.clientX - target.getBoundingClientRect().x,
  436. y = event.clientY - target.getBoundingClientRect().y,
  437. alpha;
  438. testCtx.canvas.width = w;
  439. testCtx.canvas.height = h;
  440. // Draw image to canvas
  441. // and read Alpha channel value
  442. testCtx.drawImage(target, 0, 0, w, h);
  443. alpha = testCtx.getImageData(Math.floor(x / ratio), Math.floor(y / ratio), 1, 1).data[3]; // [0]R [1]G [2]B [3]A
  444. // If pixel is transparent,
  445. // retrieve the element underneath and trigger it's click event
  446. if (alpha === 0) {
  447. const oldDisplay = target.style.display;
  448. target.style.display = "none";
  449. const newTarget = document.elementFromPoint(event.clientX, event.clientY);
  450. newTarget.dispatchEvent(new MouseEvent(event.type, {
  451. "clientX": event.clientX,
  452. "clientY": event.clientY
  453. }));
  454. target.style.display = oldDisplay;
  455. } else {
  456. clickDown(target.parentElement, event.clientX, event.clientY);
  457. }
  458. }
  459. function arrangeEntities(order) {
  460. let x = 0.1;
  461. order.forEach(key => {
  462. document.querySelector("#entity-" + key).dataset.x = x;
  463. x += 0.8 / order.length
  464. });
  465. updateSizes();
  466. }
  467. function removeAllEntities() {
  468. Object.keys(entities).forEach(key => {
  469. removeEntity(document.querySelector("#entity-" + key));
  470. });
  471. }
  472. function removeEntity(element) {
  473. delete entities[element.dataset.key];
  474. const bottomName = document.querySelector("#bottom-name-" + element.dataset.key);
  475. bottomName.parentElement.removeChild(bottomName);
  476. element.parentElement.removeChild(element);
  477. }
  478. function displayEntity(entity, view, x, y) {
  479. const box = document.createElement("div");
  480. box.classList.add("entity-box");
  481. const img = document.createElement("img");
  482. img.classList.add("entity-image");
  483. img.addEventListener("dragstart", e => {
  484. e.preventDefault();
  485. });
  486. const nameTag = document.createElement("div");
  487. nameTag.classList.add("entity-name");
  488. nameTag.innerText = entity.name;
  489. box.appendChild(img);
  490. box.appendChild(nameTag);
  491. const image = entity.views[view].image;
  492. img.src = image.source;
  493. if (image.bottom !== undefined) {
  494. img.style.setProperty("--offset", ((-1 + image.bottom) * 100) + "%")
  495. } else {
  496. img.style.setProperty("--offset", ((-1) * 100) + "%")
  497. }
  498. box.dataset.x = x;
  499. box.dataset.y = y;
  500. img.addEventListener("mousedown", e => { testClick(e); e.stopPropagation() });
  501. img.addEventListener("touchstart", e => {
  502. const fakeEvent = {
  503. target: e.target,
  504. clientX: e.touches[0].clientX,
  505. clientY: e.touches[0].clientY
  506. };
  507. testClick(fakeEvent);
  508. });
  509. box.id = "entity-" + entityIndex;
  510. box.dataset.key = entityIndex;
  511. box.dataset.view = view;
  512. entity.view = view;
  513. entities[entityIndex] = entity;
  514. entity.index = entityIndex;
  515. const world = document.querySelector("#entities");
  516. world.appendChild(box);
  517. const bottomName = document.createElement("div");
  518. bottomName.classList.add("bottom-name");
  519. bottomName.id = "bottom-name-" + entityIndex;
  520. bottomName.innerText = entity.name;
  521. bottomName.addEventListener("click", () => select(box));
  522. world.appendChild(bottomName);
  523. entityIndex += 1;
  524. updateEntityElement(entity, box);
  525. if (config.autoFit) {
  526. fitWorld();
  527. }
  528. select(box);
  529. }
  530. document.addEventListener("DOMContentLoaded", () => {
  531. prepareEntities();
  532. const stuff = availableEntities.characters.map(x => x.constructor).filter(x => {
  533. const result = x();
  534. return result.views[result.defaultView].height.toNumber("meters") < 1000;
  535. })
  536. let x = 0.2;
  537. stuff.forEach(entity => {
  538. displayEntity(entity(), entity().defaultView, x, 1);
  539. x += 0.7 / stuff.length;
  540. })
  541. const order = Object.keys(entities).sort((a, b) => {
  542. const entA = entities[a];
  543. const entB = entities[b];
  544. const viewA = document.querySelector("#entity-" + a).dataset.view;
  545. const viewB = document.querySelector("#entity-" + b).dataset.view;
  546. const heightA = entA.views[viewA].height.to("meter").value;
  547. const heightB = entB.views[viewB].height.to("meter").value;
  548. return heightA - heightB;
  549. });
  550. arrangeEntities(order);
  551. fitWorld();
  552. window.addEventListener("wheel", e => {
  553. if (shiftHeld) {
  554. const dir = e.deltaY > 0 ? 0.9 : 1.1;
  555. if (selected) {
  556. const entity = entities[selected.dataset.key];
  557. entity.views[entity.view].height = math.multiply(entity.views[entity.view].height, dir);
  558. updateEntityOptions(entity, entity.view);
  559. updateViewOptions(entity, entity.view);
  560. }
  561. } else {
  562. const dir = e.deltaY < 0 ? 0.9 : 1.1;
  563. config.height = math.multiply(config.height, dir);
  564. updateWorldOptions();
  565. }
  566. checkFitWorld();
  567. updateSizes();
  568. })
  569. document.querySelector("body").appendChild(testCtx.canvas);
  570. updateSizes();
  571. document.querySelector("#options-height-value").addEventListener("input", e => {
  572. updateWorldHeight();
  573. })
  574. document.querySelector("#options-height-unit").addEventListener("input", e => {
  575. checkFitWorld();
  576. updateWorldHeight();
  577. })
  578. world.addEventListener("mousedown", e => deselect());
  579. document.querySelector("#display").addEventListener("mousedown", deselect);
  580. document.addEventListener("mouseup", e => clickUp(e));
  581. document.addEventListener("touchend", e => {
  582. const fakeEvent = {
  583. target: e.target,
  584. clientX: e.changedTouches[0].clientX,
  585. clientY: e.changedTouches[0].clientY
  586. };
  587. clickUp(fakeEvent);
  588. });
  589. document.querySelector("#entity-view").addEventListener("input", e => {
  590. selected.dataset.view = e.target.value;
  591. entities[selected.dataset.key].view = e.target.value;
  592. const image = entities[selected.dataset.key].views[e.target.value].image
  593. selected.querySelector(".entity-image").src = image.source;
  594. if (image.bottom !== undefined) {
  595. selected.querySelector(".entity-image").style.setProperty("--offset", ((-1 + image.bottom) * 100) + "%")
  596. } else {
  597. selected.querySelector(".entity-image").style.setProperty("--offset", ((-1) * 100) + "%")
  598. }
  599. updateSizes();
  600. updateEntityOptions(entities[selected.dataset.key], e.target.value);
  601. updateViewOptions(entities[selected.dataset.key], e.target.value);
  602. });
  603. clearViewList();
  604. document.querySelector("#menu-clear").addEventListener("click", e => {
  605. removeAllEntities();
  606. });
  607. document.querySelector("#menu-order-height").addEventListener("click", e => {
  608. const order = Object.keys(entities).sort((a, b) => {
  609. const entA = entities[a];
  610. const entB = entities[b];
  611. const viewA = document.querySelector("#entity-" + a).dataset.view;
  612. const viewB = document.querySelector("#entity-" + b).dataset.view;
  613. const heightA = entA.views[viewA].height.to("meter").value;
  614. const heightB = entB.views[viewB].height.to("meter").value;
  615. return heightA - heightB;
  616. });
  617. arrangeEntities(order);
  618. });
  619. document.querySelector("#options-world-fit").addEventListener("click", fitWorld);
  620. document.querySelector("#options-world-autofit").addEventListener("input", e => {
  621. config.autoFit = e.target.checked;
  622. if (config.autoFit) {
  623. fitWorld();
  624. }
  625. });
  626. document.addEventListener("keydown", e => {
  627. if (e.key == "Delete") {
  628. if (selected) {
  629. removeEntity(selected);
  630. selected = null;
  631. }
  632. }
  633. })
  634. document.addEventListener("keydown", e => {
  635. if (e.key == "Shift") {
  636. shiftHeld = true;
  637. } else if (e.key == "Alt") {
  638. altHeld = true;
  639. }
  640. });
  641. document.addEventListener("keyup", e => {
  642. if (e.key == "Shift") {
  643. shiftHeld = false;
  644. } else if (e.key == "Alt") {
  645. altHeld = false;
  646. }
  647. });
  648. document.addEventListener("paste", e => {
  649. try {
  650. const data = JSON.parse(e.clipboardData.getData("text"));
  651. console.log(data)
  652. if (data.entities === undefined) {
  653. return;
  654. }
  655. if (data.world === undefined) {
  656. return;
  657. }
  658. importScene(data);
  659. } catch(err) {
  660. console.error(err);
  661. // probably wasn't valid data
  662. }
  663. });
  664. document.querySelector("#menu-export").addEventListener("click", e => {
  665. copyScene();
  666. });
  667. document.querySelector("#menu-save").addEventListener("click", e => {
  668. saveScene();
  669. });
  670. document.querySelector("#menu-load").addEventListener("click", e => {
  671. loadScene();
  672. });
  673. });
  674. function prepareEntities() {
  675. availableEntities["buildings"] = makeBuildings();
  676. availableEntities["landmarks"] = makeLandmarks();
  677. availableEntities["characters"] = makeCharacters();
  678. availableEntities["objects"] = makeObjects();
  679. availableEntities["naturals"] = makeNaturals();
  680. availableEntities["vehicles"] = makeVehicles();
  681. availableEntities["characters"].sort((x,y) => {
  682. return x.name < y.name ? -1 : 1
  683. });
  684. const holder = document.querySelector("#spawners");
  685. const categorySelect = document.createElement("select");
  686. categorySelect.id = "category-picker";
  687. holder.appendChild(categorySelect);
  688. Object.entries(availableEntities).forEach(([category, entityList]) => {
  689. const select = document.createElement("select");
  690. select.id = "create-entity-" + category;
  691. for (let i = 0; i < entityList.length; i++) {
  692. const entity = entityList[i];
  693. const option = document.createElement("option");
  694. option.value = i;
  695. option.innerText = entity.name;
  696. select.appendChild(option);
  697. };
  698. const button = document.createElement("button");
  699. button.id = "create-entity-" + category + "-button";
  700. button.innerText = "Create";
  701. button.addEventListener("click", e => {
  702. const newEntity = entityList[select.value].constructor()
  703. displayEntity(newEntity, newEntity.defaultView, 0.5, 1);
  704. });
  705. const categoryOption = document.createElement("option");
  706. categoryOption.value = category
  707. categoryOption.innerText = category;
  708. if (category == "characters") {
  709. categoryOption.selected = true;
  710. select.classList.add("category-visible");
  711. button.classList.add("category-visible");
  712. }
  713. categorySelect.appendChild(categoryOption);
  714. holder.appendChild(select);
  715. holder.appendChild(button);
  716. });
  717. categorySelect.addEventListener("input", e => {
  718. const oldSelect = document.querySelector("select.category-visible");
  719. oldSelect.classList.remove("category-visible");
  720. const oldButton = document.querySelector("button.category-visible");
  721. oldButton.classList.remove("category-visible");
  722. const newSelect = document.querySelector("#create-entity-" + e.target.value);
  723. newSelect.classList.add("category-visible");
  724. const newButton = document.querySelector("#create-entity-" + e.target.value + "-button");
  725. newButton.classList.add("category-visible");
  726. });
  727. }
  728. window.addEventListener("resize", () => {
  729. updateSizes();
  730. })
  731. document.addEventListener("mousemove", (e) => {
  732. if (clicked) {
  733. const position = snapRel(abs2rel({ x: e.clientX - dragOffsetX, y: e.clientY - dragOffsetY }));
  734. clicked.dataset.x = position.x;
  735. clicked.dataset.y = position.y;
  736. updateEntityElement(entities[clicked.dataset.key], clicked);
  737. if (hoveringInDeleteArea(e)) {
  738. document.querySelector("#menubar").classList.add("hover-delete");
  739. } else {
  740. document.querySelector("#menubar").classList.remove("hover-delete");
  741. }
  742. }
  743. });
  744. document.addEventListener("touchmove", (e) => {
  745. if (clicked) {
  746. e.preventDefault();
  747. let x = e.touches[0].clientX;
  748. let y = e.touches[0].clientY;
  749. const position = snapRel(abs2rel({ x: x - dragOffsetX, y: y - dragOffsetY }));
  750. clicked.dataset.x = position.x;
  751. clicked.dataset.y = position.y;
  752. updateEntityElement(entities[clicked.dataset.key], clicked);
  753. // what a hack
  754. // I should centralize this 'fake event' creation...
  755. if (hoveringInDeleteArea({ clientY: y })) {
  756. document.querySelector("#menubar").classList.add("hover-delete");
  757. } else {
  758. document.querySelector("#menubar").classList.remove("hover-delete");
  759. }
  760. }
  761. }, { passive: false });
  762. function checkFitWorld() {
  763. if (config.autoFit) {
  764. fitWorld();
  765. }
  766. }
  767. function fitWorld() {
  768. let max = math.unit(0, "meters");
  769. Object.entries(entities).forEach(([key, entity]) => {
  770. const view = document.querySelector("#entity-" + key).dataset.view;
  771. max = math.max(max, entity.views[view].height);
  772. });
  773. setWorldHeight(config.height, math.multiply(max, 1.1));
  774. }
  775. function updateWorldHeight() {
  776. const unit = document.querySelector("#options-height-unit").value;
  777. const value = Math.max(0.000000001, document.querySelector("#options-height-value").value);
  778. const oldHeight = config.height;
  779. setWorldHeight(oldHeight, math.unit(value, unit));
  780. }
  781. function setWorldHeight(oldHeight, newHeight) {
  782. config.height = newHeight.to(document.querySelector("#options-height-unit").value)
  783. const unit = document.querySelector("#options-height-unit").value;
  784. document.querySelector("#options-height-value").value = config.height.toNumber(unit);
  785. Object.entries(entities).forEach(([key, entity]) => {
  786. const element = document.querySelector("#entity-" + key);
  787. const newPosition = adjustAbs({ x: element.dataset.x, y: element.dataset.y }, oldHeight, config.height);
  788. element.dataset.x = newPosition.x;
  789. element.dataset.y = newPosition.y;
  790. });
  791. updateSizes();
  792. }
  793. function loadScene() {
  794. try {
  795. const data = JSON.parse(localStorage.getItem("macrovision-save"));
  796. importScene(data);
  797. } catch (err) {
  798. alert("Something went wrong while loading (maybe you didn't have anything saved. Check the F12 console for the error.")
  799. console.error(err);
  800. }
  801. }
  802. function saveScene() {
  803. try {
  804. const string = JSON.stringify(exportScene());
  805. localStorage.setItem("macrovision-save", string);
  806. } catch (err) {
  807. alert("Something went wrong while saving (maybe I don't have localStorage permissions, or exporting failed). Check the F12 console for the error.")
  808. console.error(err);
  809. }
  810. }
  811. function exportScene() {
  812. const results = {};
  813. results.entities = [];
  814. Object.entries(entities).forEach(([key, entity]) => {
  815. const element = document.querySelector("#entity-" + key);
  816. results.entities.push({
  817. name: entity.identifier,
  818. scale: entity.scale,
  819. view: entity.view,
  820. x: element.dataset.x,
  821. y: element.dataset.y
  822. });
  823. });
  824. const unit = document.querySelector("#options-height-unit").value;
  825. results.world = {
  826. height: config.height.toNumber(unit),
  827. unit: unit
  828. }
  829. return results;
  830. }
  831. function copyScene() {
  832. const results = exportScene();
  833. navigator.clipboard.writeText(JSON.stringify(results))
  834. alert("Scene copied to clipboard. Paste text into the page to load the scene.");
  835. }
  836. // TODO - don't just search through every single entity
  837. // probably just have a way to do lookups directly
  838. function findEntity(name) {
  839. const groups = Object.values(availableEntities);
  840. for (let i = 0; i < groups.length; i++) {
  841. const entityGroup = groups[i];
  842. for (let j = 0; j < entityGroup.length; j++) {
  843. const candidate = entityGroup[j];
  844. if (candidate.name === name) {
  845. return candidate;
  846. }
  847. }
  848. }
  849. return null;
  850. }
  851. function importScene(data) {
  852. removeAllEntities();
  853. data.entities.forEach(entityInfo => {
  854. console.log(findEntity(entityInfo.name))
  855. const entity = findEntity(entityInfo.name).constructor();
  856. entity.scale = entityInfo.scale
  857. displayEntity(entity, entityInfo.view, entityInfo.x, entityInfo.y);
  858. });
  859. config.height = math.unit(data.world.height, data.world.unit);
  860. document.querySelector("#options-height-unit").value = data.world.unit;
  861. updateSizes();
  862. }