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.
 
 
 

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