less copy protection, more size visualization
Nie możesz wybrać więcej, niż 25 tematów Tematy muszą się zaczynać od litery lub cyfry, mogą zawierać myślniki ('-') i mogą mieć do 35 znaków.
 
 
 

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