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.
 
 
 

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