less copy protection, more size visualization
Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.
 
 
 

1673 řádky
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. console.warn("No authors: " + file);
  620. } else if (authors === undefined) {
  621. const div = document.createElement("div");
  622. div.innerText = "Not yet entered";
  623. authorHolder.innerHTML = "";
  624. authorHolder.appendChild(div);
  625. console.warn("No authors: " + file);
  626. } else {
  627. authorHolder.innerHTML = "";
  628. const list = document.createElement("ul");
  629. authorHolder.appendChild(list);
  630. authors.forEach(author => {
  631. const authorEntry = document.createElement("li");
  632. if (author.url) {
  633. const link = document.createElement("a");
  634. link.href = author.url;
  635. link.innerText = author.name;
  636. authorEntry.appendChild(link);
  637. } else {
  638. const div = document.createElement("div");
  639. div.innerText = author.name;
  640. authorEntry.appendChild(div);
  641. }
  642. list.appendChild(authorEntry);
  643. });
  644. }
  645. if (owners === []) {
  646. const div = document.createElement("div");
  647. div.innerText = "Unknown";
  648. ownerHolder.innerHTML = "";
  649. ownerHolder.appendChild(div);
  650. } else if (owners === undefined) {
  651. const div = document.createElement("div");
  652. div.innerText = "Not yet entered";
  653. ownerHolder.innerHTML = "";
  654. ownerHolder.appendChild(div);
  655. console.warn("No owners: " + file);
  656. } else {
  657. ownerHolder.innerHTML = "";
  658. const list = document.createElement("ul");
  659. ownerHolder.appendChild(list);
  660. owners.forEach(owner => {
  661. const ownerEntry = document.createElement("li");
  662. if (owner.url) {
  663. const link = document.createElement("a");
  664. link.href = owner.url;
  665. link.innerText = owner.name;
  666. ownerEntry.appendChild(link);
  667. } else {
  668. const div = document.createElement("div");
  669. div.innerText = owner.name;
  670. ownerEntry.appendChild(div);
  671. }
  672. list.appendChild(ownerEntry);
  673. });
  674. }
  675. if (source === null) {
  676. const div = document.createElement("div");
  677. div.innerText = "No link";
  678. sourceHolder.innerHTML = "";
  679. sourceHolder.appendChild(div);
  680. } else if (source === undefined) {
  681. const div = document.createElement("div");
  682. div.innerText = "Not yet entered";
  683. sourceHolder.innerHTML = "";
  684. sourceHolder.appendChild(div);
  685. } else {
  686. sourceHolder.innerHTML = "";
  687. const link = document.createElement("a");
  688. link.style.display = "block";
  689. link.href = source;
  690. link.innerText = new URL(source).host;
  691. sourceHolder.appendChild(link);
  692. }
  693. }
  694. function removeEntity(element) {
  695. if (selected == element) {
  696. deselect();
  697. }
  698. delete entities[element.dataset.key];
  699. const bottomName = document.querySelector("#bottom-name-" + element.dataset.key);
  700. bottomName.parentElement.removeChild(bottomName);
  701. element.parentElement.removeChild(element);
  702. }
  703. function displayEntity(entity, view, x, y, selectEntity=false) {
  704. const box = document.createElement("div");
  705. box.classList.add("entity-box");
  706. const img = document.createElement("img");
  707. img.classList.add("entity-image");
  708. img.addEventListener("dragstart", e => {
  709. e.preventDefault();
  710. });
  711. const nameTag = document.createElement("div");
  712. nameTag.classList.add("entity-name");
  713. nameTag.innerText = entity.name;
  714. box.appendChild(img);
  715. box.appendChild(nameTag);
  716. const image = entity.views[view].image;
  717. img.src = image.source;
  718. displayAttribution(image.source);
  719. if (image.bottom !== undefined) {
  720. img.style.setProperty("--offset", ((-1 + image.bottom) * 100) + "%")
  721. } else {
  722. img.style.setProperty("--offset", ((-1) * 100) + "%")
  723. }
  724. box.dataset.x = x;
  725. box.dataset.y = y;
  726. img.addEventListener("mousedown", e => { testClick(e); e.stopPropagation() });
  727. img.addEventListener("touchstart", e => {
  728. const fakeEvent = {
  729. target: e.target,
  730. clientX: e.touches[0].clientX,
  731. clientY: e.touches[0].clientY
  732. };
  733. testClick(fakeEvent);
  734. });
  735. const heightBar = document.createElement("div");
  736. heightBar.classList.add("height-bar");
  737. box.appendChild(heightBar);
  738. box.id = "entity-" + entityIndex;
  739. box.dataset.key = entityIndex;
  740. entity.view = view;
  741. entity.priority = 0;
  742. entities[entityIndex] = entity;
  743. entity.index = entityIndex;
  744. const world = document.querySelector("#entities");
  745. world.appendChild(box);
  746. const bottomName = document.createElement("div");
  747. bottomName.classList.add("bottom-name");
  748. bottomName.id = "bottom-name-" + entityIndex;
  749. bottomName.innerText = entity.name;
  750. bottomName.addEventListener("click", () => select(box));
  751. world.appendChild(bottomName);
  752. const topName = document.createElement("div");
  753. topName.classList.add("top-name");
  754. topName.id = "top-name-" + entityIndex;
  755. topName.innerText = entity.name;
  756. topName.addEventListener("click", () => select(box));
  757. world.appendChild(topName);
  758. entityIndex += 1;
  759. if (config.autoFit) {
  760. fitWorld();
  761. }
  762. if (selectEntity)
  763. select(box);
  764. entity.dirty = true;
  765. updateSizes(true);
  766. }
  767. window.onblur = function () {
  768. altHeld = false;
  769. shiftHeld = false;
  770. }
  771. window.onfocus = function () {
  772. window.dispatchEvent(new Event("keydown"));
  773. }
  774. function doSliderScale() {
  775. if (sliderScale == 1) {
  776. clearInterval(dragScaleHandle);
  777. }
  778. setWorldHeight(config.height, math.multiply(config.height, (9 + sliderScale) / 10));
  779. }
  780. function doSliderEntityScale() {
  781. if (sliderEntityScale == 1) {
  782. clearInterval(dragEntityScaleHandle);
  783. }
  784. if (selected) {
  785. const entity = entities[selected.dataset.key];
  786. entity.scale *= (9 + sliderEntityScale) / 10;
  787. entity.dirty = true;
  788. updateSizes(true);
  789. updateEntityOptions(entity, entity.view);
  790. updateViewOptions(entity, entity.view);
  791. }
  792. }
  793. // thanks to https://developers.google.com/web/fundamentals/native-hardware/fullscreen
  794. function toggleFullScreen() {
  795. var doc = window.document;
  796. var docEl = doc.documentElement;
  797. var requestFullScreen = docEl.requestFullscreen || docEl.mozRequestFullScreen || docEl.webkitRequestFullScreen || docEl.msRequestFullscreen;
  798. var cancelFullScreen = doc.exitFullscreen || doc.mozCancelFullScreen || doc.webkitExitFullscreen || doc.msExitFullscreen;
  799. if(!doc.fullscreenElement && !doc.mozFullScreenElement && !doc.webkitFullscreenElement && !doc.msFullscreenElement) {
  800. requestFullScreen.call(docEl);
  801. }
  802. else {
  803. cancelFullScreen.call(doc);
  804. }
  805. }
  806. function handleResize() {
  807. entityX = document.querySelector("#entities").getBoundingClientRect().x;
  808. console.log(entityX)
  809. canvasWidth = document.querySelector("#display").clientWidth - 100;
  810. canvasHeight = document.querySelector("#display").clientHeight - 50;
  811. updateSizes();
  812. }
  813. document.addEventListener("DOMContentLoaded", () => {
  814. prepareEntities();
  815. document.querySelector("#menu-toggle-sidebar").addEventListener("click", e => {
  816. const sidebar = document.querySelector("#options");
  817. if (sidebar.classList.contains("hidden")) {
  818. sidebar.classList.remove("hidden");
  819. e.target.classList.remove("rotate-forward");
  820. e.target.classList.add("rotate-backward");
  821. } else {
  822. sidebar.classList.add("hidden");
  823. e.target.classList.add("rotate-forward");
  824. e.target.classList.remove("rotate-backward");
  825. }
  826. handleResize();
  827. });
  828. document.querySelector("#menu-fullscreen").addEventListener("click", toggleFullScreen);
  829. document.querySelector("#options-show-extra").addEventListener("input", e => {
  830. document.body.classList[e.target.checked ? "add" : "remove"]("show-extra-options");
  831. });
  832. document.querySelector("#options-world-show-names").addEventListener("input", e => {
  833. document.body.classList[e.target.checked ? "add" : "remove"]("toggle-entity-name");
  834. });
  835. document.querySelector("#options-world-show-bottom-names").addEventListener("input", e => {
  836. document.body.classList[e.target.checked ? "add" : "remove"]("toggle-bottom-name");
  837. });
  838. document.querySelector("#options-world-show-top-names").addEventListener("input", e => {
  839. document.body.classList[e.target.checked ? "add" : "remove"]("toggle-top-name");
  840. });
  841. document.querySelector("#options-world-show-height-bars").addEventListener("input", e => {
  842. document.body.classList[e.target.checked ? "add" : "remove"]("toggle-height-bars");
  843. });
  844. document.querySelector("#options-world-show-entity-glow").addEventListener("input", e => {
  845. document.body.classList[e.target.checked ? "add" : "remove"]("toggle-entity-glow");
  846. });
  847. document.querySelector("#options-world-show-scale-sliders").addEventListener("input", e => {
  848. document.body.classList[e.target.checked ? "add" : "remove"]("toggle-scale-sliders");
  849. });
  850. document.querySelector("#options-world-show-bottom-cover").addEventListener("input", e => {
  851. document.body.classList[e.target.checked ? "add" : "remove"]("toggle-bottom-cover");
  852. });
  853. document.querySelector("#options-world-show-scale").addEventListener("input", e => {
  854. document.body.classList[e.target.checked ? "add" : "remove"]("toggle-scale");
  855. });
  856. document.querySelector("#options-order-forward").addEventListener("click", e => {
  857. if (selected) {
  858. entities[selected.dataset.key].priority += 1;
  859. }
  860. document.querySelector("#options-order-display").innerText = entities[selected.dataset.key].priority;
  861. updateSizes();
  862. });
  863. document.querySelector("#options-order-back").addEventListener("click", e => {
  864. if (selected) {
  865. entities[selected.dataset.key].priority -= 1;
  866. }
  867. document.querySelector("#options-order-display").innerText = entities[selected.dataset.key].priority;
  868. updateSizes();
  869. });
  870. document.querySelector("#slider-scale").addEventListener("mousedown", e => {
  871. clearInterval(dragScaleHandle);
  872. dragScaleHandle = setInterval(doSliderScale, 50);
  873. e.stopPropagation();
  874. });
  875. document.querySelector("#slider-scale").addEventListener("touchstart", e => {
  876. clearInterval(dragScaleHandle);
  877. dragScaleHandle = setInterval(doSliderScale, 50);
  878. e.stopPropagation();
  879. });
  880. document.querySelector("#slider-scale").addEventListener("input", e => {
  881. const val = Number(e.target.value);
  882. if (val < 1) {
  883. sliderScale = (val + 1) / 2;
  884. } else {
  885. sliderScale = val;
  886. }
  887. });
  888. document.querySelector("#slider-scale").addEventListener("change", e => {
  889. clearInterval(dragScaleHandle);
  890. dragScaleHandle = null;
  891. e.target.value = 1;
  892. });
  893. document.querySelector("#slider-entity-scale").addEventListener("mousedown", e => {
  894. clearInterval(dragEntityScaleHandle);
  895. dragEntityScaleHandle = setInterval(doSliderEntityScale, 50);
  896. e.stopPropagation();
  897. });
  898. document.querySelector("#slider-entity-scale").addEventListener("touchstart", e => {
  899. clearInterval(dragEntityScaleHandle);
  900. dragEntityScaleHandle = setInterval(doSliderEntityScale, 50);
  901. e.stopPropagation();
  902. });
  903. document.querySelector("#slider-entity-scale").addEventListener("input", e => {
  904. const val = Number(e.target.value);
  905. if (val < 1) {
  906. sliderEntityScale = (val + 1) / 2;
  907. } else {
  908. sliderEntityScale = val;
  909. }
  910. });
  911. document.querySelector("#slider-entity-scale").addEventListener("change", e => {
  912. clearInterval(dragEntityScaleHandle);
  913. dragEntityScaleHandle = null;
  914. e.target.value = 1;
  915. });
  916. const sceneChoices = document.querySelector("#scene-choices");
  917. Object.entries(scenes).forEach(([id, scene]) => {
  918. const option = document.createElement("option");
  919. option.innerText = id;
  920. option.value = id;
  921. sceneChoices.appendChild(option);
  922. });
  923. document.querySelector("#load-scene").addEventListener("click", e => {
  924. const chosen = sceneChoices.value;
  925. removeAllEntities();
  926. scenes[chosen]();
  927. });
  928. entityX = document.querySelector("#entities").getBoundingClientRect().x;
  929. canvasWidth = document.querySelector("#display").clientWidth - 100;
  930. canvasHeight = document.querySelector("#display").clientHeight - 50;
  931. document.querySelector("#open-help").addEventListener("click", e => {
  932. document.querySelector("#help").classList.add("visible");
  933. });
  934. document.querySelector("#close-help").addEventListener("click", e => {
  935. document.querySelector("#help").classList.remove("visible");
  936. });
  937. const unitSelector = document.querySelector("#options-height-unit");
  938. unitChoices.length.forEach(lengthOption => {
  939. const option = document.createElement("option");
  940. option.innerText = lengthOption;
  941. option.value = lengthOption;
  942. if (lengthOption === "meters") {
  943. option.selected = true;
  944. }
  945. unitSelector.appendChild(option);
  946. });
  947. param = new URL(window.location.href).searchParams.get("scene");
  948. if (param === null)
  949. scenes["Default"]();
  950. else {
  951. try {
  952. const data = JSON.parse(b64DecodeUnicode(param));
  953. if (data.entities === undefined) {
  954. return;
  955. }
  956. if (data.world === undefined) {
  957. return;
  958. }
  959. importScene(data);
  960. } catch (err) {
  961. console.error(err);
  962. scenes["Default"]();
  963. // probably wasn't valid data
  964. }
  965. }
  966. document.querySelector("#world").addEventListener("wheel", e => {
  967. if (shiftHeld) {
  968. const dir = e.deltaY > 0 ? 0.9 : 1.1;
  969. if (selected) {
  970. const entity = entities[selected.dataset.key];
  971. entity.views[entity.view].height = math.multiply(entity.views[entity.view].height, dir);
  972. entity.dirty = true;
  973. updateEntityOptions(entity, entity.view);
  974. updateViewOptions(entity, entity.view);
  975. updateSizes(true);
  976. }
  977. } else {
  978. const dir = e.deltaY < 0 ? 0.9 : 1.1;
  979. setWorldHeight(config.height, math.multiply(config.height, dir));
  980. updateWorldOptions();
  981. }
  982. checkFitWorld();
  983. })
  984. document.querySelector("body").appendChild(testCtx.canvas);
  985. updateSizes();
  986. document.querySelector("#options-height-value").addEventListener("input", e => {
  987. updateWorldHeight();
  988. })
  989. unitSelector.addEventListener("input", e => {
  990. checkFitWorld();
  991. updateWorldHeight();
  992. })
  993. world.addEventListener("mousedown", e => deselect());
  994. document.querySelector("#display").addEventListener("mousedown", deselect);
  995. document.addEventListener("mouseup", e => clickUp(e));
  996. document.addEventListener("touchend", e => {
  997. const fakeEvent = {
  998. target: e.target,
  999. clientX: e.changedTouches[0].clientX,
  1000. clientY: e.changedTouches[0].clientY
  1001. };
  1002. clickUp(fakeEvent);
  1003. });
  1004. document.querySelector("#entity-view").addEventListener("input", e => {
  1005. const entity = entities[selected.dataset.key];
  1006. entity.view = e.target.value;
  1007. const image = entities[selected.dataset.key].views[e.target.value].image;
  1008. selected.querySelector(".entity-image").src = image.source;
  1009. displayAttribution(image.source);
  1010. if (image.bottom !== undefined) {
  1011. selected.querySelector(".entity-image").style.setProperty("--offset", ((-1 + image.bottom) * 100) + "%")
  1012. } else {
  1013. selected.querySelector(".entity-image").style.setProperty("--offset", ((-1) * 100) + "%")
  1014. }
  1015. updateSizes();
  1016. updateEntityOptions(entities[selected.dataset.key], e.target.value);
  1017. updateViewOptions(entities[selected.dataset.key], e.target.value);
  1018. });
  1019. clearViewList();
  1020. document.querySelector("#menu-clear").addEventListener("click", e => {
  1021. removeAllEntities();
  1022. });
  1023. document.querySelector("#menu-order-height").addEventListener("click", e => {
  1024. const order = Object.keys(entities).sort((a, b) => {
  1025. const entA = entities[a];
  1026. const entB = entities[b];
  1027. const viewA = entA.view;
  1028. const viewB = entB.view;
  1029. const heightA = entA.views[viewA].height.to("meter").value;
  1030. const heightB = entB.views[viewB].height.to("meter").value;
  1031. return heightA - heightB;
  1032. });
  1033. arrangeEntities(order);
  1034. });
  1035. document.querySelector("#options-world-fit").addEventListener("click", () => fitWorld(true));
  1036. document.querySelector("#options-world-autofit").addEventListener("input", e => {
  1037. config.autoFit = e.target.checked;
  1038. if (config.autoFit) {
  1039. fitWorld();
  1040. }
  1041. });
  1042. document.querySelector("#options-world-autofit-mode").addEventListener("input", e => {
  1043. config.autoFitMode = e.target.value;
  1044. if (config.autoFit) {
  1045. fitWorld();
  1046. }
  1047. })
  1048. document.addEventListener("keydown", e => {
  1049. if (e.key == "Delete") {
  1050. if (selected) {
  1051. removeEntity(selected);
  1052. selected = null;
  1053. }
  1054. }
  1055. })
  1056. document.addEventListener("keydown", e => {
  1057. if (e.key == "Shift") {
  1058. shiftHeld = true;
  1059. e.preventDefault();
  1060. } else if (e.key == "Alt") {
  1061. altHeld = true;
  1062. e.preventDefault();
  1063. }
  1064. });
  1065. document.addEventListener("keyup", e => {
  1066. if (e.key == "Shift") {
  1067. shiftHeld = false;
  1068. e.preventDefault();
  1069. } else if (e.key == "Alt") {
  1070. altHeld = false;
  1071. e.preventDefault();
  1072. }
  1073. });
  1074. document.addEventListener("paste", e => {
  1075. try {
  1076. const data = JSON.parse(e.clipboardData.getData("text"));
  1077. if (data.entities === undefined) {
  1078. return;
  1079. }
  1080. if (data.world === undefined) {
  1081. return;
  1082. }
  1083. importScene(data);
  1084. } catch (err) {
  1085. console.error(err);
  1086. // probably wasn't valid data
  1087. }
  1088. });
  1089. window.addEventListener("resize", handleResize);
  1090. // TODO: further investigate why the tool initially starts out with wrong
  1091. // values under certain circumstances (seems to be narrow aspect ratios -
  1092. // maybe the menu bar is animating when it shouldn't)
  1093. setTimeout(handleResize, 250);
  1094. document.querySelector("#menu-permalink").addEventListener("click", e => {
  1095. linkScene();
  1096. });
  1097. document.querySelector("#menu-export").addEventListener("click", e => {
  1098. copyScene();
  1099. });
  1100. document.querySelector("#menu-save").addEventListener("click", e => {
  1101. saveScene();
  1102. });
  1103. document.querySelector("#menu-load").addEventListener("click", e => {
  1104. loadScene();
  1105. });
  1106. });
  1107. function prepareEntities() {
  1108. availableEntities["buildings"] = makeBuildings();
  1109. availableEntities["landmarks"] = makeLandmarks();
  1110. availableEntities["characters"] = makeCharacters();
  1111. availableEntities["objects"] = makeObjects();
  1112. availableEntities["food"] = makeFood();
  1113. availableEntities["naturals"] = makeNaturals();
  1114. availableEntities["vehicles"] = makeVehicles();
  1115. availableEntities["cities"] = makeCities();
  1116. availableEntities["pokemon"] = makePokemon();
  1117. availableEntities["characters"].sort((x, y) => {
  1118. return x.name.toLowerCase() < y.name.toLowerCase() ? -1 : 1
  1119. });
  1120. const holder = document.querySelector("#spawners");
  1121. const categorySelect = document.createElement("select");
  1122. categorySelect.id = "category-picker";
  1123. holder.appendChild(categorySelect);
  1124. Object.entries(availableEntities).forEach(([category, entityList]) => {
  1125. const select = document.createElement("select");
  1126. select.id = "create-entity-" + category;
  1127. for (let i = 0; i < entityList.length; i++) {
  1128. const entity = entityList[i];
  1129. const option = document.createElement("option");
  1130. option.value = i;
  1131. option.innerText = entity.name;
  1132. select.appendChild(option);
  1133. availableEntitiesByName[entity.name] = entity;
  1134. };
  1135. const button = document.createElement("button");
  1136. button.id = "create-entity-" + category + "-button";
  1137. button.innerHTML = "<i class=\"far fa-plus-square\"></i>";
  1138. button.addEventListener("click", e => {
  1139. const newEntity = entityList[select.value].constructor()
  1140. displayEntity(newEntity, newEntity.defaultView, 0.5, 1, true);
  1141. });
  1142. const categoryOption = document.createElement("option");
  1143. categoryOption.value = category
  1144. categoryOption.innerText = category;
  1145. if (category == "characters") {
  1146. categoryOption.selected = true;
  1147. select.classList.add("category-visible");
  1148. button.classList.add("category-visible");
  1149. }
  1150. categorySelect.appendChild(categoryOption);
  1151. holder.appendChild(select);
  1152. holder.appendChild(button);
  1153. });
  1154. categorySelect.addEventListener("input", e => {
  1155. const oldSelect = document.querySelector("select.category-visible");
  1156. oldSelect.classList.remove("category-visible");
  1157. const oldButton = document.querySelector("button.category-visible");
  1158. oldButton.classList.remove("category-visible");
  1159. const newSelect = document.querySelector("#create-entity-" + e.target.value);
  1160. newSelect.classList.add("category-visible");
  1161. const newButton = document.querySelector("#create-entity-" + e.target.value + "-button");
  1162. newButton.classList.add("category-visible");
  1163. });
  1164. }
  1165. document.addEventListener("mousemove", (e) => {
  1166. if (clicked) {
  1167. const position = snapRel(abs2rel({ x: e.clientX - dragOffsetX, y: e.clientY - dragOffsetY }));
  1168. clicked.dataset.x = position.x;
  1169. clicked.dataset.y = position.y;
  1170. updateEntityElement(entities[clicked.dataset.key], clicked);
  1171. if (hoveringInDeleteArea(e)) {
  1172. document.querySelector("#menubar").classList.add("hover-delete");
  1173. } else {
  1174. document.querySelector("#menubar").classList.remove("hover-delete");
  1175. }
  1176. }
  1177. });
  1178. document.addEventListener("touchmove", (e) => {
  1179. if (clicked) {
  1180. e.preventDefault();
  1181. let x = e.touches[0].clientX;
  1182. let y = e.touches[0].clientY;
  1183. const position = snapRel(abs2rel({ x: x - dragOffsetX, y: y - dragOffsetY }));
  1184. clicked.dataset.x = position.x;
  1185. clicked.dataset.y = position.y;
  1186. updateEntityElement(entities[clicked.dataset.key], clicked);
  1187. // what a hack
  1188. // I should centralize this 'fake event' creation...
  1189. if (hoveringInDeleteArea({ clientY: y })) {
  1190. document.querySelector("#menubar").classList.add("hover-delete");
  1191. } else {
  1192. document.querySelector("#menubar").classList.remove("hover-delete");
  1193. }
  1194. }
  1195. }, { passive: false });
  1196. function checkFitWorld() {
  1197. if (config.autoFit) {
  1198. fitWorld();
  1199. return true;
  1200. }
  1201. return false;
  1202. }
  1203. const fitModes = {
  1204. "max": {
  1205. start: 0,
  1206. binop: Math.max,
  1207. final: (total, count) => total
  1208. },
  1209. "arithmetic mean": {
  1210. start: 0,
  1211. binop: math.add,
  1212. final: (total, count) => total / count
  1213. },
  1214. "geometric mean": {
  1215. start: 1,
  1216. binop: math.multiply,
  1217. final: (total, count) => math.pow(total, 1 / count)
  1218. }
  1219. }
  1220. function fitWorld(manual=false, factor=1.1) {
  1221. const fitMode = fitModes[config.autoFitMode]
  1222. let max = fitMode.start
  1223. let count = 0;
  1224. Object.entries(entities).forEach(([key, entity]) => {
  1225. const view = entity.view;
  1226. let extra = entity.views[view].image.extra;
  1227. extra = extra === undefined ? 1 : extra;
  1228. max = fitMode.binop(max, math.multiply(extra, entity.views[view].height.toNumber("meter")));
  1229. count += 1;
  1230. });
  1231. max = fitMode.final(max, count)
  1232. max = math.unit(max, "meter")
  1233. if (manual)
  1234. altHeld = true;
  1235. setWorldHeight(config.height, math.multiply(max, factor));
  1236. if (manual)
  1237. altHeld = false;
  1238. }
  1239. function updateWorldHeight() {
  1240. const unit = document.querySelector("#options-height-unit").value;
  1241. const value = Math.max(0.000000001, document.querySelector("#options-height-value").value);
  1242. const oldHeight = config.height;
  1243. setWorldHeight(oldHeight, math.unit(value, unit));
  1244. }
  1245. function setWorldHeight(oldHeight, newHeight) {
  1246. config.height = newHeight.to(document.querySelector("#options-height-unit").value)
  1247. const unit = document.querySelector("#options-height-unit").value;
  1248. document.querySelector("#options-height-value").value = config.height.toNumber(unit);
  1249. Object.entries(entities).forEach(([key, entity]) => {
  1250. const element = document.querySelector("#entity-" + key);
  1251. let newPosition;
  1252. if (!altHeld) {
  1253. newPosition = adjustAbs({ x: element.dataset.x, y: element.dataset.y }, oldHeight, config.height);
  1254. } else {
  1255. newPosition = { x: element.dataset.x, y: element.dataset.y };
  1256. }
  1257. element.dataset.x = newPosition.x;
  1258. element.dataset.y = newPosition.y;
  1259. });
  1260. updateSizes();
  1261. }
  1262. function loadScene() {
  1263. try {
  1264. const data = JSON.parse(localStorage.getItem("macrovision-save"));
  1265. importScene(data);
  1266. } catch (err) {
  1267. alert("Something went wrong while loading (maybe you didn't have anything saved. Check the F12 console for the error.")
  1268. console.error(err);
  1269. }
  1270. }
  1271. function saveScene() {
  1272. try {
  1273. const string = JSON.stringify(exportScene());
  1274. localStorage.setItem("macrovision-save", string);
  1275. } catch (err) {
  1276. alert("Something went wrong while saving (maybe I don't have localStorage permissions, or exporting failed). Check the F12 console for the error.")
  1277. console.error(err);
  1278. }
  1279. }
  1280. function exportScene() {
  1281. const results = {};
  1282. results.entities = [];
  1283. Object.entries(entities).forEach(([key, entity]) => {
  1284. const element = document.querySelector("#entity-" + key);
  1285. results.entities.push({
  1286. name: entity.identifier,
  1287. scale: entity.scale,
  1288. view: entity.view,
  1289. x: element.dataset.x,
  1290. y: element.dataset.y
  1291. });
  1292. });
  1293. const unit = document.querySelector("#options-height-unit").value;
  1294. results.world = {
  1295. height: config.height.toNumber(unit),
  1296. unit: unit
  1297. }
  1298. return results;
  1299. }
  1300. // btoa doesn't like anything that isn't ASCII
  1301. // great
  1302. // thanks to https://stackoverflow.com/questions/30106476/using-javascripts-atob-to-decode-base64-doesnt-properly-decode-utf-8-strings
  1303. // for providing an alternative
  1304. function b64EncodeUnicode(str) {
  1305. // first we use encodeURIComponent to get percent-encoded UTF-8,
  1306. // then we convert the percent encodings into raw bytes which
  1307. // can be fed into btoa.
  1308. return btoa(encodeURIComponent(str).replace(/%([0-9A-F]{2})/g,
  1309. function toSolidBytes(match, p1) {
  1310. return String.fromCharCode('0x' + p1);
  1311. }));
  1312. }
  1313. function b64DecodeUnicode(str) {
  1314. // Going backwards: from bytestream, to percent-encoding, to original string.
  1315. return decodeURIComponent(atob(str).split('').map(function(c) {
  1316. return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
  1317. }).join(''));
  1318. }
  1319. function linkScene() {
  1320. loc = new URL(window.location);
  1321. window.location = loc.protocol + "//" + loc.host + loc.pathname + "?scene=" + b64EncodeUnicode(JSON.stringify(exportScene()));
  1322. }
  1323. function copyScene() {
  1324. const results = exportScene();
  1325. navigator.clipboard.writeText(JSON.stringify(results))
  1326. alert("Scene copied to clipboard. Paste text into the page to load the scene.");
  1327. }
  1328. // TODO - don't just search through every single entity
  1329. // probably just have a way to do lookups directly
  1330. function findEntity(name) {
  1331. return availableEntitiesByName[name];
  1332. }
  1333. function importScene(data) {
  1334. removeAllEntities();
  1335. data.entities.forEach(entityInfo => {
  1336. const entity = findEntity(entityInfo.name).constructor();
  1337. entity.scale = entityInfo.scale
  1338. displayEntity(entity, entityInfo.view, entityInfo.x, entityInfo.y);
  1339. });
  1340. config.height = math.unit(data.world.height, data.world.unit);
  1341. document.querySelector("#options-height-unit").value = data.world.unit;
  1342. updateSizes();
  1343. }