less copy protection, more size visualization
Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.
 
 
 

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