less copy protection, more size visualization
Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.
 
 
 

4942 řádky
149 KiB

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