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

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