less copy protection, more size visualization
Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.
 
 
 

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