less copy protection, more size visualization
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

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