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.
 
 
 

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