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.
 
 
 

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