less copy protection, more size visualization
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

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