less copy protection, more size visualization
Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.
 
 
 

3896 lignes
117 KiB

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