less copy protection, more size visualization
Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.
 
 
 

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