less copy protection, more size visualization
Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.
 
 
 

2398 lignes
72 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. let scrollDirection = 0;
  19. let scrollHandle = null;
  20. let zoomDirection = 0;
  21. let zoomHandle = null;
  22. let sizeDirection = 0;
  23. let sizeHandle = null;
  24. let worldSizeDirty = false;
  25. math.createUnit("humans", {
  26. definition: "5.75 feet"
  27. });
  28. math.createUnit("story", {
  29. definition: "12 feet",
  30. prefixes: "long"
  31. });
  32. math.createUnit("stories", {
  33. definition: "12 feet",
  34. prefixes: "long"
  35. });
  36. math.createUnit("earths", {
  37. definition: "12756km",
  38. prefixes: "long"
  39. });
  40. math.createUnit("parsec", {
  41. definition: "3.086e16 meters",
  42. prefixes: "long"
  43. })
  44. math.createUnit("parsecs", {
  45. definition: "3.086e16 meters",
  46. prefixes: "long"
  47. })
  48. math.createUnit("lightyears", {
  49. definition: "9.461e15 meters",
  50. prefixes: "long"
  51. })
  52. math.createUnit("AU", {
  53. definition: "149597870700 meters"
  54. })
  55. math.createUnit("AUs", {
  56. definition: "149597870700 meters"
  57. })
  58. math.createUnit("dalton", {
  59. definition: "1.66e-27 kg",
  60. prefixes: "long"
  61. });
  62. math.createUnit("daltons", {
  63. definition: "1.66e-27 kg",
  64. prefixes: "long"
  65. });
  66. math.createUnit("solarradii", {
  67. definition: "695990 km",
  68. prefixes: "long"
  69. });
  70. math.createUnit("solarmasses", {
  71. definition: "2e30 kg",
  72. prefixes: "long"
  73. });
  74. math.createUnit("galaxy", {
  75. definition: "105700 lightyears",
  76. prefixes: "long"
  77. });
  78. math.createUnit("galaxies", {
  79. definition: "105700 lightyears",
  80. prefixes: "long"
  81. });
  82. math.createUnit("universe", {
  83. definition: "93.016e9 lightyears",
  84. prefixes: "long"
  85. });
  86. math.createUnit("universes", {
  87. definition: "93.016e9 lightyears",
  88. prefixes: "long"
  89. });
  90. math.createUnit("multiverse", {
  91. definition: "1e30 lightyears",
  92. prefixes: "long"
  93. });
  94. math.createUnit("multiverses", {
  95. definition: "1e30 lightyears",
  96. prefixes: "long"
  97. });
  98. const unitChoices = {
  99. length: [
  100. "meters",
  101. "angstroms",
  102. "millimeters",
  103. "centimeters",
  104. "kilometers",
  105. "inches",
  106. "feet",
  107. "humans",
  108. "stories",
  109. "miles",
  110. "earths",
  111. "solarradii",
  112. "AUs",
  113. "lightyears",
  114. "parsecs",
  115. "galaxies",
  116. "universes",
  117. "multiverses"
  118. ],
  119. area: [
  120. "meters^2",
  121. "cm^2",
  122. "kilometers^2",
  123. "acres",
  124. "miles^2"
  125. ],
  126. mass: [
  127. "kilograms",
  128. "milligrams",
  129. "grams",
  130. "tonnes",
  131. "lbs",
  132. "ounces",
  133. "tons"
  134. ]
  135. }
  136. const config = {
  137. height: math.unit(1500, "meters"),
  138. minLineSize: 100,
  139. maxLineSize: 150,
  140. autoFit: false,
  141. autoFitMode: "max"
  142. }
  143. const availableEntities = {
  144. }
  145. const availableEntitiesByName = {
  146. }
  147. const entities = {
  148. }
  149. function constrainRel(coords) {
  150. if (altHeld) {
  151. return coords;
  152. }
  153. return {
  154. x: Math.min(Math.max(coords.x, 0), 1),
  155. y: Math.min(Math.max(coords.y, 0), 1)
  156. }
  157. }
  158. function snapRel(coords) {
  159. return constrainRel({
  160. x: coords.x,
  161. y: altHeld ? coords.y : (Math.abs(coords.y - 1) < 0.05 ? 1 : coords.y)
  162. });
  163. }
  164. function adjustAbs(coords, oldHeight, newHeight) {
  165. const ratio = math.divide(oldHeight, newHeight);
  166. return { x: 0.5 + (coords.x - 0.5) * math.divide(oldHeight, newHeight), y: 1 + (coords.y - 1) * math.divide(oldHeight, newHeight) };
  167. }
  168. function rel2abs(coords) {
  169. return { x: coords.x * canvasWidth + 50, y: coords.y * canvasHeight };
  170. }
  171. function abs2rel(coords) {
  172. return { x: (coords.x - 50) / canvasWidth, y: coords.y / canvasHeight };
  173. }
  174. function updateEntityElement(entity, element) {
  175. const position = rel2abs({ x: element.dataset.x, y: element.dataset.y });
  176. const view = entity.view;
  177. element.style.left = position.x + "px";
  178. element.style.top = position.y + "px";
  179. element.style.setProperty("--xpos", position.x + "px");
  180. element.style.setProperty("--entity-height", "'" + entity.views[view].height.to(config.height.units[0].unit.name).format({ precision: 2 }) + "'");
  181. const pixels = math.divide(entity.views[view].height, config.height) * (canvasHeight - 50);
  182. const extra = entity.views[view].image.extra;
  183. const bottom = entity.views[view].image.bottom;
  184. const bonus = (extra ? extra : 1) * (1 / (1 - (bottom ? bottom : 0)));
  185. element.style.setProperty("--height", pixels * bonus + "px");
  186. element.style.setProperty("--extra", pixels * bonus - pixels + "px");
  187. if (entity.views[view].rename)
  188. element.querySelector(".entity-name").innerText = entity.name == "" ? "" : entity.views[view].name;
  189. else
  190. element.querySelector(".entity-name").innerText = entity.name;
  191. const bottomName = document.querySelector("#bottom-name-" + element.dataset.key);
  192. bottomName.style.left = position.x + entityX + "px";
  193. bottomName.style.bottom = "0vh";
  194. bottomName.innerText = entity.name;
  195. const topName = document.querySelector("#top-name-" + element.dataset.key);
  196. topName.style.left = position.x + entityX + "px";
  197. topName.style.top = "20vh";
  198. topName.innerText = entity.name;
  199. if (entity.views[view].height.toNumber("meters") / 10 > config.height.toNumber("meters")) {
  200. topName.classList.add("top-name-needed");
  201. } else {
  202. topName.classList.remove("top-name-needed");
  203. }
  204. }
  205. function updateSizes(dirtyOnly = false) {
  206. drawScale(dirtyOnly);
  207. let ordered = Object.entries(entities);
  208. ordered.sort((e1, e2) => {
  209. if (e1[1].priority != e2[1].priority) {
  210. return e2[1].priority - e1[1].priority;
  211. } else {
  212. return e1[1].views[e1[1].view].height.value - e2[1].views[e2[1].view].height.value
  213. }
  214. });
  215. let zIndex = ordered.length;
  216. ordered.forEach(entity => {
  217. const element = document.querySelector("#entity-" + entity[0]);
  218. element.style.zIndex = zIndex;
  219. if (!dirtyOnly || entity[1].dirty) {
  220. updateEntityElement(entity[1], element, zIndex);
  221. entity[1].dirty = false;
  222. }
  223. zIndex -= 1;
  224. });
  225. }
  226. function drawScale(ifDirty = false) {
  227. if (ifDirty && !worldSizeDirty)
  228. return;
  229. function drawTicks(/** @type {CanvasRenderingContext2D} */ ctx, pixelsPer, heightPer) {
  230. let total = heightPer.clone();
  231. total.value = 0;
  232. for (let y = ctx.canvas.clientHeight - 50; y >= 50; y -= pixelsPer) {
  233. drawTick(ctx, 50, y, total);
  234. total = math.add(total, heightPer);
  235. }
  236. }
  237. function drawTick(/** @type {CanvasRenderingContext2D} */ ctx, x, y, value) {
  238. const oldStroke = ctx.strokeStyle;
  239. const oldFill = ctx.fillStyle;
  240. ctx.beginPath();
  241. ctx.moveTo(x, y);
  242. ctx.lineTo(x + 20, y);
  243. ctx.strokeStyle = "#000000";
  244. ctx.stroke();
  245. ctx.beginPath();
  246. ctx.moveTo(x + 20, y);
  247. ctx.lineTo(ctx.canvas.clientWidth - 70, y);
  248. ctx.strokeStyle = "#aaaaaa";
  249. ctx.stroke();
  250. ctx.beginPath();
  251. ctx.moveTo(ctx.canvas.clientWidth - 70, y);
  252. ctx.lineTo(ctx.canvas.clientWidth - 50, y);
  253. ctx.strokeStyle = "#000000";
  254. ctx.stroke();
  255. const oldFont = ctx.font;
  256. ctx.font = 'normal 24pt coda';
  257. ctx.fillStyle = "#dddddd";
  258. ctx.beginPath();
  259. ctx.fillText(value.format({ precision: 3 }), x + 20, y + 35);
  260. ctx.font = oldFont;
  261. ctx.strokeStyle = oldStroke;
  262. ctx.fillStyle = oldFill;
  263. }
  264. const canvas = document.querySelector("#display");
  265. /** @type {CanvasRenderingContext2D} */
  266. const ctx = canvas.getContext("2d");
  267. let pixelsPer = (ctx.canvas.clientHeight - 100) / config.height.toNumber();
  268. heightPer = 1;
  269. if (pixelsPer < config.minLineSize) {
  270. const factor = math.ceil(config.minLineSize / pixelsPer);
  271. heightPer *= factor;
  272. pixelsPer *= factor;
  273. }
  274. if (pixelsPer > config.maxLineSize) {
  275. const factor = math.ceil(pixelsPer / config.maxLineSize);
  276. heightPer /= factor;
  277. pixelsPer /= factor;
  278. }
  279. heightPer = math.unit(heightPer, config.height.units[0].unit.name)
  280. ctx.scale(1, 1);
  281. ctx.canvas.width = canvas.clientWidth;
  282. ctx.canvas.height = canvas.clientHeight;
  283. ctx.beginPath();
  284. ctx.rect(0, 0, canvas.width, canvas.height);
  285. ctx.fillStyle = "#333";
  286. ctx.fill();
  287. ctx.beginPath();
  288. ctx.moveTo(50, 50);
  289. ctx.lineTo(50, ctx.canvas.clientHeight - 50);
  290. ctx.stroke();
  291. ctx.beginPath();
  292. ctx.moveTo(ctx.canvas.clientWidth - 50, 50);
  293. ctx.lineTo(ctx.canvas.clientWidth - 50, ctx.canvas.clientHeight - 50);
  294. ctx.stroke();
  295. drawTicks(ctx, pixelsPer, heightPer);
  296. }
  297. // Entities are generated as needed, and we make a copy
  298. // every time - the resulting objects get mutated, after all.
  299. // But we also want to be able to read some information without
  300. // calling the constructor -- e.g. making a list of authors and
  301. // owners. So, this function is used to generate that information.
  302. // It is invoked like makeEntity so that it can be dropped in easily,
  303. // but returns an object that lets you construct many copies of an entity,
  304. // rather than creating a new entity.
  305. function createEntityMaker(info, views, sizes) {
  306. const maker = {};
  307. maker.name = info.name;
  308. maker.constructor = () => makeEntity(info, views, sizes);
  309. maker.authors = [];
  310. maker.owners = [];
  311. Object.values(views).forEach(view => {
  312. const authors = authorsOf(view.image.source);
  313. if (authors) {
  314. authors.forEach(author => {
  315. if (maker.authors.indexOf(author) == -1) {
  316. maker.authors.push(author);
  317. }
  318. });
  319. }
  320. const owners = ownersOf(view.image.source);
  321. if (owners) {
  322. owners.forEach(owner => {
  323. if (maker.owners.indexOf(owner) == -1) {
  324. maker.owners.push(owner);
  325. }
  326. });
  327. }
  328. });
  329. return maker;
  330. }
  331. // This function serializes and parses its arguments to avoid sharing
  332. // references to a common object. This allows for the objects to be
  333. // safely mutated.
  334. function makeEntity(info, views, sizes) {
  335. const entityTemplate = {
  336. name: info.name,
  337. identifier: info.name,
  338. scale: 1,
  339. info: JSON.parse(JSON.stringify(info)),
  340. views: JSON.parse(JSON.stringify(views), math.reviver),
  341. sizes: sizes === undefined ? [] : JSON.parse(JSON.stringify(sizes), math.reviver),
  342. init: function () {
  343. const entity = this;
  344. Object.entries(this.views).forEach(([viewKey, view]) => {
  345. view.parent = this;
  346. if (this.defaultView === undefined) {
  347. this.defaultView = viewKey;
  348. this.view = viewKey;
  349. }
  350. Object.entries(view.attributes).forEach(([key, val]) => {
  351. Object.defineProperty(
  352. view,
  353. key,
  354. {
  355. get: function () {
  356. return math.multiply(Math.pow(this.parent.scale, this.attributes[key].power), this.attributes[key].base);
  357. },
  358. set: function (value) {
  359. const newScale = Math.pow(math.divide(value, this.attributes[key].base), 1 / this.attributes[key].power);
  360. this.parent.scale = newScale;
  361. }
  362. }
  363. )
  364. });
  365. });
  366. this.sizes.forEach(size => {
  367. if (size.default === true) {
  368. this.views[this.defaultView].height = size.height;
  369. this.size = size;
  370. }
  371. });
  372. if (this.size === undefined && this.sizes.length > 0) {
  373. this.views[this.defaultView].height = this.sizes[0].height;
  374. this.size = this.sizes[0];
  375. console.warn("No default size set for " + info.name);
  376. } else if (this.sizes.length == 0) {
  377. this.sizes = [
  378. {
  379. name: "Normal",
  380. height: this.views[this.defaultView].height
  381. }
  382. ];
  383. this.size = this.sizes[0];
  384. }
  385. this.desc = {};
  386. Object.entries(this.info).forEach(([key, value]) => {
  387. Object.defineProperty(
  388. this.desc,
  389. key,
  390. {
  391. get: function () {
  392. let text = value.text;
  393. if (entity.views[entity.view].info) {
  394. if (entity.views[entity.view].info[key]) {
  395. text = combineInfo(text, entity.views[entity.view].info[key]);
  396. }
  397. }
  398. if (entity.size.info) {
  399. if (entity.size.info[key]) {
  400. text = combineInfo(text, entity.size.info[key]);
  401. }
  402. }
  403. return { title: value.title, text: text };
  404. }
  405. }
  406. )
  407. });
  408. delete this.init;
  409. return this;
  410. }
  411. }.init();
  412. return entityTemplate;
  413. }
  414. function combineInfo(existing, next) {
  415. switch (next.mode) {
  416. case "replace":
  417. return next.text;
  418. case "prepend":
  419. return next.text + existing;
  420. case "append":
  421. return existing + next.text;
  422. }
  423. return existing;
  424. }
  425. function clickDown(target, x, y) {
  426. clicked = target;
  427. const rect = target.getBoundingClientRect();
  428. let entX = document.querySelector("#entities").getBoundingClientRect().x;
  429. let entY = document.querySelector("#entities").getBoundingClientRect().y;
  430. dragOffsetX = x - rect.left + entX;
  431. dragOffsetY = y - rect.top + entY;
  432. clickTimeout = setTimeout(() => { dragging = true }, 200)
  433. target.classList.add("no-transition");
  434. }
  435. // could we make this actually detect the menu area?
  436. function hoveringInDeleteArea(e) {
  437. return e.clientY < document.body.clientHeight / 10;
  438. }
  439. function clickUp(e) {
  440. clearTimeout(clickTimeout);
  441. if (clicked) {
  442. if (dragging) {
  443. dragging = false;
  444. if (hoveringInDeleteArea(e)) {
  445. removeEntity(clicked);
  446. document.querySelector("#menubar").classList.remove("hover-delete");
  447. }
  448. } else {
  449. select(clicked);
  450. }
  451. clicked.classList.remove("no-transition");
  452. clicked = null;
  453. }
  454. }
  455. function deselect() {
  456. if (selected) {
  457. selected.classList.remove("selected");
  458. }
  459. document.getElementById("options-selected-entity-none").selected = "selected";
  460. clearAttribution();
  461. selected = null;
  462. clearViewList();
  463. clearEntityOptions();
  464. clearViewOptions();
  465. document.querySelector("#delete-entity").disabled = true;
  466. document.querySelector("#grow").disabled = true;
  467. document.querySelector("#shrink").disabled = true;
  468. document.querySelector("#fit").disabled = true;
  469. }
  470. function select(target) {
  471. deselect();
  472. selected = target;
  473. selectedEntity = entities[target.dataset.key];
  474. document.getElementById("options-selected-entity-" + target.dataset.key).selected = "selected";
  475. selected.classList.add("selected");
  476. displayAttribution(selectedEntity.views[selectedEntity.view].image.source);
  477. configViewList(selectedEntity, selectedEntity.view);
  478. configEntityOptions(selectedEntity, selectedEntity.view);
  479. configViewOptions(selectedEntity, selectedEntity.view);
  480. document.querySelector("#delete-entity").disabled = false;
  481. document.querySelector("#grow").disabled = false;
  482. document.querySelector("#shrink").disabled = false;
  483. document.querySelector("#fit").disabled = false;
  484. }
  485. function configViewList(entity, selectedView) {
  486. const list = document.querySelector("#entity-view");
  487. list.innerHTML = "";
  488. list.style.display = "block";
  489. Object.keys(entity.views).forEach(view => {
  490. const option = document.createElement("option");
  491. option.innerText = entity.views[view].name;
  492. option.value = view;
  493. if (view === selectedView) {
  494. option.selected = true;
  495. }
  496. list.appendChild(option);
  497. });
  498. }
  499. function clearViewList() {
  500. const list = document.querySelector("#entity-view");
  501. list.innerHTML = "";
  502. list.style.display = "none";
  503. }
  504. function updateWorldOptions(entity, view) {
  505. const heightInput = document.querySelector("#options-height-value");
  506. const heightSelect = document.querySelector("#options-height-unit");
  507. const converted = config.height.toNumber(heightSelect.value);
  508. setNumericInput(heightInput, converted);
  509. }
  510. function configEntityOptions(entity, view) {
  511. const holder = document.querySelector("#options-entity");
  512. document.querySelector("#entity-category-header").style.display = "block";
  513. document.querySelector("#entity-category").style.display = "block";
  514. holder.innerHTML = "";
  515. const scaleLabel = document.createElement("div");
  516. scaleLabel.classList.add("options-label");
  517. scaleLabel.innerText = "Scale";
  518. const scaleRow = document.createElement("div");
  519. scaleRow.classList.add("options-row");
  520. const scaleInput = document.createElement("input");
  521. scaleInput.classList.add("options-field-numeric");
  522. scaleInput.id = "options-entity-scale";
  523. scaleInput.addEventListener("change", e => {
  524. entity.scale = e.target.value == 0 ? 1 : e.target.value;
  525. entity.dirty = true;
  526. if (config.autoFit) {
  527. fitWorld();
  528. } else {
  529. updateSizes(true);
  530. }
  531. updateEntityOptions(entity, view);
  532. updateViewOptions(entity, view);
  533. });
  534. scaleInput.addEventListener("keydown", e => {
  535. e.stopPropagation();
  536. })
  537. scaleInput.setAttribute("min", 1);
  538. scaleInput.setAttribute("type", "number");
  539. setNumericInput(scaleInput, entity.scale);
  540. scaleRow.appendChild(scaleInput);
  541. holder.appendChild(scaleLabel);
  542. holder.appendChild(scaleRow);
  543. const nameLabel = document.createElement("div");
  544. nameLabel.classList.add("options-label");
  545. nameLabel.innerText = "Name";
  546. const nameRow = document.createElement("div");
  547. nameRow.classList.add("options-row");
  548. const nameInput = document.createElement("input");
  549. nameInput.classList.add("options-field-text");
  550. nameInput.value = entity.name;
  551. nameInput.addEventListener("input", e => {
  552. entity.name = e.target.value;
  553. entity.dirty = true;
  554. updateSizes(true);
  555. })
  556. nameInput.addEventListener("keydown", e => {
  557. e.stopPropagation();
  558. })
  559. nameRow.appendChild(nameInput);
  560. holder.appendChild(nameLabel);
  561. holder.appendChild(nameRow);
  562. const defaultHolder = document.querySelector("#options-entity-defaults");
  563. defaultHolder.innerHTML = "";
  564. entity.sizes.forEach(defaultInfo => {
  565. const button = document.createElement("button");
  566. button.classList.add("options-button");
  567. button.innerText = defaultInfo.name;
  568. button.addEventListener("click", e => {
  569. entity.views[entity.defaultView].height = defaultInfo.height;
  570. entity.dirty = true;
  571. updateEntityOptions(entity, entity.view);
  572. updateViewOptions(entity, entity.view);
  573. if (!checkFitWorld()) {
  574. updateSizes(true);
  575. }
  576. });
  577. defaultHolder.appendChild(button);
  578. });
  579. document.querySelector("#options-order-display").innerText = entity.priority;
  580. document.querySelector("#options-ordering").style.display = "flex";
  581. }
  582. function updateEntityOptions(entity, view) {
  583. const scaleInput = document.querySelector("#options-entity-scale");
  584. setNumericInput(scaleInput, entity.scale);
  585. document.querySelector("#options-order-display").innerText = entity.priority;
  586. }
  587. function clearEntityOptions() {
  588. document.querySelector("#entity-category-header").style.display = "none";
  589. document.querySelector("#entity-category").style.display = "none";
  590. /*
  591. const holder = document.querySelector("#options-entity");
  592. holder.innerHTML = "";
  593. document.querySelector("#options-entity-defaults").innerHTML = "";
  594. document.querySelector("#options-ordering").style.display = "none";
  595. document.querySelector("#options-ordering").style.display = "none";*/
  596. }
  597. function configViewOptions(entity, view) {
  598. const holder = document.querySelector("#options-view");
  599. document.querySelector("#view-category-header").style.display = "block";
  600. document.querySelector("#view-category").style.display = "block";
  601. holder.innerHTML = "";
  602. Object.entries(entity.views[view].attributes).forEach(([key, val]) => {
  603. const label = document.createElement("div");
  604. label.classList.add("options-label");
  605. label.innerText = val.name;
  606. holder.appendChild(label);
  607. const row = document.createElement("div");
  608. row.classList.add("options-row");
  609. holder.appendChild(row);
  610. const input = document.createElement("input");
  611. input.classList.add("options-field-numeric");
  612. input.id = "options-view-" + key + "-input";
  613. input.setAttribute("type", "number");
  614. input.setAttribute("min", 1);
  615. setNumericInput(input, entity.views[view][key].value);
  616. const select = document.createElement("select");
  617. select.classList.add("options-field-unit");
  618. select.id = "options-view-" + key + "-select"
  619. unitChoices[val.type].forEach(name => {
  620. const option = document.createElement("option");
  621. option.innerText = name;
  622. select.appendChild(option);
  623. });
  624. input.addEventListener("change", e => {
  625. const value = input.value == 0 ? 1 : input.value;
  626. entity.views[view][key] = math.unit(value, select.value);
  627. entity.dirty = true;
  628. if (config.autoFit) {
  629. fitWorld();
  630. } else {
  631. updateSizes(true);
  632. }
  633. updateEntityOptions(entity, view);
  634. updateViewOptions(entity, view, key);
  635. });
  636. input.addEventListener("keydown", e => {
  637. e.stopPropagation();
  638. })
  639. select.setAttribute("oldUnit", select.value);
  640. // TODO does this ever cause a change in the world?
  641. select.addEventListener("input", e => {
  642. const value = input.value == 0 ? 1 : input.value;
  643. const oldUnit = select.getAttribute("oldUnit");
  644. entity.views[entity.view][key] = math.unit(value, oldUnit).to(select.value);
  645. entity.dirty = true;
  646. setNumericInput(input, entity.views[entity.view][key].toNumber(select.value));
  647. select.setAttribute("oldUnit", select.value);
  648. if (config.autoFit) {
  649. fitWorld();
  650. } else {
  651. updateSizes(true);
  652. }
  653. updateEntityOptions(entity, view);
  654. updateViewOptions(entity, view, key);
  655. });
  656. row.appendChild(input);
  657. row.appendChild(select);
  658. });
  659. }
  660. function updateViewOptions(entity, view, changed) {
  661. Object.entries(entity.views[view].attributes).forEach(([key, val]) => {
  662. if (key != changed) {
  663. const input = document.querySelector("#options-view-" + key + "-input");
  664. const select = document.querySelector("#options-view-" + key + "-select");
  665. const currentUnit = select.value;
  666. const convertedAmount = entity.views[view][key].toNumber(currentUnit);
  667. setNumericInput(input, convertedAmount);
  668. }
  669. });
  670. }
  671. function setNumericInput(input, value, round = 3) {
  672. input.value = math.round(value, round);
  673. }
  674. function getSortedEntities() {
  675. return Object.keys(entities).sort((a, b) => {
  676. const entA = entities[a];
  677. const entB = entities[b];
  678. const viewA = entA.view;
  679. const viewB = entB.view;
  680. const heightA = entA.views[viewA].height.to("meter").value;
  681. const heightB = entB.views[viewB].height.to("meter").value;
  682. return heightA - heightB;
  683. });
  684. }
  685. function clearViewOptions() {
  686. document.querySelector("#view-category-header").style.display = "none";
  687. document.querySelector("#view-category").style.display = "none";
  688. }
  689. // this is a crime against humanity, and also stolen from
  690. // stack overflow
  691. // https://stackoverflow.com/questions/38487569/click-through-png-image-only-if-clicked-coordinate-is-transparent
  692. const testCanvas = document.createElement("canvas");
  693. testCanvas.id = "test-canvas";
  694. const testCtx = testCanvas.getContext("2d");
  695. function testClick(event) {
  696. // oh my god I can't believe I'm doing this
  697. const target = event.target;
  698. if (navigator.userAgent.indexOf("Firefox") != -1) {
  699. clickDown(target.parentElement, event.clientX, event.clientY);
  700. return;
  701. }
  702. // Get click coordinates
  703. let w = target.width;
  704. let h = target.height;
  705. let ratioW = 1, ratioH = 1;
  706. // Limit the size of the canvas so that very large images don't cause problems)
  707. if (w > 1000) {
  708. ratioW = w / 1000;
  709. w /= ratioW;
  710. h /= ratioW;
  711. }
  712. if (h > 1000) {
  713. ratioH = h / 1000;
  714. w /= ratioH;
  715. h /= ratioH;
  716. }
  717. const ratio = ratioW * ratioH;
  718. var x = event.clientX - target.getBoundingClientRect().x,
  719. y = event.clientY - target.getBoundingClientRect().y,
  720. alpha;
  721. testCtx.canvas.width = w;
  722. testCtx.canvas.height = h;
  723. // Draw image to canvas
  724. // and read Alpha channel value
  725. testCtx.drawImage(target, 0, 0, w, h);
  726. alpha = testCtx.getImageData(Math.floor(x / ratio), Math.floor(y / ratio), 1, 1).data[3]; // [0]R [1]G [2]B [3]A
  727. // If pixel is transparent,
  728. // retrieve the element underneath and trigger its click event
  729. if (alpha === 0) {
  730. const oldDisplay = target.style.display;
  731. target.style.display = "none";
  732. const newTarget = document.elementFromPoint(event.clientX, event.clientY);
  733. newTarget.dispatchEvent(new MouseEvent(event.type, {
  734. "clientX": event.clientX,
  735. "clientY": event.clientY
  736. }));
  737. target.style.display = oldDisplay;
  738. } else {
  739. clickDown(target.parentElement, event.clientX, event.clientY);
  740. }
  741. }
  742. function arrangeEntities(order) {
  743. let x = 0.1;
  744. order.forEach(key => {
  745. document.querySelector("#entity-" + key).dataset.x = x;
  746. x += 0.8 / (order.length - 1);
  747. });
  748. updateSizes();
  749. }
  750. function removeAllEntities() {
  751. Object.keys(entities).forEach(key => {
  752. removeEntity(document.querySelector("#entity-" + key));
  753. });
  754. }
  755. function clearAttribution() {
  756. document.querySelector("#attribution-category-header").style.display = "none";
  757. document.querySelector("#options-attribution").style.display = "none";
  758. }
  759. function displayAttribution(file) {
  760. document.querySelector("#attribution-category-header").style.display = "block";
  761. document.querySelector("#options-attribution").style.display = "inline";
  762. const authors = authorsOfFull(file);
  763. const owners = ownersOfFull(file);
  764. const source = sourceOf(file);
  765. const authorHolder = document.querySelector("#options-attribution-authors");
  766. const ownerHolder = document.querySelector("#options-attribution-owners");
  767. const sourceHolder = document.querySelector("#options-attribution-source");
  768. if (authors === []) {
  769. const div = document.createElement("div");
  770. div.innerText = "Unknown";
  771. authorHolder.innerHTML = "";
  772. authorHolder.appendChild(div);
  773. } else if (authors === undefined) {
  774. const div = document.createElement("div");
  775. div.innerText = "Not yet entered";
  776. authorHolder.innerHTML = "";
  777. authorHolder.appendChild(div);
  778. } else {
  779. authorHolder.innerHTML = "";
  780. const list = document.createElement("ul");
  781. authorHolder.appendChild(list);
  782. authors.forEach(author => {
  783. const authorEntry = document.createElement("li");
  784. if (author.url) {
  785. const link = document.createElement("a");
  786. link.href = author.url;
  787. link.innerText = author.name;
  788. authorEntry.appendChild(link);
  789. } else {
  790. const div = document.createElement("div");
  791. div.innerText = author.name;
  792. authorEntry.appendChild(div);
  793. }
  794. list.appendChild(authorEntry);
  795. });
  796. }
  797. if (owners === []) {
  798. const div = document.createElement("div");
  799. div.innerText = "Unknown";
  800. ownerHolder.innerHTML = "";
  801. ownerHolder.appendChild(div);
  802. } else if (owners === undefined) {
  803. const div = document.createElement("div");
  804. div.innerText = "Not yet entered";
  805. ownerHolder.innerHTML = "";
  806. ownerHolder.appendChild(div);
  807. } else {
  808. ownerHolder.innerHTML = "";
  809. const list = document.createElement("ul");
  810. ownerHolder.appendChild(list);
  811. owners.forEach(owner => {
  812. const ownerEntry = document.createElement("li");
  813. if (owner.url) {
  814. const link = document.createElement("a");
  815. link.href = owner.url;
  816. link.innerText = owner.name;
  817. ownerEntry.appendChild(link);
  818. } else {
  819. const div = document.createElement("div");
  820. div.innerText = owner.name;
  821. ownerEntry.appendChild(div);
  822. }
  823. list.appendChild(ownerEntry);
  824. });
  825. }
  826. if (source === null) {
  827. const div = document.createElement("div");
  828. div.innerText = "No link";
  829. sourceHolder.innerHTML = "";
  830. sourceHolder.appendChild(div);
  831. } else if (source === undefined) {
  832. const div = document.createElement("div");
  833. div.innerText = "Not yet entered";
  834. sourceHolder.innerHTML = "";
  835. sourceHolder.appendChild(div);
  836. } else {
  837. sourceHolder.innerHTML = "";
  838. const link = document.createElement("a");
  839. link.style.display = "block";
  840. link.href = source;
  841. link.innerText = new URL(source).host;
  842. sourceHolder.appendChild(link);
  843. }
  844. }
  845. function removeEntity(element) {
  846. if (selected == element) {
  847. deselect();
  848. }
  849. const option = document.querySelector("#options-selected-entity-" + element.dataset.key);
  850. option.parentElement.removeChild(option);
  851. delete entities[element.dataset.key];
  852. const bottomName = document.querySelector("#bottom-name-" + element.dataset.key);
  853. const topName = document.querySelector("#top-name-" + element.dataset.key);
  854. bottomName.parentElement.removeChild(bottomName);
  855. topName.parentElement.removeChild(topName);
  856. element.parentElement.removeChild(element);
  857. }
  858. function checkEntity(entity) {
  859. Object.values(entity.views).forEach(view => {
  860. if (authorsOf(view.image.source) === undefined) {
  861. console.warn("No authors: " + view.image.source);
  862. }
  863. });
  864. }
  865. function displayEntity(entity, view, x, y, selectEntity = false, refresh = false) {
  866. checkEntity(entity);
  867. const box = document.createElement("div");
  868. box.classList.add("entity-box");
  869. const img = document.createElement("img");
  870. img.classList.add("entity-image");
  871. img.addEventListener("dragstart", e => {
  872. e.preventDefault();
  873. });
  874. const nameTag = document.createElement("div");
  875. nameTag.classList.add("entity-name");
  876. nameTag.innerText = entity.name;
  877. box.appendChild(img);
  878. box.appendChild(nameTag);
  879. const image = entity.views[view].image;
  880. img.src = image.source;
  881. if (image.bottom !== undefined) {
  882. img.style.setProperty("--offset", ((-1 + image.bottom) * 100) + "%")
  883. } else {
  884. img.style.setProperty("--offset", ((-1) * 100) + "%")
  885. }
  886. box.dataset.x = x;
  887. box.dataset.y = y;
  888. img.addEventListener("mousedown", e => { testClick(e); e.stopPropagation() });
  889. img.addEventListener("touchstart", e => {
  890. const fakeEvent = {
  891. target: e.target,
  892. clientX: e.touches[0].clientX,
  893. clientY: e.touches[0].clientY
  894. };
  895. testClick(fakeEvent);
  896. });
  897. const heightBar = document.createElement("div");
  898. heightBar.classList.add("height-bar");
  899. box.appendChild(heightBar);
  900. box.id = "entity-" + entityIndex;
  901. box.dataset.key = entityIndex;
  902. entity.view = view;
  903. entity.priority = 0;
  904. entities[entityIndex] = entity;
  905. entity.index = entityIndex;
  906. const world = document.querySelector("#entities");
  907. world.appendChild(box);
  908. const bottomName = document.createElement("div");
  909. bottomName.classList.add("bottom-name");
  910. bottomName.id = "bottom-name-" + entityIndex;
  911. bottomName.innerText = entity.name;
  912. bottomName.addEventListener("click", () => select(box));
  913. world.appendChild(bottomName);
  914. const topName = document.createElement("div");
  915. topName.classList.add("top-name");
  916. topName.id = "top-name-" + entityIndex;
  917. topName.innerText = entity.name;
  918. topName.addEventListener("click", () => select(box));
  919. world.appendChild(topName);
  920. const entityOption = document.createElement("option");
  921. entityOption.id = "options-selected-entity-" + entityIndex;
  922. entityOption.value = entityIndex;
  923. entityOption.innerText = entity.name;
  924. document.getElementById("options-selected-entity").appendChild(entityOption);
  925. entityIndex += 1;
  926. if (config.autoFit) {
  927. fitWorld();
  928. }
  929. if (selectEntity)
  930. select(box);
  931. entity.dirty = true;
  932. if (refresh)
  933. updateSizes(true);
  934. }
  935. window.onblur = function () {
  936. altHeld = false;
  937. shiftHeld = false;
  938. }
  939. window.onfocus = function () {
  940. window.dispatchEvent(new Event("keydown"));
  941. }
  942. // thanks to https://developers.google.com/web/fundamentals/native-hardware/fullscreen
  943. function toggleFullScreen() {
  944. var doc = window.document;
  945. var docEl = doc.documentElement;
  946. var requestFullScreen = docEl.requestFullscreen || docEl.mozRequestFullScreen || docEl.webkitRequestFullScreen || docEl.msRequestFullscreen;
  947. var cancelFullScreen = doc.exitFullscreen || doc.mozCancelFullScreen || doc.webkitExitFullscreen || doc.msExitFullscreen;
  948. if (!doc.fullscreenElement && !doc.mozFullScreenElement && !doc.webkitFullscreenElement && !doc.msFullscreenElement) {
  949. requestFullScreen.call(docEl);
  950. }
  951. else {
  952. cancelFullScreen.call(doc);
  953. }
  954. }
  955. function handleResize() {
  956. const oldCanvasWidth = canvasWidth;
  957. entityX = document.querySelector("#entities").getBoundingClientRect().x;
  958. canvasWidth = document.querySelector("#display").clientWidth - 100;
  959. canvasHeight = document.querySelector("#display").clientHeight - 50;
  960. const change = oldCanvasWidth / canvasWidth;
  961. doHorizReposition(change);
  962. updateSizes();
  963. }
  964. function doHorizReposition(change) {
  965. Object.keys(entities).forEach(key => {
  966. const element = document.querySelector("#entity-" + key);
  967. const x = element.dataset.x;
  968. element.dataset.x = (x - 0.5) * change + 0.5;
  969. });
  970. }
  971. function prepareMenu() {
  972. const menubar = document.querySelector("#popout-menu");
  973. [
  974. {
  975. name: "Show/hide sidebar",
  976. id: "menu-toggle-sidebar",
  977. icon: "fas fa-chevron-circle-down",
  978. rotates: true
  979. },
  980. {
  981. name: "Fullscreen",
  982. id: "menu-fullscreen",
  983. icon: "fas fa-compress"
  984. },
  985. {
  986. name: "Clear",
  987. id: "menu-clear",
  988. icon: "fas fa-file"
  989. },
  990. {
  991. name: "Sort by height",
  992. id: "menu-order-height",
  993. icon: "fas fa-sort-numeric-up"
  994. },
  995. {
  996. name: "Permalink",
  997. id: "menu-permalink",
  998. icon: "fas fa-link"
  999. },
  1000. {
  1001. name: "Export to clipboard",
  1002. id: "menu-export",
  1003. icon: "fas fa-share"
  1004. },
  1005. {
  1006. name: "Import from clipboard",
  1007. id: "menu-import",
  1008. icon: "fas fa-share",
  1009. classes: ["flipped"]
  1010. },
  1011. {
  1012. name: "Save",
  1013. id: "menu-save",
  1014. icon: "fas fa-download"
  1015. },
  1016. {
  1017. name: "Load",
  1018. id: "menu-load",
  1019. icon: "fas fa-upload"
  1020. },
  1021. {
  1022. name: "Load Autosave",
  1023. id: "menu-load-autosave",
  1024. icon: "fas fa-redo"
  1025. },
  1026. {
  1027. name: "Add Image",
  1028. id: "menu-add-image",
  1029. icon: "fas fa-camera"
  1030. }
  1031. ].forEach(entry => {
  1032. const buttonHolder = document.createElement("div");
  1033. buttonHolder.classList.add("menu-button-holder");
  1034. const button = document.createElement("button");
  1035. button.id = entry.id;
  1036. button.classList.add("menu-button");
  1037. const icon = document.createElement("i");
  1038. icon.classList.add(...entry.icon.split(" "));
  1039. if (entry.rotates) {
  1040. icon.classList.add("rotate-backward", "transitions");
  1041. }
  1042. if (entry.classes) {
  1043. entry.classes.forEach(cls => icon.classList.add(cls));
  1044. }
  1045. const actionText = document.createElement("span");
  1046. actionText.innerText = entry.name;
  1047. actionText.classList.add("menu-text");
  1048. const srText = document.createElement("span");
  1049. srText.classList.add("sr-only");
  1050. srText.innerText = entry.name;
  1051. button.appendChild(icon);
  1052. button.appendChild(srText);
  1053. buttonHolder.appendChild(button);
  1054. buttonHolder.appendChild(actionText);
  1055. menubar.appendChild(buttonHolder);
  1056. });
  1057. if (checkHelpDate()) {
  1058. document.querySelector("#open-help").classList.add("highlighted");
  1059. }
  1060. }
  1061. const lastHelpChange = 1587847743294;
  1062. function checkHelpDate() {
  1063. try {
  1064. const old = localStorage.getItem("help-viewed");
  1065. if (old === null || old < lastHelpChange) {
  1066. return true;
  1067. }
  1068. return false;
  1069. } catch {
  1070. console.warn("Could not set the help-viewed date");
  1071. return false;
  1072. }
  1073. }
  1074. function setHelpDate() {
  1075. try {
  1076. localStorage.setItem("help-viewed", Date.now());
  1077. } catch {
  1078. console.warn("Could not set the help-viewed date");
  1079. }
  1080. }
  1081. function doScroll() {
  1082. document.querySelectorAll(".entity-box").forEach(element => {
  1083. element.dataset.x = parseFloat(element.dataset.x) + scrollDirection / 180;
  1084. });
  1085. updateSizes();
  1086. scrollDirection *= 1.05;
  1087. }
  1088. function doZoom() {
  1089. const oldHeight = config.height;
  1090. setWorldHeight(oldHeight, math.multiply(oldHeight, 1 + zoomDirection / 10));
  1091. zoomDirection *= 1.05;
  1092. }
  1093. function doSize() {
  1094. if (selected) {
  1095. const entity = entities[selected.dataset.key];
  1096. const oldHeight = entity.views[entity.view].height;
  1097. entity.views[entity.view].height = math.multiply(oldHeight, 1 + sizeDirection / 20);
  1098. entity.dirty = true;
  1099. updateEntityOptions(entity, entity.view);
  1100. updateViewOptions(entity, entity.view);
  1101. updateSizes(true);
  1102. sizeDirection *= 1.05;
  1103. const ownHeight = entity.views[entity.view].height.toNumber("meters");
  1104. const worldHeight = config.height.toNumber("meters");
  1105. console.log(ownHeight, worldHeight)
  1106. if (ownHeight > worldHeight) {
  1107. setWorldHeight(config.height, entity.views[entity.view].height)
  1108. } else if (ownHeight * 10 < worldHeight) {
  1109. setWorldHeight(config.height, math.multiply(entity.views[entity.view].height, 10));
  1110. }
  1111. }
  1112. }
  1113. function prepareHelp() {
  1114. const toc = document.querySelector("#table-of-contents");
  1115. const holder = document.querySelector("#help-contents-holder");
  1116. document.querySelectorAll("#help-contents h2").forEach(header => {
  1117. const li = document.createElement("li");
  1118. li.innerText = header.textContent;
  1119. li.addEventListener("click", e => {
  1120. holder.scrollTop = header.offsetTop;
  1121. });
  1122. toc.appendChild(li);
  1123. });
  1124. }
  1125. document.addEventListener("DOMContentLoaded", () => {
  1126. prepareMenu();
  1127. prepareEntities();
  1128. prepareHelp();
  1129. document.querySelector("#open-help").addEventListener("click", e => {
  1130. setHelpDate();
  1131. document.querySelector("#help-menu").classList.add("visible");
  1132. document.querySelector("#open-help").classList.remove("highlighted");
  1133. });
  1134. document.querySelector("#close-help").addEventListener("click", e => {
  1135. document.querySelector("#help-menu").classList.remove("visible");
  1136. });
  1137. document.querySelector("#copy-screenshot").addEventListener("click", e => {
  1138. copyScreenshot();
  1139. toast("Copied to clipboard!");
  1140. });
  1141. document.querySelector("#save-screenshot").addEventListener("click", e => {
  1142. saveScreenshot();
  1143. });
  1144. document.querySelector("#toggle-menu").addEventListener("click", e => {
  1145. const popoutMenu = document.querySelector("#popout-menu");
  1146. if (popoutMenu.classList.contains("visible")) {
  1147. popoutMenu.classList.remove("visible");
  1148. } else {
  1149. const rect = e.target.getBoundingClientRect();
  1150. popoutMenu.classList.add("visible");
  1151. popoutMenu.style.left = rect.x + rect.width + 10 + "px";
  1152. popoutMenu.style.top = rect.y + rect.height + 10 + "px";
  1153. }
  1154. e.stopPropagation();
  1155. });
  1156. document.querySelector("#popout-menu").addEventListener("click", e => {
  1157. e.stopPropagation();
  1158. });
  1159. document.addEventListener("click", e => {
  1160. document.querySelector("#popout-menu").classList.remove("visible");
  1161. });
  1162. window.addEventListener("unload", () => saveScene("autosave"));
  1163. document.querySelector("#options-selected-entity").addEventListener("input", e => {
  1164. if (e.target.value == "none") {
  1165. deselect()
  1166. } else {
  1167. select(document.querySelector("#entity-" + e.target.value));
  1168. }
  1169. });
  1170. document.querySelector("#menu-toggle-sidebar").addEventListener("click", e => {
  1171. const sidebar = document.querySelector("#options");
  1172. if (sidebar.classList.contains("hidden")) {
  1173. sidebar.classList.remove("hidden");
  1174. e.target.classList.remove("rotate-forward");
  1175. e.target.classList.add("rotate-backward");
  1176. } else {
  1177. sidebar.classList.add("hidden");
  1178. e.target.classList.add("rotate-forward");
  1179. e.target.classList.remove("rotate-backward");
  1180. }
  1181. handleResize();
  1182. });
  1183. document.querySelector("#menu-fullscreen").addEventListener("click", toggleFullScreen);
  1184. document.querySelector("#options-show-extra").addEventListener("input", e => {
  1185. document.body.classList[e.target.checked ? "add" : "remove"]("show-extra-options");
  1186. });
  1187. document.querySelector("#options-world-show-names").addEventListener("input", e => {
  1188. document.body.classList[e.target.checked ? "add" : "remove"]("toggle-entity-name");
  1189. });
  1190. document.querySelector("#options-world-show-bottom-names").addEventListener("input", e => {
  1191. document.body.classList[e.target.checked ? "add" : "remove"]("toggle-bottom-name");
  1192. });
  1193. document.querySelector("#options-world-show-top-names").addEventListener("input", e => {
  1194. document.body.classList[e.target.checked ? "add" : "remove"]("toggle-top-name");
  1195. });
  1196. document.querySelector("#options-world-show-height-bars").addEventListener("input", e => {
  1197. document.body.classList[e.target.checked ? "add" : "remove"]("toggle-height-bars");
  1198. });
  1199. document.querySelector("#options-world-show-entity-glow").addEventListener("input", e => {
  1200. document.body.classList[e.target.checked ? "add" : "remove"]("toggle-entity-glow");
  1201. });
  1202. document.querySelector("#options-world-show-bottom-cover").addEventListener("input", e => {
  1203. document.body.classList[e.target.checked ? "add" : "remove"]("toggle-bottom-cover");
  1204. });
  1205. document.querySelector("#options-world-show-scale").addEventListener("input", e => {
  1206. document.body.classList[e.target.checked ? "add" : "remove"]("toggle-scale");
  1207. });
  1208. document.querySelector("#options-order-forward").addEventListener("click", e => {
  1209. if (selected) {
  1210. entities[selected.dataset.key].priority += 1;
  1211. }
  1212. document.querySelector("#options-order-display").innerText = entities[selected.dataset.key].priority;
  1213. updateSizes();
  1214. });
  1215. document.querySelector("#options-order-back").addEventListener("click", e => {
  1216. if (selected) {
  1217. entities[selected.dataset.key].priority -= 1;
  1218. }
  1219. document.querySelector("#options-order-display").innerText = entities[selected.dataset.key].priority;
  1220. updateSizes();
  1221. });
  1222. const sceneChoices = document.querySelector("#scene-choices");
  1223. Object.entries(scenes).forEach(([id, scene]) => {
  1224. const option = document.createElement("option");
  1225. option.innerText = id;
  1226. option.value = id;
  1227. sceneChoices.appendChild(option);
  1228. });
  1229. document.querySelector("#load-scene").addEventListener("click", e => {
  1230. const chosen = sceneChoices.value;
  1231. removeAllEntities();
  1232. scenes[chosen]();
  1233. });
  1234. entityX = document.querySelector("#entities").getBoundingClientRect().x;
  1235. canvasWidth = document.querySelector("#display").clientWidth - 100;
  1236. canvasHeight = document.querySelector("#display").clientHeight - 50;
  1237. document.querySelector("#options-height-value").addEventListener("change", e => {
  1238. updateWorldHeight();
  1239. })
  1240. document.querySelector("#options-height-value").addEventListener("keydown", e => {
  1241. e.stopPropagation();
  1242. })
  1243. const unitSelector = document.querySelector("#options-height-unit");
  1244. unitChoices.length.forEach(lengthOption => {
  1245. const option = document.createElement("option");
  1246. option.innerText = lengthOption;
  1247. option.value = lengthOption;
  1248. if (lengthOption === "meters") {
  1249. option.selected = true;
  1250. }
  1251. unitSelector.appendChild(option);
  1252. });
  1253. unitSelector.setAttribute("oldUnit", "meters");
  1254. unitSelector.addEventListener("input", e => {
  1255. checkFitWorld();
  1256. const scaleInput = document.querySelector("#options-height-value");
  1257. const newVal = math.unit(scaleInput.value, unitSelector.getAttribute("oldUnit")).toNumber(e.target.value);
  1258. setNumericInput(scaleInput, newVal);
  1259. updateWorldHeight();
  1260. unitSelector.setAttribute("oldUnit", unitSelector.value);
  1261. });
  1262. param = new URL(window.location.href).searchParams.get("scene");
  1263. if (param === null) {
  1264. scenes["Default"]();
  1265. }
  1266. else {
  1267. try {
  1268. const data = JSON.parse(b64DecodeUnicode(param));
  1269. if (data.entities === undefined) {
  1270. return;
  1271. }
  1272. if (data.world === undefined) {
  1273. return;
  1274. }
  1275. importScene(data);
  1276. } catch (err) {
  1277. console.error(err);
  1278. scenes["Default"]();
  1279. // probably wasn't valid data
  1280. }
  1281. }
  1282. document.querySelector("#world").addEventListener("wheel", e => {
  1283. if (shiftHeld) {
  1284. if (selected) {
  1285. const dir = e.deltaY > 0 ? 10 / 11 : 11 / 10;
  1286. const entity = entities[selected.dataset.key];
  1287. entity.views[entity.view].height = math.multiply(entity.views[entity.view].height, dir);
  1288. entity.dirty = true;
  1289. updateEntityOptions(entity, entity.view);
  1290. updateViewOptions(entity, entity.view);
  1291. updateSizes(true);
  1292. } else {
  1293. document.querySelectorAll(".entity-box").forEach(element => {
  1294. element.dataset.x = parseFloat(element.dataset.x) + (e.deltaY < 0 ? 0.1 : -0.1);
  1295. });
  1296. updateSizes();
  1297. }
  1298. } else {
  1299. const dir = e.deltaY < 0 ? 10 / 11 : 11 / 10;
  1300. setWorldHeight(config.height, math.multiply(config.height, dir));
  1301. updateWorldOptions();
  1302. }
  1303. checkFitWorld();
  1304. })
  1305. document.querySelector("body").appendChild(testCtx.canvas);
  1306. updateSizes();
  1307. world.addEventListener("mousedown", e => deselect());
  1308. document.querySelector("#entities").addEventListener("mousedown", deselect);
  1309. document.querySelector("#display").addEventListener("mousedown", deselect);
  1310. document.addEventListener("mouseup", e => clickUp(e));
  1311. document.addEventListener("touchend", e => {
  1312. const fakeEvent = {
  1313. target: e.target,
  1314. clientX: e.changedTouches[0].clientX,
  1315. clientY: e.changedTouches[0].clientY
  1316. };
  1317. clickUp(fakeEvent);
  1318. });
  1319. document.querySelector("#entity-view").addEventListener("input", e => {
  1320. const entity = entities[selected.dataset.key];
  1321. entity.view = e.target.value;
  1322. const image = entities[selected.dataset.key].views[e.target.value].image;
  1323. selected.querySelector(".entity-image").src = image.source;
  1324. displayAttribution(image.source);
  1325. if (image.bottom !== undefined) {
  1326. selected.querySelector(".entity-image").style.setProperty("--offset", ((-1 + image.bottom) * 100) + "%")
  1327. } else {
  1328. selected.querySelector(".entity-image").style.setProperty("--offset", ((-1) * 100) + "%")
  1329. }
  1330. updateSizes();
  1331. updateEntityOptions(entities[selected.dataset.key], e.target.value);
  1332. updateViewOptions(entities[selected.dataset.key], e.target.value);
  1333. });
  1334. clearViewList();
  1335. document.querySelector("#menu-clear").addEventListener("click", e => {
  1336. removeAllEntities();
  1337. });
  1338. document.querySelector("#delete-entity").disabled = true;
  1339. document.querySelector("#delete-entity").addEventListener("click", e => {
  1340. if (selected) {
  1341. removeEntity(selected);
  1342. selected = null;
  1343. }
  1344. });
  1345. document.querySelector("#menu-order-height").addEventListener("click", e => {
  1346. const order = Object.keys(entities).sort((a, b) => {
  1347. const entA = entities[a];
  1348. const entB = entities[b];
  1349. const viewA = entA.view;
  1350. const viewB = entB.view;
  1351. const heightA = entA.views[viewA].height.to("meter").value;
  1352. const heightB = entB.views[viewB].height.to("meter").value;
  1353. return heightA - heightB;
  1354. });
  1355. arrangeEntities(order);
  1356. });
  1357. // TODO: write some generic logic for this lol
  1358. document.querySelector("#scroll-left").addEventListener("mousedown", e => {
  1359. scrollDirection = 1;
  1360. clearInterval(scrollHandle);
  1361. scrollHandle = setInterval(doScroll, 1000 / 20);
  1362. e.stopPropagation();
  1363. });
  1364. document.querySelector("#scroll-right").addEventListener("mousedown", e => {
  1365. scrollDirection = -1;
  1366. clearInterval(scrollHandle);
  1367. scrollHandle = setInterval(doScroll, 1000 / 20);
  1368. e.stopPropagation();
  1369. });
  1370. document.querySelector("#scroll-left").addEventListener("touchstart", e => {
  1371. scrollDirection = 1;
  1372. clearInterval(scrollHandle);
  1373. scrollHandle = setInterval(doScroll, 1000 / 20);
  1374. e.stopPropagation();
  1375. });
  1376. document.querySelector("#scroll-right").addEventListener("touchstart", e => {
  1377. scrollDirection = -1;
  1378. clearInterval(scrollHandle);
  1379. scrollHandle = setInterval(doScroll, 1000 / 20);
  1380. e.stopPropagation();
  1381. });
  1382. document.addEventListener("mouseup", e => {
  1383. clearInterval(scrollHandle);
  1384. scrollHandle = null;
  1385. });
  1386. document.addEventListener("touchend", e => {
  1387. clearInterval(scrollHandle);
  1388. scrollHandle = null;
  1389. });
  1390. document.querySelector("#zoom-in").addEventListener("mousedown", e => {
  1391. zoomDirection = -1;
  1392. clearInterval(zoomHandle);
  1393. zoomHandle = setInterval(doZoom, 1000 / 20);
  1394. e.stopPropagation();
  1395. });
  1396. document.querySelector("#zoom-out").addEventListener("mousedown", e => {
  1397. zoomDirection = 1;
  1398. clearInterval(zoomHandle);
  1399. zoomHandle = setInterval(doZoom, 1000 / 20);
  1400. e.stopPropagation();
  1401. });
  1402. document.querySelector("#zoom-in").addEventListener("touchstart", e => {
  1403. zoomDirection = -1;
  1404. clearInterval(zoomHandle);
  1405. zoomHandle = setInterval(doZoom, 1000 / 20);
  1406. e.stopPropagation();
  1407. });
  1408. document.querySelector("#zoom-out").addEventListener("touchstart", e => {
  1409. zoomDirection = 1;
  1410. clearInterval(zoomHandle);
  1411. zoomHandle = setInterval(doZoom, 1000 / 20);
  1412. e.stopPropagation();
  1413. });
  1414. document.addEventListener("mouseup", e => {
  1415. clearInterval(zoomHandle);
  1416. zoomHandle = null;
  1417. });
  1418. document.addEventListener("touchend", e => {
  1419. clearInterval(zoomHandle);
  1420. zoomHandle = null;
  1421. });
  1422. document.querySelector("#shrink").addEventListener("mousedown", e => {
  1423. sizeDirection = -1;
  1424. clearInterval(sizeHandle);
  1425. sizeHandle = setInterval(doSize, 1000 / 20);
  1426. e.stopPropagation();
  1427. });
  1428. document.querySelector("#grow").addEventListener("mousedown", e => {
  1429. sizeDirection = 1;
  1430. clearInterval(sizeHandle);
  1431. sizeHandle = setInterval(doSize, 1000 / 20);
  1432. e.stopPropagation();
  1433. });
  1434. document.querySelector("#shrink").addEventListener("touchstart", e => {
  1435. sizeDirection = -1;
  1436. clearInterval(sizeHandle);
  1437. sizeHandle = setInterval(doSize, 1000 / 20);
  1438. e.stopPropagation();
  1439. });
  1440. document.querySelector("#grow").addEventListener("touchstart", e => {
  1441. sizeDirection = 1;
  1442. clearInterval(sizeHandle);
  1443. sizeHandle = setInterval(doSize, 1000 / 20);
  1444. e.stopPropagation();
  1445. });
  1446. document.addEventListener("mouseup", e => {
  1447. clearInterval(sizeHandle);
  1448. sizeHandle = null;
  1449. });
  1450. document.addEventListener("touchend", e => {
  1451. clearInterval(sizeHandle);
  1452. sizeHandle = null;
  1453. });
  1454. document.querySelector("#fit").addEventListener("click", e => {
  1455. const x = parseFloat(selected.dataset.x);
  1456. Object.keys(entities).forEach(id => {
  1457. const element = document.querySelector("#entity-" + id);
  1458. const newX = parseFloat(element.dataset.x) - x + 0.5;
  1459. element.dataset.x = newX;
  1460. });
  1461. const entity = entities[selected.dataset.key];
  1462. const height = math.multiply(entity.views[entity.view].height, 1.1);
  1463. setWorldHeight(config.height, height);
  1464. });
  1465. document.querySelector("#fit").addEventListener("mousedown", e => {
  1466. e.stopPropagation();
  1467. });
  1468. document.querySelector("#fit").addEventListener("touchstart", e => {
  1469. e.stopPropagation();
  1470. });
  1471. document.querySelector("#options-world-fit").addEventListener("click", () => fitWorld(true));
  1472. document.querySelector("#options-world-autofit").addEventListener("input", e => {
  1473. config.autoFit = e.target.checked;
  1474. if (config.autoFit) {
  1475. fitWorld();
  1476. }
  1477. });
  1478. document.addEventListener("keydown", e => {
  1479. if (e.key == "Delete") {
  1480. if (selected) {
  1481. removeEntity(selected);
  1482. selected = null;
  1483. }
  1484. }
  1485. })
  1486. document.addEventListener("keydown", e => {
  1487. if (e.key == "Shift") {
  1488. shiftHeld = true;
  1489. e.preventDefault();
  1490. } else if (e.key == "Alt") {
  1491. altHeld = true;
  1492. e.preventDefault();
  1493. }
  1494. });
  1495. document.addEventListener("keyup", e => {
  1496. if (e.key == "Shift") {
  1497. shiftHeld = false;
  1498. e.preventDefault();
  1499. } else if (e.key == "Alt") {
  1500. altHeld = false;
  1501. e.preventDefault();
  1502. }
  1503. });
  1504. window.addEventListener("resize", handleResize);
  1505. // TODO: further investigate why the tool initially starts out with wrong
  1506. // values under certain circumstances (seems to be narrow aspect ratios -
  1507. // maybe the menu bar is animating when it shouldn't)
  1508. setTimeout(handleResize, 250);
  1509. setTimeout(handleResize, 500);
  1510. setTimeout(handleResize, 750);
  1511. setTimeout(handleResize, 1000);
  1512. document.querySelector("#menu-permalink").addEventListener("click", e => {
  1513. linkScene();
  1514. });
  1515. document.querySelector("#menu-export").addEventListener("click", e => {
  1516. copyScene();
  1517. });
  1518. document.querySelector("#menu-import").addEventListener("click", e => {
  1519. pasteScene();
  1520. });
  1521. document.querySelector("#menu-save").addEventListener("click", e => {
  1522. saveScene();
  1523. });
  1524. document.querySelector("#menu-load").addEventListener("click", e => {
  1525. loadScene();
  1526. });
  1527. document.querySelector("#menu-load-autosave").addEventListener("click", e => {
  1528. loadScene("autosave");
  1529. });
  1530. document.querySelector("#menu-add-image").addEventListener("click", e => {
  1531. document.querySelector("#file-upload-picker").click();
  1532. });
  1533. document.querySelector("#file-upload-picker").addEventListener("change", e => {
  1534. if (e.target.files.length > 0) {
  1535. for (let i=0; i<e.target.files.length; i++) {
  1536. customEntityFromFile(e.target.files[i]);
  1537. }
  1538. }
  1539. })
  1540. document.addEventListener("paste", e => {
  1541. let index = 0;
  1542. let item = null;
  1543. let found = false;
  1544. for (; index < e.clipboardData.items.length; index++) {
  1545. item = e.clipboardData.items[index];
  1546. if (item.type == "image/png") {
  1547. found = true;
  1548. break;
  1549. }
  1550. }
  1551. if (!found) {
  1552. return;
  1553. }
  1554. console.log(item)
  1555. console.log(item.type)
  1556. let url = null;
  1557. const file = item.getAsFile();
  1558. customEntityFromFile(file);
  1559. });
  1560. document.querySelector("#world").addEventListener("dragover", e => {
  1561. e.preventDefault();
  1562. })
  1563. document.querySelector("#world").addEventListener("drop", e => {
  1564. e.preventDefault();
  1565. if (e.dataTransfer.files.length > 0) {
  1566. let entX = document.querySelector("#entities").getBoundingClientRect().x;
  1567. let entY = document.querySelector("#entities").getBoundingClientRect().y;
  1568. let coords = abs2rel({x: e.clientX-entX, y: e.clientY-entY});
  1569. customEntityFromFile(e.dataTransfer.files[0], coords.x, coords.y);
  1570. }
  1571. })
  1572. clearEntityOptions();
  1573. clearViewOptions();
  1574. clearAttribution();
  1575. });
  1576. function customEntityFromFile(file, x=0.5, y=0.5) {
  1577. file.arrayBuffer().then(buf => {
  1578. arr = new Uint8Array(buf);
  1579. blob = new Blob([arr], {type: file.type });
  1580. url = window.URL.createObjectURL(blob)
  1581. makeCustomEntity(url, x, y);
  1582. });
  1583. }
  1584. function makeCustomEntity(url, x=0.5, y=0.5) {
  1585. const maker = createEntityMaker(
  1586. {
  1587. name: "Custom Entity"
  1588. },
  1589. {
  1590. custom: {
  1591. attributes: {
  1592. height: {
  1593. name: "Height",
  1594. power: 1,
  1595. type: "length",
  1596. base: math.unit(6, "feet")
  1597. }
  1598. },
  1599. image: {
  1600. source: url
  1601. },
  1602. name: "Image",
  1603. info: {},
  1604. rename: false
  1605. }
  1606. },
  1607. []
  1608. );
  1609. const entity = maker.constructor();
  1610. entity.scale = config.height.toNumber("feet") / 20;
  1611. entity.ephemeral = true;
  1612. displayEntity(entity, "custom", x, y, true, true);
  1613. }
  1614. function prepareEntities() {
  1615. availableEntities["buildings"] = makeBuildings();
  1616. availableEntities["characters"] = makeCharacters();
  1617. availableEntities["cities"] = makeCities();
  1618. availableEntities["fiction"] = makeFiction();
  1619. availableEntities["food"] = makeFood();
  1620. availableEntities["landmarks"] = makeLandmarks();
  1621. availableEntities["naturals"] = makeNaturals();
  1622. availableEntities["objects"] = makeObjects();
  1623. availableEntities["pokemon"] = makePokemon();
  1624. availableEntities["species"] = makeSpecies();
  1625. availableEntities["vehicles"] = makeVehicles();
  1626. availableEntities["characters"].sort((x, y) => {
  1627. return x.name.toLowerCase() < y.name.toLowerCase() ? -1 : 1
  1628. });
  1629. const holder = document.querySelector("#spawners");
  1630. const categorySelect = document.createElement("select");
  1631. categorySelect.id = "category-picker";
  1632. holder.appendChild(categorySelect);
  1633. Object.entries(availableEntities).forEach(([category, entityList]) => {
  1634. const select = document.createElement("select");
  1635. select.id = "create-entity-" + category;
  1636. for (let i = 0; i < entityList.length; i++) {
  1637. const entity = entityList[i];
  1638. const option = document.createElement("option");
  1639. option.value = i;
  1640. option.innerText = entity.name;
  1641. select.appendChild(option);
  1642. availableEntitiesByName[entity.name] = entity;
  1643. };
  1644. const button = document.createElement("button");
  1645. button.id = "create-entity-" + category + "-button";
  1646. button.innerHTML = "<i class=\"far fa-plus-square\"></i>";
  1647. button.addEventListener("click", e => {
  1648. const newEntity = entityList[select.value].constructor()
  1649. displayEntity(newEntity, newEntity.defaultView, 0.5, 1, true, true);
  1650. });
  1651. const categoryOption = document.createElement("option");
  1652. categoryOption.value = category
  1653. categoryOption.innerText = category;
  1654. if (category == "characters") {
  1655. categoryOption.selected = true;
  1656. select.classList.add("category-visible");
  1657. button.classList.add("category-visible");
  1658. }
  1659. categorySelect.appendChild(categoryOption);
  1660. holder.appendChild(select);
  1661. holder.appendChild(button);
  1662. });
  1663. console.log("Loaded " + Object.keys(availableEntitiesByName).length + " entities");
  1664. categorySelect.addEventListener("input", e => {
  1665. const oldSelect = document.querySelector("select.category-visible");
  1666. oldSelect.classList.remove("category-visible");
  1667. const oldButton = document.querySelector("button.category-visible");
  1668. oldButton.classList.remove("category-visible");
  1669. const newSelect = document.querySelector("#create-entity-" + e.target.value);
  1670. newSelect.classList.add("category-visible");
  1671. const newButton = document.querySelector("#create-entity-" + e.target.value + "-button");
  1672. newButton.classList.add("category-visible");
  1673. });
  1674. }
  1675. document.addEventListener("mousemove", (e) => {
  1676. if (clicked) {
  1677. const position = snapRel(abs2rel({ x: e.clientX - dragOffsetX, y: e.clientY - dragOffsetY }));
  1678. clicked.dataset.x = position.x;
  1679. clicked.dataset.y = position.y;
  1680. updateEntityElement(entities[clicked.dataset.key], clicked);
  1681. if (hoveringInDeleteArea(e)) {
  1682. document.querySelector("#menubar").classList.add("hover-delete");
  1683. } else {
  1684. document.querySelector("#menubar").classList.remove("hover-delete");
  1685. }
  1686. }
  1687. });
  1688. document.addEventListener("touchmove", (e) => {
  1689. if (clicked) {
  1690. e.preventDefault();
  1691. let x = e.touches[0].clientX;
  1692. let y = e.touches[0].clientY;
  1693. const position = snapRel(abs2rel({ x: x - dragOffsetX, y: y - dragOffsetY }));
  1694. clicked.dataset.x = position.x;
  1695. clicked.dataset.y = position.y;
  1696. updateEntityElement(entities[clicked.dataset.key], clicked);
  1697. // what a hack
  1698. // I should centralize this 'fake event' creation...
  1699. if (hoveringInDeleteArea({ clientY: y })) {
  1700. document.querySelector("#menubar").classList.add("hover-delete");
  1701. } else {
  1702. document.querySelector("#menubar").classList.remove("hover-delete");
  1703. }
  1704. }
  1705. }, { passive: false });
  1706. function checkFitWorld() {
  1707. if (config.autoFit) {
  1708. fitWorld();
  1709. return true;
  1710. }
  1711. return false;
  1712. }
  1713. const fitModes = {
  1714. "max": {
  1715. start: 0,
  1716. binop: Math.max,
  1717. final: (total, count) => total
  1718. },
  1719. "arithmetic mean": {
  1720. start: 0,
  1721. binop: math.add,
  1722. final: (total, count) => total / count
  1723. },
  1724. "geometric mean": {
  1725. start: 1,
  1726. binop: math.multiply,
  1727. final: (total, count) => math.pow(total, 1 / count)
  1728. }
  1729. }
  1730. function fitWorld(manual = false, factor = 1.1) {
  1731. const fitMode = fitModes[config.autoFitMode]
  1732. let max = fitMode.start
  1733. let count = 0;
  1734. Object.entries(entities).forEach(([key, entity]) => {
  1735. const view = entity.view;
  1736. let extra = entity.views[view].image.extra;
  1737. extra = extra === undefined ? 1 : extra;
  1738. max = fitMode.binop(max, math.multiply(extra, entity.views[view].height.toNumber("meter")));
  1739. count += 1;
  1740. });
  1741. max = fitMode.final(max, count)
  1742. max = math.unit(max, "meter")
  1743. if (manual)
  1744. altHeld = true;
  1745. setWorldHeight(config.height, math.multiply(max, factor));
  1746. if (manual)
  1747. altHeld = false;
  1748. }
  1749. function updateWorldHeight() {
  1750. const unit = document.querySelector("#options-height-unit").value;
  1751. const value = Math.max(0.000000001, document.querySelector("#options-height-value").value);
  1752. const oldHeight = config.height;
  1753. setWorldHeight(oldHeight, math.unit(value, unit));
  1754. }
  1755. function setWorldHeight(oldHeight, newHeight) {
  1756. worldSizeDirty = true;
  1757. config.height = newHeight.to(document.querySelector("#options-height-unit").value)
  1758. const unit = document.querySelector("#options-height-unit").value;
  1759. setNumericInput(document.querySelector("#options-height-value"), config.height.toNumber(unit));
  1760. Object.entries(entities).forEach(([key, entity]) => {
  1761. const element = document.querySelector("#entity-" + key);
  1762. let newPosition;
  1763. if (!altHeld) {
  1764. newPosition = adjustAbs({ x: element.dataset.x, y: element.dataset.y }, oldHeight, config.height);
  1765. } else {
  1766. newPosition = { x: element.dataset.x, y: element.dataset.y };
  1767. }
  1768. element.dataset.x = newPosition.x;
  1769. element.dataset.y = newPosition.y;
  1770. });
  1771. updateSizes();
  1772. }
  1773. function loadScene(name = "default") {
  1774. try {
  1775. const data = JSON.parse(localStorage.getItem("macrovision-save-" + name));
  1776. if (data === null) {
  1777. return false;
  1778. }
  1779. importScene(data);
  1780. return true;
  1781. } catch (err) {
  1782. alert("Something went wrong while loading (maybe you didn't have anything saved. Check the F12 console for the error.")
  1783. console.error(err);
  1784. return false;
  1785. }
  1786. }
  1787. function saveScene(name = "default") {
  1788. try {
  1789. const string = JSON.stringify(exportScene());
  1790. localStorage.setItem("macrovision-save-" + name, string);
  1791. } catch (err) {
  1792. alert("Something went wrong while saving (maybe I don't have localStorage permissions, or exporting failed). Check the F12 console for the error.")
  1793. console.error(err);
  1794. }
  1795. }
  1796. function deleteScene(name = "default") {
  1797. try {
  1798. localStorage.removeItem("macrovision-save-" + name)
  1799. } catch (err) {
  1800. console.error(err);
  1801. }
  1802. }
  1803. function exportScene() {
  1804. const results = {};
  1805. results.entities = [];
  1806. Object.entries(entities).filter(([key, entity]) => entity.ephemeral !== true).forEach(([key, entity]) => {
  1807. const element = document.querySelector("#entity-" + key);
  1808. results.entities.push({
  1809. name: entity.identifier,
  1810. scale: entity.scale,
  1811. view: entity.view,
  1812. x: element.dataset.x,
  1813. y: element.dataset.y
  1814. });
  1815. });
  1816. const unit = document.querySelector("#options-height-unit").value;
  1817. results.world = {
  1818. height: config.height.toNumber(unit),
  1819. unit: unit
  1820. }
  1821. results.canvasWidth = canvasWidth;
  1822. return results;
  1823. }
  1824. // btoa doesn't like anything that isn't ASCII
  1825. // great
  1826. // thanks to https://stackoverflow.com/questions/30106476/using-javascripts-atob-to-decode-base64-doesnt-properly-decode-utf-8-strings
  1827. // for providing an alternative
  1828. function b64EncodeUnicode(str) {
  1829. // first we use encodeURIComponent to get percent-encoded UTF-8,
  1830. // then we convert the percent encodings into raw bytes which
  1831. // can be fed into btoa.
  1832. return btoa(encodeURIComponent(str).replace(/%([0-9A-F]{2})/g,
  1833. function toSolidBytes(match, p1) {
  1834. return String.fromCharCode('0x' + p1);
  1835. }));
  1836. }
  1837. function b64DecodeUnicode(str) {
  1838. // Going backwards: from bytestream, to percent-encoding, to original string.
  1839. return decodeURIComponent(atob(str).split('').map(function (c) {
  1840. return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
  1841. }).join(''));
  1842. }
  1843. function linkScene() {
  1844. loc = new URL(window.location);
  1845. window.location = loc.protocol + "//" + loc.host + loc.pathname + "?scene=" + b64EncodeUnicode(JSON.stringify(exportScene()));
  1846. }
  1847. function copyScene() {
  1848. const results = exportScene();
  1849. navigator.clipboard.writeText(JSON.stringify(results));
  1850. }
  1851. function pasteScene() {
  1852. try {
  1853. navigator.clipboard.readText().then(text => {
  1854. const data = JSON.parse(text);
  1855. if (data.entities === undefined) {
  1856. return;
  1857. }
  1858. if (data.world === undefined) {
  1859. return;
  1860. }
  1861. importScene(data);
  1862. }).catch(err => alert(err));
  1863. } catch (err) {
  1864. console.error(err);
  1865. // probably wasn't valid data
  1866. }
  1867. }
  1868. // TODO - don't just search through every single entity
  1869. // probably just have a way to do lookups directly
  1870. function findEntity(name) {
  1871. return availableEntitiesByName[name];
  1872. }
  1873. function importScene(data) {
  1874. removeAllEntities();
  1875. data.entities.forEach(entityInfo => {
  1876. const entity = findEntity(entityInfo.name).constructor();
  1877. entity.scale = entityInfo.scale
  1878. displayEntity(entity, entityInfo.view, entityInfo.x, entityInfo.y);
  1879. });
  1880. config.height = math.unit(data.world.height, data.world.unit);
  1881. document.querySelector("#options-height-unit").value = data.world.unit;
  1882. if (data.canvasWidth) {
  1883. doHorizReposition(data.canvasWidth / canvasWidth);
  1884. }
  1885. updateSizes();
  1886. }
  1887. function renderToCanvas() {
  1888. const ctx = document.querySelector("#display").getContext("2d");
  1889. Object.entries(entities).sort((ent1, ent2) => {
  1890. z1 = document.querySelector("#entity-" + ent1[0]).style.zIndex;
  1891. z2 = document.querySelector("#entity-" + ent2[0]).style.zIndex;
  1892. return z1 - z2;
  1893. }).forEach(([id, entity]) => {
  1894. element = document.querySelector("#entity-" + id);
  1895. img = element.querySelector("img");
  1896. let x = parseFloat(element.dataset.x);
  1897. let y = parseFloat(element.dataset.y);
  1898. let coords = rel2abs({x: x, y: y});
  1899. let offset = img.style.getPropertyValue("--offset");
  1900. offset = parseFloat(offset.substring(0, offset.length-1))
  1901. x = coords.x - img.getBoundingClientRect().width/2;
  1902. y = coords.y - img.getBoundingClientRect().height * (-offset/100);
  1903. let xSize = img.getBoundingClientRect().width;
  1904. let ySize = img.getBoundingClientRect().height;
  1905. ctx.drawImage(img, x, y, xSize, ySize);
  1906. });
  1907. }
  1908. function exportCanvas(callback) {
  1909. /** @type {CanvasRenderingContext2D} */
  1910. const ctx = document.querySelector("#display").getContext("2d");
  1911. const blob = ctx.canvas.toBlob(callback);
  1912. }
  1913. function generateScreenshot(callback) {
  1914. renderToCanvas();
  1915. /** @type {CanvasRenderingContext2D} */
  1916. const ctx = document.querySelector("#display").getContext("2d");
  1917. ctx.fillStyle = "#555";
  1918. ctx.font = "normal normal lighter 16pt coda";
  1919. ctx.fillText("macrovision.crux.sexy", 10, 25);
  1920. exportCanvas(blob => {
  1921. callback(blob);
  1922. });
  1923. }
  1924. function copyScreenshot() {
  1925. generateScreenshot(blob => {
  1926. navigator.clipboard.write([
  1927. new ClipboardItem({
  1928. "image/png": blob
  1929. })
  1930. ]);
  1931. });
  1932. drawScale(false);
  1933. }
  1934. function saveScreenshot() {
  1935. generateScreenshot(blob => {
  1936. const a = document.createElement("a");
  1937. a.href = URL.createObjectURL(blob);
  1938. a.setAttribute("download", "macrovision.png");
  1939. a.click();
  1940. });
  1941. drawScale(false);
  1942. }
  1943. function toast(msg) {
  1944. let div = document.createElement("div");
  1945. div.innerHTML = msg;
  1946. div.classList.add("toast");
  1947. document.body.appendChild(div);
  1948. setTimeout(() => {
  1949. document.body.removeChild(div);
  1950. }, 5000)
  1951. }