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.
 
 
 

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