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

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