less copy protection, more size visualization
No puede seleccionar más de 25 temas Los temas deben comenzar con una letra o número, pueden incluir guiones ('-') y pueden tener hasta 35 caracteres de largo.
 
 
 

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