less copy protection, more size visualization
Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.
 
 
 

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