less copy protection, more size visualization
25개 이상의 토픽을 선택하실 수 없습니다. Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

4356 lines
132 KiB

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