less copy protection, more size visualization
No puede seleccionar más de 25 temas Los temas deben comenzar con una letra o número, pueden incluir guiones ('-') y pueden tener hasta 35 caracteres de largo.
 
 
 

1324 líneas
38 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 owners = ownersOfFull(file);
  540. const source = sourceOf(file);
  541. const authorHolder = document.querySelector("#options-attribution-authors");
  542. const ownerHolder = document.querySelector("#options-attribution-owners");
  543. const sourceHolder = document.querySelector("#options-attribution-source");
  544. if (authors === []) {
  545. authorHolder.innerText = "Unknown";
  546. } else if (authors === undefined) {
  547. authorHolder.innerText = "Not yet entered";
  548. } else {
  549. authorHolder.innerHTML = "";
  550. const list = document.createElement("ul");
  551. authorHolder.appendChild(list);
  552. authors.forEach(author => {
  553. const authorEntry = document.createElement("li");
  554. const link = document.createElement("a");
  555. link.href = author.url;
  556. link.innerText = author.name;
  557. authorEntry.appendChild(link);
  558. list.appendChild(authorEntry);
  559. });
  560. }
  561. if (owners === []) {
  562. ownerHolder.innerText = "Unknown";
  563. } else if (owners === undefined) {
  564. ownerHolder.innerText = "Not yet entered";
  565. } else {
  566. ownerHolder.innerHTML = "";
  567. const list = document.createElement("ul");
  568. ownerHolder.appendChild(list);
  569. owners.forEach(owner => {
  570. const ownerEntry = document.createElement("li");
  571. const link = document.createElement("a");
  572. link.href = owner.url;
  573. link.innerText = owner.name;
  574. ownerEntry.appendChild(link);
  575. list.appendChild(ownerEntry);
  576. });
  577. }
  578. if (source === null) {
  579. sourceHolder.innerText = "No Link"
  580. } else if (source === undefined) {
  581. sourceHolder.innerText = "Not yet entered";
  582. } else {
  583. sourceHolder.innerHTML = "";
  584. const link = document.createElement("a");
  585. link.href = source;
  586. link.innerText = new URL(source).host;
  587. sourceHolder.appendChild(link);
  588. }
  589. }
  590. function removeEntity(element) {
  591. if (selected == element) {
  592. deselect();
  593. }
  594. delete entities[element.dataset.key];
  595. const bottomName = document.querySelector("#bottom-name-" + element.dataset.key);
  596. bottomName.parentElement.removeChild(bottomName);
  597. element.parentElement.removeChild(element);
  598. }
  599. function displayEntity(entity, view, x, y) {
  600. const box = document.createElement("div");
  601. box.classList.add("entity-box");
  602. const img = document.createElement("img");
  603. img.classList.add("entity-image");
  604. img.addEventListener("dragstart", e => {
  605. e.preventDefault();
  606. });
  607. const nameTag = document.createElement("div");
  608. nameTag.classList.add("entity-name");
  609. nameTag.innerText = entity.name;
  610. box.appendChild(img);
  611. box.appendChild(nameTag);
  612. const image = entity.views[view].image;
  613. img.src = image.source;
  614. displayAttribution(image.source);
  615. if (image.bottom !== undefined) {
  616. img.style.setProperty("--offset", ((-1 + image.bottom) * 100) + "%")
  617. } else {
  618. img.style.setProperty("--offset", ((-1) * 100) + "%")
  619. }
  620. box.dataset.x = x;
  621. box.dataset.y = y;
  622. img.addEventListener("mousedown", e => { testClick(e); e.stopPropagation() });
  623. img.addEventListener("touchstart", e => {
  624. const fakeEvent = {
  625. target: e.target,
  626. clientX: e.touches[0].clientX,
  627. clientY: e.touches[0].clientY
  628. };
  629. testClick(fakeEvent);
  630. });
  631. box.id = "entity-" + entityIndex;
  632. box.dataset.key = entityIndex;
  633. entity.view = view;
  634. entities[entityIndex] = entity;
  635. entity.index = entityIndex;
  636. const world = document.querySelector("#entities");
  637. world.appendChild(box);
  638. const bottomName = document.createElement("div");
  639. bottomName.classList.add("bottom-name");
  640. bottomName.id = "bottom-name-" + entityIndex;
  641. bottomName.innerText = entity.name;
  642. bottomName.addEventListener("click", () => select(box));
  643. world.appendChild(bottomName);
  644. entityIndex += 1;
  645. updateEntityElement(entity, box);
  646. if (config.autoFit) {
  647. fitWorld();
  648. }
  649. select(box);
  650. }
  651. window.onblur = function () {
  652. altHeld = false;
  653. shiftHeld = false;
  654. }
  655. window.onfocus = function () {
  656. window.dispatchEvent(new Event("keydown"));
  657. }
  658. document.addEventListener("DOMContentLoaded", () => {
  659. prepareEntities();
  660. const sceneChoices = document.querySelector("#scene-choices");
  661. Object.entries(scenes).forEach(([id, scene]) => {
  662. const option = document.createElement("option");
  663. option.innerText = id;
  664. option.value = id;
  665. sceneChoices.appendChild(option);
  666. });
  667. document.querySelector("#load-scene").addEventListener("click", e => {
  668. const chosen = sceneChoices.value;
  669. removeAllEntities();
  670. scenes[chosen]();
  671. });
  672. entityX = document.querySelector("#entities").getBoundingClientRect().x;
  673. canvasWidth = document.querySelector("#display").clientWidth - 100;
  674. canvasHeight = document.querySelector("#display").clientHeight - 50;
  675. document.querySelector("#open-help").addEventListener("click", e => {
  676. document.querySelector("#help").classList.add("visible");
  677. });
  678. document.querySelector("#close-help").addEventListener("click", e => {
  679. document.querySelector("#help").classList.remove("visible");
  680. });
  681. const unitSelector = document.querySelector("#options-height-unit");
  682. unitChoices.length.forEach(lengthOption => {
  683. const option = document.createElement("option");
  684. option.innerText = lengthOption;
  685. option.value = lengthOption;
  686. if (lengthOption === "meters") {
  687. option.selected = true;
  688. }
  689. unitSelector.appendChild(option);
  690. });
  691. param = new URL(window.location.href).searchParams.get("scene");
  692. if (param === null)
  693. scenes["Demo"]();
  694. else {
  695. try {
  696. const data = JSON.parse(atob(param));
  697. if (data.entities === undefined) {
  698. return;
  699. }
  700. if (data.world === undefined) {
  701. return;
  702. }
  703. importScene(data);
  704. } catch (err) {
  705. console.error(err);
  706. scenes["Demo"]();
  707. // probably wasn't valid data
  708. }
  709. }
  710. fitWorld();
  711. document.querySelector("#world").addEventListener("wheel", e => {
  712. if (shiftHeld) {
  713. const dir = e.deltaY > 0 ? 0.9 : 1.1;
  714. if (selected) {
  715. const entity = entities[selected.dataset.key];
  716. entity.views[entity.view].height = math.multiply(entity.views[entity.view].height, dir);
  717. updateEntityOptions(entity, entity.view);
  718. updateViewOptions(entity, entity.view);
  719. updateSizes();
  720. }
  721. } else {
  722. const dir = e.deltaY < 0 ? 0.9 : 1.1;
  723. setWorldHeight(config.height, math.multiply(config.height, dir));
  724. updateWorldOptions();
  725. }
  726. checkFitWorld();
  727. })
  728. document.querySelector("body").appendChild(testCtx.canvas);
  729. updateSizes();
  730. document.querySelector("#options-height-value").addEventListener("input", e => {
  731. updateWorldHeight();
  732. })
  733. unitSelector.addEventListener("input", e => {
  734. checkFitWorld();
  735. updateWorldHeight();
  736. })
  737. world.addEventListener("mousedown", e => deselect());
  738. document.querySelector("#display").addEventListener("mousedown", deselect);
  739. document.addEventListener("mouseup", e => clickUp(e));
  740. document.addEventListener("touchend", e => {
  741. const fakeEvent = {
  742. target: e.target,
  743. clientX: e.changedTouches[0].clientX,
  744. clientY: e.changedTouches[0].clientY
  745. };
  746. clickUp(fakeEvent);
  747. });
  748. document.querySelector("#entity-view").addEventListener("input", e => {
  749. entities[selected.dataset.key].view = e.target.value;
  750. const image = entities[selected.dataset.key].views[e.target.value].image;
  751. selected.querySelector(".entity-image").src = image.source;
  752. displayAttribution(image.source);
  753. if (image.bottom !== undefined) {
  754. selected.querySelector(".entity-image").style.setProperty("--offset", ((-1 + image.bottom) * 100) + "%")
  755. } else {
  756. selected.querySelector(".entity-image").style.setProperty("--offset", ((-1) * 100) + "%")
  757. }
  758. updateSizes();
  759. updateEntityOptions(entities[selected.dataset.key], e.target.value);
  760. updateViewOptions(entities[selected.dataset.key], e.target.value);
  761. });
  762. clearViewList();
  763. document.querySelector("#menu-clear").addEventListener("click", e => {
  764. removeAllEntities();
  765. });
  766. document.querySelector("#menu-order-height").addEventListener("click", e => {
  767. const order = Object.keys(entities).sort((a, b) => {
  768. const entA = entities[a];
  769. const entB = entities[b];
  770. const viewA = entA.view;
  771. const viewB = entB.view;
  772. const heightA = entA.views[viewA].height.to("meter").value;
  773. const heightB = entB.views[viewB].height.to("meter").value;
  774. return heightA - heightB;
  775. });
  776. arrangeEntities(order);
  777. });
  778. document.querySelector("#options-world-fit").addEventListener("click", fitWorld);
  779. document.querySelector("#options-world-autofit").addEventListener("input", e => {
  780. config.autoFit = e.target.checked;
  781. if (config.autoFit) {
  782. fitWorld();
  783. }
  784. });
  785. document.querySelector("#options-world-autofit-mode").addEventListener("input", e => {
  786. config.autoFitMode = e.target.value;
  787. if (config.autoFit) {
  788. fitWorld();
  789. }
  790. })
  791. document.addEventListener("keydown", e => {
  792. if (e.key == "Delete") {
  793. if (selected) {
  794. removeEntity(selected);
  795. selected = null;
  796. }
  797. }
  798. })
  799. document.addEventListener("keydown", e => {
  800. if (e.key == "Shift") {
  801. shiftHeld = true;
  802. e.preventDefault();
  803. } else if (e.key == "Alt") {
  804. altHeld = true;
  805. e.preventDefault();
  806. }
  807. });
  808. document.addEventListener("keyup", e => {
  809. if (e.key == "Shift") {
  810. shiftHeld = false;
  811. e.preventDefault();
  812. } else if (e.key == "Alt") {
  813. altHeld = false;
  814. e.preventDefault();
  815. }
  816. });
  817. document.addEventListener("paste", e => {
  818. try {
  819. const data = JSON.parse(e.clipboardData.getData("text"));
  820. if (data.entities === undefined) {
  821. return;
  822. }
  823. if (data.world === undefined) {
  824. return;
  825. }
  826. importScene(data);
  827. } catch (err) {
  828. console.error(err);
  829. // probably wasn't valid data
  830. }
  831. });
  832. document.querySelector("#menu-export").addEventListener("click", e => {
  833. copyScene();
  834. });
  835. document.querySelector("#menu-save").addEventListener("click", e => {
  836. saveScene();
  837. });
  838. document.querySelector("#menu-load").addEventListener("click", e => {
  839. loadScene();
  840. });
  841. });
  842. function prepareEntities() {
  843. availableEntities["buildings"] = makeBuildings();
  844. availableEntities["landmarks"] = makeLandmarks();
  845. availableEntities["characters"] = makeCharacters();
  846. availableEntities["objects"] = makeObjects();
  847. availableEntities["naturals"] = makeNaturals();
  848. availableEntities["vehicles"] = makeVehicles();
  849. availableEntities["cities"] = makeCities();
  850. availableEntities["characters"].sort((x, y) => {
  851. return x.name < y.name ? -1 : 1
  852. });
  853. const holder = document.querySelector("#spawners");
  854. const categorySelect = document.createElement("select");
  855. categorySelect.id = "category-picker";
  856. holder.appendChild(categorySelect);
  857. Object.entries(availableEntities).forEach(([category, entityList]) => {
  858. const select = document.createElement("select");
  859. select.id = "create-entity-" + category;
  860. for (let i = 0; i < entityList.length; i++) {
  861. const entity = entityList[i];
  862. const option = document.createElement("option");
  863. option.value = i;
  864. option.innerText = entity.name;
  865. select.appendChild(option);
  866. availableEntitiesByName[entity.name] = entity;
  867. };
  868. const button = document.createElement("button");
  869. button.id = "create-entity-" + category + "-button";
  870. button.innerText = "Create";
  871. button.addEventListener("click", e => {
  872. const newEntity = entityList[select.value].constructor()
  873. displayEntity(newEntity, newEntity.defaultView, 0.5, 1);
  874. });
  875. const categoryOption = document.createElement("option");
  876. categoryOption.value = category
  877. categoryOption.innerText = category;
  878. if (category == "characters") {
  879. categoryOption.selected = true;
  880. select.classList.add("category-visible");
  881. button.classList.add("category-visible");
  882. }
  883. categorySelect.appendChild(categoryOption);
  884. holder.appendChild(select);
  885. holder.appendChild(button);
  886. });
  887. categorySelect.addEventListener("input", e => {
  888. const oldSelect = document.querySelector("select.category-visible");
  889. oldSelect.classList.remove("category-visible");
  890. const oldButton = document.querySelector("button.category-visible");
  891. oldButton.classList.remove("category-visible");
  892. const newSelect = document.querySelector("#create-entity-" + e.target.value);
  893. newSelect.classList.add("category-visible");
  894. const newButton = document.querySelector("#create-entity-" + e.target.value + "-button");
  895. newButton.classList.add("category-visible");
  896. });
  897. }
  898. window.addEventListener("resize", () => {
  899. entityX = document.querySelector("#entities").getBoundingClientRect().x;
  900. canvasWidth = document.querySelector("#display").clientWidth - 100;
  901. canvasHeight = document.querySelector("#display").clientHeight - 50;
  902. updateSizes();
  903. })
  904. document.addEventListener("mousemove", (e) => {
  905. if (clicked) {
  906. const position = snapRel(abs2rel({ x: e.clientX - dragOffsetX, y: e.clientY - dragOffsetY }));
  907. clicked.dataset.x = position.x;
  908. clicked.dataset.y = position.y;
  909. updateEntityElement(entities[clicked.dataset.key], clicked);
  910. if (hoveringInDeleteArea(e)) {
  911. document.querySelector("#menubar").classList.add("hover-delete");
  912. } else {
  913. document.querySelector("#menubar").classList.remove("hover-delete");
  914. }
  915. }
  916. });
  917. document.addEventListener("touchmove", (e) => {
  918. if (clicked) {
  919. e.preventDefault();
  920. let x = e.touches[0].clientX;
  921. let y = e.touches[0].clientY;
  922. const position = snapRel(abs2rel({ x: x - dragOffsetX, y: y - dragOffsetY }));
  923. clicked.dataset.x = position.x;
  924. clicked.dataset.y = position.y;
  925. updateEntityElement(entities[clicked.dataset.key], clicked);
  926. // what a hack
  927. // I should centralize this 'fake event' creation...
  928. if (hoveringInDeleteArea({ clientY: y })) {
  929. document.querySelector("#menubar").classList.add("hover-delete");
  930. } else {
  931. document.querySelector("#menubar").classList.remove("hover-delete");
  932. }
  933. }
  934. }, { passive: false });
  935. function checkFitWorld() {
  936. if (config.autoFit) {
  937. fitWorld();
  938. }
  939. }
  940. const fitModes = {
  941. "max": {
  942. start: 0,
  943. binop: math.max,
  944. final: (total, count) => total
  945. },
  946. "arithmetic mean": {
  947. start: 0,
  948. binop: math.add,
  949. final: (total, count) => total / count
  950. },
  951. "geometric mean": {
  952. start: 1,
  953. binop: math.multiply,
  954. final: (total, count) => math.pow(total, 1 / count)
  955. }
  956. }
  957. function fitWorld() {
  958. const fitMode = fitModes[config.autoFitMode]
  959. let max = fitMode.start
  960. let count = 0;
  961. Object.entries(entities).forEach(([key, entity]) => {
  962. const view = entity.view;
  963. max = fitMode.binop(max, entity.views[view].height.toNumber("meter"));
  964. count += 1;
  965. });
  966. max = fitMode.final(max, count)
  967. max = math.unit(max, "meter")
  968. setWorldHeight(config.height, math.multiply(max, 1.1));
  969. }
  970. function updateWorldHeight() {
  971. const unit = document.querySelector("#options-height-unit").value;
  972. const value = Math.max(0.000000001, document.querySelector("#options-height-value").value);
  973. const oldHeight = config.height;
  974. setWorldHeight(oldHeight, math.unit(value, unit));
  975. }
  976. function setWorldHeight(oldHeight, newHeight) {
  977. config.height = newHeight.to(document.querySelector("#options-height-unit").value)
  978. const unit = document.querySelector("#options-height-unit").value;
  979. document.querySelector("#options-height-value").value = config.height.toNumber(unit);
  980. Object.entries(entities).forEach(([key, entity]) => {
  981. const element = document.querySelector("#entity-" + key);
  982. let newPosition;
  983. if (!altHeld) {
  984. newPosition = adjustAbs({ x: element.dataset.x, y: element.dataset.y }, oldHeight, config.height);
  985. } else {
  986. newPosition = { x: element.dataset.x, y: element.dataset.y };
  987. }
  988. element.dataset.x = newPosition.x;
  989. element.dataset.y = newPosition.y;
  990. });
  991. updateSizes();
  992. }
  993. function loadScene() {
  994. try {
  995. const data = JSON.parse(localStorage.getItem("macrovision-save"));
  996. importScene(data);
  997. } catch (err) {
  998. alert("Something went wrong while loading (maybe you didn't have anything saved. Check the F12 console for the error.")
  999. console.error(err);
  1000. }
  1001. }
  1002. function saveScene() {
  1003. try {
  1004. const string = JSON.stringify(exportScene());
  1005. localStorage.setItem("macrovision-save", string);
  1006. } catch (err) {
  1007. alert("Something went wrong while saving (maybe I don't have localStorage permissions, or exporting failed). Check the F12 console for the error.")
  1008. console.error(err);
  1009. }
  1010. }
  1011. function exportScene() {
  1012. const results = {};
  1013. results.entities = [];
  1014. Object.entries(entities).forEach(([key, entity]) => {
  1015. const element = document.querySelector("#entity-" + key);
  1016. results.entities.push({
  1017. name: entity.identifier,
  1018. scale: entity.scale,
  1019. view: entity.view,
  1020. x: element.dataset.x,
  1021. y: element.dataset.y
  1022. });
  1023. });
  1024. const unit = document.querySelector("#options-height-unit").value;
  1025. results.world = {
  1026. height: config.height.toNumber(unit),
  1027. unit: unit
  1028. }
  1029. return results;
  1030. }
  1031. function copyScene() {
  1032. const results = exportScene();
  1033. navigator.clipboard.writeText(JSON.stringify(results))
  1034. alert("Scene copied to clipboard. Paste text into the page to load the scene.");
  1035. }
  1036. // TODO - don't just search through every single entity
  1037. // probably just have a way to do lookups directly
  1038. function findEntity(name) {
  1039. return availableEntitiesByName[name];
  1040. }
  1041. function importScene(data) {
  1042. removeAllEntities();
  1043. data.entities.forEach(entityInfo => {
  1044. const entity = findEntity(entityInfo.name).constructor();
  1045. entity.scale = entityInfo.scale
  1046. displayEntity(entity, entityInfo.view, entityInfo.x, entityInfo.y);
  1047. });
  1048. config.height = math.unit(data.world.height, data.world.unit);
  1049. document.querySelector("#options-height-unit").value = data.world.unit;
  1050. updateSizes();
  1051. }