less copy protection, more size visualization
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

5449 lines
165 KiB

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