less copy protection, more size visualization
25'ten fazla konu seçemezsiniz Konular bir harf veya rakamla başlamalı, kısa çizgiler ('-') içerebilir ve en fazla 35 karakter uzunluğunda olabilir.
 
 
 

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