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

3892 lines
117 KiB

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