less copy protection, more size visualization
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

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