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

4447 lignes
135 KiB

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