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

4425 строки
135 KiB

  1. let selected = null;
  2. let prevSelected = null;
  3. let selectedEntity = null;
  4. let prevSelectedEntity = null;
  5. let entityIndex = 0;
  6. let clicked = null;
  7. let movingInBounds = false;
  8. let dragging = false;
  9. let clickTimeout = null;
  10. let dragOffsetX = null;
  11. let dragOffsetY = null;
  12. let preloaded = new Set();
  13. let panning = false;
  14. let panReady = true;
  15. let panOffsetX = null;
  16. let panOffsetY = null;
  17. let shiftHeld = false;
  18. let altHeld = false;
  19. let entityX;
  20. let canvasWidth;
  21. let canvasHeight;
  22. let dragScale = 1;
  23. let dragScaleHandle = null;
  24. let dragEntityScale = 1;
  25. let dragEntityScaleHandle = null;
  26. let scrollDirection = 0;
  27. let scrollHandle = null;
  28. let zoomDirection = 0;
  29. let zoomHandle = null;
  30. let sizeDirection = 0;
  31. let sizeHandle = null;
  32. let worldSizeDirty = false;
  33. let rulerMode = false;
  34. let rulers = [];
  35. let currentRuler = undefined;
  36. const tagDefs = {
  37. "anthro": "Anthro",
  38. "feral": "Feral",
  39. "taur": "Taur",
  40. "naga": "Naga",
  41. "goo": "Goo"
  42. }
  43. math.createUnit("humans", {
  44. definition: "5.75 feet"
  45. });
  46. math.createUnit("story", {
  47. definition: "12 feet",
  48. prefixes: "long"
  49. });
  50. math.createUnit("stories", {
  51. definition: "12 feet",
  52. prefixes: "long"
  53. });
  54. math.createUnit("buses", {
  55. definition: "11.95 meters",
  56. prefixes: "long"
  57. });
  58. math.createUnit("marathons", {
  59. definition: "26.2 miles",
  60. prefixes: "long"
  61. });
  62. math.createUnit("earths", {
  63. definition: "12756km",
  64. prefixes: "long"
  65. });
  66. math.createUnit("lightsecond", {
  67. definition: "299792458 meters",
  68. prefixes: "long"
  69. });
  70. math.createUnit("lightseconds", {
  71. definition: "299792458 meters",
  72. prefixes: "long"
  73. });
  74. math.createUnit("parsec", {
  75. definition: "3.086e16 meters",
  76. prefixes: "long"
  77. })
  78. math.createUnit("parsecs", {
  79. definition: "3.086e16 meters",
  80. prefixes: "long"
  81. })
  82. math.createUnit("lightyears", {
  83. definition: "9.461e15 meters",
  84. prefixes: "long"
  85. })
  86. math.createUnit("AU", {
  87. definition: "149597870700 meters"
  88. })
  89. math.createUnit("AUs", {
  90. definition: "149597870700 meters"
  91. })
  92. math.createUnit("dalton", {
  93. definition: "1.66e-27 kg",
  94. prefixes: "long"
  95. });
  96. math.createUnit("daltons", {
  97. definition: "1.66e-27 kg",
  98. prefixes: "long"
  99. });
  100. math.createUnit("solarradii", {
  101. definition: "695990 km",
  102. prefixes: "long"
  103. });
  104. math.createUnit("solarmasses", {
  105. definition: "2e30 kg",
  106. prefixes: "long"
  107. });
  108. math.createUnit("galaxy", {
  109. definition: "105700 lightyears",
  110. prefixes: "long"
  111. });
  112. math.createUnit("galaxies", {
  113. definition: "105700 lightyears",
  114. prefixes: "long"
  115. });
  116. math.createUnit("universe", {
  117. definition: "93.016e9 lightyears",
  118. prefixes: "long"
  119. });
  120. math.createUnit("universes", {
  121. definition: "93.016e9 lightyears",
  122. prefixes: "long"
  123. });
  124. math.createUnit("multiverse", {
  125. definition: "1e30 lightyears",
  126. prefixes: "long"
  127. });
  128. math.createUnit("multiverses", {
  129. definition: "1e30 lightyears",
  130. prefixes: "long"
  131. });
  132. math.createUnit("footballFields", {
  133. definition: "57600 feet^2",
  134. prefixes: "long"
  135. });
  136. math.createUnit("people", {
  137. definition: "75 liters",
  138. prefixes: "long"
  139. });
  140. math.createUnit("olympicPools", {
  141. definition: "2500 m^3",
  142. prefixes: "long"
  143. });
  144. math.createUnit("oceans", {
  145. definition: "700000000 km^3",
  146. prefixes: "long"
  147. });
  148. math.createUnit("earthVolumes", {
  149. definition: "1.0867813e12 km^3",
  150. prefixes: "long"
  151. });
  152. math.createUnit("universeVolumes", {
  153. definition: "4.2137775e+32 lightyears^3",
  154. prefixes: "long"
  155. });
  156. math.createUnit("multiverseVolumes", {
  157. definition: "5.2359878e+89 lightyears^3",
  158. prefixes: "long"
  159. });
  160. math.createUnit("peopleMass", {
  161. definition: "80 kg",
  162. prefixes: "long"
  163. });
  164. math.createUnit("cars", {
  165. definition: "1250kg",
  166. prefixes: "long"
  167. });
  168. math.createUnit("busMasses", {
  169. definition: "15000kg",
  170. prefixes: "long"
  171. });
  172. math.createUnit("earthMass", {
  173. definition: "5.97e24 kg",
  174. prefixes: "long"
  175. });
  176. math.createUnit("kcal", {
  177. definition: "4184 joules",
  178. prefixes: "long"
  179. })
  180. math.createUnit("foodPounds", {
  181. definition: "867 kcal",
  182. prefixes: "long"
  183. })
  184. math.createUnit("foodKilograms", {
  185. definition: "1909 kcal",
  186. prefixes: "long"
  187. })
  188. math.createUnit("peopleEaten", {
  189. definition: "125000 kcal",
  190. prefixes: "long"
  191. })
  192. math.createUnit("barn", {
  193. definition: "10e-28 m^2",
  194. prefixes: "long"
  195. })
  196. math.createUnit("barns", {
  197. definition: "10e-28 m^2",
  198. prefixes: "long"
  199. })
  200. math.createUnit("points", {
  201. definition: "0.013888888888888888888888888 inches",
  202. prefixes: "long"
  203. })
  204. math.createUnit("beardSeconds", {
  205. definition: "10 nanometers",
  206. prefixes: "long"
  207. })
  208. math.createUnit("smoots", {
  209. definition: "5.5833333 feet",
  210. prefixes: "long"
  211. })
  212. math.createUnit("furlongs", {
  213. definition: "660 feet",
  214. prefixes: "long"
  215. })
  216. math.createUnit("nanoacres", {
  217. definition: "1e-9 acres",
  218. prefixes: "long"
  219. })
  220. math.createUnit("barnMegaparsecs", {
  221. definition: "barn megaparsec",
  222. prefixes: "long"
  223. })
  224. math.createUnit("firkins", {
  225. definition: "90 lb",
  226. prefixes: "long"
  227. })
  228. math.createUnit("donkeySeconds", {
  229. definition: "250 joules",
  230. prefixes: "long"
  231. })
  232. const defaultUnits = {
  233. length: {
  234. metric: "meters",
  235. customary: "feet",
  236. relative: "stories",
  237. quirky: "smoots"
  238. },
  239. area: {
  240. metric: "meters^2",
  241. customary: "feet^2",
  242. relative: "footballFields",
  243. quirky: "nanoacres"
  244. },
  245. volume: {
  246. metric: "liters",
  247. customary: "gallons",
  248. relative: "olympicPools",
  249. volume: "barnmegaparsecs"
  250. },
  251. mass: {
  252. metric: "kilograms",
  253. customary: "lbs",
  254. relative: "peopleMass",
  255. quirky: "firkins"
  256. },
  257. energy: {
  258. metric: "kJ",
  259. customary: "kcal",
  260. relative: "peopleEaten",
  261. quirky: "donkeySeconds"
  262. }
  263. }
  264. const unitChoices = {
  265. length: {
  266. "metric": [
  267. "angstroms",
  268. "millimeters",
  269. "centimeters",
  270. "meters",
  271. "kilometers",
  272. ],
  273. "customary": [
  274. "inches",
  275. "feet",
  276. "miles",
  277. ],
  278. "relative": [
  279. "humans",
  280. "stories",
  281. "buses",
  282. "marathons",
  283. "earths",
  284. "lightseconds",
  285. "solarradii",
  286. "AUs",
  287. "lightyears",
  288. "parsecs",
  289. "galaxies",
  290. "universes",
  291. "multiverses"
  292. ],
  293. "quirky": [
  294. "beardSeconds",
  295. "points",
  296. "smoots",
  297. "furlongs"
  298. ]
  299. },
  300. area: {
  301. "metric": [
  302. "cm^2",
  303. "meters^2",
  304. "kilometers^2",
  305. ],
  306. "customary": [
  307. "feet^2",
  308. "acres",
  309. "miles^2"
  310. ],
  311. "relative": [
  312. "footballFields"
  313. ],
  314. "quirky": [
  315. "barns",
  316. "nanoacres"
  317. ]
  318. },
  319. volume: {
  320. "metric": [
  321. "milliliters",
  322. "liters",
  323. "m^3",
  324. ],
  325. "customary": [
  326. "floz",
  327. "cups",
  328. "pints",
  329. "quarts",
  330. "gallons",
  331. ],
  332. "relative": [
  333. "people",
  334. "olympicPools",
  335. "oceans",
  336. "earthVolumes",
  337. "universeVolumes",
  338. "multiverseVolumes",
  339. ],
  340. "quirky": [
  341. "barnMegaparsecs"
  342. ]
  343. },
  344. mass: {
  345. "metric": [
  346. "kilograms",
  347. "milligrams",
  348. "grams",
  349. "tonnes",
  350. ],
  351. "customary": [
  352. "lbs",
  353. "ounces",
  354. "tons"
  355. ],
  356. "relative": [
  357. "peopleMass",
  358. "cars",
  359. "busMasses",
  360. "earthMass",
  361. "solarmasses"
  362. ],
  363. "quirky": [
  364. "firkins"
  365. ]
  366. },
  367. energy: {
  368. "metric": [
  369. "kJ",
  370. "foodKilograms"
  371. ],
  372. "customary": [
  373. "kcal",
  374. "foodPounds"
  375. ],
  376. "relative": [
  377. "peopleEaten"
  378. ],
  379. "quirky": [
  380. "donkeySeconds"
  381. ]
  382. }
  383. }
  384. const config = {
  385. height: math.unit(1500, "meters"),
  386. x: 0,
  387. y: 0,
  388. minLineSize: 100,
  389. maxLineSize: 150,
  390. autoFit: false,
  391. drawYAxis: true,
  392. drawXAxis: false,
  393. autoFoodIntake: false,
  394. autoPreyCapacity: false
  395. }
  396. const availableEntities = {
  397. }
  398. const availableEntitiesByName = {
  399. }
  400. const entities = {
  401. }
  402. function constrainRel(coords) {
  403. const worldWidth = config.height.toNumber("meters") / canvasHeight * canvasWidth;
  404. const worldHeight = config.height.toNumber("meters");
  405. if (altHeld) {
  406. return coords;
  407. }
  408. return {
  409. x: Math.min(Math.max(coords.x, -worldWidth / 2 + config.x), worldWidth / 2 + config.x),
  410. y: Math.min(Math.max(coords.y, config.y), worldHeight + config.y)
  411. }
  412. }
  413. function snapPos(coords) {
  414. return constrainRel({
  415. x: coords.x,
  416. y: (!config.lockYAxis || altHeld) ? coords.y : (Math.abs(coords.y) < config.height.toNumber("meters")/20 ? 0 : coords.y)
  417. });
  418. }
  419. function adjustAbs(coords, oldHeight, newHeight) {
  420. const ratio = math.divide(newHeight, oldHeight);
  421. const x = (coords.x - config.x) * ratio + config.x;
  422. const y = (coords.y - config.y) * ratio + config.y;
  423. return { x: x, y: y};
  424. }
  425. function pos2pix(coords) {
  426. const worldWidth = config.height.toNumber("meters") / canvasHeight * canvasWidth;
  427. const worldHeight = config.height.toNumber("meters");
  428. const x = ((coords.x - config.x) / worldWidth + 0.5) * (canvasWidth - 50) + 50;
  429. const y = (1 - (coords.y - config.y) / worldHeight) * (canvasHeight - 50) + 50;
  430. return { x: x, y: y };
  431. }
  432. function pix2pos(coords) {
  433. const worldWidth = config.height.toNumber("meters") / canvasHeight * canvasWidth;
  434. const worldHeight = config.height.toNumber("meters");
  435. const x = (((coords.x - 50) / (canvasWidth - 50)) - 0.5) * worldWidth + config.x;
  436. const y = (1 - ((coords.y - 50) / (canvasHeight - 50))) * worldHeight + config.y;
  437. return { x: x, y: y };
  438. }
  439. function updateEntityElement(entity, element) {
  440. const position = pos2pix({ x: element.dataset.x, y: element.dataset.y });
  441. const view = entity.view;
  442. element.style.left = position.x + "px";
  443. element.style.top = position.y + "px";
  444. element.style.setProperty("--xpos", position.x + "px");
  445. element.style.setProperty("--entity-height", "'" + entity.views[view].height.to(config.height.units[0].unit.name).format({ precision: 2 }) + "'");
  446. const pixels = math.divide(entity.views[view].height, config.height) * (canvasHeight - 50);
  447. const extra = entity.views[view].image.extra;
  448. const bottom = entity.views[view].image.bottom;
  449. const bonus = (extra ? extra : 1) * (1 / (1 - (bottom ? bottom : 0)));
  450. let height = pixels * bonus;
  451. // working around a Firefox bug here
  452. if (height > 17895698) {
  453. height = 0;
  454. }
  455. element.style.setProperty("--height", height + "px");
  456. element.style.setProperty("--extra", height - pixels + "px");
  457. element.style.setProperty("--brightness", entity.brightness);
  458. if (entity.views[view].rename)
  459. element.querySelector(".entity-name").innerText = entity.name == "" ? "" : entity.views[view].name;
  460. else
  461. element.querySelector(".entity-name").innerText = entity.name;
  462. const bottomName = document.querySelector("#bottom-name-" + element.dataset.key);
  463. bottomName.style.left = position.x + entityX + "px";
  464. bottomName.style.bottom = "0vh";
  465. bottomName.innerText = entity.name;
  466. const topName = document.querySelector("#top-name-" + element.dataset.key);
  467. topName.style.left = position.x + entityX + "px";
  468. topName.style.top = "20vh";
  469. topName.innerText = entity.name;
  470. if (entity.views[view].height.toNumber("meters") / 10 > config.height.toNumber("meters")) {
  471. topName.classList.add("top-name-needed");
  472. } else {
  473. topName.classList.remove("top-name-needed");
  474. }
  475. }
  476. function updateRatios() {
  477. if (config.showRatios) {
  478. if (selectedEntity !== null && prevSelectedEntity !== null && selectedEntity !== prevSelectedEntity) {
  479. let first = selectedEntity.currentView.height;
  480. let second = prevSelectedEntity.currentView.height;
  481. let text = ""
  482. if (first.toNumber("meters") < second.toNumber("meters")) {
  483. text += selectedEntity.name + " is " + math.format(math.divide(second, first), { precision: 5 }) + " times smaller than " + prevSelectedEntity.name;
  484. } else {
  485. text += selectedEntity.name + " is " + math.format(math.divide(first, second), { precision: 5 })+ " times taller than " + prevSelectedEntity.name;
  486. }
  487. text += "\n";
  488. let apparentHeight = math.multiply(math.divide(second, first), math.unit(6, "feet"));
  489. if (config.units === "metric") {
  490. apparentHeight = apparentHeight.to("meters");
  491. }
  492. text += prevSelectedEntity.name + " looks " + math.format(apparentHeight, { precision: 3}) + " tall to " + selectedEntity.name;
  493. document.querySelector(".ratio-info").innerText = text;
  494. } else {
  495. document.querySelector(".ratio-info").innerText = "";
  496. }
  497. }
  498. }
  499. function updateSizes(dirtyOnly = false) {
  500. updateRatios();
  501. if (config.lockYAxis) {
  502. config.y = 0;
  503. }
  504. drawScales(dirtyOnly);
  505. let ordered = Object.entries(entities);
  506. ordered.sort((e1, e2) => {
  507. if (e1[1].priority != e2[1].priority) {
  508. return e2[1].priority - e1[1].priority;
  509. } else {
  510. return e1[1].views[e1[1].view].height.value - e2[1].views[e2[1].view].height.value
  511. }
  512. });
  513. let zIndex = ordered.length;
  514. ordered.forEach(entity => {
  515. const element = document.querySelector("#entity-" + entity[0]);
  516. element.style.zIndex = zIndex;
  517. if (!dirtyOnly || entity[1].dirty) {
  518. updateEntityElement(entity[1], element, zIndex);
  519. entity[1].dirty = false;
  520. }
  521. zIndex -= 1;
  522. });
  523. document.querySelector("#ground").style.top = pos2pix({x: 0, y: 0}).y + "px";
  524. drawRulers();
  525. }
  526. function drawRulers() {
  527. const canvas = document.querySelector("#rulers");
  528. /** @type {CanvasRenderingContext2D} */
  529. const ctx = canvas.getContext("2d");
  530. ctx.canvas.width = canvas.clientWidth;
  531. ctx.canvas.height = canvas.clientHeight;
  532. rulers.concat(currentRuler ? [currentRuler] : []).forEach(rulerDef => {
  533. ctx.save();
  534. ctx.beginPath();
  535. const start = pos2pix({x: rulerDef.x0, y: rulerDef.y0});
  536. const end = pos2pix({x: rulerDef.x1, y: rulerDef.y1});
  537. ctx.moveTo(start.x, start.y);
  538. ctx.lineTo(end.x, end.y);
  539. ctx.lineWidth = 5;
  540. ctx.strokeStyle = "#f2f";
  541. ctx.stroke();
  542. const center = { x: (start.x + end.x) / 2, y: (start.y + end.y) / 2 };
  543. ctx.fillStyle = "#eeeeee";
  544. ctx.font = 'normal 24pt coda';
  545. ctx.translate(center.x, center.y);
  546. let angle = Math.atan2(end.y - start.y, end.x - start.x);
  547. if (angle < -Math.PI/2) {
  548. angle += Math.PI;
  549. }
  550. if (angle > Math.PI/2) {
  551. angle -= Math.PI;
  552. }
  553. ctx.rotate(angle);
  554. const offsetX = Math.cos(angle + Math.PI/2);
  555. const offsetY = Math.sin(angle + Math.PI/2);
  556. const distance = Math.sqrt(Math.pow(rulerDef.y1 - rulerDef.y0, 2) + Math.pow(rulerDef.x1 - rulerDef.x0, 2));
  557. const distanceInUnits = math.unit(distance, "meters").to(document.querySelector("#options-height-unit").value);
  558. const textSize = ctx.measureText(distanceInUnits.format({ precision: 3}));
  559. ctx.fillText(distanceInUnits.format({ precision: 3}), -offsetX * 10 - textSize.width / 2, -offsetY*10);
  560. ctx.restore();
  561. });
  562. }
  563. function drawScales(ifDirty = false) {
  564. const canvas = document.querySelector("#display");
  565. /** @type {CanvasRenderingContext2D} */
  566. const ctx = canvas.getContext("2d");
  567. ctx.scale(1, 1);
  568. ctx.canvas.width = canvas.clientWidth;
  569. ctx.canvas.height = canvas.clientHeight;
  570. ctx.beginPath();
  571. ctx.rect(0, 0, canvas.width, canvas.height);
  572. ctx.fillStyle = "#333";
  573. ctx.fill();
  574. if (config.drawYAxis || config.drawAltitudes !== "none") {
  575. drawVerticalScale(ifDirty);
  576. }
  577. if (config.drawXAxis) {
  578. drawHorizontalScale(ifDirty);
  579. }
  580. }
  581. function drawVerticalScale(ifDirty = false) {
  582. if (ifDirty && !worldSizeDirty)
  583. return;
  584. function drawTicks(/** @type {CanvasRenderingContext2D} */ ctx, pixelsPer, heightPer) {
  585. let total = heightPer.clone();
  586. total.value = config.y;
  587. let y = ctx.canvas.clientHeight - 50;
  588. let offset = total.toNumber("meters") % heightPer.toNumber("meters");
  589. y += offset / heightPer.toNumber("meters") * pixelsPer;
  590. total = math.subtract(total, math.unit(offset, "meters"));
  591. for (; y >= 50; y -= pixelsPer) {
  592. drawTick(ctx, 50, y, total.format({ precision: 3 }));
  593. total = math.add(total, heightPer);
  594. }
  595. }
  596. function drawTick(/** @type {CanvasRenderingContext2D} */ ctx, x, y, label, flipped=false) {
  597. const oldStroke = ctx.strokeStyle;
  598. const oldFill = ctx.fillStyle;
  599. ctx.beginPath();
  600. ctx.moveTo(x, y);
  601. ctx.lineTo(x + 20, y);
  602. ctx.strokeStyle = "#000000";
  603. ctx.stroke();
  604. ctx.beginPath();
  605. ctx.moveTo(x + 20, y);
  606. ctx.lineTo(ctx.canvas.clientWidth - 70, y);
  607. if (flipped) {
  608. ctx.strokeStyle = "#666666";
  609. } else {
  610. ctx.strokeStyle = "#aaaaaa";
  611. }
  612. ctx.stroke();
  613. ctx.beginPath();
  614. ctx.moveTo(ctx.canvas.clientWidth - 70, y);
  615. ctx.lineTo(ctx.canvas.clientWidth - 50, y);
  616. ctx.strokeStyle = "#000000";
  617. ctx.stroke();
  618. const oldFont = ctx.font;
  619. ctx.font = 'normal 24pt coda';
  620. ctx.fillStyle = "#dddddd";
  621. ctx.beginPath();
  622. if (flipped) {
  623. ctx.textAlign = "end";
  624. ctx.fillText(label, ctx.canvas.clientWidth - 70, y + 35)
  625. } else {
  626. ctx.fillText(label, x + 20, y + 35);
  627. }
  628. ctx.textAlign = "start";
  629. ctx.font = oldFont;
  630. ctx.strokeStyle = oldStroke;
  631. ctx.fillStyle = oldFill;
  632. }
  633. function drawAltitudeLine(ctx, height, label) {
  634. const pixelScale = (ctx.canvas.clientHeight - 100) / config.height.toNumber("meters");
  635. const y = ctx.canvas.clientHeight - 50 - (height.toNumber("meters") - config.y) * pixelScale;
  636. if (y < ctx.canvas.clientHeight - 100) {
  637. drawTick(ctx, 50, y, label, true);
  638. }
  639. }
  640. const canvas = document.querySelector("#display");
  641. /** @type {CanvasRenderingContext2D} */
  642. const ctx = canvas.getContext("2d");
  643. const pixelScale = (ctx.canvas.clientHeight - 100) / config.height.toNumber();
  644. let pixelsPer = pixelScale;
  645. heightPer = 1;
  646. if (pixelsPer < config.minLineSize) {
  647. const factor = math.ceil(config.minLineSize / pixelsPer);
  648. heightPer *= factor;
  649. pixelsPer *= factor;
  650. }
  651. if (pixelsPer > config.maxLineSize) {
  652. const factor = math.ceil(pixelsPer / config.maxLineSize);
  653. heightPer /= factor;
  654. pixelsPer /= factor;
  655. }
  656. if (heightPer == 0) {
  657. console.error("The world size is invalid! Refusing to draw the scale...");
  658. return;
  659. }
  660. heightPer = math.unit(heightPer, document.querySelector("#options-height-unit").value);
  661. ctx.beginPath();
  662. ctx.moveTo(50, 50);
  663. ctx.lineTo(50, ctx.canvas.clientHeight - 50);
  664. ctx.stroke();
  665. ctx.beginPath();
  666. ctx.moveTo(ctx.canvas.clientWidth - 50, 50);
  667. ctx.lineTo(ctx.canvas.clientWidth - 50, ctx.canvas.clientHeight - 50);
  668. ctx.stroke();
  669. if (config.drawYAxis) {
  670. drawTicks(ctx, pixelsPer, heightPer);
  671. }
  672. if (config.drawAltitudes == "atmosphere" || config.drawAltitudes == "all") {
  673. drawAltitudeLine(ctx, math.unit(8, "km"), "Troposphere");
  674. drawAltitudeLine(ctx, math.unit(17.5, "km"), "Ozone Layer");
  675. drawAltitudeLine(ctx, math.unit(50, "km"), "Stratosphere");
  676. drawAltitudeLine(ctx, math.unit(85, "km"), "Mesosphere");
  677. drawAltitudeLine(ctx, math.unit(675, "km"), "Thermosphere");
  678. drawAltitudeLine(ctx, math.unit(10000, "km"), "Exosphere");
  679. }
  680. if (config.drawAltitudes == "orbits" || config.drawAltitudes == "all") {
  681. drawAltitudeLine(ctx, math.unit(7, "miles"), "Cruising Altitude");
  682. drawAltitudeLine(ctx, math.unit(100, "km"), "Edge of Space (Kármán line)");
  683. drawAltitudeLine(ctx, math.unit(211.3, "miles"), "Space Station");
  684. drawAltitudeLine(ctx, math.unit(369.7, "miles"), "Hubble Telescope");
  685. drawAltitudeLine(ctx, math.unit(1500, "km"), "Low Earth Orbit");
  686. drawAltitudeLine(ctx, math.unit(20350, "km"), "GPS Satellites");
  687. drawAltitudeLine(ctx, math.unit(35786, "km"), "Geosynchronous Orbit");
  688. drawAltitudeLine(ctx, math.unit(238900, "miles"), "Lunar Orbit");
  689. drawAltitudeLine(ctx, math.unit(57.9e6, "km"), "Orbit of Mercury");
  690. drawAltitudeLine(ctx, math.unit(108.2e6, "km"), "Orbit of Venus");
  691. drawAltitudeLine(ctx, math.unit(1, "AU"), "Orbit of Earth");
  692. drawAltitudeLine(ctx, math.unit(227.9e6, "km"), "Orbit of Mars");
  693. drawAltitudeLine(ctx, math.unit(778.6e6, "km"), "Orbit of Jupiter");
  694. drawAltitudeLine(ctx, math.unit(1433.5e6, "km"), "Orbit of Saturn");
  695. drawAltitudeLine(ctx, math.unit(2872.5e6, "km"), "Orbit of Uranus");
  696. drawAltitudeLine(ctx, math.unit(4495.1e6, "km"), "Orbit of Neptune");
  697. drawAltitudeLine(ctx, math.unit(5906.4e6, "km"), "Orbit of Pluto");
  698. drawAltitudeLine(ctx, math.unit(2.7, "AU"), "Asteroid Belt");
  699. drawAltitudeLine(ctx, math.unit(123, "AU"), "Heliopause");
  700. drawAltitudeLine(ctx, math.unit(26e3, "lightyears"), "Orbit of Sol");
  701. }
  702. if (config.drawAltitudes == "weather" || config.drawAltitudes == "all") {
  703. drawAltitudeLine(ctx, math.unit(1000, "meters"), "Low-level Clouds");
  704. drawAltitudeLine(ctx, math.unit(3000, "meters"), "Mid-level Clouds");
  705. drawAltitudeLine(ctx, math.unit(10000, "meters"), "High-level Clouds");
  706. drawAltitudeLine(ctx, math.unit(20, "km"), "Polar Stratospheric Clouds");
  707. drawAltitudeLine(ctx, math.unit(80, "km"), "Noctilucent Clouds");
  708. drawAltitudeLine(ctx, math.unit(100, "km"), "Aurora");
  709. }
  710. if (config.drawAltitudes == "water" || config.drawAltitudes == "all") {
  711. drawAltitudeLine(ctx, math.unit(12100, "feet"), "Average Ocean Depth");
  712. drawAltitudeLine(ctx, math.unit(8376, "meters"), "Milkwaukee Deep");
  713. drawAltitudeLine(ctx, math.unit(10984, "meters"), "Challenger Deep");
  714. drawAltitudeLine(ctx, math.unit(5550, "meters"), "Molloy Deep");
  715. drawAltitudeLine(ctx, math.unit(7290, "meters"), "Sunda Deep");
  716. drawAltitudeLine(ctx, math.unit(592, "meters"), "Crater Lake");
  717. drawAltitudeLine(ctx, math.unit(7.5, "meters"), "Littoral Zone");
  718. drawAltitudeLine(ctx, math.unit(140, "meters"), "Continental Shelf");
  719. }
  720. if (config.drawAltitudes == "geology" || config.drawAltitudes == "all") {
  721. drawAltitudeLine(ctx, math.unit(35, "km"), "Crust");
  722. drawAltitudeLine(ctx, math.unit(670, "km"), "Upper Mantle");
  723. drawAltitudeLine(ctx, math.unit(2890, "km"), "Lower Mantle");
  724. drawAltitudeLine(ctx, math.unit(5150, "km"), "Outer Core");
  725. drawAltitudeLine(ctx, math.unit(6370, "km"), "Inner Core");
  726. }
  727. if (config.drawAltitudes == "thicknesses" || config.drawAltitudes == "all") {
  728. drawAltitudeLine(ctx, math.unit(0.335, "nm"), "Monolayer Graphene");
  729. drawAltitudeLine(ctx, math.unit(3, "um"), "Spider Silk");
  730. drawAltitudeLine(ctx, math.unit(0.07, "mm"), "Human Hair");
  731. drawAltitudeLine(ctx, math.unit(0.1, "mm"), "Sheet of Paper");
  732. drawAltitudeLine(ctx, math.unit(0.5, "mm"), "Yarn");
  733. drawAltitudeLine(ctx, math.unit(0.0155, "inches"), "Thread");
  734. drawAltitudeLine(ctx, math.unit(0.1, "um"), "Gold Leaf");
  735. drawAltitudeLine(ctx, math.unit(35, "um"), "PCB Trace");
  736. }
  737. }
  738. // this is a lot of copypizza...
  739. function drawHorizontalScale(ifDirty = false) {
  740. if (ifDirty && !worldSizeDirty)
  741. return;
  742. function drawTicks(/** @type {CanvasRenderingContext2D} */ ctx, pixelsPer, heightPer) {
  743. let total = heightPer.clone();
  744. total.value = math.unit(-config.x, "meters").toNumber(config.unit);
  745. // further adjust it to put the current position in the center
  746. total.value -= heightPer.toNumber("meters") / pixelsPer * (canvasWidth + 50) / 2;
  747. let x = ctx.canvas.clientWidth - 50;
  748. let offset = total.toNumber("meters") % heightPer.toNumber("meters");
  749. x += offset / heightPer.toNumber("meters") * pixelsPer;
  750. total = math.subtract(total, math.unit(offset, "meters"));
  751. for (; x >= 50 - pixelsPer; x -= pixelsPer) {
  752. // negate it so that the left side is negative
  753. drawTick(ctx, x, 50, math.multiply(-1, total).format({ precision: 3 }));
  754. total = math.add(total, heightPer);
  755. }
  756. }
  757. function drawTick(/** @type {CanvasRenderingContext2D} */ ctx, x, y, label) {
  758. const oldStroke = ctx.strokeStyle;
  759. const oldFill = ctx.fillStyle;
  760. ctx.beginPath();
  761. ctx.moveTo(x, y);
  762. ctx.lineTo(x, y + 20);
  763. ctx.strokeStyle = "#000000";
  764. ctx.stroke();
  765. ctx.beginPath();
  766. ctx.moveTo(x, y + 20);
  767. ctx.lineTo(x, ctx.canvas.clientHeight - 70);
  768. ctx.strokeStyle = "#aaaaaa";
  769. ctx.stroke();
  770. ctx.beginPath();
  771. ctx.moveTo(x, ctx.canvas.clientHeight - 70);
  772. ctx.lineTo(x, ctx.canvas.clientHeight - 50);
  773. ctx.strokeStyle = "#000000";
  774. ctx.stroke();
  775. const oldFont = ctx.font;
  776. ctx.font = 'normal 24pt coda';
  777. ctx.fillStyle = "#dddddd";
  778. ctx.beginPath();
  779. ctx.fillText(label, x + 35, y + 20);
  780. ctx.font = oldFont;
  781. ctx.strokeStyle = oldStroke;
  782. ctx.fillStyle = oldFill;
  783. }
  784. const canvas = document.querySelector("#display");
  785. /** @type {CanvasRenderingContext2D} */
  786. const ctx = canvas.getContext("2d");
  787. let pixelsPer = (ctx.canvas.clientHeight - 100) / config.height.toNumber();
  788. heightPer = 1;
  789. if (pixelsPer < config.minLineSize * 2) {
  790. const factor = math.ceil(config.minLineSize * 2/ pixelsPer);
  791. heightPer *= factor;
  792. pixelsPer *= factor;
  793. }
  794. if (pixelsPer > config.maxLineSize * 2) {
  795. const factor = math.ceil(pixelsPer / 2/ config.maxLineSize);
  796. heightPer /= factor;
  797. pixelsPer /= factor;
  798. }
  799. if (heightPer == 0) {
  800. console.error("The world size is invalid! Refusing to draw the scale...");
  801. return;
  802. }
  803. heightPer = math.unit(heightPer, document.querySelector("#options-height-unit").value);
  804. ctx.beginPath();
  805. ctx.moveTo(0, 50);
  806. ctx.lineTo(ctx.canvas.clientWidth, 50);
  807. ctx.stroke();
  808. ctx.beginPath();
  809. ctx.moveTo(0, ctx.canvas.clientHeight - 50);
  810. ctx.lineTo(ctx.canvas.clientWidth , ctx.canvas.clientHeight - 50);
  811. ctx.stroke();
  812. drawTicks(ctx, pixelsPer, heightPer);
  813. }
  814. // Entities are generated as needed, and we make a copy
  815. // every time - the resulting objects get mutated, after all.
  816. // But we also want to be able to read some information without
  817. // calling the constructor -- e.g. making a list of authors and
  818. // owners. So, this function is used to generate that information.
  819. // It is invoked like makeEntity so that it can be dropped in easily,
  820. // but returns an object that lets you construct many copies of an entity,
  821. // rather than creating a new entity.
  822. function createEntityMaker(info, views, sizes) {
  823. const maker = {};
  824. maker.name = info.name;
  825. maker.info = info;
  826. maker.sizes = sizes;
  827. maker.constructor = () => makeEntity(info, views, sizes);
  828. maker.authors = [];
  829. maker.owners = [];
  830. maker.nsfw = false;
  831. Object.values(views).forEach(view => {
  832. const authors = authorsOf(view.image.source);
  833. if (authors) {
  834. authors.forEach(author => {
  835. if (maker.authors.indexOf(author) == -1) {
  836. maker.authors.push(author);
  837. }
  838. });
  839. }
  840. const owners = ownersOf(view.image.source);
  841. if (owners) {
  842. owners.forEach(owner => {
  843. if (maker.owners.indexOf(owner) == -1) {
  844. maker.owners.push(owner);
  845. }
  846. });
  847. }
  848. if (isNsfw(view.image.source)) {
  849. maker.nsfw = true;
  850. }
  851. });
  852. return maker;
  853. }
  854. // This function serializes and parses its arguments to avoid sharing
  855. // references to a common object. This allows for the objects to be
  856. // safely mutated.
  857. function makeEntity(info, views, sizes) {
  858. const entityTemplate = {
  859. name: info.name,
  860. identifier: info.name,
  861. scale: 1,
  862. info: JSON.parse(JSON.stringify(info)),
  863. views: JSON.parse(JSON.stringify(views), math.reviver),
  864. sizes: sizes === undefined ? [] : JSON.parse(JSON.stringify(sizes), math.reviver),
  865. init: function () {
  866. const entity = this;
  867. Object.entries(this.views).forEach(([viewKey, view]) => {
  868. view.parent = this;
  869. if (this.defaultView === undefined) {
  870. this.defaultView = viewKey;
  871. this.view = viewKey;
  872. }
  873. if (view.default) {
  874. this.defaultView = viewKey;
  875. this.view = viewKey;
  876. }
  877. // to remember the units the user last picked
  878. view.units = {};
  879. if (config.autoFoodIntake && view.attributes.weight !== undefined && view.attributes.energyNeed === undefined) {
  880. view.attributes.energyNeed = {
  881. name: "Food Intake",
  882. power: 3,
  883. type: "energy",
  884. base: math.unit(2000 * view.attributes.weight.base.toNumber("lbs") / 150, "kcal")
  885. }
  886. }
  887. if (config.autoPreyCapacity !== "none" && view.attributes.weight !== undefined && view.attributes.capacity === undefined) {
  888. view.attributes.capacity = {
  889. name: "Capacity",
  890. power: 3,
  891. type: "volume",
  892. base: math.unit((config.autoPreyCapacity == "same-size" ? 1 : 0.05) * view.attributes.weight.base.toNumber("lbs") / 150, "people")
  893. }
  894. }
  895. Object.entries(view.attributes).forEach(([key, val]) => {
  896. Object.defineProperty(
  897. view,
  898. key,
  899. {
  900. get: function () {
  901. return math.multiply(Math.pow(this.parent.scale, this.attributes[key].power), this.attributes[key].base);
  902. },
  903. set: function (value) {
  904. const newScale = Math.pow(math.divide(value, this.attributes[key].base), 1 / this.attributes[key].power);
  905. this.parent.scale = newScale;
  906. }
  907. }
  908. );
  909. });
  910. });
  911. this.sizes.forEach(size => {
  912. if (size.default === true) {
  913. this.views[this.defaultView].height = size.height;
  914. this.size = size;
  915. }
  916. });
  917. if (this.size === undefined && this.sizes.length > 0) {
  918. this.views[this.defaultView].height = this.sizes[0].height;
  919. this.size = this.sizes[0];
  920. console.warn("No default size set for " + info.name);
  921. } else if (this.sizes.length == 0) {
  922. this.sizes = [
  923. {
  924. name: "Normal",
  925. height: this.views[this.defaultView].height
  926. }
  927. ];
  928. this.size = this.sizes[0];
  929. }
  930. this.desc = {};
  931. Object.entries(this.info).forEach(([key, value]) => {
  932. Object.defineProperty(
  933. this.desc,
  934. key,
  935. {
  936. get: function () {
  937. let text = value.text;
  938. if (entity.views[entity.view].info) {
  939. if (entity.views[entity.view].info[key]) {
  940. text = combineInfo(text, entity.views[entity.view].info[key]);
  941. }
  942. }
  943. if (entity.size.info) {
  944. if (entity.size.info[key]) {
  945. text = combineInfo(text, entity.size.info[key]);
  946. }
  947. }
  948. return { title: value.title, text: text };
  949. }
  950. }
  951. )
  952. });
  953. Object.defineProperty(
  954. this,
  955. "currentView",
  956. {
  957. get: function() {
  958. return entity.views[entity.view];
  959. }
  960. }
  961. )
  962. delete this.init;
  963. return this;
  964. }
  965. }.init();
  966. return entityTemplate;
  967. }
  968. function combineInfo(existing, next) {
  969. switch (next.mode) {
  970. case "replace":
  971. return next.text;
  972. case "prepend":
  973. return next.text + existing;
  974. case "append":
  975. return existing + next.text;
  976. }
  977. return existing;
  978. }
  979. function clickDown(target, x, y) {
  980. clicked = target;
  981. movingInBounds = false;
  982. const rect = target.getBoundingClientRect();
  983. let entX = document.querySelector("#entities").getBoundingClientRect().x;
  984. let entY = document.querySelector("#entities").getBoundingClientRect().y;
  985. dragOffsetX = x - rect.left + entX;
  986. dragOffsetY = y - rect.top + entY;
  987. x = x - dragOffsetX;
  988. y = y - dragOffsetY;
  989. if (x >= 0 && x <= canvasWidth && y >= 0 && y <= canvasHeight) {
  990. movingInBounds = true;
  991. }
  992. clickTimeout = setTimeout(() => { dragging = true }, 200)
  993. target.classList.add("no-transition");
  994. }
  995. // could we make this actually detect the menu area?
  996. function hoveringInDeleteArea(e) {
  997. return e.clientY < document.body.clientHeight / 10;
  998. }
  999. function clickUp(e) {
  1000. if (e.which != 1) {
  1001. return;
  1002. }
  1003. clearTimeout(clickTimeout);
  1004. if (clicked) {
  1005. clicked.classList.remove("no-transition");
  1006. if (dragging) {
  1007. dragging = false;
  1008. if (hoveringInDeleteArea(e)) {
  1009. removeEntity(clicked);
  1010. document.querySelector("#menubar").classList.remove("hover-delete");
  1011. }
  1012. } else {
  1013. select(clicked);
  1014. }
  1015. clicked = null;
  1016. }
  1017. }
  1018. function deselect(e) {
  1019. if (e !== undefined && e.which != 1) {
  1020. return;
  1021. }
  1022. if (selected) {
  1023. selected.classList.remove("selected");
  1024. }
  1025. if (prevSelected) {
  1026. prevSelected.classList.remove("prevSelected");
  1027. }
  1028. document.getElementById("options-selected-entity-none").selected = "selected";
  1029. clearAttribution();
  1030. selected = null;
  1031. clearViewList();
  1032. clearEntityOptions();
  1033. clearViewOptions();
  1034. document.querySelector("#delete-entity").disabled = true;
  1035. document.querySelector("#grow").disabled = true;
  1036. document.querySelector("#shrink").disabled = true;
  1037. document.querySelector("#fit").disabled = true;
  1038. }
  1039. function select(target) {
  1040. if (prevSelected !== null) {
  1041. prevSelected.classList.remove("prevSelected");
  1042. }
  1043. prevSelected = selected;
  1044. prevSelectedEntity = selectedEntity;
  1045. deselect();
  1046. selected = target;
  1047. selectedEntity = entities[target.dataset.key];
  1048. updateRatios();
  1049. document.getElementById("options-selected-entity-" + target.dataset.key).selected = "selected";
  1050. if (prevSelected !== null && config.showRatios && selected !== prevSelected) {
  1051. prevSelected.classList.add("prevSelected");
  1052. }
  1053. selected.classList.add("selected");
  1054. displayAttribution(selectedEntity.views[selectedEntity.view].image.source);
  1055. configViewList(selectedEntity, selectedEntity.view);
  1056. configEntityOptions(selectedEntity, selectedEntity.view);
  1057. configViewOptions(selectedEntity, selectedEntity.view);
  1058. document.querySelector("#delete-entity").disabled = false;
  1059. document.querySelector("#grow").disabled = false;
  1060. document.querySelector("#shrink").disabled = false;
  1061. document.querySelector("#fit").disabled = false;
  1062. }
  1063. function configViewList(entity, selectedView) {
  1064. const list = document.querySelector("#entity-view");
  1065. list.innerHTML = "";
  1066. list.style.display = "block";
  1067. Object.keys(entity.views).forEach(view => {
  1068. const option = document.createElement("option");
  1069. option.innerText = entity.views[view].name;
  1070. option.value = view;
  1071. if (isNsfw(entity.views[view].image.source)) {
  1072. option.classList.add("nsfw")
  1073. }
  1074. if (view === selectedView) {
  1075. option.selected = true;
  1076. if (option.classList.contains("nsfw")) {
  1077. list.classList.add("nsfw");
  1078. } else {
  1079. list.classList.remove("nsfw");
  1080. }
  1081. }
  1082. list.appendChild(option);
  1083. });
  1084. }
  1085. function clearViewList() {
  1086. const list = document.querySelector("#entity-view");
  1087. list.innerHTML = "";
  1088. list.style.display = "none";
  1089. }
  1090. function updateWorldOptions(entity, view) {
  1091. const heightInput = document.querySelector("#options-height-value");
  1092. const heightSelect = document.querySelector("#options-height-unit");
  1093. const converted = config.height.toNumber(heightSelect.value);
  1094. setNumericInput(heightInput, converted);
  1095. }
  1096. function configEntityOptions(entity, view) {
  1097. const holder = document.querySelector("#options-entity");
  1098. document.querySelector("#entity-category-header").style.display = "block";
  1099. document.querySelector("#entity-category").style.display = "block";
  1100. holder.innerHTML = "";
  1101. const scaleLabel = document.createElement("div");
  1102. scaleLabel.classList.add("options-label");
  1103. scaleLabel.innerText = "Scale";
  1104. const scaleRow = document.createElement("div");
  1105. scaleRow.classList.add("options-row");
  1106. const scaleInput = document.createElement("input");
  1107. scaleInput.classList.add("options-field-numeric");
  1108. scaleInput.id = "options-entity-scale";
  1109. scaleInput.addEventListener("change", e => {
  1110. entity.scale = e.target.value == 0 ? 1 : e.target.value;
  1111. entity.dirty = true;
  1112. if (config.autoFit) {
  1113. fitWorld();
  1114. } else {
  1115. updateSizes(true);
  1116. }
  1117. updateEntityOptions(entity, entity.view);
  1118. updateViewOptions(entity, entity.view);
  1119. });
  1120. scaleInput.addEventListener("keydown", e => {
  1121. e.stopPropagation();
  1122. })
  1123. scaleInput.setAttribute("min", 1);
  1124. scaleInput.setAttribute("type", "number");
  1125. setNumericInput(scaleInput, entity.scale);
  1126. scaleRow.appendChild(scaleInput);
  1127. holder.appendChild(scaleLabel);
  1128. holder.appendChild(scaleRow);
  1129. const nameLabel = document.createElement("div");
  1130. nameLabel.classList.add("options-label");
  1131. nameLabel.innerText = "Name";
  1132. const nameRow = document.createElement("div");
  1133. nameRow.classList.add("options-row");
  1134. const nameInput = document.createElement("input");
  1135. nameInput.classList.add("options-field-text");
  1136. nameInput.value = entity.name;
  1137. nameInput.addEventListener("input", e => {
  1138. entity.name = e.target.value;
  1139. entity.dirty = true;
  1140. updateSizes(true);
  1141. })
  1142. nameInput.addEventListener("keydown", e => {
  1143. e.stopPropagation();
  1144. })
  1145. nameRow.appendChild(nameInput);
  1146. holder.appendChild(nameLabel);
  1147. holder.appendChild(nameRow);
  1148. const defaultHolder = document.querySelector("#options-entity-defaults");
  1149. defaultHolder.innerHTML = "";
  1150. entity.sizes.forEach(defaultInfo => {
  1151. const button = document.createElement("button");
  1152. button.classList.add("options-button");
  1153. button.innerText = defaultInfo.name;
  1154. button.addEventListener("click", e => {
  1155. entity.views[entity.defaultView].height = defaultInfo.height;
  1156. entity.dirty = true;
  1157. updateEntityOptions(entity, entity.view);
  1158. updateViewOptions(entity, entity.view);
  1159. if (!checkFitWorld()) {
  1160. updateSizes(true);
  1161. }
  1162. if (config.autoFitSize) {
  1163. let targets = {};
  1164. targets[selected.dataset.key] = entities[selected.dataset.key];
  1165. fitEntities(targets);
  1166. }
  1167. });
  1168. defaultHolder.appendChild(button);
  1169. });
  1170. document.querySelector("#options-order-display").innerText = entity.priority;
  1171. document.querySelector("#options-brightness-display").innerText = entity.brightness;
  1172. document.querySelector("#options-ordering").style.display = "flex";
  1173. }
  1174. function updateEntityOptions(entity, view) {
  1175. const scaleInput = document.querySelector("#options-entity-scale");
  1176. setNumericInput(scaleInput, entity.scale);
  1177. document.querySelector("#options-order-display").innerText = entity.priority;
  1178. document.querySelector("#options-brightness-display").innerText = entity.brightness;
  1179. }
  1180. function clearEntityOptions() {
  1181. document.querySelector("#entity-category-header").style.display = "none";
  1182. document.querySelector("#entity-category").style.display = "none";
  1183. /*
  1184. const holder = document.querySelector("#options-entity");
  1185. holder.innerHTML = "";
  1186. document.querySelector("#options-entity-defaults").innerHTML = "";
  1187. document.querySelector("#options-ordering").style.display = "none";
  1188. document.querySelector("#options-ordering").style.display = "none";*/
  1189. }
  1190. function configViewOptions(entity, view) {
  1191. const holder = document.querySelector("#options-view");
  1192. document.querySelector("#view-category-header").style.display = "block";
  1193. document.querySelector("#view-category").style.display = "block";
  1194. holder.innerHTML = "";
  1195. Object.entries(entity.views[view].attributes).forEach(([key, val]) => {
  1196. const label = document.createElement("div");
  1197. label.classList.add("options-label");
  1198. label.innerText = val.name;
  1199. holder.appendChild(label);
  1200. const row = document.createElement("div");
  1201. row.classList.add("options-row");
  1202. holder.appendChild(row);
  1203. const input = document.createElement("input");
  1204. input.classList.add("options-field-numeric");
  1205. input.id = "options-view-" + key + "-input";
  1206. input.setAttribute("type", "number");
  1207. input.setAttribute("min", 1);
  1208. const select = document.createElement("select");
  1209. select.classList.add("options-field-unit");
  1210. select.id = "options-view-" + key + "-select"
  1211. Object.entries(unitChoices[val.type]).forEach(([group, entries]) => {
  1212. const optGroup = document.createElement("optgroup");
  1213. optGroup.label = group;
  1214. select.appendChild(optGroup);
  1215. entries.forEach(entry => {
  1216. const option = document.createElement("option");
  1217. option.innerText = entry;
  1218. if (entry == defaultUnits[val.type][config.units]) {
  1219. option.selected = true;
  1220. }
  1221. select.appendChild(option);
  1222. })
  1223. });
  1224. input.addEventListener("change", e => {
  1225. const value = input.value == 0 ? 1 : input.value;
  1226. entity.views[view][key] = math.unit(value, select.value);
  1227. entity.dirty = true;
  1228. if (config.autoFit) {
  1229. fitWorld();
  1230. } else {
  1231. updateSizes(true);
  1232. }
  1233. updateEntityOptions(entity, view);
  1234. updateViewOptions(entity, view, key);
  1235. });
  1236. input.addEventListener("keydown", e => {
  1237. e.stopPropagation();
  1238. })
  1239. if (entity.currentView.units[key]) {
  1240. select.value = entity.currentView.units[key];
  1241. } else {
  1242. entity.currentView.units[key] = select.value;
  1243. }
  1244. select.dataset.oldUnit = select.value;
  1245. setNumericInput(input, entity.views[view][key].toNumber(select.value));
  1246. // TODO does this ever cause a change in the world?
  1247. select.addEventListener("input", e => {
  1248. const value = input.value == 0 ? 1 : input.value;
  1249. const oldUnit = select.dataset.oldUnit;
  1250. entity.views[entity.view][key] = math.unit(value, oldUnit).to(select.value);
  1251. entity.dirty = true;
  1252. setNumericInput(input, entity.views[entity.view][key].toNumber(select.value));
  1253. select.dataset.oldUnit = select.value;
  1254. entity.views[view].units[key] = select.value;
  1255. if (config.autoFit) {
  1256. fitWorld();
  1257. } else {
  1258. updateSizes(true);
  1259. }
  1260. updateEntityOptions(entity, view);
  1261. updateViewOptions(entity, view, key);
  1262. });
  1263. row.appendChild(input);
  1264. row.appendChild(select);
  1265. });
  1266. }
  1267. function updateViewOptions(entity, view, changed) {
  1268. Object.entries(entity.views[view].attributes).forEach(([key, val]) => {
  1269. if (key != changed) {
  1270. const input = document.querySelector("#options-view-" + key + "-input");
  1271. const select = document.querySelector("#options-view-" + key + "-select");
  1272. const currentUnit = select.value;
  1273. const convertedAmount = entity.views[view][key].toNumber(currentUnit);
  1274. setNumericInput(input, convertedAmount);
  1275. }
  1276. });
  1277. }
  1278. function setNumericInput(input, value, round = 6) {
  1279. if (typeof value == "string") {
  1280. value = parseFloat(value)
  1281. }
  1282. input.value = value.toPrecision(round);
  1283. }
  1284. function getSortedEntities() {
  1285. return Object.keys(entities).sort((a, b) => {
  1286. const entA = entities[a];
  1287. const entB = entities[b];
  1288. const viewA = entA.view;
  1289. const viewB = entB.view;
  1290. const heightA = entA.views[viewA].height.to("meter").value;
  1291. const heightB = entB.views[viewB].height.to("meter").value;
  1292. return heightA - heightB;
  1293. });
  1294. }
  1295. function clearViewOptions() {
  1296. document.querySelector("#view-category-header").style.display = "none";
  1297. document.querySelector("#view-category").style.display = "none";
  1298. }
  1299. // this is a crime against humanity, and also stolen from
  1300. // stack overflow
  1301. // https://stackoverflow.com/questions/38487569/click-through-png-image-only-if-clicked-coordinate-is-transparent
  1302. const testCanvas = document.createElement("canvas");
  1303. testCanvas.id = "test-canvas";
  1304. const testCtx = testCanvas.getContext("2d");
  1305. function testClick(event) {
  1306. // oh my god I can't believe I'm doing this
  1307. const target = event.target;
  1308. if (rulerMode) {
  1309. return;
  1310. }
  1311. // Get click coordinates
  1312. let w = target.width;
  1313. let h = target.height;
  1314. let ratioW = 1, ratioH = 1;
  1315. // Limit the size of the canvas so that very large images don't cause problems)
  1316. if (w > 1000) {
  1317. ratioW = w / 1000;
  1318. w /= ratioW;
  1319. h /= ratioW;
  1320. }
  1321. if (h > 1000) {
  1322. ratioH = h / 1000;
  1323. w /= ratioH;
  1324. h /= ratioH;
  1325. }
  1326. const ratio = ratioW * ratioH;
  1327. var x = event.clientX - target.getBoundingClientRect().x,
  1328. y = event.clientY - target.getBoundingClientRect().y,
  1329. alpha;
  1330. testCtx.canvas.width = w;
  1331. testCtx.canvas.height = h;
  1332. // Draw image to canvas
  1333. // and read Alpha channel value
  1334. testCtx.drawImage(target, 0, 0, w, h);
  1335. alpha = testCtx.getImageData(Math.floor(x / ratio), Math.floor(y / ratio), 1, 1).data[3]; // [0]R [1]G [2]B [3]A
  1336. // If pixel is transparent,
  1337. // retrieve the element underneath and trigger its click event
  1338. if (alpha === 0) {
  1339. const oldDisplay = target.style.display;
  1340. target.style.display = "none";
  1341. const newTarget = document.elementFromPoint(event.clientX, event.clientY);
  1342. newTarget.dispatchEvent(new MouseEvent(event.type, {
  1343. "clientX": event.clientX,
  1344. "clientY": event.clientY
  1345. }));
  1346. target.style.display = oldDisplay;
  1347. } else {
  1348. clickDown(target.parentElement, event.clientX, event.clientY);
  1349. }
  1350. }
  1351. function arrangeEntities(order) {
  1352. const worldWidth = config.height.toNumber("meters") / canvasHeight * canvasWidth;
  1353. let sum = 0;
  1354. order.forEach(key => {
  1355. const image = document.querySelector("#entity-" + key + " > .entity-image");
  1356. const meters = entities[key].views[entities[key].view].height.toNumber("meters");
  1357. let height = image.height;
  1358. let width = image.width;
  1359. if (height == 0) {
  1360. height = 100;
  1361. }
  1362. if (width == 0) {
  1363. width = height;
  1364. }
  1365. sum += meters * width / height;
  1366. });
  1367. let x = config.x - sum / 2;
  1368. order.forEach(key => {
  1369. const image = document.querySelector("#entity-" + key + " > .entity-image");
  1370. const meters = entities[key].views[entities[key].view].height.toNumber("meters");
  1371. let height = image.height;
  1372. let width = image.width;
  1373. if (height == 0) {
  1374. height = 100;
  1375. }
  1376. if (width == 0) {
  1377. width = height;
  1378. }
  1379. x += meters * width / height / 2;
  1380. document.querySelector("#entity-" + key).dataset.x = x;
  1381. document.querySelector("#entity-" + key).dataset.y = config.y;
  1382. x += meters * width / height / 2;
  1383. })
  1384. fitWorld();
  1385. updateSizes();
  1386. }
  1387. function removeAllEntities() {
  1388. Object.keys(entities).forEach(key => {
  1389. removeEntity(document.querySelector("#entity-" + key));
  1390. });
  1391. }
  1392. function clearAttribution() {
  1393. document.querySelector("#attribution-category-header").style.display = "none";
  1394. document.querySelector("#options-attribution").style.display = "none";
  1395. }
  1396. function displayAttribution(file) {
  1397. document.querySelector("#attribution-category-header").style.display = "block";
  1398. document.querySelector("#options-attribution").style.display = "inline";
  1399. const authors = authorsOfFull(file);
  1400. const owners = ownersOfFull(file);
  1401. const citations = citationsOf(file);
  1402. const source = sourceOf(file);
  1403. const authorHolder = document.querySelector("#options-attribution-authors");
  1404. const ownerHolder = document.querySelector("#options-attribution-owners");
  1405. const citationHolder = document.querySelector("#options-attribution-citations");
  1406. const sourceHolder = document.querySelector("#options-attribution-source");
  1407. if (authors === []) {
  1408. const div = document.createElement("div");
  1409. div.innerText = "Unknown";
  1410. authorHolder.innerHTML = "";
  1411. authorHolder.appendChild(div);
  1412. } else if (authors === undefined) {
  1413. const div = document.createElement("div");
  1414. div.innerText = "Not yet entered";
  1415. authorHolder.innerHTML = "";
  1416. authorHolder.appendChild(div);
  1417. } else {
  1418. authorHolder.innerHTML = "";
  1419. const list = document.createElement("ul");
  1420. authorHolder.appendChild(list);
  1421. authors.forEach(author => {
  1422. const authorEntry = document.createElement("li");
  1423. if (author.url) {
  1424. const link = document.createElement("a");
  1425. link.href = author.url;
  1426. link.innerText = author.name;
  1427. authorEntry.appendChild(link);
  1428. } else {
  1429. const div = document.createElement("div");
  1430. div.innerText = author.name;
  1431. authorEntry.appendChild(div);
  1432. }
  1433. list.appendChild(authorEntry);
  1434. });
  1435. }
  1436. if (owners === []) {
  1437. const div = document.createElement("div");
  1438. div.innerText = "Unknown";
  1439. ownerHolder.innerHTML = "";
  1440. ownerHolder.appendChild(div);
  1441. } else if (owners === undefined) {
  1442. const div = document.createElement("div");
  1443. div.innerText = "Not yet entered";
  1444. ownerHolder.innerHTML = "";
  1445. ownerHolder.appendChild(div);
  1446. } else {
  1447. ownerHolder.innerHTML = "";
  1448. const list = document.createElement("ul");
  1449. ownerHolder.appendChild(list);
  1450. owners.forEach(owner => {
  1451. const ownerEntry = document.createElement("li");
  1452. if (owner.url) {
  1453. const link = document.createElement("a");
  1454. link.href = owner.url;
  1455. link.innerText = owner.name;
  1456. ownerEntry.appendChild(link);
  1457. } else {
  1458. const div = document.createElement("div");
  1459. div.innerText = owner.name;
  1460. ownerEntry.appendChild(div);
  1461. }
  1462. list.appendChild(ownerEntry);
  1463. });
  1464. }
  1465. if (citations === [] || citations === undefined) {
  1466. } else {
  1467. citationHolder.innerHTML = "";
  1468. const list = document.createElement("ul");
  1469. citationHolder.appendChild(list);
  1470. citations.forEach(citation => {
  1471. const citationEntry = document.createElement("li");
  1472. const link = document.createElement("a");
  1473. link.style.display = "block";
  1474. link.href = citation;
  1475. link.innerText = new URL(citation).host;
  1476. citationEntry.appendChild(link);
  1477. list.appendChild(citationEntry);
  1478. })
  1479. }
  1480. if (source === null) {
  1481. const div = document.createElement("div");
  1482. div.innerText = "No link";
  1483. sourceHolder.innerHTML = "";
  1484. sourceHolder.appendChild(div);
  1485. } else if (source === undefined) {
  1486. const div = document.createElement("div");
  1487. div.innerText = "Not yet entered";
  1488. sourceHolder.innerHTML = "";
  1489. sourceHolder.appendChild(div);
  1490. } else {
  1491. sourceHolder.innerHTML = "";
  1492. const link = document.createElement("a");
  1493. link.style.display = "block";
  1494. link.href = source;
  1495. link.innerText = new URL(source).host;
  1496. sourceHolder.appendChild(link);
  1497. }
  1498. }
  1499. function removeEntity(element) {
  1500. if (selected == element) {
  1501. deselect();
  1502. }
  1503. if (clicked == element) {
  1504. clicked = null;
  1505. }
  1506. const option = document.querySelector("#options-selected-entity-" + element.dataset.key);
  1507. option.parentElement.removeChild(option);
  1508. delete entities[element.dataset.key];
  1509. const bottomName = document.querySelector("#bottom-name-" + element.dataset.key);
  1510. const topName = document.querySelector("#top-name-" + element.dataset.key);
  1511. bottomName.parentElement.removeChild(bottomName);
  1512. topName.parentElement.removeChild(topName);
  1513. element.parentElement.removeChild(element);
  1514. }
  1515. function checkEntity(entity) {
  1516. Object.values(entity.views).forEach(view => {
  1517. if (authorsOf(view.image.source) === undefined) {
  1518. console.warn("No authors: " + view.image.source);
  1519. }
  1520. });
  1521. }
  1522. function displayEntity(entity, view, x, y, selectEntity = false, refresh = false) {
  1523. checkEntity(entity);
  1524. // preload all of the entity's views
  1525. Object.values(entity.views).forEach(view => {
  1526. if (!preloaded.has(view.image.source)) {
  1527. let img = new Image();
  1528. img.src = view.image.source;
  1529. preloaded.add(view.image.source);
  1530. }
  1531. });
  1532. const box = document.createElement("div");
  1533. box.classList.add("entity-box");
  1534. const img = document.createElement("img");
  1535. img.classList.add("entity-image");
  1536. img.addEventListener("dragstart", e => {
  1537. e.preventDefault();
  1538. });
  1539. const nameTag = document.createElement("div");
  1540. nameTag.classList.add("entity-name");
  1541. nameTag.innerText = entity.name;
  1542. box.appendChild(img);
  1543. box.appendChild(nameTag);
  1544. const image = entity.views[view].image;
  1545. img.src = image.source;
  1546. if (image.bottom !== undefined) {
  1547. img.style.setProperty("--offset", ((-1 + image.bottom) * 100) + "%")
  1548. } else {
  1549. img.style.setProperty("--offset", ((-1) * 100) + "%")
  1550. }
  1551. box.dataset.x = x;
  1552. box.dataset.y = y;
  1553. img.addEventListener("mousedown", e => { if (e.which == 1) { testClick(e); if (clicked) { e.stopPropagation() } } });
  1554. img.addEventListener("touchstart", e => {
  1555. const fakeEvent = {
  1556. target: e.target,
  1557. clientX: e.touches[0].clientX,
  1558. clientY: e.touches[0].clientY,
  1559. which: 1
  1560. };
  1561. testClick(fakeEvent);
  1562. if (clicked) { e.stopPropagation() }
  1563. });
  1564. const heightBar = document.createElement("div");
  1565. heightBar.classList.add("height-bar");
  1566. box.appendChild(heightBar);
  1567. box.id = "entity-" + entityIndex;
  1568. box.dataset.key = entityIndex;
  1569. entity.view = view;
  1570. if (entity.priority === undefined)
  1571. entity.priority = 0;
  1572. if (entity.brightness === undefined)
  1573. entity.brightness = 1;
  1574. entities[entityIndex] = entity;
  1575. entity.index = entityIndex;
  1576. const world = document.querySelector("#entities");
  1577. world.appendChild(box);
  1578. const bottomName = document.createElement("div");
  1579. bottomName.classList.add("bottom-name");
  1580. bottomName.id = "bottom-name-" + entityIndex;
  1581. bottomName.innerText = entity.name;
  1582. bottomName.addEventListener("click", () => select(box));
  1583. world.appendChild(bottomName);
  1584. const topName = document.createElement("div");
  1585. topName.classList.add("top-name");
  1586. topName.id = "top-name-" + entityIndex;
  1587. topName.innerText = entity.name;
  1588. topName.addEventListener("click", () => select(box));
  1589. world.appendChild(topName);
  1590. const entityOption = document.createElement("option");
  1591. entityOption.id = "options-selected-entity-" + entityIndex;
  1592. entityOption.value = entityIndex;
  1593. entityOption.innerText = entity.name;
  1594. document.getElementById("options-selected-entity").appendChild(entityOption);
  1595. entityIndex += 1;
  1596. if (config.autoFit) {
  1597. fitWorld();
  1598. }
  1599. if (selectEntity)
  1600. select(box);
  1601. entity.dirty = true;
  1602. if (refresh && config.autoFitAdd) {
  1603. let targets = {};
  1604. targets[entityIndex - 1] = entity;
  1605. fitEntities(targets);
  1606. }
  1607. if (refresh)
  1608. updateSizes(true);
  1609. }
  1610. window.onblur = function () {
  1611. altHeld = false;
  1612. shiftHeld = false;
  1613. }
  1614. window.onfocus = function () {
  1615. window.dispatchEvent(new Event("keydown"));
  1616. }
  1617. // thanks to https://developers.google.com/web/fundamentals/native-hardware/fullscreen
  1618. function toggleFullScreen() {
  1619. var doc = window.document;
  1620. var docEl = doc.documentElement;
  1621. var requestFullScreen = docEl.requestFullscreen || docEl.mozRequestFullScreen || docEl.webkitRequestFullScreen || docEl.msRequestFullscreen;
  1622. var cancelFullScreen = doc.exitFullscreen || doc.mozCancelFullScreen || doc.webkitExitFullscreen || doc.msExitFullscreen;
  1623. if (!doc.fullscreenElement && !doc.mozFullScreenElement && !doc.webkitFullscreenElement && !doc.msFullscreenElement) {
  1624. requestFullScreen.call(docEl);
  1625. }
  1626. else {
  1627. cancelFullScreen.call(doc);
  1628. }
  1629. }
  1630. function handleResize() {
  1631. const oldCanvasWidth = canvasWidth;
  1632. entityX = document.querySelector("#entities").getBoundingClientRect().x;
  1633. canvasWidth = document.querySelector("#display").clientWidth - 100;
  1634. canvasHeight = document.querySelector("#display").clientHeight - 50;
  1635. const change = oldCanvasWidth / canvasWidth;
  1636. updateSizes();
  1637. }
  1638. function prepareSidebar() {
  1639. const menubar = document.querySelector("#sidebar-menu");
  1640. [
  1641. {
  1642. name: "Show/hide sidebar",
  1643. id: "menu-toggle-sidebar",
  1644. icon: "fas fa-chevron-circle-down",
  1645. rotates: true
  1646. },
  1647. {
  1648. name: "Fullscreen",
  1649. id: "menu-fullscreen",
  1650. icon: "fas fa-compress"
  1651. },
  1652. {
  1653. name: "Clear",
  1654. id: "menu-clear",
  1655. icon: "fas fa-file"
  1656. },
  1657. {
  1658. name: "Sort by height",
  1659. id: "menu-order-height",
  1660. icon: "fas fa-sort-numeric-up"
  1661. },
  1662. {
  1663. name: "Permalink",
  1664. id: "menu-permalink",
  1665. icon: "fas fa-link"
  1666. },
  1667. {
  1668. name: "Export to clipboard",
  1669. id: "menu-export",
  1670. icon: "fas fa-share"
  1671. },
  1672. {
  1673. name: "Import from clipboard",
  1674. id: "menu-import",
  1675. icon: "fas fa-share",
  1676. classes: ["flipped"]
  1677. },
  1678. {
  1679. name: "Save Scene",
  1680. id: "menu-save",
  1681. icon: "fas fa-download",
  1682. input: true
  1683. },
  1684. {
  1685. name: "Load Scene",
  1686. id: "menu-load",
  1687. icon: "fas fa-upload",
  1688. select: true
  1689. },
  1690. {
  1691. name: "Delete Scene",
  1692. id: "menu-delete",
  1693. icon: "fas fa-trash",
  1694. select: true
  1695. },
  1696. {
  1697. name: "Load Autosave",
  1698. id: "menu-load-autosave",
  1699. icon: "fas fa-redo"
  1700. },
  1701. {
  1702. name: "Add Image",
  1703. id: "menu-add-image",
  1704. icon: "fas fa-camera"
  1705. },
  1706. {
  1707. name: "Clear Rulers",
  1708. id: "menu-clear-rulers",
  1709. icon: "fas fa-ruler"
  1710. }
  1711. ].forEach(entry => {
  1712. const buttonHolder = document.createElement("div");
  1713. buttonHolder.classList.add("menu-button-holder");
  1714. const button = document.createElement("button");
  1715. button.id = entry.id;
  1716. button.classList.add("menu-button");
  1717. const icon = document.createElement("i");
  1718. icon.classList.add(...entry.icon.split(" "));
  1719. if (entry.rotates) {
  1720. icon.classList.add("rotate-backward", "transitions");
  1721. }
  1722. if (entry.classes) {
  1723. entry.classes.forEach(cls => icon.classList.add(cls));
  1724. }
  1725. const actionText = document.createElement("span");
  1726. actionText.innerText = entry.name;
  1727. actionText.classList.add("menu-text");
  1728. const srText = document.createElement("span");
  1729. srText.classList.add("sr-only");
  1730. srText.innerText = entry.name;
  1731. button.appendChild(icon);
  1732. button.appendChild(srText);
  1733. buttonHolder.appendChild(button);
  1734. buttonHolder.appendChild(actionText);
  1735. if (entry.input) {
  1736. const input = document.createElement("input");
  1737. buttonHolder.appendChild(input);
  1738. input.placeholder = "default";
  1739. input.addEventListener("keyup", e => {
  1740. if (e.key === "Enter") {
  1741. const name = document.querySelector("#menu-save ~ input").value;
  1742. if (/\S/.test(name)) {
  1743. saveScene(name);
  1744. }
  1745. updateSaveInfo();
  1746. e.preventDefault();
  1747. }
  1748. })
  1749. }
  1750. if (entry.select) {
  1751. const select = document.createElement("select");
  1752. buttonHolder.appendChild(select);
  1753. }
  1754. menubar.appendChild(buttonHolder);
  1755. });
  1756. }
  1757. function checkBodyClass(cls) {
  1758. return document.body.classList.contains(cls);
  1759. }
  1760. function toggleBodyClass(cls, setting) {
  1761. if (setting) {
  1762. document.body.classList.add(cls);
  1763. } else {
  1764. document.body.classList.remove(cls);
  1765. }
  1766. }
  1767. const settingsData = {
  1768. "lock-y-axis": {
  1769. name: "Lock Y-Axis",
  1770. desc: "Keep the camera at ground-level",
  1771. type: "toggle",
  1772. default: true,
  1773. get value() {
  1774. return config.lockYAxis;
  1775. },
  1776. set value(param) {
  1777. config.lockYAxis = param;
  1778. if (param) {
  1779. config.y = 0;
  1780. updateSizes();
  1781. document.querySelector("#scroll-up").disabled = true;
  1782. document.querySelector("#scroll-down").disabled = true;
  1783. } else {
  1784. document.querySelector("#scroll-up").disabled = false;
  1785. document.querySelector("#scroll-down").disabled = false;
  1786. }
  1787. }
  1788. },
  1789. "auto-scale": {
  1790. name: "Auto-Size World",
  1791. desc: "Constantly zoom to fit the largest entity",
  1792. type: "toggle",
  1793. default: false,
  1794. get value() {
  1795. return config.autoFit;
  1796. },
  1797. set value(param) {
  1798. config.autoFit = param;
  1799. checkFitWorld();
  1800. }
  1801. },
  1802. "show-vertical-scale": {
  1803. name: "Show Vertical Scale",
  1804. desc: "Draw vertical scale marks",
  1805. type: "toggle",
  1806. default: true,
  1807. get value() {
  1808. return config.drawYAxis;
  1809. },
  1810. set value(param) {
  1811. config.drawYAxis = param;
  1812. drawScales(false);
  1813. }
  1814. },
  1815. "show-altitudes": {
  1816. name: "Show Altitudes",
  1817. desc: "Draw interesting altitudes",
  1818. type: "select",
  1819. default: "none",
  1820. options: [
  1821. "none",
  1822. "all",
  1823. "atmosphere",
  1824. "orbits",
  1825. "weather",
  1826. "water",
  1827. "geology",
  1828. "thicknesses"
  1829. ],
  1830. get value() {
  1831. return config.drawAltitudes;
  1832. },
  1833. set value(param) {
  1834. config.drawAltitudes = param;
  1835. drawScales(false);
  1836. }
  1837. },
  1838. "show-horizontal-scale": {
  1839. name: "Show Horiziontal Scale",
  1840. desc: "Draw horizontal scale marks",
  1841. type: "toggle",
  1842. default: false,
  1843. get value() {
  1844. return config.drawXAxis;
  1845. },
  1846. set value(param) {
  1847. config.drawXAxis = param;
  1848. drawScales(false);
  1849. }
  1850. },
  1851. "zoom-when-adding": {
  1852. name: "Zoom When Adding",
  1853. desc: "Zoom to fit when you add a new entity",
  1854. type: "toggle",
  1855. default: true,
  1856. get value() {
  1857. return config.autoFitAdd;
  1858. },
  1859. set value(param) {
  1860. config.autoFitAdd = param;
  1861. }
  1862. },
  1863. "zoom-when-sizing": {
  1864. name: "Zoom When Sizing",
  1865. desc: "Zoom to fit when you select an entity's size",
  1866. type: "toggle",
  1867. default: true,
  1868. get value() {
  1869. return config.autoFitSize;
  1870. },
  1871. set value(param) {
  1872. config.autoFitSize = param;
  1873. }
  1874. },
  1875. "show-ratios": {
  1876. name: "Show Ratios",
  1877. desc: "Show the proportions between the current selection and the most recent selection.",
  1878. type: "toggle",
  1879. default: true,
  1880. get value() {
  1881. return config.showRatios;
  1882. },
  1883. set value(param) {
  1884. config.showRatios = param;
  1885. if (param) {
  1886. document.body.querySelector(".ratio-info").style.display = "block";
  1887. } else {
  1888. document.body.querySelector(".ratio-info").style.display = "none";
  1889. }
  1890. }
  1891. },
  1892. "units": {
  1893. name: "Default Units",
  1894. desc: "Which kind of unit to use by default",
  1895. type: "select",
  1896. default: "metric",
  1897. options: [
  1898. "metric",
  1899. "customary",
  1900. "relative",
  1901. "quirky"
  1902. ],
  1903. get value() {
  1904. return config.units;
  1905. },
  1906. set value(param) {
  1907. config.units = param;
  1908. updateSizes();
  1909. }
  1910. },
  1911. "names": {
  1912. name: "Show Names",
  1913. desc: "Display names over entities",
  1914. type: "toggle",
  1915. default: true,
  1916. get value() {
  1917. return checkBodyClass("toggle-entity-name");
  1918. },
  1919. set value(param) {
  1920. toggleBodyClass("toggle-entity-name", param);
  1921. }
  1922. },
  1923. "bottom-names": {
  1924. name: "Bottom Names",
  1925. desc: "Display names at the bottom",
  1926. type: "toggle",
  1927. default: false,
  1928. get value() {
  1929. return checkBodyClass("toggle-bottom-name");
  1930. },
  1931. set value(param) {
  1932. toggleBodyClass("toggle-bottom-name", param);
  1933. }
  1934. },
  1935. "top-names": {
  1936. name: "Show Arrows",
  1937. desc: "Point to entities that are much larger than the current view",
  1938. type: "toggle",
  1939. default: false,
  1940. get value() {
  1941. return checkBodyClass("toggle-top-name");
  1942. },
  1943. set value(param) {
  1944. toggleBodyClass("toggle-top-name", param);
  1945. }
  1946. },
  1947. "height-bars": {
  1948. name: "Height Bars",
  1949. desc: "Draw dashed lines to the top of each entity",
  1950. type: "toggle",
  1951. default: false,
  1952. get value() {
  1953. return checkBodyClass("toggle-height-bars");
  1954. },
  1955. set value(param) {
  1956. toggleBodyClass("toggle-height-bars", param);
  1957. }
  1958. },
  1959. "glowing-entities": {
  1960. name: "Glowing Edges",
  1961. desc: "Makes all entities glow",
  1962. type: "toggle",
  1963. default: false,
  1964. get value() {
  1965. return checkBodyClass("toggle-entity-glow");
  1966. },
  1967. set value(param) {
  1968. toggleBodyClass("toggle-entity-glow", param);
  1969. }
  1970. },
  1971. "solid-ground": {
  1972. name: "Solid Ground",
  1973. desc: "Draw solid ground at the y=0 line",
  1974. type: "toggle",
  1975. default: true,
  1976. get value() {
  1977. return checkBodyClass("toggle-bottom-cover");
  1978. },
  1979. set value(param) {
  1980. toggleBodyClass("toggle-bottom-cover", param);
  1981. }
  1982. },
  1983. "auto-food-intake": {
  1984. name: "Estimate Food Intake",
  1985. desc: "Guess how much food creatures need, based on their mass -- 2000kcal per 150lbs",
  1986. type: "toggle",
  1987. default: false,
  1988. get value() {
  1989. return config.autoFoodIntake
  1990. },
  1991. set value(param) {
  1992. config.autoFoodIntake = param
  1993. }
  1994. },
  1995. "auto-prey-capacity": {
  1996. name: "Estimate Prey Capacity",
  1997. desc: "Guess how much prey creatures can hold, based on their mass",
  1998. type: "select",
  1999. default: "none",
  2000. options: [
  2001. "none",
  2002. "realistic",
  2003. "same-size"
  2004. ],
  2005. get value() {
  2006. return config.autoPreyCapacity;
  2007. },
  2008. set value(param) {
  2009. config.autoPreyCapacity = param;
  2010. }
  2011. },
  2012. }
  2013. function getBoundingBox(entities, margin = 0.05) {
  2014. }
  2015. function prepareSettings(userSettings) {
  2016. const menubar = document.querySelector("#settings-menu");
  2017. Object.entries(settingsData).forEach(([id, entry]) => {
  2018. const holder = document.createElement("label");
  2019. holder.classList.add("settings-holder");
  2020. const input = document.createElement("input");
  2021. input.id = "setting-" + id;
  2022. const name = document.createElement("label");
  2023. name.innerText = entry.name;
  2024. name.classList.add("settings-name");
  2025. name.setAttribute("for", input.id);
  2026. const desc = document.createElement("label");
  2027. desc.innerText = entry.desc;
  2028. desc.classList.add("settings-desc");
  2029. desc.setAttribute("for", input.id);
  2030. if (entry.type == "toggle") {
  2031. input.type = "checkbox";
  2032. input.checked = userSettings[id] === undefined ? entry.default : userSettings[id];
  2033. holder.setAttribute("for", input.id);
  2034. holder.appendChild(name);
  2035. holder.appendChild(input);
  2036. holder.appendChild(desc);
  2037. menubar.appendChild(holder);
  2038. const update = () => {
  2039. if (input.checked) {
  2040. holder.classList.add("enabled");
  2041. holder.classList.remove("disabled");
  2042. } else {
  2043. holder.classList.remove("enabled");
  2044. holder.classList.add("disabled");
  2045. }
  2046. entry.value = input.checked;
  2047. }
  2048. update();
  2049. input.addEventListener("change", update);
  2050. } else if (entry.type == "select") {
  2051. // we don't use the input element we made!
  2052. const select = document.createElement("select");
  2053. select.id = "setting-" + id;
  2054. entry.options.forEach(choice => {
  2055. const option = document.createElement("option");
  2056. option.innerText = choice;
  2057. select.appendChild(option);
  2058. })
  2059. select.value = userSettings[id] === undefined ? entry.default : userSettings[id];
  2060. holder.appendChild(name);
  2061. holder.appendChild(select);
  2062. holder.appendChild(desc);
  2063. menubar.appendChild(holder);
  2064. holder.classList.add("enabled");
  2065. const update = () => {
  2066. entry.value = select.value;
  2067. }
  2068. update();
  2069. select.addEventListener("change", update);
  2070. }
  2071. })
  2072. }
  2073. function prepareMenu() {
  2074. prepareSidebar();
  2075. updateSaveInfo();
  2076. if (checkHelpDate()) {
  2077. document.querySelector("#open-help").classList.add("highlighted");
  2078. }
  2079. }
  2080. function updateSaveInfo() {
  2081. const saves = getSaves();
  2082. const load = document.querySelector("#menu-load ~ select");
  2083. load.innerHTML = "";
  2084. saves.forEach(save => {
  2085. const option = document.createElement("option");
  2086. option.innerText = save;
  2087. option.value = save;
  2088. load.appendChild(option);
  2089. });
  2090. const del = document.querySelector("#menu-delete ~ select");
  2091. del.innerHTML = "";
  2092. saves.forEach(save => {
  2093. const option = document.createElement("option");
  2094. option.innerText = save;
  2095. option.value = save;
  2096. del.appendChild(option);
  2097. });
  2098. }
  2099. function getSaves() {
  2100. try {
  2101. const results = [];
  2102. Object.keys(localStorage).forEach(key => {
  2103. if (key.startsWith("macrovision-save-")) {
  2104. results.push(key.replace("macrovision-save-", ""));
  2105. }
  2106. })
  2107. return results;
  2108. } catch (err) {
  2109. alert("Something went wrong while loading (maybe you didn't have anything saved. Check the F12 console for the error.")
  2110. console.error(err);
  2111. return false;
  2112. }
  2113. }
  2114. function getUserSettings() {
  2115. try {
  2116. const settings = JSON.parse(localStorage.getItem("settings"));
  2117. return settings === null ? {} : settings;
  2118. } catch {
  2119. return {};
  2120. }
  2121. }
  2122. function exportUserSettings() {
  2123. const settings = {};
  2124. Object.entries(settingsData).forEach(([id, entry]) => {
  2125. settings[id] = entry.value;
  2126. });
  2127. return settings;
  2128. }
  2129. function setUserSettings(settings) {
  2130. try {
  2131. localStorage.setItem("settings", JSON.stringify(settings));
  2132. } catch {
  2133. // :(
  2134. }
  2135. }
  2136. const lastHelpChange = 1601955834693;
  2137. function checkHelpDate() {
  2138. try {
  2139. const old = localStorage.getItem("help-viewed");
  2140. if (old === null || old < lastHelpChange) {
  2141. return true;
  2142. }
  2143. return false;
  2144. } catch {
  2145. console.warn("Could not set the help-viewed date");
  2146. return false;
  2147. }
  2148. }
  2149. function setHelpDate() {
  2150. try {
  2151. localStorage.setItem("help-viewed", Date.now());
  2152. } catch {
  2153. console.warn("Could not set the help-viewed date");
  2154. }
  2155. }
  2156. function doYScroll() {
  2157. const worldHeight = config.height.toNumber("meters");
  2158. config.y += scrollDirection * worldHeight / 180;
  2159. updateSizes();
  2160. scrollDirection *= 1.05;
  2161. }
  2162. function doXScroll() {
  2163. const worldWidth = config.height.toNumber("meters") / canvasHeight * canvasWidth;
  2164. config.x += scrollDirection * worldWidth / 180 ;
  2165. updateSizes();
  2166. scrollDirection *= 1.05;
  2167. }
  2168. function doZoom() {
  2169. const oldHeight = config.height;
  2170. setWorldHeight(oldHeight, math.multiply(oldHeight, 1 + zoomDirection / 10));
  2171. zoomDirection *= 1.05;
  2172. }
  2173. function doSize() {
  2174. if (selected) {
  2175. const entity = entities[selected.dataset.key];
  2176. const oldHeight = entity.views[entity.view].height;
  2177. entity.views[entity.view].height = math.multiply(oldHeight, sizeDirection < 0 ? -1/sizeDirection : sizeDirection);
  2178. entity.dirty = true;
  2179. updateEntityOptions(entity, entity.view);
  2180. updateViewOptions(entity, entity.view);
  2181. updateSizes(true);
  2182. sizeDirection *= 1.01;
  2183. const ownHeight = entity.views[entity.view].height.toNumber("meters");
  2184. const worldHeight = config.height.toNumber("meters");
  2185. if (ownHeight > worldHeight) {
  2186. setWorldHeight(config.height, entity.views[entity.view].height)
  2187. } else if (ownHeight * 10 < worldHeight) {
  2188. setWorldHeight(config.height, math.multiply(entity.views[entity.view].height, 10));
  2189. }
  2190. }
  2191. }
  2192. document.addEventListener("DOMContentLoaded", () => {
  2193. prepareMenu();
  2194. prepareEntities();
  2195. document.querySelector("#open-help").addEventListener("click", e => {
  2196. setHelpDate();
  2197. document.querySelector("#open-help").classList.remove("highlighted");
  2198. window.open("https://www.notion.so/Macrovision-5c7f9377424743358ddf6db5671f439e", "_blank");
  2199. });
  2200. document.querySelector("#copy-screenshot").addEventListener("click", e => {
  2201. copyScreenshot();
  2202. toast("Copied to clipboard!");
  2203. });
  2204. document.querySelector("#save-screenshot").addEventListener("click", e => {
  2205. saveScreenshot();
  2206. });
  2207. document.querySelector("#open-screenshot").addEventListener("click", e => {
  2208. openScreenshot();
  2209. });
  2210. document.querySelector("#toggle-menu").addEventListener("click", e => {
  2211. const popoutMenu = document.querySelector("#sidebar-menu");
  2212. if (popoutMenu.classList.contains("visible")) {
  2213. popoutMenu.classList.remove("visible");
  2214. } else {
  2215. document.querySelectorAll(".popout-menu").forEach(menu => menu.classList.remove("visible"));
  2216. const rect = e.target.getBoundingClientRect();
  2217. popoutMenu.classList.add("visible");
  2218. popoutMenu.style.left = rect.x + rect.width + 10 + "px";
  2219. popoutMenu.style.top = rect.y + rect.height + 10 + "px";
  2220. }
  2221. e.stopPropagation();
  2222. });
  2223. document.querySelector("#sidebar-menu").addEventListener("click", e => {
  2224. e.stopPropagation();
  2225. });
  2226. document.addEventListener("click", e => {
  2227. document.querySelector("#sidebar-menu").classList.remove("visible");
  2228. });
  2229. document.querySelector("#toggle-settings").addEventListener("click", e => {
  2230. const popoutMenu = document.querySelector("#settings-menu");
  2231. if (popoutMenu.classList.contains("visible")) {
  2232. popoutMenu.classList.remove("visible");
  2233. } else {
  2234. document.querySelectorAll(".popout-menu").forEach(menu => menu.classList.remove("visible"));
  2235. const rect = e.target.getBoundingClientRect();
  2236. popoutMenu.classList.add("visible");
  2237. popoutMenu.style.left = rect.x + rect.width + 10 + "px";
  2238. popoutMenu.style.top = rect.y + rect.height + 10 + "px";
  2239. }
  2240. e.stopPropagation();
  2241. });
  2242. document.querySelector("#settings-menu").addEventListener("click", e => {
  2243. e.stopPropagation();
  2244. });
  2245. document.addEventListener("click", e => {
  2246. document.querySelector("#settings-menu").classList.remove("visible");
  2247. });
  2248. window.addEventListener("unload", () => {
  2249. saveScene("autosave");
  2250. setUserSettings(exportUserSettings());
  2251. });
  2252. document.querySelector("#options-selected-entity").addEventListener("input", e => {
  2253. if (e.target.value == "None") {
  2254. deselect()
  2255. } else {
  2256. select(document.querySelector("#entity-" + e.target.value));
  2257. }
  2258. });
  2259. document.querySelector("#menu-toggle-sidebar").addEventListener("click", e => {
  2260. const sidebar = document.querySelector("#options");
  2261. if (sidebar.classList.contains("hidden")) {
  2262. sidebar.classList.remove("hidden");
  2263. e.target.classList.remove("rotate-forward");
  2264. e.target.classList.add("rotate-backward");
  2265. } else {
  2266. sidebar.classList.add("hidden");
  2267. e.target.classList.add("rotate-forward");
  2268. e.target.classList.remove("rotate-backward");
  2269. }
  2270. handleResize();
  2271. });
  2272. document.querySelector("#menu-fullscreen").addEventListener("click", toggleFullScreen);
  2273. document.querySelector("#options-order-forward").addEventListener("click", e => {
  2274. if (selected) {
  2275. entities[selected.dataset.key].priority += 1;
  2276. }
  2277. document.querySelector("#options-order-display").innerText = entities[selected.dataset.key].priority;
  2278. updateSizes();
  2279. });
  2280. document.querySelector("#options-order-back").addEventListener("click", e => {
  2281. if (selected) {
  2282. entities[selected.dataset.key].priority -= 1;
  2283. }
  2284. document.querySelector("#options-order-display").innerText = entities[selected.dataset.key].priority;
  2285. updateSizes();
  2286. });
  2287. document.querySelector("#options-brightness-up").addEventListener("click", e => {
  2288. if (selected) {
  2289. entities[selected.dataset.key].brightness += 1;
  2290. }
  2291. document.querySelector("#options-brightness-display").innerText = entities[selected.dataset.key].brightness;
  2292. updateSizes();
  2293. });
  2294. document.querySelector("#options-brightness-down").addEventListener("click", e => {
  2295. if (selected) {
  2296. entities[selected.dataset.key].brightness = Math.max(entities[selected.dataset.key].brightness -1, 0);
  2297. }
  2298. document.querySelector("#options-brightness-display").innerText = entities[selected.dataset.key].brightness;
  2299. updateSizes();
  2300. });
  2301. document.querySelector("#options-flip").addEventListener("click", e => {
  2302. if (selected) {
  2303. selected.querySelector(".entity-image").classList.toggle("flipped");
  2304. }
  2305. document.querySelector("#options-brightness-display").innerText = entities[selected.dataset.key].brightness;
  2306. updateSizes();
  2307. });
  2308. const sceneChoices = document.querySelector("#scene-choices");
  2309. Object.entries(scenes).forEach(([id, scene]) => {
  2310. const option = document.createElement("option");
  2311. option.innerText = id;
  2312. option.value = id;
  2313. sceneChoices.appendChild(option);
  2314. });
  2315. document.querySelector("#load-scene").addEventListener("click", e => {
  2316. const chosen = sceneChoices.value;
  2317. removeAllEntities();
  2318. scenes[chosen]();
  2319. });
  2320. entityX = document.querySelector("#entities").getBoundingClientRect().x;
  2321. canvasWidth = document.querySelector("#display").clientWidth - 100;
  2322. canvasHeight = document.querySelector("#display").clientHeight - 50;
  2323. document.querySelector("#options-height-value").addEventListener("change", e => {
  2324. updateWorldHeight();
  2325. })
  2326. document.querySelector("#options-height-value").addEventListener("keydown", e => {
  2327. e.stopPropagation();
  2328. })
  2329. const unitSelector = document.querySelector("#options-height-unit");
  2330. Object.entries(unitChoices.length).forEach(([group, entries]) => {
  2331. const optGroup = document.createElement("optgroup");
  2332. optGroup.label = group;
  2333. unitSelector.appendChild(optGroup);
  2334. entries.forEach(entry => {
  2335. const option = document.createElement("option");
  2336. option.innerText = entry;
  2337. // we haven't loaded user settings yet, so we can't choose the unit just yet
  2338. unitSelector.appendChild(option);
  2339. })
  2340. });
  2341. unitSelector.addEventListener("input", e => {
  2342. checkFitWorld();
  2343. const scaleInput = document.querySelector("#options-height-value");
  2344. const newVal = math.unit(scaleInput.value, unitSelector.dataset.oldUnit).toNumber(e.target.value);
  2345. setNumericInput(scaleInput, newVal);
  2346. updateWorldHeight();
  2347. unitSelector.dataset.oldUnit = unitSelector.value;
  2348. });
  2349. param = new URL(window.location.href).searchParams.get("scene");
  2350. document.querySelector("#world").addEventListener("mousedown", e => {
  2351. // only middle mouse clicks
  2352. if (e.which == 2) {
  2353. panning = true;
  2354. panOffsetX = e.clientX;
  2355. panOffsetY = e.clientY;
  2356. Object.keys(entities).forEach(key => {
  2357. document.querySelector("#entity-" + key).classList.add("no-transition");
  2358. });
  2359. }
  2360. });
  2361. document.addEventListener("mouseup", e => {
  2362. if (e.which == 2) {
  2363. panning = false;
  2364. Object.keys(entities).forEach(key => {
  2365. document.querySelector("#entity-" + key).classList.remove("no-transition");
  2366. });
  2367. }
  2368. });
  2369. document.querySelector("#world").addEventListener("touchstart", e => {
  2370. if (!rulerMode) {
  2371. panning = true;
  2372. panOffsetX = e.touches[0].clientX;
  2373. panOffsetY = e.touches[0].clientY;
  2374. e.preventDefault();
  2375. Object.keys(entities).forEach(key => {
  2376. document.querySelector("#entity-" + key).classList.add("no-transition");
  2377. });
  2378. }
  2379. });
  2380. document.querySelector("#world").addEventListener("touchend", e => {
  2381. panning = false;
  2382. Object.keys(entities).forEach(key => {
  2383. document.querySelector("#entity-" + key).classList.remove("no-transition");
  2384. });
  2385. });
  2386. document.querySelector("#world").addEventListener("mousedown", e => {
  2387. // only left mouse clicks
  2388. if (e.which == 1 && rulerMode) {
  2389. let entX = document.querySelector("#entities").getBoundingClientRect().x;
  2390. let entY = document.querySelector("#entities").getBoundingClientRect().y;
  2391. const pos = pix2pos({ x: e.clientX - entX, y: e.clientY - entY });
  2392. currentRuler = { x0: pos.x, y0: pos.y, x1: pos.y, y1: pos.y };
  2393. }
  2394. });
  2395. document.querySelector("#world").addEventListener("mouseup", e => {
  2396. // only left mouse clicks
  2397. if (e.which == 1 && currentRuler) {
  2398. rulers.push(currentRuler);
  2399. currentRuler = null;
  2400. rulerMode = false;
  2401. }
  2402. });
  2403. document.querySelector("#world").addEventListener("touchstart", e => {
  2404. if (rulerMode) {
  2405. let entX = document.querySelector("#entities").getBoundingClientRect().x;
  2406. let entY = document.querySelector("#entities").getBoundingClientRect().y;
  2407. const pos = pix2pos({ x: e.touches[0].clientX - entX, y: e.touches[0].clientY - entY });
  2408. currentRuler = { x0: pos.x, y0: pos.y, x1: pos.y, y1: pos.y };
  2409. }
  2410. });
  2411. document.querySelector("#world").addEventListener("touchend", e => {
  2412. if (currentRuler) {
  2413. rulers.push(currentRuler);
  2414. currentRuler = null;
  2415. rulerMode = false;
  2416. }
  2417. });
  2418. document.querySelector("body").appendChild(testCtx.canvas);
  2419. world.addEventListener("mousedown", e => deselect(e));
  2420. world.addEventListener("touchstart", e => deselect({
  2421. which: 1,
  2422. }));
  2423. document.querySelector("#entities").addEventListener("mousedown", deselect);
  2424. document.querySelector("#display").addEventListener("mousedown", deselect);
  2425. document.addEventListener("mouseup", e => clickUp(e));
  2426. document.addEventListener("touchend", e => {
  2427. const fakeEvent = {
  2428. target: e.target,
  2429. clientX: e.changedTouches[0].clientX,
  2430. clientY: e.changedTouches[0].clientY,
  2431. which: 1
  2432. };
  2433. clickUp(fakeEvent);
  2434. });
  2435. const viewList = document.querySelector("#entity-view");
  2436. document.querySelector("#entity-view").addEventListener("input", e => {
  2437. const entity = entities[selected.dataset.key];
  2438. entity.view = e.target.value;
  2439. const image = entities[selected.dataset.key].views[e.target.value].image;
  2440. selected.querySelector(".entity-image").src = image.source;
  2441. configViewOptions(entity, entity.view);
  2442. displayAttribution(image.source);
  2443. if (image.bottom !== undefined) {
  2444. selected.querySelector(".entity-image").style.setProperty("--offset", ((-1 + image.bottom) * 100) + "%")
  2445. } else {
  2446. selected.querySelector(".entity-image").style.setProperty("--offset", ((-1) * 100) + "%")
  2447. }
  2448. updateSizes();
  2449. updateEntityOptions(entities[selected.dataset.key], e.target.value);
  2450. updateViewOptions(entities[selected.dataset.key], e.target.value);
  2451. });
  2452. document.querySelector("#entity-view").addEventListener("input", e => {
  2453. if (viewList.options[viewList.selectedIndex].classList.contains("nsfw")) {
  2454. viewList.classList.add("nsfw");
  2455. } else {
  2456. viewList.classList.remove("nsfw");
  2457. }
  2458. })
  2459. clearViewList();
  2460. document.querySelector("#menu-clear").addEventListener("click", e => {
  2461. removeAllEntities();
  2462. });
  2463. document.querySelector("#delete-entity").disabled = true;
  2464. document.querySelector("#delete-entity").addEventListener("click", e => {
  2465. if (selected) {
  2466. removeEntity(selected);
  2467. selected = null;
  2468. }
  2469. });
  2470. document.querySelector("#menu-order-height").addEventListener("click", e => {
  2471. const order = Object.keys(entities).sort((a, b) => {
  2472. const entA = entities[a];
  2473. const entB = entities[b];
  2474. const viewA = entA.view;
  2475. const viewB = entB.view;
  2476. const heightA = entA.views[viewA].height.to("meter").value;
  2477. const heightB = entB.views[viewB].height.to("meter").value;
  2478. return heightA - heightB;
  2479. });
  2480. arrangeEntities(order);
  2481. });
  2482. // TODO: write some generic logic for this lol
  2483. document.querySelector("#scroll-left").addEventListener("mousedown", e => {
  2484. scrollDirection = -1;
  2485. clearInterval(scrollHandle);
  2486. scrollHandle = setInterval(doXScroll, 1000 / 20);
  2487. e.stopPropagation();
  2488. });
  2489. document.querySelector("#scroll-right").addEventListener("mousedown", e => {
  2490. scrollDirection = 1;
  2491. clearInterval(scrollHandle);
  2492. scrollHandle = setInterval(doXScroll, 1000 / 20);
  2493. e.stopPropagation();
  2494. });
  2495. document.querySelector("#scroll-left").addEventListener("touchstart", e => {
  2496. scrollDirection = -1;
  2497. clearInterval(scrollHandle);
  2498. scrollHandle = setInterval(doXScroll, 1000 / 20);
  2499. e.stopPropagation();
  2500. });
  2501. document.querySelector("#scroll-right").addEventListener("touchstart", e => {
  2502. scrollDirection = 1;
  2503. clearInterval(scrollHandle);
  2504. scrollHandle = setInterval(doXScroll, 1000 / 20);
  2505. e.stopPropagation();
  2506. });
  2507. document.querySelector("#scroll-up").addEventListener("mousedown", e => {
  2508. scrollDirection = 1;
  2509. clearInterval(scrollHandle);
  2510. scrollHandle = setInterval(doYScroll, 1000 / 20);
  2511. e.stopPropagation();
  2512. });
  2513. document.querySelector("#scroll-down").addEventListener("mousedown", e => {
  2514. scrollDirection = -1;
  2515. clearInterval(scrollHandle);
  2516. scrollHandle = setInterval(doYScroll, 1000 / 20);
  2517. e.stopPropagation();
  2518. });
  2519. document.querySelector("#scroll-up").addEventListener("touchstart", e => {
  2520. scrollDirection = 1;
  2521. clearInterval(scrollHandle);
  2522. scrollHandle = setInterval(doYScroll, 1000 / 20);
  2523. e.stopPropagation();
  2524. });
  2525. document.querySelector("#scroll-down").addEventListener("touchstart", e => {
  2526. scrollDirection = -1;
  2527. clearInterval(scrollHandle);
  2528. scrollHandle = setInterval(doYScroll, 1000 / 20);
  2529. e.stopPropagation();
  2530. });
  2531. document.addEventListener("mouseup", e => {
  2532. clearInterval(scrollHandle);
  2533. scrollHandle = null;
  2534. });
  2535. document.addEventListener("touchend", e => {
  2536. clearInterval(scrollHandle);
  2537. scrollHandle = null;
  2538. });
  2539. document.querySelector("#zoom-in").addEventListener("mousedown", e => {
  2540. zoomDirection = -1;
  2541. clearInterval(zoomHandle);
  2542. zoomHandle = setInterval(doZoom, 1000 / 20);
  2543. e.stopPropagation();
  2544. });
  2545. document.querySelector("#zoom-out").addEventListener("mousedown", e => {
  2546. zoomDirection = 1;
  2547. clearInterval(zoomHandle);
  2548. zoomHandle = setInterval(doZoom, 1000 / 20);
  2549. e.stopPropagation();
  2550. });
  2551. document.querySelector("#zoom-in").addEventListener("touchstart", e => {
  2552. zoomDirection = -1;
  2553. clearInterval(zoomHandle);
  2554. zoomHandle = setInterval(doZoom, 1000 / 20);
  2555. e.stopPropagation();
  2556. });
  2557. document.querySelector("#zoom-out").addEventListener("touchstart", e => {
  2558. zoomDirection = 1;
  2559. clearInterval(zoomHandle);
  2560. zoomHandle = setInterval(doZoom, 1000 / 20);
  2561. e.stopPropagation();
  2562. });
  2563. document.addEventListener("mouseup", e => {
  2564. clearInterval(zoomHandle);
  2565. zoomHandle = null;
  2566. });
  2567. document.addEventListener("touchend", e => {
  2568. clearInterval(zoomHandle);
  2569. zoomHandle = null;
  2570. });
  2571. document.querySelector("#shrink").addEventListener("mousedown", e => {
  2572. sizeDirection = -1;
  2573. clearInterval(sizeHandle);
  2574. sizeHandle = setInterval(doSize, 1000 / 20);
  2575. e.stopPropagation();
  2576. });
  2577. document.querySelector("#grow").addEventListener("mousedown", e => {
  2578. sizeDirection = 1;
  2579. clearInterval(sizeHandle);
  2580. sizeHandle = setInterval(doSize, 1000 / 20);
  2581. e.stopPropagation();
  2582. });
  2583. document.querySelector("#shrink").addEventListener("touchstart", e => {
  2584. sizeDirection = -1;
  2585. clearInterval(sizeHandle);
  2586. sizeHandle = setInterval(doSize, 1000 / 20);
  2587. e.stopPropagation();
  2588. });
  2589. document.querySelector("#grow").addEventListener("touchstart", e => {
  2590. sizeDirection = 1;
  2591. clearInterval(sizeHandle);
  2592. sizeHandle = setInterval(doSize, 1000 / 20);
  2593. e.stopPropagation();
  2594. });
  2595. document.addEventListener("mouseup", e => {
  2596. clearInterval(sizeHandle);
  2597. sizeHandle = null;
  2598. });
  2599. document.addEventListener("touchend", e => {
  2600. clearInterval(sizeHandle);
  2601. sizeHandle = null;
  2602. });
  2603. document.querySelector("#ruler").addEventListener("click", e => {
  2604. rulerMode = !rulerMode;
  2605. if (rulerMode) {
  2606. toast("Ready to draw a ruler mark");
  2607. } else {
  2608. toast("Cancelled ruler mode");
  2609. }
  2610. });
  2611. document.querySelector("#ruler").addEventListener("mousedown", e => {
  2612. e.stopPropagation();
  2613. });
  2614. document.querySelector("#ruler").addEventListener("touchstart", e => {
  2615. e.stopPropagation();
  2616. });
  2617. document.querySelector("#fit").addEventListener("click", e => {
  2618. if (selected) {
  2619. let targets = {};
  2620. targets[selected.dataset.key] = entities[selected.dataset.key];
  2621. fitEntities(targets);
  2622. }
  2623. });
  2624. document.querySelector("#fit").addEventListener("mousedown", e => {
  2625. e.stopPropagation();
  2626. });
  2627. document.querySelector("#fit").addEventListener("touchstart", e => {
  2628. e.stopPropagation();
  2629. });
  2630. document.querySelector("#options-world-fit").addEventListener("click", () => fitWorld(true));
  2631. document.querySelector("#options-reset-pos-x").addEventListener("click", () => { config.x = 0; updateSizes(); });
  2632. document.querySelector("#options-reset-pos-y").addEventListener("click", () => { config.y = 0; updateSizes(); });
  2633. document.addEventListener("keydown", e => {
  2634. if (e.key == "Delete") {
  2635. if (selected) {
  2636. removeEntity(selected);
  2637. selected = null;
  2638. }
  2639. }
  2640. })
  2641. document.addEventListener("keydown", e => {
  2642. if (e.key == "Shift") {
  2643. shiftHeld = true;
  2644. e.preventDefault();
  2645. } else if (e.key == "Alt") {
  2646. altHeld = true;
  2647. movingInBounds = false; // don't snap the object back in bounds when we let go
  2648. e.preventDefault();
  2649. }
  2650. });
  2651. document.addEventListener("keyup", e => {
  2652. if (e.key == "Shift") {
  2653. shiftHeld = false;
  2654. e.preventDefault();
  2655. } else if (e.key == "Alt") {
  2656. altHeld = false;
  2657. e.preventDefault();
  2658. }
  2659. });
  2660. window.addEventListener("resize", handleResize);
  2661. // TODO: further investigate why the tool initially starts out with wrong
  2662. // values under certain circumstances (seems to be narrow aspect ratios -
  2663. // maybe the menu bar is animating when it shouldn't)
  2664. setTimeout(handleResize, 250);
  2665. setTimeout(handleResize, 500);
  2666. setTimeout(handleResize, 750);
  2667. setTimeout(handleResize, 1000);
  2668. document.querySelector("#menu-permalink").addEventListener("click", e => {
  2669. linkScene();
  2670. });
  2671. document.querySelector("#menu-export").addEventListener("click", e => {
  2672. copyScene();
  2673. });
  2674. document.querySelector("#menu-import").addEventListener("click", e => {
  2675. pasteScene();
  2676. });
  2677. document.querySelector("#menu-save").addEventListener("click", e => {
  2678. const name = document.querySelector("#menu-save ~ input").value;
  2679. if (/\S/.test(name)) {
  2680. saveScene(name);
  2681. }
  2682. updateSaveInfo();
  2683. });
  2684. document.querySelector("#menu-load").addEventListener("click", e => {
  2685. const name = document.querySelector("#menu-load ~ select").value;
  2686. if (/\S/.test(name)) {
  2687. loadScene(name);
  2688. }
  2689. });
  2690. document.querySelector("#menu-delete").addEventListener("click", e => {
  2691. const name = document.querySelector("#menu-delete ~ select").value;
  2692. if (/\S/.test(name)) {
  2693. deleteScene(name);
  2694. }
  2695. });
  2696. document.querySelector("#menu-load-autosave").addEventListener("click", e => {
  2697. loadScene("autosave");
  2698. });
  2699. document.querySelector("#menu-add-image").addEventListener("click", e => {
  2700. document.querySelector("#file-upload-picker").click();
  2701. });
  2702. document.querySelector("#file-upload-picker").addEventListener("change", e => {
  2703. if (e.target.files.length > 0) {
  2704. for (let i=0; i<e.target.files.length; i++) {
  2705. customEntityFromFile(e.target.files[i]);
  2706. }
  2707. }
  2708. })
  2709. document.querySelector("#menu-clear-rulers").addEventListener("click", e => {
  2710. rulers = [];
  2711. drawRulers();
  2712. });
  2713. document.addEventListener("paste", e => {
  2714. let index = 0;
  2715. let item = null;
  2716. let found = false;
  2717. for (; index < e.clipboardData.items.length; index++) {
  2718. item = e.clipboardData.items[index];
  2719. if (item.type == "image/png") {
  2720. found = true;
  2721. break;
  2722. }
  2723. }
  2724. if (!found) {
  2725. return;
  2726. }
  2727. let url = null;
  2728. const file = item.getAsFile();
  2729. customEntityFromFile(file);
  2730. });
  2731. document.querySelector("#world").addEventListener("dragover", e => {
  2732. e.preventDefault();
  2733. })
  2734. document.querySelector("#world").addEventListener("drop", e => {
  2735. e.preventDefault();
  2736. if (e.dataTransfer.files.length > 0) {
  2737. let entX = document.querySelector("#entities").getBoundingClientRect().x;
  2738. let entY = document.querySelector("#entities").getBoundingClientRect().y;
  2739. let coords = pix2pos({x: e.clientX-entX, y: e.clientY-entY});
  2740. customEntityFromFile(e.dataTransfer.files[0], coords.x, coords.y);
  2741. }
  2742. })
  2743. clearEntityOptions();
  2744. clearViewOptions();
  2745. clearAttribution();
  2746. // we do this last because configuring settings can cause things
  2747. // to happen (e.g. auto-fit)
  2748. prepareSettings(getUserSettings());
  2749. // now that we have this loaded, we can set it
  2750. unitSelector.dataset.oldUnit = defaultUnits.length[config.units];
  2751. document.querySelector("#options-height-unit").value = defaultUnits.length[config.units];
  2752. // ...and then update the world height by setting off an input event
  2753. document.querySelector("#options-height-unit").dispatchEvent(new Event('input', {
  2754. }));
  2755. if (param === null) {
  2756. scenes["Empty"]();
  2757. }
  2758. else {
  2759. try {
  2760. const data = JSON.parse(b64DecodeUnicode(param));
  2761. if (data.entities === undefined) {
  2762. return;
  2763. }
  2764. if (data.world === undefined) {
  2765. return;
  2766. }
  2767. importScene(data);
  2768. } catch (err) {
  2769. console.error(err);
  2770. scenes["Empty"]();
  2771. // probably wasn't valid data
  2772. }
  2773. }
  2774. document.querySelector("#world").addEventListener("wheel", e => {
  2775. if (shiftHeld) {
  2776. if (selected) {
  2777. const dir = e.deltaY > 0 ? 10 / 11 : 11 / 10;
  2778. const entity = entities[selected.dataset.key];
  2779. entity.views[entity.view].height = math.multiply(entity.views[entity.view].height, dir);
  2780. entity.dirty = true;
  2781. updateEntityOptions(entity, entity.view);
  2782. updateViewOptions(entity, entity.view);
  2783. updateSizes(true);
  2784. } else {
  2785. const worldWidth = config.height.toNumber("meters") / canvasHeight * canvasWidth;
  2786. config.x += (e.deltaY > 0 ? 1 : -1) * worldWidth / 20 ;
  2787. updateSizes();
  2788. updateSizes();
  2789. }
  2790. } else {
  2791. if (config.autoFit) {
  2792. toastRateLimit("Zoom is locked! Check Settings to disable.", "zoom-lock", 1000);
  2793. } else {
  2794. const dir = e.deltaY < 0 ? 10 / 11 : 11 / 10;
  2795. const change = config.height.toNumber("meters") - math.multiply(config.height, dir).toNumber("meters");
  2796. if (!config.lockYAxis) {
  2797. config.y += change / 2;
  2798. }
  2799. setWorldHeight(config.height, math.multiply(config.height, dir));
  2800. updateWorldOptions();
  2801. }
  2802. }
  2803. checkFitWorld();
  2804. })
  2805. updateWorldHeight();
  2806. });
  2807. function customEntityFromFile(file, x=0.5, y=0.5) {
  2808. file.arrayBuffer().then(buf => {
  2809. arr = new Uint8Array(buf);
  2810. blob = new Blob([arr], {type: file.type });
  2811. url = window.URL.createObjectURL(blob)
  2812. makeCustomEntity(url, x, y);
  2813. });
  2814. }
  2815. function makeCustomEntity(url, x=0.5, y=0.5) {
  2816. const maker = createEntityMaker(
  2817. {
  2818. name: "Custom Entity"
  2819. },
  2820. {
  2821. custom: {
  2822. attributes: {
  2823. height: {
  2824. name: "Height",
  2825. power: 1,
  2826. type: "length",
  2827. base: math.unit(6, "feet")
  2828. }
  2829. },
  2830. image: {
  2831. source: url
  2832. },
  2833. name: "Image",
  2834. info: {},
  2835. rename: false
  2836. }
  2837. },
  2838. []
  2839. );
  2840. const entity = maker.constructor();
  2841. entity.scale = config.height.toNumber("feet") / 20;
  2842. entity.ephemeral = true;
  2843. displayEntity(entity, "custom", x, y, true, true);
  2844. }
  2845. const filterDefs = {
  2846. none: {
  2847. id: "none",
  2848. name: "No Filter",
  2849. extract: maker => [],
  2850. render: name => name,
  2851. sort: (tag1, tag2) => tag1[1].localeCompare(tag2[1])
  2852. },
  2853. author: {
  2854. id: "author",
  2855. name: "Authors",
  2856. extract: maker => maker.authors ? maker.authors : [],
  2857. render: author => attributionData.people[author].name,
  2858. sort: (tag1, tag2) => tag1[1].localeCompare(tag2[1])
  2859. },
  2860. owner: {
  2861. id: "owner",
  2862. name: "Owners",
  2863. extract: maker => maker.owners ? maker.owners : [],
  2864. render: owner => attributionData.people[owner].name,
  2865. sort: (tag1, tag2) => tag1[1].localeCompare(tag2[1])
  2866. },
  2867. species: {
  2868. id: "species",
  2869. name: "Species",
  2870. extract: maker => maker.info && maker.info.species ? getSpeciesInfo(maker.info.species) : [],
  2871. render: species => speciesData[species].name,
  2872. sort: (tag1, tag2) => tag1[1].localeCompare(tag2[1])
  2873. },
  2874. tags: {
  2875. id: "tags",
  2876. name: "Tags",
  2877. extract: maker => maker.info && maker.info.tags ? maker.info.tags : [],
  2878. render: tag => tagDefs[tag],
  2879. sort: (tag1, tag2) => tag1[1].localeCompare(tag2[1])
  2880. },
  2881. size: {
  2882. id: "size",
  2883. name: "Normal Size",
  2884. extract: maker => maker.sizes && maker.sizes.length > 0 ? Array.from(maker.sizes.reduce((result, size) => {
  2885. if (result && !size.default) {
  2886. return result;
  2887. }
  2888. let meters = size.height.toNumber("meters");
  2889. if (meters < 1e-1) {
  2890. return ["micro"];
  2891. } else if (meters < 1e1) {
  2892. return ["moderate"];
  2893. } else {
  2894. return ["macro"];
  2895. }
  2896. }, null)) : [],
  2897. render: tag => { return {
  2898. "micro": "Micro",
  2899. "moderate": "Moderate",
  2900. "macro": "Macro"
  2901. }[tag]},
  2902. sort: (tag1, tag2) => {
  2903. const order = {
  2904. "micro": 0,
  2905. "moderate": 1,
  2906. "macro": 2
  2907. };
  2908. return order[tag1[0]] - order[tag2[0]];
  2909. }
  2910. },
  2911. allSizes: {
  2912. id: "allSizes",
  2913. name: "Possible Size",
  2914. extract: maker => maker.sizes ? Array.from(maker.sizes.reduce((set, size) => {
  2915. const height = size.height;
  2916. let result = Object.entries(sizeCategories).reduce((result, [name, value]) => {
  2917. if (result) {
  2918. return result;
  2919. } else {
  2920. if (math.compare(height, value) <= 0) {
  2921. return name;
  2922. }
  2923. }
  2924. }, null);
  2925. set.add(result ? result : "infinite");
  2926. return set;
  2927. }, new Set())) : [],
  2928. render: tag => tag[0].toUpperCase() + tag.slice(1),
  2929. sort: (tag1, tag2) => {
  2930. const order = [
  2931. "atomic", "microscopic", "tiny", "small", "moderate", "large", "macro", "megamacro", "planetary", "stellar",
  2932. "galactic", "universal", "omniversal", "infinite"
  2933. ]
  2934. return order.indexOf(tag1[0]) - order.indexOf(tag2[0]);
  2935. }
  2936. }
  2937. }
  2938. const sizeCategories = {
  2939. "atomic": math.unit(100, "angstroms"),
  2940. "microscopic": math.unit(100, "micrometers"),
  2941. "tiny": math.unit(100, "millimeters"),
  2942. "small": math.unit(1, "meter"),
  2943. "moderate": math.unit(3, "meters"),
  2944. "large": math.unit(10, "meters"),
  2945. "macro": math.unit(300, "meters"),
  2946. "megamacro": math.unit(1000, "kilometers"),
  2947. "planetary": math.unit(10, "earths"),
  2948. "stellar": math.unit(10, "solarradii"),
  2949. "galactic": math.unit(10, "galaxies"),
  2950. "universal": math.unit(10, "universes"),
  2951. "omniversal": math.unit(10, "multiverses")
  2952. };
  2953. function prepareEntities() {
  2954. availableEntities["buildings"] = makeBuildings();
  2955. availableEntities["characters"] = makeCharacters();
  2956. availableEntities["creatures"] = makeCreatures();
  2957. availableEntities["dildos"] = makeDildos();
  2958. availableEntities["fiction"] = makeFiction();
  2959. availableEntities["food"] = makeFood();
  2960. availableEntities["furniture"] = makeFurniture();
  2961. availableEntities["landmarks"] = makeLandmarks();
  2962. availableEntities["naturals"] = makeNaturals();
  2963. availableEntities["objects"] = makeObjects();
  2964. availableEntities["pokemon"] = makePokemon();
  2965. availableEntities["real-buildings"] = makeRealBuildings();
  2966. availableEntities["real-terrain"] = makeRealTerrains();
  2967. availableEntities["species"] = makeSpecies();
  2968. availableEntities["vehicles"] = makeVehicles();
  2969. availableEntities["species"].forEach(x => {
  2970. if (x.name == "Human") {
  2971. availableEntities["food"].push(x);
  2972. }
  2973. })
  2974. availableEntities["characters"].sort((x, y) => {
  2975. return x.name.toLowerCase() < y.name.toLowerCase() ? -1 : 1
  2976. });
  2977. availableEntities["species"].sort((x, y) => {
  2978. return x.name.toLowerCase() < y.name.toLowerCase() ? -1 : 1
  2979. });
  2980. const holder = document.querySelector("#spawners");
  2981. const filterHolder = document.querySelector("#filters");
  2982. const categorySelect = document.createElement("select");
  2983. categorySelect.id = "category-picker";
  2984. const filterSelect = document.createElement("select");
  2985. filterSelect.id = "filter-picker";
  2986. holder.appendChild(categorySelect);
  2987. filterHolder.appendChild(filterSelect);
  2988. const filterSets = {};
  2989. Object.values(filterDefs).forEach(filter => {
  2990. filterSets[filter.id] = new Set();
  2991. })
  2992. Object.entries(availableEntities).forEach(([category, entityList]) => {
  2993. const select = document.createElement("select");
  2994. select.id = "create-entity-" + category;
  2995. select.classList.add("entity-select");
  2996. for (let i = 0; i < entityList.length; i++) {
  2997. const entity = entityList[i];
  2998. const option = document.createElement("option");
  2999. option.value = i;
  3000. option.innerText = entity.name;
  3001. select.appendChild(option);
  3002. if (entity.nsfw) {
  3003. option.classList.add("nsfw");
  3004. }
  3005. Object.values(filterDefs).forEach(filter => {
  3006. filter.extract(entity).forEach(result => {
  3007. filterSets[filter.id].add(result);
  3008. });
  3009. });
  3010. availableEntitiesByName[entity.name] = entity;
  3011. };
  3012. select.addEventListener("change", e => {
  3013. if (select.options[select.selectedIndex].classList.contains("nsfw")) {
  3014. select.classList.add("nsfw");
  3015. } else {
  3016. select.classList.remove("nsfw");
  3017. }
  3018. // preload the entity's first image
  3019. const entity = entityList[select.selectedIndex].constructor();
  3020. let img = new Image();
  3021. img.src = entity.currentView.image.source;
  3022. })
  3023. const button = document.createElement("button");
  3024. button.id = "create-entity-" + category + "-button";
  3025. button.classList.add("entity-button");
  3026. button.innerHTML = "<i class=\"far fa-plus-square\"></i>";
  3027. button.addEventListener("click", e => {
  3028. const newEntity = entityList[select.value].constructor()
  3029. displayEntity(newEntity, newEntity.defaultView, config.x, config.y + (config.lockYAxis ? 0 : config.height.toNumber("meters")/2), true, true);
  3030. });
  3031. const categoryOption = document.createElement("option");
  3032. categoryOption.value = category
  3033. categoryOption.innerText = category;
  3034. if (category == "characters") {
  3035. categoryOption.selected = true;
  3036. select.classList.add("category-visible");
  3037. button.classList.add("category-visible");
  3038. }
  3039. categorySelect.appendChild(categoryOption);
  3040. holder.appendChild(select);
  3041. holder.appendChild(button);
  3042. });
  3043. Object.values(filterDefs).forEach(filter => {
  3044. const option = document.createElement("option");
  3045. option.innerText = filter.name;
  3046. option.value = filter.id;
  3047. filterSelect.appendChild(option);
  3048. const filterNameSelect = document.createElement("select");
  3049. filterNameSelect.classList.add("filter-select");
  3050. filterNameSelect.id = "filter-" + filter.id;
  3051. filterHolder.appendChild(filterNameSelect);
  3052. const button = document.createElement("button");
  3053. button.classList.add("filter-button");
  3054. button.id = "create-filtered-" + filter.id + "-button";
  3055. filterHolder.appendChild(button);
  3056. const counter = document.createElement("div");
  3057. counter.classList.add("button-counter");
  3058. counter.innerText = "10";
  3059. button.appendChild(counter);
  3060. const i = document.createElement("i");
  3061. i.classList.add("fas");
  3062. i.classList.add("fa-plus");
  3063. button.appendChild(i);
  3064. button.addEventListener("click", e => {
  3065. const makers = Array.from(document.querySelector(".entity-select.category-visible")).filter(element => !element.classList.contains("filtered"));
  3066. const count = makers.length + 2;
  3067. let index = 1;
  3068. if (makers.length > 50) {
  3069. if (!confirm("Really spawn " + makers.length + " things at once?")) {
  3070. return;
  3071. }
  3072. }
  3073. const worldWidth = config.height.toNumber("meters") / canvasHeight * canvasWidth;
  3074. const spawned = makers.map(element => {
  3075. const category = document.querySelector("#category-picker").value;
  3076. const maker = availableEntities[category][element.value];
  3077. const entity = maker.constructor()
  3078. displayEntity(entity, entity.view, -worldWidth * 0.45 + config.x + worldWidth * 0.9 * index / (count - 1), config.y);
  3079. index += 1;
  3080. return entityIndex - 1;
  3081. });
  3082. updateSizes(true);
  3083. if (config.autoFitAdd) {
  3084. let targets = {};
  3085. spawned.forEach(key => {
  3086. targets[key] = entities[key];
  3087. })
  3088. fitEntities(targets);
  3089. }
  3090. });
  3091. Array.from(filterSets[filter.id]).map(name => [name, filter.render(name)]).sort(filterDefs[filter.id].sort).forEach(name => {
  3092. const option = document.createElement("option");
  3093. option.innerText = name[1];
  3094. option.value = name[0];
  3095. filterNameSelect.appendChild(option);
  3096. });
  3097. filterNameSelect.addEventListener("change", e => {
  3098. updateFilter();
  3099. });
  3100. });
  3101. console.log("Loaded " + Object.keys(availableEntitiesByName).length + " entities");
  3102. categorySelect.addEventListener("input", e => {
  3103. const oldSelect = document.querySelector(".entity-select.category-visible");
  3104. oldSelect.classList.remove("category-visible");
  3105. const oldButton = document.querySelector(".entity-button.category-visible");
  3106. oldButton.classList.remove("category-visible");
  3107. const newSelect = document.querySelector("#create-entity-" + e.target.value);
  3108. newSelect.classList.add("category-visible");
  3109. const newButton = document.querySelector("#create-entity-" + e.target.value + "-button");
  3110. newButton.classList.add("category-visible");
  3111. recomputeFilters();
  3112. updateFilter();
  3113. });
  3114. recomputeFilters();
  3115. filterSelect.addEventListener("input", e => {
  3116. const oldSelect = document.querySelector(".filter-select.category-visible");
  3117. if (oldSelect)
  3118. oldSelect.classList.remove("category-visible");
  3119. const newSelect = document.querySelector("#filter-" + e.target.value);
  3120. if (newSelect && e.target.value != "none")
  3121. newSelect.classList.add("category-visible");
  3122. updateFilter();
  3123. });
  3124. }
  3125. // Only display authors and owners if they appear
  3126. // somewhere in the current entity list
  3127. function recomputeFilters() {
  3128. const category = document.querySelector("#category-picker").value;
  3129. const filterSets = {};
  3130. Object.values(filterDefs).forEach(filter => {
  3131. filterSets[filter.id] = new Set();
  3132. });
  3133. document.querySelectorAll(".entity-select.category-visible > option").forEach(element => {
  3134. const entity = availableEntities[category][element.value];
  3135. Object.values(filterDefs).forEach(filter => {
  3136. filter.extract(entity).forEach(result => {
  3137. filterSets[filter.id].add(result);
  3138. });
  3139. });
  3140. });
  3141. Object.values(filterDefs).forEach(filter => {
  3142. // always show the "none" option
  3143. let found = filter.id == "none";
  3144. document.querySelectorAll("#filter-" + filter.id + " > option").forEach(element => {
  3145. if (filterSets[filter.id].has(element.value) || filter.id == "none") {
  3146. element.classList.remove("filtered");
  3147. element.disabled = false;
  3148. found = true;
  3149. } else {
  3150. element.classList.add("filtered");
  3151. element.disabled = true;
  3152. }
  3153. });
  3154. const filterOption = document.querySelector("#filter-picker > option[value='" + filter.id + "']");
  3155. if (found) {
  3156. filterOption.classList.remove("filtered");
  3157. filterOption.disabled = false;
  3158. } else {
  3159. filterOption.classList.add("filtered");
  3160. filterOption.disabled = true;
  3161. }
  3162. });
  3163. document.querySelector("#filter-picker").value = "none";
  3164. document.querySelector("#filter-picker").dispatchEvent(new Event("input"));
  3165. }
  3166. function updateFilter() {
  3167. const category = document.querySelector("#category-picker").value;
  3168. const type = document.querySelector("#filter-picker").value;
  3169. const filterKeySelect = document.querySelector(".filter-select.category-visible");
  3170. clearFilter();
  3171. if (!filterKeySelect) {
  3172. return;
  3173. }
  3174. const key = filterKeySelect.value;
  3175. let current = document.querySelector(".entity-select.category-visible").value;
  3176. let replace = false;
  3177. let first = null;
  3178. let count = 0;
  3179. document.querySelectorAll(".entity-select.category-visible > option").forEach(element => {
  3180. let keep = type == "none";
  3181. if (filterDefs[type].extract(availableEntities[category][element.value]).indexOf(key) >= 0) {
  3182. keep = true;
  3183. }
  3184. if (!keep) {
  3185. element.classList.add("filtered");
  3186. element.disabled = true;
  3187. if (current == element.value) {
  3188. replace = true;
  3189. }
  3190. } else {
  3191. count += 1;
  3192. if (!first) {
  3193. first = element.value;
  3194. }
  3195. }
  3196. });
  3197. const button = document.querySelector(".filter-select.category-visible + button");
  3198. if (button) {
  3199. button.querySelector(".button-counter").innerText = count;
  3200. }
  3201. if (replace) {
  3202. document.querySelector(".entity-select.category-visible").value = first;
  3203. document.querySelector("#create-entity-" + category).dispatchEvent(new Event("change"));
  3204. }
  3205. }
  3206. function clearFilter() {
  3207. document.querySelectorAll(".entity-select.category-visible > option").forEach(element => {
  3208. element.classList.remove("filtered");
  3209. element.disabled = false;
  3210. });
  3211. }
  3212. document.addEventListener("mousemove", (e) => {
  3213. if (currentRuler) {
  3214. let entX = document.querySelector("#entities").getBoundingClientRect().x;
  3215. let entY = document.querySelector("#entities").getBoundingClientRect().y;
  3216. let position = pix2pos({ x: e.clientX - entX, y: e.clientY - entY });
  3217. currentRuler.x1 = position.x;
  3218. currentRuler.y1 = position.y;
  3219. }
  3220. drawRulers();
  3221. });
  3222. document.addEventListener("touchmove", (e) => {
  3223. if (currentRuler) {
  3224. let entX = document.querySelector("#entities").getBoundingClientRect().x;
  3225. let entY = document.querySelector("#entities").getBoundingClientRect().y;
  3226. let position = pix2pos({ x: e.touches[0].clientX - entX, y: e.touches[0].clientY - entY });
  3227. currentRuler.x1 = position.x;
  3228. currentRuler.y1 = position.y;
  3229. }
  3230. drawRulers();
  3231. });
  3232. document.addEventListener("mousemove", (e) => {
  3233. if (clicked) {
  3234. let position = pix2pos({ x: e.clientX - dragOffsetX, y: e.clientY - dragOffsetY });
  3235. if (movingInBounds) {
  3236. position = snapPos(position);
  3237. } else {
  3238. let x = e.clientX - dragOffsetX;
  3239. let y = e.clientY - dragOffsetY;
  3240. if (x >= 0 && x <= canvasWidth && y >= 0 && y <= canvasHeight) {
  3241. movingInBounds = true;
  3242. }
  3243. }
  3244. clicked.dataset.x = position.x;
  3245. clicked.dataset.y = position.y;
  3246. updateEntityElement(entities[clicked.dataset.key], clicked);
  3247. if (hoveringInDeleteArea(e)) {
  3248. document.querySelector("#menubar").classList.add("hover-delete");
  3249. } else {
  3250. document.querySelector("#menubar").classList.remove("hover-delete");
  3251. }
  3252. }
  3253. if (panning && panReady) {
  3254. const worldWidth = config.height.toNumber("meters") / canvasHeight * canvasWidth;
  3255. const worldHeight = config.height.toNumber("meters");
  3256. config.x -= (e.clientX - panOffsetX) / canvasWidth * worldWidth;
  3257. config.y += (e.clientY - panOffsetY) / canvasHeight * worldHeight;
  3258. panOffsetX = e.clientX;
  3259. panOffsetY = e.clientY;
  3260. updateSizes();
  3261. panReady = false;
  3262. setTimeout(() => panReady=true, 1000/120);
  3263. }
  3264. });
  3265. document.addEventListener("touchmove", (e) => {
  3266. if (clicked) {
  3267. e.preventDefault();
  3268. let x = e.touches[0].clientX;
  3269. let y = e.touches[0].clientY;
  3270. const position = snapPos(pix2pos({ x: x - dragOffsetX, y: y - dragOffsetY }));
  3271. clicked.dataset.x = position.x;
  3272. clicked.dataset.y = position.y;
  3273. updateEntityElement(entities[clicked.dataset.key], clicked);
  3274. // what a hack
  3275. // I should centralize this 'fake event' creation...
  3276. if (hoveringInDeleteArea({ clientY: y })) {
  3277. document.querySelector("#menubar").classList.add("hover-delete");
  3278. } else {
  3279. document.querySelector("#menubar").classList.remove("hover-delete");
  3280. }
  3281. }
  3282. if (panning && panReady) {
  3283. const worldWidth = config.height.toNumber("meters") / canvasHeight * canvasWidth;
  3284. const worldHeight = config.height.toNumber("meters");
  3285. config.x -= (e.touches[0].clientX - panOffsetX) / canvasWidth * worldWidth;
  3286. config.y += (e.touches[0].clientY - panOffsetY) / canvasHeight * worldHeight;
  3287. panOffsetX = e.touches[0].clientX;
  3288. panOffsetY = e.touches[0].clientY;
  3289. updateSizes();
  3290. panReady = false;
  3291. setTimeout(() => panReady=true, 1000/60);
  3292. }
  3293. }, { passive: false });
  3294. function checkFitWorld() {
  3295. if (config.autoFit) {
  3296. fitWorld();
  3297. return true;
  3298. }
  3299. return false;
  3300. }
  3301. function fitWorld(manual = false, factor = 1.1) {
  3302. if (Object.keys(entities).length > 0) {
  3303. fitEntities(entities, factor);
  3304. }
  3305. }
  3306. function fitEntities(targetEntities, manual = false, factor = 1.1) {
  3307. let minX = Infinity;
  3308. let maxX = -Infinity;
  3309. let minY = Infinity;
  3310. let maxY = -Infinity;
  3311. let count = 0;
  3312. const worldWidth = config.height.toNumber("meters") / canvasHeight * canvasWidth;
  3313. const worldHeight = config.height.toNumber("meters");
  3314. Object.entries(targetEntities).forEach(([key, entity]) => {
  3315. const view = entity.view;
  3316. let extra = entity.views[view].image.extra;
  3317. extra = extra === undefined ? 1 : extra;
  3318. const image = document.querySelector("#entity-" + key + " > .entity-image");
  3319. const x = parseFloat(document.querySelector("#entity-" + key).dataset.x);
  3320. let width = image.width;
  3321. let height = image.height;
  3322. // only really relevant if the images haven't loaded in yet
  3323. if (height == 0) {
  3324. height = 100;
  3325. }
  3326. if (width == 0) {
  3327. width = height;
  3328. }
  3329. const xBottom = x - entity.views[view].height.toNumber("meters") * width / height / 2;
  3330. const xTop = x + entity.views[view].height.toNumber("meters") * width / height / 2;
  3331. const y = parseFloat(document.querySelector("#entity-" + key).dataset.y);
  3332. const yBottom = y;
  3333. const yTop = entity.views[view].height.toNumber("meters") + yBottom;
  3334. minX = Math.min(minX, xBottom);
  3335. maxX = Math.max(maxX, xTop);
  3336. minY = Math.min(minY, yBottom);
  3337. maxY = Math.max(maxY, yTop);
  3338. count += 1;
  3339. });
  3340. if (config.lockYAxis) {
  3341. minY = 0;
  3342. }
  3343. let ySize = (maxY - minY) * factor;
  3344. let xSize = (maxX - minX) * factor;
  3345. if (xSize / ySize > worldWidth / worldHeight) {
  3346. ySize *= ((xSize / ySize) / (worldWidth / worldHeight));
  3347. }
  3348. config.x = (maxX + minX) / 2;
  3349. config.y = minY;
  3350. height = math.unit(ySize, "meter")
  3351. setWorldHeight(config.height, math.multiply(height, factor));
  3352. }
  3353. // TODO why am I doing this
  3354. function updateWorldHeight() {
  3355. const unit = document.querySelector("#options-height-unit").value;
  3356. const value = Math.max(0.000000001, document.querySelector("#options-height-value").value);
  3357. const oldHeight = config.height;
  3358. setWorldHeight(oldHeight, math.unit(value, unit));
  3359. }
  3360. function setWorldHeight(oldHeight, newHeight) {
  3361. worldSizeDirty = true;
  3362. config.height = newHeight.to(document.querySelector("#options-height-unit").value)
  3363. const unit = document.querySelector("#options-height-unit").value;
  3364. setNumericInput(document.querySelector("#options-height-value"), config.height.toNumber(unit));
  3365. Object.entries(entities).forEach(([key, entity]) => {
  3366. const element = document.querySelector("#entity-" + key);
  3367. let newPosition;
  3368. if (altHeld) {
  3369. newPosition = adjustAbs({ x: element.dataset.x, y: element.dataset.y }, oldHeight, config.height);
  3370. } else {
  3371. newPosition = { x: element.dataset.x, y: element.dataset.y };
  3372. }
  3373. element.dataset.x = newPosition.x;
  3374. element.dataset.y = newPosition.y;
  3375. });
  3376. updateSizes();
  3377. }
  3378. function loadScene(name = "default") {
  3379. if (name === "") {
  3380. name = "default"
  3381. }
  3382. try {
  3383. const data = JSON.parse(localStorage.getItem("macrovision-save-" + name));
  3384. if (data === null) {
  3385. console.error("Couldn't load " + name)
  3386. return false;
  3387. }
  3388. importScene(data);
  3389. toast("Loaded " + name);
  3390. return true;
  3391. } catch (err) {
  3392. alert("Something went wrong while loading (maybe you didn't have anything saved. Check the F12 console for the error.")
  3393. console.error(err);
  3394. return false;
  3395. }
  3396. }
  3397. function saveScene(name = "default") {
  3398. try {
  3399. const string = JSON.stringify(exportScene());
  3400. localStorage.setItem("macrovision-save-" + name, string);
  3401. toast("Saved as " + name);
  3402. } catch (err) {
  3403. alert("Something went wrong while saving (maybe I don't have localStorage permissions, or exporting failed). Check the F12 console for the error.")
  3404. console.error(err);
  3405. }
  3406. }
  3407. function deleteScene(name = "default") {
  3408. if (confirm("Really delete the " + name + " scene?")) {
  3409. try {
  3410. localStorage.removeItem("macrovision-save-" + name)
  3411. toast("Deleted " + name);
  3412. } catch (err) {
  3413. console.error(err);
  3414. }
  3415. }
  3416. updateSaveInfo();
  3417. }
  3418. function exportScene() {
  3419. const results = {};
  3420. results.entities = [];
  3421. Object.entries(entities).filter(([key, entity]) => entity.ephemeral !== true).forEach(([key, entity]) => {
  3422. const element = document.querySelector("#entity-" + key);
  3423. results.entities.push({
  3424. name: entity.identifier,
  3425. customName: entity.name,
  3426. scale: entity.scale,
  3427. view: entity.view,
  3428. x: element.dataset.x,
  3429. y: element.dataset.y,
  3430. priority: entity.priority,
  3431. brightness: entity.brightness
  3432. });
  3433. });
  3434. const unit = document.querySelector("#options-height-unit").value;
  3435. results.world = {
  3436. height: config.height.toNumber(unit),
  3437. unit: unit,
  3438. x: config.x,
  3439. y: config.y
  3440. }
  3441. results.version = migrationDefs.length;
  3442. return results;
  3443. }
  3444. // btoa doesn't like anything that isn't ASCII
  3445. // great
  3446. // thanks to https://stackoverflow.com/questions/30106476/using-javascripts-atob-to-decode-base64-doesnt-properly-decode-utf-8-strings
  3447. // for providing an alternative
  3448. function b64EncodeUnicode(str) {
  3449. // first we use encodeURIComponent to get percent-encoded UTF-8,
  3450. // then we convert the percent encodings into raw bytes which
  3451. // can be fed into btoa.
  3452. return btoa(encodeURIComponent(str).replace(/%([0-9A-F]{2})/g,
  3453. function toSolidBytes(match, p1) {
  3454. return String.fromCharCode('0x' + p1);
  3455. }));
  3456. }
  3457. function b64DecodeUnicode(str) {
  3458. // Going backwards: from bytestream, to percent-encoding, to original string.
  3459. return decodeURIComponent(atob(str).split('').map(function (c) {
  3460. return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
  3461. }).join(''));
  3462. }
  3463. function linkScene() {
  3464. loc = new URL(window.location);
  3465. const link = loc.protocol + "//" + loc.host + loc.pathname + "?scene=" + b64EncodeUnicode(JSON.stringify(exportScene()));
  3466. window.history.replaceState(null, "Macrovision", link);
  3467. try {
  3468. navigator.clipboard.writeText(link);
  3469. toast("Copied permalink to clipboard");
  3470. } catch {
  3471. toast("Couldn't copy permalink");
  3472. }
  3473. }
  3474. function copyScene() {
  3475. const results = exportScene();
  3476. navigator.clipboard.writeText(JSON.stringify(results));
  3477. }
  3478. function pasteScene() {
  3479. try {
  3480. navigator.clipboard.readText().then(text => {
  3481. const data = JSON.parse(text);
  3482. if (data.entities === undefined) {
  3483. return;
  3484. }
  3485. if (data.world === undefined) {
  3486. return;
  3487. }
  3488. importScene(data);
  3489. }).catch(err => alert(err));
  3490. } catch (err) {
  3491. console.error(err);
  3492. // probably wasn't valid data
  3493. }
  3494. }
  3495. // TODO - don't just search through every single entity
  3496. // probably just have a way to do lookups directly
  3497. function findEntity(name) {
  3498. return availableEntitiesByName[name];
  3499. }
  3500. const migrationDefs = [
  3501. /*
  3502. Migration: 0 -> 1
  3503. Adds x and y coordinates for the camera
  3504. */
  3505. data => {
  3506. data.world.x = 0;
  3507. data.world.y = 0;
  3508. },
  3509. /*
  3510. Migration: 1 -> 2
  3511. Adds priority and brightness to each entity
  3512. */
  3513. data => {
  3514. data.entities.forEach(entity => {
  3515. entity.priority = 0;
  3516. entity.brightness = 1;
  3517. });
  3518. },
  3519. /*
  3520. Migration: 2 -> 3
  3521. Custom names are exported
  3522. */
  3523. data => {
  3524. data.entities.forEach(entity => {
  3525. entity.customName = entity.name
  3526. });
  3527. }
  3528. ]
  3529. function migrateScene(data) {
  3530. if (data.version === undefined) {
  3531. alert("This save was created before save versions were tracked. The scene may import incorrectly.");
  3532. console.trace()
  3533. data.version = 0;
  3534. } else if (data.version < migrationDefs.length) {
  3535. migrationDefs[data.version](data);
  3536. data.version += 1;
  3537. migrateScene(data);
  3538. }
  3539. }
  3540. function importScene(data) {
  3541. removeAllEntities();
  3542. migrateScene(data);
  3543. data.entities.forEach(entityInfo => {
  3544. const entity = findEntity(entityInfo.name).constructor();
  3545. entity.name = entityInfo.customName;
  3546. entity.scale = entityInfo.scale;
  3547. entity.priority = entityInfo.priority;
  3548. entity.brightness = entityInfo.brightness;
  3549. displayEntity(entity, entityInfo.view, entityInfo.x, entityInfo.y);
  3550. });
  3551. config.height = math.unit(data.world.height, data.world.unit);
  3552. config.x = data.world.x;
  3553. config.y = data.world.y;
  3554. const height = math.unit(data.world.height, data.world.unit).toNumber(defaultUnits.length[config.units]);
  3555. document.querySelector("#options-height-value").value = height;
  3556. document.querySelector("#options-height-unit").dataset.oldUnit = defaultUnits.length[config.units];
  3557. document.querySelector("#options-height-unit").value = defaultUnits.length[config.units];
  3558. if (data.canvasWidth) {
  3559. doHorizReposition(data.canvasWidth / canvasWidth);
  3560. }
  3561. updateSizes();
  3562. }
  3563. function renderToCanvas() {
  3564. const ctx = document.querySelector("#display").getContext("2d");
  3565. Object.entries(entities).sort((ent1, ent2) => {
  3566. z1 = document.querySelector("#entity-" + ent1[0]).style.zIndex;
  3567. z2 = document.querySelector("#entity-" + ent2[0]).style.zIndex;
  3568. return z1 - z2;
  3569. }).forEach(([id, entity]) => {
  3570. element = document.querySelector("#entity-" + id);
  3571. img = element.querySelector("img");
  3572. let x = parseFloat(element.dataset.x);
  3573. let y = parseFloat(element.dataset.y);
  3574. let coords = pos2pix({x: x, y: y});
  3575. let offset = img.style.getPropertyValue("--offset");
  3576. offset = parseFloat(offset.substring(0, offset.length-1))
  3577. x = coords.x - img.getBoundingClientRect().width/2;
  3578. y = coords.y - img.getBoundingClientRect().height * (-offset/100);
  3579. let xSize = img.getBoundingClientRect().width;
  3580. let ySize = img.getBoundingClientRect().height;
  3581. const oldFilter = ctx.filter
  3582. const brightness = getComputedStyle(element).getPropertyValue("--brightness")
  3583. ctx.filter = `brightness(${brightness})`;
  3584. ctx.drawImage(img, x, y, xSize, ySize);
  3585. ctx.drawImage(document.querySelector("#rulers"), 0, 0);
  3586. ctx.filter = oldFilter
  3587. });
  3588. }
  3589. function exportCanvas(callback) {
  3590. /** @type {CanvasRenderingContext2D} */
  3591. const ctx = document.querySelector("#display").getContext("2d");
  3592. const blob = ctx.canvas.toBlob(callback);
  3593. }
  3594. function generateScreenshot(callback) {
  3595. /** @type {CanvasRenderingContext2D} */
  3596. const ctx = document.querySelector("#display").getContext("2d");
  3597. if (checkBodyClass("toggle-bottom-cover")) {
  3598. ctx.fillStyle = "#000";
  3599. ctx.fillRect(0, pos2pix({x: 0, y: 0}).y, canvasWidth + 100, canvasHeight);
  3600. }
  3601. renderToCanvas();
  3602. ctx.fillStyle = "#777";
  3603. ctx.font = "normal normal lighter 16pt coda";
  3604. ctx.fillText("macrovision.crux.sexy", 10, 25);
  3605. exportCanvas(blob => {
  3606. callback(blob);
  3607. });
  3608. }
  3609. function copyScreenshot() {
  3610. if (window.ClipboardItem === undefined) {
  3611. alert("Sorry, this browser doesn't yet support writing images to the clipboard.");
  3612. return;
  3613. }
  3614. generateScreenshot(blob => {
  3615. navigator.clipboard.write([
  3616. new ClipboardItem({
  3617. "image/png": blob
  3618. })
  3619. ]);
  3620. });
  3621. drawScales(false);
  3622. }
  3623. function saveScreenshot() {
  3624. generateScreenshot(blob => {
  3625. const a = document.createElement("a");
  3626. a.href = URL.createObjectURL(blob);
  3627. a.setAttribute("download", "macrovision.png");
  3628. a.click();
  3629. });
  3630. drawScales(false);
  3631. }
  3632. function openScreenshot() {
  3633. generateScreenshot(blob => {
  3634. const a = document.createElement("a");
  3635. a.href = URL.createObjectURL(blob);
  3636. a.setAttribute("target", "_blank");
  3637. a.click();
  3638. });
  3639. drawScales(false);
  3640. }
  3641. const rateLimits = {};
  3642. function toast(msg) {
  3643. let div = document.createElement("div");
  3644. div.innerHTML = msg;
  3645. div.classList.add("toast");
  3646. document.body.appendChild(div);
  3647. setTimeout(() => {
  3648. document.body.removeChild(div);
  3649. }, 5000)
  3650. }
  3651. function toastRateLimit(msg, key, delay) {
  3652. if (!rateLimits[key]) {
  3653. toast(msg);
  3654. rateLimits[key] = setTimeout(() => {
  3655. delete rateLimits[key]
  3656. }, delay);
  3657. }
  3658. }
  3659. let lastTime = undefined;
  3660. function pan(fromX, fromY, fromHeight, toX, toY, toHeight, duration) {
  3661. Object.keys(entities).forEach(key => {
  3662. document.querySelector("#entity-" + key).classList.add("no-transition");
  3663. });
  3664. config.x = fromX;
  3665. config.y = fromY;
  3666. config.height = math.unit(fromHeight, "meters")
  3667. updateSizes();
  3668. lastTime = undefined;
  3669. requestAnimationFrame((timestamp) => panTo(toX, toY, toHeight, (toX - fromX) / duration, (toY - fromY) / duration, (toHeight - fromHeight) / duration, timestamp, duration));
  3670. }
  3671. function panTo(x, y, height, xSpeed, ySpeed, heightSpeed, timestamp, remaining) {
  3672. if (lastTime === undefined) {
  3673. lastTime = timestamp;
  3674. }
  3675. dt = timestamp - lastTime;
  3676. remaining -= dt;
  3677. console.log(lastTime, remaining, dt)
  3678. if (remaining < 0) {
  3679. dt += remaining
  3680. }
  3681. let newX = config.x + xSpeed * dt;
  3682. let newY = config.y + ySpeed * dt;
  3683. let newHeight = config.height.toNumber("meters") + heightSpeed * dt;
  3684. console.log(newX);
  3685. if (remaining > 0) {
  3686. requestAnimationFrame((timestamp) => panTo(x, y, height, xSpeed, ySpeed, heightSpeed, timestamp, remaining))
  3687. } else {
  3688. Object.keys(entities).forEach(key => {
  3689. document.querySelector("#entity-" + key).classList.remove("no-transition");
  3690. });
  3691. }
  3692. config.x = newX;
  3693. config.y = newY;
  3694. config.height = math.unit(newHeight, "meters");
  3695. updateSizes();
  3696. }