less copy protection, more size visualization
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

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