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.
 
 
 

6249 lines
185 KiB

  1. let selected = null;
  2. let prevSelected = null;
  3. let selectedEntity = null;
  4. let prevSelectedEntity = null;
  5. let entityIndex = 0;
  6. let firsterror = true;
  7. let clicked = null;
  8. let movingInBounds = false;
  9. let dragging = false;
  10. let clickTimeout = null;
  11. let dragOffsetX = null;
  12. let dragOffsetY = null;
  13. let preloaded = new Set();
  14. let panning = false;
  15. let panReady = true;
  16. let panOffsetX = null;
  17. let panOffsetY = null;
  18. let shiftHeld = false;
  19. let altHeld = false;
  20. let entityX;
  21. let canvasWidth;
  22. let canvasHeight;
  23. let dragScale = 1;
  24. let dragScaleHandle = null;
  25. let dragEntityScale = 1;
  26. let dragEntityScaleHandle = null;
  27. let scrollDirection = 0;
  28. let scrollHandle = null;
  29. let zoomDirection = 0;
  30. let zoomHandle = null;
  31. let sizeDirection = 0;
  32. let sizeHandle = null;
  33. let worldSizeDirty = false;
  34. let rulerMode = false;
  35. let rulers = [];
  36. let currentRuler = undefined;
  37. let webkitCanvasBug = false;
  38. const tagDefs = {
  39. anthro: "Anthro",
  40. feral: "Feral",
  41. taur: "Taur",
  42. naga: "Naga",
  43. goo: "Goo",
  44. };
  45. math.createUnit({
  46. ShoeSizeMensUS: {
  47. prefixes: "long",
  48. definition: "0.3333333333333333333 inches",
  49. offset: 22,
  50. },
  51. ShoeSizeWomensUS: {
  52. prefixes: "long",
  53. definition: "0.3333333333333333333 inches",
  54. offset: 21,
  55. },
  56. ShoeSizeEU: {
  57. prefixes: "long",
  58. definition: "0.666666666667 cm",
  59. offset: -2,
  60. },
  61. ShoeSizeUK: {
  62. prefixes: "long",
  63. definition: "0.3333333333333333333 in",
  64. offset: 23,
  65. },
  66. });
  67. math.createUnit("humans", {
  68. definition: "5.75 feet",
  69. });
  70. math.createUnit("story", {
  71. definition: "12 feet",
  72. prefixes: "long",
  73. });
  74. math.createUnit("stories", {
  75. definition: "12 feet",
  76. prefixes: "long",
  77. });
  78. math.createUnit("buses", {
  79. definition: "11.95 meters",
  80. prefixes: "long",
  81. });
  82. math.createUnit("marathons", {
  83. definition: "26.2 miles",
  84. prefixes: "long",
  85. });
  86. math.createUnit("timezones", {
  87. definition: "1037.54167 miles",
  88. prefixes: "long",
  89. aliases: ["timezone", "timezones"],
  90. });
  91. math.createUnit("nauticalMiles", {
  92. definition: "6080 feet",
  93. prefixes: "long",
  94. aliases: ["nauticalMile", "nauticalMiles"],
  95. });
  96. math.createUnit("fathoms", {
  97. definition: "6 feet",
  98. prefixes: "long",
  99. aliases: ["fathom", "fathoms"],
  100. });
  101. math.createUnit("U", {
  102. definition: "1.75 inches",
  103. prefixes: "short",
  104. });
  105. math.createUnit("earths", {
  106. definition: "12756km",
  107. prefixes: "long",
  108. aliases: ["earth", "earths", "Earth", "Earths"],
  109. });
  110. math.createUnit("lightsecond", {
  111. definition: "299792458 meters",
  112. prefixes: "long",
  113. });
  114. math.createUnit("lightseconds", {
  115. definition: "299792458 meters",
  116. prefixes: "long",
  117. });
  118. math.createUnit("parsec", {
  119. definition: "3.086e16 meters",
  120. prefixes: "long",
  121. });
  122. math.createUnit("parsecs", {
  123. definition: "3.086e16 meters",
  124. prefixes: "long",
  125. });
  126. math.createUnit("lightyears", {
  127. definition: "9.461e15 meters",
  128. prefixes: "long",
  129. });
  130. math.createUnit("AU", {
  131. definition: "149597870700 meters",
  132. });
  133. math.createUnit("AUs", {
  134. definition: "149597870700 meters",
  135. });
  136. math.createUnit("dalton", {
  137. definition: "1.66e-27 kg",
  138. prefixes: "long",
  139. });
  140. math.createUnit("daltons", {
  141. definition: "1.66e-27 kg",
  142. prefixes: "long",
  143. });
  144. math.createUnit("solarradii", {
  145. definition: "695990 km",
  146. prefixes: "long",
  147. });
  148. math.createUnit("solarmasses", {
  149. definition: "2e30 kg",
  150. prefixes: "long",
  151. });
  152. math.createUnit("galaxy", {
  153. definition: "105700 lightyears",
  154. prefixes: "long",
  155. });
  156. math.createUnit("galaxies", {
  157. definition: "105700 lightyears",
  158. prefixes: "long",
  159. });
  160. math.createUnit("universe", {
  161. definition: "93.016e9 lightyears",
  162. prefixes: "long",
  163. });
  164. math.createUnit("universes", {
  165. definition: "93.016e9 lightyears",
  166. prefixes: "long",
  167. });
  168. math.createUnit("multiverse", {
  169. definition: "1e30 lightyears",
  170. prefixes: "long",
  171. });
  172. math.createUnit("multiverses", {
  173. definition: "1e30 lightyears",
  174. prefixes: "long",
  175. });
  176. math.createUnit("pinHeads", {
  177. definition: "3.14159 mm^2",
  178. prefixes: "long",
  179. });
  180. math.createUnit("dinnerPlates", {
  181. definition: "95 inches^2",
  182. prefixes: "long",
  183. });
  184. math.createUnit("suburbanHouses", {
  185. definition: "2000 feet^2",
  186. prefixes: "long",
  187. });
  188. math.createUnit("footballFields", {
  189. definition: "57600 feet^2",
  190. prefixes: "long",
  191. });
  192. math.createUnit("blocks", {
  193. definition: "20000 m^2",
  194. prefixes: "long",
  195. aliases: ["block", "blocks"],
  196. });
  197. math.createUnit("peopleInRural", {
  198. definition: "0.02 miles^2",
  199. });
  200. math.createUnit("peopleInManhattan", {
  201. definition: "15 m^2",
  202. });
  203. math.createUnit("peopleInLooseCrowd", {
  204. definition: "1 m^2",
  205. });
  206. math.createUnit("peopleInCrowd", {
  207. definition: "0.3333333333333333 m^2",
  208. });
  209. math.createUnit("peopleInDenseCrowd", {
  210. definition: "0.2 m^2",
  211. });
  212. math.createUnit("people", {
  213. definition: "75 liters",
  214. prefixes: "long",
  215. });
  216. math.createUnit("shippingContainers", {
  217. definition: "1169 ft^3",
  218. prefixes: "long",
  219. });
  220. math.createUnit("olympicPools", {
  221. definition: "2500 m^3",
  222. prefixes: "long",
  223. });
  224. math.createUnit("oceans", {
  225. definition: "700000000 km^3",
  226. prefixes: "long",
  227. });
  228. math.createUnit("earthVolumes", {
  229. definition: "1.0867813e12 km^3",
  230. prefixes: "long",
  231. });
  232. math.createUnit("universeVolumes", {
  233. definition: "4.2137775e+32 lightyears^3",
  234. prefixes: "long",
  235. });
  236. math.createUnit("multiverseVolumes", {
  237. definition: "5.2359878e+89 lightyears^3",
  238. prefixes: "long",
  239. });
  240. math.createUnit("peopleMass", {
  241. definition: "80 kg",
  242. prefixes: "long",
  243. });
  244. math.createUnit("cars", {
  245. definition: "1250kg",
  246. prefixes: "long",
  247. });
  248. math.createUnit("busMasses", {
  249. definition: "15000kg",
  250. prefixes: "long",
  251. });
  252. math.createUnit("earthMass", {
  253. definition: "5.97e24 kg",
  254. prefixes: "long",
  255. });
  256. math.createUnit("kcal", {
  257. definition: "4184 joules",
  258. prefixes: "long",
  259. });
  260. math.createUnit("foodPounds", {
  261. definition: "867 kcal",
  262. prefixes: "long",
  263. });
  264. math.createUnit("foodKilograms", {
  265. definition: "1909 kcal",
  266. prefixes: "long",
  267. });
  268. math.createUnit("chickenNuggets", {
  269. definition: "42 kcal",
  270. prefixes: "long",
  271. });
  272. math.createUnit("peopleEaten", {
  273. definition: "125000 kcal",
  274. prefixes: "long",
  275. });
  276. math.createUnit("villagesEaten", {
  277. definition: "1000 peopleEaten",
  278. prefixes: "long",
  279. });
  280. math.createUnit("townsEaten", {
  281. definition: "10000 peopleEaten",
  282. prefixes: "long",
  283. });
  284. math.createUnit("citiesEaten", {
  285. definition: "100000 peopleEaten",
  286. prefixes: "long",
  287. });
  288. math.createUnit("metrosEaten", {
  289. definition: "1000000 peopleEaten",
  290. prefixes: "long",
  291. });
  292. math.createUnit("barn", {
  293. definition: "10e-28 m^2",
  294. prefixes: "long",
  295. });
  296. math.createUnit("barns", {
  297. definition: "10e-28 m^2",
  298. prefixes: "long",
  299. });
  300. math.createUnit("points", {
  301. definition: "0.013888888888888888888888888 inches",
  302. prefixes: "long",
  303. });
  304. math.createUnit("beardSeconds", {
  305. definition: "10 nanometers",
  306. prefixes: "long",
  307. });
  308. math.createUnit("smoots", {
  309. definition: "5.5833333 feet",
  310. prefixes: "long",
  311. });
  312. math.createUnit("furlongs", {
  313. definition: "660 feet",
  314. prefixes: "long",
  315. });
  316. math.createUnit("nanoacres", {
  317. definition: "1e-9 acres",
  318. prefixes: "long",
  319. });
  320. math.createUnit("barnMegaparsecs", {
  321. definition: "1 barn megaparsec",
  322. prefixes: "long",
  323. });
  324. math.createUnit("firkins", {
  325. definition: "90 lb",
  326. prefixes: "long",
  327. });
  328. math.createUnit("donkeySeconds", {
  329. definition: "250 joules",
  330. prefixes: "long",
  331. });
  332. math.createUnit("HU", {
  333. definition: "0.75 inches",
  334. aliases: ["HUs", "hammerUnits"],
  335. });
  336. const defaultUnits = {
  337. length: {
  338. metric: "meters",
  339. customary: "feet",
  340. relative: "stories",
  341. quirky: "smoots",
  342. human: "humans",
  343. },
  344. area: {
  345. metric: "meters^2",
  346. customary: "feet^2",
  347. relative: "footballFields",
  348. quirky: "nanoacres",
  349. human: "peopleInCrowd",
  350. },
  351. volume: {
  352. metric: "liters",
  353. customary: "gallons",
  354. relative: "olympicPools",
  355. volume: "barnMegaparsecs",
  356. human: "people",
  357. },
  358. mass: {
  359. metric: "kilograms",
  360. customary: "lbs",
  361. relative: "peopleMass",
  362. quirky: "firkins",
  363. human: "peopleMass",
  364. },
  365. energy: {
  366. metric: "kJ",
  367. customary: "kcal",
  368. relative: "chickenNuggets",
  369. quirky: "donkeySeconds",
  370. human: "peopleEaten",
  371. },
  372. };
  373. const unitChoices = {
  374. length: {
  375. metric: [
  376. "angstroms",
  377. "millimeters",
  378. "centimeters",
  379. "meters",
  380. "kilometers",
  381. ],
  382. customary: ["inches", "feet", "yards", "miles", "nauticalMiles"],
  383. relative: [
  384. "ShoeSizeEU",
  385. "ShoeSizeUK",
  386. "ShoeSizeMensUS",
  387. "ShoeSizeWomensUS",
  388. "stories",
  389. "buses",
  390. "marathons",
  391. "timezones",
  392. "earths",
  393. "lightseconds",
  394. "solarradii",
  395. "AUs",
  396. "lightyears",
  397. "parsecs",
  398. "galaxies",
  399. "universes",
  400. "multiverses",
  401. ],
  402. quirky: [
  403. "beardSeconds",
  404. "points",
  405. "smoots",
  406. "furlongs",
  407. "HUs",
  408. "U",
  409. "fathoms",
  410. ],
  411. human: ["humans"],
  412. },
  413. area: {
  414. metric: ["cm^2", "meters^2", "kilometers^2"],
  415. customary: ["inches^2", "feet^2", "acres", "miles^2"],
  416. relative: [
  417. "pinHeads",
  418. "dinnerPlates",
  419. "suburbanHouses",
  420. "footballFields",
  421. "blocks",
  422. ],
  423. quirky: ["barns", "nanoacres"],
  424. human: [
  425. "peopleInRural",
  426. "peopleInManhattan",
  427. "peopleInLooseCrowd",
  428. "peopleInCrowd",
  429. "peopleInDenseCrowd",
  430. ],
  431. },
  432. volume: {
  433. metric: ["milliliters", "liters", "m^3"],
  434. customary: ["in^3", "floz", "cups", "pints", "quarts", "gallons"],
  435. relative: [
  436. "shippingContainers",
  437. "olympicPools",
  438. "oceans",
  439. "earthVolumes",
  440. "universeVolumes",
  441. "multiverseVolumes",
  442. ],
  443. quirky: ["barnMegaparsecs"],
  444. human: ["people"],
  445. },
  446. mass: {
  447. metric: ["kilograms", "milligrams", "grams", "tonnes"],
  448. customary: ["lbs", "ounces", "tons"],
  449. relative: ["cars", "busMasses", "earthMass", "solarmasses"],
  450. quirky: ["firkins"],
  451. human: ["peopleMass"],
  452. },
  453. energy: {
  454. metric: ["kJ", "foodKilograms"],
  455. customary: ["kcal", "foodPounds"],
  456. relative: ["chickenNuggets"],
  457. quirky: ["donkeySeconds"],
  458. human: [
  459. "peopleEaten",
  460. "villagesEaten",
  461. "townsEaten",
  462. "citiesEaten",
  463. "metrosEaten",
  464. ],
  465. },
  466. };
  467. const config = {
  468. height: math.unit(1500, "meters"),
  469. x: 0,
  470. y: 0,
  471. minLineSize: 100,
  472. maxLineSize: 150,
  473. autoFit: false,
  474. drawYAxis: true,
  475. drawXAxis: false,
  476. autoMass: "off",
  477. autoFoodIntake: false,
  478. autoPreyCapacity: "off",
  479. };
  480. const availableEntities = {};
  481. const availableEntitiesByName = {};
  482. const entities = {};
  483. function constrainRel(coords) {
  484. const worldWidth =
  485. (config.height.toNumber("meters") / canvasHeight) * canvasWidth;
  486. const worldHeight = config.height.toNumber("meters");
  487. if (altHeld) {
  488. return coords;
  489. }
  490. return {
  491. x: Math.min(
  492. Math.max(coords.x, -worldWidth / 2 + config.x),
  493. worldWidth / 2 + config.x
  494. ),
  495. y: Math.min(Math.max(coords.y, config.y), worldHeight + config.y),
  496. };
  497. }
  498. // not using constrainRel anymore
  499. function snapPos(coords) {
  500. return {
  501. x: coords.x,
  502. y:
  503. !config.groundSnap || altHeld
  504. ? coords.y
  505. : Math.abs(coords.y) < config.height.toNumber("meters") / 20
  506. ? 0
  507. : coords.y,
  508. };
  509. }
  510. function adjustAbs(coords, oldHeight, newHeight) {
  511. const ratio = math.divide(newHeight, oldHeight);
  512. const x = (coords.x - config.x) * ratio + config.x;
  513. const y = (coords.y - config.y) * ratio + config.y;
  514. return { x: x, y: y };
  515. }
  516. function pos2pix(coords) {
  517. const worldWidth =
  518. (config.height.toNumber("meters") / canvasHeight) * canvasWidth;
  519. const worldHeight = config.height.toNumber("meters");
  520. const x =
  521. ((coords.x - config.x) / worldWidth + 0.5) * (canvasWidth - 50) + 50;
  522. const y =
  523. (1 - (coords.y - config.y) / worldHeight) * (canvasHeight - 50) + 50;
  524. return { x: x, y: y };
  525. }
  526. function pix2pos(coords) {
  527. const worldWidth =
  528. (config.height.toNumber("meters") / canvasHeight) * canvasWidth;
  529. const worldHeight = config.height.toNumber("meters");
  530. const x =
  531. ((coords.x - 50) / (canvasWidth - 50) - 0.5) * worldWidth + config.x;
  532. const y =
  533. (1 - (coords.y - 50) / (canvasHeight - 50)) * worldHeight + config.y;
  534. return { x: x, y: y };
  535. }
  536. function updateEntityElement(entity, element) {
  537. const position = pos2pix({ x: element.dataset.x, y: element.dataset.y });
  538. const view = entity.view;
  539. const form = entity.form;
  540. element.style.left = position.x + "px";
  541. element.style.top = position.y + "px";
  542. element.style.setProperty("--xpos", position.x + "px");
  543. element.style.setProperty(
  544. "--entity-height",
  545. "'" +
  546. entity.views[view].height
  547. .to(config.height.units[0].unit.name)
  548. .format({ precision: 2 }) +
  549. "'"
  550. );
  551. const pixels =
  552. math.divide(entity.views[view].height, config.height) *
  553. (canvasHeight - 50);
  554. const extra = entity.views[view].image.extra;
  555. const bottom = entity.views[view].image.bottom;
  556. const bonus = (extra ? extra : 1) * (1 / (1 - (bottom ? bottom : 0)));
  557. let height = pixels * bonus;
  558. // working around a Firefox bug here
  559. if (height > 17895698) {
  560. height = 0;
  561. }
  562. element.style.setProperty("--height", height + "px");
  563. element.style.setProperty("--extra", height - pixels + "px");
  564. element.style.setProperty("--brightness", entity.brightness);
  565. if (entity.views[view].rename)
  566. element.querySelector(".entity-name").innerText =
  567. entity.name == "" ? "" : entity.views[view].name;
  568. else if (
  569. entity.forms !== undefined &&
  570. Object.keys(entity.forms).length > 0 &&
  571. entity.forms[form].rename
  572. )
  573. element.querySelector(".entity-name").innerText =
  574. entity.name == "" ? "" : entity.forms[form].name;
  575. else element.querySelector(".entity-name").innerText = entity.name;
  576. const bottomName = document.querySelector(
  577. "#bottom-name-" + element.dataset.key
  578. );
  579. bottomName.style.left = position.x + entityX + "px";
  580. bottomName.style.bottom = "0vh";
  581. bottomName.innerText = entity.name;
  582. const topName = document.querySelector("#top-name-" + element.dataset.key);
  583. topName.style.left = position.x + entityX + "px";
  584. topName.style.top = "20vh";
  585. topName.innerText = entity.name;
  586. if (
  587. entity.views[view].height.toNumber("meters") / 10 >
  588. config.height.toNumber("meters")
  589. ) {
  590. topName.classList.add("top-name-needed");
  591. } else {
  592. topName.classList.remove("top-name-needed");
  593. }
  594. updateInfo();
  595. }
  596. let ratioInfo;
  597. function updateInfo() {
  598. let text = "";
  599. if (config.showRatios) {
  600. if (
  601. selectedEntity !== null &&
  602. prevSelectedEntity !== null &&
  603. selectedEntity !== prevSelectedEntity
  604. ) {
  605. let first = selectedEntity.currentView.height;
  606. let second = prevSelectedEntity.currentView.height;
  607. if (first.toNumber("meters") < second.toNumber("meters")) {
  608. text +=
  609. selectedEntity.name +
  610. " is " +
  611. math.format(math.divide(second, first), { precision: 5 }) +
  612. " times smaller than " +
  613. prevSelectedEntity.name;
  614. } else {
  615. text +=
  616. selectedEntity.name +
  617. " is " +
  618. math.format(math.divide(first, second), { precision: 5 }) +
  619. " times taller than " +
  620. prevSelectedEntity.name;
  621. }
  622. text += "\n";
  623. let apparentHeight = math.multiply(
  624. math.divide(second, first),
  625. math.unit(6, "feet")
  626. );
  627. if (config.units === "metric") {
  628. apparentHeight = apparentHeight.to("meters");
  629. }
  630. text +=
  631. prevSelectedEntity.name +
  632. " looks " +
  633. math.format(apparentHeight, { precision: 3 }) +
  634. " tall to " +
  635. selectedEntity.name +
  636. "\n";
  637. if (
  638. selectedEntity.currentView.weight &&
  639. prevSelectedEntity.currentView.weight
  640. ) {
  641. const ratio = math.divide(
  642. selectedEntity.currentView.weight,
  643. prevSelectedEntity.currentView.weight
  644. );
  645. if (ratio > 1) {
  646. text +=
  647. selectedEntity.name +
  648. " is " +
  649. math.format(ratio, { precision: 2 }) +
  650. " times heavier than " +
  651. prevSelectedEntity.name +
  652. "\n";
  653. } else {
  654. text +=
  655. selectedEntity.name +
  656. " is " +
  657. math.format(1 / ratio, { precision: 2 }) +
  658. " times lighter than " +
  659. prevSelectedEntity.name +
  660. "\n";
  661. }
  662. }
  663. const capacity =
  664. selectedEntity.currentView.preyCapacity ??
  665. selectedEntity.currentView.capacity ??
  666. selectedEntity.currentView.volume;
  667. if (capacity && prevSelectedEntity.currentView.weight) {
  668. const containCount = math.divide(
  669. capacity,
  670. math.divide(
  671. prevSelectedEntity.currentView.weight,
  672. math.unit("80kg/people")
  673. )
  674. );
  675. if (containCount > 0.1) {
  676. text +=
  677. selectedEntity.name +
  678. " can fit " +
  679. math.format(containCount, { precision: 1 }) +
  680. " of " +
  681. prevSelectedEntity.name +
  682. " inside them" +
  683. "\n";
  684. }
  685. }
  686. if (
  687. selectedEntity.currentView.energyIntake &&
  688. prevSelectedEntity.currentView.energyValue
  689. ) {
  690. const consumeCount = math.divide(
  691. selectedEntity.currentView.energyIntake,
  692. prevSelectedEntity.currentView.energyValue
  693. );
  694. if (consumeCount > 0.1) {
  695. text +=
  696. selectedEntity.name +
  697. " needs to eat " +
  698. math.format(consumeCount, { precision: 1 }) +
  699. " of " +
  700. prevSelectedEntity.name +
  701. " per day" +
  702. "\n";
  703. }
  704. }
  705. // todo needs a nice system for formatting this
  706. Object.entries(selectedEntity.currentView.attributes).forEach(
  707. ([key, attr]) => {
  708. if (key !== "height") {
  709. if (attr.type === "length") {
  710. const ratio = math.divide(
  711. selectedEntity.currentView[key],
  712. prevSelectedEntity.currentView.height
  713. );
  714. if (ratio > 1) {
  715. text +=
  716. selectedEntity.name +
  717. "'s " +
  718. attr.name +
  719. " is " +
  720. math.format(ratio, { precision: 2 }) +
  721. " times longer than " +
  722. prevSelectedEntity.name +
  723. " is tall\n";
  724. } else {
  725. text +=
  726. selectedEntity.name +
  727. "'s " +
  728. attr.name +
  729. " is " +
  730. math.format(1 / ratio, { precision: 2 }) +
  731. " times shorter than " +
  732. prevSelectedEntity.name +
  733. " is tall\n";
  734. }
  735. }
  736. }
  737. }
  738. );
  739. }
  740. }
  741. if (config.showHorizon) {
  742. if (selectedEntity !== null) {
  743. const y = document.querySelector("#entity-" + selectedEntity.index)
  744. .dataset.y;
  745. const R = math.unit(1.2756e7, "meters");
  746. const h = math.add(
  747. selectedEntity.currentView.height,
  748. math.unit(y, "meters")
  749. );
  750. const first = math.multiply(2, math.multiply(R, h));
  751. const second = math.multiply(h, h);
  752. const sightline = math
  753. .sqrt(math.add(first, second))
  754. .to(config.height.units[0].unit.name);
  755. sightline.fixPrefix = false;
  756. text +=
  757. selectedEntity.name +
  758. " could see for " +
  759. math.format(sightline, { precision: 3 }) +
  760. "\n";
  761. }
  762. }
  763. if (config.showRatios && config.showHorizon) {
  764. if (
  765. selectedEntity !== null &&
  766. prevSelectedEntity !== null &&
  767. selectedEntity !== prevSelectedEntity
  768. ) {
  769. const y1 = document.querySelector("#entity-" + selectedEntity.index)
  770. .dataset.y;
  771. const y2 = document.querySelector(
  772. "#entity-" + prevSelectedEntity.index
  773. ).dataset.y;
  774. const R = math.unit(1.2756e7, "meters");
  775. const R2 = math.subtract(
  776. math.subtract(R, prevSelectedEntity.currentView.height),
  777. math.unit(y2, "meters")
  778. );
  779. const h = math.add(
  780. selectedEntity.currentView.height,
  781. math.unit(y1, "meters")
  782. );
  783. const first = math.pow(math.add(R, h), 2);
  784. const second = math.pow(R2, 2);
  785. const sightline = math
  786. .sqrt(math.subtract(first, second))
  787. .to(config.height.units[0].unit.name);
  788. sightline.fixPrefix = false;
  789. text +=
  790. selectedEntity.name +
  791. " could see " +
  792. prevSelectedEntity.name +
  793. " from " +
  794. math.format(sightline, { precision: 3 }) +
  795. " away\n";
  796. }
  797. }
  798. ratioInfo.innerText = text;
  799. }
  800. function pickUnit() {
  801. if (!config.autoUnits) {
  802. return;
  803. }
  804. let type = null;
  805. let category = null;
  806. const heightSelect = document.querySelector("#options-height-unit");
  807. currentUnit = heightSelect.value;
  808. Object.keys(unitChoices).forEach((unitType) => {
  809. Object.keys(unitChoices[unitType]).forEach((unitCategory) => {
  810. if (unitChoices[unitType][unitCategory].includes(currentUnit)) {
  811. type = unitType;
  812. category = unitCategory;
  813. }
  814. });
  815. });
  816. // This should only happen if the unit selector isn't set up yet.
  817. // It doesn't really matter what goes into it.
  818. if (type === null || category === null) {
  819. return "meters";
  820. }
  821. const choices = unitChoices[type][category].map((unit) => {
  822. let value = config.height.toNumber(unit);
  823. if (value < 1) {
  824. value = 1 / value / value;
  825. }
  826. return [unit, value];
  827. });
  828. heightSelect.value = choices.sort((a, b) => {
  829. return a[1] - b[1];
  830. })[0][0];
  831. selectNewUnit();
  832. }
  833. function updateSizes(dirtyOnly = false) {
  834. updateInfo();
  835. if (config.lockYAxis) {
  836. config.y = -getVerticalOffset();
  837. }
  838. drawScales(dirtyOnly);
  839. let ordered = Object.entries(entities);
  840. ordered.sort((e1, e2) => {
  841. if (e1[1].priority != e2[1].priority) {
  842. return e2[1].priority - e1[1].priority;
  843. } else {
  844. return (
  845. e1[1].views[e1[1].view].height.value -
  846. e2[1].views[e2[1].view].height.value
  847. );
  848. }
  849. });
  850. let zIndex = ordered.length;
  851. ordered.forEach((entity) => {
  852. const element = document.querySelector("#entity-" + entity[0]);
  853. element.style.zIndex = zIndex;
  854. if (!dirtyOnly || entity[1].dirty) {
  855. updateEntityElement(entity[1], element, zIndex);
  856. entity[1].dirty = false;
  857. }
  858. zIndex -= 1;
  859. });
  860. document.querySelector("#ground").style.top =
  861. pos2pix({ x: 0, y: 0 }).y + "px";
  862. drawRulers();
  863. }
  864. function drawRulers() {
  865. const canvas = document.querySelector("#rulers");
  866. /** @type {CanvasRenderingContext2D} */
  867. const ctx = canvas.getContext("2d");
  868. const deviceScale = window.devicePixelRatio;
  869. ctx.canvas.width = Math.floor(canvas.clientWidth * deviceScale);
  870. ctx.canvas.height = Math.floor(canvas.clientHeight * deviceScale);
  871. ctx.scale(deviceScale, deviceScale);
  872. rulers.concat(currentRuler ? [currentRuler] : []).forEach((rulerDef) => {
  873. let x0 = rulerDef.x0;
  874. let y0 = rulerDef.y0;
  875. let x1 = rulerDef.x1;
  876. let y1 = rulerDef.y1;
  877. if (rulerDef.entityKey !== null) {
  878. const entity = entities[rulerDef.entityKey];
  879. const entityElement = document.querySelector(
  880. "#entity-" + rulerDef.entityKey
  881. );
  882. x0 *= entity.scale;
  883. y0 *= entity.scale;
  884. x1 *= entity.scale;
  885. y1 *= entity.scale;
  886. x0 += parseFloat(entityElement.dataset.x);
  887. x1 += parseFloat(entityElement.dataset.x);
  888. y0 += parseFloat(entityElement.dataset.y);
  889. y1 += parseFloat(entityElement.dataset.y);
  890. }
  891. ctx.save();
  892. ctx.beginPath();
  893. const start = pos2pix({ x: x0, y: y0 });
  894. const end = pos2pix({ x: x1, y: y1 });
  895. ctx.moveTo(start.x, start.y);
  896. ctx.lineTo(end.x, end.y);
  897. ctx.lineWidth = 5;
  898. ctx.strokeStyle = "#f8f";
  899. ctx.stroke();
  900. const center = { x: (start.x + end.x) / 2, y: (start.y + end.y) / 2 };
  901. ctx.fillStyle = "#eeeeee";
  902. ctx.font = "normal 24pt coda";
  903. ctx.translate(center.x, center.y);
  904. let angle = Math.atan2(end.y - start.y, end.x - start.x);
  905. if (angle < -Math.PI / 2) {
  906. angle += Math.PI;
  907. }
  908. if (angle > Math.PI / 2) {
  909. angle -= Math.PI;
  910. }
  911. ctx.rotate(angle);
  912. const offsetX = Math.cos(angle + Math.PI / 2);
  913. const offsetY = Math.sin(angle + Math.PI / 2);
  914. const distance = Math.sqrt(Math.pow(y1 - y0, 2) + Math.pow(x1 - x0, 2));
  915. const distanceInUnits = math
  916. .unit(distance, "meters")
  917. .to(document.querySelector("#options-height-unit").value);
  918. const textSize = ctx.measureText(
  919. distanceInUnits.format({ precision: 3 })
  920. );
  921. ctx.fillText(
  922. distanceInUnits.format({ precision: 3 }),
  923. -offsetX * 10 - textSize.width / 2,
  924. -offsetY * 10
  925. );
  926. ctx.restore();
  927. });
  928. }
  929. function drawScales(ifDirty = false) {
  930. const canvas = document.querySelector("#display");
  931. /** @type {CanvasRenderingContext2D} */
  932. const ctx = canvas.getContext("2d");
  933. const deviceScale = window.devicePixelRatio;
  934. ctx.canvas.width = Math.floor(canvas.clientWidth * deviceScale);
  935. ctx.canvas.height = Math.floor(canvas.clientHeight * deviceScale);
  936. ctx.scale(deviceScale, deviceScale);
  937. ctx.beginPath();
  938. ctx.rect(
  939. 0,
  940. 0,
  941. ctx.canvas.width / deviceScale,
  942. ctx.canvas.height / deviceScale
  943. );
  944. switch (config.background) {
  945. case "black":
  946. ctx.fillStyle = "#000";
  947. break;
  948. case "dark":
  949. ctx.fillStyle = "#111";
  950. break;
  951. case "medium":
  952. ctx.fillStyle = "#333";
  953. break;
  954. case "light":
  955. ctx.fillStyle = "#555";
  956. break;
  957. }
  958. ctx.fill();
  959. if (config.drawYAxis || config.drawAltitudes !== "none") {
  960. drawVerticalScale(ifDirty);
  961. }
  962. if (config.drawXAxis) {
  963. drawHorizontalScale(ifDirty);
  964. }
  965. }
  966. function drawVerticalScale(ifDirty = false) {
  967. if (ifDirty && !worldSizeDirty) return;
  968. function drawTicks(
  969. /** @type {CanvasRenderingContext2D} */ ctx,
  970. pixelsPer,
  971. heightPer
  972. ) {
  973. let total = heightPer.clone();
  974. total.value = config.y;
  975. let y = ctx.canvas.clientHeight - 50;
  976. let offset = total.toNumber("meters") % heightPer.toNumber("meters");
  977. y += (offset / heightPer.toNumber("meters")) * pixelsPer;
  978. total = math.subtract(total, math.unit(offset, "meters"));
  979. for (; y >= 50; y -= pixelsPer) {
  980. drawTick(ctx, 50, y, total.format({ precision: 3 }));
  981. total = math.add(total, heightPer);
  982. }
  983. }
  984. function drawTick(
  985. /** @type {CanvasRenderingContext2D} */ ctx,
  986. x,
  987. y,
  988. label,
  989. flipped = false
  990. ) {
  991. const oldStroke = ctx.strokeStyle;
  992. const oldFill = ctx.fillStyle;
  993. x = Math.round(x);
  994. y = Math.round(y);
  995. ctx.beginPath();
  996. ctx.moveTo(x, y);
  997. ctx.lineTo(x + 20, y);
  998. ctx.strokeStyle = "#000000";
  999. ctx.stroke();
  1000. ctx.beginPath();
  1001. ctx.moveTo(x + 20, y);
  1002. ctx.lineTo(ctx.canvas.clientWidth - 70, y);
  1003. if (flipped) {
  1004. ctx.strokeStyle = "#666666";
  1005. } else {
  1006. ctx.strokeStyle = "#aaaaaa";
  1007. }
  1008. ctx.stroke();
  1009. ctx.beginPath();
  1010. ctx.moveTo(ctx.canvas.clientWidth - 70, y);
  1011. ctx.lineTo(ctx.canvas.clientWidth - 50, y);
  1012. ctx.strokeStyle = "#000000";
  1013. ctx.stroke();
  1014. const oldFont = ctx.font;
  1015. ctx.font = "normal 24pt coda";
  1016. ctx.fillStyle = "#dddddd";
  1017. ctx.beginPath();
  1018. if (flipped) {
  1019. ctx.textAlign = "end";
  1020. ctx.fillText(label, ctx.canvas.clientWidth - 70, y + 35);
  1021. } else {
  1022. ctx.fillText(label, x + 20, y + 35);
  1023. }
  1024. ctx.textAlign = "start";
  1025. ctx.font = oldFont;
  1026. ctx.strokeStyle = oldStroke;
  1027. ctx.fillStyle = oldFill;
  1028. }
  1029. function drawAltitudeLine(ctx, height, label) {
  1030. const pixelScale =
  1031. (ctx.canvas.clientHeight - 100) / config.height.toNumber("meters");
  1032. const y =
  1033. ctx.canvas.clientHeight -
  1034. 50 -
  1035. (height.toNumber("meters") - config.y) * pixelScale;
  1036. const offsetY = y + getVerticalOffset() * pixelScale;
  1037. if (offsetY < ctx.canvas.clientHeight - 100) {
  1038. drawTick(ctx, 50, y, label, true);
  1039. }
  1040. }
  1041. const canvas = document.querySelector("#display");
  1042. /** @type {CanvasRenderingContext2D} */
  1043. const ctx = canvas.getContext("2d");
  1044. const pixelScale =
  1045. (ctx.canvas.clientHeight - 100) / config.height.toNumber();
  1046. let pixelsPer = pixelScale;
  1047. heightPer = 1;
  1048. if (pixelsPer < config.minLineSize) {
  1049. const factor = math.ceil(config.minLineSize / pixelsPer);
  1050. heightPer *= factor;
  1051. pixelsPer *= factor;
  1052. }
  1053. if (pixelsPer > config.maxLineSize) {
  1054. const factor = math.ceil(pixelsPer / config.maxLineSize);
  1055. heightPer /= factor;
  1056. pixelsPer /= factor;
  1057. }
  1058. if (heightPer == 0) {
  1059. console.error(
  1060. "The world size is invalid! Refusing to draw the scale..."
  1061. );
  1062. return;
  1063. }
  1064. heightPer = math.unit(
  1065. heightPer,
  1066. document.querySelector("#options-height-unit").value
  1067. );
  1068. ctx.beginPath();
  1069. ctx.moveTo(50, 50);
  1070. ctx.lineTo(50, ctx.canvas.clientHeight - 50);
  1071. ctx.stroke();
  1072. ctx.beginPath();
  1073. ctx.moveTo(ctx.canvas.clientWidth - 50, 50);
  1074. ctx.lineTo(ctx.canvas.clientWidth - 50, ctx.canvas.clientHeight - 50);
  1075. ctx.stroke();
  1076. if (config.drawYAxis) {
  1077. drawTicks(ctx, pixelsPer, heightPer);
  1078. }
  1079. if (config.drawAltitudes == "atmosphere" || config.drawAltitudes == "all") {
  1080. drawAltitudeLine(ctx, math.unit(8, "km"), "Troposphere");
  1081. drawAltitudeLine(ctx, math.unit(17.5, "km"), "Ozone Layer");
  1082. drawAltitudeLine(ctx, math.unit(50, "km"), "Stratosphere");
  1083. drawAltitudeLine(ctx, math.unit(85, "km"), "Mesosphere");
  1084. drawAltitudeLine(ctx, math.unit(675, "km"), "Thermosphere");
  1085. drawAltitudeLine(ctx, math.unit(10000, "km"), "Exosphere");
  1086. }
  1087. if (config.drawAltitudes == "orbits" || config.drawAltitudes == "all") {
  1088. drawAltitudeLine(ctx, math.unit(7, "miles"), "Cruising Altitude");
  1089. drawAltitudeLine(
  1090. ctx,
  1091. math.unit(100, "km"),
  1092. "Edge of Space (Kármán line)"
  1093. );
  1094. drawAltitudeLine(ctx, math.unit(211.3, "miles"), "Space Station");
  1095. drawAltitudeLine(ctx, math.unit(369.7, "miles"), "Hubble Telescope");
  1096. drawAltitudeLine(ctx, math.unit(1500, "km"), "Low Earth Orbit");
  1097. drawAltitudeLine(ctx, math.unit(20350, "km"), "GPS Satellites");
  1098. drawAltitudeLine(ctx, math.unit(35786, "km"), "Geosynchronous Orbit");
  1099. drawAltitudeLine(ctx, math.unit(238900, "miles"), "Lunar Orbit");
  1100. drawAltitudeLine(ctx, math.unit(57.9e6, "km"), "Orbit of Mercury");
  1101. drawAltitudeLine(ctx, math.unit(108.2e6, "km"), "Orbit of Venus");
  1102. drawAltitudeLine(ctx, math.unit(1, "AU"), "Orbit of Earth");
  1103. drawAltitudeLine(ctx, math.unit(227.9e6, "km"), "Orbit of Mars");
  1104. drawAltitudeLine(ctx, math.unit(778.6e6, "km"), "Orbit of Jupiter");
  1105. drawAltitudeLine(ctx, math.unit(1433.5e6, "km"), "Orbit of Saturn");
  1106. drawAltitudeLine(ctx, math.unit(2872.5e6, "km"), "Orbit of Uranus");
  1107. drawAltitudeLine(ctx, math.unit(4495.1e6, "km"), "Orbit of Neptune");
  1108. drawAltitudeLine(ctx, math.unit(5906.4e6, "km"), "Orbit of Pluto");
  1109. drawAltitudeLine(ctx, math.unit(2.7, "AU"), "Asteroid Belt");
  1110. drawAltitudeLine(ctx, math.unit(123, "AU"), "Heliopause");
  1111. drawAltitudeLine(ctx, math.unit(26e3, "lightyears"), "Orbit of Sol");
  1112. }
  1113. if (config.drawAltitudes == "weather" || config.drawAltitudes == "all") {
  1114. drawAltitudeLine(ctx, math.unit(1000, "meters"), "Low-level Clouds");
  1115. drawAltitudeLine(ctx, math.unit(3000, "meters"), "Mid-level Clouds");
  1116. drawAltitudeLine(ctx, math.unit(10000, "meters"), "High-level Clouds");
  1117. drawAltitudeLine(
  1118. ctx,
  1119. math.unit(20, "km"),
  1120. "Polar Stratospheric Clouds"
  1121. );
  1122. drawAltitudeLine(ctx, math.unit(80, "km"), "Noctilucent Clouds");
  1123. drawAltitudeLine(ctx, math.unit(100, "km"), "Aurora");
  1124. }
  1125. if (config.drawAltitudes == "water" || config.drawAltitudes == "all") {
  1126. drawAltitudeLine(ctx, math.unit(12100, "feet"), "Average Ocean Depth");
  1127. drawAltitudeLine(ctx, math.unit(8376, "meters"), "Milkwaukee Deep");
  1128. drawAltitudeLine(ctx, math.unit(10984, "meters"), "Challenger Deep");
  1129. drawAltitudeLine(ctx, math.unit(5550, "meters"), "Molloy Deep");
  1130. drawAltitudeLine(ctx, math.unit(7290, "meters"), "Sunda Deep");
  1131. drawAltitudeLine(ctx, math.unit(592, "meters"), "Crater Lake");
  1132. drawAltitudeLine(ctx, math.unit(7.5, "meters"), "Littoral Zone");
  1133. drawAltitudeLine(ctx, math.unit(140, "meters"), "Continental Shelf");
  1134. }
  1135. if (config.drawAltitudes == "geology" || config.drawAltitudes == "all") {
  1136. drawAltitudeLine(ctx, math.unit(35, "km"), "Crust");
  1137. drawAltitudeLine(ctx, math.unit(670, "km"), "Upper Mantle");
  1138. drawAltitudeLine(ctx, math.unit(2890, "km"), "Lower Mantle");
  1139. drawAltitudeLine(ctx, math.unit(5150, "km"), "Outer Core");
  1140. drawAltitudeLine(ctx, math.unit(6370, "km"), "Inner Core");
  1141. }
  1142. if (
  1143. config.drawAltitudes == "thicknesses" ||
  1144. config.drawAltitudes == "all"
  1145. ) {
  1146. drawAltitudeLine(ctx, math.unit(0.335, "nm"), "Monolayer Graphene");
  1147. drawAltitudeLine(ctx, math.unit(3, "um"), "Spider Silk");
  1148. drawAltitudeLine(ctx, math.unit(0.07, "mm"), "Human Hair");
  1149. drawAltitudeLine(ctx, math.unit(0.1, "mm"), "Sheet of Paper");
  1150. drawAltitudeLine(ctx, math.unit(0.5, "mm"), "Yarn");
  1151. drawAltitudeLine(ctx, math.unit(0.0155, "inches"), "Thread");
  1152. drawAltitudeLine(ctx, math.unit(0.1, "um"), "Gold Leaf");
  1153. drawAltitudeLine(ctx, math.unit(35, "um"), "PCB Trace");
  1154. }
  1155. if (config.drawAltitudes == "airspaces" || config.drawAltitudes == "all") {
  1156. drawAltitudeLine(ctx, math.unit(18000, "feet"), "Class A");
  1157. drawAltitudeLine(ctx, math.unit(14500, "feet"), "Class E");
  1158. drawAltitudeLine(ctx, math.unit(10000, "feet"), "Class B");
  1159. drawAltitudeLine(ctx, math.unit(4000, "feet"), "Class C");
  1160. drawAltitudeLine(ctx, math.unit(2500, "feet"), "Class D");
  1161. }
  1162. if (config.drawAltitudes == "races" || config.drawAltitudes == "all") {
  1163. drawAltitudeLine(ctx, math.unit(100, "meters"), "100m Dash");
  1164. drawAltitudeLine(ctx, math.unit(26.2188 / 2, "miles"), "Half Marathon");
  1165. drawAltitudeLine(ctx, math.unit(26.2188, "miles"), "Marathon");
  1166. drawAltitudeLine(ctx, math.unit(161.734, "miles"), "Monaco Grand Prix");
  1167. drawAltitudeLine(ctx, math.unit(500, "miles"), "Daytona 500");
  1168. drawAltitudeLine(ctx, math.unit(2121.6, "miles"), "Tour de France");
  1169. }
  1170. if (
  1171. config.drawAltitudes == "olympic-records" ||
  1172. config.drawAltitudes == "all"
  1173. ) {
  1174. drawAltitudeLine(ctx, math.unit(2.39, "meters"), "High Jump");
  1175. drawAltitudeLine(ctx, math.unit(6.03, "meters"), "Pole Vault");
  1176. drawAltitudeLine(ctx, math.unit(8.9, "meters"), "Long Jump");
  1177. drawAltitudeLine(ctx, math.unit(18.09, "meters"), "Triple Jump");
  1178. drawAltitudeLine(ctx, math.unit(23.3, "meters"), "Shot Put");
  1179. drawAltitudeLine(ctx, math.unit(72.3, "meters"), "Discus Throw");
  1180. drawAltitudeLine(ctx, math.unit(84.8, "meters"), "Hammer Throw");
  1181. drawAltitudeLine(ctx, math.unit(90.57, "meters"), "Javelin Throw");
  1182. }
  1183. if (config.drawAltitudes == "d&d-sizes" || config.drawAltitudes == "all") {
  1184. drawAltitudeLine(ctx, math.unit(0.375, "feet"), "Fine");
  1185. drawAltitudeLine(ctx, math.unit(0.75, "feet"), "Dimnutive");
  1186. drawAltitudeLine(ctx, math.unit(1.5, "feet"), "Tiny");
  1187. drawAltitudeLine(ctx, math.unit(3, "feet"), "Small");
  1188. drawAltitudeLine(ctx, math.unit(6, "feet"), "Medium");
  1189. drawAltitudeLine(ctx, math.unit(12, "feet"), "Large");
  1190. drawAltitudeLine(ctx, math.unit(24, "feet"), "Huge");
  1191. drawAltitudeLine(ctx, math.unit(48, "feet"), "Gargantuan");
  1192. drawAltitudeLine(ctx, math.unit(96, "feet"), "Colossal");
  1193. }
  1194. }
  1195. // this is a lot of copypizza...
  1196. function drawHorizontalScale(ifDirty = false) {
  1197. if (ifDirty && !worldSizeDirty) return;
  1198. function drawTicks(
  1199. /** @type {CanvasRenderingContext2D} */ ctx,
  1200. pixelsPer,
  1201. heightPer
  1202. ) {
  1203. let total = heightPer.clone();
  1204. total.value = math.unit(-config.x, "meters").toNumber(config.unit);
  1205. // further adjust it to put the current position in the center
  1206. total.value -=
  1207. ((heightPer.toNumber("meters") / pixelsPer) * (canvasWidth + 50)) /
  1208. 2;
  1209. let x = ctx.canvas.clientWidth - 50;
  1210. let offset = total.toNumber("meters") % heightPer.toNumber("meters");
  1211. x += (offset / heightPer.toNumber("meters")) * pixelsPer;
  1212. total = math.subtract(total, math.unit(offset, "meters"));
  1213. for (; x >= 50 - pixelsPer; x -= pixelsPer) {
  1214. // negate it so that the left side is negative
  1215. drawTick(
  1216. ctx,
  1217. x,
  1218. 50,
  1219. math.multiply(-1, total).format({ precision: 3 })
  1220. );
  1221. total = math.add(total, heightPer);
  1222. }
  1223. }
  1224. function drawTick(
  1225. /** @type {CanvasRenderingContext2D} */ ctx,
  1226. x,
  1227. y,
  1228. label
  1229. ) {
  1230. ctx.save();
  1231. x = Math.round(x);
  1232. y = Math.round(y);
  1233. ctx.beginPath();
  1234. ctx.moveTo(x, y);
  1235. ctx.lineTo(x, y + 20);
  1236. ctx.strokeStyle = "#000000";
  1237. ctx.stroke();
  1238. ctx.beginPath();
  1239. ctx.moveTo(x, y + 20);
  1240. ctx.lineTo(x, ctx.canvas.clientHeight - 70);
  1241. ctx.strokeStyle = "#aaaaaa";
  1242. ctx.stroke();
  1243. ctx.beginPath();
  1244. ctx.moveTo(x, ctx.canvas.clientHeight - 70);
  1245. ctx.lineTo(x, ctx.canvas.clientHeight - 50);
  1246. ctx.strokeStyle = "#000000";
  1247. ctx.stroke();
  1248. const oldFont = ctx.font;
  1249. ctx.font = "normal 24pt coda";
  1250. ctx.fillStyle = "#dddddd";
  1251. ctx.beginPath();
  1252. ctx.fillText(label, x + 35, y + 20);
  1253. ctx.restore();
  1254. }
  1255. const canvas = document.querySelector("#display");
  1256. /** @type {CanvasRenderingContext2D} */
  1257. const ctx = canvas.getContext("2d");
  1258. let pixelsPer = (ctx.canvas.clientHeight - 100) / config.height.toNumber();
  1259. heightPer = 1;
  1260. if (pixelsPer < config.minLineSize * 2) {
  1261. const factor = math.ceil((config.minLineSize * 2) / pixelsPer);
  1262. heightPer *= factor;
  1263. pixelsPer *= factor;
  1264. }
  1265. if (pixelsPer > config.maxLineSize * 2) {
  1266. const factor = math.ceil(pixelsPer / 2 / config.maxLineSize);
  1267. heightPer /= factor;
  1268. pixelsPer /= factor;
  1269. }
  1270. if (heightPer == 0) {
  1271. console.error(
  1272. "The world size is invalid! Refusing to draw the scale..."
  1273. );
  1274. return;
  1275. }
  1276. heightPer = math.unit(
  1277. heightPer,
  1278. document.querySelector("#options-height-unit").value
  1279. );
  1280. ctx.beginPath();
  1281. ctx.moveTo(0, 50);
  1282. ctx.lineTo(ctx.canvas.clientWidth, 50);
  1283. ctx.stroke();
  1284. ctx.beginPath();
  1285. ctx.moveTo(0, ctx.canvas.clientHeight - 50);
  1286. ctx.lineTo(ctx.canvas.clientWidth, ctx.canvas.clientHeight - 50);
  1287. ctx.stroke();
  1288. drawTicks(ctx, pixelsPer, heightPer);
  1289. }
  1290. // Entities are generated as needed, and we make a copy
  1291. // every time - the resulting objects get mutated, after all.
  1292. // But we also want to be able to read some information without
  1293. // calling the constructor -- e.g. making a list of authors and
  1294. // owners. So, this function is used to generate that information.
  1295. // It is invoked like makeEntity so that it can be dropped in easily,
  1296. // but returns an object that lets you construct many copies of an entity,
  1297. // rather than creating a new entity.
  1298. function createEntityMaker(info, views, sizes, forms) {
  1299. const maker = {};
  1300. maker.name = info.name;
  1301. maker.info = info;
  1302. maker.sizes = sizes;
  1303. maker.constructor = () => makeEntity(info, views, sizes, forms);
  1304. maker.authors = [];
  1305. maker.owners = [];
  1306. maker.nsfw = false;
  1307. Object.values(views).forEach((view) => {
  1308. const authors = authorsOf(view.image.source);
  1309. if (authors) {
  1310. authors.forEach((author) => {
  1311. if (maker.authors.indexOf(author) == -1) {
  1312. maker.authors.push(author);
  1313. }
  1314. });
  1315. }
  1316. const owners = ownersOf(view.image.source);
  1317. if (owners) {
  1318. owners.forEach((owner) => {
  1319. if (maker.owners.indexOf(owner) == -1) {
  1320. maker.owners.push(owner);
  1321. }
  1322. });
  1323. }
  1324. if (isNsfw(view.image.source)) {
  1325. maker.nsfw = true;
  1326. }
  1327. });
  1328. return maker;
  1329. }
  1330. // This function serializes and parses its arguments to avoid sharing
  1331. // references to a common object. This allows for the objects to be
  1332. // safely mutated.
  1333. function makeEntity(info, views, sizes, forms = {}) {
  1334. const entityTemplate = {
  1335. name: info.name,
  1336. identifier: info.name,
  1337. scale: 1,
  1338. rotation: 0,
  1339. info: JSON.parse(JSON.stringify(info)),
  1340. views: JSON.parse(JSON.stringify(views), math.reviver),
  1341. sizes:
  1342. sizes === undefined
  1343. ? []
  1344. : JSON.parse(JSON.stringify(sizes), math.reviver),
  1345. forms: forms,
  1346. init: function () {
  1347. const entity = this;
  1348. Object.entries(this.forms).forEach(([formKey, form]) => {
  1349. if (form.default) {
  1350. this.defaultForm = formKey;
  1351. }
  1352. });
  1353. Object.entries(this.views).forEach(([viewKey, view]) => {
  1354. view.parent = this;
  1355. if (this.defaultView === undefined) {
  1356. this.defaultView = viewKey;
  1357. this.view = viewKey;
  1358. this.form = view.form;
  1359. }
  1360. if (view.default) {
  1361. if (forms === {} || this.defaultForm === view.form) {
  1362. this.defaultView = viewKey;
  1363. this.view = viewKey;
  1364. this.form = view.form;
  1365. }
  1366. }
  1367. // to remember the units the user last picked
  1368. view.units = {};
  1369. if (
  1370. config.autoMass !== "off" &&
  1371. view.attributes.weight === undefined
  1372. ) {
  1373. let base = undefined;
  1374. switch (config.autoMass) {
  1375. case "human":
  1376. baseMass = math.unit(150, "lbs");
  1377. baseHeight = math.unit(5.917, "feet");
  1378. break;
  1379. case "quadruped at shoulder":
  1380. baseMass = math.unit(80, "lbs");
  1381. baseHeight = math.unit(30, "inches");
  1382. break;
  1383. }
  1384. const ratio = math.divide(
  1385. view.attributes.height.base,
  1386. baseHeight
  1387. );
  1388. view.attributes.weight = {
  1389. name: "Mass",
  1390. power: 3,
  1391. type: "mass",
  1392. base: math.multiply(baseMass, Math.pow(ratio, 3)),
  1393. };
  1394. }
  1395. if (
  1396. config.autoFoodIntake &&
  1397. view.attributes.weight !== undefined &&
  1398. view.attributes.energyIntake === undefined
  1399. ) {
  1400. view.attributes.energyIntake = {
  1401. name: "Food Intake",
  1402. power: (3 * 3) / 4,
  1403. type: "energy",
  1404. base: math.unit(
  1405. 2000 *
  1406. Math.pow(
  1407. view.attributes.weight.base.toNumber(
  1408. "lbs"
  1409. ) / 150,
  1410. 3 / 4
  1411. ),
  1412. "kcal"
  1413. ),
  1414. };
  1415. }
  1416. if (
  1417. config.autoCaloricValue &&
  1418. view.attributes.weight !== undefined &&
  1419. view.attributes.energyWorth === undefined
  1420. ) {
  1421. view.attributes.energyValue = {
  1422. name: "Caloric Value",
  1423. power: 3,
  1424. type: "energy",
  1425. base: math.unit(
  1426. 860 * view.attributes.weight.base.toNumber("lbs"),
  1427. "kcal"
  1428. ),
  1429. };
  1430. }
  1431. if (
  1432. config.autoPreyCapacity !== "off" &&
  1433. view.attributes.weight !== undefined &&
  1434. view.attributes.preyCapacity === undefined
  1435. ) {
  1436. view.attributes.preyCapacity = {
  1437. name: "Prey Capacity",
  1438. power: 3,
  1439. type: "volume",
  1440. base: math.unit(
  1441. ((config.autoPreyCapacity == "same-size"
  1442. ? 1
  1443. : 0.05) *
  1444. view.attributes.weight.base.toNumber("lbs")) /
  1445. 150,
  1446. "people"
  1447. ),
  1448. };
  1449. }
  1450. Object.entries(view.attributes).forEach(([key, val]) => {
  1451. Object.defineProperty(view, key, {
  1452. get: function () {
  1453. return math.multiply(
  1454. Math.pow(
  1455. this.parent.scale,
  1456. this.attributes[key].power
  1457. ),
  1458. this.attributes[key].base
  1459. );
  1460. },
  1461. set: function (value) {
  1462. const newScale = Math.pow(
  1463. math.divide(value, this.attributes[key].base),
  1464. 1 / this.attributes[key].power
  1465. );
  1466. this.parent.scale = newScale;
  1467. },
  1468. });
  1469. });
  1470. });
  1471. this.sizes.forEach((size) => {
  1472. if (size.default === true) {
  1473. if (Object.keys(forms).length > 0) {
  1474. if (this.defaultForm !== size.form) {
  1475. return;
  1476. }
  1477. }
  1478. this.views[this.defaultView].height = size.height;
  1479. this.size = size;
  1480. }
  1481. });
  1482. if (this.size === undefined && this.sizes.length > 0) {
  1483. this.views[this.defaultView].height = this.sizes[0].height;
  1484. this.size = this.sizes[0];
  1485. console.warn("No default size set for " + info.name);
  1486. } else if (this.sizes.length == 0) {
  1487. this.sizes = [
  1488. {
  1489. name: "Normal",
  1490. height: this.views[this.defaultView].height,
  1491. },
  1492. ];
  1493. this.size = this.sizes[0];
  1494. }
  1495. this.desc = {};
  1496. Object.entries(this.info).forEach(([key, value]) => {
  1497. Object.defineProperty(this.desc, key, {
  1498. get: function () {
  1499. let text = value.text;
  1500. if (entity.views[entity.view].info) {
  1501. if (entity.views[entity.view].info[key]) {
  1502. text = combineInfo(
  1503. text,
  1504. entity.views[entity.view].info[key]
  1505. );
  1506. }
  1507. }
  1508. if (entity.size.info) {
  1509. if (entity.size.info[key]) {
  1510. text = combineInfo(text, entity.size.info[key]);
  1511. }
  1512. }
  1513. return { title: value.title, text: text };
  1514. },
  1515. });
  1516. });
  1517. Object.defineProperty(this, "currentView", {
  1518. get: function () {
  1519. return entity.views[entity.view];
  1520. },
  1521. });
  1522. this.formViews = {};
  1523. this.formSizes = {};
  1524. Object.entries(views).forEach(([key, value]) => {
  1525. if (value.default) {
  1526. this.formViews[value.form] = key;
  1527. }
  1528. });
  1529. Object.entries(views).forEach(([key, value]) => {
  1530. if (this.formViews[value.form] === undefined) {
  1531. this.formViews[value.form] = key;
  1532. }
  1533. });
  1534. this.sizes.forEach((size) => {
  1535. if (size.default) {
  1536. this.formSizes[size.form] = size;
  1537. }
  1538. });
  1539. this.sizes.forEach((size) => {
  1540. if (this.formSizes[size.form] === undefined) {
  1541. this.formSizes[size.form] = size;
  1542. }
  1543. });
  1544. Object.values(views).forEach((view) => {
  1545. if (this.formSizes[view.form] === undefined) {
  1546. this.formSizes[view.form] = {
  1547. name: "Normal",
  1548. height: view.attributes.height.base,
  1549. default: true,
  1550. form: view.form,
  1551. };
  1552. }
  1553. });
  1554. delete this.init;
  1555. return this;
  1556. },
  1557. }.init();
  1558. return entityTemplate;
  1559. }
  1560. function combineInfo(existing, next) {
  1561. switch (next.mode) {
  1562. case "replace":
  1563. return next.text;
  1564. case "prepend":
  1565. return next.text + existing;
  1566. case "append":
  1567. return existing + next.text;
  1568. }
  1569. return existing;
  1570. }
  1571. function clickDown(target, x, y) {
  1572. clicked = target;
  1573. movingInBounds = false;
  1574. const rect = target.getBoundingClientRect();
  1575. let entX = document.querySelector("#entities").getBoundingClientRect().x;
  1576. let entY = document.querySelector("#entities").getBoundingClientRect().y;
  1577. dragOffsetX = x - rect.left + entX;
  1578. dragOffsetY = y - rect.top + entY;
  1579. x = x - dragOffsetX;
  1580. y = y - dragOffsetY;
  1581. if (x >= 0 && x <= canvasWidth && y >= 0 && y <= canvasHeight) {
  1582. movingInBounds = true;
  1583. }
  1584. clickTimeout = setTimeout(() => {
  1585. dragging = true;
  1586. }, 200);
  1587. target.classList.add("no-transition");
  1588. }
  1589. // could we make this actually detect the menu area?
  1590. function hoveringInDeleteArea(e) {
  1591. return e.clientY < document.querySelector("#menubar").clientHeight;
  1592. }
  1593. function clickUp(e) {
  1594. if (e.which != 1) {
  1595. return;
  1596. }
  1597. clearTimeout(clickTimeout);
  1598. if (clicked) {
  1599. clicked.classList.remove("no-transition");
  1600. if (dragging) {
  1601. dragging = false;
  1602. if (hoveringInDeleteArea(e)) {
  1603. removeEntity(clicked);
  1604. document
  1605. .querySelector("#menubar")
  1606. .classList.remove("hover-delete");
  1607. }
  1608. } else {
  1609. select(clicked);
  1610. }
  1611. clicked = null;
  1612. }
  1613. }
  1614. function deselect(e) {
  1615. if (rulerMode) {
  1616. return;
  1617. }
  1618. if (e !== undefined && e.which != 1) {
  1619. return;
  1620. }
  1621. if (selected) {
  1622. selected.classList.remove("selected");
  1623. }
  1624. if (prevSelected) {
  1625. prevSelected.classList.remove("prevSelected");
  1626. }
  1627. document.getElementById("options-selected-entity-none").selected =
  1628. "selected";
  1629. document.getElementById("delete-entity").style.display = "none";
  1630. clearAttribution();
  1631. selected = null;
  1632. clearViewList();
  1633. clearEntityOptions();
  1634. clearViewOptions();
  1635. document.querySelector("#delete-entity").disabled = true;
  1636. document.querySelector("#grow").disabled = true;
  1637. document.querySelector("#shrink").disabled = true;
  1638. document.querySelector("#fit").disabled = true;
  1639. }
  1640. function select(target) {
  1641. if (prevSelected !== null) {
  1642. prevSelected.classList.remove("prevSelected");
  1643. }
  1644. prevSelected = selected;
  1645. prevSelectedEntity = selectedEntity;
  1646. deselect();
  1647. selected = target;
  1648. selectedEntity = entities[target.dataset.key];
  1649. updateInfo();
  1650. document.getElementById(
  1651. "options-selected-entity-" + target.dataset.key
  1652. ).selected = "selected";
  1653. document.getElementById("delete-entity").style.display = "";
  1654. if (
  1655. prevSelected !== null &&
  1656. config.showRatios &&
  1657. selected !== prevSelected
  1658. ) {
  1659. prevSelected.classList.add("prevSelected");
  1660. }
  1661. selected.classList.add("selected");
  1662. displayAttribution(selectedEntity.views[selectedEntity.view].image.source);
  1663. configFormList(selectedEntity, selectedEntity.form);
  1664. configViewList(selectedEntity, selectedEntity.view);
  1665. configEntityOptions(selectedEntity, selectedEntity.view);
  1666. configViewOptions(selectedEntity, selectedEntity.view);
  1667. document.querySelector("#delete-entity").disabled = false;
  1668. document.querySelector("#grow").disabled = false;
  1669. document.querySelector("#shrink").disabled = false;
  1670. document.querySelector("#fit").disabled = false;
  1671. }
  1672. function configFormList(entity, selectedForm) {
  1673. const label = document.querySelector("#options-label-form");
  1674. const list = document.querySelector("#entity-form");
  1675. list.innerHTML = "";
  1676. if (selectedForm === undefined) {
  1677. label.style.display = "none";
  1678. list.style.display = "none";
  1679. return;
  1680. }
  1681. label.style.display = "block";
  1682. list.style.display = "block";
  1683. Object.keys(entity.forms).forEach((form) => {
  1684. const option = document.createElement("option");
  1685. option.innerText = entity.forms[form].name;
  1686. option.value = form;
  1687. if (form === selectedForm) {
  1688. option.selected = true;
  1689. }
  1690. list.appendChild(option);
  1691. });
  1692. }
  1693. function configViewList(entity, selectedView) {
  1694. const list = document.querySelector("#entity-view");
  1695. list.innerHTML = "";
  1696. list.style.display = "block";
  1697. Object.keys(entity.views).forEach((view) => {
  1698. if (Object.keys(entity.forms).length > 0) {
  1699. if (entity.views[view].form !== entity.form) {
  1700. return;
  1701. }
  1702. }
  1703. const option = document.createElement("option");
  1704. option.innerText = entity.views[view].name;
  1705. option.value = view;
  1706. if (isNsfw(entity.views[view].image.source)) {
  1707. option.classList.add("nsfw");
  1708. }
  1709. if (view === selectedView) {
  1710. option.selected = true;
  1711. if (option.classList.contains("nsfw")) {
  1712. list.classList.add("nsfw");
  1713. } else {
  1714. list.classList.remove("nsfw");
  1715. }
  1716. }
  1717. list.appendChild(option);
  1718. });
  1719. }
  1720. function clearViewList() {
  1721. const list = document.querySelector("#entity-view");
  1722. list.innerHTML = "";
  1723. list.style.display = "none";
  1724. }
  1725. function updateWorldOptions(entity, view) {
  1726. const heightInput = document.querySelector("#options-height-value");
  1727. const heightSelect = document.querySelector("#options-height-unit");
  1728. const converted = config.height.toNumber(heightSelect.value);
  1729. setNumericInput(heightInput, converted);
  1730. }
  1731. function configEntityOptions(entity, view) {
  1732. const holder = document.querySelector("#options-entity");
  1733. document.querySelector("#entity-category-header").style.display = "block";
  1734. document.querySelector("#entity-category").style.display = "block";
  1735. holder.innerHTML = "";
  1736. const scaleLabel = document.createElement("div");
  1737. scaleLabel.classList.add("options-label");
  1738. scaleLabel.innerText = "Scale";
  1739. const scaleRow = document.createElement("div");
  1740. scaleRow.classList.add("options-row");
  1741. const scaleInput = document.createElement("input");
  1742. scaleInput.classList.add("options-field-numeric");
  1743. scaleInput.id = "options-entity-scale";
  1744. scaleInput.addEventListener("change", (e) => {
  1745. try {
  1746. const newScale =
  1747. e.target.value == 0 ? 1 : math.evaluate(e.target.value);
  1748. if (typeof newScale !== "number") {
  1749. toast("Invalid input: scale can't have any units!");
  1750. return;
  1751. }
  1752. entity.scale = newScale;
  1753. } catch {
  1754. toast("Invalid input: could not parse " + e.target.value);
  1755. }
  1756. entity.dirty = true;
  1757. if (config.autoFit) {
  1758. fitWorld();
  1759. } else {
  1760. updateSizes(true);
  1761. }
  1762. updateEntityOptions(entity, entity.view);
  1763. updateViewOptions(entity, entity.view);
  1764. });
  1765. scaleInput.addEventListener("keydown", (e) => {
  1766. e.stopPropagation();
  1767. });
  1768. setNumericInput(scaleInput, entity.scale);
  1769. scaleRow.appendChild(scaleInput);
  1770. holder.appendChild(scaleLabel);
  1771. holder.appendChild(scaleRow);
  1772. const nameLabel = document.createElement("div");
  1773. nameLabel.classList.add("options-label");
  1774. nameLabel.innerText = "Name";
  1775. const nameRow = document.createElement("div");
  1776. nameRow.classList.add("options-row");
  1777. const nameInput = document.createElement("input");
  1778. nameInput.classList.add("options-field-text");
  1779. nameInput.value = entity.name;
  1780. nameInput.addEventListener("input", (e) => {
  1781. entity.name = e.target.value;
  1782. entity.dirty = true;
  1783. updateSizes(true);
  1784. });
  1785. nameInput.addEventListener("keydown", (e) => {
  1786. e.stopPropagation();
  1787. });
  1788. nameRow.appendChild(nameInput);
  1789. holder.appendChild(nameLabel);
  1790. holder.appendChild(nameRow);
  1791. configSizeList(entity);
  1792. document.querySelector("#options-order-display").innerText =
  1793. entity.priority;
  1794. document.querySelector("#options-brightness-display").innerText =
  1795. entity.brightness;
  1796. document.querySelector("#options-ordering").style.display = "flex";
  1797. }
  1798. function configSizeList(entity) {
  1799. const defaultHolder = document.querySelector("#options-entity-defaults");
  1800. defaultHolder.innerHTML = "";
  1801. entity.sizes.forEach((defaultInfo) => {
  1802. if (Object.keys(entity.forms).length > 0) {
  1803. if (defaultInfo.form !== entity.form) {
  1804. return;
  1805. }
  1806. }
  1807. const button = document.createElement("button");
  1808. button.classList.add("options-button");
  1809. button.innerText = defaultInfo.name;
  1810. button.addEventListener("click", (e) => {
  1811. if (Object.keys(entity.forms).length > 0) {
  1812. entity.views[entity.formViews[entity.form]].height =
  1813. defaultInfo.height;
  1814. } else {
  1815. entity.views[entity.defaultView].height = defaultInfo.height;
  1816. }
  1817. entity.dirty = true;
  1818. updateEntityOptions(entity, entity.view);
  1819. updateViewOptions(entity, entity.view);
  1820. if (!checkFitWorld()) {
  1821. updateSizes(true);
  1822. }
  1823. if (config.autoFitSize) {
  1824. let targets = {};
  1825. targets[selected.dataset.key] = entities[selected.dataset.key];
  1826. fitEntities(targets);
  1827. }
  1828. });
  1829. defaultHolder.appendChild(button);
  1830. });
  1831. }
  1832. function updateEntityOptions(entity, view) {
  1833. const scaleInput = document.querySelector("#options-entity-scale");
  1834. setNumericInput(scaleInput, entity.scale);
  1835. document.querySelector("#options-order-display").innerText =
  1836. entity.priority;
  1837. document.querySelector("#options-brightness-display").innerText =
  1838. entity.brightness;
  1839. }
  1840. function clearEntityOptions() {
  1841. document.querySelector("#entity-category-header").style.display = "none";
  1842. document.querySelector("#entity-category").style.display = "none";
  1843. /*
  1844. const holder = document.querySelector("#options-entity");
  1845. holder.innerHTML = "";
  1846. document.querySelector("#options-entity-defaults").innerHTML = "";
  1847. document.querySelector("#options-ordering").style.display = "none";
  1848. document.querySelector("#options-ordering").style.display = "none";*/
  1849. }
  1850. function configViewOptions(entity, view) {
  1851. const holder = document.querySelector("#options-view");
  1852. document.querySelector("#view-category-header").style.display = "block";
  1853. document.querySelector("#view-category").style.display = "block";
  1854. holder.innerHTML = "";
  1855. Object.entries(entity.views[view].attributes).forEach(([key, val]) => {
  1856. const label = document.createElement("div");
  1857. label.classList.add("options-label");
  1858. label.innerText = val.name;
  1859. holder.appendChild(label);
  1860. const row = document.createElement("div");
  1861. row.classList.add("options-row");
  1862. holder.appendChild(row);
  1863. const input = document.createElement("input");
  1864. input.classList.add("options-field-numeric");
  1865. input.id = "options-view-" + key + "-input";
  1866. const select = document.createElement("select");
  1867. select.classList.add("options-field-unit");
  1868. select.id = "options-view-" + key + "-select";
  1869. Object.entries(unitChoices[val.type]).forEach(([group, entries]) => {
  1870. const optGroup = document.createElement("optgroup");
  1871. optGroup.label = group;
  1872. select.appendChild(optGroup);
  1873. entries.forEach((entry) => {
  1874. const option = document.createElement("option");
  1875. option.innerText = entry;
  1876. if (entry == defaultUnits[val.type][config.units]) {
  1877. option.selected = true;
  1878. }
  1879. select.appendChild(option);
  1880. });
  1881. });
  1882. input.addEventListener("change", (e) => {
  1883. const raw_value = input.value == 0 ? 1 : input.value;
  1884. let value;
  1885. try {
  1886. value = math.evaluate(raw_value).toNumber(select.value);
  1887. } catch {
  1888. try {
  1889. value = math.evaluate(input.value);
  1890. if (typeof value !== "number") {
  1891. toast(
  1892. "Invalid input: " +
  1893. value.format() +
  1894. " can't convert to " +
  1895. select.value
  1896. );
  1897. value = undefined;
  1898. }
  1899. } catch {
  1900. toast("Invalid input: could not parse: " + input.value);
  1901. value = undefined;
  1902. }
  1903. }
  1904. if (value === undefined) {
  1905. return;
  1906. }
  1907. input.value = value;
  1908. entity.views[view][key] = math.unit(value, select.value);
  1909. entity.dirty = true;
  1910. if (config.autoFit) {
  1911. fitWorld();
  1912. } else {
  1913. updateSizes(true);
  1914. }
  1915. updateEntityOptions(entity, view);
  1916. updateViewOptions(entity, view, key);
  1917. });
  1918. input.addEventListener("keydown", (e) => {
  1919. e.stopPropagation();
  1920. });
  1921. if (entity.currentView.units[key]) {
  1922. select.value = entity.currentView.units[key];
  1923. } else {
  1924. entity.currentView.units[key] = select.value;
  1925. }
  1926. select.dataset.oldUnit = select.value;
  1927. setNumericInput(input, entity.views[view][key].toNumber(select.value));
  1928. // TODO does this ever cause a change in the world?
  1929. select.addEventListener("input", (e) => {
  1930. const value = input.value == 0 ? 1 : input.value;
  1931. const oldUnit = select.dataset.oldUnit;
  1932. entity.views[entity.view][key] = math
  1933. .unit(value, oldUnit)
  1934. .to(select.value);
  1935. entity.dirty = true;
  1936. setNumericInput(
  1937. input,
  1938. entity.views[entity.view][key].toNumber(select.value)
  1939. );
  1940. select.dataset.oldUnit = select.value;
  1941. entity.views[view].units[key] = select.value;
  1942. if (config.autoFit) {
  1943. fitWorld();
  1944. } else {
  1945. updateSizes(true);
  1946. }
  1947. updateEntityOptions(entity, view);
  1948. updateViewOptions(entity, view, key);
  1949. });
  1950. row.appendChild(input);
  1951. row.appendChild(select);
  1952. });
  1953. }
  1954. function updateViewOptions(entity, view, changed) {
  1955. Object.entries(entity.views[view].attributes).forEach(([key, val]) => {
  1956. if (key != changed) {
  1957. const input = document.querySelector(
  1958. "#options-view-" + key + "-input"
  1959. );
  1960. const select = document.querySelector(
  1961. "#options-view-" + key + "-select"
  1962. );
  1963. const currentUnit = select.value;
  1964. const convertedAmount =
  1965. entity.views[view][key].toNumber(currentUnit);
  1966. setNumericInput(input, convertedAmount);
  1967. }
  1968. });
  1969. }
  1970. function setNumericInput(input, value, round = 6) {
  1971. if (typeof value == "string") {
  1972. value = parseFloat(value);
  1973. }
  1974. input.value = value.toPrecision(round);
  1975. }
  1976. function getSortedEntities() {
  1977. return Object.keys(entities).sort((a, b) => {
  1978. const entA = entities[a];
  1979. const entB = entities[b];
  1980. const viewA = entA.view;
  1981. const viewB = entB.view;
  1982. const heightA = entA.views[viewA].height.to("meter").value;
  1983. const heightB = entB.views[viewB].height.to("meter").value;
  1984. return heightA - heightB;
  1985. });
  1986. }
  1987. function clearViewOptions() {
  1988. document.querySelector("#view-category-header").style.display = "none";
  1989. document.querySelector("#view-category").style.display = "none";
  1990. }
  1991. // this is a crime against humanity, and also stolen from
  1992. // stack overflow
  1993. // https://stackoverflow.com/questions/38487569/click-through-png-image-only-if-clicked-coordinate-is-transparent
  1994. const testCanvas = document.createElement("canvas");
  1995. testCanvas.id = "test-canvas";
  1996. function rotate(point, angle) {
  1997. return [
  1998. point[0] * Math.cos(angle) - point[1] * Math.sin(angle),
  1999. point[0] * Math.sin(angle) + point[1] * Math.cos(angle),
  2000. ];
  2001. }
  2002. const testCtx = testCanvas.getContext("2d");
  2003. function testClick(event) {
  2004. const target = event.target;
  2005. if (webkitCanvasBug) {
  2006. return clickDown(target.parentElement, event.clientX, event.clientY);
  2007. }
  2008. testCtx.save();
  2009. if (rulerMode) {
  2010. return;
  2011. }
  2012. // Get click coordinates
  2013. let w = target.width;
  2014. let h = target.height;
  2015. let ratioW = 1,
  2016. ratioH = 1;
  2017. // Limit the size of the canvas so that very large images don't cause problems)
  2018. if (w > 1000) {
  2019. ratioW = w / 1000;
  2020. w /= ratioW;
  2021. h /= ratioW;
  2022. }
  2023. if (h > 1000) {
  2024. ratioH = h / 1000;
  2025. w /= ratioH;
  2026. h /= ratioH;
  2027. }
  2028. // todo remove some of this unused stuff
  2029. const ratio = ratioW * ratioH;
  2030. const entity = entities[target.parentElement.dataset.key];
  2031. const angle = entity.rotation;
  2032. var x = event.clientX - target.getBoundingClientRect().x,
  2033. y = event.clientY - target.getBoundingClientRect().y,
  2034. alpha;
  2035. [xTarget, yTarget] = [x, y];
  2036. [actualW, actualH] = [
  2037. target.getBoundingClientRect().width,
  2038. target.getBoundingClientRect().height,
  2039. ];
  2040. xTarget /= ratio;
  2041. yTarget /= ratio;
  2042. actualW /= ratio;
  2043. actualH /= ratio;
  2044. testCtx.canvas.width = actualW;
  2045. testCtx.canvas.height = actualH;
  2046. testCtx.save();
  2047. // dear future me: Sorry :(
  2048. testCtx.resetTransform();
  2049. testCtx.translate(actualW / 2, actualH / 2);
  2050. testCtx.rotate(angle);
  2051. testCtx.translate(-actualW / 2, -actualH / 2);
  2052. testCtx.drawImage(target, actualW / 2 - w / 2, actualH / 2 - h / 2, w, h);
  2053. testCtx.fillStyle = "red";
  2054. testCtx.fillRect(actualW / 2, actualH / 2, 10, 10);
  2055. testCtx.restore();
  2056. testCtx.fillStyle = "red";
  2057. alpha = testCtx.getImageData(xTarget, yTarget, 1, 1).data[3];
  2058. testCtx.fillRect(xTarget, yTarget, 3, 3);
  2059. // If the pixel is transparent,
  2060. // retrieve the element underneath and trigger its click event
  2061. if (alpha === 0) {
  2062. const oldDisplay = target.style.display;
  2063. target.style.display = "none";
  2064. const newTarget = document.elementFromPoint(
  2065. event.clientX,
  2066. event.clientY
  2067. );
  2068. newTarget.dispatchEvent(
  2069. new MouseEvent(event.type, {
  2070. clientX: event.clientX,
  2071. clientY: event.clientY,
  2072. })
  2073. );
  2074. target.style.display = oldDisplay;
  2075. } else {
  2076. clickDown(target.parentElement, event.clientX, event.clientY);
  2077. }
  2078. testCtx.restore();
  2079. }
  2080. function arrangeEntities(order) {
  2081. const worldWidth =
  2082. (config.height.toNumber("meters") / canvasHeight) * canvasWidth;
  2083. let sum = 0;
  2084. order.forEach((key) => {
  2085. const image = document.querySelector(
  2086. "#entity-" + key + " > .entity-image"
  2087. );
  2088. const meters =
  2089. entities[key].views[entities[key].view].height.toNumber("meters");
  2090. let height = image.height;
  2091. let width = image.width;
  2092. if (height == 0) {
  2093. height = 100;
  2094. }
  2095. if (width == 0) {
  2096. width = height;
  2097. }
  2098. sum += (meters * width) / height;
  2099. });
  2100. let x = config.x - sum / 2;
  2101. order.forEach((key) => {
  2102. const image = document.querySelector(
  2103. "#entity-" + key + " > .entity-image"
  2104. );
  2105. const meters =
  2106. entities[key].views[entities[key].view].height.toNumber("meters");
  2107. let height = image.height;
  2108. let width = image.width;
  2109. if (height == 0) {
  2110. height = 100;
  2111. }
  2112. if (width == 0) {
  2113. width = height;
  2114. }
  2115. x += (meters * width) / height / 2;
  2116. document.querySelector("#entity-" + key).dataset.x = x;
  2117. document.querySelector("#entity-" + key).dataset.y = config.y;
  2118. x += (meters * width) / height / 2;
  2119. });
  2120. fitWorld();
  2121. updateSizes();
  2122. }
  2123. function removeAllEntities() {
  2124. Object.keys(entities).forEach((key) => {
  2125. removeEntity(document.querySelector("#entity-" + key));
  2126. });
  2127. }
  2128. function clearAttribution() {
  2129. document.querySelector("#attribution-category-header").style.display =
  2130. "none";
  2131. document.querySelector("#options-attribution").style.display = "none";
  2132. }
  2133. function displayAttribution(file) {
  2134. document.querySelector("#attribution-category-header").style.display =
  2135. "block";
  2136. document.querySelector("#options-attribution").style.display = "inline";
  2137. const authors = authorsOfFull(file);
  2138. const owners = ownersOfFull(file);
  2139. const citations = citationsOf(file);
  2140. const source = sourceOf(file);
  2141. const authorHolder = document.querySelector("#options-attribution-authors");
  2142. const ownerHolder = document.querySelector("#options-attribution-owners");
  2143. const citationHolder = document.querySelector(
  2144. "#options-attribution-citations"
  2145. );
  2146. const sourceHolder = document.querySelector("#options-attribution-source");
  2147. if (authors === []) {
  2148. const div = document.createElement("div");
  2149. div.innerText = "Unknown";
  2150. authorHolder.innerHTML = "";
  2151. authorHolder.appendChild(div);
  2152. } else if (authors === undefined) {
  2153. const div = document.createElement("div");
  2154. div.innerText = "Not yet entered";
  2155. authorHolder.innerHTML = "";
  2156. authorHolder.appendChild(div);
  2157. } else {
  2158. authorHolder.innerHTML = "";
  2159. const list = document.createElement("ul");
  2160. authorHolder.appendChild(list);
  2161. authors.forEach((author) => {
  2162. const authorEntry = document.createElement("li");
  2163. if (author.url) {
  2164. const link = document.createElement("a");
  2165. link.href = author.url;
  2166. link.innerText = author.name;
  2167. link.rel = "noreferrer no opener";
  2168. link.target = "_blank";
  2169. authorEntry.appendChild(link);
  2170. } else {
  2171. const div = document.createElement("div");
  2172. div.innerText = author.name;
  2173. authorEntry.appendChild(div);
  2174. }
  2175. list.appendChild(authorEntry);
  2176. });
  2177. }
  2178. if (owners === []) {
  2179. const div = document.createElement("div");
  2180. div.innerText = "Unknown";
  2181. ownerHolder.innerHTML = "";
  2182. ownerHolder.appendChild(div);
  2183. } else if (owners === undefined) {
  2184. const div = document.createElement("div");
  2185. div.innerText = "Not yet entered";
  2186. ownerHolder.innerHTML = "";
  2187. ownerHolder.appendChild(div);
  2188. } else {
  2189. ownerHolder.innerHTML = "";
  2190. const list = document.createElement("ul");
  2191. ownerHolder.appendChild(list);
  2192. owners.forEach((owner) => {
  2193. const ownerEntry = document.createElement("li");
  2194. if (owner.url) {
  2195. const link = document.createElement("a");
  2196. link.href = owner.url;
  2197. link.innerText = owner.name;
  2198. link.rel = "noreferrer no opener";
  2199. link.target = "_blank";
  2200. ownerEntry.appendChild(link);
  2201. } else {
  2202. const div = document.createElement("div");
  2203. div.innerText = owner.name;
  2204. ownerEntry.appendChild(div);
  2205. }
  2206. list.appendChild(ownerEntry);
  2207. });
  2208. }
  2209. citationHolder.innerHTML = "";
  2210. if (citations === [] || citations === undefined) {
  2211. } else {
  2212. citationHolder.innerHTML = "";
  2213. const list = document.createElement("ul");
  2214. citationHolder.appendChild(list);
  2215. citations.forEach((citation) => {
  2216. const citationEntry = document.createElement("li");
  2217. const link = document.createElement("a");
  2218. link.style.display = "block";
  2219. link.href = citation;
  2220. link.innerText = new URL(citation).host;
  2221. link.rel = "noreferrer no opener";
  2222. link.target = "_blank";
  2223. citationEntry.appendChild(link);
  2224. list.appendChild(citationEntry);
  2225. });
  2226. }
  2227. if (source === null) {
  2228. const div = document.createElement("div");
  2229. div.innerText = "No link";
  2230. sourceHolder.innerHTML = "";
  2231. sourceHolder.appendChild(div);
  2232. } else if (source === undefined) {
  2233. const div = document.createElement("div");
  2234. div.innerText = "Not yet entered";
  2235. sourceHolder.innerHTML = "";
  2236. sourceHolder.appendChild(div);
  2237. } else {
  2238. sourceHolder.innerHTML = "";
  2239. const link = document.createElement("a");
  2240. link.style.display = "block";
  2241. link.href = source;
  2242. link.innerText = new URL(source).host;
  2243. link.rel = "noreferrer no opener";
  2244. link.target = "_blank";
  2245. sourceHolder.appendChild(link);
  2246. }
  2247. }
  2248. function removeEntity(element) {
  2249. if (selected == element) {
  2250. deselect();
  2251. }
  2252. if (clicked == element) {
  2253. clicked = null;
  2254. }
  2255. const option = document.querySelector(
  2256. "#options-selected-entity-" + element.dataset.key
  2257. );
  2258. option.parentElement.removeChild(option);
  2259. delete entities[element.dataset.key];
  2260. const bottomName = document.querySelector(
  2261. "#bottom-name-" + element.dataset.key
  2262. );
  2263. const topName = document.querySelector("#top-name-" + element.dataset.key);
  2264. bottomName.parentElement.removeChild(bottomName);
  2265. topName.parentElement.removeChild(topName);
  2266. element.parentElement.removeChild(element);
  2267. selectedEntity = null;
  2268. prevSelectedEntity = null;
  2269. updateInfo();
  2270. }
  2271. function checkEntity(entity) {
  2272. Object.values(entity.views).forEach((view) => {
  2273. if (authorsOf(view.image.source) === undefined) {
  2274. console.warn("No authors: " + view.image.source);
  2275. }
  2276. });
  2277. }
  2278. function preloadViews(entity) {
  2279. Object.values(entity.views).forEach((view) => {
  2280. if (Object.keys(entity.forms).length > 0) {
  2281. if (entity.form !== view.form) {
  2282. return;
  2283. }
  2284. }
  2285. if (!preloaded.has(view.image.source)) {
  2286. let img = new Image();
  2287. img.src = view.image.source;
  2288. preloaded.add(view.image.source);
  2289. }
  2290. });
  2291. }
  2292. function displayEntity(
  2293. entity,
  2294. view,
  2295. x,
  2296. y,
  2297. selectEntity = false,
  2298. refresh = false
  2299. ) {
  2300. checkEntity(entity);
  2301. // preload all of the entity's views
  2302. preloadViews(entity);
  2303. const box = document.createElement("div");
  2304. box.classList.add("entity-box");
  2305. const img = document.createElement("img");
  2306. img.classList.add("entity-image");
  2307. img.addEventListener("dragstart", (e) => {
  2308. e.preventDefault();
  2309. });
  2310. const nameTag = document.createElement("div");
  2311. nameTag.classList.add("entity-name");
  2312. nameTag.innerText = entity.name;
  2313. box.appendChild(img);
  2314. box.appendChild(nameTag);
  2315. const image = entity.views[view].image;
  2316. img.src = image.source;
  2317. if (image.bottom !== undefined) {
  2318. img.style.setProperty("--offset", (-1 + image.bottom) * 100 + "%");
  2319. } else {
  2320. img.style.setProperty("--offset", -1 * 100 + "%");
  2321. }
  2322. img.style.setProperty(
  2323. "--rotation",
  2324. (entity.rotation * 180) / Math.PI + "deg"
  2325. );
  2326. box.dataset.x = x;
  2327. box.dataset.y = y;
  2328. img.addEventListener("mousedown", (e) => {
  2329. if (e.which == 1) {
  2330. testClick(e);
  2331. if (clicked) {
  2332. e.stopPropagation();
  2333. }
  2334. }
  2335. });
  2336. img.addEventListener("touchstart", (e) => {
  2337. const fakeEvent = {
  2338. target: e.target,
  2339. clientX: e.touches[0].clientX,
  2340. clientY: e.touches[0].clientY,
  2341. which: 1,
  2342. };
  2343. testClick(fakeEvent);
  2344. if (clicked) {
  2345. e.stopPropagation();
  2346. }
  2347. });
  2348. const heightBar = document.createElement("div");
  2349. heightBar.classList.add("height-bar");
  2350. box.appendChild(heightBar);
  2351. box.id = "entity-" + entityIndex;
  2352. box.dataset.key = entityIndex;
  2353. entity.view = view;
  2354. if (entity.priority === undefined) entity.priority = 0;
  2355. if (entity.brightness === undefined) entity.brightness = 1;
  2356. entities[entityIndex] = entity;
  2357. entity.index = entityIndex;
  2358. const world = document.querySelector("#entities");
  2359. world.appendChild(box);
  2360. const bottomName = document.createElement("div");
  2361. bottomName.classList.add("bottom-name");
  2362. bottomName.id = "bottom-name-" + entityIndex;
  2363. bottomName.innerText = entity.name;
  2364. bottomName.addEventListener("click", () => select(box));
  2365. world.appendChild(bottomName);
  2366. const topName = document.createElement("div");
  2367. topName.classList.add("top-name");
  2368. topName.id = "top-name-" + entityIndex;
  2369. topName.innerText = entity.name;
  2370. topName.addEventListener("click", () => select(box));
  2371. world.appendChild(topName);
  2372. const entityOption = document.createElement("option");
  2373. entityOption.id = "options-selected-entity-" + entityIndex;
  2374. entityOption.value = entityIndex;
  2375. entityOption.innerText = entity.name;
  2376. document
  2377. .getElementById("options-selected-entity")
  2378. .appendChild(entityOption);
  2379. entityIndex += 1;
  2380. if (config.autoFit) {
  2381. fitWorld();
  2382. }
  2383. if (selectEntity) select(box);
  2384. entity.dirty = true;
  2385. if (refresh && config.autoFitAdd) {
  2386. let targets = {};
  2387. targets[entityIndex - 1] = entity;
  2388. fitEntities(targets);
  2389. }
  2390. if (refresh) updateSizes(true);
  2391. }
  2392. window.onblur = function () {
  2393. altHeld = false;
  2394. shiftHeld = false;
  2395. };
  2396. window.onfocus = function () {
  2397. window.dispatchEvent(new Event("keydown"));
  2398. };
  2399. // thanks to https://developers.google.com/web/fundamentals/native-hardware/fullscreen
  2400. function toggleFullScreen() {
  2401. var doc = window.document;
  2402. var docEl = doc.documentElement;
  2403. var requestFullScreen =
  2404. docEl.requestFullscreen ||
  2405. docEl.mozRequestFullScreen ||
  2406. docEl.webkitRequestFullScreen ||
  2407. docEl.msRequestFullscreen;
  2408. var cancelFullScreen =
  2409. doc.exitFullscreen ||
  2410. doc.mozCancelFullScreen ||
  2411. doc.webkitExitFullscreen ||
  2412. doc.msExitFullscreen;
  2413. if (
  2414. !doc.fullscreenElement &&
  2415. !doc.mozFullScreenElement &&
  2416. !doc.webkitFullscreenElement &&
  2417. !doc.msFullscreenElement
  2418. ) {
  2419. requestFullScreen.call(docEl);
  2420. } else {
  2421. cancelFullScreen.call(doc);
  2422. }
  2423. }
  2424. function handleResize() {
  2425. const oldCanvasWidth = canvasWidth;
  2426. entityX = document.querySelector("#entities").getBoundingClientRect().x;
  2427. canvasWidth = document.querySelector("#display").clientWidth - 100;
  2428. canvasHeight = document.querySelector("#display").clientHeight - 50;
  2429. const change = oldCanvasWidth / canvasWidth;
  2430. updateSizes();
  2431. }
  2432. function prepareSidebar() {
  2433. const menubar = document.querySelector("#sidebar-menu");
  2434. [
  2435. {
  2436. name: "Show/hide sidebar",
  2437. id: "menu-toggle-sidebar",
  2438. icon: "fas fa-chevron-circle-down",
  2439. rotates: true,
  2440. },
  2441. {
  2442. name: "Fullscreen",
  2443. id: "menu-fullscreen",
  2444. icon: "fas fa-compress",
  2445. },
  2446. {
  2447. name: "Clear",
  2448. id: "menu-clear",
  2449. icon: "fas fa-file",
  2450. },
  2451. {
  2452. name: "Sort by height",
  2453. id: "menu-order-height",
  2454. icon: "fas fa-sort-numeric-up",
  2455. },
  2456. {
  2457. name: "Permalink",
  2458. id: "menu-permalink",
  2459. icon: "fas fa-link",
  2460. },
  2461. {
  2462. name: "Export to clipboard",
  2463. id: "menu-export",
  2464. icon: "fas fa-share",
  2465. },
  2466. {
  2467. name: "Import from clipboard",
  2468. id: "menu-import",
  2469. icon: "fas fa-share",
  2470. classes: ["flipped"],
  2471. },
  2472. {
  2473. name: "Save Scene",
  2474. id: "menu-save",
  2475. icon: "fas fa-download",
  2476. input: true,
  2477. },
  2478. {
  2479. name: "Load Scene",
  2480. id: "menu-load",
  2481. icon: "fas fa-upload",
  2482. select: true,
  2483. },
  2484. {
  2485. name: "Delete Scene",
  2486. id: "menu-delete",
  2487. icon: "fas fa-trash",
  2488. select: true,
  2489. },
  2490. {
  2491. name: "Load Autosave",
  2492. id: "menu-load-autosave",
  2493. icon: "fas fa-redo",
  2494. },
  2495. {
  2496. name: "Load Preset",
  2497. id: "menu-preset",
  2498. icon: "fas fa-play",
  2499. select: true,
  2500. },
  2501. {
  2502. name: "Add Image",
  2503. id: "menu-add-image",
  2504. icon: "fas fa-camera",
  2505. },
  2506. {
  2507. name: "Clear Rulers",
  2508. id: "menu-clear-rulers",
  2509. icon: "fas fa-ruler",
  2510. },
  2511. ].forEach((entry) => {
  2512. const buttonHolder = document.createElement("div");
  2513. buttonHolder.classList.add("menu-button-holder");
  2514. const button = document.createElement("button");
  2515. button.id = entry.id;
  2516. button.classList.add("menu-button");
  2517. const icon = document.createElement("i");
  2518. icon.classList.add(...entry.icon.split(" "));
  2519. if (entry.rotates) {
  2520. icon.classList.add("rotate-backward", "transitions");
  2521. }
  2522. if (entry.classes) {
  2523. entry.classes.forEach((cls) => icon.classList.add(cls));
  2524. }
  2525. const actionText = document.createElement("span");
  2526. actionText.innerText = entry.name;
  2527. actionText.classList.add("menu-text");
  2528. const srText = document.createElement("span");
  2529. srText.classList.add("sr-only");
  2530. srText.innerText = entry.name;
  2531. button.appendChild(icon);
  2532. button.appendChild(srText);
  2533. buttonHolder.appendChild(button);
  2534. buttonHolder.appendChild(actionText);
  2535. if (entry.input) {
  2536. const input = document.createElement("input");
  2537. buttonHolder.appendChild(input);
  2538. input.placeholder = "default";
  2539. input.addEventListener("keyup", (e) => {
  2540. if (e.key === "Enter") {
  2541. const name =
  2542. document.querySelector("#menu-save ~ input").value;
  2543. if (/\S/.test(name)) {
  2544. saveScene(name);
  2545. }
  2546. updateSaveInfo();
  2547. e.preventDefault();
  2548. }
  2549. });
  2550. }
  2551. if (entry.select) {
  2552. const select = document.createElement("select");
  2553. buttonHolder.appendChild(select);
  2554. }
  2555. menubar.appendChild(buttonHolder);
  2556. });
  2557. }
  2558. function checkBodyClass(cls) {
  2559. return document.body.classList.contains(cls);
  2560. }
  2561. function toggleBodyClass(cls, setting) {
  2562. if (setting) {
  2563. document.body.classList.add(cls);
  2564. } else {
  2565. document.body.classList.remove(cls);
  2566. }
  2567. }
  2568. const backgroundColors = {
  2569. none: "#00000000",
  2570. black: "#000",
  2571. dark: "#111",
  2572. medium: "#333",
  2573. light: "#555",
  2574. };
  2575. const settingsCategories = {
  2576. background: "Background",
  2577. controls: "Controls",
  2578. info: "Info",
  2579. visuals: "Visuals",
  2580. };
  2581. const groundPosChoices = [
  2582. "very-high",
  2583. "high",
  2584. "medium",
  2585. "low",
  2586. "very-low",
  2587. "bottom",
  2588. ];
  2589. const settingsData = {
  2590. "show-vertical-scale": {
  2591. name: "Vertical Scale",
  2592. desc: "Draw vertical scale marks",
  2593. type: "toggle",
  2594. default: true,
  2595. get value() {
  2596. return config.drawYAxis;
  2597. },
  2598. set value(param) {
  2599. config.drawYAxis = param;
  2600. drawScales(false);
  2601. },
  2602. },
  2603. "show-horizontal-scale": {
  2604. name: "Horiziontal Scale",
  2605. desc: "Draw horizontal scale marks",
  2606. type: "toggle",
  2607. default: false,
  2608. get value() {
  2609. return config.drawXAxis;
  2610. },
  2611. set value(param) {
  2612. config.drawXAxis = param;
  2613. drawScales(false);
  2614. },
  2615. },
  2616. "show-altitudes": {
  2617. name: "Altitudes",
  2618. desc: "Draw interesting altitudes",
  2619. type: "select",
  2620. default: "none",
  2621. disabled: "none",
  2622. options: [
  2623. "none",
  2624. "all",
  2625. "atmosphere",
  2626. "orbits",
  2627. "weather",
  2628. "water",
  2629. "geology",
  2630. "thicknesses",
  2631. "airspaces",
  2632. "races",
  2633. "olympic-records",
  2634. "d&d-sizes",
  2635. ],
  2636. get value() {
  2637. return config.drawAltitudes;
  2638. },
  2639. set value(param) {
  2640. config.drawAltitudes = param;
  2641. drawScales(false);
  2642. },
  2643. },
  2644. "lock-y-axis": {
  2645. name: "Lock Y-Axis",
  2646. desc: "Keep the camera at ground-level",
  2647. type: "toggle",
  2648. default: true,
  2649. get value() {
  2650. return config.lockYAxis;
  2651. },
  2652. set value(param) {
  2653. config.lockYAxis = param;
  2654. updateScrollButtons();
  2655. if (param) {
  2656. updateSizes();
  2657. }
  2658. },
  2659. },
  2660. "ground-snap": {
  2661. name: "Snap to Ground",
  2662. desc: "Snap things to the ground",
  2663. type: "toggle",
  2664. default: true,
  2665. get value() {
  2666. return config.groundSnap;
  2667. },
  2668. set value(param) {
  2669. config.groundSnap = param;
  2670. },
  2671. },
  2672. "axis-spacing": {
  2673. name: "Axis Spacing",
  2674. desc: "How frequent the axis lines are",
  2675. type: "select",
  2676. default: "standard",
  2677. options: ["dense", "standard", "sparse"],
  2678. get value() {
  2679. return config.axisSpacing;
  2680. },
  2681. set value(param) {
  2682. config.axisSpacing = param;
  2683. const factor = {
  2684. dense: 0.5,
  2685. standard: 1,
  2686. sparse: 2,
  2687. }[param];
  2688. config.minLineSize = factor * 100;
  2689. config.maxLineSize = factor * 150;
  2690. updateSizes();
  2691. },
  2692. },
  2693. "ground-type": {
  2694. name: "Ground",
  2695. desc: "What kind of ground to show, if any",
  2696. type: "select",
  2697. default: "black",
  2698. disabled: "none",
  2699. options: ["none", "black", "dark", "medium", "light"],
  2700. get value() {
  2701. return config.groundKind;
  2702. },
  2703. set value(param) {
  2704. config.groundKind = param;
  2705. document
  2706. .querySelector("#ground")
  2707. .style.setProperty("--ground-color", backgroundColors[param]);
  2708. },
  2709. },
  2710. "ground-pos": {
  2711. name: "Ground Position",
  2712. desc: "How high the ground is if the y-axis is locked",
  2713. type: "select",
  2714. default: "very-low",
  2715. options: groundPosChoices,
  2716. get value() {
  2717. return config.groundPos;
  2718. },
  2719. set value(param) {
  2720. config.groundPos = param;
  2721. updateScrollButtons();
  2722. updateSizes();
  2723. },
  2724. },
  2725. "background-brightness": {
  2726. name: "Background Color",
  2727. desc: "How bright the background is",
  2728. type: "select",
  2729. default: "medium",
  2730. options: ["black", "dark", "medium", "light"],
  2731. get value() {
  2732. return config.background;
  2733. },
  2734. set value(param) {
  2735. config.background = param;
  2736. drawScales();
  2737. },
  2738. },
  2739. "auto-scale": {
  2740. name: "Auto-Size World",
  2741. desc: "Constantly zoom to fit the largest entity",
  2742. type: "toggle",
  2743. default: false,
  2744. get value() {
  2745. return config.autoFit;
  2746. },
  2747. set value(param) {
  2748. config.autoFit = param;
  2749. checkFitWorld();
  2750. },
  2751. },
  2752. "auto-units": {
  2753. name: "Auto-Select Units",
  2754. desc: "Automatically switch units when zooming in and out",
  2755. type: "toggle",
  2756. default: false,
  2757. get value() {
  2758. return config.autoUnits;
  2759. },
  2760. set value(param) {
  2761. config.autoUnits = param;
  2762. },
  2763. },
  2764. "zoom-when-adding": {
  2765. name: "Zoom On Add",
  2766. desc: "Zoom to fit when you add a new entity",
  2767. type: "toggle",
  2768. default: false,
  2769. get value() {
  2770. return config.autoFitAdd;
  2771. },
  2772. set value(param) {
  2773. config.autoFitAdd = param;
  2774. },
  2775. },
  2776. "zoom-when-sizing": {
  2777. name: "Zoom On Size",
  2778. desc: "Zoom to fit when you select an entity's size",
  2779. type: "toggle",
  2780. default: false,
  2781. get value() {
  2782. return config.autoFitSize;
  2783. },
  2784. set value(param) {
  2785. config.autoFitSize = param;
  2786. },
  2787. },
  2788. "show-ratios": {
  2789. name: "Show Ratios",
  2790. desc: "Show the proportions between the current selection and the most recent selection.",
  2791. type: "toggle",
  2792. default: false,
  2793. get value() {
  2794. return config.showRatios;
  2795. },
  2796. set value(param) {
  2797. config.showRatios = param;
  2798. updateInfo();
  2799. },
  2800. },
  2801. "show-horizon": {
  2802. name: "Show Horizon",
  2803. desc: "Show how far the horizon would be for the selected character",
  2804. type: "toggle",
  2805. default: false,
  2806. get value() {
  2807. return config.showHorizon;
  2808. },
  2809. set value(param) {
  2810. config.showHorizon = param;
  2811. updateInfo();
  2812. },
  2813. },
  2814. "attach-rulers": {
  2815. name: "Attach Rulers",
  2816. desc: "Rulers will attach to the currently-selected entity, moving around with it.",
  2817. type: "toggle",
  2818. default: true,
  2819. get value() {
  2820. return config.rulersStick;
  2821. },
  2822. set value(param) {
  2823. config.rulersStick = param;
  2824. },
  2825. },
  2826. units: {
  2827. name: "Default Units",
  2828. desc: "Which kind of unit to use by default",
  2829. type: "select",
  2830. default: "metric",
  2831. options: ["metric", "customary", "relative", "quirky", "human"],
  2832. get value() {
  2833. return config.units;
  2834. },
  2835. set value(param) {
  2836. config.units = param;
  2837. updateSizes();
  2838. },
  2839. },
  2840. names: {
  2841. name: "Show Names",
  2842. desc: "Display names over entities",
  2843. type: "toggle",
  2844. default: true,
  2845. get value() {
  2846. return checkBodyClass("toggle-entity-name");
  2847. },
  2848. set value(param) {
  2849. toggleBodyClass("toggle-entity-name", param);
  2850. },
  2851. },
  2852. "bottom-names": {
  2853. name: "Bottom Names",
  2854. desc: "Display names at the bottom",
  2855. type: "toggle",
  2856. default: false,
  2857. get value() {
  2858. return checkBodyClass("toggle-bottom-name");
  2859. },
  2860. set value(param) {
  2861. toggleBodyClass("toggle-bottom-name", param);
  2862. },
  2863. },
  2864. "top-names": {
  2865. name: "Show Arrows",
  2866. desc: "Point to entities that are much larger than the current view",
  2867. type: "toggle",
  2868. default: false,
  2869. get value() {
  2870. return checkBodyClass("toggle-top-name");
  2871. },
  2872. set value(param) {
  2873. toggleBodyClass("toggle-top-name", param);
  2874. },
  2875. },
  2876. "height-bars": {
  2877. name: "Height Bars",
  2878. desc: "Draw dashed lines to the top of each entity",
  2879. type: "toggle",
  2880. default: false,
  2881. get value() {
  2882. return checkBodyClass("toggle-height-bars");
  2883. },
  2884. set value(param) {
  2885. toggleBodyClass("toggle-height-bars", param);
  2886. },
  2887. },
  2888. "flag-nsfw": {
  2889. name: "Flag NSFW",
  2890. desc: "Highlight NSFW things in red",
  2891. type: "toggle",
  2892. default: false,
  2893. get value() {
  2894. return checkBodyClass("flag-nsfw");
  2895. },
  2896. set value(param) {
  2897. toggleBodyClass("flag-nsfw", param);
  2898. },
  2899. },
  2900. "glowing-entities": {
  2901. name: "Glowing Edges",
  2902. desc: "Makes all entities glow",
  2903. type: "toggle",
  2904. default: false,
  2905. get value() {
  2906. return checkBodyClass("toggle-entity-glow");
  2907. },
  2908. set value(param) {
  2909. toggleBodyClass("toggle-entity-glow", param);
  2910. },
  2911. },
  2912. "select-style": {
  2913. name: "Selection Style",
  2914. desc: "How to highlight selected entities (outlines are laggier",
  2915. type: "select",
  2916. default: "color",
  2917. options: ["color", "outline"],
  2918. get value() {
  2919. if (checkBodyClass("highlight-color")) {
  2920. return "color";
  2921. } else {
  2922. return "outline";
  2923. }
  2924. },
  2925. set value(param) {
  2926. toggleBodyClass("highlight-color", param === "color");
  2927. toggleBodyClass("highlight-outline", param === "outline");
  2928. },
  2929. },
  2930. smoothing: {
  2931. name: "Smoothing",
  2932. desc: "Smooth out movements and size changes. Disable for better performance.",
  2933. type: "toggle",
  2934. default: true,
  2935. get value() {
  2936. return checkBodyClass("smoothing");
  2937. },
  2938. set value(param) {
  2939. toggleBodyClass("smoothing", param);
  2940. },
  2941. },
  2942. "auto-mass": {
  2943. name: "Estimate Mass",
  2944. desc: "Guess the mass of things that don't have one specified using the selected body type",
  2945. type: "select",
  2946. default: "off",
  2947. disabled: "off",
  2948. options: ["off", "human", "quadruped at shoulder"],
  2949. get value() {
  2950. return config.autoMass;
  2951. },
  2952. set value(param) {
  2953. config.autoMass = param;
  2954. },
  2955. },
  2956. "auto-food-intake": {
  2957. name: "Estimate Food Intake",
  2958. desc: "Guess how much food creatures need, based on their mass -- 2000kcal per 150lbs",
  2959. type: "toggle",
  2960. default: false,
  2961. get value() {
  2962. return config.autoFoodIntake;
  2963. },
  2964. set value(param) {
  2965. config.autoFoodIntake = param;
  2966. },
  2967. },
  2968. "auto-caloric-value": {
  2969. name: "Estimate Caloric Value",
  2970. desc: "Guess how much food a creature is worth -- 860kcal per pound",
  2971. type: "toggle",
  2972. default: false,
  2973. get value() {
  2974. return config.autoCaloricValue;
  2975. },
  2976. set value(param) {
  2977. config.autoCaloricValue = param;
  2978. },
  2979. },
  2980. "auto-prey-capacity": {
  2981. name: "Estimate Prey Capacity",
  2982. desc: "Guess how much prey creatures can hold, based on their mass",
  2983. type: "select",
  2984. default: "off",
  2985. disabled: "off",
  2986. options: ["off", "realistic", "same-size"],
  2987. get value() {
  2988. return config.autoPreyCapacity;
  2989. },
  2990. set value(param) {
  2991. config.autoPreyCapacity = param;
  2992. },
  2993. },
  2994. };
  2995. function prepareSettings(userSettings) {
  2996. const menubar = document.querySelector("#settings-menu");
  2997. Object.entries(settingsData).forEach(([id, entry]) => {
  2998. const holder = document.createElement("label");
  2999. holder.classList.add("settings-holder");
  3000. const input = document.createElement("input");
  3001. input.id = "setting-" + id;
  3002. const vertical = document.createElement("div");
  3003. vertical.classList.add("settings-vertical");
  3004. const name = document.createElement("label");
  3005. name.innerText = entry.name;
  3006. name.classList.add("settings-name");
  3007. name.setAttribute("for", input.id);
  3008. const desc = document.createElement("label");
  3009. desc.innerText = entry.desc;
  3010. desc.classList.add("settings-desc");
  3011. desc.setAttribute("for", input.id);
  3012. if (entry.type == "toggle") {
  3013. input.type = "checkbox";
  3014. input.checked =
  3015. userSettings[id] === undefined
  3016. ? entry.default
  3017. : userSettings[id];
  3018. holder.setAttribute("for", input.id);
  3019. vertical.appendChild(name);
  3020. vertical.appendChild(desc);
  3021. holder.appendChild(vertical);
  3022. holder.appendChild(input);
  3023. menubar.appendChild(holder);
  3024. const update = () => {
  3025. if (input.checked) {
  3026. holder.classList.add("enabled");
  3027. holder.classList.remove("disabled");
  3028. } else {
  3029. holder.classList.remove("enabled");
  3030. holder.classList.add("disabled");
  3031. }
  3032. entry.value = input.checked;
  3033. };
  3034. setTimeout(update);
  3035. input.addEventListener("change", update);
  3036. } else if (entry.type == "select") {
  3037. // we don't use the input element we made!
  3038. const select = document.createElement("select");
  3039. select.id = "setting-" + id;
  3040. entry.options.forEach((choice) => {
  3041. const option = document.createElement("option");
  3042. option.innerText = choice;
  3043. select.appendChild(option);
  3044. });
  3045. select.value =
  3046. userSettings[id] === undefined
  3047. ? entry.default
  3048. : userSettings[id];
  3049. vertical.appendChild(name);
  3050. vertical.appendChild(desc);
  3051. holder.appendChild(vertical);
  3052. holder.appendChild(select);
  3053. menubar.appendChild(holder);
  3054. const update = () => {
  3055. entry.value = select.value;
  3056. if (
  3057. entry.disabled !== undefined &&
  3058. entry.value !== entry.disabled
  3059. ) {
  3060. holder.classList.add("enabled");
  3061. holder.classList.remove("disabled");
  3062. } else {
  3063. holder.classList.remove("enabled");
  3064. holder.classList.add("disabled");
  3065. }
  3066. };
  3067. update();
  3068. select.addEventListener("change", update);
  3069. }
  3070. });
  3071. }
  3072. function prepareMenu() {
  3073. prepareSidebar();
  3074. updateSaveInfo();
  3075. if (checkHelpDate()) {
  3076. document.querySelector("#open-help").classList.add("highlighted");
  3077. }
  3078. }
  3079. function updateSaveInfo() {
  3080. const saves = getSaves();
  3081. const load = document.querySelector("#menu-load ~ select");
  3082. load.innerHTML = "";
  3083. saves.forEach((save) => {
  3084. const option = document.createElement("option");
  3085. option.innerText = save;
  3086. option.value = save;
  3087. load.appendChild(option);
  3088. });
  3089. const del = document.querySelector("#menu-delete ~ select");
  3090. del.innerHTML = "";
  3091. saves.forEach((save) => {
  3092. const option = document.createElement("option");
  3093. option.innerText = save;
  3094. option.value = save;
  3095. del.appendChild(option);
  3096. });
  3097. }
  3098. function getSaves() {
  3099. try {
  3100. const results = [];
  3101. Object.keys(localStorage).forEach((key) => {
  3102. if (key.startsWith("macrovision-save-")) {
  3103. results.push(key.replace("macrovision-save-", ""));
  3104. }
  3105. });
  3106. return results;
  3107. } catch (err) {
  3108. alert(
  3109. "Something went wrong while loading (maybe you didn't have anything saved. Check the F12 console for the error."
  3110. );
  3111. console.error(err);
  3112. return false;
  3113. }
  3114. }
  3115. function getUserSettings() {
  3116. try {
  3117. const settings = JSON.parse(localStorage.getItem("settings"));
  3118. return settings === null ? {} : settings;
  3119. } catch {
  3120. return {};
  3121. }
  3122. }
  3123. function exportUserSettings() {
  3124. const settings = {};
  3125. Object.entries(settingsData).forEach(([id, entry]) => {
  3126. settings[id] = entry.value;
  3127. });
  3128. return settings;
  3129. }
  3130. function setUserSettings(settings) {
  3131. try {
  3132. localStorage.setItem("settings", JSON.stringify(settings));
  3133. } catch {
  3134. // :(
  3135. }
  3136. }
  3137. const lastHelpChange = 1601955834693;
  3138. function checkHelpDate() {
  3139. // disabling this for now
  3140. return false;
  3141. try {
  3142. const old = localStorage.getItem("help-viewed");
  3143. if (old === null || old < lastHelpChange) {
  3144. return true;
  3145. }
  3146. return false;
  3147. } catch {
  3148. console.warn("Could not set the help-viewed date");
  3149. return false;
  3150. }
  3151. }
  3152. function setHelpDate() {
  3153. try {
  3154. localStorage.setItem("help-viewed", Date.now());
  3155. } catch {
  3156. console.warn("Could not set the help-viewed date");
  3157. }
  3158. }
  3159. function doYScroll() {
  3160. const worldHeight = config.height.toNumber("meters");
  3161. config.y += (scrollDirection * worldHeight) / 180;
  3162. updateSizes();
  3163. scrollDirection *= 1.05;
  3164. }
  3165. function doXScroll() {
  3166. const worldWidth =
  3167. (config.height.toNumber("meters") / canvasHeight) * canvasWidth;
  3168. config.x += (scrollDirection * worldWidth) / 180;
  3169. updateSizes();
  3170. scrollDirection *= 1.05;
  3171. }
  3172. function doZoom() {
  3173. const oldHeight = config.height;
  3174. setWorldHeight(oldHeight, math.multiply(oldHeight, 1 + zoomDirection / 10));
  3175. zoomDirection *= 1.05;
  3176. }
  3177. function doSize() {
  3178. if (selected) {
  3179. const entity = entities[selected.dataset.key];
  3180. const oldHeight = entity.views[entity.view].height;
  3181. entity.views[entity.view].height = math.multiply(
  3182. oldHeight,
  3183. sizeDirection < 0 ? -1 / sizeDirection : sizeDirection
  3184. );
  3185. entity.dirty = true;
  3186. updateEntityOptions(entity, entity.view);
  3187. updateViewOptions(entity, entity.view);
  3188. updateSizes(true);
  3189. sizeDirection *= 1.01;
  3190. const ownHeight = entity.views[entity.view].height.toNumber("meters");
  3191. let extra = entity.views[entity.view].image.extra;
  3192. extra = extra === undefined ? 1 : extra;
  3193. const worldHeight = config.height.toNumber("meters");
  3194. if (ownHeight * extra > worldHeight) {
  3195. setWorldHeight(
  3196. config.height,
  3197. math.multiply(entity.views[entity.view].height, extra)
  3198. );
  3199. } else if (ownHeight * extra * 10 < worldHeight) {
  3200. setWorldHeight(
  3201. config.height,
  3202. math.multiply(entity.views[entity.view].height, extra * 10)
  3203. );
  3204. }
  3205. }
  3206. }
  3207. function selectNewUnit() {
  3208. const unitSelector = document.querySelector("#options-height-unit");
  3209. checkFitWorld();
  3210. const scaleInput = document.querySelector("#options-height-value");
  3211. const newVal = math
  3212. .unit(scaleInput.value, unitSelector.dataset.oldUnit)
  3213. .toNumber(unitSelector.value);
  3214. setNumericInput(scaleInput, newVal);
  3215. updateWorldHeight();
  3216. unitSelector.dataset.oldUnit = unitSelector.value;
  3217. }
  3218. // given a world position, return the position relative to the entity at normal scale
  3219. function entityRelativePosition(pos, entityElement) {
  3220. const entity = entities[entityElement.dataset.key];
  3221. const x = parseFloat(entityElement.dataset.x);
  3222. const y = parseFloat(entityElement.dataset.y);
  3223. pos.x -= x;
  3224. pos.y -= y;
  3225. pos.x /= entity.scale;
  3226. pos.y /= entity.scale;
  3227. return pos;
  3228. }
  3229. document.addEventListener("DOMContentLoaded", () => {
  3230. prepareMenu();
  3231. prepareEntities();
  3232. document
  3233. .querySelector("#copy-screenshot")
  3234. .addEventListener("click", (e) => {
  3235. copyScreenshot();
  3236. });
  3237. document
  3238. .querySelector("#save-screenshot")
  3239. .addEventListener("click", (e) => {
  3240. saveScreenshot();
  3241. });
  3242. document
  3243. .querySelector("#open-screenshot")
  3244. .addEventListener("click", (e) => {
  3245. openScreenshot();
  3246. });
  3247. document.querySelector("#toggle-menu").addEventListener("click", (e) => {
  3248. const popoutMenu = document.querySelector("#sidebar-menu");
  3249. if (popoutMenu.classList.contains("visible")) {
  3250. popoutMenu.classList.remove("visible");
  3251. } else {
  3252. document
  3253. .querySelectorAll(".popout-menu")
  3254. .forEach((menu) => menu.classList.remove("visible"));
  3255. const rect = e.target.getBoundingClientRect();
  3256. popoutMenu.classList.add("visible");
  3257. popoutMenu.style.left = rect.x + rect.width + 10 + "px";
  3258. popoutMenu.style.top = rect.y + rect.height + 10 + "px";
  3259. let menuWidth = popoutMenu.getBoundingClientRect().width;
  3260. let screenWidth = window.innerWidth;
  3261. if (menuWidth * 1.5 > screenWidth) {
  3262. popoutMenu.style.left = 25 + "px";
  3263. }
  3264. }
  3265. e.stopPropagation();
  3266. });
  3267. document.querySelector("#sidebar-menu").addEventListener("click", (e) => {
  3268. e.stopPropagation();
  3269. });
  3270. document.querySelector("#sidebar-menu").addEventListener("touchstart", (e) => {
  3271. e.stopPropagation();
  3272. });
  3273. document.addEventListener("click", (e) => {
  3274. document.querySelector("#sidebar-menu").classList.remove("visible");
  3275. });
  3276. document.addEventListener("touchstart", (e) => {
  3277. document.querySelector("#sidebar-menu").classList.remove("visible");
  3278. });
  3279. document
  3280. .querySelector("#toggle-settings")
  3281. .addEventListener("click", (e) => {
  3282. const popoutMenu = document.querySelector("#settings-menu");
  3283. if (popoutMenu.classList.contains("visible")) {
  3284. popoutMenu.classList.remove("visible");
  3285. } else {
  3286. document
  3287. .querySelectorAll(".popout-menu")
  3288. .forEach((menu) => menu.classList.remove("visible"));
  3289. const rect = e.target.getBoundingClientRect();
  3290. popoutMenu.classList.add("visible");
  3291. popoutMenu.style.left = rect.x + rect.width + 10 + "px";
  3292. popoutMenu.style.top = rect.y + rect.height + 10 + "px";
  3293. let menuWidth = popoutMenu.getBoundingClientRect().width;
  3294. let screenWidth = window.innerWidth;
  3295. if (menuWidth * 1.5 > screenWidth) {
  3296. popoutMenu.style.left = 25 + "px";
  3297. }
  3298. }
  3299. e.stopPropagation();
  3300. });
  3301. document.querySelector("#settings-menu").addEventListener("click", (e) => {
  3302. e.stopPropagation();
  3303. });
  3304. document.querySelector("#settings-menu").addEventListener("touchstart", (e) => {
  3305. e.stopPropagation();
  3306. });
  3307. document.addEventListener("click", (e) => {
  3308. document.querySelector("#settings-menu").classList.remove("visible");
  3309. });
  3310. document.addEventListener("touchstart", (e) => {
  3311. document.querySelector("#settings-menu").classList.remove("visible");
  3312. });
  3313. document.querySelector("#toggle-filters").addEventListener("click", (e) => {
  3314. const popoutMenu = document.querySelector("#filters-menu");
  3315. if (popoutMenu.classList.contains("visible")) {
  3316. popoutMenu.classList.remove("visible");
  3317. } else {
  3318. document
  3319. .querySelectorAll(".popout-menu")
  3320. .forEach((menu) => menu.classList.remove("visible"));
  3321. const rect = e.target.getBoundingClientRect();
  3322. popoutMenu.classList.add("visible");
  3323. popoutMenu.style.left = rect.x + rect.width + 10 + "px";
  3324. popoutMenu.style.top = rect.y + rect.height + 10 + "px";
  3325. let menuWidth = popoutMenu.getBoundingClientRect().width;
  3326. let screenWidth = window.innerWidth;
  3327. if (menuWidth * 1.5 > screenWidth) {
  3328. popoutMenu.style.left = 25 + "px";
  3329. }
  3330. }
  3331. e.stopPropagation();
  3332. });
  3333. document.querySelector("#filters-menu").addEventListener("click", (e) => {
  3334. e.stopPropagation();
  3335. });
  3336. document.querySelector("#filters-menu").addEventListener("touchstart", (e) => {
  3337. e.stopPropagation();
  3338. });
  3339. document.addEventListener("click", (e) => {
  3340. document.querySelector("#filters-menu").classList.remove("visible");
  3341. });
  3342. document.addEventListener("touchstart", (e) => {
  3343. document.querySelector("#filters-menu").classList.remove("visible");
  3344. });
  3345. document.querySelector("#toggle-info").addEventListener("click", (e) => {
  3346. const popoutMenu = document.querySelector("#info-menu");
  3347. if (popoutMenu.classList.contains("visible")) {
  3348. popoutMenu.classList.remove("visible");
  3349. } else {
  3350. document
  3351. .querySelectorAll(".popout-menu")
  3352. .forEach((menu) => menu.classList.remove("visible"));
  3353. const rect = e.target.getBoundingClientRect();
  3354. popoutMenu.classList.add("visible");
  3355. popoutMenu.style.left = rect.x + rect.width + 10 + "px";
  3356. popoutMenu.style.top = rect.y + rect.height + 10 + "px";
  3357. let menuWidth = popoutMenu.getBoundingClientRect().width;
  3358. let screenWidth = window.innerWidth;
  3359. if (menuWidth * 1.5 > screenWidth) {
  3360. popoutMenu.style.left = 25 + "px";
  3361. }
  3362. }
  3363. e.stopPropagation();
  3364. });
  3365. document.querySelector("#info-menu").addEventListener("click", (e) => {
  3366. e.stopPropagation();
  3367. });
  3368. document.querySelector("#info-menu").addEventListener("touchstart", (e) => {
  3369. e.stopPropagation();
  3370. });
  3371. document.addEventListener("click", (e) => {
  3372. document.querySelector("#info-menu").classList.remove("visible");
  3373. });
  3374. document.addEventListener("touchstart", (e) => {
  3375. document.querySelector("#info-menu").classList.remove("visible");
  3376. });
  3377. window.addEventListener("unload", () => {
  3378. saveScene("autosave");
  3379. setUserSettings(exportUserSettings());
  3380. });
  3381. document
  3382. .querySelector("#options-selected-entity")
  3383. .addEventListener("input", (e) => {
  3384. if (e.target.value == "None") {
  3385. deselect();
  3386. } else {
  3387. select(document.querySelector("#entity-" + e.target.value));
  3388. }
  3389. });
  3390. document
  3391. .querySelector("#menu-toggle-sidebar")
  3392. .addEventListener("click", (e) => {
  3393. const sidebar = document.querySelector("#options");
  3394. if (sidebar.classList.contains("hidden")) {
  3395. sidebar.classList.remove("hidden");
  3396. e.target.classList.remove("rotate-forward");
  3397. e.target.classList.add("rotate-backward");
  3398. } else {
  3399. sidebar.classList.add("hidden");
  3400. e.target.classList.add("rotate-forward");
  3401. e.target.classList.remove("rotate-backward");
  3402. }
  3403. handleResize();
  3404. });
  3405. document
  3406. .querySelector("#menu-fullscreen")
  3407. .addEventListener("click", toggleFullScreen);
  3408. document
  3409. .querySelector("#options-order-forward")
  3410. .addEventListener("click", (e) => {
  3411. if (selected) {
  3412. entities[selected.dataset.key].priority += 1;
  3413. }
  3414. document.querySelector("#options-order-display").innerText =
  3415. entities[selected.dataset.key].priority;
  3416. updateSizes();
  3417. });
  3418. document
  3419. .querySelector("#options-order-back")
  3420. .addEventListener("click", (e) => {
  3421. if (selected) {
  3422. entities[selected.dataset.key].priority -= 1;
  3423. }
  3424. document.querySelector("#options-order-display").innerText =
  3425. entities[selected.dataset.key].priority;
  3426. updateSizes();
  3427. });
  3428. document
  3429. .querySelector("#options-brightness-up")
  3430. .addEventListener("click", (e) => {
  3431. if (selected) {
  3432. entities[selected.dataset.key].brightness += 1;
  3433. }
  3434. document.querySelector("#options-brightness-display").innerText =
  3435. entities[selected.dataset.key].brightness;
  3436. updateSizes();
  3437. });
  3438. document
  3439. .querySelector("#options-brightness-down")
  3440. .addEventListener("click", (e) => {
  3441. if (selected) {
  3442. entities[selected.dataset.key].brightness -= 1;
  3443. }
  3444. document.querySelector("#options-brightness-display").innerText =
  3445. entities[selected.dataset.key].brightness;
  3446. updateSizes();
  3447. });
  3448. document
  3449. .querySelector("#options-rotate-left")
  3450. .addEventListener("click", (e) => {
  3451. if (selected) {
  3452. entities[selected.dataset.key].rotation -= Math.PI / 4;
  3453. }
  3454. selected
  3455. .querySelector("img")
  3456. .style.setProperty(
  3457. "--rotation",
  3458. (entities[selected.dataset.key].rotation * 180) / Math.PI +
  3459. "deg"
  3460. );
  3461. updateSizes();
  3462. });
  3463. document
  3464. .querySelector("#options-rotate-right")
  3465. .addEventListener("click", (e) => {
  3466. if (selected) {
  3467. entities[selected.dataset.key].rotation += Math.PI / 4;
  3468. }
  3469. selected
  3470. .querySelector("img")
  3471. .style.setProperty(
  3472. "--rotation",
  3473. (entities[selected.dataset.key].rotation * 180) / Math.PI +
  3474. "deg"
  3475. );
  3476. updateSizes();
  3477. });
  3478. document.querySelector("#options-flip").addEventListener("click", (e) => {
  3479. if (selected) {
  3480. selected.querySelector(".entity-image").classList.toggle("flipped");
  3481. }
  3482. document.querySelector("#options-brightness-display").innerText =
  3483. entities[selected.dataset.key].brightness;
  3484. updateSizes();
  3485. });
  3486. const sceneChoices = document.querySelector("#menu-preset ~ select");
  3487. Object.entries(scenes).forEach(([id, scene]) => {
  3488. const option = document.createElement("option");
  3489. option.innerText = id;
  3490. option.value = id;
  3491. sceneChoices.appendChild(option);
  3492. });
  3493. document.querySelector("#menu-preset").addEventListener("click", (e) => {
  3494. const chosen = sceneChoices.value;
  3495. removeAllEntities();
  3496. scenes[chosen]();
  3497. });
  3498. entityX = document.querySelector("#entities").getBoundingClientRect().x;
  3499. canvasWidth = document.querySelector("#display").clientWidth - 100;
  3500. canvasHeight = document.querySelector("#display").clientHeight - 50;
  3501. document
  3502. .querySelector("#options-height-value")
  3503. .addEventListener("change", (e) => {
  3504. updateWorldHeight();
  3505. });
  3506. document
  3507. .querySelector("#options-height-value")
  3508. .addEventListener("keydown", (e) => {
  3509. e.stopPropagation();
  3510. });
  3511. const unitSelector = document.querySelector("#options-height-unit");
  3512. Object.entries(unitChoices.length).forEach(([group, entries]) => {
  3513. const optGroup = document.createElement("optgroup");
  3514. optGroup.label = group;
  3515. unitSelector.appendChild(optGroup);
  3516. entries.forEach((entry) => {
  3517. const option = document.createElement("option");
  3518. option.innerText = entry;
  3519. // we haven't loaded user settings yet, so we can't choose the unit just yet
  3520. unitSelector.appendChild(option);
  3521. });
  3522. });
  3523. unitSelector.addEventListener("input", selectNewUnit);
  3524. param = window.location.hash;
  3525. // we now use the fragment for links, but we should still support old stuff:
  3526. if (param.length > 0) {
  3527. param = param.substring(1);
  3528. } else {
  3529. param = new URL(window.location.href).searchParams.get("scene");
  3530. }
  3531. document.querySelector("#world").addEventListener("mousedown", (e) => {
  3532. // only middle mouse clicks
  3533. if (e.which == 2) {
  3534. panning = true;
  3535. panOffsetX = e.clientX;
  3536. panOffsetY = e.clientY;
  3537. Object.keys(entities).forEach((key) => {
  3538. document
  3539. .querySelector("#entity-" + key)
  3540. .classList.add("no-transition");
  3541. });
  3542. }
  3543. });
  3544. document.addEventListener("mouseup", (e) => {
  3545. if (e.which == 2) {
  3546. panning = false;
  3547. Object.keys(entities).forEach((key) => {
  3548. document
  3549. .querySelector("#entity-" + key)
  3550. .classList.remove("no-transition");
  3551. });
  3552. }
  3553. });
  3554. document.querySelector("#world").addEventListener("touchstart", (e) => {
  3555. if (!rulerMode) {
  3556. panning = true;
  3557. panOffsetX = e.touches[0].clientX;
  3558. panOffsetY = e.touches[0].clientY;
  3559. e.preventDefault();
  3560. Object.keys(entities).forEach((key) => {
  3561. document
  3562. .querySelector("#entity-" + key)
  3563. .classList.add("no-transition");
  3564. });
  3565. }
  3566. });
  3567. document.querySelector("#world").addEventListener("touchend", (e) => {
  3568. panning = false;
  3569. Object.keys(entities).forEach((key) => {
  3570. document
  3571. .querySelector("#entity-" + key)
  3572. .classList.remove("no-transition");
  3573. });
  3574. });
  3575. document.querySelector("#world").addEventListener("mousedown", (e) => {
  3576. // only left mouse clicks
  3577. if (e.which == 1 && rulerMode) {
  3578. let entX = document
  3579. .querySelector("#entities")
  3580. .getBoundingClientRect().x;
  3581. let entY = document
  3582. .querySelector("#entities")
  3583. .getBoundingClientRect().y;
  3584. let pos = pix2pos({ x: e.clientX - entX, y: e.clientY - entY });
  3585. if (config.rulersStick && selected) {
  3586. pos = entityRelativePosition(pos, selected);
  3587. }
  3588. currentRuler = {
  3589. x0: pos.x,
  3590. y0: pos.y,
  3591. x1: pos.y,
  3592. y1: pos.y,
  3593. entityKey: null,
  3594. };
  3595. if (config.rulersStick && selected) {
  3596. currentRuler.entityKey = selected.dataset.key;
  3597. }
  3598. }
  3599. });
  3600. document.querySelector("#world").addEventListener("mouseup", (e) => {
  3601. // only left mouse clicks
  3602. if (e.which == 1 && currentRuler) {
  3603. rulers.push(currentRuler);
  3604. currentRuler = null;
  3605. rulerMode = false;
  3606. }
  3607. });
  3608. document.querySelector("#world").addEventListener("touchstart", (e) => {
  3609. if (rulerMode) {
  3610. let entX = document
  3611. .querySelector("#entities")
  3612. .getBoundingClientRect().x;
  3613. let entY = document
  3614. .querySelector("#entities")
  3615. .getBoundingClientRect().y;
  3616. let pos = pix2pos({
  3617. x: e.touches[0].clientX - entX,
  3618. y: e.touches[0].clientY - entY,
  3619. });
  3620. if (config.rulersStick && selected) {
  3621. pos = entityRelativePosition(pos, selected);
  3622. }
  3623. currentRuler = {
  3624. x0: pos.x,
  3625. y0: pos.y,
  3626. x1: pos.y,
  3627. y1: pos.y,
  3628. entityKey: null,
  3629. };
  3630. if (config.rulersStick && selected) {
  3631. currentRuler.entityKey = selected.dataset.key;
  3632. }
  3633. }
  3634. });
  3635. document.querySelector("#world").addEventListener("touchend", (e) => {
  3636. if (currentRuler) {
  3637. rulers.push(currentRuler);
  3638. currentRuler = null;
  3639. rulerMode = false;
  3640. }
  3641. });
  3642. document.querySelector("body").appendChild(testCtx.canvas);
  3643. world.addEventListener("mousedown", (e) => deselect(e));
  3644. world.addEventListener("touchstart", (e) =>
  3645. deselect({
  3646. which: 1,
  3647. })
  3648. );
  3649. document.querySelector("#entities").addEventListener("mousedown", deselect);
  3650. document.querySelector("#display").addEventListener("mousedown", deselect);
  3651. document.addEventListener("mouseup", (e) => clickUp(e));
  3652. document.addEventListener("touchend", (e) => {
  3653. const fakeEvent = {
  3654. target: e.target,
  3655. clientX: e.changedTouches[0].clientX,
  3656. clientY: e.changedTouches[0].clientY,
  3657. which: 1,
  3658. };
  3659. clickUp(fakeEvent);
  3660. });
  3661. const formList = document.querySelector("#entity-form");
  3662. formList.addEventListener("input", (e) => {
  3663. const entity = entities[selected.dataset.key];
  3664. entity.form = e.target.value;
  3665. const oldView = entity.currentView;
  3666. entity.view = entity.formViews[entity.form];
  3667. // to set the size properly, even if we use a non-default view
  3668. if (Object.keys(entity.forms).length > 0)
  3669. entity.views[entity.view].height =
  3670. entity.formSizes[entity.form].height;
  3671. let found = Object.entries(entity.views).find(([key, view]) => {
  3672. return view.form === entity.form && view.name === oldView.name;
  3673. });
  3674. const newView = found ? found[0] : entity.formViews[entity.form];
  3675. entity.view = newView;
  3676. preloadViews(entity);
  3677. configViewList(entity, entity.view);
  3678. const image = entity.views[entity.view].image;
  3679. selected.querySelector(".entity-image").src = image.source;
  3680. configViewOptions(entity, entity.view);
  3681. displayAttribution(image.source);
  3682. if (image.bottom !== undefined) {
  3683. selected
  3684. .querySelector(".entity-image")
  3685. .style.setProperty("--offset", (-1 + image.bottom) * 100 + "%");
  3686. } else {
  3687. selected
  3688. .querySelector(".entity-image")
  3689. .style.setProperty("--offset", -1 * 100 + "%");
  3690. }
  3691. if (config.autoFitSize) {
  3692. let targets = {};
  3693. targets[selected.dataset.key] = entities[selected.dataset.key];
  3694. fitEntities(targets);
  3695. }
  3696. configSizeList(entity);
  3697. updateSizes();
  3698. updateEntityOptions(entities[selected.dataset.key], e.target.value);
  3699. updateViewOptions(entities[selected.dataset.key], entity.view);
  3700. });
  3701. const viewList = document.querySelector("#entity-view");
  3702. document.querySelector("#entity-view").addEventListener("input", (e) => {
  3703. const entity = entities[selected.dataset.key];
  3704. entity.view = e.target.value;
  3705. preloadViews(entity);
  3706. const image =
  3707. entities[selected.dataset.key].views[e.target.value].image;
  3708. selected.querySelector(".entity-image").src = image.source;
  3709. configViewOptions(entity, entity.view);
  3710. displayAttribution(image.source);
  3711. if (image.bottom !== undefined) {
  3712. selected
  3713. .querySelector(".entity-image")
  3714. .style.setProperty("--offset", (-1 + image.bottom) * 100 + "%");
  3715. } else {
  3716. selected
  3717. .querySelector(".entity-image")
  3718. .style.setProperty("--offset", -1 * 100 + "%");
  3719. }
  3720. updateSizes();
  3721. updateEntityOptions(entities[selected.dataset.key], e.target.value);
  3722. updateViewOptions(entities[selected.dataset.key], e.target.value);
  3723. });
  3724. document.querySelector("#entity-view").addEventListener("input", (e) => {
  3725. if (
  3726. viewList.options[viewList.selectedIndex].classList.contains("nsfw")
  3727. ) {
  3728. viewList.classList.add("nsfw");
  3729. } else {
  3730. viewList.classList.remove("nsfw");
  3731. }
  3732. });
  3733. clearViewList();
  3734. document.querySelector("#menu-clear").addEventListener("click", (e) => {
  3735. removeAllEntities();
  3736. });
  3737. document.querySelector("#delete-entity").disabled = true;
  3738. document.querySelector("#delete-entity").addEventListener("click", (e) => {
  3739. if (selected) {
  3740. removeEntity(selected);
  3741. selected = null;
  3742. }
  3743. });
  3744. document
  3745. .querySelector("#menu-order-height")
  3746. .addEventListener("click", (e) => {
  3747. const order = Object.keys(entities).sort((a, b) => {
  3748. const entA = entities[a];
  3749. const entB = entities[b];
  3750. const viewA = entA.view;
  3751. const viewB = entB.view;
  3752. const heightA = entA.views[viewA].height.to("meter").value;
  3753. const heightB = entB.views[viewB].height.to("meter").value;
  3754. return heightA - heightB;
  3755. });
  3756. arrangeEntities(order);
  3757. });
  3758. // TODO: write some generic logic for this lol
  3759. document
  3760. .querySelector("#scroll-left")
  3761. .addEventListener("mousedown", (e) => {
  3762. scrollDirection = -1;
  3763. clearInterval(scrollHandle);
  3764. scrollHandle = setInterval(doXScroll, 1000 / 20);
  3765. e.stopPropagation();
  3766. });
  3767. document
  3768. .querySelector("#scroll-right")
  3769. .addEventListener("mousedown", (e) => {
  3770. scrollDirection = 1;
  3771. clearInterval(scrollHandle);
  3772. scrollHandle = setInterval(doXScroll, 1000 / 20);
  3773. e.stopPropagation();
  3774. });
  3775. document
  3776. .querySelector("#scroll-left")
  3777. .addEventListener("touchstart", (e) => {
  3778. scrollDirection = -1;
  3779. clearInterval(scrollHandle);
  3780. scrollHandle = setInterval(doXScroll, 1000 / 20);
  3781. e.stopPropagation();
  3782. });
  3783. document
  3784. .querySelector("#scroll-right")
  3785. .addEventListener("touchstart", (e) => {
  3786. scrollDirection = 1;
  3787. clearInterval(scrollHandle);
  3788. scrollHandle = setInterval(doXScroll, 1000 / 20);
  3789. e.stopPropagation();
  3790. });
  3791. document.querySelector("#scroll-up").addEventListener("mousedown", (e) => {
  3792. if (config.lockYAxis) {
  3793. moveGround(true);
  3794. } else {
  3795. scrollDirection = 1;
  3796. clearInterval(scrollHandle);
  3797. scrollHandle = setInterval(doYScroll, 1000 / 20);
  3798. e.stopPropagation();
  3799. }
  3800. });
  3801. document
  3802. .querySelector("#scroll-down")
  3803. .addEventListener("mousedown", (e) => {
  3804. if (config.lockYAxis) {
  3805. moveGround(false);
  3806. } else {
  3807. scrollDirection = -1;
  3808. clearInterval(scrollHandle);
  3809. scrollHandle = setInterval(doYScroll, 1000 / 20);
  3810. e.stopPropagation();
  3811. }
  3812. });
  3813. document.querySelector("#scroll-up").addEventListener("touchstart", (e) => {
  3814. if (config.lockYAxis) {
  3815. moveGround(true);
  3816. } else {
  3817. scrollDirection = 1;
  3818. clearInterval(scrollHandle);
  3819. scrollHandle = setInterval(doYScroll, 1000 / 20);
  3820. e.stopPropagation();
  3821. }
  3822. });
  3823. document
  3824. .querySelector("#scroll-down")
  3825. .addEventListener("touchstart", (e) => {
  3826. if (config.lockYAxis) {
  3827. moveGround(false);
  3828. } else {
  3829. scrollDirection = -1;
  3830. clearInterval(scrollHandle);
  3831. scrollHandle = setInterval(doYScroll, 1000 / 20);
  3832. e.stopPropagation();
  3833. }
  3834. });
  3835. document.addEventListener("mouseup", (e) => {
  3836. clearInterval(scrollHandle);
  3837. scrollHandle = null;
  3838. });
  3839. document.addEventListener("touchend", (e) => {
  3840. clearInterval(scrollHandle);
  3841. scrollHandle = null;
  3842. });
  3843. document.querySelector("#zoom-in").addEventListener("mousedown", (e) => {
  3844. zoomDirection = -1;
  3845. clearInterval(zoomHandle);
  3846. zoomHandle = setInterval(doZoom, 1000 / 20);
  3847. e.stopPropagation();
  3848. });
  3849. document.querySelector("#zoom-out").addEventListener("mousedown", (e) => {
  3850. zoomDirection = 1;
  3851. clearInterval(zoomHandle);
  3852. zoomHandle = setInterval(doZoom, 1000 / 20);
  3853. e.stopPropagation();
  3854. });
  3855. document.querySelector("#zoom-in").addEventListener("touchstart", (e) => {
  3856. zoomDirection = -1;
  3857. clearInterval(zoomHandle);
  3858. zoomHandle = setInterval(doZoom, 1000 / 20);
  3859. e.stopPropagation();
  3860. });
  3861. document.querySelector("#zoom-out").addEventListener("touchstart", (e) => {
  3862. zoomDirection = 1;
  3863. clearInterval(zoomHandle);
  3864. zoomHandle = setInterval(doZoom, 1000 / 20);
  3865. e.stopPropagation();
  3866. });
  3867. document.addEventListener("mouseup", (e) => {
  3868. clearInterval(zoomHandle);
  3869. zoomHandle = null;
  3870. });
  3871. document.addEventListener("touchend", (e) => {
  3872. clearInterval(zoomHandle);
  3873. zoomHandle = null;
  3874. });
  3875. document.querySelector("#shrink").addEventListener("mousedown", (e) => {
  3876. sizeDirection = -1;
  3877. clearInterval(sizeHandle);
  3878. sizeHandle = setInterval(doSize, 1000 / 20);
  3879. e.stopPropagation();
  3880. });
  3881. document.querySelector("#grow").addEventListener("mousedown", (e) => {
  3882. sizeDirection = 1;
  3883. clearInterval(sizeHandle);
  3884. sizeHandle = setInterval(doSize, 1000 / 20);
  3885. e.stopPropagation();
  3886. });
  3887. document.querySelector("#shrink").addEventListener("touchstart", (e) => {
  3888. sizeDirection = -1;
  3889. clearInterval(sizeHandle);
  3890. sizeHandle = setInterval(doSize, 1000 / 20);
  3891. e.stopPropagation();
  3892. });
  3893. document.querySelector("#grow").addEventListener("touchstart", (e) => {
  3894. sizeDirection = 1;
  3895. clearInterval(sizeHandle);
  3896. sizeHandle = setInterval(doSize, 1000 / 20);
  3897. e.stopPropagation();
  3898. });
  3899. document.addEventListener("mouseup", (e) => {
  3900. clearInterval(sizeHandle);
  3901. sizeHandle = null;
  3902. });
  3903. document.addEventListener("touchend", (e) => {
  3904. clearInterval(sizeHandle);
  3905. sizeHandle = null;
  3906. });
  3907. document.querySelector("#ruler").addEventListener("click", (e) => {
  3908. rulerMode = !rulerMode;
  3909. if (rulerMode) {
  3910. toast("Ready to draw a ruler mark");
  3911. } else {
  3912. toast("Cancelled ruler mode");
  3913. }
  3914. });
  3915. document.querySelector("#ruler").addEventListener("mousedown", (e) => {
  3916. e.stopPropagation();
  3917. });
  3918. document.querySelector("#ruler").addEventListener("touchstart", (e) => {
  3919. e.stopPropagation();
  3920. });
  3921. document.querySelector("#fit").addEventListener("click", (e) => {
  3922. if (selected) {
  3923. let targets = {};
  3924. targets[selected.dataset.key] = entities[selected.dataset.key];
  3925. fitEntities(targets);
  3926. }
  3927. });
  3928. document.querySelector("#fit").addEventListener("mousedown", (e) => {
  3929. e.stopPropagation();
  3930. });
  3931. document.querySelector("#fit").addEventListener("touchstart", (e) => {
  3932. e.stopPropagation();
  3933. });
  3934. document
  3935. .querySelector("#options-world-fit")
  3936. .addEventListener("click", () => fitWorld(true));
  3937. document
  3938. .querySelector("#options-reset-pos-x")
  3939. .addEventListener("click", () => {
  3940. config.x = 0;
  3941. updateSizes();
  3942. });
  3943. document
  3944. .querySelector("#options-reset-pos-y")
  3945. .addEventListener("click", () => {
  3946. config.y = 0;
  3947. updateSizes();
  3948. });
  3949. document.addEventListener("keydown", (e) => {
  3950. if (e.key == "Delete" || e.key == "Backspace") {
  3951. if (selected) {
  3952. removeEntity(selected);
  3953. selected = null;
  3954. }
  3955. }
  3956. });
  3957. document.addEventListener("keydown", (e) => {
  3958. if (e.key == "Shift") {
  3959. shiftHeld = true;
  3960. e.preventDefault();
  3961. } else if (e.key == "Alt") {
  3962. altHeld = true;
  3963. movingInBounds = false; // don't snap the object back in bounds when we let go
  3964. e.preventDefault();
  3965. }
  3966. });
  3967. document.addEventListener("keyup", (e) => {
  3968. if (e.key == "Shift") {
  3969. shiftHeld = false;
  3970. e.preventDefault();
  3971. } else if (e.key == "Alt") {
  3972. altHeld = false;
  3973. e.preventDefault();
  3974. }
  3975. });
  3976. window.addEventListener("resize", handleResize);
  3977. // TODO: further investigate why the tool initially starts out with wrong
  3978. // values under certain circumstances (seems to be narrow aspect ratios -
  3979. // maybe the menu bar is animating when it shouldn't)
  3980. setTimeout(handleResize, 250);
  3981. setTimeout(handleResize, 500);
  3982. setTimeout(handleResize, 750);
  3983. setTimeout(handleResize, 1000);
  3984. document.querySelector("#menu-permalink").addEventListener("click", (e) => {
  3985. linkScene();
  3986. });
  3987. document.querySelector("#menu-export").addEventListener("click", (e) => {
  3988. copyScene();
  3989. });
  3990. document.querySelector("#menu-import").addEventListener("click", (e) => {
  3991. pasteScene();
  3992. });
  3993. document.querySelector("#menu-save").addEventListener("click", (e) => {
  3994. const name = document.querySelector("#menu-save ~ input").value;
  3995. if (/\S/.test(name)) {
  3996. saveScene(name);
  3997. }
  3998. updateSaveInfo();
  3999. });
  4000. document.querySelector("#menu-load").addEventListener("click", (e) => {
  4001. const name = document.querySelector("#menu-load ~ select").value;
  4002. if (/\S/.test(name)) {
  4003. loadScene(name);
  4004. }
  4005. });
  4006. document.querySelector("#menu-delete").addEventListener("click", (e) => {
  4007. const name = document.querySelector("#menu-delete ~ select").value;
  4008. if (/\S/.test(name)) {
  4009. deleteScene(name);
  4010. }
  4011. });
  4012. document
  4013. .querySelector("#menu-load-autosave")
  4014. .addEventListener("click", (e) => {
  4015. loadScene("autosave");
  4016. });
  4017. document.querySelector("#menu-add-image").addEventListener("click", (e) => {
  4018. document.querySelector("#file-upload-picker").click();
  4019. });
  4020. document
  4021. .querySelector("#file-upload-picker")
  4022. .addEventListener("change", (e) => {
  4023. if (e.target.files.length > 0) {
  4024. for (let i = 0; i < e.target.files.length; i++) {
  4025. customEntityFromFile(e.target.files[i]);
  4026. }
  4027. }
  4028. });
  4029. document
  4030. .querySelector("#menu-clear-rulers")
  4031. .addEventListener("click", (e) => {
  4032. rulers = [];
  4033. drawRulers();
  4034. });
  4035. document.addEventListener("paste", (e) => {
  4036. let index = 0;
  4037. let item = null;
  4038. let found = false;
  4039. for (; index < e.clipboardData.items.length; index++) {
  4040. item = e.clipboardData.items[index];
  4041. if (item.type == "image/png") {
  4042. found = true;
  4043. break;
  4044. }
  4045. }
  4046. if (!found) {
  4047. return;
  4048. }
  4049. let url = null;
  4050. const file = item.getAsFile();
  4051. customEntityFromFile(file);
  4052. });
  4053. document.querySelector("#world").addEventListener("dragover", (e) => {
  4054. e.preventDefault();
  4055. });
  4056. document.querySelector("#world").addEventListener("drop", (e) => {
  4057. e.preventDefault();
  4058. if (e.dataTransfer.files.length > 0) {
  4059. let entX = document
  4060. .querySelector("#entities")
  4061. .getBoundingClientRect().x;
  4062. let entY = document
  4063. .querySelector("#entities")
  4064. .getBoundingClientRect().y;
  4065. let coords = pix2pos({ x: e.clientX - entX, y: e.clientY - entY });
  4066. customEntityFromFile(e.dataTransfer.files[0], coords.x, coords.y);
  4067. }
  4068. });
  4069. clearEntityOptions();
  4070. clearViewOptions();
  4071. clearAttribution();
  4072. // we do this last because configuring settings can cause things
  4073. // to happen (e.g. auto-fit)
  4074. prepareSettings(getUserSettings());
  4075. // now that we have this loaded, we can set it
  4076. unitSelector.dataset.oldUnit = defaultUnits.length[config.units];
  4077. document.querySelector("#options-height-unit").value =
  4078. defaultUnits.length[config.units];
  4079. // ...and then update the world height by setting off an input event
  4080. document
  4081. .querySelector("#options-height-unit")
  4082. .dispatchEvent(new Event("input", {}));
  4083. if (param === null) {
  4084. scenes["Empty"]();
  4085. } else {
  4086. try {
  4087. const data = JSON.parse(b64DecodeUnicode(param));
  4088. if (data.entities === undefined) {
  4089. return;
  4090. }
  4091. if (data.world === undefined) {
  4092. return;
  4093. }
  4094. importScene(data);
  4095. } catch (err) {
  4096. console.error(err);
  4097. scenes["Empty"]();
  4098. // probably wasn't valid data
  4099. }
  4100. }
  4101. document.querySelector("#world").addEventListener("wheel", (e) => {
  4102. let magnitude = Math.abs(e.deltaY / 100);
  4103. if (shiftHeld) {
  4104. // macs do horizontal scrolling with shift held
  4105. let delta = e.deltaY;
  4106. if (e.deltaY == 0) {
  4107. magnitude = Math.abs(e.deltaX / 100);
  4108. delta = e.deltaX;
  4109. }
  4110. if (selected) {
  4111. let dir = delta > 0 ? 10 / 11 : 11 / 10;
  4112. dir -= 1;
  4113. dir *= magnitude;
  4114. dir += 1;
  4115. const entity = entities[selected.dataset.key];
  4116. entity.views[entity.view].height = math.multiply(
  4117. entity.views[entity.view].height,
  4118. dir
  4119. );
  4120. entity.dirty = true;
  4121. updateEntityOptions(entity, entity.view);
  4122. updateViewOptions(entity, entity.view);
  4123. updateSizes(true);
  4124. } else {
  4125. const worldWidth =
  4126. (config.height.toNumber("meters") / canvasHeight) *
  4127. canvasWidth;
  4128. config.x += ((e.deltaY > 0 ? 1 : -1) * worldWidth) / 20;
  4129. updateSizes();
  4130. updateSizes();
  4131. }
  4132. } else {
  4133. if (config.autoFit) {
  4134. toastRateLimit(
  4135. "Zoom is locked! Check Settings to disable.",
  4136. "zoom-lock",
  4137. 1000
  4138. );
  4139. } else {
  4140. let dir = e.deltaY < 0 ? 10 / 11 : 11 / 10;
  4141. dir -= 1;
  4142. dir *= magnitude;
  4143. dir += 1;
  4144. const change =
  4145. config.height.toNumber("meters") -
  4146. math.multiply(config.height, dir).toNumber("meters");
  4147. if (!config.lockYAxis) {
  4148. config.y += change / 2;
  4149. }
  4150. setWorldHeight(
  4151. config.height,
  4152. math.multiply(config.height, dir)
  4153. );
  4154. updateWorldOptions();
  4155. }
  4156. }
  4157. checkFitWorld();
  4158. });
  4159. document.addEventListener("mousemove", (e) => {
  4160. if (currentRuler) {
  4161. let entX = document
  4162. .querySelector("#entities")
  4163. .getBoundingClientRect().x;
  4164. let entY = document
  4165. .querySelector("#entities")
  4166. .getBoundingClientRect().y;
  4167. let position = pix2pos({
  4168. x: e.clientX - entX,
  4169. y: e.clientY - entY,
  4170. });
  4171. if (config.rulersStick && selected) {
  4172. position = entityRelativePosition(position, selected);
  4173. }
  4174. currentRuler.x1 = position.x;
  4175. currentRuler.y1 = position.y;
  4176. }
  4177. drawRulers();
  4178. });
  4179. document.addEventListener("touchmove", (e) => {
  4180. if (currentRuler) {
  4181. let entX = document
  4182. .querySelector("#entities")
  4183. .getBoundingClientRect().x;
  4184. let entY = document
  4185. .querySelector("#entities")
  4186. .getBoundingClientRect().y;
  4187. let position = pix2pos({
  4188. x: e.touches[0].clientX - entX,
  4189. y: e.touches[0].clientY - entY,
  4190. });
  4191. if (config.rulersStick && selected) {
  4192. position = entityRelativePosition(position, selected);
  4193. }
  4194. currentRuler.x1 = position.x;
  4195. currentRuler.y1 = position.y;
  4196. }
  4197. drawRulers();
  4198. });
  4199. document.addEventListener("mousemove", (e) => {
  4200. if (clicked) {
  4201. let position = pix2pos({
  4202. x: e.clientX - dragOffsetX,
  4203. y: e.clientY - dragOffsetY,
  4204. });
  4205. if (movingInBounds) {
  4206. position = snapPos(position);
  4207. } else {
  4208. let x = e.clientX - dragOffsetX;
  4209. let y = e.clientY - dragOffsetY;
  4210. if (x >= 0 && x <= canvasWidth && y >= 0 && y <= canvasHeight) {
  4211. movingInBounds = true;
  4212. }
  4213. }
  4214. clicked.dataset.x = position.x;
  4215. clicked.dataset.y = position.y;
  4216. updateEntityElement(entities[clicked.dataset.key], clicked);
  4217. if (hoveringInDeleteArea(e)) {
  4218. document
  4219. .querySelector("#menubar")
  4220. .classList.add("hover-delete");
  4221. } else {
  4222. document
  4223. .querySelector("#menubar")
  4224. .classList.remove("hover-delete");
  4225. }
  4226. }
  4227. if (panning && panReady) {
  4228. const worldWidth =
  4229. (config.height.toNumber("meters") / canvasHeight) * canvasWidth;
  4230. const worldHeight = config.height.toNumber("meters");
  4231. config.x -= ((e.clientX - panOffsetX) / canvasWidth) * worldWidth;
  4232. config.y += ((e.clientY - panOffsetY) / canvasHeight) * worldHeight;
  4233. panOffsetX = e.clientX;
  4234. panOffsetY = e.clientY;
  4235. updateSizes();
  4236. panReady = false;
  4237. setTimeout(() => (panReady = true), 1000 / 120);
  4238. }
  4239. });
  4240. document.addEventListener(
  4241. "touchmove",
  4242. (e) => {
  4243. if (clicked) {
  4244. e.preventDefault();
  4245. let x = e.touches[0].clientX;
  4246. let y = e.touches[0].clientY;
  4247. const position = snapPos(
  4248. pix2pos({ x: x - dragOffsetX, y: y - dragOffsetY })
  4249. );
  4250. clicked.dataset.x = position.x;
  4251. clicked.dataset.y = position.y;
  4252. updateEntityElement(entities[clicked.dataset.key], clicked);
  4253. // what a hack
  4254. // I should centralize this 'fake event' creation...
  4255. if (hoveringInDeleteArea({ clientY: y })) {
  4256. document
  4257. .querySelector("#menubar")
  4258. .classList.add("hover-delete");
  4259. } else {
  4260. document
  4261. .querySelector("#menubar")
  4262. .classList.remove("hover-delete");
  4263. }
  4264. }
  4265. if (panning && panReady) {
  4266. const worldWidth =
  4267. (config.height.toNumber("meters") / canvasHeight) *
  4268. canvasWidth;
  4269. const worldHeight = config.height.toNumber("meters");
  4270. config.x -=
  4271. ((e.touches[0].clientX - panOffsetX) / canvasWidth) *
  4272. worldWidth;
  4273. config.y +=
  4274. ((e.touches[0].clientY - panOffsetY) / canvasHeight) *
  4275. worldHeight;
  4276. panOffsetX = e.touches[0].clientX;
  4277. panOffsetY = e.touches[0].clientY;
  4278. updateSizes();
  4279. panReady = false;
  4280. setTimeout(() => (panReady = true), 1000 / 60);
  4281. }
  4282. },
  4283. { passive: false }
  4284. );
  4285. updateWorldHeight();
  4286. document
  4287. .querySelector("#search-box")
  4288. .addEventListener("change", (e) => doSearch(e.target.value));
  4289. document
  4290. .querySelector("#search-box")
  4291. .addEventListener("keydown", e => e.stopPropagation());
  4292. // Webkit doesn't draw resized SVGs correctly. It will always draw them at their intrinsic size, I think
  4293. // This checks for that.
  4294. webkitBugTest.onload = () => {
  4295. testCtx.canvas.width = 500;
  4296. testCtx.canvas.height = 500;
  4297. testCtx.clearRect(0, 0, 500, 500);
  4298. testCtx.drawImage(webkitBugTest, 0, 0, 500, 500);
  4299. webkitCanvasBug = testCtx.getImageData(250, 250, 1, 1).data[3] == 0;
  4300. if (webkitCanvasBug) {
  4301. toast(
  4302. "Heads up: Safari can't select through gaps or take screenshots (check the console for info!)"
  4303. );
  4304. console.log(
  4305. "Webkit messes up the process of drawing an SVG image to a canvas. This is important for both selecting things (it lets you click through a gap and hit something else) and for taking screenshots (since it needs to render them to a canvas). Sorry :("
  4306. );
  4307. }
  4308. };
  4309. updateFilter();
  4310. });
  4311. let searchText = "";
  4312. function doSearch(value) {
  4313. searchText = value;
  4314. updateFilter();
  4315. }
  4316. function customEntityFromFile(file, x = 0.5, y = 0.5) {
  4317. file.arrayBuffer().then((buf) => {
  4318. arr = new Uint8Array(buf);
  4319. blob = new Blob([arr], { type: file.type });
  4320. url = window.URL.createObjectURL(blob);
  4321. makeCustomEntity(url, x, y);
  4322. });
  4323. }
  4324. function makeCustomEntity(url, x = 0.5, y = 0.5) {
  4325. const maker = createEntityMaker(
  4326. {
  4327. name: "Custom Entity",
  4328. },
  4329. {
  4330. custom: {
  4331. attributes: {
  4332. height: {
  4333. name: "Height",
  4334. power: 1,
  4335. type: "length",
  4336. base: math.unit(6, "feet"),
  4337. },
  4338. },
  4339. image: {
  4340. source: url,
  4341. },
  4342. name: "Image",
  4343. info: {},
  4344. rename: false,
  4345. },
  4346. },
  4347. []
  4348. );
  4349. const entity = maker.constructor();
  4350. entity.scale = config.height.toNumber("feet") / 20;
  4351. entity.ephemeral = true;
  4352. displayEntity(entity, "custom", x, y, true, true);
  4353. }
  4354. const filterDefs = {
  4355. author: {
  4356. id: "author",
  4357. name: "Authors",
  4358. extract: (maker) => (maker.authors ? maker.authors : []),
  4359. render: (author) => attributionData.people[author].name,
  4360. sort: (tag1, tag2) => tag1[1].localeCompare(tag2[1]),
  4361. },
  4362. owner: {
  4363. id: "owner",
  4364. name: "Owners",
  4365. extract: (maker) => (maker.owners ? maker.owners : []),
  4366. render: (owner) => attributionData.people[owner].name,
  4367. sort: (tag1, tag2) => tag1[1].localeCompare(tag2[1]),
  4368. },
  4369. species: {
  4370. id: "species",
  4371. name: "Species",
  4372. extract: (maker) =>
  4373. maker.info && maker.info.species
  4374. ? getSpeciesInfo(maker.info.species)
  4375. : [],
  4376. render: (species) => speciesData[species].name,
  4377. sort: (tag1, tag2) => tag1[1].localeCompare(tag2[1]),
  4378. },
  4379. tags: {
  4380. id: "tags",
  4381. name: "Tags",
  4382. extract: (maker) =>
  4383. maker.info && maker.info.tags ? maker.info.tags : [],
  4384. render: (tag) => tagDefs[tag],
  4385. sort: (tag1, tag2) => tag1[1].localeCompare(tag2[1]),
  4386. },
  4387. size: {
  4388. id: "size",
  4389. name: "Normal Size",
  4390. extract: (maker) =>
  4391. maker.sizes && maker.sizes.length > 0
  4392. ? Array.from(
  4393. maker.sizes.reduce((result, size) => {
  4394. if (result && !size.default) {
  4395. return result;
  4396. }
  4397. let meters = size.height.toNumber("meters");
  4398. if (meters < 1e-1) {
  4399. return ["micro"];
  4400. } else if (meters < 1e1) {
  4401. return ["moderate"];
  4402. } else {
  4403. return ["macro"];
  4404. }
  4405. }, null)
  4406. )
  4407. : [],
  4408. render: (tag) => {
  4409. return {
  4410. micro: "Micro",
  4411. moderate: "Moderate",
  4412. macro: "Macro",
  4413. }[tag];
  4414. },
  4415. sort: (tag1, tag2) => {
  4416. const order = {
  4417. micro: 0,
  4418. moderate: 1,
  4419. macro: 2,
  4420. };
  4421. return order[tag1[0]] - order[tag2[0]];
  4422. },
  4423. },
  4424. allSizes: {
  4425. id: "allSizes",
  4426. name: "Possible Size",
  4427. extract: (maker) =>
  4428. maker.sizes
  4429. ? Array.from(
  4430. maker.sizes.reduce((set, size) => {
  4431. const height = size.height;
  4432. let result = Object.entries(sizeCategories).reduce(
  4433. (result, [name, value]) => {
  4434. if (result) {
  4435. return result;
  4436. } else {
  4437. if (math.compare(height, value) <= 0) {
  4438. return name;
  4439. }
  4440. }
  4441. },
  4442. null
  4443. );
  4444. set.add(result ? result : "infinite");
  4445. return set;
  4446. }, new Set())
  4447. )
  4448. : [],
  4449. render: (tag) => tag[0].toUpperCase() + tag.slice(1),
  4450. sort: (tag1, tag2) => {
  4451. const order = [
  4452. "atomic",
  4453. "microscopic",
  4454. "tiny",
  4455. "small",
  4456. "moderate",
  4457. "large",
  4458. "macro",
  4459. "megamacro",
  4460. "planetary",
  4461. "stellar",
  4462. "galactic",
  4463. "universal",
  4464. "omniversal",
  4465. "infinite",
  4466. ];
  4467. return order.indexOf(tag1[0]) - order.indexOf(tag2[0]);
  4468. },
  4469. },
  4470. };
  4471. const filterStates = {};
  4472. const sizeCategories = {
  4473. atomic: math.unit(100, "angstroms"),
  4474. microscopic: math.unit(100, "micrometers"),
  4475. tiny: math.unit(100, "millimeters"),
  4476. small: math.unit(1, "meter"),
  4477. moderate: math.unit(3, "meters"),
  4478. large: math.unit(10, "meters"),
  4479. macro: math.unit(300, "meters"),
  4480. megamacro: math.unit(1000, "kilometers"),
  4481. planetary: math.unit(10, "earths"),
  4482. stellar: math.unit(10, "solarradii"),
  4483. galactic: math.unit(10, "galaxies"),
  4484. universal: math.unit(10, "universes"),
  4485. omniversal: math.unit(10, "multiverses"),
  4486. };
  4487. function prepareEntities() {
  4488. availableEntities["buildings"] = makeBuildings();
  4489. availableEntities["characters"] = makeCharacters();
  4490. availableEntities["clothing"] = makeClothing();
  4491. availableEntities["creatures"] = makeCreatures();
  4492. availableEntities["fiction"] = makeFiction();
  4493. availableEntities["food"] = makeFood();
  4494. availableEntities["furniture"] = makeFurniture();
  4495. availableEntities["landmarks"] = makeLandmarks();
  4496. availableEntities["naturals"] = makeNaturals();
  4497. availableEntities["objects"] = makeObjects();
  4498. availableEntities["pokemon"] = makePokemon();
  4499. availableEntities["real-buildings"] = makeRealBuildings();
  4500. availableEntities["real-terrain"] = makeRealTerrains();
  4501. availableEntities["species"] = makeSpecies();
  4502. availableEntities["vehicles"] = makeVehicles();
  4503. availableEntities["species"].forEach((x) => {
  4504. if (x.name == "Human") {
  4505. availableEntities["food"].push(x);
  4506. }
  4507. });
  4508. availableEntities["characters"].sort((x, y) => {
  4509. return x.name.localeCompare(y.name);
  4510. });
  4511. availableEntities["species"].sort((x, y) => {
  4512. return x.name.localeCompare(y.name);
  4513. });
  4514. availableEntities["objects"].sort((x, y) => {
  4515. return x.name.localeCompare(y.name);
  4516. });
  4517. availableEntities["furniture"].sort((x, y) => {
  4518. return x.name.localeCompare(y.name);
  4519. });
  4520. const holder = document.querySelector("#spawners");
  4521. const filterMenu = document.querySelector("#filters-menu");
  4522. const categorySelect = document.createElement("select");
  4523. categorySelect.id = "category-picker";
  4524. holder.appendChild(categorySelect);
  4525. const filterSets = {};
  4526. Object.values(filterDefs).forEach((filter) => {
  4527. filterSets[filter.id] = new Set();
  4528. filterStates[filter.id] = false;
  4529. });
  4530. Object.entries(availableEntities).forEach(([category, entityList]) => {
  4531. const select = document.createElement("select");
  4532. select.id = "create-entity-" + category;
  4533. select.classList.add("entity-select");
  4534. for (let i = 0; i < entityList.length; i++) {
  4535. const entity = entityList[i];
  4536. const option = document.createElement("option");
  4537. option.value = i;
  4538. option.innerText = entity.name;
  4539. select.appendChild(option);
  4540. if (entity.nsfw) {
  4541. option.classList.add("nsfw");
  4542. }
  4543. Object.values(filterDefs).forEach((filter) => {
  4544. filter.extract(entity).forEach((result) => {
  4545. filterSets[filter.id].add(result);
  4546. });
  4547. });
  4548. availableEntitiesByName[entity.name] = entity;
  4549. }
  4550. select.addEventListener("change", (e) => {
  4551. if (
  4552. select.options[select.selectedIndex]?.classList.contains("nsfw")
  4553. ) {
  4554. select.classList.add("nsfw");
  4555. } else {
  4556. select.classList.remove("nsfw");
  4557. }
  4558. // preload the entity's first image
  4559. const entity = entityList[select.selectedIndex]?.constructor();
  4560. if (entity) {
  4561. let img = new Image();
  4562. img.src = entity.currentView.image.source;
  4563. }
  4564. });
  4565. const button = document.createElement("button");
  4566. button.id = "create-entity-" + category + "-button";
  4567. button.classList.add("entity-button");
  4568. button.innerHTML = '<i class="far fa-plus-square"></i>';
  4569. button.addEventListener("click", (e) => {
  4570. if (entityList[select.value] == null) return;
  4571. const newEntity = entityList[select.value].constructor();
  4572. let yOffset = 0;
  4573. if (config.lockYAxis) {
  4574. yOffset = getVerticalOffset();
  4575. } else {
  4576. yOffset = config.lockYAxis
  4577. ? 0
  4578. : config.height.toNumber("meters") / 2;
  4579. }
  4580. displayEntity(
  4581. newEntity,
  4582. newEntity.defaultView,
  4583. config.x,
  4584. config.y + yOffset,
  4585. true,
  4586. true
  4587. );
  4588. });
  4589. const categoryOption = document.createElement("option");
  4590. categoryOption.value = category;
  4591. categoryOption.innerText = category;
  4592. if (category == "characters") {
  4593. categoryOption.selected = true;
  4594. select.classList.add("category-visible");
  4595. button.classList.add("category-visible");
  4596. }
  4597. categorySelect.appendChild(categoryOption);
  4598. holder.appendChild(select);
  4599. holder.appendChild(button);
  4600. });
  4601. Object.values(filterDefs).forEach((filter) => {
  4602. const filterHolder = document.createElement("label");
  4603. filterHolder.setAttribute("for", "filter-toggle-" + filter.id);
  4604. filterHolder.classList.add("filter-holder");
  4605. const filterToggle = document.createElement("input");
  4606. filterToggle.type = "checkbox";
  4607. filterToggle.id = "filter-toggle-" + filter.id;
  4608. filterHolder.appendChild(filterToggle);
  4609. filterToggle.addEventListener("input", e => {
  4610. filterStates[filter.id] = filterToggle.checked
  4611. if (filterToggle.checked) {
  4612. filterHolder.classList.add("enabled");
  4613. } else {
  4614. filterHolder.classList.remove("enabled");
  4615. }
  4616. clearFilter();
  4617. updateFilter();
  4618. });
  4619. const filterLabel = document.createElement("div");
  4620. filterLabel.innerText = filter.name;
  4621. filterHolder.appendChild(filterLabel);
  4622. const filterNameSelect = document.createElement("select");
  4623. filterNameSelect.classList.add("filter-select");
  4624. filterNameSelect.id = "filter-" + filter.id;
  4625. filterHolder.appendChild(filterNameSelect);
  4626. filterMenu.appendChild(filterHolder);
  4627. Array.from(filterSets[filter.id])
  4628. .map((name) => [name, filter.render(name)])
  4629. .sort(filterDefs[filter.id].sort)
  4630. .forEach((name) => {
  4631. const option = document.createElement("option");
  4632. option.innerText = name[1];
  4633. option.value = name[0];
  4634. filterNameSelect.appendChild(option);
  4635. });
  4636. filterNameSelect.addEventListener("change", (e) => {
  4637. updateFilter();
  4638. });
  4639. });
  4640. const spawnButton = document.createElement("button");
  4641. spawnButton.id = "spawn-all"
  4642. spawnButton.addEventListener("click", e => {
  4643. spawnAll();
  4644. });
  4645. filterMenu.appendChild(spawnButton);
  4646. console.log(
  4647. "Loaded " + Object.keys(availableEntitiesByName).length + " entities"
  4648. );
  4649. categorySelect.addEventListener("input", (e) => {
  4650. const oldSelect = document.querySelector(
  4651. ".entity-select.category-visible"
  4652. );
  4653. oldSelect.classList.remove("category-visible");
  4654. const oldButton = document.querySelector(
  4655. ".entity-button.category-visible"
  4656. );
  4657. oldButton.classList.remove("category-visible");
  4658. const newSelect = document.querySelector(
  4659. "#create-entity-" + e.target.value
  4660. );
  4661. newSelect.classList.add("category-visible");
  4662. const newButton = document.querySelector(
  4663. "#create-entity-" + e.target.value + "-button"
  4664. );
  4665. newButton.classList.add("category-visible");
  4666. recomputeFilters();
  4667. updateFilter();
  4668. });
  4669. recomputeFilters();
  4670. ratioInfo = document.body.querySelector(".extra-info");
  4671. }
  4672. function spawnAll() {
  4673. const makers = Array.from(
  4674. document.querySelector(".entity-select.category-visible")
  4675. ).filter((element) => !element.classList.contains("filtered"));
  4676. const count = makers.length + 2;
  4677. let index = 1;
  4678. if (makers.length > 50) {
  4679. if (!confirm("Really spawn " + makers.length + " things at once?")) {
  4680. return;
  4681. }
  4682. }
  4683. const worldWidth =
  4684. (config.height.toNumber("meters") / canvasHeight) * canvasWidth;
  4685. const spawned = makers.map((element) => {
  4686. const category = document.querySelector("#category-picker").value;
  4687. const maker = availableEntities[category][element.value];
  4688. const entity = maker.constructor();
  4689. displayEntity(
  4690. entity,
  4691. entity.view,
  4692. -worldWidth * 0.45 +
  4693. config.x +
  4694. (worldWidth * 0.9 * index) / (count - 1),
  4695. config.y
  4696. );
  4697. index += 1;
  4698. return entityIndex - 1;
  4699. });
  4700. updateSizes(true);
  4701. if (config.autoFitAdd) {
  4702. let targets = {};
  4703. spawned.forEach((key) => {
  4704. targets[key] = entities[key];
  4705. });
  4706. fitEntities(targets);
  4707. }
  4708. }
  4709. // Only display authors and owners if they appear
  4710. // somewhere in the current entity list
  4711. function recomputeFilters() {
  4712. const category = document.querySelector("#category-picker").value;
  4713. const filterSets = {};
  4714. Object.values(filterDefs).forEach((filter) => {
  4715. filterSets[filter.id] = new Set();
  4716. });
  4717. availableEntities[category].forEach((entity) => {
  4718. Object.values(filterDefs).forEach((filter) => {
  4719. filter.extract(entity).forEach((result) => {
  4720. filterSets[filter.id].add(result);
  4721. });
  4722. });
  4723. });
  4724. Object.values(filterDefs).forEach((filter) => {
  4725. filterStates[filter.id] = false;
  4726. document.querySelector("#filter-toggle-" + filter.id).checked = false
  4727. document.querySelector("#filter-toggle-" + filter.id).dispatchEvent(new Event("click"))
  4728. // always show the "none" option
  4729. let found = filter.id == "none";
  4730. const filterSelect = document.querySelector("#filter-" + filter.id);
  4731. const filterSelectHolder = filterSelect.parentElement;
  4732. filterSelect.querySelectorAll("option").forEach((element) => {
  4733. if (
  4734. filterSets[filter.id].has(element.value) ||
  4735. filter.id == "none"
  4736. ) {
  4737. element.classList.remove("filtered");
  4738. element.disabled = false;
  4739. found = true;
  4740. } else {
  4741. element.classList.add("filtered");
  4742. element.disabled = true;
  4743. }
  4744. });
  4745. if (found) {
  4746. filterSelectHolder.style.display = "";
  4747. } else {
  4748. filterSelectHolder.style.display = "none";
  4749. }
  4750. });
  4751. }
  4752. function updateFilter() {
  4753. const category = document.querySelector("#category-picker").value;
  4754. const types = Object.values(filterDefs).filter(def => filterStates[def.id]).map(def => def.id)
  4755. const keys = {
  4756. }
  4757. types.forEach(type => {
  4758. const filterKeySelect = document.querySelector("#filter-" + type);
  4759. keys[type] = filterKeySelect.value;
  4760. })
  4761. clearFilter();
  4762. let current = document.querySelector(
  4763. ".entity-select.category-visible"
  4764. ).value;
  4765. let replace = current == "";
  4766. let first = null;
  4767. let count = 0;
  4768. const lowerSearchText = searchText !== "" ? searchText.toLowerCase() : null;
  4769. document
  4770. .querySelectorAll(".entity-select.category-visible > option")
  4771. .forEach((element) => {
  4772. let keep = true
  4773. types.forEach(type => {
  4774. if (
  4775. !(filterDefs[type]
  4776. .extract(availableEntities[category][element.value])
  4777. .indexOf(keys[type]) >= 0)
  4778. ) {
  4779. keep = false;
  4780. }
  4781. })
  4782. if (
  4783. searchText != "" &&
  4784. !availableEntities[category][element.value].name
  4785. .toLowerCase()
  4786. .includes(lowerSearchText)
  4787. ) {
  4788. keep = false;
  4789. }
  4790. if (!keep) {
  4791. element.classList.add("filtered");
  4792. element.disabled = true;
  4793. if (current == element.value) {
  4794. replace = true;
  4795. }
  4796. } else {
  4797. count += 1;
  4798. if (!first) {
  4799. first = element.value;
  4800. }
  4801. }
  4802. });
  4803. const button = document.querySelector("#spawn-all")
  4804. button.innerText = "Spawn " + count + " filtered " + (count == 1 ? "entity" : "entities") + ".";
  4805. if (replace) {
  4806. document.querySelector(".entity-select.category-visible").value = first;
  4807. document
  4808. .querySelector("#create-entity-" + category)
  4809. .dispatchEvent(new Event("change"));
  4810. }
  4811. }
  4812. function clearFilter() {
  4813. document
  4814. .querySelectorAll(".entity-select.category-visible > option")
  4815. .forEach((element) => {
  4816. element.classList.remove("filtered");
  4817. element.disabled = false;
  4818. });
  4819. }
  4820. function checkFitWorld() {
  4821. if (config.autoFit) {
  4822. fitWorld();
  4823. return true;
  4824. }
  4825. return false;
  4826. }
  4827. function fitWorld(manual = false, factor = 1.1) {
  4828. if (Object.keys(entities).length > 0) {
  4829. fitEntities(entities, factor);
  4830. }
  4831. }
  4832. function fitEntities(targetEntities, manual = false, factor = 1.1) {
  4833. let minX = Infinity;
  4834. let maxX = -Infinity;
  4835. let minY = Infinity;
  4836. let maxY = -Infinity;
  4837. let count = 0;
  4838. const worldWidth =
  4839. (config.height.toNumber("meters") / canvasHeight) * canvasWidth;
  4840. const worldHeight = config.height.toNumber("meters");
  4841. Object.entries(targetEntities).forEach(([key, entity]) => {
  4842. const view = entity.view;
  4843. let extra = entity.views[view].image.extra;
  4844. extra = extra === undefined ? 1 : extra;
  4845. const image = document.querySelector(
  4846. "#entity-" + key + " > .entity-image"
  4847. );
  4848. const x = parseFloat(
  4849. document.querySelector("#entity-" + key).dataset.x
  4850. );
  4851. let width = image.width;
  4852. let height = image.height;
  4853. // only really relevant if the images haven't loaded in yet
  4854. if (height == 0) {
  4855. height = 100;
  4856. }
  4857. if (width == 0) {
  4858. width = height;
  4859. }
  4860. const xBottom =
  4861. x -
  4862. (entity.views[view].height.toNumber("meters") * width) / height / 2;
  4863. const xTop =
  4864. x +
  4865. (entity.views[view].height.toNumber("meters") * width) / height / 2;
  4866. const y = parseFloat(
  4867. document.querySelector("#entity-" + key).dataset.y
  4868. );
  4869. const yBottom = y;
  4870. const yTop = entity.views[view].height.toNumber("meters") + yBottom;
  4871. minX = Math.min(minX, xBottom);
  4872. maxX = Math.max(maxX, xTop);
  4873. minY = Math.min(minY, yBottom);
  4874. maxY = Math.max(maxY, yTop);
  4875. count += 1;
  4876. });
  4877. if (config.lockYAxis) {
  4878. minY = 0;
  4879. }
  4880. let ySize = (maxY - minY) * factor;
  4881. let xSize = (maxX - minX) * factor;
  4882. if (xSize / ySize > worldWidth / worldHeight) {
  4883. ySize *= xSize / ySize / (worldWidth / worldHeight);
  4884. }
  4885. config.x = (maxX + minX) / 2;
  4886. config.y = minY;
  4887. height = math.unit(ySize, "meter");
  4888. setWorldHeight(config.height, math.multiply(height, factor));
  4889. }
  4890. function updateWorldHeight() {
  4891. const unit = document.querySelector("#options-height-unit").value;
  4892. const rawValue = document.querySelector("#options-height-value").value;
  4893. var value;
  4894. try {
  4895. value = math.evaluate(rawValue);
  4896. if (typeof value !== "number") {
  4897. try {
  4898. value = value.toNumber(unit);
  4899. } catch {
  4900. toast(
  4901. "Invalid input: " +
  4902. rawValue +
  4903. " can't be converted to " +
  4904. unit
  4905. );
  4906. }
  4907. }
  4908. } catch {
  4909. toast("Invalid input: could not parse " + rawValue);
  4910. return;
  4911. }
  4912. const newHeight = Math.max(0.000000001, value);
  4913. const oldHeight = config.height;
  4914. setWorldHeight(oldHeight, math.unit(newHeight, unit), true);
  4915. }
  4916. function setWorldHeight(oldHeight, newHeight, keepUnit = false) {
  4917. worldSizeDirty = true;
  4918. config.height = newHeight.to(
  4919. document.querySelector("#options-height-unit").value
  4920. );
  4921. const unit = document.querySelector("#options-height-unit").value;
  4922. setNumericInput(
  4923. document.querySelector("#options-height-value"),
  4924. config.height.toNumber(unit)
  4925. );
  4926. Object.entries(entities).forEach(([key, entity]) => {
  4927. const element = document.querySelector("#entity-" + key);
  4928. let newPosition;
  4929. if (altHeld) {
  4930. newPosition = adjustAbs(
  4931. { x: element.dataset.x, y: element.dataset.y },
  4932. oldHeight,
  4933. config.height
  4934. );
  4935. } else {
  4936. newPosition = { x: element.dataset.x, y: element.dataset.y };
  4937. }
  4938. element.dataset.x = newPosition.x;
  4939. element.dataset.y = newPosition.y;
  4940. });
  4941. if (!keepUnit) {
  4942. pickUnit();
  4943. }
  4944. updateSizes();
  4945. }
  4946. function loadScene(name = "default") {
  4947. if (name === "") {
  4948. name = "default";
  4949. }
  4950. try {
  4951. const data = JSON.parse(
  4952. localStorage.getItem("macrovision-save-" + name)
  4953. );
  4954. if (data === null) {
  4955. console.error("Couldn't load " + name);
  4956. return false;
  4957. }
  4958. importScene(data);
  4959. toast("Loaded " + name);
  4960. return true;
  4961. } catch (err) {
  4962. alert(
  4963. "Something went wrong while loading (maybe you didn't have anything saved. Check the F12 console for the error."
  4964. );
  4965. console.error(err);
  4966. return false;
  4967. }
  4968. }
  4969. function saveScene(name = "default") {
  4970. try {
  4971. const string = JSON.stringify(exportScene());
  4972. localStorage.setItem("macrovision-save-" + name, string);
  4973. toast("Saved as " + name);
  4974. } catch (err) {
  4975. alert(
  4976. "Something went wrong while saving (maybe I don't have localStorage permissions, or exporting failed). Check the F12 console for the error."
  4977. );
  4978. console.error(err);
  4979. }
  4980. }
  4981. function deleteScene(name = "default") {
  4982. if (confirm("Really delete the " + name + " scene?")) {
  4983. try {
  4984. localStorage.removeItem("macrovision-save-" + name);
  4985. toast("Deleted " + name);
  4986. } catch (err) {
  4987. console.error(err);
  4988. }
  4989. }
  4990. updateSaveInfo();
  4991. }
  4992. function exportScene() {
  4993. const results = {};
  4994. results.entities = [];
  4995. Object.entries(entities)
  4996. .filter(([key, entity]) => entity.ephemeral !== true)
  4997. .forEach(([key, entity]) => {
  4998. const element = document.querySelector("#entity-" + key);
  4999. results.entities.push({
  5000. name: entity.identifier,
  5001. customName: entity.name,
  5002. scale: entity.scale,
  5003. rotation: entity.rotation,
  5004. view: entity.view,
  5005. form: entity.form,
  5006. x: element.dataset.x,
  5007. y: element.dataset.y,
  5008. priority: entity.priority,
  5009. brightness: entity.brightness,
  5010. });
  5011. });
  5012. const unit = document.querySelector("#options-height-unit").value;
  5013. results.world = {
  5014. height: config.height.toNumber(unit),
  5015. unit: unit,
  5016. x: config.x,
  5017. y: config.y,
  5018. };
  5019. results.version = migrationDefs.length;
  5020. return results;
  5021. }
  5022. // btoa doesn't like anything that isn't ASCII
  5023. // great
  5024. // thanks to https://stackoverflow.com/questions/30106476/using-javascripts-atob-to-decode-base64-doesnt-properly-decode-utf-8-strings
  5025. // for providing an alternative
  5026. function b64EncodeUnicode(str) {
  5027. // first we use encodeURIComponent to get percent-encoded UTF-8,
  5028. // then we convert the percent encodings into raw bytes which
  5029. // can be fed into btoa.
  5030. return btoa(
  5031. encodeURIComponent(str).replace(
  5032. /%([0-9A-F]{2})/g,
  5033. function toSolidBytes(match, p1) {
  5034. return String.fromCharCode("0x" + p1);
  5035. }
  5036. )
  5037. );
  5038. }
  5039. function b64DecodeUnicode(str) {
  5040. // Going backwards: from bytestream, to percent-encoding, to original string.
  5041. return decodeURIComponent(
  5042. atob(str)
  5043. .split("")
  5044. .map(function (c) {
  5045. return "%" + ("00" + c.charCodeAt(0).toString(16)).slice(-2);
  5046. })
  5047. .join("")
  5048. );
  5049. }
  5050. function linkScene() {
  5051. loc = new URL(window.location);
  5052. const link =
  5053. loc.protocol +
  5054. "//" +
  5055. loc.host +
  5056. loc.pathname +
  5057. "#" +
  5058. b64EncodeUnicode(JSON.stringify(exportScene()));
  5059. window.history.replaceState(null, "Macrovision", link);
  5060. try {
  5061. navigator.clipboard.writeText(link);
  5062. toast("Copied permalink to clipboard");
  5063. } catch {
  5064. toast("Couldn't copy permalink");
  5065. }
  5066. }
  5067. function copyScene() {
  5068. const results = exportScene();
  5069. navigator.clipboard.writeText(JSON.stringify(results));
  5070. }
  5071. function pasteScene() {
  5072. try {
  5073. navigator.clipboard
  5074. .readText()
  5075. .then((text) => {
  5076. const data = JSON.parse(text);
  5077. if (data.entities === undefined) {
  5078. return;
  5079. }
  5080. if (data.world === undefined) {
  5081. return;
  5082. }
  5083. importScene(data);
  5084. })
  5085. .catch((err) => alert(err));
  5086. } catch (err) {
  5087. console.error(err);
  5088. // probably wasn't valid data
  5089. }
  5090. }
  5091. // TODO - don't just search through every single entity
  5092. // probably just have a way to do lookups directly
  5093. function findEntity(name) {
  5094. return availableEntitiesByName[name];
  5095. }
  5096. const migrationDefs = [
  5097. /*
  5098. Migration: 0 -> 1
  5099. Adds x and y coordinates for the camera
  5100. */
  5101. (data) => {
  5102. data.world.x = 0;
  5103. data.world.y = 0;
  5104. },
  5105. /*
  5106. Migration: 1 -> 2
  5107. Adds priority and brightness to each entity
  5108. */
  5109. (data) => {
  5110. data.entities.forEach((entity) => {
  5111. entity.priority = 0;
  5112. entity.brightness = 1;
  5113. });
  5114. },
  5115. /*
  5116. Migration: 2 -> 3
  5117. Custom names are exported
  5118. */
  5119. (data) => {
  5120. data.entities.forEach((entity) => {
  5121. entity.customName = entity.name;
  5122. });
  5123. },
  5124. /*
  5125. Migration: 3 -> 4
  5126. Rotation is now stored
  5127. */
  5128. (data) => {
  5129. data.entities.forEach((entity) => {
  5130. entity.rotation = 0;
  5131. });
  5132. },
  5133. ];
  5134. function migrateScene(data) {
  5135. if (data.version === undefined) {
  5136. alert(
  5137. "This save was created before save versions were tracked. The scene may import incorrectly."
  5138. );
  5139. console.trace();
  5140. data.version = 0;
  5141. } else if (data.version < migrationDefs.length) {
  5142. migrationDefs[data.version](data);
  5143. data.version += 1;
  5144. migrateScene(data);
  5145. }
  5146. }
  5147. function importScene(data) {
  5148. removeAllEntities();
  5149. migrateScene(data);
  5150. data.entities.forEach((entityInfo) => {
  5151. const entity = findEntity(entityInfo.name).constructor();
  5152. entity.name = entityInfo.customName;
  5153. entity.scale = entityInfo.scale;
  5154. entity.rotation = entityInfo.rotation;
  5155. entity.priority = entityInfo.priority;
  5156. entity.brightness = entityInfo.brightness;
  5157. entity.form = entityInfo.form;
  5158. displayEntity(entity, entityInfo.view, entityInfo.x, entityInfo.y);
  5159. });
  5160. config.height = math.unit(data.world.height, data.world.unit);
  5161. config.x = data.world.x;
  5162. config.y = data.world.y;
  5163. const height = math
  5164. .unit(data.world.height, data.world.unit)
  5165. .toNumber(defaultUnits.length[config.units]);
  5166. document.querySelector("#options-height-value").value = height;
  5167. document.querySelector("#options-height-unit").dataset.oldUnit =
  5168. defaultUnits.length[config.units];
  5169. document.querySelector("#options-height-unit").value =
  5170. defaultUnits.length[config.units];
  5171. if (data.canvasWidth) {
  5172. doHorizReposition(data.canvasWidth / canvasWidth);
  5173. }
  5174. updateSizes();
  5175. }
  5176. function renderToCanvas() {
  5177. const ctx = document.querySelector("#display").getContext("2d");
  5178. Object.entries(entities)
  5179. .sort((ent1, ent2) => {
  5180. z1 = document.querySelector("#entity-" + ent1[0]).style.zIndex;
  5181. z2 = document.querySelector("#entity-" + ent2[0]).style.zIndex;
  5182. return z1 - z2;
  5183. })
  5184. .forEach(([id, entity]) => {
  5185. element = document.querySelector("#entity-" + id);
  5186. img = element.querySelector("img");
  5187. let x = parseFloat(element.dataset.x);
  5188. let y = parseFloat(element.dataset.y);
  5189. let coords = pos2pix({ x: x, y: y });
  5190. let offset = img.style.getPropertyValue("--offset");
  5191. offset = parseFloat(offset.substring(0, offset.length - 1));
  5192. let xSize = img.width;
  5193. let ySize = img.height;
  5194. x = coords.x;
  5195. y = coords.y + ySize / 2 + (ySize * offset) / 100;
  5196. const oldFilter = ctx.filter;
  5197. const brightness =
  5198. getComputedStyle(element).getPropertyValue("--brightness");
  5199. ctx.filter = `brightness(${brightness})`;
  5200. ctx.save();
  5201. ctx.resetTransform();
  5202. ctx.scale(window.devicePixelRatio, window.devicePixelRatio);
  5203. ctx.translate(x, y);
  5204. ctx.rotate(entity.rotation);
  5205. ctx.drawImage(img, -xSize / 2, -ySize / 2, xSize, ySize);
  5206. ctx.restore();
  5207. ctx.filter = oldFilter;
  5208. });
  5209. ctx.save();
  5210. ctx.resetTransform();
  5211. ctx.drawImage(document.querySelector("#rulers"), 0, 0);
  5212. ctx.restore();
  5213. }
  5214. function exportCanvas(callback) {
  5215. /** @type {CanvasRenderingContext2D} */
  5216. const ctx = document.querySelector("#display").getContext("2d");
  5217. const blob = ctx.canvas.toBlob(callback);
  5218. }
  5219. function generateScreenshot(callback) {
  5220. /** @type {CanvasRenderingContext2D} */
  5221. const ctx = document.querySelector("#display").getContext("2d");
  5222. if (config.groundKind !== "none") {
  5223. ctx.fillStyle = backgroundColors[config.groundKind];
  5224. ctx.fillRect(
  5225. 0,
  5226. pos2pix({ x: 0, y: 0 }).y,
  5227. canvasWidth + 100,
  5228. canvasHeight
  5229. );
  5230. }
  5231. renderToCanvas();
  5232. ctx.resetTransform();
  5233. ctx.fillStyle = "#999";
  5234. ctx.font = "normal normal lighter 16pt coda";
  5235. ctx.fillText("macrovision.crux.sexy", 10, 25);
  5236. exportCanvas((blob) => {
  5237. callback(blob);
  5238. });
  5239. }
  5240. function copyScreenshot() {
  5241. if (window.ClipboardItem === undefined) {
  5242. alert(
  5243. "Sorry, this browser doesn't yet support writing images to the clipboard."
  5244. );
  5245. return;
  5246. }
  5247. generateScreenshot((blob) => {
  5248. navigator.clipboard
  5249. .write([
  5250. new ClipboardItem({
  5251. "image/png": blob,
  5252. }),
  5253. ])
  5254. .then((e) => toast("Copied to clipboard!"))
  5255. .catch((e) => {
  5256. console.error(e);
  5257. toast(
  5258. "Couldn't write to the clipboard. Make sure the screenshot completes before switching tabs. Also, currently busted in Safari :("
  5259. );
  5260. });
  5261. });
  5262. drawScales(false);
  5263. }
  5264. function saveScreenshot() {
  5265. generateScreenshot((blob) => {
  5266. const a = document.createElement("a");
  5267. a.href = URL.createObjectURL(blob);
  5268. a.setAttribute("download", "macrovision.png");
  5269. a.click();
  5270. });
  5271. drawScales(false);
  5272. }
  5273. function openScreenshot() {
  5274. generateScreenshot((blob) => {
  5275. const a = document.createElement("a");
  5276. a.href = URL.createObjectURL(blob);
  5277. a.setAttribute("target", "_blank");
  5278. a.click();
  5279. });
  5280. drawScales(false);
  5281. }
  5282. const rateLimits = {};
  5283. function toast(msg) {
  5284. let div = document.createElement("div");
  5285. div.innerHTML = msg;
  5286. div.classList.add("toast");
  5287. document.body.appendChild(div);
  5288. setTimeout(() => {
  5289. document.body.removeChild(div);
  5290. }, 5000);
  5291. }
  5292. function toastRateLimit(msg, key, delay) {
  5293. if (!rateLimits[key]) {
  5294. toast(msg);
  5295. rateLimits[key] = setTimeout(() => {
  5296. delete rateLimits[key];
  5297. }, delay);
  5298. }
  5299. }
  5300. let lastTime = undefined;
  5301. function pan(fromX, fromY, fromHeight, toX, toY, toHeight, duration) {
  5302. Object.keys(entities).forEach((key) => {
  5303. document.querySelector("#entity-" + key).classList.add("no-transition");
  5304. });
  5305. config.x = fromX;
  5306. config.y = fromY;
  5307. config.height = math.unit(fromHeight, "meters");
  5308. updateSizes();
  5309. lastTime = undefined;
  5310. requestAnimationFrame((timestamp) =>
  5311. panTo(
  5312. toX,
  5313. toY,
  5314. toHeight,
  5315. (toX - fromX) / duration,
  5316. (toY - fromY) / duration,
  5317. (toHeight - fromHeight) / duration,
  5318. timestamp,
  5319. duration
  5320. )
  5321. );
  5322. }
  5323. function panTo(
  5324. x,
  5325. y,
  5326. height,
  5327. xSpeed,
  5328. ySpeed,
  5329. heightSpeed,
  5330. timestamp,
  5331. remaining
  5332. ) {
  5333. if (lastTime === undefined) {
  5334. lastTime = timestamp;
  5335. }
  5336. dt = timestamp - lastTime;
  5337. remaining -= dt;
  5338. if (remaining < 0) {
  5339. dt += remaining;
  5340. }
  5341. let newX = config.x + xSpeed * dt;
  5342. let newY = config.y + ySpeed * dt;
  5343. let newHeight = config.height.toNumber("meters") + heightSpeed * dt;
  5344. if (remaining > 0) {
  5345. requestAnimationFrame((timestamp) =>
  5346. panTo(
  5347. x,
  5348. y,
  5349. height,
  5350. xSpeed,
  5351. ySpeed,
  5352. heightSpeed,
  5353. timestamp,
  5354. remaining
  5355. )
  5356. );
  5357. } else {
  5358. Object.keys(entities).forEach((key) => {
  5359. document
  5360. .querySelector("#entity-" + key)
  5361. .classList.remove("no-transition");
  5362. });
  5363. }
  5364. config.x = newX;
  5365. config.y = newY;
  5366. config.height = math.unit(newHeight, "meters");
  5367. updateSizes();
  5368. }
  5369. function getVerticalOffset() {
  5370. if (config.groundPos === "very-high") {
  5371. return (config.height.toNumber("meters") / 12) * 5;
  5372. } else if (config.groundPos === "high") {
  5373. return (config.height.toNumber("meters") / 12) * 4;
  5374. } else if (config.groundPos === "medium") {
  5375. return (config.height.toNumber("meters") / 12) * 3;
  5376. } else if (config.groundPos === "low") {
  5377. return (config.height.toNumber("meters") / 12) * 2;
  5378. } else if (config.groundPos === "very-low") {
  5379. return config.height.toNumber("meters") / 12;
  5380. } else {
  5381. return 0;
  5382. }
  5383. }
  5384. function moveGround(down) {
  5385. const index = groundPosChoices.indexOf(config.groundPos);
  5386. if (down) {
  5387. if (index < groundPosChoices.length - 1) {
  5388. config.groundPos = groundPosChoices[index + 1];
  5389. }
  5390. } else {
  5391. if (index > 0) {
  5392. config.groundPos = groundPosChoices[index - 1];
  5393. }
  5394. }
  5395. updateScrollButtons();
  5396. updateSizes();
  5397. }
  5398. function updateScrollButtons() {
  5399. const up = document.querySelector("#scroll-up");
  5400. const down = document.querySelector("#scroll-down");
  5401. up.disabled = false;
  5402. down.disabled = false;
  5403. document.querySelector("#setting-ground-pos").value = config.groundPos;
  5404. if (config.lockYAxis) {
  5405. const index = groundPosChoices.indexOf(config.groundPos);
  5406. if (index == 0) {
  5407. down.disabled = true;
  5408. }
  5409. if (index == groundPosChoices.length - 1) {
  5410. up.disabled = true;
  5411. }
  5412. }
  5413. }