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.
 
 
 

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