less copy protection, more size visualization
Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.
 
 
 

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