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.
 
 
 

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