less copy protection, more size visualization
25개 이상의 토픽을 선택하실 수 없습니다. Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

3927 lines
117 KiB

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