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

5373 строки
163 KiB

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