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

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