less copy protection, more size visualization
No puede seleccionar más de 25 temas Los temas deben comenzar con una letra o número, pueden incluir guiones ('-') y pueden tener hasta 35 caracteres de largo.
 
 
 

4807 líneas
145 KiB

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