less copy protection, more size visualization
No puede seleccionar más de 25 temas Los temas deben comenzar con una letra o número, pueden incluir guiones ('-') y pueden tener hasta 35 caracteres de largo.
 
 
 

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