less copy protection, more size visualization
Du kannst nicht mehr als 25 Themen auswählen Themen müssen entweder mit einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.
 
 
 

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