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.
 
 
 

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