less copy protection, more size visualization
Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.
 
 
 

4844 lignes
146 KiB

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