less copy protection, more size visualization
Du kannst nicht mehr als 25 Themen auswählen Themen müssen entweder mit einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.
 
 
 

5299 Zeilen
162 KiB

  1. let selected = null;
  2. let prevSelected = null;
  3. let selectedEntity = null;
  4. let prevSelectedEntity = null;
  5. let entityIndex = 0;
  6. let firsterror = true;
  7. let clicked = null;
  8. let movingInBounds = false;
  9. let dragging = false;
  10. let clickTimeout = null;
  11. let dragOffsetX = null;
  12. let dragOffsetY = null;
  13. let preloaded = new Set();
  14. let panning = false;
  15. let panReady = true;
  16. let panOffsetX = null;
  17. let panOffsetY = null;
  18. let shiftHeld = false;
  19. let altHeld = false;
  20. let entityX;
  21. let canvasWidth;
  22. let canvasHeight;
  23. let dragScale = 1;
  24. let dragScaleHandle = null;
  25. let dragEntityScale = 1;
  26. let dragEntityScaleHandle = null;
  27. let scrollDirection = 0;
  28. let scrollHandle = null;
  29. let zoomDirection = 0;
  30. let zoomHandle = null;
  31. let sizeDirection = 0;
  32. let sizeHandle = null;
  33. let worldSizeDirty = false;
  34. let rulerMode = false;
  35. let rulers = [];
  36. let currentRuler = undefined;
  37. const tagDefs = {
  38. "anthro": "Anthro",
  39. "feral": "Feral",
  40. "taur": "Taur",
  41. "naga": "Naga",
  42. "goo": "Goo"
  43. }
  44. math.createUnit("humans", {
  45. definition: "5.75 feet"
  46. });
  47. math.createUnit("story", {
  48. definition: "12 feet",
  49. prefixes: "long"
  50. });
  51. math.createUnit("stories", {
  52. definition: "12 feet",
  53. prefixes: "long"
  54. });
  55. math.createUnit("buses", {
  56. definition: "11.95 meters",
  57. prefixes: "long"
  58. });
  59. math.createUnit("marathons", {
  60. definition: "26.2 miles",
  61. prefixes: "long"
  62. });
  63. math.createUnit("timezones", {
  64. definition: "1037.54167 miles",
  65. prefixes: "long",
  66. aliases: ["timezone", "timezones"]
  67. });
  68. math.createUnit("nauticalMiles", {
  69. definition: "6080 feet",
  70. prefixes: "long",
  71. aliases: ["nauticalMile", "nauticalMiles"]
  72. });
  73. math.createUnit("fathoms", {
  74. definition: "6 feet",
  75. prefixes: "long",
  76. aliases: ["fathom", "fathoms"]
  77. });
  78. math.createUnit("earths", {
  79. definition: "12756km",
  80. prefixes: "long",
  81. aliases: ["earth", "earths", "Earth", "Earths"]
  82. });
  83. math.createUnit("lightsecond", {
  84. definition: "299792458 meters",
  85. prefixes: "long"
  86. });
  87. math.createUnit("lightseconds", {
  88. definition: "299792458 meters",
  89. prefixes: "long"
  90. });
  91. math.createUnit("parsec", {
  92. definition: "3.086e16 meters",
  93. prefixes: "long"
  94. })
  95. math.createUnit("parsecs", {
  96. definition: "3.086e16 meters",
  97. prefixes: "long"
  98. })
  99. math.createUnit("lightyears", {
  100. definition: "9.461e15 meters",
  101. prefixes: "long"
  102. })
  103. math.createUnit("AU", {
  104. definition: "149597870700 meters"
  105. })
  106. math.createUnit("AUs", {
  107. definition: "149597870700 meters"
  108. })
  109. math.createUnit("dalton", {
  110. definition: "1.66e-27 kg",
  111. prefixes: "long"
  112. });
  113. math.createUnit("daltons", {
  114. definition: "1.66e-27 kg",
  115. prefixes: "long"
  116. });
  117. math.createUnit("solarradii", {
  118. definition: "695990 km",
  119. prefixes: "long"
  120. });
  121. math.createUnit("solarmasses", {
  122. definition: "2e30 kg",
  123. prefixes: "long"
  124. });
  125. math.createUnit("galaxy", {
  126. definition: "105700 lightyears",
  127. prefixes: "long"
  128. });
  129. math.createUnit("galaxies", {
  130. definition: "105700 lightyears",
  131. prefixes: "long"
  132. });
  133. math.createUnit("universe", {
  134. definition: "93.016e9 lightyears",
  135. prefixes: "long"
  136. });
  137. math.createUnit("universes", {
  138. definition: "93.016e9 lightyears",
  139. prefixes: "long"
  140. });
  141. math.createUnit("multiverse", {
  142. definition: "1e30 lightyears",
  143. prefixes: "long"
  144. });
  145. math.createUnit("multiverses", {
  146. definition: "1e30 lightyears",
  147. prefixes: "long"
  148. });
  149. math.createUnit("footballFields", {
  150. definition: "57600 feet^2",
  151. prefixes: "long"
  152. });
  153. math.createUnit("people", {
  154. definition: "75 liters",
  155. prefixes: "long"
  156. });
  157. math.createUnit("shippingContainers", {
  158. definition: "1169 ft^3",
  159. prefixes: "long"
  160. });
  161. math.createUnit("olympicPools", {
  162. definition: "2500 m^3",
  163. prefixes: "long"
  164. });
  165. math.createUnit("oceans", {
  166. definition: "700000000 km^3",
  167. prefixes: "long"
  168. });
  169. math.createUnit("earthVolumes", {
  170. definition: "1.0867813e12 km^3",
  171. prefixes: "long"
  172. });
  173. math.createUnit("universeVolumes", {
  174. definition: "4.2137775e+32 lightyears^3",
  175. prefixes: "long"
  176. });
  177. math.createUnit("multiverseVolumes", {
  178. definition: "5.2359878e+89 lightyears^3",
  179. prefixes: "long"
  180. });
  181. math.createUnit("peopleMass", {
  182. definition: "80 kg",
  183. prefixes: "long"
  184. });
  185. math.createUnit("cars", {
  186. definition: "1250kg",
  187. prefixes: "long"
  188. });
  189. math.createUnit("busMasses", {
  190. definition: "15000kg",
  191. prefixes: "long"
  192. });
  193. math.createUnit("earthMass", {
  194. definition: "5.97e24 kg",
  195. prefixes: "long"
  196. });
  197. math.createUnit("kcal", {
  198. definition: "4184 joules",
  199. prefixes: "long"
  200. })
  201. math.createUnit("foodPounds", {
  202. definition: "867 kcal",
  203. prefixes: "long"
  204. })
  205. math.createUnit("foodKilograms", {
  206. definition: "1909 kcal",
  207. prefixes: "long"
  208. })
  209. math.createUnit("peopleEaten", {
  210. definition: "125000 kcal",
  211. prefixes: "long"
  212. })
  213. math.createUnit("villagesEaten", {
  214. definition: "1000 peopleEaten",
  215. prefixes: "long"
  216. })
  217. math.createUnit("townsEaten", {
  218. definition: "10000 peopleEaten",
  219. prefixes: "long"
  220. })
  221. math.createUnit("citiesEaten", {
  222. definition: "100000 peopleEaten",
  223. prefixes: "long"
  224. })
  225. math.createUnit("metrosEaten", {
  226. definition: "1000000 peopleEaten",
  227. prefixes: "long"
  228. })
  229. math.createUnit("barn", {
  230. definition: "10e-28 m^2",
  231. prefixes: "long"
  232. })
  233. math.createUnit("barns", {
  234. definition: "10e-28 m^2",
  235. prefixes: "long"
  236. })
  237. math.createUnit("points", {
  238. definition: "0.013888888888888888888888888 inches",
  239. prefixes: "long"
  240. })
  241. math.createUnit("beardSeconds", {
  242. definition: "10 nanometers",
  243. prefixes: "long"
  244. })
  245. math.createUnit("smoots", {
  246. definition: "5.5833333 feet",
  247. prefixes: "long"
  248. })
  249. math.createUnit("furlongs", {
  250. definition: "660 feet",
  251. prefixes: "long"
  252. })
  253. math.createUnit("nanoacres", {
  254. definition: "1e-9 acres",
  255. prefixes: "long"
  256. })
  257. math.createUnit("barnMegaparsecs", {
  258. definition: "1 barn megaparsec",
  259. prefixes: "long"
  260. })
  261. math.createUnit("firkins", {
  262. definition: "90 lb",
  263. prefixes: "long"
  264. })
  265. math.createUnit("donkeySeconds", {
  266. definition: "250 joules",
  267. prefixes: "long"
  268. })
  269. math.createUnit("HU", {
  270. definition: "0.75 inches",
  271. aliases: [
  272. "HUs",
  273. "hammerUnits"
  274. ]
  275. });
  276. const defaultUnits = {
  277. length: {
  278. metric: "meters",
  279. customary: "feet",
  280. relative: "stories",
  281. quirky: "smoots"
  282. },
  283. area: {
  284. metric: "meters^2",
  285. customary: "feet^2",
  286. relative: "footballFields",
  287. quirky: "nanoacres"
  288. },
  289. volume: {
  290. metric: "liters",
  291. customary: "gallons",
  292. relative: "olympicPools",
  293. volume: "barnMegaparsecs"
  294. },
  295. mass: {
  296. metric: "kilograms",
  297. customary: "lbs",
  298. relative: "peopleMass",
  299. quirky: "firkins"
  300. },
  301. energy: {
  302. metric: "kJ",
  303. customary: "kcal",
  304. relative: "peopleEaten",
  305. quirky: "donkeySeconds"
  306. }
  307. }
  308. const unitChoices = {
  309. length: {
  310. "metric": [
  311. "angstroms",
  312. "millimeters",
  313. "centimeters",
  314. "meters",
  315. "kilometers",
  316. ],
  317. "customary": [
  318. "inches",
  319. "feet",
  320. "yards",
  321. "miles",
  322. "nauticalMiles",
  323. ],
  324. "relative": [
  325. "humans",
  326. "stories",
  327. "buses",
  328. "marathons",
  329. "timezones",
  330. "earths",
  331. "lightseconds",
  332. "solarradii",
  333. "AUs",
  334. "lightyears",
  335. "parsecs",
  336. "galaxies",
  337. "universes",
  338. "multiverses"
  339. ],
  340. "quirky": [
  341. "beardSeconds",
  342. "points",
  343. "smoots",
  344. "furlongs",
  345. "HUs",
  346. "fathoms",
  347. ]
  348. },
  349. area: {
  350. "metric": [
  351. "cm^2",
  352. "meters^2",
  353. "kilometers^2",
  354. ],
  355. "customary": [
  356. "feet^2",
  357. "acres",
  358. "miles^2"
  359. ],
  360. "relative": [
  361. "footballFields"
  362. ],
  363. "quirky": [
  364. "barns",
  365. "nanoacres"
  366. ]
  367. },
  368. volume: {
  369. "metric": [
  370. "milliliters",
  371. "liters",
  372. "m^3",
  373. ],
  374. "customary": [
  375. "floz",
  376. "cups",
  377. "pints",
  378. "quarts",
  379. "gallons",
  380. ],
  381. "relative": [
  382. "people",
  383. "shippingContainers",
  384. "olympicPools",
  385. "oceans",
  386. "earthVolumes",
  387. "universeVolumes",
  388. "multiverseVolumes",
  389. ],
  390. "quirky": [
  391. "barnMegaparsecs"
  392. ]
  393. },
  394. mass: {
  395. "metric": [
  396. "kilograms",
  397. "milligrams",
  398. "grams",
  399. "tonnes",
  400. ],
  401. "customary": [
  402. "lbs",
  403. "ounces",
  404. "tons"
  405. ],
  406. "relative": [
  407. "peopleMass",
  408. "cars",
  409. "busMasses",
  410. "earthMass",
  411. "solarmasses"
  412. ],
  413. "quirky": [
  414. "firkins"
  415. ]
  416. },
  417. energy: {
  418. "metric": [
  419. "kJ",
  420. "foodKilograms"
  421. ],
  422. "customary": [
  423. "kcal",
  424. "foodPounds"
  425. ],
  426. "relative": [
  427. "peopleEaten",
  428. "villagesEaten",
  429. "townsEaten",
  430. "citiesEaten",
  431. "metrosEaten",
  432. ],
  433. "quirky": [
  434. "donkeySeconds"
  435. ]
  436. }
  437. }
  438. const config = {
  439. height: math.unit(1500, "meters"),
  440. x: 0,
  441. y: 0,
  442. minLineSize: 100,
  443. maxLineSize: 150,
  444. autoFit: false,
  445. drawYAxis: true,
  446. drawXAxis: false,
  447. autoMass: "off",
  448. autoFoodIntake: false,
  449. autoPreyCapacity: false
  450. }
  451. const availableEntities = {
  452. }
  453. const availableEntitiesByName = {
  454. }
  455. const entities = {
  456. }
  457. function constrainRel(coords) {
  458. const worldWidth = config.height.toNumber("meters") / canvasHeight * canvasWidth;
  459. const worldHeight = config.height.toNumber("meters");
  460. if (altHeld) {
  461. return coords;
  462. }
  463. return {
  464. x: Math.min(Math.max(coords.x, -worldWidth / 2 + config.x), worldWidth / 2 + config.x),
  465. y: Math.min(Math.max(coords.y, config.y), worldHeight + config.y)
  466. }
  467. }
  468. // not using constrainRel anymore
  469. function snapPos(coords) {
  470. return {
  471. x: coords.x,
  472. y: (!config.groundSnap || altHeld) ? coords.y : (Math.abs(coords.y) < config.height.toNumber("meters")/20 ? 0 : coords.y)
  473. };
  474. }
  475. function adjustAbs(coords, oldHeight, newHeight) {
  476. const ratio = math.divide(newHeight, oldHeight);
  477. const x = (coords.x - config.x) * ratio + config.x;
  478. const y = (coords.y - config.y) * ratio + config.y;
  479. return { x: x, y: y};
  480. }
  481. function pos2pix(coords) {
  482. const worldWidth = config.height.toNumber("meters") / canvasHeight * canvasWidth;
  483. const worldHeight = config.height.toNumber("meters");
  484. const x = ((coords.x - config.x) / worldWidth + 0.5) * (canvasWidth - 50) + 50;
  485. const y = (1 - (coords.y - config.y) / worldHeight) * (canvasHeight - 50) + 50;
  486. return { x: x, y: y };
  487. }
  488. function pix2pos(coords) {
  489. const worldWidth = config.height.toNumber("meters") / canvasHeight * canvasWidth;
  490. const worldHeight = config.height.toNumber("meters");
  491. const x = (((coords.x - 50) / (canvasWidth - 50)) - 0.5) * worldWidth + config.x;
  492. const y = (1 - ((coords.y - 50) / (canvasHeight - 50))) * worldHeight + config.y;
  493. return { x: x, y: y };
  494. }
  495. function updateEntityElement(entity, element) {
  496. const position = pos2pix({ x: element.dataset.x, y: element.dataset.y });
  497. const view = entity.view;
  498. element.style.left = position.x + "px";
  499. element.style.top = position.y + "px";
  500. element.style.setProperty("--xpos", position.x + "px");
  501. element.style.setProperty("--entity-height", "'" + entity.views[view].height.to(config.height.units[0].unit.name).format({ precision: 2 }) + "'");
  502. const pixels = math.divide(entity.views[view].height, config.height) * (canvasHeight - 50);
  503. const extra = entity.views[view].image.extra;
  504. const bottom = entity.views[view].image.bottom;
  505. const bonus = (extra ? extra : 1) * (1 / (1 - (bottom ? bottom : 0)));
  506. let height = pixels * bonus;
  507. // working around a Firefox bug here
  508. if (height > 17895698) {
  509. height = 0;
  510. }
  511. element.style.setProperty("--height", height + "px");
  512. element.style.setProperty("--extra", height - pixels + "px");
  513. element.style.setProperty("--brightness", entity.brightness);
  514. if (entity.views[view].rename)
  515. element.querySelector(".entity-name").innerText = entity.name == "" ? "" : entity.views[view].name;
  516. else
  517. element.querySelector(".entity-name").innerText = entity.name;
  518. const bottomName = document.querySelector("#bottom-name-" + element.dataset.key);
  519. bottomName.style.left = position.x + entityX + "px";
  520. bottomName.style.bottom = "0vh";
  521. bottomName.innerText = entity.name;
  522. const topName = document.querySelector("#top-name-" + element.dataset.key);
  523. topName.style.left = position.x + entityX + "px";
  524. topName.style.top = "20vh";
  525. topName.innerText = entity.name;
  526. if (entity.views[view].height.toNumber("meters") / 10 > config.height.toNumber("meters")) {
  527. topName.classList.add("top-name-needed");
  528. } else {
  529. topName.classList.remove("top-name-needed");
  530. }
  531. updateInfo();
  532. }
  533. let ratioInfo
  534. function updateInfo() {
  535. let text = ""
  536. if (config.showRatios) {
  537. if (selectedEntity !== null && prevSelectedEntity !== null && selectedEntity !== prevSelectedEntity) {
  538. let first = selectedEntity.currentView.height;
  539. let second = prevSelectedEntity.currentView.height;
  540. if (first.toNumber("meters") < second.toNumber("meters")) {
  541. text += selectedEntity.name + " is " + math.format(math.divide(second, first), { precision: 5 }) + " times smaller than " + prevSelectedEntity.name;
  542. } else {
  543. text += selectedEntity.name + " is " + math.format(math.divide(first, second), { precision: 5 })+ " times taller than " + prevSelectedEntity.name;
  544. }
  545. text += "\n";
  546. let apparentHeight = math.multiply(math.divide(second, first), math.unit(6, "feet"));
  547. if (config.units === "metric") {
  548. apparentHeight = apparentHeight.to("meters");
  549. }
  550. text += prevSelectedEntity.name + " looks " + math.format(apparentHeight, { precision: 3}) + " tall to " + selectedEntity.name + "\n";
  551. if (selectedEntity.currentView.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. config.y = -getVerticalOffset();
  624. }
  625. drawScales(dirtyOnly);
  626. let ordered = Object.entries(entities);
  627. ordered.sort((e1, e2) => {
  628. if (e1[1].priority != e2[1].priority) {
  629. return e2[1].priority - e1[1].priority;
  630. } else {
  631. return e1[1].views[e1[1].view].height.value - e2[1].views[e2[1].view].height.value
  632. }
  633. });
  634. let zIndex = ordered.length;
  635. ordered.forEach(entity => {
  636. const element = document.querySelector("#entity-" + entity[0]);
  637. element.style.zIndex = zIndex;
  638. if (!dirtyOnly || entity[1].dirty) {
  639. updateEntityElement(entity[1], element, zIndex);
  640. entity[1].dirty = false;
  641. }
  642. zIndex -= 1;
  643. });
  644. document.querySelector("#ground").style.top = pos2pix({x: 0, y: 0}).y + "px";
  645. drawRulers();
  646. }
  647. function drawRulers() {
  648. const canvas = document.querySelector("#rulers");
  649. /** @type {CanvasRenderingContext2D} */
  650. const ctx = canvas.getContext("2d");
  651. const deviceScale = window.devicePixelRatio;
  652. ctx.canvas.width = Math.floor(canvas.clientWidth * deviceScale);
  653. ctx.canvas.height = Math.floor(canvas.clientHeight * deviceScale);
  654. ctx.scale(deviceScale, deviceScale);
  655. rulers.concat(currentRuler ? [currentRuler] : []).forEach(rulerDef => {
  656. let x0 = rulerDef.x0;
  657. let y0 = rulerDef.y0;
  658. let x1 = rulerDef.x1;
  659. let y1 = rulerDef.y1;
  660. if (rulerDef.entityKey !== null) {
  661. const entity = entities[rulerDef.entityKey]
  662. const entityElement = document.querySelector("#entity-" + rulerDef.entityKey)
  663. x0 *= entity.scale;
  664. y0 *= entity.scale;
  665. x1 *= entity.scale;
  666. y1 *= entity.scale;
  667. x0 += parseFloat(entityElement.dataset.x)
  668. x1 += parseFloat(entityElement.dataset.x)
  669. y0 += parseFloat(entityElement.dataset.y)
  670. y1 += parseFloat(entityElement.dataset.y)
  671. }
  672. ctx.save();
  673. ctx.beginPath();
  674. const start = pos2pix({x: x0, y: y0});
  675. const end = pos2pix({x: x1, y: y1});
  676. ctx.moveTo(start.x, start.y);
  677. ctx.lineTo(end.x, end.y);
  678. ctx.lineWidth = 5;
  679. ctx.strokeStyle = "#f8f";
  680. ctx.stroke();
  681. const center = { x: (start.x + end.x) / 2, y: (start.y + end.y) / 2 };
  682. ctx.fillStyle = "#eeeeee";
  683. ctx.font = 'normal 24pt coda';
  684. ctx.translate(center.x, center.y);
  685. let angle = Math.atan2(end.y - start.y, end.x - start.x);
  686. if (angle < -Math.PI/2) {
  687. angle += Math.PI;
  688. }
  689. if (angle > Math.PI/2) {
  690. angle -= Math.PI;
  691. }
  692. ctx.rotate(angle);
  693. const offsetX = Math.cos(angle + Math.PI/2);
  694. const offsetY = Math.sin(angle + Math.PI/2);
  695. const distance = Math.sqrt(Math.pow(y1 - y0, 2) + Math.pow(x1 - x0, 2));
  696. const distanceInUnits = math.unit(distance, "meters").to(document.querySelector("#options-height-unit").value);
  697. const textSize = ctx.measureText(distanceInUnits.format({ precision: 3}));
  698. ctx.fillText(distanceInUnits.format({ precision: 3}), -offsetX * 10 - textSize.width / 2, -offsetY*10);
  699. ctx.restore();
  700. });
  701. }
  702. function drawScales(ifDirty = false) {
  703. const canvas = document.querySelector("#display");
  704. /** @type {CanvasRenderingContext2D} */
  705. const ctx = canvas.getContext("2d");
  706. const deviceScale = window.devicePixelRatio;
  707. ctx.canvas.width = Math.floor(canvas.clientWidth * deviceScale);
  708. ctx.canvas.height = Math.floor(canvas.clientHeight * deviceScale);
  709. ctx.scale(deviceScale, deviceScale);
  710. ctx.beginPath();
  711. ctx.rect(0, 0, ctx.canvas.width / deviceScale, ctx.canvas.height / deviceScale);
  712. switch(config.background){
  713. case "black":
  714. ctx.fillStyle = "#000";
  715. break;
  716. case "dark":
  717. ctx.fillStyle = "#111";
  718. break;
  719. case "medium":
  720. ctx.fillStyle = "#333";
  721. break;
  722. case "light":
  723. ctx.fillStyle = "#555";
  724. break;
  725. }
  726. ctx.fill();
  727. if (config.drawYAxis || config.drawAltitudes !== "none") {
  728. drawVerticalScale(ifDirty);
  729. }
  730. if (config.drawXAxis) {
  731. drawHorizontalScale(ifDirty);
  732. }
  733. }
  734. function drawVerticalScale(ifDirty = false) {
  735. if (ifDirty && !worldSizeDirty)
  736. return;
  737. function drawTicks(/** @type {CanvasRenderingContext2D} */ ctx, pixelsPer, heightPer) {
  738. let total = heightPer.clone();
  739. total.value = config.y;
  740. let y = ctx.canvas.clientHeight - 50;
  741. let offset = total.toNumber("meters") % heightPer.toNumber("meters");
  742. y += offset / heightPer.toNumber("meters") * pixelsPer;
  743. total = math.subtract(total, math.unit(offset, "meters"));
  744. for (; y >= 50; y -= pixelsPer) {
  745. drawTick(ctx, 50, y, total.format({ precision: 3 }));
  746. total = math.add(total, heightPer);
  747. }
  748. }
  749. function drawTick(/** @type {CanvasRenderingContext2D} */ ctx, x, y, label, flipped=false) {
  750. const oldStroke = ctx.strokeStyle;
  751. const oldFill = ctx.fillStyle;
  752. x = Math.round(x);
  753. y = Math.round(y);
  754. ctx.beginPath();
  755. ctx.moveTo(x, y);
  756. ctx.lineTo(x + 20, y);
  757. ctx.strokeStyle = "#000000";
  758. ctx.stroke();
  759. ctx.beginPath();
  760. ctx.moveTo(x + 20, y);
  761. ctx.lineTo(ctx.canvas.clientWidth - 70, y);
  762. if (flipped) {
  763. ctx.strokeStyle = "#666666";
  764. } else {
  765. ctx.strokeStyle = "#aaaaaa";
  766. }
  767. ctx.stroke();
  768. ctx.beginPath();
  769. ctx.moveTo(ctx.canvas.clientWidth - 70, y);
  770. ctx.lineTo(ctx.canvas.clientWidth - 50, y);
  771. ctx.strokeStyle = "#000000";
  772. ctx.stroke();
  773. const oldFont = ctx.font;
  774. ctx.font = 'normal 24pt coda';
  775. ctx.fillStyle = "#dddddd";
  776. ctx.beginPath();
  777. if (flipped) {
  778. ctx.textAlign = "end";
  779. ctx.fillText(label, ctx.canvas.clientWidth - 70, y + 35)
  780. } else {
  781. ctx.fillText(label, x + 20, y + 35);
  782. }
  783. ctx.textAlign = "start";
  784. ctx.font = oldFont;
  785. ctx.strokeStyle = oldStroke;
  786. ctx.fillStyle = oldFill;
  787. }
  788. function drawAltitudeLine(ctx, height, label) {
  789. const pixelScale = (ctx.canvas.clientHeight - 100) / config.height.toNumber("meters");
  790. const y = ctx.canvas.clientHeight - 50 - (height.toNumber("meters") - config.y) * pixelScale;
  791. const offsetY = y + getVerticalOffset() * pixelScale;
  792. if (offsetY < ctx.canvas.clientHeight - 100) {
  793. drawTick(ctx, 50, y, label, true);
  794. }
  795. }
  796. const canvas = document.querySelector("#display");
  797. /** @type {CanvasRenderingContext2D} */
  798. const ctx = canvas.getContext("2d");
  799. const pixelScale = (ctx.canvas.clientHeight - 100) / config.height.toNumber();
  800. let pixelsPer = pixelScale;
  801. heightPer = 1;
  802. if (pixelsPer < config.minLineSize) {
  803. const factor = math.ceil(config.minLineSize / pixelsPer);
  804. heightPer *= factor;
  805. pixelsPer *= factor;
  806. }
  807. if (pixelsPer > config.maxLineSize) {
  808. const factor = math.ceil(pixelsPer / config.maxLineSize);
  809. heightPer /= factor;
  810. pixelsPer /= factor;
  811. }
  812. if (heightPer == 0) {
  813. console.error("The world size is invalid! Refusing to draw the scale...");
  814. return;
  815. }
  816. heightPer = math.unit(heightPer, document.querySelector("#options-height-unit").value);
  817. ctx.beginPath();
  818. ctx.moveTo(50, 50);
  819. ctx.lineTo(50, ctx.canvas.clientHeight - 50);
  820. ctx.stroke();
  821. ctx.beginPath();
  822. ctx.moveTo(ctx.canvas.clientWidth - 50, 50);
  823. ctx.lineTo(ctx.canvas.clientWidth - 50, ctx.canvas.clientHeight - 50);
  824. ctx.stroke();
  825. if (config.drawYAxis) {
  826. drawTicks(ctx, pixelsPer, heightPer);
  827. }
  828. if (config.drawAltitudes == "atmosphere" || config.drawAltitudes == "all") {
  829. drawAltitudeLine(ctx, math.unit(8, "km"), "Troposphere");
  830. drawAltitudeLine(ctx, math.unit(17.5, "km"), "Ozone Layer");
  831. drawAltitudeLine(ctx, math.unit(50, "km"), "Stratosphere");
  832. drawAltitudeLine(ctx, math.unit(85, "km"), "Mesosphere");
  833. drawAltitudeLine(ctx, math.unit(675, "km"), "Thermosphere");
  834. drawAltitudeLine(ctx, math.unit(10000, "km"), "Exosphere");
  835. }
  836. if (config.drawAltitudes == "orbits" || config.drawAltitudes == "all") {
  837. drawAltitudeLine(ctx, math.unit(7, "miles"), "Cruising Altitude");
  838. drawAltitudeLine(ctx, math.unit(100, "km"), "Edge of Space (Kármán line)");
  839. drawAltitudeLine(ctx, math.unit(211.3, "miles"), "Space Station");
  840. drawAltitudeLine(ctx, math.unit(369.7, "miles"), "Hubble Telescope");
  841. drawAltitudeLine(ctx, math.unit(1500, "km"), "Low Earth Orbit");
  842. drawAltitudeLine(ctx, math.unit(20350, "km"), "GPS Satellites");
  843. drawAltitudeLine(ctx, math.unit(35786, "km"), "Geosynchronous Orbit");
  844. drawAltitudeLine(ctx, math.unit(238900, "miles"), "Lunar Orbit");
  845. drawAltitudeLine(ctx, math.unit(57.9e6, "km"), "Orbit of Mercury");
  846. drawAltitudeLine(ctx, math.unit(108.2e6, "km"), "Orbit of Venus");
  847. drawAltitudeLine(ctx, math.unit(1, "AU"), "Orbit of Earth");
  848. drawAltitudeLine(ctx, math.unit(227.9e6, "km"), "Orbit of Mars");
  849. drawAltitudeLine(ctx, math.unit(778.6e6, "km"), "Orbit of Jupiter");
  850. drawAltitudeLine(ctx, math.unit(1433.5e6, "km"), "Orbit of Saturn");
  851. drawAltitudeLine(ctx, math.unit(2872.5e6, "km"), "Orbit of Uranus");
  852. drawAltitudeLine(ctx, math.unit(4495.1e6, "km"), "Orbit of Neptune");
  853. drawAltitudeLine(ctx, math.unit(5906.4e6, "km"), "Orbit of Pluto");
  854. drawAltitudeLine(ctx, math.unit(2.7, "AU"), "Asteroid Belt");
  855. drawAltitudeLine(ctx, math.unit(123, "AU"), "Heliopause");
  856. drawAltitudeLine(ctx, math.unit(26e3, "lightyears"), "Orbit of Sol");
  857. }
  858. if (config.drawAltitudes == "weather" || config.drawAltitudes == "all") {
  859. drawAltitudeLine(ctx, math.unit(1000, "meters"), "Low-level Clouds");
  860. drawAltitudeLine(ctx, math.unit(3000, "meters"), "Mid-level Clouds");
  861. drawAltitudeLine(ctx, math.unit(10000, "meters"), "High-level Clouds");
  862. drawAltitudeLine(ctx, math.unit(20, "km"), "Polar Stratospheric Clouds");
  863. drawAltitudeLine(ctx, math.unit(80, "km"), "Noctilucent Clouds");
  864. drawAltitudeLine(ctx, math.unit(100, "km"), "Aurora");
  865. }
  866. if (config.drawAltitudes == "water" || config.drawAltitudes == "all") {
  867. drawAltitudeLine(ctx, math.unit(12100, "feet"), "Average Ocean Depth");
  868. drawAltitudeLine(ctx, math.unit(8376, "meters"), "Milkwaukee Deep");
  869. drawAltitudeLine(ctx, math.unit(10984, "meters"), "Challenger Deep");
  870. drawAltitudeLine(ctx, math.unit(5550, "meters"), "Molloy Deep");
  871. drawAltitudeLine(ctx, math.unit(7290, "meters"), "Sunda Deep");
  872. drawAltitudeLine(ctx, math.unit(592, "meters"), "Crater Lake");
  873. drawAltitudeLine(ctx, math.unit(7.5, "meters"), "Littoral Zone");
  874. drawAltitudeLine(ctx, math.unit(140, "meters"), "Continental Shelf");
  875. }
  876. if (config.drawAltitudes == "geology" || config.drawAltitudes == "all") {
  877. drawAltitudeLine(ctx, math.unit(35, "km"), "Crust");
  878. drawAltitudeLine(ctx, math.unit(670, "km"), "Upper Mantle");
  879. drawAltitudeLine(ctx, math.unit(2890, "km"), "Lower Mantle");
  880. drawAltitudeLine(ctx, math.unit(5150, "km"), "Outer Core");
  881. drawAltitudeLine(ctx, math.unit(6370, "km"), "Inner Core");
  882. }
  883. if (config.drawAltitudes == "thicknesses" || config.drawAltitudes == "all") {
  884. drawAltitudeLine(ctx, math.unit(0.335, "nm"), "Monolayer Graphene");
  885. drawAltitudeLine(ctx, math.unit(3, "um"), "Spider Silk");
  886. drawAltitudeLine(ctx, math.unit(0.07, "mm"), "Human Hair");
  887. drawAltitudeLine(ctx, math.unit(0.1, "mm"), "Sheet of Paper");
  888. drawAltitudeLine(ctx, math.unit(0.5, "mm"), "Yarn");
  889. drawAltitudeLine(ctx, math.unit(0.0155, "inches"), "Thread");
  890. drawAltitudeLine(ctx, math.unit(0.1, "um"), "Gold Leaf");
  891. drawAltitudeLine(ctx, math.unit(35, "um"), "PCB Trace");
  892. }
  893. if (config.drawAltitudes == "airspaces" || config.drawAltitudes == "all") {
  894. drawAltitudeLine(ctx, math.unit(18000, "feet"), "Class A");
  895. drawAltitudeLine(ctx, math.unit(14500, "feet"), "Class E");
  896. drawAltitudeLine(ctx, math.unit(10000, "feet"), "Class B");
  897. drawAltitudeLine(ctx, math.unit(4000, "feet"), "Class C");
  898. drawAltitudeLine(ctx, math.unit(2500, "feet"), "Class D");
  899. }
  900. if (config.drawAltitudes == "races" || config.drawAltitudes == "all") {
  901. drawAltitudeLine(ctx, math.unit(100, "meters"), "100m Dash");
  902. drawAltitudeLine(ctx, math.unit(26.2188/2, "miles"), "Half Marathon");
  903. drawAltitudeLine(ctx, math.unit(26.2188, "miles"), "Marathon");
  904. drawAltitudeLine(ctx, math.unit(161.734, "miles"), "Monaco Grand Prix");
  905. drawAltitudeLine(ctx, math.unit(500, "miles"), "Daytona 500");
  906. drawAltitudeLine(ctx, math.unit(2121.6, "miles"), "Tour de France");
  907. }
  908. if (config.drawAltitudes == "olympic-records" || config.drawAltitudes == "all") {
  909. drawAltitudeLine(ctx, math.unit(2.39, "meters"), "High Jump");
  910. drawAltitudeLine(ctx, math.unit(6.03, "meters"), "Pole Vault");
  911. drawAltitudeLine(ctx, math.unit(8.90, "meters"), "Long Jump");
  912. drawAltitudeLine(ctx, math.unit(18.09, "meters"), "Triple Jump");
  913. drawAltitudeLine(ctx, math.unit(23.30, "meters"), "Shot Put");
  914. drawAltitudeLine(ctx, math.unit(72.30, "meters"), "Discus Throw");
  915. drawAltitudeLine(ctx, math.unit(84.80, "meters"), "Hammer Throw");
  916. drawAltitudeLine(ctx, math.unit(90.57, "meters"), "Javelin Throw");
  917. }
  918. if (config.drawAltitudes == "d&d-sizes" || config.drawAltitudes == "all") {
  919. drawAltitudeLine(ctx, math.unit(0.375, "feet"), "Fine");
  920. drawAltitudeLine(ctx, math.unit(0.75, "feet"), "Dimnutive");
  921. drawAltitudeLine(ctx, math.unit(1.5, "feet"), "Tiny");
  922. drawAltitudeLine(ctx, math.unit(3, "feet"), "Small");
  923. drawAltitudeLine(ctx, math.unit(6, "feet"), "Medium");
  924. drawAltitudeLine(ctx, math.unit(12, "feet"), "Large");
  925. drawAltitudeLine(ctx, math.unit(24, "feet"), "Huge");
  926. drawAltitudeLine(ctx, math.unit(48, "feet"), "Gargantuan");
  927. drawAltitudeLine(ctx, math.unit(96, "feet"), "Colossal");
  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. "d&d-sizes"
  2202. ],
  2203. get value() {
  2204. return config.drawAltitudes;
  2205. },
  2206. set value(param) {
  2207. config.drawAltitudes = param;
  2208. drawScales(false);
  2209. }
  2210. },
  2211. "lock-y-axis": {
  2212. name: "Lock Y-Axis",
  2213. desc: "Keep the camera at ground-level",
  2214. type: "toggle",
  2215. default: true,
  2216. get value() {
  2217. return config.lockYAxis;
  2218. },
  2219. set value(param) {
  2220. config.lockYAxis = param;
  2221. if (param) {
  2222. config.y = 0;
  2223. updateSizes();
  2224. document.querySelector("#scroll-up").disabled = true;
  2225. document.querySelector("#scroll-down").disabled = true;
  2226. } else {
  2227. document.querySelector("#scroll-up").disabled = false;
  2228. document.querySelector("#scroll-down").disabled = false;
  2229. }
  2230. }
  2231. },
  2232. "ground-snap": {
  2233. name: "Snap to Ground",
  2234. desc: "Snap things to the ground",
  2235. type: "toggle",
  2236. default: true,
  2237. get value() {
  2238. return config.groundSnap;
  2239. },
  2240. set value(param) {
  2241. config.groundSnap = param;
  2242. }
  2243. },
  2244. "axis-spacing": {
  2245. name: "Axis Spacing",
  2246. desc: "How frequent the axis lines are",
  2247. type: "select",
  2248. default: "standard",
  2249. options: [
  2250. "dense",
  2251. "standard",
  2252. "sparse"
  2253. ],
  2254. get value() {
  2255. return config.axisSpacing;
  2256. },
  2257. set value(param) {
  2258. config.axisSpacing = param;
  2259. const factor = {
  2260. "dense": 0.5,
  2261. "standard": 1,
  2262. "sparse": 2
  2263. }[param];
  2264. config.minLineSize = factor * 100;
  2265. config.maxLineSize = factor * 150;
  2266. updateSizes();
  2267. }
  2268. },
  2269. "ground-type": {
  2270. name: "Ground",
  2271. desc: "What kind of ground to show, if any",
  2272. type: "select",
  2273. default: "black",
  2274. disabled: "none",
  2275. options: [
  2276. "none",
  2277. "black",
  2278. "dark",
  2279. "medium",
  2280. "light",
  2281. ],
  2282. get value() {
  2283. return config.groundKind;
  2284. },
  2285. set value(param) {
  2286. config.groundKind = param;
  2287. document.querySelector("#ground").style.setProperty("--ground-color", backgroundColors[param])
  2288. }
  2289. },
  2290. "ground-pos": {
  2291. name: "Ground Position",
  2292. desc: "How high the ground is if the y-axis is locked",
  2293. type: "select",
  2294. default: "bottom",
  2295. options: [
  2296. "very-high",
  2297. "high",
  2298. "medium",
  2299. "low",
  2300. "very-low",
  2301. "bottom",
  2302. ],
  2303. get value() {
  2304. return config.groundPos;
  2305. },
  2306. set value(param) {
  2307. config.groundPos = param;
  2308. updateSizes();
  2309. }
  2310. },
  2311. "background-brightness": {
  2312. name: "Background Color",
  2313. desc: "How bright the background is",
  2314. type: "select",
  2315. default: "medium",
  2316. options: [
  2317. "black",
  2318. "dark",
  2319. "medium",
  2320. "light",
  2321. ],
  2322. get value() {
  2323. return config.background;
  2324. },
  2325. set value(param) {
  2326. config.background = param;
  2327. drawScales();
  2328. }
  2329. },
  2330. "auto-scale": {
  2331. name: "Auto-Size World",
  2332. desc: "Constantly zoom to fit the largest entity",
  2333. type: "toggle",
  2334. default: false,
  2335. get value() {
  2336. return config.autoFit;
  2337. },
  2338. set value(param) {
  2339. config.autoFit = param;
  2340. checkFitWorld();
  2341. }
  2342. },
  2343. "auto-units": {
  2344. name: "Auto-Select Units",
  2345. desc: "Automatically switch units when zooming in and out",
  2346. type: "toggle",
  2347. default: false,
  2348. get value() {
  2349. return config.autoUnits;
  2350. },
  2351. set value(param) {
  2352. config.autoUnits = param;
  2353. }
  2354. },
  2355. "zoom-when-adding": {
  2356. name: "Zoom On Add",
  2357. desc: "Zoom to fit when you add a new entity",
  2358. type: "toggle",
  2359. default: true,
  2360. get value() {
  2361. return config.autoFitAdd;
  2362. },
  2363. set value(param) {
  2364. config.autoFitAdd = param;
  2365. }
  2366. },
  2367. "zoom-when-sizing": {
  2368. name: "Zoom On Size",
  2369. desc: "Zoom to fit when you select an entity's size",
  2370. type: "toggle",
  2371. default: false,
  2372. get value() {
  2373. return config.autoFitSize;
  2374. },
  2375. set value(param) {
  2376. config.autoFitSize = param;
  2377. }
  2378. },
  2379. "show-ratios": {
  2380. name: "Show Ratios",
  2381. desc: "Show the proportions between the current selection and the most recent selection.",
  2382. type: "toggle",
  2383. default: false,
  2384. get value() {
  2385. return config.showRatios;
  2386. },
  2387. set value(param) {
  2388. config.showRatios = param;
  2389. updateInfo();
  2390. }
  2391. },
  2392. "show-horizon": {
  2393. name: "Show Horizon",
  2394. desc: "Show how far the horizon would be for the selected character",
  2395. type: "toggle",
  2396. default: false,
  2397. get value() {
  2398. return config.showHorizon;
  2399. },
  2400. set value(param) {
  2401. config.showHorizon = param;
  2402. updateInfo();
  2403. }
  2404. },
  2405. "attach-rulers": {
  2406. name: "Attach Rulers",
  2407. desc: "Rulers will attach to the currently-selected entity, moving around with it.",
  2408. type: "toggle",
  2409. default: true,
  2410. get value() {
  2411. return config.rulersStick;
  2412. },
  2413. set value(param) {
  2414. config.rulersStick = param;
  2415. }
  2416. },
  2417. "units": {
  2418. name: "Default Units",
  2419. desc: "Which kind of unit to use by default",
  2420. type: "select",
  2421. default: "metric",
  2422. options: [
  2423. "metric",
  2424. "customary",
  2425. "relative",
  2426. "quirky"
  2427. ],
  2428. get value() {
  2429. return config.units;
  2430. },
  2431. set value(param) {
  2432. config.units = param;
  2433. updateSizes();
  2434. }
  2435. },
  2436. "names": {
  2437. name: "Show Names",
  2438. desc: "Display names over entities",
  2439. type: "toggle",
  2440. default: true,
  2441. get value() {
  2442. return checkBodyClass("toggle-entity-name");
  2443. },
  2444. set value(param) {
  2445. toggleBodyClass("toggle-entity-name", param);
  2446. }
  2447. },
  2448. "bottom-names": {
  2449. name: "Bottom Names",
  2450. desc: "Display names at the bottom",
  2451. type: "toggle",
  2452. default: false,
  2453. get value() {
  2454. return checkBodyClass("toggle-bottom-name");
  2455. },
  2456. set value(param) {
  2457. toggleBodyClass("toggle-bottom-name", param);
  2458. }
  2459. },
  2460. "top-names": {
  2461. name: "Show Arrows",
  2462. desc: "Point to entities that are much larger than the current view",
  2463. type: "toggle",
  2464. default: false,
  2465. get value() {
  2466. return checkBodyClass("toggle-top-name");
  2467. },
  2468. set value(param) {
  2469. toggleBodyClass("toggle-top-name", param);
  2470. }
  2471. },
  2472. "height-bars": {
  2473. name: "Height Bars",
  2474. desc: "Draw dashed lines to the top of each entity",
  2475. type: "toggle",
  2476. default: false,
  2477. get value() {
  2478. return checkBodyClass("toggle-height-bars");
  2479. },
  2480. set value(param) {
  2481. toggleBodyClass("toggle-height-bars", param);
  2482. }
  2483. },
  2484. "flag-nsfw": {
  2485. name: "Flag NSFW",
  2486. desc: "Highlight NSFW things in red",
  2487. type: "toggle",
  2488. default: false,
  2489. get value() {
  2490. return checkBodyClass("flag-nsfw");
  2491. },
  2492. set value(param) {
  2493. toggleBodyClass("flag-nsfw", param);
  2494. }
  2495. },
  2496. "glowing-entities": {
  2497. name: "Glowing Edges",
  2498. desc: "Makes all entities glow",
  2499. type: "toggle",
  2500. default: false,
  2501. get value() {
  2502. return checkBodyClass("toggle-entity-glow");
  2503. },
  2504. set value(param) {
  2505. toggleBodyClass("toggle-entity-glow", param);
  2506. }
  2507. },
  2508. "smoothing": {
  2509. name: "Smoothing",
  2510. desc: "Smooth out movements and size changes. Disable for better performance.",
  2511. type: "toggle",
  2512. default: true,
  2513. get value() {
  2514. return checkBodyClass("smoothing");
  2515. },
  2516. set value(param) {
  2517. toggleBodyClass("smoothing", param);
  2518. }
  2519. },
  2520. "auto-mass": {
  2521. name: "Estimate Mass",
  2522. desc: "Guess the mass of things that don't have one specified using the selected body type",
  2523. type: "select",
  2524. default: "off",
  2525. disabled: "off",
  2526. options: [
  2527. "off",
  2528. "human",
  2529. "quadruped at shoulder",
  2530. ],
  2531. get value() {
  2532. return config.autoMass
  2533. },
  2534. set value(param) {
  2535. config.autoMass = param
  2536. }
  2537. },
  2538. "auto-food-intake": {
  2539. name: "Estimate Food Intake",
  2540. desc: "Guess how much food creatures need, based on their mass -- 2000kcal per 150lbs",
  2541. type: "toggle",
  2542. default: false,
  2543. get value() {
  2544. return config.autoFoodIntake
  2545. },
  2546. set value(param) {
  2547. config.autoFoodIntake = param
  2548. }
  2549. },
  2550. "auto-caloric-value": {
  2551. name: "Estimate Caloric Value",
  2552. desc: "Guess how much food a creature is worth -- 860kcal per pound",
  2553. type: "toggle",
  2554. default: false,
  2555. get value() {
  2556. return config.autoCaloricValue
  2557. },
  2558. set value(param) {
  2559. config.autoCaloricValue = param
  2560. }
  2561. },
  2562. "auto-prey-capacity": {
  2563. name: "Estimate Prey Capacity",
  2564. desc: "Guess how much prey creatures can hold, based on their mass",
  2565. type: "select",
  2566. default: "none",
  2567. options: [
  2568. "none",
  2569. "realistic",
  2570. "same-size"
  2571. ],
  2572. get value() {
  2573. return config.autoPreyCapacity;
  2574. },
  2575. set value(param) {
  2576. config.autoPreyCapacity = param;
  2577. }
  2578. },
  2579. }
  2580. function prepareSettings(userSettings) {
  2581. const menubar = document.querySelector("#settings-menu");
  2582. Object.entries(settingsData).forEach(([id, entry]) => {
  2583. const holder = document.createElement("label");
  2584. holder.classList.add("settings-holder");
  2585. const input = document.createElement("input");
  2586. input.id = "setting-" + id;
  2587. const vertical = document.createElement("div");
  2588. vertical.classList.add("settings-vertical");
  2589. const name = document.createElement("label");
  2590. name.innerText = entry.name;
  2591. name.classList.add("settings-name");
  2592. name.setAttribute("for", input.id);
  2593. const desc = document.createElement("label");
  2594. desc.innerText = entry.desc;
  2595. desc.classList.add("settings-desc");
  2596. desc.setAttribute("for", input.id);
  2597. if (entry.type == "toggle") {
  2598. input.type = "checkbox";
  2599. input.checked = userSettings[id] === undefined ? entry.default : userSettings[id];
  2600. holder.setAttribute("for", input.id);
  2601. vertical.appendChild(name);
  2602. vertical.appendChild(desc);
  2603. holder.appendChild(vertical);
  2604. holder.appendChild(input);
  2605. menubar.appendChild(holder);
  2606. const update = () => {
  2607. if (input.checked) {
  2608. holder.classList.add("enabled");
  2609. holder.classList.remove("disabled");
  2610. } else {
  2611. holder.classList.remove("enabled");
  2612. holder.classList.add("disabled");
  2613. }
  2614. entry.value = input.checked;
  2615. }
  2616. update();
  2617. input.addEventListener("change", update);
  2618. } else if (entry.type == "select") {
  2619. // we don't use the input element we made!
  2620. const select = document.createElement("select");
  2621. select.id = "setting-" + id;
  2622. entry.options.forEach(choice => {
  2623. const option = document.createElement("option");
  2624. option.innerText = choice;
  2625. select.appendChild(option);
  2626. })
  2627. select.value = userSettings[id] === undefined ? entry.default : userSettings[id];
  2628. vertical.appendChild(name);
  2629. vertical.appendChild(desc);
  2630. holder.appendChild(vertical);
  2631. holder.appendChild(select);
  2632. menubar.appendChild(holder);
  2633. const update = () => {
  2634. entry.value = select.value;
  2635. if (entry.disabled !== undefined && entry.value !== entry.disabled) {
  2636. holder.classList.add("enabled");
  2637. holder.classList.remove("disabled");
  2638. } else {
  2639. holder.classList.remove("enabled");
  2640. holder.classList.add("disabled");
  2641. }
  2642. }
  2643. update();
  2644. select.addEventListener("change", update);
  2645. }
  2646. })
  2647. }
  2648. function prepareMenu() {
  2649. prepareSidebar();
  2650. updateSaveInfo();
  2651. if (checkHelpDate()) {
  2652. document.querySelector("#open-help").classList.add("highlighted");
  2653. }
  2654. }
  2655. function updateSaveInfo() {
  2656. const saves = getSaves();
  2657. const load = document.querySelector("#menu-load ~ select");
  2658. load.innerHTML = "";
  2659. saves.forEach(save => {
  2660. const option = document.createElement("option");
  2661. option.innerText = save;
  2662. option.value = save;
  2663. load.appendChild(option);
  2664. });
  2665. const del = document.querySelector("#menu-delete ~ select");
  2666. del.innerHTML = "";
  2667. saves.forEach(save => {
  2668. const option = document.createElement("option");
  2669. option.innerText = save;
  2670. option.value = save;
  2671. del.appendChild(option);
  2672. });
  2673. }
  2674. function getSaves() {
  2675. try {
  2676. const results = [];
  2677. Object.keys(localStorage).forEach(key => {
  2678. if (key.startsWith("macrovision-save-")) {
  2679. results.push(key.replace("macrovision-save-", ""));
  2680. }
  2681. })
  2682. return results;
  2683. } catch (err) {
  2684. alert("Something went wrong while loading (maybe you didn't have anything saved. Check the F12 console for the error.")
  2685. console.error(err);
  2686. return false;
  2687. }
  2688. }
  2689. function getUserSettings() {
  2690. try {
  2691. const settings = JSON.parse(localStorage.getItem("settings"));
  2692. return settings === null ? {} : settings;
  2693. } catch {
  2694. return {};
  2695. }
  2696. }
  2697. function exportUserSettings() {
  2698. const settings = {};
  2699. Object.entries(settingsData).forEach(([id, entry]) => {
  2700. settings[id] = entry.value;
  2701. });
  2702. return settings;
  2703. }
  2704. function setUserSettings(settings) {
  2705. try {
  2706. localStorage.setItem("settings", JSON.stringify(settings));
  2707. } catch {
  2708. // :(
  2709. }
  2710. }
  2711. const lastHelpChange = 1601955834693;
  2712. function checkHelpDate() {
  2713. // disabling this for now
  2714. return false;
  2715. try {
  2716. const old = localStorage.getItem("help-viewed");
  2717. if (old === null || old < lastHelpChange) {
  2718. return true;
  2719. }
  2720. return false;
  2721. } catch {
  2722. console.warn("Could not set the help-viewed date");
  2723. return false;
  2724. }
  2725. }
  2726. function setHelpDate() {
  2727. try {
  2728. localStorage.setItem("help-viewed", Date.now());
  2729. } catch {
  2730. console.warn("Could not set the help-viewed date");
  2731. }
  2732. }
  2733. function doYScroll() {
  2734. const worldHeight = config.height.toNumber("meters");
  2735. config.y += scrollDirection * worldHeight / 180;
  2736. updateSizes();
  2737. scrollDirection *= 1.05;
  2738. }
  2739. function doXScroll() {
  2740. const worldWidth = config.height.toNumber("meters") / canvasHeight * canvasWidth;
  2741. config.x += scrollDirection * worldWidth / 180 ;
  2742. updateSizes();
  2743. scrollDirection *= 1.05;
  2744. }
  2745. function doZoom() {
  2746. const oldHeight = config.height;
  2747. setWorldHeight(oldHeight, math.multiply(oldHeight, 1 + zoomDirection / 10));
  2748. zoomDirection *= 1.05;
  2749. }
  2750. function doSize() {
  2751. if (selected) {
  2752. const entity = entities[selected.dataset.key];
  2753. const oldHeight = entity.views[entity.view].height;
  2754. entity.views[entity.view].height = math.multiply(oldHeight, sizeDirection < 0 ? -1/sizeDirection : sizeDirection);
  2755. entity.dirty = true;
  2756. updateEntityOptions(entity, entity.view);
  2757. updateViewOptions(entity, entity.view);
  2758. updateSizes(true);
  2759. sizeDirection *= 1.01;
  2760. const ownHeight = entity.views[entity.view].height.toNumber("meters");
  2761. let extra = entity.views[entity.view].image.extra;
  2762. extra = extra === undefined ? 1 : extra;
  2763. const worldHeight = config.height.toNumber("meters");
  2764. if (ownHeight * extra > worldHeight) {
  2765. setWorldHeight(config.height, math.multiply(entity.views[entity.view].height, extra));
  2766. } else if (ownHeight * extra * 10 < worldHeight) {
  2767. setWorldHeight(config.height, math.multiply(entity.views[entity.view].height, extra * 10));
  2768. }
  2769. }
  2770. }
  2771. function selectNewUnit() {
  2772. const unitSelector = document.querySelector("#options-height-unit");
  2773. checkFitWorld();
  2774. const scaleInput = document.querySelector("#options-height-value");
  2775. const newVal = math.unit(scaleInput.value, unitSelector.dataset.oldUnit).toNumber(unitSelector.value);
  2776. setNumericInput(scaleInput, newVal);
  2777. updateWorldHeight();
  2778. unitSelector.dataset.oldUnit = unitSelector.value;
  2779. }
  2780. // given a world position, return the position relative to the entity at normal scale
  2781. function entityRelativePosition(pos, entityElement) {
  2782. const entity = entities[entityElement.dataset.key]
  2783. const x = parseFloat(entityElement.dataset.x)
  2784. const y = parseFloat(entityElement.dataset.y)
  2785. pos.x -= x
  2786. pos.y -= y
  2787. pos.x /= entity.scale
  2788. pos.y /= entity.scale
  2789. return pos
  2790. }
  2791. document.addEventListener("DOMContentLoaded", () => {
  2792. prepareMenu();
  2793. prepareEntities();
  2794. document.querySelector("#open-help").addEventListener("click", e => {
  2795. setHelpDate();
  2796. document.querySelector("#open-help").classList.remove("highlighted");
  2797. window.open("https://www.notion.so/Macrovision-5c7f9377424743358ddf6db5671f439e", "_blank");
  2798. });
  2799. document.querySelector("#copy-screenshot").addEventListener("click", e => {
  2800. copyScreenshot();
  2801. });
  2802. document.querySelector("#save-screenshot").addEventListener("click", e => {
  2803. saveScreenshot();
  2804. });
  2805. document.querySelector("#open-screenshot").addEventListener("click", e => {
  2806. openScreenshot();
  2807. });
  2808. document.querySelector("#toggle-menu").addEventListener("click", e => {
  2809. const popoutMenu = document.querySelector("#sidebar-menu");
  2810. if (popoutMenu.classList.contains("visible")) {
  2811. popoutMenu.classList.remove("visible");
  2812. } else {
  2813. document.querySelectorAll(".popout-menu").forEach(menu => menu.classList.remove("visible"));
  2814. const rect = e.target.getBoundingClientRect();
  2815. popoutMenu.classList.add("visible");
  2816. popoutMenu.style.left = rect.x + rect.width + 10 + "px";
  2817. popoutMenu.style.top = rect.y + rect.height + 10 + "px";
  2818. let menuWidth = popoutMenu.getBoundingClientRect().width;
  2819. let screenWidth = window.innerWidth;
  2820. if (menuWidth * 1.5 > screenWidth) {
  2821. popoutMenu.style.left = 25 + "px";
  2822. }
  2823. }
  2824. e.stopPropagation();
  2825. });
  2826. document.querySelector("#sidebar-menu").addEventListener("click", e => {
  2827. e.stopPropagation();
  2828. });
  2829. document.addEventListener("click", e => {
  2830. document.querySelector("#sidebar-menu").classList.remove("visible");
  2831. });
  2832. document.querySelector("#toggle-settings").addEventListener("click", e => {
  2833. const popoutMenu = document.querySelector("#settings-menu");
  2834. if (popoutMenu.classList.contains("visible")) {
  2835. popoutMenu.classList.remove("visible");
  2836. } else {
  2837. document.querySelectorAll(".popout-menu").forEach(menu => menu.classList.remove("visible"));
  2838. const rect = e.target.getBoundingClientRect();
  2839. popoutMenu.classList.add("visible");
  2840. popoutMenu.style.left = rect.x + rect.width + 10 + "px";
  2841. popoutMenu.style.top = rect.y + rect.height + 10 + "px";
  2842. let menuWidth = popoutMenu.getBoundingClientRect().width;
  2843. let screenWidth = window.innerWidth;
  2844. if (menuWidth * 1.5 > screenWidth) {
  2845. popoutMenu.style.left = 25 + "px";
  2846. }
  2847. }
  2848. e.stopPropagation();
  2849. });
  2850. document.querySelector("#settings-menu").addEventListener("click", e => {
  2851. e.stopPropagation();
  2852. });
  2853. document.addEventListener("click", e => {
  2854. document.querySelector("#settings-menu").classList.remove("visible");
  2855. });
  2856. window.addEventListener("unload", () => {
  2857. saveScene("autosave");
  2858. setUserSettings(exportUserSettings());
  2859. });
  2860. document.querySelector("#options-selected-entity").addEventListener("input", e => {
  2861. if (e.target.value == "None") {
  2862. deselect()
  2863. } else {
  2864. select(document.querySelector("#entity-" + e.target.value));
  2865. }
  2866. });
  2867. document.querySelector("#menu-toggle-sidebar").addEventListener("click", e => {
  2868. const sidebar = document.querySelector("#options");
  2869. if (sidebar.classList.contains("hidden")) {
  2870. sidebar.classList.remove("hidden");
  2871. e.target.classList.remove("rotate-forward");
  2872. e.target.classList.add("rotate-backward");
  2873. } else {
  2874. sidebar.classList.add("hidden");
  2875. e.target.classList.add("rotate-forward");
  2876. e.target.classList.remove("rotate-backward");
  2877. }
  2878. handleResize();
  2879. });
  2880. document.querySelector("#menu-fullscreen").addEventListener("click", toggleFullScreen);
  2881. document.querySelector("#options-order-forward").addEventListener("click", e => {
  2882. if (selected) {
  2883. entities[selected.dataset.key].priority += 1;
  2884. }
  2885. document.querySelector("#options-order-display").innerText = entities[selected.dataset.key].priority;
  2886. updateSizes();
  2887. });
  2888. document.querySelector("#options-order-back").addEventListener("click", e => {
  2889. if (selected) {
  2890. entities[selected.dataset.key].priority -= 1;
  2891. }
  2892. document.querySelector("#options-order-display").innerText = entities[selected.dataset.key].priority;
  2893. updateSizes();
  2894. });
  2895. document.querySelector("#options-brightness-up").addEventListener("click", e => {
  2896. if (selected) {
  2897. entities[selected.dataset.key].brightness += 1;
  2898. }
  2899. document.querySelector("#options-brightness-display").innerText = entities[selected.dataset.key].brightness;
  2900. updateSizes();
  2901. });
  2902. document.querySelector("#options-brightness-down").addEventListener("click", e => {
  2903. if (selected) {
  2904. entities[selected.dataset.key].brightness -= 1;
  2905. }
  2906. document.querySelector("#options-brightness-display").innerText = entities[selected.dataset.key].brightness;
  2907. updateSizes();
  2908. });
  2909. document.querySelector("#options-rotate-left").addEventListener("click", e => {
  2910. if (selected) {
  2911. entities[selected.dataset.key].rotation -= Math.PI/4;
  2912. }
  2913. selected.querySelector("img").style.setProperty("--rotation", (entities[selected.dataset.key].rotation * 180 / Math.PI) + "deg")
  2914. updateSizes();
  2915. });
  2916. document.querySelector("#options-rotate-right").addEventListener("click", e => {
  2917. if (selected) {
  2918. entities[selected.dataset.key].rotation += Math.PI/4;
  2919. }
  2920. selected.querySelector("img").style.setProperty("--rotation", (entities[selected.dataset.key].rotation * 180 / Math.PI) + "deg")
  2921. updateSizes();
  2922. });
  2923. document.querySelector("#options-flip").addEventListener("click", e => {
  2924. if (selected) {
  2925. selected.querySelector(".entity-image").classList.toggle("flipped");
  2926. }
  2927. document.querySelector("#options-brightness-display").innerText = entities[selected.dataset.key].brightness;
  2928. updateSizes();
  2929. });
  2930. const sceneChoices = document.querySelector("#menu-preset ~ select");
  2931. Object.entries(scenes).forEach(([id, scene]) => {
  2932. const option = document.createElement("option");
  2933. option.innerText = id;
  2934. option.value = id;
  2935. sceneChoices.appendChild(option);
  2936. });
  2937. document.querySelector("#menu-preset").addEventListener("click", e => {
  2938. const chosen = sceneChoices.value;
  2939. removeAllEntities();
  2940. scenes[chosen]();
  2941. });
  2942. entityX = document.querySelector("#entities").getBoundingClientRect().x;
  2943. canvasWidth = document.querySelector("#display").clientWidth - 100;
  2944. canvasHeight = document.querySelector("#display").clientHeight - 50;
  2945. document.querySelector("#options-height-value").addEventListener("change", e => {
  2946. updateWorldHeight();
  2947. })
  2948. document.querySelector("#options-height-value").addEventListener("keydown", e => {
  2949. e.stopPropagation();
  2950. })
  2951. const unitSelector = document.querySelector("#options-height-unit");
  2952. Object.entries(unitChoices.length).forEach(([group, entries]) => {
  2953. const optGroup = document.createElement("optgroup");
  2954. optGroup.label = group;
  2955. unitSelector.appendChild(optGroup);
  2956. entries.forEach(entry => {
  2957. const option = document.createElement("option");
  2958. option.innerText = entry;
  2959. // we haven't loaded user settings yet, so we can't choose the unit just yet
  2960. unitSelector.appendChild(option);
  2961. })
  2962. });
  2963. unitSelector.addEventListener("input", selectNewUnit);
  2964. param = window.location.hash;
  2965. // we now use the fragment for links, but we should still support old stuff:
  2966. if (param.length > 0) {
  2967. param = param.substring(1);
  2968. } else {
  2969. param = new URL(window.location.href).searchParams.get("scene");
  2970. }
  2971. document.querySelector("#world").addEventListener("mousedown", e => {
  2972. // only middle mouse clicks
  2973. if (e.which == 2) {
  2974. panning = true;
  2975. panOffsetX = e.clientX;
  2976. panOffsetY = e.clientY;
  2977. Object.keys(entities).forEach(key => {
  2978. document.querySelector("#entity-" + key).classList.add("no-transition");
  2979. });
  2980. }
  2981. });
  2982. document.addEventListener("mouseup", e => {
  2983. if (e.which == 2) {
  2984. panning = false;
  2985. Object.keys(entities).forEach(key => {
  2986. document.querySelector("#entity-" + key).classList.remove("no-transition");
  2987. });
  2988. }
  2989. });
  2990. document.querySelector("#world").addEventListener("touchstart", e => {
  2991. if (!rulerMode) {
  2992. panning = true;
  2993. panOffsetX = e.touches[0].clientX;
  2994. panOffsetY = e.touches[0].clientY;
  2995. e.preventDefault();
  2996. Object.keys(entities).forEach(key => {
  2997. document.querySelector("#entity-" + key).classList.add("no-transition");
  2998. });
  2999. }
  3000. });
  3001. document.querySelector("#world").addEventListener("touchend", e => {
  3002. panning = false;
  3003. Object.keys(entities).forEach(key => {
  3004. document.querySelector("#entity-" + key).classList.remove("no-transition");
  3005. });
  3006. });
  3007. document.querySelector("#world").addEventListener("mousedown", e => {
  3008. // only left mouse clicks
  3009. if (e.which == 1 && rulerMode) {
  3010. let entX = document.querySelector("#entities").getBoundingClientRect().x;
  3011. let entY = document.querySelector("#entities").getBoundingClientRect().y;
  3012. let pos = pix2pos({ x: e.clientX - entX, y: e.clientY - entY });
  3013. if (config.rulersStick && selected) {
  3014. pos = entityRelativePosition(pos, selected)
  3015. }
  3016. currentRuler = { x0: pos.x, y0: pos.y, x1: pos.y, y1: pos.y, entityKey: null };
  3017. if (config.rulersStick && selected) {
  3018. currentRuler.entityKey = selected.dataset.key
  3019. }
  3020. }
  3021. });
  3022. document.querySelector("#world").addEventListener("mouseup", e => {
  3023. // only left mouse clicks
  3024. if (e.which == 1 && currentRuler) {
  3025. rulers.push(currentRuler);
  3026. currentRuler = null;
  3027. rulerMode = false;
  3028. }
  3029. });
  3030. document.querySelector("#world").addEventListener("touchstart", e => {
  3031. if (rulerMode) {
  3032. let entX = document.querySelector("#entities").getBoundingClientRect().x;
  3033. let entY = document.querySelector("#entities").getBoundingClientRect().y;
  3034. let pos = pix2pos({ x: e.touches[0].clientX - entX, y: e.touches[0].clientY - entY });
  3035. if (config.rulersStick && selected) {
  3036. pos = entityRelativePosition(pos, selected)
  3037. }
  3038. currentRuler = { x0: pos.x, y0: pos.y, x1: pos.y, y1: pos.y, entityKey: null };
  3039. if (config.rulersStick && selected) {
  3040. currentRuler.entityKey = selected.dataset.key
  3041. }
  3042. }
  3043. });
  3044. document.querySelector("#world").addEventListener("touchend", e => {
  3045. if (currentRuler) {
  3046. rulers.push(currentRuler);
  3047. currentRuler = null;
  3048. rulerMode = false;
  3049. }
  3050. });
  3051. document.querySelector("body").appendChild(testCtx.canvas);
  3052. world.addEventListener("mousedown", e => deselect(e));
  3053. world.addEventListener("touchstart", e => deselect({
  3054. which: 1,
  3055. }));
  3056. document.querySelector("#entities").addEventListener("mousedown", deselect);
  3057. document.querySelector("#display").addEventListener("mousedown", deselect);
  3058. document.addEventListener("mouseup", e => clickUp(e));
  3059. document.addEventListener("touchend", e => {
  3060. const fakeEvent = {
  3061. target: e.target,
  3062. clientX: e.changedTouches[0].clientX,
  3063. clientY: e.changedTouches[0].clientY,
  3064. which: 1
  3065. };
  3066. clickUp(fakeEvent);
  3067. });
  3068. const formList = document.querySelector("#entity-form");
  3069. formList.addEventListener("input", e => {
  3070. const entity = entities[selected.dataset.key];
  3071. entity.form = e.target.value;
  3072. entity.view = entity.formViews[entity.form];
  3073. if (Object.keys(entity.forms).length > 0)
  3074. entity.views[entity.view].height = entity.formSizes[entity.form].height;
  3075. preloadViews(entity);
  3076. configViewList(entity, entity.view);
  3077. const image = entity.views[entity.view].image;
  3078. selected.querySelector(".entity-image").src = image.source;
  3079. configViewOptions(entity, entity.view);
  3080. displayAttribution(image.source);
  3081. if (image.bottom !== undefined) {
  3082. selected.querySelector(".entity-image").style.setProperty("--offset", ((-1 + image.bottom) * 100) + "%")
  3083. } else {
  3084. selected.querySelector(".entity-image").style.setProperty("--offset", ((-1) * 100) + "%")
  3085. }
  3086. if (config.autoFitSize) {
  3087. let targets = {};
  3088. targets[selected.dataset.key] = entities[selected.dataset.key];
  3089. fitEntities(targets);
  3090. }
  3091. configSizeList(entity);
  3092. updateSizes();
  3093. updateEntityOptions(entities[selected.dataset.key], e.target.value);
  3094. updateViewOptions(entities[selected.dataset.key], entity.view);
  3095. });
  3096. const viewList = document.querySelector("#entity-view");
  3097. document.querySelector("#entity-view").addEventListener("input", e => {
  3098. const entity = entities[selected.dataset.key];
  3099. entity.view = e.target.value;
  3100. preloadViews(entity);
  3101. const image = entities[selected.dataset.key].views[e.target.value].image;
  3102. selected.querySelector(".entity-image").src = image.source;
  3103. configViewOptions(entity, entity.view);
  3104. displayAttribution(image.source);
  3105. if (image.bottom !== undefined) {
  3106. selected.querySelector(".entity-image").style.setProperty("--offset", ((-1 + image.bottom) * 100) + "%")
  3107. } else {
  3108. selected.querySelector(".entity-image").style.setProperty("--offset", ((-1) * 100) + "%")
  3109. }
  3110. updateSizes();
  3111. updateEntityOptions(entities[selected.dataset.key], e.target.value);
  3112. updateViewOptions(entities[selected.dataset.key], e.target.value);
  3113. });
  3114. document.querySelector("#entity-view").addEventListener("input", e => {
  3115. if (viewList.options[viewList.selectedIndex].classList.contains("nsfw")) {
  3116. viewList.classList.add("nsfw");
  3117. } else {
  3118. viewList.classList.remove("nsfw");
  3119. }
  3120. })
  3121. clearViewList();
  3122. document.querySelector("#menu-clear").addEventListener("click", e => {
  3123. removeAllEntities();
  3124. });
  3125. document.querySelector("#delete-entity").disabled = true;
  3126. document.querySelector("#delete-entity").addEventListener("click", e => {
  3127. if (selected) {
  3128. removeEntity(selected);
  3129. selected = null;
  3130. }
  3131. });
  3132. document.querySelector("#menu-order-height").addEventListener("click", e => {
  3133. const order = Object.keys(entities).sort((a, b) => {
  3134. const entA = entities[a];
  3135. const entB = entities[b];
  3136. const viewA = entA.view;
  3137. const viewB = entB.view;
  3138. const heightA = entA.views[viewA].height.to("meter").value;
  3139. const heightB = entB.views[viewB].height.to("meter").value;
  3140. return heightA - heightB;
  3141. });
  3142. arrangeEntities(order);
  3143. });
  3144. // TODO: write some generic logic for this lol
  3145. document.querySelector("#scroll-left").addEventListener("mousedown", e => {
  3146. scrollDirection = -1;
  3147. clearInterval(scrollHandle);
  3148. scrollHandle = setInterval(doXScroll, 1000 / 20);
  3149. e.stopPropagation();
  3150. });
  3151. document.querySelector("#scroll-right").addEventListener("mousedown", e => {
  3152. scrollDirection = 1;
  3153. clearInterval(scrollHandle);
  3154. scrollHandle = setInterval(doXScroll, 1000 / 20);
  3155. e.stopPropagation();
  3156. });
  3157. document.querySelector("#scroll-left").addEventListener("touchstart", e => {
  3158. scrollDirection = -1;
  3159. clearInterval(scrollHandle);
  3160. scrollHandle = setInterval(doXScroll, 1000 / 20);
  3161. e.stopPropagation();
  3162. });
  3163. document.querySelector("#scroll-right").addEventListener("touchstart", e => {
  3164. scrollDirection = 1;
  3165. clearInterval(scrollHandle);
  3166. scrollHandle = setInterval(doXScroll, 1000 / 20);
  3167. e.stopPropagation();
  3168. });
  3169. document.querySelector("#scroll-up").addEventListener("mousedown", e => {
  3170. scrollDirection = 1;
  3171. clearInterval(scrollHandle);
  3172. scrollHandle = setInterval(doYScroll, 1000 / 20);
  3173. e.stopPropagation();
  3174. });
  3175. document.querySelector("#scroll-down").addEventListener("mousedown", e => {
  3176. scrollDirection = -1;
  3177. clearInterval(scrollHandle);
  3178. scrollHandle = setInterval(doYScroll, 1000 / 20);
  3179. e.stopPropagation();
  3180. });
  3181. document.querySelector("#scroll-up").addEventListener("touchstart", e => {
  3182. scrollDirection = 1;
  3183. clearInterval(scrollHandle);
  3184. scrollHandle = setInterval(doYScroll, 1000 / 20);
  3185. e.stopPropagation();
  3186. });
  3187. document.querySelector("#scroll-down").addEventListener("touchstart", e => {
  3188. scrollDirection = -1;
  3189. clearInterval(scrollHandle);
  3190. scrollHandle = setInterval(doYScroll, 1000 / 20);
  3191. e.stopPropagation();
  3192. });
  3193. document.addEventListener("mouseup", e => {
  3194. clearInterval(scrollHandle);
  3195. scrollHandle = null;
  3196. });
  3197. document.addEventListener("touchend", e => {
  3198. clearInterval(scrollHandle);
  3199. scrollHandle = null;
  3200. });
  3201. document.querySelector("#zoom-in").addEventListener("mousedown", e => {
  3202. zoomDirection = -1;
  3203. clearInterval(zoomHandle);
  3204. zoomHandle = setInterval(doZoom, 1000 / 20);
  3205. e.stopPropagation();
  3206. });
  3207. document.querySelector("#zoom-out").addEventListener("mousedown", e => {
  3208. zoomDirection = 1;
  3209. clearInterval(zoomHandle);
  3210. zoomHandle = setInterval(doZoom, 1000 / 20);
  3211. e.stopPropagation();
  3212. });
  3213. document.querySelector("#zoom-in").addEventListener("touchstart", e => {
  3214. zoomDirection = -1;
  3215. clearInterval(zoomHandle);
  3216. zoomHandle = setInterval(doZoom, 1000 / 20);
  3217. e.stopPropagation();
  3218. });
  3219. document.querySelector("#zoom-out").addEventListener("touchstart", e => {
  3220. zoomDirection = 1;
  3221. clearInterval(zoomHandle);
  3222. zoomHandle = setInterval(doZoom, 1000 / 20);
  3223. e.stopPropagation();
  3224. });
  3225. document.addEventListener("mouseup", e => {
  3226. clearInterval(zoomHandle);
  3227. zoomHandle = null;
  3228. });
  3229. document.addEventListener("touchend", e => {
  3230. clearInterval(zoomHandle);
  3231. zoomHandle = null;
  3232. });
  3233. document.querySelector("#shrink").addEventListener("mousedown", e => {
  3234. sizeDirection = -1;
  3235. clearInterval(sizeHandle);
  3236. sizeHandle = setInterval(doSize, 1000 / 20);
  3237. e.stopPropagation();
  3238. });
  3239. document.querySelector("#grow").addEventListener("mousedown", e => {
  3240. sizeDirection = 1;
  3241. clearInterval(sizeHandle);
  3242. sizeHandle = setInterval(doSize, 1000 / 20);
  3243. e.stopPropagation();
  3244. });
  3245. document.querySelector("#shrink").addEventListener("touchstart", e => {
  3246. sizeDirection = -1;
  3247. clearInterval(sizeHandle);
  3248. sizeHandle = setInterval(doSize, 1000 / 20);
  3249. e.stopPropagation();
  3250. });
  3251. document.querySelector("#grow").addEventListener("touchstart", e => {
  3252. sizeDirection = 1;
  3253. clearInterval(sizeHandle);
  3254. sizeHandle = setInterval(doSize, 1000 / 20);
  3255. e.stopPropagation();
  3256. });
  3257. document.addEventListener("mouseup", e => {
  3258. clearInterval(sizeHandle);
  3259. sizeHandle = null;
  3260. });
  3261. document.addEventListener("touchend", e => {
  3262. clearInterval(sizeHandle);
  3263. sizeHandle = null;
  3264. });
  3265. document.querySelector("#ruler").addEventListener("click", e => {
  3266. rulerMode = !rulerMode;
  3267. if (rulerMode) {
  3268. toast("Ready to draw a ruler mark");
  3269. } else {
  3270. toast("Cancelled ruler mode");
  3271. }
  3272. });
  3273. document.querySelector("#ruler").addEventListener("mousedown", e => {
  3274. e.stopPropagation();
  3275. });
  3276. document.querySelector("#ruler").addEventListener("touchstart", e => {
  3277. e.stopPropagation();
  3278. });
  3279. document.querySelector("#fit").addEventListener("click", e => {
  3280. if (selected) {
  3281. let targets = {};
  3282. targets[selected.dataset.key] = entities[selected.dataset.key];
  3283. fitEntities(targets);
  3284. }
  3285. });
  3286. document.querySelector("#fit").addEventListener("mousedown", e => {
  3287. e.stopPropagation();
  3288. });
  3289. document.querySelector("#fit").addEventListener("touchstart", e => {
  3290. e.stopPropagation();
  3291. });
  3292. document.querySelector("#options-world-fit").addEventListener("click", () => fitWorld(true));
  3293. document.querySelector("#options-reset-pos-x").addEventListener("click", () => { config.x = 0; updateSizes(); });
  3294. document.querySelector("#options-reset-pos-y").addEventListener("click", () => { config.y = 0; updateSizes(); });
  3295. document.addEventListener("keydown", e => {
  3296. if (e.key == "Delete") {
  3297. if (selected) {
  3298. removeEntity(selected);
  3299. selected = null;
  3300. }
  3301. }
  3302. })
  3303. document.addEventListener("keydown", e => {
  3304. if (e.key == "Shift") {
  3305. shiftHeld = true;
  3306. e.preventDefault();
  3307. } else if (e.key == "Alt") {
  3308. altHeld = true;
  3309. movingInBounds = false; // don't snap the object back in bounds when we let go
  3310. e.preventDefault();
  3311. }
  3312. });
  3313. document.addEventListener("keyup", e => {
  3314. if (e.key == "Shift") {
  3315. shiftHeld = false;
  3316. e.preventDefault();
  3317. } else if (e.key == "Alt") {
  3318. altHeld = false;
  3319. e.preventDefault();
  3320. }
  3321. });
  3322. window.addEventListener("resize", handleResize);
  3323. // TODO: further investigate why the tool initially starts out with wrong
  3324. // values under certain circumstances (seems to be narrow aspect ratios -
  3325. // maybe the menu bar is animating when it shouldn't)
  3326. setTimeout(handleResize, 250);
  3327. setTimeout(handleResize, 500);
  3328. setTimeout(handleResize, 750);
  3329. setTimeout(handleResize, 1000);
  3330. document.querySelector("#menu-permalink").addEventListener("click", e => {
  3331. linkScene();
  3332. });
  3333. document.querySelector("#menu-export").addEventListener("click", e => {
  3334. copyScene();
  3335. });
  3336. document.querySelector("#menu-import").addEventListener("click", e => {
  3337. pasteScene();
  3338. });
  3339. document.querySelector("#menu-save").addEventListener("click", e => {
  3340. const name = document.querySelector("#menu-save ~ input").value;
  3341. if (/\S/.test(name)) {
  3342. saveScene(name);
  3343. }
  3344. updateSaveInfo();
  3345. });
  3346. document.querySelector("#menu-load").addEventListener("click", e => {
  3347. const name = document.querySelector("#menu-load ~ select").value;
  3348. if (/\S/.test(name)) {
  3349. loadScene(name);
  3350. }
  3351. });
  3352. document.querySelector("#menu-delete").addEventListener("click", e => {
  3353. const name = document.querySelector("#menu-delete ~ select").value;
  3354. if (/\S/.test(name)) {
  3355. deleteScene(name);
  3356. }
  3357. });
  3358. document.querySelector("#menu-load-autosave").addEventListener("click", e => {
  3359. loadScene("autosave");
  3360. });
  3361. document.querySelector("#menu-add-image").addEventListener("click", e => {
  3362. document.querySelector("#file-upload-picker").click();
  3363. });
  3364. document.querySelector("#file-upload-picker").addEventListener("change", e => {
  3365. if (e.target.files.length > 0) {
  3366. for (let i=0; i<e.target.files.length; i++) {
  3367. customEntityFromFile(e.target.files[i]);
  3368. }
  3369. }
  3370. })
  3371. document.querySelector("#menu-clear-rulers").addEventListener("click", e => {
  3372. rulers = [];
  3373. drawRulers();
  3374. });
  3375. document.addEventListener("paste", e => {
  3376. let index = 0;
  3377. let item = null;
  3378. let found = false;
  3379. for (; index < e.clipboardData.items.length; index++) {
  3380. item = e.clipboardData.items[index];
  3381. if (item.type == "image/png") {
  3382. found = true;
  3383. break;
  3384. }
  3385. }
  3386. if (!found) {
  3387. return;
  3388. }
  3389. let url = null;
  3390. const file = item.getAsFile();
  3391. customEntityFromFile(file);
  3392. });
  3393. document.querySelector("#world").addEventListener("dragover", e => {
  3394. e.preventDefault();
  3395. })
  3396. document.querySelector("#world").addEventListener("drop", e => {
  3397. e.preventDefault();
  3398. if (e.dataTransfer.files.length > 0) {
  3399. let entX = document.querySelector("#entities").getBoundingClientRect().x;
  3400. let entY = document.querySelector("#entities").getBoundingClientRect().y;
  3401. let coords = pix2pos({x: e.clientX-entX, y: e.clientY-entY});
  3402. customEntityFromFile(e.dataTransfer.files[0], coords.x, coords.y);
  3403. }
  3404. })
  3405. clearEntityOptions();
  3406. clearViewOptions();
  3407. clearAttribution();
  3408. // we do this last because configuring settings can cause things
  3409. // to happen (e.g. auto-fit)
  3410. prepareSettings(getUserSettings());
  3411. // now that we have this loaded, we can set it
  3412. unitSelector.dataset.oldUnit = defaultUnits.length[config.units];
  3413. document.querySelector("#options-height-unit").value = defaultUnits.length[config.units];
  3414. // ...and then update the world height by setting off an input event
  3415. document.querySelector("#options-height-unit").dispatchEvent(new Event('input', {
  3416. }));
  3417. if (param === null) {
  3418. scenes["Empty"]();
  3419. }
  3420. else {
  3421. try {
  3422. const data = JSON.parse(b64DecodeUnicode(param));
  3423. if (data.entities === undefined) {
  3424. return;
  3425. }
  3426. if (data.world === undefined) {
  3427. return;
  3428. }
  3429. importScene(data);
  3430. } catch (err) {
  3431. console.error(err);
  3432. scenes["Empty"]();
  3433. // probably wasn't valid data
  3434. }
  3435. }
  3436. document.querySelector("#world").addEventListener("wheel", e => {
  3437. if (shiftHeld) {
  3438. if (selected) {
  3439. const dir = e.deltaY > 0 ? 10 / 11 : 11 / 10;
  3440. const entity = entities[selected.dataset.key];
  3441. entity.views[entity.view].height = math.multiply(entity.views[entity.view].height, dir);
  3442. entity.dirty = true;
  3443. updateEntityOptions(entity, entity.view);
  3444. updateViewOptions(entity, entity.view);
  3445. updateSizes(true);
  3446. } else {
  3447. const worldWidth = config.height.toNumber("meters") / canvasHeight * canvasWidth;
  3448. config.x += (e.deltaY > 0 ? 1 : -1) * worldWidth / 20 ;
  3449. updateSizes();
  3450. updateSizes();
  3451. }
  3452. } else {
  3453. if (config.autoFit) {
  3454. toastRateLimit("Zoom is locked! Check Settings to disable.", "zoom-lock", 1000);
  3455. } else {
  3456. const dir = e.deltaY < 0 ? 10 / 11 : 11 / 10;
  3457. const change = config.height.toNumber("meters") - math.multiply(config.height, dir).toNumber("meters");
  3458. if (!config.lockYAxis) {
  3459. config.y += change / 2;
  3460. }
  3461. setWorldHeight(config.height, math.multiply(config.height, dir));
  3462. updateWorldOptions();
  3463. }
  3464. }
  3465. checkFitWorld();
  3466. })
  3467. updateWorldHeight();
  3468. document.querySelector("#search-box").addEventListener("change", e => doSearch(e.target.value));
  3469. });
  3470. let searchText = "";
  3471. function doSearch(value) {
  3472. searchText = value;
  3473. updateFilter();
  3474. }
  3475. function customEntityFromFile(file, x=0.5, y=0.5) {
  3476. file.arrayBuffer().then(buf => {
  3477. arr = new Uint8Array(buf);
  3478. blob = new Blob([arr], {type: file.type });
  3479. url = window.URL.createObjectURL(blob)
  3480. makeCustomEntity(url, x, y);
  3481. });
  3482. }
  3483. function makeCustomEntity(url, x=0.5, y=0.5) {
  3484. const maker = createEntityMaker(
  3485. {
  3486. name: "Custom Entity"
  3487. },
  3488. {
  3489. custom: {
  3490. attributes: {
  3491. height: {
  3492. name: "Height",
  3493. power: 1,
  3494. type: "length",
  3495. base: math.unit(6, "feet")
  3496. }
  3497. },
  3498. image: {
  3499. source: url
  3500. },
  3501. name: "Image",
  3502. info: {},
  3503. rename: false
  3504. }
  3505. },
  3506. []
  3507. );
  3508. const entity = maker.constructor();
  3509. entity.scale = config.height.toNumber("feet") / 20;
  3510. entity.ephemeral = true;
  3511. displayEntity(entity, "custom", x, y, true, true);
  3512. }
  3513. const filterDefs = {
  3514. none: {
  3515. id: "none",
  3516. name: "No Filter",
  3517. extract: maker => [],
  3518. render: name => name,
  3519. sort: (tag1, tag2) => tag1[1].localeCompare(tag2[1])
  3520. },
  3521. author: {
  3522. id: "author",
  3523. name: "Authors",
  3524. extract: maker => maker.authors ? maker.authors : [],
  3525. render: author => attributionData.people[author].name,
  3526. sort: (tag1, tag2) => tag1[1].localeCompare(tag2[1])
  3527. },
  3528. owner: {
  3529. id: "owner",
  3530. name: "Owners",
  3531. extract: maker => maker.owners ? maker.owners : [],
  3532. render: owner => attributionData.people[owner].name,
  3533. sort: (tag1, tag2) => tag1[1].localeCompare(tag2[1])
  3534. },
  3535. species: {
  3536. id: "species",
  3537. name: "Species",
  3538. extract: maker => maker.info && maker.info.species ? getSpeciesInfo(maker.info.species) : [],
  3539. render: species => speciesData[species].name,
  3540. sort: (tag1, tag2) => tag1[1].localeCompare(tag2[1])
  3541. },
  3542. tags: {
  3543. id: "tags",
  3544. name: "Tags",
  3545. extract: maker => maker.info && maker.info.tags ? maker.info.tags : [],
  3546. render: tag => tagDefs[tag],
  3547. sort: (tag1, tag2) => tag1[1].localeCompare(tag2[1])
  3548. },
  3549. size: {
  3550. id: "size",
  3551. name: "Normal Size",
  3552. extract: maker => maker.sizes && maker.sizes.length > 0 ? Array.from(maker.sizes.reduce((result, size) => {
  3553. if (result && !size.default) {
  3554. return result;
  3555. }
  3556. let meters = size.height.toNumber("meters");
  3557. if (meters < 1e-1) {
  3558. return ["micro"];
  3559. } else if (meters < 1e1) {
  3560. return ["moderate"];
  3561. } else {
  3562. return ["macro"];
  3563. }
  3564. }, null)) : [],
  3565. render: tag => { return {
  3566. "micro": "Micro",
  3567. "moderate": "Moderate",
  3568. "macro": "Macro"
  3569. }[tag]},
  3570. sort: (tag1, tag2) => {
  3571. const order = {
  3572. "micro": 0,
  3573. "moderate": 1,
  3574. "macro": 2
  3575. };
  3576. return order[tag1[0]] - order[tag2[0]];
  3577. }
  3578. },
  3579. allSizes: {
  3580. id: "allSizes",
  3581. name: "Possible Size",
  3582. extract: maker => maker.sizes ? Array.from(maker.sizes.reduce((set, size) => {
  3583. const height = size.height;
  3584. let result = Object.entries(sizeCategories).reduce((result, [name, value]) => {
  3585. if (result) {
  3586. return result;
  3587. } else {
  3588. if (math.compare(height, value) <= 0) {
  3589. return name;
  3590. }
  3591. }
  3592. }, null);
  3593. set.add(result ? result : "infinite");
  3594. return set;
  3595. }, new Set())) : [],
  3596. render: tag => tag[0].toUpperCase() + tag.slice(1),
  3597. sort: (tag1, tag2) => {
  3598. const order = [
  3599. "atomic", "microscopic", "tiny", "small", "moderate", "large", "macro", "megamacro", "planetary", "stellar",
  3600. "galactic", "universal", "omniversal", "infinite"
  3601. ]
  3602. return order.indexOf(tag1[0]) - order.indexOf(tag2[0]);
  3603. }
  3604. }
  3605. }
  3606. const sizeCategories = {
  3607. "atomic": math.unit(100, "angstroms"),
  3608. "microscopic": math.unit(100, "micrometers"),
  3609. "tiny": math.unit(100, "millimeters"),
  3610. "small": math.unit(1, "meter"),
  3611. "moderate": math.unit(3, "meters"),
  3612. "large": math.unit(10, "meters"),
  3613. "macro": math.unit(300, "meters"),
  3614. "megamacro": math.unit(1000, "kilometers"),
  3615. "planetary": math.unit(10, "earths"),
  3616. "stellar": math.unit(10, "solarradii"),
  3617. "galactic": math.unit(10, "galaxies"),
  3618. "universal": math.unit(10, "universes"),
  3619. "omniversal": math.unit(10, "multiverses")
  3620. };
  3621. function prepareEntities() {
  3622. availableEntities["buildings"] = makeBuildings();
  3623. availableEntities["characters"] = makeCharacters();
  3624. availableEntities["clothing"] = makeClothing();
  3625. availableEntities["creatures"] = makeCreatures();
  3626. availableEntities["fiction"] = makeFiction();
  3627. availableEntities["food"] = makeFood();
  3628. availableEntities["furniture"] = makeFurniture();
  3629. availableEntities["landmarks"] = makeLandmarks();
  3630. availableEntities["naturals"] = makeNaturals();
  3631. availableEntities["objects"] = makeObjects();
  3632. availableEntities["pokemon"] = makePokemon();
  3633. availableEntities["real-buildings"] = makeRealBuildings();
  3634. availableEntities["real-terrain"] = makeRealTerrains();
  3635. availableEntities["species"] = makeSpecies();
  3636. availableEntities["vehicles"] = makeVehicles();
  3637. availableEntities["species"].forEach(x => {
  3638. if (x.name == "Human") {
  3639. availableEntities["food"].push(x);
  3640. }
  3641. })
  3642. availableEntities["characters"].sort((x, y) => {
  3643. return x.name.localeCompare(y.name)
  3644. });
  3645. availableEntities["species"].sort((x, y) => {
  3646. return x.name.localeCompare(y.name)
  3647. });
  3648. availableEntities["objects"].sort((x, y) => {
  3649. return x.name.localeCompare(y.name)
  3650. });
  3651. const holder = document.querySelector("#spawners");
  3652. const filterHolder = document.querySelector("#filters");
  3653. const categorySelect = document.createElement("select");
  3654. categorySelect.id = "category-picker";
  3655. const filterSelect = document.createElement("select");
  3656. filterSelect.id = "filter-picker";
  3657. holder.appendChild(categorySelect);
  3658. filterHolder.appendChild(filterSelect);
  3659. const filterSets = {};
  3660. Object.values(filterDefs).forEach(filter => {
  3661. filterSets[filter.id] = new Set();
  3662. })
  3663. Object.entries(availableEntities).forEach(([category, entityList]) => {
  3664. const select = document.createElement("select");
  3665. select.id = "create-entity-" + category;
  3666. select.classList.add("entity-select");
  3667. for (let i = 0; i < entityList.length; i++) {
  3668. const entity = entityList[i];
  3669. const option = document.createElement("option");
  3670. option.value = i;
  3671. option.innerText = entity.name;
  3672. select.appendChild(option);
  3673. if (entity.nsfw) {
  3674. option.classList.add("nsfw");
  3675. }
  3676. Object.values(filterDefs).forEach(filter => {
  3677. filter.extract(entity).forEach(result => {
  3678. filterSets[filter.id].add(result);
  3679. });
  3680. });
  3681. availableEntitiesByName[entity.name] = entity;
  3682. };
  3683. select.addEventListener("change", e => {
  3684. if (select.options[select.selectedIndex]?.classList.contains("nsfw")) {
  3685. select.classList.add("nsfw");
  3686. } else {
  3687. select.classList.remove("nsfw");
  3688. }
  3689. // preload the entity's first image
  3690. const entity = entityList[select.selectedIndex]?.constructor();
  3691. if (entity)
  3692. {
  3693. let img = new Image();
  3694. img.src = entity.currentView.image.source;
  3695. }
  3696. })
  3697. const button = document.createElement("button");
  3698. button.id = "create-entity-" + category + "-button";
  3699. button.classList.add("entity-button");
  3700. button.innerHTML = "<i class=\"far fa-plus-square\"></i>";
  3701. button.addEventListener("click", e => {
  3702. if (entityList[select.value] == null)
  3703. return;
  3704. const newEntity = entityList[select.value].constructor()
  3705. let yOffset = 0;
  3706. if (config.lockYAxis) {
  3707. yOffset = getVerticalOffset();
  3708. } else {
  3709. yOffset = (config.lockYAxis ? 0 : config.height.toNumber("meters")/2);
  3710. }
  3711. displayEntity(newEntity, newEntity.defaultView, config.x, config.y + yOffset, true, true);
  3712. });
  3713. const categoryOption = document.createElement("option");
  3714. categoryOption.value = category
  3715. categoryOption.innerText = category;
  3716. if (category == "characters") {
  3717. categoryOption.selected = true;
  3718. select.classList.add("category-visible");
  3719. button.classList.add("category-visible");
  3720. }
  3721. categorySelect.appendChild(categoryOption);
  3722. holder.appendChild(select);
  3723. holder.appendChild(button);
  3724. });
  3725. Object.values(filterDefs).forEach(filter => {
  3726. const option = document.createElement("option");
  3727. option.innerText = filter.name;
  3728. option.value = filter.id;
  3729. filterSelect.appendChild(option);
  3730. const filterNameSelect = document.createElement("select");
  3731. filterNameSelect.classList.add("filter-select");
  3732. filterNameSelect.id = "filter-" + filter.id;
  3733. filterHolder.appendChild(filterNameSelect);
  3734. const button = document.createElement("button");
  3735. button.classList.add("filter-button");
  3736. button.id = "create-filtered-" + filter.id + "-button";
  3737. filterHolder.appendChild(button);
  3738. const counter = document.createElement("div");
  3739. counter.classList.add("button-counter");
  3740. counter.innerText = "10";
  3741. button.appendChild(counter);
  3742. const i = document.createElement("i");
  3743. i.classList.add("fas");
  3744. i.classList.add("fa-plus");
  3745. button.appendChild(i);
  3746. button.addEventListener("click", e => {
  3747. const makers = Array.from(document.querySelector(".entity-select.category-visible")).filter(element => !element.classList.contains("filtered"));
  3748. const count = makers.length + 2;
  3749. let index = 1;
  3750. if (makers.length > 50) {
  3751. if (!confirm("Really spawn " + makers.length + " things at once?")) {
  3752. return;
  3753. }
  3754. }
  3755. const worldWidth = config.height.toNumber("meters") / canvasHeight * canvasWidth;
  3756. const spawned = makers.map(element => {
  3757. const category = document.querySelector("#category-picker").value;
  3758. const maker = availableEntities[category][element.value];
  3759. const entity = maker.constructor()
  3760. displayEntity(entity, entity.view, -worldWidth * 0.45 + config.x + worldWidth * 0.9 * index / (count - 1), config.y);
  3761. index += 1;
  3762. return entityIndex - 1;
  3763. });
  3764. updateSizes(true);
  3765. if (config.autoFitAdd) {
  3766. let targets = {};
  3767. spawned.forEach(key => {
  3768. targets[key] = entities[key];
  3769. })
  3770. fitEntities(targets);
  3771. }
  3772. });
  3773. Array.from(filterSets[filter.id]).map(name => [name, filter.render(name)]).sort(filterDefs[filter.id].sort).forEach(name => {
  3774. const option = document.createElement("option");
  3775. option.innerText = name[1];
  3776. option.value = name[0];
  3777. filterNameSelect.appendChild(option);
  3778. });
  3779. filterNameSelect.addEventListener("change", e => {
  3780. updateFilter();
  3781. });
  3782. });
  3783. console.log("Loaded " + Object.keys(availableEntitiesByName).length + " entities");
  3784. categorySelect.addEventListener("input", e => {
  3785. const oldSelect = document.querySelector(".entity-select.category-visible");
  3786. oldSelect.classList.remove("category-visible");
  3787. const oldButton = document.querySelector(".entity-button.category-visible");
  3788. oldButton.classList.remove("category-visible");
  3789. const newSelect = document.querySelector("#create-entity-" + e.target.value);
  3790. newSelect.classList.add("category-visible");
  3791. const newButton = document.querySelector("#create-entity-" + e.target.value + "-button");
  3792. newButton.classList.add("category-visible");
  3793. recomputeFilters();
  3794. updateFilter();
  3795. });
  3796. recomputeFilters();
  3797. filterSelect.addEventListener("input", e => {
  3798. const oldSelect = document.querySelector(".filter-select.category-visible");
  3799. if (oldSelect)
  3800. oldSelect.classList.remove("category-visible");
  3801. const newSelect = document.querySelector("#filter-" + e.target.value);
  3802. if (newSelect && e.target.value != "none")
  3803. newSelect.classList.add("category-visible");
  3804. updateFilter();
  3805. });
  3806. ratioInfo = document.body.querySelector(".extra-info")
  3807. }
  3808. // Only display authors and owners if they appear
  3809. // somewhere in the current entity list
  3810. function recomputeFilters() {
  3811. const category = document.querySelector("#category-picker").value;
  3812. const filterSets = {};
  3813. Object.values(filterDefs).forEach(filter => {
  3814. filterSets[filter.id] = new Set();
  3815. });
  3816. document.querySelectorAll(".entity-select.category-visible > option").forEach(element => {
  3817. const entity = availableEntities[category][element.value];
  3818. Object.values(filterDefs).forEach(filter => {
  3819. filter.extract(entity).forEach(result => {
  3820. filterSets[filter.id].add(result);
  3821. });
  3822. });
  3823. });
  3824. Object.values(filterDefs).forEach(filter => {
  3825. // always show the "none" option
  3826. let found = filter.id == "none";
  3827. document.querySelectorAll("#filter-" + filter.id + " > option").forEach(element => {
  3828. if (filterSets[filter.id].has(element.value) || filter.id == "none") {
  3829. element.classList.remove("filtered");
  3830. element.disabled = false;
  3831. found = true;
  3832. } else {
  3833. element.classList.add("filtered");
  3834. element.disabled = true;
  3835. }
  3836. });
  3837. const filterOption = document.querySelector("#filter-picker > option[value='" + filter.id + "']");
  3838. if (found) {
  3839. filterOption.classList.remove("filtered");
  3840. filterOption.disabled = false;
  3841. } else {
  3842. filterOption.classList.add("filtered");
  3843. filterOption.disabled = true;
  3844. }
  3845. });
  3846. document.querySelector("#filter-picker").value = "none";
  3847. document.querySelector("#filter-picker").dispatchEvent(new Event("input"));
  3848. }
  3849. function updateFilter() {
  3850. const category = document.querySelector("#category-picker").value;
  3851. const type = document.querySelector("#filter-picker").value;
  3852. const filterKeySelect = document.querySelector(".filter-select.category-visible");
  3853. clearFilter();
  3854. const noFilter = !filterKeySelect;
  3855. let key;
  3856. let current = document.querySelector(".entity-select.category-visible").value;
  3857. if (!noFilter)
  3858. {
  3859. key = filterKeySelect.value;
  3860. current
  3861. }
  3862. let replace = current == "";
  3863. let first = null;
  3864. let count = 0;
  3865. const lowerSearchText = searchText !== "" ? searchText.toLowerCase() : null;
  3866. document.querySelectorAll(".entity-select.category-visible > option").forEach(element => {
  3867. let keep = noFilter;
  3868. if (!noFilter && filterDefs[type].extract(availableEntities[category][element.value]).indexOf(key) >= 0) {
  3869. keep = true;
  3870. }
  3871. if (searchText != "" && !availableEntities[category][element.value].name.toLowerCase().includes(lowerSearchText))
  3872. {
  3873. keep = false;
  3874. }
  3875. if (!keep) {
  3876. element.classList.add("filtered");
  3877. element.disabled = true;
  3878. if (current == element.value) {
  3879. replace = true;
  3880. }
  3881. } else {
  3882. count += 1;
  3883. if (!first) {
  3884. first = element.value;
  3885. }
  3886. }
  3887. });
  3888. const button = document.querySelector(".filter-select.category-visible + button");
  3889. if (button) {
  3890. button.querySelector(".button-counter").innerText = count;
  3891. }
  3892. if (replace) {
  3893. document.querySelector(".entity-select.category-visible").value = first;
  3894. document.querySelector("#create-entity-" + category).dispatchEvent(new Event("change"));
  3895. }
  3896. }
  3897. function clearFilter() {
  3898. document.querySelectorAll(".entity-select.category-visible > option").forEach(element => {
  3899. element.classList.remove("filtered");
  3900. element.disabled = false;
  3901. });
  3902. }
  3903. document.addEventListener("mousemove", (e) => {
  3904. if (currentRuler) {
  3905. let entX = document.querySelector("#entities").getBoundingClientRect().x;
  3906. let entY = document.querySelector("#entities").getBoundingClientRect().y;
  3907. let position = pix2pos({ x: e.clientX - entX, y: e.clientY - entY });
  3908. if (config.rulersStick && selected) {
  3909. position = entityRelativePosition(position, selected)
  3910. }
  3911. currentRuler.x1 = position.x;
  3912. currentRuler.y1 = position.y;
  3913. }
  3914. drawRulers();
  3915. });
  3916. document.addEventListener("touchmove", (e) => {
  3917. if (currentRuler) {
  3918. let entX = document.querySelector("#entities").getBoundingClientRect().x;
  3919. let entY = document.querySelector("#entities").getBoundingClientRect().y;
  3920. let position = pix2pos({ x: e.touches[0].clientX - entX, y: e.touches[0].clientY - entY });
  3921. if (config.rulersStick && selected) {
  3922. position = entityRelativePosition(position, selected)
  3923. }
  3924. currentRuler.x1 = position.x;
  3925. currentRuler.y1 = position.y;
  3926. }
  3927. drawRulers();
  3928. });
  3929. document.addEventListener("mousemove", (e) => {
  3930. if (clicked) {
  3931. let position = pix2pos({ x: e.clientX - dragOffsetX, y: e.clientY - dragOffsetY });
  3932. if (movingInBounds) {
  3933. position = snapPos(position);
  3934. } else {
  3935. let x = e.clientX - dragOffsetX;
  3936. let y = e.clientY - dragOffsetY;
  3937. if (x >= 0 && x <= canvasWidth && y >= 0 && y <= canvasHeight) {
  3938. movingInBounds = true;
  3939. }
  3940. }
  3941. clicked.dataset.x = position.x;
  3942. clicked.dataset.y = position.y;
  3943. updateEntityElement(entities[clicked.dataset.key], clicked);
  3944. if (hoveringInDeleteArea(e)) {
  3945. document.querySelector("#menubar").classList.add("hover-delete");
  3946. } else {
  3947. document.querySelector("#menubar").classList.remove("hover-delete");
  3948. }
  3949. }
  3950. if (panning && panReady) {
  3951. const worldWidth = config.height.toNumber("meters") / canvasHeight * canvasWidth;
  3952. const worldHeight = config.height.toNumber("meters");
  3953. config.x -= (e.clientX - panOffsetX) / canvasWidth * worldWidth;
  3954. config.y += (e.clientY - panOffsetY) / canvasHeight * worldHeight;
  3955. panOffsetX = e.clientX;
  3956. panOffsetY = e.clientY;
  3957. updateSizes();
  3958. panReady = false;
  3959. setTimeout(() => panReady=true, 1000/120);
  3960. }
  3961. });
  3962. document.addEventListener("touchmove", (e) => {
  3963. if (clicked) {
  3964. e.preventDefault();
  3965. let x = e.touches[0].clientX;
  3966. let y = e.touches[0].clientY;
  3967. const position = snapPos(pix2pos({ x: x - dragOffsetX, y: y - dragOffsetY }));
  3968. clicked.dataset.x = position.x;
  3969. clicked.dataset.y = position.y;
  3970. updateEntityElement(entities[clicked.dataset.key], clicked);
  3971. // what a hack
  3972. // I should centralize this 'fake event' creation...
  3973. if (hoveringInDeleteArea({ clientY: y })) {
  3974. document.querySelector("#menubar").classList.add("hover-delete");
  3975. } else {
  3976. document.querySelector("#menubar").classList.remove("hover-delete");
  3977. }
  3978. }
  3979. if (panning && panReady) {
  3980. const worldWidth = config.height.toNumber("meters") / canvasHeight * canvasWidth;
  3981. const worldHeight = config.height.toNumber("meters");
  3982. config.x -= (e.touches[0].clientX - panOffsetX) / canvasWidth * worldWidth;
  3983. config.y += (e.touches[0].clientY - panOffsetY) / canvasHeight * worldHeight;
  3984. panOffsetX = e.touches[0].clientX;
  3985. panOffsetY = e.touches[0].clientY;
  3986. updateSizes();
  3987. panReady = false;
  3988. setTimeout(() => panReady=true, 1000/60);
  3989. }
  3990. }, { passive: false });
  3991. function checkFitWorld() {
  3992. if (config.autoFit) {
  3993. fitWorld();
  3994. return true;
  3995. }
  3996. return false;
  3997. }
  3998. function fitWorld(manual = false, factor = 1.1) {
  3999. if (Object.keys(entities).length > 0) {
  4000. fitEntities(entities, factor);
  4001. }
  4002. }
  4003. function fitEntities(targetEntities, manual = false, factor = 1.1) {
  4004. let minX = Infinity;
  4005. let maxX = -Infinity;
  4006. let minY = Infinity;
  4007. let maxY = -Infinity;
  4008. let count = 0;
  4009. const worldWidth = config.height.toNumber("meters") / canvasHeight * canvasWidth;
  4010. const worldHeight = config.height.toNumber("meters");
  4011. Object.entries(targetEntities).forEach(([key, entity]) => {
  4012. const view = entity.view;
  4013. let extra = entity.views[view].image.extra;
  4014. extra = extra === undefined ? 1 : extra;
  4015. const image = document.querySelector("#entity-" + key + " > .entity-image");
  4016. const x = parseFloat(document.querySelector("#entity-" + key).dataset.x);
  4017. let width = image.width;
  4018. let height = image.height;
  4019. // only really relevant if the images haven't loaded in yet
  4020. if (height == 0) {
  4021. height = 100;
  4022. }
  4023. if (width == 0) {
  4024. width = height;
  4025. }
  4026. const xBottom = x - entity.views[view].height.toNumber("meters") * width / height / 2;
  4027. const xTop = x + entity.views[view].height.toNumber("meters") * width / height / 2;
  4028. const y = parseFloat(document.querySelector("#entity-" + key).dataset.y);
  4029. const yBottom = y;
  4030. const yTop = entity.views[view].height.toNumber("meters") + yBottom;
  4031. minX = Math.min(minX, xBottom);
  4032. maxX = Math.max(maxX, xTop);
  4033. minY = Math.min(minY, yBottom);
  4034. maxY = Math.max(maxY, yTop);
  4035. count += 1;
  4036. });
  4037. if (config.lockYAxis) {
  4038. minY = 0;
  4039. }
  4040. let ySize = (maxY - minY) * factor;
  4041. let xSize = (maxX - minX) * factor;
  4042. if (xSize / ySize > worldWidth / worldHeight) {
  4043. ySize *= ((xSize / ySize) / (worldWidth / worldHeight));
  4044. }
  4045. config.x = (maxX + minX) / 2;
  4046. config.y = minY;
  4047. height = math.unit(ySize, "meter")
  4048. setWorldHeight(config.height, math.multiply(height, factor));
  4049. }
  4050. function updateWorldHeight() {
  4051. const unit = document.querySelector("#options-height-unit").value;
  4052. const rawValue = document.querySelector("#options-height-value").value;
  4053. var value
  4054. try {
  4055. value = math.evaluate(rawValue)
  4056. if (typeof(value) !== "number") {
  4057. try {
  4058. value = value.toNumber(unit)
  4059. } catch {
  4060. toast("Invalid input: " + rawValue + " can't be converted to " + unit)
  4061. }
  4062. }
  4063. } catch {
  4064. toast("Invalid input: could not parse " + rawValue)
  4065. return;
  4066. }
  4067. const newHeight = Math.max(0.000000001, value);
  4068. const oldHeight = config.height;
  4069. setWorldHeight(oldHeight, math.unit(newHeight, unit), true);
  4070. }
  4071. function setWorldHeight(oldHeight, newHeight, keepUnit=false) {
  4072. worldSizeDirty = true;
  4073. config.height = newHeight.to(document.querySelector("#options-height-unit").value)
  4074. const unit = document.querySelector("#options-height-unit").value;
  4075. setNumericInput(document.querySelector("#options-height-value"), config.height.toNumber(unit));
  4076. Object.entries(entities).forEach(([key, entity]) => {
  4077. const element = document.querySelector("#entity-" + key);
  4078. let newPosition;
  4079. if (altHeld) {
  4080. newPosition = adjustAbs({ x: element.dataset.x, y: element.dataset.y }, oldHeight, config.height);
  4081. } else {
  4082. newPosition = { x: element.dataset.x, y: element.dataset.y };
  4083. }
  4084. element.dataset.x = newPosition.x;
  4085. element.dataset.y = newPosition.y;
  4086. });
  4087. if (!keepUnit) {
  4088. pickUnit()
  4089. }
  4090. updateSizes();
  4091. }
  4092. function loadScene(name = "default") {
  4093. if (name === "") {
  4094. name = "default"
  4095. }
  4096. try {
  4097. const data = JSON.parse(localStorage.getItem("macrovision-save-" + name));
  4098. if (data === null) {
  4099. console.error("Couldn't load " + name)
  4100. return false;
  4101. }
  4102. importScene(data);
  4103. toast("Loaded " + name);
  4104. return true;
  4105. } catch (err) {
  4106. alert("Something went wrong while loading (maybe you didn't have anything saved. Check the F12 console for the error.")
  4107. console.error(err);
  4108. return false;
  4109. }
  4110. }
  4111. function saveScene(name = "default") {
  4112. try {
  4113. const string = JSON.stringify(exportScene());
  4114. localStorage.setItem("macrovision-save-" + name, string);
  4115. toast("Saved as " + name);
  4116. } catch (err) {
  4117. alert("Something went wrong while saving (maybe I don't have localStorage permissions, or exporting failed). Check the F12 console for the error.")
  4118. console.error(err);
  4119. }
  4120. }
  4121. function deleteScene(name = "default") {
  4122. if (confirm("Really delete the " + name + " scene?")) {
  4123. try {
  4124. localStorage.removeItem("macrovision-save-" + name)
  4125. toast("Deleted " + name);
  4126. } catch (err) {
  4127. console.error(err);
  4128. }
  4129. }
  4130. updateSaveInfo();
  4131. }
  4132. function exportScene() {
  4133. const results = {};
  4134. results.entities = [];
  4135. Object.entries(entities).filter(([key, entity]) => entity.ephemeral !== true).forEach(([key, entity]) => {
  4136. const element = document.querySelector("#entity-" + key);
  4137. results.entities.push({
  4138. name: entity.identifier,
  4139. customName: entity.name,
  4140. scale: entity.scale,
  4141. rotation: entity.rotation,
  4142. view: entity.view,
  4143. form: entity.form,
  4144. x: element.dataset.x,
  4145. y: element.dataset.y,
  4146. priority: entity.priority,
  4147. brightness: entity.brightness
  4148. });
  4149. });
  4150. const unit = document.querySelector("#options-height-unit").value;
  4151. results.world = {
  4152. height: config.height.toNumber(unit),
  4153. unit: unit,
  4154. x: config.x,
  4155. y: config.y
  4156. }
  4157. results.version = migrationDefs.length;
  4158. return results;
  4159. }
  4160. // btoa doesn't like anything that isn't ASCII
  4161. // great
  4162. // thanks to https://stackoverflow.com/questions/30106476/using-javascripts-atob-to-decode-base64-doesnt-properly-decode-utf-8-strings
  4163. // for providing an alternative
  4164. function b64EncodeUnicode(str) {
  4165. // first we use encodeURIComponent to get percent-encoded UTF-8,
  4166. // then we convert the percent encodings into raw bytes which
  4167. // can be fed into btoa.
  4168. return btoa(encodeURIComponent(str).replace(/%([0-9A-F]{2})/g,
  4169. function toSolidBytes(match, p1) {
  4170. return String.fromCharCode('0x' + p1);
  4171. }));
  4172. }
  4173. function b64DecodeUnicode(str) {
  4174. // Going backwards: from bytestream, to percent-encoding, to original string.
  4175. return decodeURIComponent(atob(str).split('').map(function (c) {
  4176. return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
  4177. }).join(''));
  4178. }
  4179. function linkScene() {
  4180. loc = new URL(window.location);
  4181. const link = loc.protocol + "//" + loc.host + loc.pathname + "#" + b64EncodeUnicode(JSON.stringify(exportScene()));
  4182. window.history.replaceState(null, "Macrovision", link);
  4183. try {
  4184. navigator.clipboard.writeText(link);
  4185. toast("Copied permalink to clipboard");
  4186. } catch {
  4187. toast("Couldn't copy permalink");
  4188. }
  4189. }
  4190. function copyScene() {
  4191. const results = exportScene();
  4192. navigator.clipboard.writeText(JSON.stringify(results));
  4193. }
  4194. function pasteScene() {
  4195. try {
  4196. navigator.clipboard.readText().then(text => {
  4197. const data = JSON.parse(text);
  4198. if (data.entities === undefined) {
  4199. return;
  4200. }
  4201. if (data.world === undefined) {
  4202. return;
  4203. }
  4204. importScene(data);
  4205. }).catch(err => alert(err));
  4206. } catch (err) {
  4207. console.error(err);
  4208. // probably wasn't valid data
  4209. }
  4210. }
  4211. // TODO - don't just search through every single entity
  4212. // probably just have a way to do lookups directly
  4213. function findEntity(name) {
  4214. return availableEntitiesByName[name];
  4215. }
  4216. const migrationDefs = [
  4217. /*
  4218. Migration: 0 -> 1
  4219. Adds x and y coordinates for the camera
  4220. */
  4221. data => {
  4222. data.world.x = 0;
  4223. data.world.y = 0;
  4224. },
  4225. /*
  4226. Migration: 1 -> 2
  4227. Adds priority and brightness to each entity
  4228. */
  4229. data => {
  4230. data.entities.forEach(entity => {
  4231. entity.priority = 0;
  4232. entity.brightness = 1;
  4233. });
  4234. },
  4235. /*
  4236. Migration: 2 -> 3
  4237. Custom names are exported
  4238. */
  4239. data => {
  4240. data.entities.forEach(entity => {
  4241. entity.customName = entity.name
  4242. });
  4243. },
  4244. /*
  4245. Migration: 3 -> 4
  4246. Rotation is now stored
  4247. */
  4248. data => {
  4249. data.entities.forEach(entity => {
  4250. entity.rotation = 0
  4251. });
  4252. }
  4253. ]
  4254. function migrateScene(data) {
  4255. if (data.version === undefined) {
  4256. alert("This save was created before save versions were tracked. The scene may import incorrectly.");
  4257. console.trace()
  4258. data.version = 0;
  4259. } else if (data.version < migrationDefs.length) {
  4260. migrationDefs[data.version](data);
  4261. data.version += 1;
  4262. migrateScene(data);
  4263. }
  4264. }
  4265. function importScene(data) {
  4266. removeAllEntities();
  4267. migrateScene(data);
  4268. data.entities.forEach(entityInfo => {
  4269. const entity = findEntity(entityInfo.name).constructor();
  4270. entity.name = entityInfo.customName;
  4271. entity.scale = entityInfo.scale;
  4272. entity.rotation = entityInfo.rotation;
  4273. entity.priority = entityInfo.priority;
  4274. entity.brightness = entityInfo.brightness;
  4275. entity.form = entityInfo.form;
  4276. displayEntity(entity, entityInfo.view, entityInfo.x, entityInfo.y);
  4277. });
  4278. config.height = math.unit(data.world.height, data.world.unit);
  4279. config.x = data.world.x;
  4280. config.y = data.world.y;
  4281. const height = math.unit(data.world.height, data.world.unit).toNumber(defaultUnits.length[config.units]);
  4282. document.querySelector("#options-height-value").value = height;
  4283. document.querySelector("#options-height-unit").dataset.oldUnit = defaultUnits.length[config.units];
  4284. document.querySelector("#options-height-unit").value = defaultUnits.length[config.units];
  4285. if (data.canvasWidth) {
  4286. doHorizReposition(data.canvasWidth / canvasWidth);
  4287. }
  4288. updateSizes();
  4289. }
  4290. function renderToCanvas() {
  4291. const ctx = document.querySelector("#display").getContext("2d");
  4292. Object.entries(entities).sort((ent1, ent2) => {
  4293. z1 = document.querySelector("#entity-" + ent1[0]).style.zIndex;
  4294. z2 = document.querySelector("#entity-" + ent2[0]).style.zIndex;
  4295. return z1 - z2;
  4296. }).forEach(([id, entity]) => {
  4297. element = document.querySelector("#entity-" + id);
  4298. img = element.querySelector("img");
  4299. let x = parseFloat(element.dataset.x);
  4300. let y = parseFloat(element.dataset.y);
  4301. let coords = pos2pix({x: x, y: y});
  4302. let offset = img.style.getPropertyValue("--offset");
  4303. offset = parseFloat(offset.substring(0, offset.length-1))
  4304. let xSize = img.width;
  4305. let ySize = img.height;
  4306. x = coords.x
  4307. y = coords.y + ySize/2 + ySize * offset / 100;
  4308. const oldFilter = ctx.filter
  4309. const brightness = getComputedStyle(element).getPropertyValue("--brightness")
  4310. ctx.filter = `brightness(${brightness})`;
  4311. ctx.save();
  4312. ctx.resetTransform();
  4313. ctx.scale(window.devicePixelRatio, window.devicePixelRatio)
  4314. ctx.translate(x, y);
  4315. ctx.rotate(entity.rotation);
  4316. ctx.drawImage(img, -xSize/2, -ySize/2, xSize, ySize);
  4317. ctx.restore();
  4318. ctx.filter = oldFilter
  4319. });
  4320. ctx.drawImage(document.querySelector("#rulers"), 0, 0);
  4321. }
  4322. function exportCanvas(callback) {
  4323. /** @type {CanvasRenderingContext2D} */
  4324. const ctx = document.querySelector("#display").getContext("2d");
  4325. const blob = ctx.canvas.toBlob(callback);
  4326. }
  4327. function generateScreenshot(callback) {
  4328. /** @type {CanvasRenderingContext2D} */
  4329. const ctx = document.querySelector("#display").getContext("2d");
  4330. if (config.groundKind !== "none") {
  4331. ctx.fillStyle = backgroundColors[config.groundKind];
  4332. ctx.fillRect(0, pos2pix({x: 0, y: 0}).y, canvasWidth + 100, canvasHeight);
  4333. }
  4334. renderToCanvas();
  4335. ctx.resetTransform();
  4336. ctx.fillStyle = "#999";
  4337. ctx.font = "normal normal lighter 16pt coda";
  4338. ctx.fillText("macrovision.crux.sexy", 10, 25);
  4339. exportCanvas(blob => {
  4340. callback(blob);
  4341. });
  4342. }
  4343. function copyScreenshot() {
  4344. if (window.ClipboardItem === undefined) {
  4345. alert("Sorry, this browser doesn't yet support writing images to the clipboard.");
  4346. return;
  4347. }
  4348. generateScreenshot(blob => {
  4349. navigator.clipboard.write([
  4350. new ClipboardItem({
  4351. "image/png": blob
  4352. })
  4353. ]).then(e =>
  4354. toast("Copied to clipboard!"))
  4355. .catch(e => {
  4356. toast("Couldn't write to the clipboard. Make sure the screenshot completes before switching tabs.")
  4357. })
  4358. });
  4359. drawScales(false);
  4360. }
  4361. function saveScreenshot() {
  4362. generateScreenshot(blob => {
  4363. const a = document.createElement("a");
  4364. a.href = URL.createObjectURL(blob);
  4365. a.setAttribute("download", "macrovision.png");
  4366. a.click();
  4367. });
  4368. drawScales(false);
  4369. }
  4370. function openScreenshot() {
  4371. generateScreenshot(blob => {
  4372. const a = document.createElement("a");
  4373. a.href = URL.createObjectURL(blob);
  4374. a.setAttribute("target", "_blank");
  4375. a.click();
  4376. });
  4377. drawScales(false);
  4378. }
  4379. const rateLimits = {};
  4380. function toast(msg) {
  4381. let div = document.createElement("div");
  4382. div.innerHTML = msg;
  4383. div.classList.add("toast");
  4384. document.body.appendChild(div);
  4385. setTimeout(() => {
  4386. document.body.removeChild(div);
  4387. }, 5000)
  4388. }
  4389. function toastRateLimit(msg, key, delay) {
  4390. if (!rateLimits[key]) {
  4391. toast(msg);
  4392. rateLimits[key] = setTimeout(() => {
  4393. delete rateLimits[key]
  4394. }, delay);
  4395. }
  4396. }
  4397. let lastTime = undefined;
  4398. function pan(fromX, fromY, fromHeight, toX, toY, toHeight, duration) {
  4399. Object.keys(entities).forEach(key => {
  4400. document.querySelector("#entity-" + key).classList.add("no-transition");
  4401. });
  4402. config.x = fromX;
  4403. config.y = fromY;
  4404. config.height = math.unit(fromHeight, "meters")
  4405. updateSizes();
  4406. lastTime = undefined;
  4407. requestAnimationFrame((timestamp) => panTo(toX, toY, toHeight, (toX - fromX) / duration, (toY - fromY) / duration, (toHeight - fromHeight) / duration, timestamp, duration));
  4408. }
  4409. function panTo(x, y, height, xSpeed, ySpeed, heightSpeed, timestamp, remaining) {
  4410. if (lastTime === undefined) {
  4411. lastTime = timestamp;
  4412. }
  4413. dt = timestamp - lastTime;
  4414. remaining -= dt;
  4415. if (remaining < 0) {
  4416. dt += remaining
  4417. }
  4418. let newX = config.x + xSpeed * dt;
  4419. let newY = config.y + ySpeed * dt;
  4420. let newHeight = config.height.toNumber("meters") + heightSpeed * dt;
  4421. if (remaining > 0) {
  4422. requestAnimationFrame((timestamp) => panTo(x, y, height, xSpeed, ySpeed, heightSpeed, timestamp, remaining))
  4423. } else {
  4424. Object.keys(entities).forEach(key => {
  4425. document.querySelector("#entity-" + key).classList.remove("no-transition");
  4426. });
  4427. }
  4428. config.x = newX;
  4429. config.y = newY;
  4430. config.height = math.unit(newHeight, "meters");
  4431. updateSizes();
  4432. }
  4433. function getVerticalOffset() {
  4434. if (config.groundPos === "very-high") {
  4435. return config.height.toNumber("meters") / 12 * 5;
  4436. } else if (config.groundPos === "high") {
  4437. return config.height.toNumber("meters") / 12 * 4;
  4438. } else if (config.groundPos === "medium") {
  4439. return config.height.toNumber("meters") / 12 * 3;
  4440. } else if (config.groundPos === "low") {
  4441. return config.height.toNumber("meters") / 12 * 2;
  4442. } else if (config.groundPos === "very-low") {
  4443. return config.height.toNumber("meters") / 12;
  4444. } else {
  4445. return 0;
  4446. }
  4447. }