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

1628 satır
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-world-show-bottom-cover").addEventListener("input", e => {
  819. document.body.classList[e.target.checked ? "add" : "remove"]("toggle-bottom-cover");
  820. });
  821. document.querySelector("#options-order-forward").addEventListener("click", e => {
  822. if (selected) {
  823. entities[selected.dataset.key].priority += 1;
  824. }
  825. document.querySelector("#options-order-display").innerText = entities[selected.dataset.key].priority;
  826. updateSizes();
  827. });
  828. document.querySelector("#options-order-back").addEventListener("click", e => {
  829. if (selected) {
  830. entities[selected.dataset.key].priority -= 1;
  831. }
  832. document.querySelector("#options-order-display").innerText = entities[selected.dataset.key].priority;
  833. updateSizes();
  834. });
  835. document.querySelector("#slider-scale").addEventListener("mousedown", e => {
  836. dragScaleHandle = setInterval(doSliderScale, 50);
  837. e.stopPropagation();
  838. });
  839. document.querySelector("#slider-scale").addEventListener("touchstart", e => {
  840. dragScaleHandle = setInterval(doSliderScale, 50);
  841. e.stopPropagation();
  842. });
  843. document.querySelector("#slider-scale").addEventListener("input", e => {
  844. const val = Number(e.target.value);
  845. if (val < 1) {
  846. sliderScale = (val + 1) / 2;
  847. } else {
  848. sliderScale = val;
  849. }
  850. });
  851. document.querySelector("#slider-scale").addEventListener("change", e => {
  852. clearInterval(dragScaleHandle);
  853. dragScaleHandle = null;
  854. e.target.value = 1;
  855. });
  856. document.querySelector("#slider-entity-scale").addEventListener("mousedown", e => {
  857. dragEntityScaleHandle = setInterval(doSliderEntityScale, 50);
  858. e.stopPropagation();
  859. });
  860. document.querySelector("#slider-entity-scale").addEventListener("touchstart", e => {
  861. dragEntityScaleHandle = setInterval(doSliderEntityScale, 50);
  862. e.stopPropagation();
  863. });
  864. document.querySelector("#slider-entity-scale").addEventListener("input", e => {
  865. const val = Number(e.target.value);
  866. if (val < 1) {
  867. sliderEntityScale = (val + 1) / 2;
  868. } else {
  869. sliderEntityScale = val;
  870. }
  871. });
  872. document.querySelector("#slider-entity-scale").addEventListener("change", e => {
  873. clearInterval(dragEntityScaleHandle);
  874. dragEntityScaleHandle = null;
  875. e.target.value = 1;
  876. });
  877. const sceneChoices = document.querySelector("#scene-choices");
  878. Object.entries(scenes).forEach(([id, scene]) => {
  879. const option = document.createElement("option");
  880. option.innerText = id;
  881. option.value = id;
  882. sceneChoices.appendChild(option);
  883. });
  884. document.querySelector("#load-scene").addEventListener("click", e => {
  885. const chosen = sceneChoices.value;
  886. removeAllEntities();
  887. scenes[chosen]();
  888. });
  889. entityX = document.querySelector("#entities").getBoundingClientRect().x;
  890. canvasWidth = document.querySelector("#display").clientWidth - 100;
  891. canvasHeight = document.querySelector("#display").clientHeight - 50;
  892. document.querySelector("#open-help").addEventListener("click", e => {
  893. document.querySelector("#help").classList.add("visible");
  894. });
  895. document.querySelector("#close-help").addEventListener("click", e => {
  896. document.querySelector("#help").classList.remove("visible");
  897. });
  898. const unitSelector = document.querySelector("#options-height-unit");
  899. unitChoices.length.forEach(lengthOption => {
  900. const option = document.createElement("option");
  901. option.innerText = lengthOption;
  902. option.value = lengthOption;
  903. if (lengthOption === "meters") {
  904. option.selected = true;
  905. }
  906. unitSelector.appendChild(option);
  907. });
  908. param = new URL(window.location.href).searchParams.get("scene");
  909. if (param === null)
  910. scenes["Default"]();
  911. else {
  912. try {
  913. const data = JSON.parse(b64DecodeUnicode(param));
  914. if (data.entities === undefined) {
  915. return;
  916. }
  917. if (data.world === undefined) {
  918. return;
  919. }
  920. importScene(data);
  921. } catch (err) {
  922. console.error(err);
  923. scenes["Default"]();
  924. // probably wasn't valid data
  925. }
  926. }
  927. document.querySelector("#world").addEventListener("wheel", e => {
  928. if (shiftHeld) {
  929. const dir = e.deltaY > 0 ? 0.9 : 1.1;
  930. if (selected) {
  931. const entity = entities[selected.dataset.key];
  932. entity.views[entity.view].height = math.multiply(entity.views[entity.view].height, dir);
  933. entity.dirty = true;
  934. updateEntityOptions(entity, entity.view);
  935. updateViewOptions(entity, entity.view);
  936. updateSizes(true);
  937. }
  938. } else {
  939. const dir = e.deltaY < 0 ? 0.9 : 1.1;
  940. setWorldHeight(config.height, math.multiply(config.height, dir));
  941. updateWorldOptions();
  942. }
  943. checkFitWorld();
  944. })
  945. document.querySelector("body").appendChild(testCtx.canvas);
  946. updateSizes();
  947. document.querySelector("#options-height-value").addEventListener("input", e => {
  948. updateWorldHeight();
  949. })
  950. unitSelector.addEventListener("input", e => {
  951. checkFitWorld();
  952. updateWorldHeight();
  953. })
  954. world.addEventListener("mousedown", e => deselect());
  955. document.querySelector("#display").addEventListener("mousedown", deselect);
  956. document.addEventListener("mouseup", e => clickUp(e));
  957. document.addEventListener("touchend", e => {
  958. const fakeEvent = {
  959. target: e.target,
  960. clientX: e.changedTouches[0].clientX,
  961. clientY: e.changedTouches[0].clientY
  962. };
  963. clickUp(fakeEvent);
  964. });
  965. document.querySelector("#entity-view").addEventListener("input", e => {
  966. const entity = entities[selected.dataset.key];
  967. entity.view = e.target.value;
  968. const image = entities[selected.dataset.key].views[e.target.value].image;
  969. selected.querySelector(".entity-image").src = image.source;
  970. displayAttribution(image.source);
  971. if (image.bottom !== undefined) {
  972. selected.querySelector(".entity-image").style.setProperty("--offset", ((-1 + image.bottom) * 100) + "%")
  973. } else {
  974. selected.querySelector(".entity-image").style.setProperty("--offset", ((-1) * 100) + "%")
  975. }
  976. updateSizes();
  977. updateEntityOptions(entities[selected.dataset.key], e.target.value);
  978. updateViewOptions(entities[selected.dataset.key], e.target.value);
  979. });
  980. clearViewList();
  981. document.querySelector("#menu-clear").addEventListener("click", e => {
  982. removeAllEntities();
  983. });
  984. document.querySelector("#menu-order-height").addEventListener("click", e => {
  985. const order = Object.keys(entities).sort((a, b) => {
  986. const entA = entities[a];
  987. const entB = entities[b];
  988. const viewA = entA.view;
  989. const viewB = entB.view;
  990. const heightA = entA.views[viewA].height.to("meter").value;
  991. const heightB = entB.views[viewB].height.to("meter").value;
  992. return heightA - heightB;
  993. });
  994. arrangeEntities(order);
  995. });
  996. document.querySelector("#options-world-fit").addEventListener("click", () => fitWorld(true));
  997. document.querySelector("#options-world-autofit").addEventListener("input", e => {
  998. config.autoFit = e.target.checked;
  999. if (config.autoFit) {
  1000. fitWorld();
  1001. }
  1002. });
  1003. document.querySelector("#options-world-autofit-mode").addEventListener("input", e => {
  1004. config.autoFitMode = e.target.value;
  1005. if (config.autoFit) {
  1006. fitWorld();
  1007. }
  1008. })
  1009. document.addEventListener("keydown", e => {
  1010. if (e.key == "Delete") {
  1011. if (selected) {
  1012. removeEntity(selected);
  1013. selected = null;
  1014. }
  1015. }
  1016. })
  1017. document.addEventListener("keydown", e => {
  1018. if (e.key == "Shift") {
  1019. shiftHeld = true;
  1020. e.preventDefault();
  1021. } else if (e.key == "Alt") {
  1022. altHeld = true;
  1023. e.preventDefault();
  1024. }
  1025. });
  1026. document.addEventListener("keyup", e => {
  1027. if (e.key == "Shift") {
  1028. shiftHeld = false;
  1029. e.preventDefault();
  1030. } else if (e.key == "Alt") {
  1031. altHeld = false;
  1032. e.preventDefault();
  1033. }
  1034. });
  1035. document.addEventListener("paste", e => {
  1036. try {
  1037. const data = JSON.parse(e.clipboardData.getData("text"));
  1038. if (data.entities === undefined) {
  1039. return;
  1040. }
  1041. if (data.world === undefined) {
  1042. return;
  1043. }
  1044. importScene(data);
  1045. } catch (err) {
  1046. console.error(err);
  1047. // probably wasn't valid data
  1048. }
  1049. });
  1050. document.querySelector("#menu-permalink").addEventListener("click", e => {
  1051. linkScene();
  1052. });
  1053. document.querySelector("#menu-export").addEventListener("click", e => {
  1054. copyScene();
  1055. });
  1056. document.querySelector("#menu-save").addEventListener("click", e => {
  1057. saveScene();
  1058. });
  1059. document.querySelector("#menu-load").addEventListener("click", e => {
  1060. loadScene();
  1061. });
  1062. });
  1063. function prepareEntities() {
  1064. availableEntities["buildings"] = makeBuildings();
  1065. availableEntities["landmarks"] = makeLandmarks();
  1066. availableEntities["characters"] = makeCharacters();
  1067. availableEntities["objects"] = makeObjects();
  1068. availableEntities["food"] = makeFood();
  1069. availableEntities["naturals"] = makeNaturals();
  1070. availableEntities["vehicles"] = makeVehicles();
  1071. availableEntities["cities"] = makeCities();
  1072. availableEntities["pokemon"] = makePokemon();
  1073. availableEntities["characters"].sort((x, y) => {
  1074. return x.name.toLowerCase() < y.name.toLowerCase() ? -1 : 1
  1075. });
  1076. const holder = document.querySelector("#spawners");
  1077. const categorySelect = document.createElement("select");
  1078. categorySelect.id = "category-picker";
  1079. holder.appendChild(categorySelect);
  1080. Object.entries(availableEntities).forEach(([category, entityList]) => {
  1081. const select = document.createElement("select");
  1082. select.id = "create-entity-" + category;
  1083. for (let i = 0; i < entityList.length; i++) {
  1084. const entity = entityList[i];
  1085. const option = document.createElement("option");
  1086. option.value = i;
  1087. option.innerText = entity.name;
  1088. select.appendChild(option);
  1089. availableEntitiesByName[entity.name] = entity;
  1090. };
  1091. const button = document.createElement("button");
  1092. button.id = "create-entity-" + category + "-button";
  1093. button.innerHTML = "<i class=\"far fa-plus-square\"></i>";
  1094. button.addEventListener("click", e => {
  1095. const newEntity = entityList[select.value].constructor()
  1096. displayEntity(newEntity, newEntity.defaultView, 0.5, 1, true);
  1097. });
  1098. const categoryOption = document.createElement("option");
  1099. categoryOption.value = category
  1100. categoryOption.innerText = category;
  1101. if (category == "characters") {
  1102. categoryOption.selected = true;
  1103. select.classList.add("category-visible");
  1104. button.classList.add("category-visible");
  1105. }
  1106. categorySelect.appendChild(categoryOption);
  1107. holder.appendChild(select);
  1108. holder.appendChild(button);
  1109. });
  1110. categorySelect.addEventListener("input", e => {
  1111. const oldSelect = document.querySelector("select.category-visible");
  1112. oldSelect.classList.remove("category-visible");
  1113. const oldButton = document.querySelector("button.category-visible");
  1114. oldButton.classList.remove("category-visible");
  1115. const newSelect = document.querySelector("#create-entity-" + e.target.value);
  1116. newSelect.classList.add("category-visible");
  1117. const newButton = document.querySelector("#create-entity-" + e.target.value + "-button");
  1118. newButton.classList.add("category-visible");
  1119. });
  1120. }
  1121. window.addEventListener("resize", () => {
  1122. entityX = document.querySelector("#entities").getBoundingClientRect().x;
  1123. console.log(entityX)
  1124. canvasWidth = document.querySelector("#display").clientWidth - 100;
  1125. canvasHeight = document.querySelector("#display").clientHeight - 50;
  1126. updateSizes();
  1127. })
  1128. document.addEventListener("mousemove", (e) => {
  1129. if (clicked) {
  1130. const position = snapRel(abs2rel({ x: e.clientX - dragOffsetX, y: e.clientY - dragOffsetY }));
  1131. clicked.dataset.x = position.x;
  1132. clicked.dataset.y = position.y;
  1133. updateEntityElement(entities[clicked.dataset.key], clicked);
  1134. if (hoveringInDeleteArea(e)) {
  1135. document.querySelector("#menubar").classList.add("hover-delete");
  1136. } else {
  1137. document.querySelector("#menubar").classList.remove("hover-delete");
  1138. }
  1139. }
  1140. });
  1141. document.addEventListener("touchmove", (e) => {
  1142. if (clicked) {
  1143. e.preventDefault();
  1144. let x = e.touches[0].clientX;
  1145. let y = e.touches[0].clientY;
  1146. const position = snapRel(abs2rel({ x: x - dragOffsetX, y: y - dragOffsetY }));
  1147. clicked.dataset.x = position.x;
  1148. clicked.dataset.y = position.y;
  1149. updateEntityElement(entities[clicked.dataset.key], clicked);
  1150. // what a hack
  1151. // I should centralize this 'fake event' creation...
  1152. if (hoveringInDeleteArea({ clientY: y })) {
  1153. document.querySelector("#menubar").classList.add("hover-delete");
  1154. } else {
  1155. document.querySelector("#menubar").classList.remove("hover-delete");
  1156. }
  1157. }
  1158. }, { passive: false });
  1159. function checkFitWorld() {
  1160. if (config.autoFit) {
  1161. fitWorld();
  1162. return true;
  1163. }
  1164. return false;
  1165. }
  1166. const fitModes = {
  1167. "max": {
  1168. start: 0,
  1169. binop: Math.max,
  1170. final: (total, count) => total
  1171. },
  1172. "arithmetic mean": {
  1173. start: 0,
  1174. binop: math.add,
  1175. final: (total, count) => total / count
  1176. },
  1177. "geometric mean": {
  1178. start: 1,
  1179. binop: math.multiply,
  1180. final: (total, count) => math.pow(total, 1 / count)
  1181. }
  1182. }
  1183. function fitWorld(manual=false, factor=1.1) {
  1184. const fitMode = fitModes[config.autoFitMode]
  1185. let max = fitMode.start
  1186. let count = 0;
  1187. Object.entries(entities).forEach(([key, entity]) => {
  1188. const view = entity.view;
  1189. let extra = entity.views[view].image.extra;
  1190. extra = extra === undefined ? 1 : extra;
  1191. max = fitMode.binop(max, math.multiply(extra, entity.views[view].height.toNumber("meter")));
  1192. count += 1;
  1193. });
  1194. max = fitMode.final(max, count)
  1195. max = math.unit(max, "meter")
  1196. if (manual)
  1197. altHeld = true;
  1198. setWorldHeight(config.height, math.multiply(max, factor));
  1199. if (manual)
  1200. altHeld = false;
  1201. }
  1202. function updateWorldHeight() {
  1203. const unit = document.querySelector("#options-height-unit").value;
  1204. const value = Math.max(0.000000001, document.querySelector("#options-height-value").value);
  1205. const oldHeight = config.height;
  1206. setWorldHeight(oldHeight, math.unit(value, unit));
  1207. }
  1208. function setWorldHeight(oldHeight, newHeight) {
  1209. config.height = newHeight.to(document.querySelector("#options-height-unit").value)
  1210. const unit = document.querySelector("#options-height-unit").value;
  1211. document.querySelector("#options-height-value").value = config.height.toNumber(unit);
  1212. Object.entries(entities).forEach(([key, entity]) => {
  1213. const element = document.querySelector("#entity-" + key);
  1214. let newPosition;
  1215. if (!altHeld) {
  1216. newPosition = adjustAbs({ x: element.dataset.x, y: element.dataset.y }, oldHeight, config.height);
  1217. } else {
  1218. newPosition = { x: element.dataset.x, y: element.dataset.y };
  1219. }
  1220. element.dataset.x = newPosition.x;
  1221. element.dataset.y = newPosition.y;
  1222. });
  1223. updateSizes();
  1224. }
  1225. function loadScene() {
  1226. try {
  1227. const data = JSON.parse(localStorage.getItem("macrovision-save"));
  1228. importScene(data);
  1229. } catch (err) {
  1230. alert("Something went wrong while loading (maybe you didn't have anything saved. Check the F12 console for the error.")
  1231. console.error(err);
  1232. }
  1233. }
  1234. function saveScene() {
  1235. try {
  1236. const string = JSON.stringify(exportScene());
  1237. localStorage.setItem("macrovision-save", string);
  1238. } catch (err) {
  1239. alert("Something went wrong while saving (maybe I don't have localStorage permissions, or exporting failed). Check the F12 console for the error.")
  1240. console.error(err);
  1241. }
  1242. }
  1243. function exportScene() {
  1244. const results = {};
  1245. results.entities = [];
  1246. Object.entries(entities).forEach(([key, entity]) => {
  1247. const element = document.querySelector("#entity-" + key);
  1248. results.entities.push({
  1249. name: entity.identifier,
  1250. scale: entity.scale,
  1251. view: entity.view,
  1252. x: element.dataset.x,
  1253. y: element.dataset.y
  1254. });
  1255. });
  1256. const unit = document.querySelector("#options-height-unit").value;
  1257. results.world = {
  1258. height: config.height.toNumber(unit),
  1259. unit: unit
  1260. }
  1261. return results;
  1262. }
  1263. // btoa doesn't like anything that isn't ASCII
  1264. // great
  1265. // thanks to https://stackoverflow.com/questions/30106476/using-javascripts-atob-to-decode-base64-doesnt-properly-decode-utf-8-strings
  1266. // for providing an alternative
  1267. function b64EncodeUnicode(str) {
  1268. // first we use encodeURIComponent to get percent-encoded UTF-8,
  1269. // then we convert the percent encodings into raw bytes which
  1270. // can be fed into btoa.
  1271. return btoa(encodeURIComponent(str).replace(/%([0-9A-F]{2})/g,
  1272. function toSolidBytes(match, p1) {
  1273. return String.fromCharCode('0x' + p1);
  1274. }));
  1275. }
  1276. function b64DecodeUnicode(str) {
  1277. // Going backwards: from bytestream, to percent-encoding, to original string.
  1278. return decodeURIComponent(atob(str).split('').map(function(c) {
  1279. return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
  1280. }).join(''));
  1281. }
  1282. function linkScene() {
  1283. loc = new URL(window.location);
  1284. window.location = loc.protocol + "//" + loc.host + loc.pathname + "?scene=" + b64EncodeUnicode(JSON.stringify(exportScene()));
  1285. }
  1286. function copyScene() {
  1287. const results = exportScene();
  1288. navigator.clipboard.writeText(JSON.stringify(results))
  1289. alert("Scene copied to clipboard. Paste text into the page to load the scene.");
  1290. }
  1291. // TODO - don't just search through every single entity
  1292. // probably just have a way to do lookups directly
  1293. function findEntity(name) {
  1294. return availableEntitiesByName[name];
  1295. }
  1296. function importScene(data) {
  1297. removeAllEntities();
  1298. data.entities.forEach(entityInfo => {
  1299. const entity = findEntity(entityInfo.name).constructor();
  1300. entity.scale = entityInfo.scale
  1301. displayEntity(entity, entityInfo.view, entityInfo.x, entityInfo.y);
  1302. });
  1303. config.height = math.unit(data.world.height, data.world.unit);
  1304. document.querySelector("#options-height-unit").value = data.world.unit;
  1305. updateSizes();
  1306. }