less copy protection, more size visualization
Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.
 
 
 

3097 строки
92 KiB

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