less copy protection, more size visualization
Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.
 
 
 

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