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

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