less copy protection, more size visualization
Nie możesz wybrać więcej, niż 25 tematów Tematy muszą się zaczynać od litery lub cyfry, mogą zawierać myślniki ('-') i mogą mieć do 35 znaków.
 
 
 

5426 wiersze
165 KiB

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