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.
 
 
 

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