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

6563 líneas
194 KiB

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