less copy protection, more size visualization
Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.
 
 
 

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