less copy protection, more size visualization
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

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