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

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