less copy protection, more size visualization
25'ten fazla konu seçemezsiniz Konular bir harf veya rakamla başlamalı, kısa çizgiler ('-') içerebilir ve en fazla 35 karakter uzunluğunda olabilir.
 
 
 

5406 satır
164 KiB

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