less copy protection, more size visualization
Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.
 
 
 

3840 řádky
115 KiB

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