less copy protection, more size visualization
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

3288 lines
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. if (clicked == element) {
  958. clicked = null;
  959. }
  960. const option = document.querySelector("#options-selected-entity-" + element.dataset.key);
  961. option.parentElement.removeChild(option);
  962. delete entities[element.dataset.key];
  963. const bottomName = document.querySelector("#bottom-name-" + element.dataset.key);
  964. const topName = document.querySelector("#top-name-" + element.dataset.key);
  965. bottomName.parentElement.removeChild(bottomName);
  966. topName.parentElement.removeChild(topName);
  967. element.parentElement.removeChild(element);
  968. }
  969. function checkEntity(entity) {
  970. Object.values(entity.views).forEach(view => {
  971. if (authorsOf(view.image.source) === undefined) {
  972. console.warn("No authors: " + view.image.source);
  973. }
  974. });
  975. }
  976. function displayEntity(entity, view, x, y, selectEntity = false, refresh = false) {
  977. checkEntity(entity);
  978. const box = document.createElement("div");
  979. box.classList.add("entity-box");
  980. const img = document.createElement("img");
  981. img.classList.add("entity-image");
  982. img.addEventListener("dragstart", e => {
  983. e.preventDefault();
  984. });
  985. const nameTag = document.createElement("div");
  986. nameTag.classList.add("entity-name");
  987. nameTag.innerText = entity.name;
  988. box.appendChild(img);
  989. box.appendChild(nameTag);
  990. const image = entity.views[view].image;
  991. img.src = image.source;
  992. if (image.bottom !== undefined) {
  993. img.style.setProperty("--offset", ((-1 + image.bottom) * 100) + "%")
  994. } else {
  995. img.style.setProperty("--offset", ((-1) * 100) + "%")
  996. }
  997. box.dataset.x = x;
  998. box.dataset.y = y;
  999. img.addEventListener("mousedown", e => { if (e.which == 1) { testClick(e); if (clicked) { e.stopPropagation() } } });
  1000. img.addEventListener("touchstart", e => {
  1001. const fakeEvent = {
  1002. target: e.target,
  1003. clientX: e.touches[0].clientX,
  1004. clientY: e.touches[0].clientY,
  1005. which: 1
  1006. };
  1007. testClick(fakeEvent);
  1008. if (clicked) { e.stopPropagation() }
  1009. });
  1010. const heightBar = document.createElement("div");
  1011. heightBar.classList.add("height-bar");
  1012. box.appendChild(heightBar);
  1013. box.id = "entity-" + entityIndex;
  1014. box.dataset.key = entityIndex;
  1015. entity.view = view;
  1016. entity.priority = 0;
  1017. entities[entityIndex] = entity;
  1018. entity.index = entityIndex;
  1019. const world = document.querySelector("#entities");
  1020. world.appendChild(box);
  1021. const bottomName = document.createElement("div");
  1022. bottomName.classList.add("bottom-name");
  1023. bottomName.id = "bottom-name-" + entityIndex;
  1024. bottomName.innerText = entity.name;
  1025. bottomName.addEventListener("click", () => select(box));
  1026. world.appendChild(bottomName);
  1027. const topName = document.createElement("div");
  1028. topName.classList.add("top-name");
  1029. topName.id = "top-name-" + entityIndex;
  1030. topName.innerText = entity.name;
  1031. topName.addEventListener("click", () => select(box));
  1032. world.appendChild(topName);
  1033. const entityOption = document.createElement("option");
  1034. entityOption.id = "options-selected-entity-" + entityIndex;
  1035. entityOption.value = entityIndex;
  1036. entityOption.innerText = entity.name;
  1037. document.getElementById("options-selected-entity").appendChild(entityOption);
  1038. entityIndex += 1;
  1039. if (config.autoFit) {
  1040. fitWorld();
  1041. }
  1042. if (selectEntity)
  1043. select(box);
  1044. entity.dirty = true;
  1045. if (refresh && config.autoFitAdd) {
  1046. const x = parseFloat(selected.dataset.x);
  1047. const y = parseFloat(selected.dataset.y);
  1048. config.x = x;
  1049. config.y = y;
  1050. const entity = entities[selected.dataset.key];
  1051. const height = math.multiply(entity.views[entity.view].height, 1.1);
  1052. setWorldHeight(config.height, height);
  1053. }
  1054. if (refresh)
  1055. updateSizes(true);
  1056. }
  1057. window.onblur = function () {
  1058. altHeld = false;
  1059. shiftHeld = false;
  1060. }
  1061. window.onfocus = function () {
  1062. window.dispatchEvent(new Event("keydown"));
  1063. }
  1064. // thanks to https://developers.google.com/web/fundamentals/native-hardware/fullscreen
  1065. function toggleFullScreen() {
  1066. var doc = window.document;
  1067. var docEl = doc.documentElement;
  1068. var requestFullScreen = docEl.requestFullscreen || docEl.mozRequestFullScreen || docEl.webkitRequestFullScreen || docEl.msRequestFullscreen;
  1069. var cancelFullScreen = doc.exitFullscreen || doc.mozCancelFullScreen || doc.webkitExitFullscreen || doc.msExitFullscreen;
  1070. if (!doc.fullscreenElement && !doc.mozFullScreenElement && !doc.webkitFullscreenElement && !doc.msFullscreenElement) {
  1071. requestFullScreen.call(docEl);
  1072. }
  1073. else {
  1074. cancelFullScreen.call(doc);
  1075. }
  1076. }
  1077. function handleResize() {
  1078. const oldCanvasWidth = canvasWidth;
  1079. entityX = document.querySelector("#entities").getBoundingClientRect().x;
  1080. canvasWidth = document.querySelector("#display").clientWidth - 100;
  1081. canvasHeight = document.querySelector("#display").clientHeight - 50;
  1082. const change = oldCanvasWidth / canvasWidth;
  1083. updateSizes();
  1084. }
  1085. function prepareSidebar() {
  1086. const menubar = document.querySelector("#sidebar-menu");
  1087. [
  1088. {
  1089. name: "Show/hide sidebar",
  1090. id: "menu-toggle-sidebar",
  1091. icon: "fas fa-chevron-circle-down",
  1092. rotates: true
  1093. },
  1094. {
  1095. name: "Fullscreen",
  1096. id: "menu-fullscreen",
  1097. icon: "fas fa-compress"
  1098. },
  1099. {
  1100. name: "Clear",
  1101. id: "menu-clear",
  1102. icon: "fas fa-file"
  1103. },
  1104. {
  1105. name: "Sort by height",
  1106. id: "menu-order-height",
  1107. icon: "fas fa-sort-numeric-up"
  1108. },
  1109. {
  1110. name: "Permalink",
  1111. id: "menu-permalink",
  1112. icon: "fas fa-link"
  1113. },
  1114. {
  1115. name: "Export to clipboard",
  1116. id: "menu-export",
  1117. icon: "fas fa-share"
  1118. },
  1119. {
  1120. name: "Import from clipboard",
  1121. id: "menu-import",
  1122. icon: "fas fa-share",
  1123. classes: ["flipped"]
  1124. },
  1125. {
  1126. name: "Save",
  1127. id: "menu-save",
  1128. icon: "fas fa-download"
  1129. },
  1130. {
  1131. name: "Load",
  1132. id: "menu-load",
  1133. icon: "fas fa-upload"
  1134. },
  1135. {
  1136. name: "Load Autosave",
  1137. id: "menu-load-autosave",
  1138. icon: "fas fa-redo"
  1139. },
  1140. {
  1141. name: "Add Image",
  1142. id: "menu-add-image",
  1143. icon: "fas fa-camera"
  1144. }
  1145. ].forEach(entry => {
  1146. const buttonHolder = document.createElement("div");
  1147. buttonHolder.classList.add("menu-button-holder");
  1148. const button = document.createElement("button");
  1149. button.id = entry.id;
  1150. button.classList.add("menu-button");
  1151. const icon = document.createElement("i");
  1152. icon.classList.add(...entry.icon.split(" "));
  1153. if (entry.rotates) {
  1154. icon.classList.add("rotate-backward", "transitions");
  1155. }
  1156. if (entry.classes) {
  1157. entry.classes.forEach(cls => icon.classList.add(cls));
  1158. }
  1159. const actionText = document.createElement("span");
  1160. actionText.innerText = entry.name;
  1161. actionText.classList.add("menu-text");
  1162. const srText = document.createElement("span");
  1163. srText.classList.add("sr-only");
  1164. srText.innerText = entry.name;
  1165. button.appendChild(icon);
  1166. button.appendChild(srText);
  1167. buttonHolder.appendChild(button);
  1168. buttonHolder.appendChild(actionText);
  1169. menubar.appendChild(buttonHolder);
  1170. });
  1171. }
  1172. function checkBodyClass(cls) {
  1173. return document.body.classList.contains(cls);
  1174. }
  1175. function toggleBodyClass(cls, setting) {
  1176. if (setting) {
  1177. document.body.classList.add(cls);
  1178. } else {
  1179. document.body.classList.remove(cls);
  1180. }
  1181. }
  1182. const settingsData = {
  1183. "lock-y-axis": {
  1184. name: "Lock Y-Axis",
  1185. desc: "Keep the camera at ground-level",
  1186. type: "toggle",
  1187. default: true,
  1188. get value() {
  1189. return config.lockYAxis;
  1190. },
  1191. set value(param) {
  1192. config.lockYAxis = param;
  1193. if (param) {
  1194. config.y = 0;
  1195. updateSizes();
  1196. document.querySelector("#scroll-up").disabled = true;
  1197. document.querySelector("#scroll-down").disabled = true;
  1198. } else {
  1199. document.querySelector("#scroll-up").disabled = false;
  1200. document.querySelector("#scroll-down").disabled = false;
  1201. }
  1202. }
  1203. },
  1204. "auto-scale": {
  1205. name: "Auto-Size World",
  1206. desc: "Constantly zoom to fit the largest entity",
  1207. type: "toggle",
  1208. default: false,
  1209. get value() {
  1210. return config.autoFit;
  1211. },
  1212. set value(param) {
  1213. config.autoFit = param;
  1214. checkFitWorld();
  1215. }
  1216. },
  1217. "zoom-when-adding": {
  1218. name: "Zoom When Adding",
  1219. desc: "Zoom to fit when you add a new entity",
  1220. type: "toggle",
  1221. default: true,
  1222. get value() {
  1223. return config.autoFitAdd;
  1224. },
  1225. set value(param) {
  1226. config.autoFitAdd = param;
  1227. }
  1228. },
  1229. "zoom-when-sizing": {
  1230. name: "Zoom When Sizing",
  1231. desc: "Zoom to fit when you select an entity's size",
  1232. type: "toggle",
  1233. default: true,
  1234. get value() {
  1235. return config.autoFitSize;
  1236. },
  1237. set value(param) {
  1238. config.autoFitSize = param;
  1239. }
  1240. },
  1241. "names": {
  1242. name: "Show Names",
  1243. desc: "Display names over entities",
  1244. type: "toggle",
  1245. default: true,
  1246. get value() {
  1247. return checkBodyClass("toggle-entity-name");
  1248. },
  1249. set value(param) {
  1250. toggleBodyClass("toggle-entity-name", param);
  1251. }
  1252. },
  1253. "bottom-names": {
  1254. name: "Bottom Names",
  1255. desc: "Display names at the bottom",
  1256. type: "toggle",
  1257. default: false,
  1258. get value() {
  1259. return checkBodyClass("toggle-bottom-name");
  1260. },
  1261. set value(param) {
  1262. toggleBodyClass("toggle-bottom-name", param);
  1263. }
  1264. },
  1265. "top-names": {
  1266. name: "Show Arrows",
  1267. desc: "Point to entities that are much larger than the current view",
  1268. type: "toggle",
  1269. default: false,
  1270. get value() {
  1271. return checkBodyClass("toggle-top-name");
  1272. },
  1273. set value(param) {
  1274. toggleBodyClass("toggle-top-name", param);
  1275. }
  1276. },
  1277. "height-bars": {
  1278. name: "Height Bars",
  1279. desc: "Draw dashed lines to the top of each entity",
  1280. type: "toggle",
  1281. default: false,
  1282. get value() {
  1283. return checkBodyClass("toggle-height-bars");
  1284. },
  1285. set value(param) {
  1286. toggleBodyClass("toggle-height-bars", param);
  1287. }
  1288. },
  1289. "glowing-entities": {
  1290. name: "Glowing Edges",
  1291. desc: "Makes all entities glow",
  1292. type: "toggle",
  1293. default: false,
  1294. get value() {
  1295. return checkBodyClass("toggle-entity-glow");
  1296. },
  1297. set value(param) {
  1298. toggleBodyClass("toggle-entity-glow", param);
  1299. }
  1300. },
  1301. "solid-ground": {
  1302. name: "Solid Ground",
  1303. desc: "Draw solid ground at the y=0 line",
  1304. type: "toggle",
  1305. default: false,
  1306. get value() {
  1307. return checkBodyClass("toggle-bottom-cover");
  1308. },
  1309. set value(param) {
  1310. toggleBodyClass("toggle-bottom-cover", param);
  1311. }
  1312. },
  1313. "show-scale": {
  1314. name: "Show Scale",
  1315. desc: "Show the scale",
  1316. type: "toggle",
  1317. default: true,
  1318. get value() {
  1319. return checkBodyClass("toggle-scale");
  1320. },
  1321. set value(param) {
  1322. toggleBodyClass("toggle-scale", param);
  1323. }
  1324. },
  1325. }
  1326. function getBoundingBox(entities, margin = 0.05) {
  1327. }
  1328. function prepareSettings(userSettings) {
  1329. const menubar = document.querySelector("#settings-menu");
  1330. Object.entries(settingsData).forEach(([id, entry]) => {
  1331. const holder = document.createElement("label");
  1332. holder.classList.add("settings-holder");
  1333. const input = document.createElement("input");
  1334. input.id = "setting-" + id;
  1335. const name = document.createElement("label");
  1336. name.innerText = entry.name;
  1337. name.classList.add("settings-name");
  1338. name.setAttribute("for", input.id);
  1339. const desc = document.createElement("label");
  1340. desc.innerText = entry.desc;
  1341. desc.classList.add("settings-desc");
  1342. desc.setAttribute("for", input.id);
  1343. if (entry.type == "toggle") {
  1344. input.type = "checkbox";
  1345. input.checked = userSettings[id] === undefined ? entry.default : userSettings[id];
  1346. holder.setAttribute("for", input.id);
  1347. input.appendChild(name);
  1348. input.appendChild(desc);
  1349. holder.appendChild(input);
  1350. holder.appendChild(name);
  1351. holder.appendChild(desc);
  1352. menubar.appendChild(holder);
  1353. const update = () => {
  1354. if (input.checked) {
  1355. holder.classList.add("enabled");
  1356. holder.classList.remove("disabled");
  1357. } else {
  1358. holder.classList.remove("enabled");
  1359. holder.classList.add("disabled");
  1360. }
  1361. entry.value = input.checked;
  1362. }
  1363. update();
  1364. input.addEventListener("change", update);
  1365. }
  1366. })
  1367. }
  1368. function prepareMenu() {
  1369. prepareSidebar();
  1370. if (checkHelpDate()) {
  1371. document.querySelector("#open-help").classList.add("highlighted");
  1372. }
  1373. }
  1374. function getUserSettings() {
  1375. try {
  1376. const settings = JSON.parse(localStorage.getItem("settings"));
  1377. return settings === null ? {} : settings;
  1378. } catch {
  1379. return {};
  1380. }
  1381. }
  1382. function exportUserSettings() {
  1383. const settings = {};
  1384. Object.entries(settingsData).forEach(([id, entry]) => {
  1385. settings[id] = entry.value;
  1386. });
  1387. return settings;
  1388. }
  1389. function setUserSettings(settings) {
  1390. try {
  1391. localStorage.setItem("settings", JSON.stringify(settings));
  1392. } catch {
  1393. // :(
  1394. }
  1395. }
  1396. const lastHelpChange = 1587847743294;
  1397. function checkHelpDate() {
  1398. try {
  1399. const old = localStorage.getItem("help-viewed");
  1400. if (old === null || old < lastHelpChange) {
  1401. return true;
  1402. }
  1403. return false;
  1404. } catch {
  1405. console.warn("Could not set the help-viewed date");
  1406. return false;
  1407. }
  1408. }
  1409. function setHelpDate() {
  1410. try {
  1411. localStorage.setItem("help-viewed", Date.now());
  1412. } catch {
  1413. console.warn("Could not set the help-viewed date");
  1414. }
  1415. }
  1416. function doYScroll() {
  1417. const worldHeight = config.height.toNumber("meters");
  1418. config.y += scrollDirection * worldHeight / 180;
  1419. updateSizes();
  1420. scrollDirection *= 1.05;
  1421. }
  1422. function doXScroll() {
  1423. const worldWidth = config.height.toNumber("meters") / canvasHeight * canvasWidth;
  1424. config.x += scrollDirection * worldWidth / 180 ;
  1425. updateSizes();
  1426. scrollDirection *= 1.05;
  1427. }
  1428. function doZoom() {
  1429. const oldHeight = config.height;
  1430. setWorldHeight(oldHeight, math.multiply(oldHeight, 1 + zoomDirection / 10));
  1431. zoomDirection *= 1.05;
  1432. }
  1433. function doSize() {
  1434. if (selected) {
  1435. const entity = entities[selected.dataset.key];
  1436. const oldHeight = entity.views[entity.view].height;
  1437. entity.views[entity.view].height = math.multiply(oldHeight, sizeDirection < 0 ? -1/sizeDirection : sizeDirection);
  1438. entity.dirty = true;
  1439. updateEntityOptions(entity, entity.view);
  1440. updateViewOptions(entity, entity.view);
  1441. updateSizes(true);
  1442. sizeDirection *= 1.01;
  1443. const ownHeight = entity.views[entity.view].height.toNumber("meters");
  1444. const worldHeight = config.height.toNumber("meters");
  1445. if (ownHeight > worldHeight) {
  1446. setWorldHeight(config.height, entity.views[entity.view].height)
  1447. } else if (ownHeight * 10 < worldHeight) {
  1448. setWorldHeight(config.height, math.multiply(entity.views[entity.view].height, 10));
  1449. }
  1450. }
  1451. }
  1452. function prepareHelp() {
  1453. const toc = document.querySelector("#table-of-contents");
  1454. const holder = document.querySelector("#help-contents-holder");
  1455. document.querySelectorAll("#help-contents h2").forEach(header => {
  1456. const li = document.createElement("li");
  1457. li.innerText = header.textContent;
  1458. li.addEventListener("click", e => {
  1459. holder.scrollTop = header.offsetTop;
  1460. });
  1461. toc.appendChild(li);
  1462. });
  1463. }
  1464. document.addEventListener("DOMContentLoaded", () => {
  1465. prepareMenu();
  1466. prepareEntities();
  1467. prepareHelp();
  1468. document.querySelector("#open-help").addEventListener("click", e => {
  1469. setHelpDate();
  1470. document.querySelector("#help-menu").classList.add("visible");
  1471. document.querySelector("#open-help").classList.remove("highlighted");
  1472. });
  1473. document.querySelector("#close-help").addEventListener("click", e => {
  1474. document.querySelector("#help-menu").classList.remove("visible");
  1475. });
  1476. document.querySelector("#copy-screenshot").addEventListener("click", e => {
  1477. copyScreenshot();
  1478. toast("Copied to clipboard!");
  1479. });
  1480. document.querySelector("#save-screenshot").addEventListener("click", e => {
  1481. saveScreenshot();
  1482. });
  1483. document.querySelector("#toggle-menu").addEventListener("click", e => {
  1484. const popoutMenu = document.querySelector("#sidebar-menu");
  1485. if (popoutMenu.classList.contains("visible")) {
  1486. popoutMenu.classList.remove("visible");
  1487. } else {
  1488. document.querySelectorAll(".popout-menu").forEach(menu => menu.classList.remove("visible"));
  1489. const rect = e.target.getBoundingClientRect();
  1490. popoutMenu.classList.add("visible");
  1491. popoutMenu.style.left = rect.x + rect.width + 10 + "px";
  1492. popoutMenu.style.top = rect.y + rect.height + 10 + "px";
  1493. }
  1494. e.stopPropagation();
  1495. });
  1496. document.querySelector("#sidebar-menu").addEventListener("click", e => {
  1497. e.stopPropagation();
  1498. });
  1499. document.addEventListener("click", e => {
  1500. document.querySelector("#sidebar-menu").classList.remove("visible");
  1501. });
  1502. document.querySelector("#toggle-settings").addEventListener("click", e => {
  1503. const popoutMenu = document.querySelector("#settings-menu");
  1504. if (popoutMenu.classList.contains("visible")) {
  1505. popoutMenu.classList.remove("visible");
  1506. } else {
  1507. document.querySelectorAll(".popout-menu").forEach(menu => menu.classList.remove("visible"));
  1508. const rect = e.target.getBoundingClientRect();
  1509. popoutMenu.classList.add("visible");
  1510. popoutMenu.style.left = rect.x + rect.width + 10 + "px";
  1511. popoutMenu.style.top = rect.y + rect.height + 10 + "px";
  1512. }
  1513. e.stopPropagation();
  1514. });
  1515. document.querySelector("#settings-menu").addEventListener("click", e => {
  1516. e.stopPropagation();
  1517. });
  1518. document.addEventListener("click", e => {
  1519. document.querySelector("#settings-menu").classList.remove("visible");
  1520. });
  1521. window.addEventListener("unload", () => {
  1522. saveScene("autosave");
  1523. setUserSettings(exportUserSettings());
  1524. });
  1525. document.querySelector("#options-selected-entity").addEventListener("input", e => {
  1526. if (e.target.value == "None") {
  1527. deselect()
  1528. } else {
  1529. select(document.querySelector("#entity-" + e.target.value));
  1530. }
  1531. });
  1532. document.querySelector("#menu-toggle-sidebar").addEventListener("click", e => {
  1533. const sidebar = document.querySelector("#options");
  1534. if (sidebar.classList.contains("hidden")) {
  1535. sidebar.classList.remove("hidden");
  1536. e.target.classList.remove("rotate-forward");
  1537. e.target.classList.add("rotate-backward");
  1538. } else {
  1539. sidebar.classList.add("hidden");
  1540. e.target.classList.add("rotate-forward");
  1541. e.target.classList.remove("rotate-backward");
  1542. }
  1543. handleResize();
  1544. });
  1545. document.querySelector("#menu-fullscreen").addEventListener("click", toggleFullScreen);
  1546. document.querySelector("#options-order-forward").addEventListener("click", e => {
  1547. if (selected) {
  1548. entities[selected.dataset.key].priority += 1;
  1549. }
  1550. document.querySelector("#options-order-display").innerText = entities[selected.dataset.key].priority;
  1551. updateSizes();
  1552. });
  1553. document.querySelector("#options-order-back").addEventListener("click", e => {
  1554. if (selected) {
  1555. entities[selected.dataset.key].priority -= 1;
  1556. }
  1557. document.querySelector("#options-order-display").innerText = entities[selected.dataset.key].priority;
  1558. updateSizes();
  1559. });
  1560. const sceneChoices = document.querySelector("#scene-choices");
  1561. Object.entries(scenes).forEach(([id, scene]) => {
  1562. const option = document.createElement("option");
  1563. option.innerText = id;
  1564. option.value = id;
  1565. sceneChoices.appendChild(option);
  1566. });
  1567. document.querySelector("#load-scene").addEventListener("click", e => {
  1568. const chosen = sceneChoices.value;
  1569. removeAllEntities();
  1570. scenes[chosen]();
  1571. });
  1572. entityX = document.querySelector("#entities").getBoundingClientRect().x;
  1573. canvasWidth = document.querySelector("#display").clientWidth - 100;
  1574. canvasHeight = document.querySelector("#display").clientHeight - 50;
  1575. document.querySelector("#options-height-value").addEventListener("change", e => {
  1576. updateWorldHeight();
  1577. })
  1578. document.querySelector("#options-height-value").addEventListener("keydown", e => {
  1579. e.stopPropagation();
  1580. })
  1581. const unitSelector = document.querySelector("#options-height-unit");
  1582. unitChoices.length.forEach(lengthOption => {
  1583. const option = document.createElement("option");
  1584. option.innerText = lengthOption;
  1585. option.value = lengthOption;
  1586. if (lengthOption === "meters") {
  1587. option.selected = true;
  1588. }
  1589. unitSelector.appendChild(option);
  1590. });
  1591. unitSelector.setAttribute("oldUnit", "meters");
  1592. unitSelector.addEventListener("input", e => {
  1593. checkFitWorld();
  1594. const scaleInput = document.querySelector("#options-height-value");
  1595. const newVal = math.unit(scaleInput.value, unitSelector.getAttribute("oldUnit")).toNumber(e.target.value);
  1596. setNumericInput(scaleInput, newVal);
  1597. updateWorldHeight();
  1598. unitSelector.setAttribute("oldUnit", unitSelector.value);
  1599. });
  1600. param = new URL(window.location.href).searchParams.get("scene");
  1601. if (param === null) {
  1602. scenes["Default"]();
  1603. }
  1604. else {
  1605. try {
  1606. const data = JSON.parse(b64DecodeUnicode(param));
  1607. if (data.entities === undefined) {
  1608. return;
  1609. }
  1610. if (data.world === undefined) {
  1611. return;
  1612. }
  1613. importScene(data);
  1614. } catch (err) {
  1615. console.error(err);
  1616. scenes["Default"]();
  1617. // probably wasn't valid data
  1618. }
  1619. }
  1620. document.querySelector("#world").addEventListener("wheel", e => {
  1621. if (shiftHeld) {
  1622. if (selected) {
  1623. const dir = e.deltaY > 0 ? 10 / 11 : 11 / 10;
  1624. const entity = entities[selected.dataset.key];
  1625. entity.views[entity.view].height = math.multiply(entity.views[entity.view].height, dir);
  1626. entity.dirty = true;
  1627. updateEntityOptions(entity, entity.view);
  1628. updateViewOptions(entity, entity.view);
  1629. updateSizes(true);
  1630. } else {
  1631. const worldWidth = config.height.toNumber("meters") / canvasHeight * canvasWidth;
  1632. config.x += (e.deltaY > 0 ? 1 : -1) * worldWidth / 20 ;
  1633. updateSizes();
  1634. updateSizes();
  1635. }
  1636. } else {
  1637. if (config.autoFit) {
  1638. toastRateLimit("Zoom is locked! Check Settings to disable.", "zoom-lock", 1000);
  1639. } else {
  1640. const dir = e.deltaY < 0 ? 10 / 11 : 11 / 10;
  1641. setWorldHeight(config.height, math.multiply(config.height, dir));
  1642. updateWorldOptions();
  1643. }
  1644. }
  1645. checkFitWorld();
  1646. })
  1647. document.querySelector("#world").addEventListener("mousedown", e => {
  1648. // only middle mouse clicks
  1649. if (e.which == 2) {
  1650. panning = true;
  1651. panOffsetX = e.clientX;
  1652. panOffsetY = e.clientY;
  1653. Object.keys(entities).forEach(key => {
  1654. document.querySelector("#entity-" + key).classList.add("no-transition");
  1655. });
  1656. }
  1657. });
  1658. document.querySelector("#world").addEventListener("mouseup", e => {
  1659. if (e.which == 2) {
  1660. panning = false;
  1661. Object.keys(entities).forEach(key => {
  1662. document.querySelector("#entity-" + key).classList.remove("no-transition");
  1663. });
  1664. }
  1665. });
  1666. document.querySelector("#world").addEventListener("touchstart", e => {
  1667. panning = true;
  1668. panOffsetX = e.touches[0].clientX;
  1669. panOffsetY = e.touches[0].clientY;
  1670. e.preventDefault();
  1671. Object.keys(entities).forEach(key => {
  1672. document.querySelector("#entity-" + key).classList.add("no-transition");
  1673. });
  1674. });
  1675. document.querySelector("#world").addEventListener("touchend", e => {
  1676. panning = false;
  1677. Object.keys(entities).forEach(key => {
  1678. document.querySelector("#entity-" + key).classList.remove("no-transition");
  1679. });
  1680. });
  1681. document.querySelector("body").appendChild(testCtx.canvas);
  1682. updateSizes();
  1683. world.addEventListener("mousedown", e => deselect(e));
  1684. world.addEventListener("touchstart", e => deselect({
  1685. which: 1,
  1686. }));
  1687. document.querySelector("#entities").addEventListener("mousedown", deselect);
  1688. document.querySelector("#display").addEventListener("mousedown", deselect);
  1689. document.addEventListener("mouseup", e => clickUp(e));
  1690. document.addEventListener("touchend", e => {
  1691. const fakeEvent = {
  1692. target: e.target,
  1693. clientX: e.changedTouches[0].clientX,
  1694. clientY: e.changedTouches[0].clientY,
  1695. which: 1
  1696. };
  1697. clickUp(fakeEvent);
  1698. });
  1699. const viewList = document.querySelector("#entity-view");
  1700. document.querySelector("#entity-view").addEventListener("input", e => {
  1701. const entity = entities[selected.dataset.key];
  1702. entity.view = e.target.value;
  1703. const image = entities[selected.dataset.key].views[e.target.value].image;
  1704. selected.querySelector(".entity-image").src = image.source;
  1705. configViewOptions(entity, entity.view);
  1706. displayAttribution(image.source);
  1707. if (image.bottom !== undefined) {
  1708. selected.querySelector(".entity-image").style.setProperty("--offset", ((-1 + image.bottom) * 100) + "%")
  1709. } else {
  1710. selected.querySelector(".entity-image").style.setProperty("--offset", ((-1) * 100) + "%")
  1711. }
  1712. updateSizes();
  1713. updateEntityOptions(entities[selected.dataset.key], e.target.value);
  1714. updateViewOptions(entities[selected.dataset.key], e.target.value);
  1715. });
  1716. document.querySelector("#entity-view").addEventListener("input", e => {
  1717. if (viewList.options[viewList.selectedIndex].classList.contains("nsfw")) {
  1718. viewList.classList.add("nsfw");
  1719. } else {
  1720. viewList.classList.remove("nsfw");
  1721. }
  1722. })
  1723. clearViewList();
  1724. document.querySelector("#menu-clear").addEventListener("click", e => {
  1725. removeAllEntities();
  1726. });
  1727. document.querySelector("#delete-entity").disabled = true;
  1728. document.querySelector("#delete-entity").addEventListener("click", e => {
  1729. if (selected) {
  1730. removeEntity(selected);
  1731. selected = null;
  1732. }
  1733. });
  1734. document.querySelector("#menu-order-height").addEventListener("click", e => {
  1735. const order = Object.keys(entities).sort((a, b) => {
  1736. const entA = entities[a];
  1737. const entB = entities[b];
  1738. const viewA = entA.view;
  1739. const viewB = entB.view;
  1740. const heightA = entA.views[viewA].height.to("meter").value;
  1741. const heightB = entB.views[viewB].height.to("meter").value;
  1742. return heightA - heightB;
  1743. });
  1744. arrangeEntities(order);
  1745. });
  1746. // TODO: write some generic logic for this lol
  1747. document.querySelector("#scroll-left").addEventListener("mousedown", e => {
  1748. scrollDirection = -1;
  1749. clearInterval(scrollHandle);
  1750. scrollHandle = setInterval(doXScroll, 1000 / 20);
  1751. e.stopPropagation();
  1752. });
  1753. document.querySelector("#scroll-right").addEventListener("mousedown", e => {
  1754. scrollDirection = 1;
  1755. clearInterval(scrollHandle);
  1756. scrollHandle = setInterval(doXScroll, 1000 / 20);
  1757. e.stopPropagation();
  1758. });
  1759. document.querySelector("#scroll-left").addEventListener("touchstart", e => {
  1760. scrollDirection = -1;
  1761. clearInterval(scrollHandle);
  1762. scrollHandle = setInterval(doXScroll, 1000 / 20);
  1763. e.stopPropagation();
  1764. });
  1765. document.querySelector("#scroll-right").addEventListener("touchstart", e => {
  1766. scrollDirection = 1;
  1767. clearInterval(scrollHandle);
  1768. scrollHandle = setInterval(doXScroll, 1000 / 20);
  1769. e.stopPropagation();
  1770. });
  1771. document.querySelector("#scroll-up").addEventListener("mousedown", e => {
  1772. scrollDirection = 1;
  1773. clearInterval(scrollHandle);
  1774. scrollHandle = setInterval(doYScroll, 1000 / 20);
  1775. e.stopPropagation();
  1776. });
  1777. document.querySelector("#scroll-down").addEventListener("mousedown", e => {
  1778. scrollDirection = -1;
  1779. clearInterval(scrollHandle);
  1780. scrollHandle = setInterval(doYScroll, 1000 / 20);
  1781. e.stopPropagation();
  1782. });
  1783. document.querySelector("#scroll-up").addEventListener("touchstart", e => {
  1784. scrollDirection = 1;
  1785. clearInterval(scrollHandle);
  1786. scrollHandle = setInterval(doYScroll, 1000 / 20);
  1787. e.stopPropagation();
  1788. });
  1789. document.querySelector("#scroll-down").addEventListener("touchstart", e => {
  1790. scrollDirection = -1;
  1791. clearInterval(scrollHandle);
  1792. scrollHandle = setInterval(doYScroll, 1000 / 20);
  1793. e.stopPropagation();
  1794. });
  1795. document.addEventListener("mouseup", e => {
  1796. clearInterval(scrollHandle);
  1797. scrollHandle = null;
  1798. });
  1799. document.addEventListener("touchend", e => {
  1800. clearInterval(scrollHandle);
  1801. scrollHandle = null;
  1802. });
  1803. document.querySelector("#zoom-in").addEventListener("mousedown", e => {
  1804. zoomDirection = -1;
  1805. clearInterval(zoomHandle);
  1806. zoomHandle = setInterval(doZoom, 1000 / 20);
  1807. e.stopPropagation();
  1808. });
  1809. document.querySelector("#zoom-out").addEventListener("mousedown", e => {
  1810. zoomDirection = 1;
  1811. clearInterval(zoomHandle);
  1812. zoomHandle = setInterval(doZoom, 1000 / 20);
  1813. e.stopPropagation();
  1814. });
  1815. document.querySelector("#zoom-in").addEventListener("touchstart", e => {
  1816. zoomDirection = -1;
  1817. clearInterval(zoomHandle);
  1818. zoomHandle = setInterval(doZoom, 1000 / 20);
  1819. e.stopPropagation();
  1820. });
  1821. document.querySelector("#zoom-out").addEventListener("touchstart", e => {
  1822. zoomDirection = 1;
  1823. clearInterval(zoomHandle);
  1824. zoomHandle = setInterval(doZoom, 1000 / 20);
  1825. e.stopPropagation();
  1826. });
  1827. document.addEventListener("mouseup", e => {
  1828. clearInterval(zoomHandle);
  1829. zoomHandle = null;
  1830. });
  1831. document.addEventListener("touchend", e => {
  1832. clearInterval(zoomHandle);
  1833. zoomHandle = null;
  1834. });
  1835. document.querySelector("#shrink").addEventListener("mousedown", e => {
  1836. sizeDirection = -1;
  1837. clearInterval(sizeHandle);
  1838. sizeHandle = setInterval(doSize, 1000 / 20);
  1839. e.stopPropagation();
  1840. });
  1841. document.querySelector("#grow").addEventListener("mousedown", e => {
  1842. sizeDirection = 1;
  1843. clearInterval(sizeHandle);
  1844. sizeHandle = setInterval(doSize, 1000 / 20);
  1845. e.stopPropagation();
  1846. });
  1847. document.querySelector("#shrink").addEventListener("touchstart", e => {
  1848. sizeDirection = -1;
  1849. clearInterval(sizeHandle);
  1850. sizeHandle = setInterval(doSize, 1000 / 20);
  1851. e.stopPropagation();
  1852. });
  1853. document.querySelector("#grow").addEventListener("touchstart", e => {
  1854. sizeDirection = 1;
  1855. clearInterval(sizeHandle);
  1856. sizeHandle = setInterval(doSize, 1000 / 20);
  1857. e.stopPropagation();
  1858. });
  1859. document.addEventListener("mouseup", e => {
  1860. clearInterval(sizeHandle);
  1861. sizeHandle = null;
  1862. });
  1863. document.addEventListener("touchend", e => {
  1864. clearInterval(sizeHandle);
  1865. sizeHandle = null;
  1866. });
  1867. document.querySelector("#fit").addEventListener("click", e => {
  1868. if (selected) {
  1869. fitEntities([selected]);
  1870. }
  1871. });
  1872. document.querySelector("#fit").addEventListener("mousedown", e => {
  1873. e.stopPropagation();
  1874. });
  1875. document.querySelector("#fit").addEventListener("touchstart", e => {
  1876. e.stopPropagation();
  1877. });
  1878. document.querySelector("#options-world-fit").addEventListener("click", () => fitWorld(true));
  1879. document.querySelector("#options-reset-pos-x").addEventListener("click", () => { config.x = 0; updateSizes(); });
  1880. document.querySelector("#options-reset-pos-y").addEventListener("click", () => { config.y = 0; updateSizes(); });
  1881. document.addEventListener("keydown", e => {
  1882. if (e.key == "Delete") {
  1883. if (selected) {
  1884. removeEntity(selected);
  1885. selected = null;
  1886. }
  1887. }
  1888. })
  1889. document.addEventListener("keydown", e => {
  1890. if (e.key == "Shift") {
  1891. shiftHeld = true;
  1892. e.preventDefault();
  1893. } else if (e.key == "Alt") {
  1894. altHeld = true;
  1895. e.preventDefault();
  1896. }
  1897. });
  1898. document.addEventListener("keyup", e => {
  1899. if (e.key == "Shift") {
  1900. shiftHeld = false;
  1901. e.preventDefault();
  1902. } else if (e.key == "Alt") {
  1903. altHeld = false;
  1904. e.preventDefault();
  1905. }
  1906. });
  1907. window.addEventListener("resize", handleResize);
  1908. // TODO: further investigate why the tool initially starts out with wrong
  1909. // values under certain circumstances (seems to be narrow aspect ratios -
  1910. // maybe the menu bar is animating when it shouldn't)
  1911. setTimeout(handleResize, 250);
  1912. setTimeout(handleResize, 500);
  1913. setTimeout(handleResize, 750);
  1914. setTimeout(handleResize, 1000);
  1915. document.querySelector("#menu-permalink").addEventListener("click", e => {
  1916. linkScene();
  1917. });
  1918. document.querySelector("#menu-export").addEventListener("click", e => {
  1919. copyScene();
  1920. });
  1921. document.querySelector("#menu-import").addEventListener("click", e => {
  1922. pasteScene();
  1923. });
  1924. document.querySelector("#menu-save").addEventListener("click", e => {
  1925. saveScene();
  1926. });
  1927. document.querySelector("#menu-load").addEventListener("click", e => {
  1928. loadScene();
  1929. });
  1930. document.querySelector("#menu-load-autosave").addEventListener("click", e => {
  1931. loadScene("autosave");
  1932. });
  1933. document.querySelector("#menu-add-image").addEventListener("click", e => {
  1934. document.querySelector("#file-upload-picker").click();
  1935. });
  1936. document.querySelector("#file-upload-picker").addEventListener("change", e => {
  1937. if (e.target.files.length > 0) {
  1938. for (let i=0; i<e.target.files.length; i++) {
  1939. customEntityFromFile(e.target.files[i]);
  1940. }
  1941. }
  1942. })
  1943. document.addEventListener("paste", e => {
  1944. let index = 0;
  1945. let item = null;
  1946. let found = false;
  1947. for (; index < e.clipboardData.items.length; index++) {
  1948. item = e.clipboardData.items[index];
  1949. if (item.type == "image/png") {
  1950. found = true;
  1951. break;
  1952. }
  1953. }
  1954. if (!found) {
  1955. return;
  1956. }
  1957. let url = null;
  1958. const file = item.getAsFile();
  1959. customEntityFromFile(file);
  1960. });
  1961. document.querySelector("#world").addEventListener("dragover", e => {
  1962. e.preventDefault();
  1963. })
  1964. document.querySelector("#world").addEventListener("drop", e => {
  1965. e.preventDefault();
  1966. if (e.dataTransfer.files.length > 0) {
  1967. let entX = document.querySelector("#entities").getBoundingClientRect().x;
  1968. let entY = document.querySelector("#entities").getBoundingClientRect().y;
  1969. let coords = pix2pos({x: e.clientX-entX, y: e.clientY-entY});
  1970. customEntityFromFile(e.dataTransfer.files[0], coords.x, coords.y);
  1971. }
  1972. })
  1973. clearEntityOptions();
  1974. clearViewOptions();
  1975. clearAttribution();
  1976. // we do this last because configuring settings can cause things
  1977. // to happen (e.g. auto-fit)
  1978. prepareSettings(getUserSettings());
  1979. });
  1980. function customEntityFromFile(file, x=0.5, y=0.5) {
  1981. file.arrayBuffer().then(buf => {
  1982. arr = new Uint8Array(buf);
  1983. blob = new Blob([arr], {type: file.type });
  1984. url = window.URL.createObjectURL(blob)
  1985. makeCustomEntity(url, x, y);
  1986. });
  1987. }
  1988. function makeCustomEntity(url, x=0.5, y=0.5) {
  1989. const maker = createEntityMaker(
  1990. {
  1991. name: "Custom Entity"
  1992. },
  1993. {
  1994. custom: {
  1995. attributes: {
  1996. height: {
  1997. name: "Height",
  1998. power: 1,
  1999. type: "length",
  2000. base: math.unit(6, "feet")
  2001. }
  2002. },
  2003. image: {
  2004. source: url
  2005. },
  2006. name: "Image",
  2007. info: {},
  2008. rename: false
  2009. }
  2010. },
  2011. []
  2012. );
  2013. const entity = maker.constructor();
  2014. entity.scale = config.height.toNumber("feet") / 20;
  2015. entity.ephemeral = true;
  2016. displayEntity(entity, "custom", x, y, true, true);
  2017. }
  2018. const filterDefs = {
  2019. none: {
  2020. id: "none",
  2021. name: "No Filter",
  2022. extract: maker => [],
  2023. render: name => name,
  2024. sort: (tag1, tag2) => tag1[1].localeCompare(tag2[1])
  2025. },
  2026. author: {
  2027. id: "author",
  2028. name: "Authors",
  2029. extract: maker => maker.authors ? maker.authors : [],
  2030. render: author => attributionData.people[author].name,
  2031. sort: (tag1, tag2) => tag1[1].localeCompare(tag2[1])
  2032. },
  2033. owner: {
  2034. id: "owner",
  2035. name: "Owners",
  2036. extract: maker => maker.owners ? maker.owners : [],
  2037. render: owner => attributionData.people[owner].name,
  2038. sort: (tag1, tag2) => tag1[1].localeCompare(tag2[1])
  2039. },
  2040. species: {
  2041. id: "species",
  2042. name: "Species",
  2043. extract: maker => maker.info && maker.info.species ? getSpeciesInfo(maker.info.species) : [],
  2044. render: species => speciesData[species].name,
  2045. sort: (tag1, tag2) => tag1[1].localeCompare(tag2[1])
  2046. },
  2047. tags: {
  2048. id: "tags",
  2049. name: "Tags",
  2050. extract: maker => maker.info && maker.info.tags ? maker.info.tags : [],
  2051. render: tag => tagDefs[tag],
  2052. sort: (tag1, tag2) => tag1[1].localeCompare(tag2[1])
  2053. },
  2054. size: {
  2055. id: "size",
  2056. name: "Normal Size",
  2057. extract: maker => maker.sizes && maker.sizes.length > 0 ? Array.from(maker.sizes.reduce((result, size) => {
  2058. if (result && !size.default) {
  2059. return result;
  2060. }
  2061. let meters = size.height.toNumber("meters");
  2062. if (meters < 1e-1) {
  2063. return ["micro"];
  2064. } else if (meters < 1e1) {
  2065. return ["moderate"];
  2066. } else {
  2067. return ["macro"];
  2068. }
  2069. }, null)) : [],
  2070. render: tag => { return {
  2071. "micro": "Micro",
  2072. "moderate": "Moderate",
  2073. "macro": "Macro"
  2074. }[tag]},
  2075. sort: (tag1, tag2) => {
  2076. const order = {
  2077. "micro": 0,
  2078. "moderate": 1,
  2079. "macro": 2
  2080. };
  2081. return order[tag1[0]] - order[tag2[0]];
  2082. }
  2083. },
  2084. allSizes: {
  2085. id: "allSizes",
  2086. name: "Possible Size",
  2087. extract: maker => maker.sizes ? Array.from(maker.sizes.reduce((set, size) => {
  2088. const height = size.height;
  2089. let result = Object.entries(sizeCategories).reduce((result, [name, value]) => {
  2090. if (result) {
  2091. return result;
  2092. } else {
  2093. if (math.compare(height, value) <= 0) {
  2094. return name;
  2095. }
  2096. }
  2097. }, null);
  2098. set.add(result ? result : "infinite");
  2099. return set;
  2100. }, new Set())) : [],
  2101. render: tag => tag[0].toUpperCase() + tag.slice(1),
  2102. sort: (tag1, tag2) => {
  2103. const order = [
  2104. "atomic", "microscopic", "tiny", "small", "moderate", "large", "macro", "megamacro", "planetary", "stellar",
  2105. "galactic", "universal", "omniversal", "infinite"
  2106. ]
  2107. return order.indexOf(tag1[0]) - order.indexOf(tag2[0]);
  2108. }
  2109. }
  2110. }
  2111. const sizeCategories = {
  2112. "atomic": math.unit(100, "angstroms"),
  2113. "microscopic": math.unit(100, "micrometers"),
  2114. "tiny": math.unit(100, "millimeters"),
  2115. "small": math.unit(1, "meter"),
  2116. "moderate": math.unit(3, "meters"),
  2117. "large": math.unit(10, "meters"),
  2118. "macro": math.unit(300, "meters"),
  2119. "megamacro": math.unit(1000, "kilometers"),
  2120. "planetary": math.unit(10, "earths"),
  2121. "stellar": math.unit(10, "solarradii"),
  2122. "galactic": math.unit(10, "galaxies"),
  2123. "universal": math.unit(10, "universes"),
  2124. "omniversal": math.unit(10, "multiverses")
  2125. };
  2126. function prepareEntities() {
  2127. availableEntities["buildings"] = makeBuildings();
  2128. availableEntities["characters"] = makeCharacters();
  2129. availableEntities["cities"] = makeCities();
  2130. availableEntities["fiction"] = makeFiction();
  2131. availableEntities["food"] = makeFood();
  2132. availableEntities["landmarks"] = makeLandmarks();
  2133. availableEntities["naturals"] = makeNaturals();
  2134. availableEntities["objects"] = makeObjects();
  2135. availableEntities["dildos"] = makeDildos();
  2136. availableEntities["pokemon"] = makePokemon();
  2137. availableEntities["species"] = makeSpecies();
  2138. availableEntities["vehicles"] = makeVehicles();
  2139. availableEntities["characters"].sort((x, y) => {
  2140. return x.name.toLowerCase() < y.name.toLowerCase() ? -1 : 1
  2141. });
  2142. const holder = document.querySelector("#spawners");
  2143. const filterHolder = document.querySelector("#filters");
  2144. const categorySelect = document.createElement("select");
  2145. categorySelect.id = "category-picker";
  2146. const filterSelect = document.createElement("select");
  2147. filterSelect.id = "filter-picker";
  2148. holder.appendChild(categorySelect);
  2149. filterHolder.appendChild(filterSelect);
  2150. const filterSets = {};
  2151. Object.values(filterDefs).forEach(filter => {
  2152. filterSets[filter.id] = new Set();
  2153. })
  2154. Object.entries(availableEntities).forEach(([category, entityList]) => {
  2155. const select = document.createElement("select");
  2156. select.id = "create-entity-" + category;
  2157. select.classList.add("entity-select");
  2158. for (let i = 0; i < entityList.length; i++) {
  2159. const entity = entityList[i];
  2160. const option = document.createElement("option");
  2161. option.value = i;
  2162. option.innerText = entity.name;
  2163. select.appendChild(option);
  2164. if (entity.nsfw) {
  2165. option.classList.add("nsfw");
  2166. }
  2167. Object.values(filterDefs).forEach(filter => {
  2168. filter.extract(entity).forEach(result => {
  2169. filterSets[filter.id].add(result);
  2170. });
  2171. });
  2172. availableEntitiesByName[entity.name] = entity;
  2173. };
  2174. select.addEventListener("change", e => {
  2175. if (select.options[select.selectedIndex].classList.contains("nsfw")) {
  2176. select.classList.add("nsfw");
  2177. } else {
  2178. select.classList.remove("nsfw");
  2179. }
  2180. })
  2181. const button = document.createElement("button");
  2182. button.id = "create-entity-" + category + "-button";
  2183. button.classList.add("entity-button");
  2184. button.innerHTML = "<i class=\"far fa-plus-square\"></i>";
  2185. button.addEventListener("click", e => {
  2186. const newEntity = entityList[select.value].constructor()
  2187. displayEntity(newEntity, newEntity.defaultView, 0, 0, true, true);
  2188. });
  2189. const categoryOption = document.createElement("option");
  2190. categoryOption.value = category
  2191. categoryOption.innerText = category;
  2192. if (category == "characters") {
  2193. categoryOption.selected = true;
  2194. select.classList.add("category-visible");
  2195. button.classList.add("category-visible");
  2196. }
  2197. categorySelect.appendChild(categoryOption);
  2198. holder.appendChild(select);
  2199. holder.appendChild(button);
  2200. });
  2201. Object.values(filterDefs).forEach(filter => {
  2202. const option = document.createElement("option");
  2203. option.innerText = filter.name;
  2204. option.value = filter.id;
  2205. filterSelect.appendChild(option);
  2206. const filterNameSelect = document.createElement("select");
  2207. filterNameSelect.classList.add("filter-select");
  2208. filterNameSelect.id = "filter-" + filter.id;
  2209. filterHolder.appendChild(filterNameSelect);
  2210. const button = document.createElement("button");
  2211. button.classList.add("filter-button");
  2212. button.id = "create-filtered-" + filter.id + "-button";
  2213. filterHolder.appendChild(button);
  2214. const counter = document.createElement("div");
  2215. counter.classList.add("button-counter");
  2216. counter.innerText = "10";
  2217. button.appendChild(counter);
  2218. const i = document.createElement("i");
  2219. i.classList.add("fas");
  2220. i.classList.add("fa-plus");
  2221. button.appendChild(i);
  2222. button.addEventListener("click", e => {
  2223. const makers = Array.from(document.querySelector(".entity-select.category-visible")).filter(element => !element.classList.contains("filtered"));
  2224. const count = makers.length + 2;
  2225. let index = 1;
  2226. if (makers.length > 50) {
  2227. if (!confirm("Really spawn " + makers.length + " things at once?")) {
  2228. return;
  2229. }
  2230. }
  2231. const worldWidth = config.height.toNumber("meters") / canvasHeight * canvasWidth;
  2232. const spawned = makers.map(element => {
  2233. const category = document.querySelector("#category-picker").value;
  2234. const maker = availableEntities[category][element.value];
  2235. const entity = maker.constructor()
  2236. displayEntity(entity, entity.view, -worldWidth * 0.45 + config.x + worldWidth * 0.9 * index / (count - 1), config.y);
  2237. index += 1;
  2238. entity;
  2239. });
  2240. updateSizes(true);
  2241. if (config.autoFitAdd)
  2242. fitEntities(spawned);
  2243. });
  2244. Array.from(filterSets[filter.id]).map(name => [name, filter.render(name)]).sort(filterDefs[filter.id].sort).forEach(name => {
  2245. const option = document.createElement("option");
  2246. option.innerText = name[1];
  2247. option.value = name[0];
  2248. filterNameSelect.appendChild(option);
  2249. });
  2250. filterNameSelect.addEventListener("change", e => {
  2251. updateFilter();
  2252. });
  2253. });
  2254. console.log("Loaded " + Object.keys(availableEntitiesByName).length + " entities");
  2255. categorySelect.addEventListener("input", e => {
  2256. const oldSelect = document.querySelector(".entity-select.category-visible");
  2257. oldSelect.classList.remove("category-visible");
  2258. const oldButton = document.querySelector(".entity-button.category-visible");
  2259. oldButton.classList.remove("category-visible");
  2260. const newSelect = document.querySelector("#create-entity-" + e.target.value);
  2261. newSelect.classList.add("category-visible");
  2262. const newButton = document.querySelector("#create-entity-" + e.target.value + "-button");
  2263. newButton.classList.add("category-visible");
  2264. recomputeFilters();
  2265. updateFilter();
  2266. });
  2267. recomputeFilters();
  2268. filterSelect.addEventListener("input", e => {
  2269. const oldSelect = document.querySelector(".filter-select.category-visible");
  2270. if (oldSelect)
  2271. oldSelect.classList.remove("category-visible");
  2272. const newSelect = document.querySelector("#filter-" + e.target.value);
  2273. if (newSelect && e.target.value != "none")
  2274. newSelect.classList.add("category-visible");
  2275. updateFilter();
  2276. });
  2277. }
  2278. // Only display authors and owners if they appear
  2279. // somewhere in the current entity list
  2280. function recomputeFilters() {
  2281. const category = document.querySelector("#category-picker").value;
  2282. const filterSets = {};
  2283. Object.values(filterDefs).forEach(filter => {
  2284. filterSets[filter.id] = new Set();
  2285. });
  2286. document.querySelectorAll(".entity-select.category-visible > option").forEach(element => {
  2287. const entity = availableEntities[category][element.value];
  2288. Object.values(filterDefs).forEach(filter => {
  2289. filter.extract(entity).forEach(result => {
  2290. filterSets[filter.id].add(result);
  2291. });
  2292. });
  2293. });
  2294. Object.values(filterDefs).forEach(filter => {
  2295. // always show the "none" option
  2296. let found = filter.id == "none";
  2297. document.querySelectorAll("#filter-" + filter.id + " > option").forEach(element => {
  2298. if (filterSets[filter.id].has(element.value) || filter.id == "none") {
  2299. element.classList.remove("filtered");
  2300. element.disabled = false;
  2301. found = true;
  2302. } else {
  2303. element.classList.add("filtered");
  2304. element.disabled = true;
  2305. }
  2306. });
  2307. const filterOption = document.querySelector("#filter-picker > option[value='" + filter.id + "']");
  2308. if (found) {
  2309. filterOption.classList.remove("filtered");
  2310. filterOption.disabled = false;
  2311. } else {
  2312. filterOption.classList.add("filtered");
  2313. filterOption.disabled = true;
  2314. }
  2315. });
  2316. document.querySelector("#filter-picker").value = "none";
  2317. document.querySelector("#filter-picker").dispatchEvent(new Event("input"));
  2318. }
  2319. function updateFilter() {
  2320. const category = document.querySelector("#category-picker").value;
  2321. const type = document.querySelector("#filter-picker").value;
  2322. const filterKeySelect = document.querySelector(".filter-select.category-visible");
  2323. clearFilter();
  2324. if (!filterKeySelect) {
  2325. return;
  2326. }
  2327. const key = filterKeySelect.value;
  2328. let current = document.querySelector(".entity-select.category-visible").value;
  2329. let replace = false;
  2330. let first = null;
  2331. let count = 0;
  2332. document.querySelectorAll(".entity-select.category-visible > option").forEach(element => {
  2333. let keep = type == "none";
  2334. if (filterDefs[type].extract(availableEntities[category][element.value]).indexOf(key) >= 0) {
  2335. keep = true;
  2336. }
  2337. if (!keep) {
  2338. element.classList.add("filtered");
  2339. element.disabled = true;
  2340. if (current == element.value) {
  2341. replace = true;
  2342. }
  2343. } else {
  2344. count += 1;
  2345. if (!first) {
  2346. first = element.value;
  2347. }
  2348. }
  2349. });
  2350. const button = document.querySelector(".filter-select.category-visible + button");
  2351. if (button) {
  2352. button.querySelector(".button-counter").innerText = count;
  2353. }
  2354. if (replace) {
  2355. document.querySelector(".entity-select.category-visible").value = first;
  2356. document.querySelector("#create-entity-" + category).dispatchEvent(new Event("change"));
  2357. }
  2358. }
  2359. function clearFilter() {
  2360. document.querySelectorAll(".entity-select.category-visible > option").forEach(element => {
  2361. element.classList.remove("filtered");
  2362. element.disabled = false;
  2363. });
  2364. }
  2365. document.addEventListener("mousemove", (e) => {
  2366. if (clicked) {
  2367. const position = snapRel(pix2pos({ x: e.clientX - dragOffsetX, y: e.clientY - dragOffsetY }));
  2368. clicked.dataset.x = position.x;
  2369. clicked.dataset.y = position.y;
  2370. updateEntityElement(entities[clicked.dataset.key], clicked);
  2371. if (hoveringInDeleteArea(e)) {
  2372. document.querySelector("#menubar").classList.add("hover-delete");
  2373. } else {
  2374. document.querySelector("#menubar").classList.remove("hover-delete");
  2375. }
  2376. }
  2377. if (panning && panReady) {
  2378. const worldWidth = config.height.toNumber("meters") / canvasHeight * canvasWidth;
  2379. const worldHeight = config.height.toNumber("meters");
  2380. config.x -= (e.clientX - panOffsetX) / canvasWidth * worldWidth;
  2381. config.y += (e.clientY - panOffsetY) / canvasHeight * worldHeight;
  2382. panOffsetX = e.clientX;
  2383. panOffsetY = e.clientY;
  2384. updateSizes();
  2385. panReady = false;
  2386. setTimeout(() => panReady=true, 1000/120);
  2387. }
  2388. });
  2389. document.addEventListener("touchmove", (e) => {
  2390. if (clicked) {
  2391. e.preventDefault();
  2392. let x = e.touches[0].clientX;
  2393. let y = e.touches[0].clientY;
  2394. const position = snapRel(pix2pos({ x: x - dragOffsetX, y: y - dragOffsetY }));
  2395. clicked.dataset.x = position.x;
  2396. clicked.dataset.y = position.y;
  2397. updateEntityElement(entities[clicked.dataset.key], clicked);
  2398. // what a hack
  2399. // I should centralize this 'fake event' creation...
  2400. if (hoveringInDeleteArea({ clientY: y })) {
  2401. document.querySelector("#menubar").classList.add("hover-delete");
  2402. } else {
  2403. document.querySelector("#menubar").classList.remove("hover-delete");
  2404. }
  2405. }
  2406. if (panning && panReady) {
  2407. const worldWidth = config.height.toNumber("meters") / canvasHeight * canvasWidth;
  2408. const worldHeight = config.height.toNumber("meters");
  2409. config.x -= (e.touches[0].clientX - panOffsetX) / canvasWidth * worldWidth;
  2410. config.y += (e.touches[0].clientY - panOffsetY) / canvasHeight * worldHeight;
  2411. panOffsetX = e.touches[0].clientX;
  2412. panOffsetY = e.touches[0].clientY;
  2413. updateSizes();
  2414. panReady = false;
  2415. setTimeout(() => panReady=true, 50);
  2416. }
  2417. }, { passive: false });
  2418. function checkFitWorld() {
  2419. if (config.autoFit) {
  2420. fitWorld();
  2421. return true;
  2422. }
  2423. return false;
  2424. }
  2425. function fitWorld(manual = false, factor = 1.1) {
  2426. fitEntities(entities, factor);
  2427. }
  2428. function fitEntities(manual = false, factor = 1.1) {
  2429. let minX = Infinity;
  2430. let maxX = -Infinity;
  2431. let minY = Infinity;
  2432. let maxY = -Infinity;
  2433. let count = 0;
  2434. const worldWidth = config.height.toNumber("meters") / canvasHeight * canvasWidth;
  2435. const worldHeight = config.height.toNumber("meters");
  2436. Object.entries(entities).forEach(([key, entity]) => {
  2437. const view = entity.view;
  2438. let extra = entity.views[view].image.extra;
  2439. extra = extra === undefined ? 1 : extra;
  2440. const image = document.querySelector("#entity-" + key + " > .entity-image");
  2441. const x = parseFloat(document.querySelector("#entity-" + key).dataset.x);
  2442. let width = image.width;
  2443. let height = image.height;
  2444. console.log(width, height);
  2445. // only really relevant if the images haven't loaded in yet
  2446. if (height == 0) {
  2447. height = 100;
  2448. }
  2449. if (width == 0) {
  2450. width = height;
  2451. }
  2452. const xBottom = x - entity.views[view].height.toNumber("meters") * width / height / 2;
  2453. const xTop = x + entity.views[view].height.toNumber("meters") * width / height / 2;
  2454. const y = parseFloat(document.querySelector("#entity-" + key).dataset.y);
  2455. const yBottom = y;
  2456. const yTop = entity.views[view].height.toNumber("meters") + yBottom;
  2457. minX = Math.min(minX, xBottom);
  2458. maxX = Math.max(maxX, xTop);
  2459. minY = Math.min(minY, yBottom);
  2460. maxY = Math.max(maxY, yTop);
  2461. count += 1;
  2462. });
  2463. let ySize = (maxY - minY) * factor;
  2464. let xSize = (maxX - minX) * factor;
  2465. if (xSize / ySize > worldWidth / worldHeight) {
  2466. ySize *= ((xSize / ySize) / (worldWidth / worldHeight));
  2467. }
  2468. config.x = (maxX + minX) / 2;
  2469. config.y = minY;
  2470. height = math.unit(ySize, "meter")
  2471. setWorldHeight(config.height, math.multiply(height, factor));
  2472. }
  2473. // TODO why am I doing this
  2474. function updateWorldHeight() {
  2475. const unit = document.querySelector("#options-height-unit").value;
  2476. const value = Math.max(0.000000001, document.querySelector("#options-height-value").value);
  2477. const oldHeight = config.height;
  2478. setWorldHeight(oldHeight, math.unit(value, unit));
  2479. }
  2480. function setWorldHeight(oldHeight, newHeight) {
  2481. worldSizeDirty = true;
  2482. config.height = newHeight.to(document.querySelector("#options-height-unit").value)
  2483. const unit = document.querySelector("#options-height-unit").value;
  2484. setNumericInput(document.querySelector("#options-height-value"), config.height.toNumber(unit));
  2485. Object.entries(entities).forEach(([key, entity]) => {
  2486. const element = document.querySelector("#entity-" + key);
  2487. let newPosition;
  2488. if (altHeld) {
  2489. newPosition = adjustAbs({ x: element.dataset.x, y: element.dataset.y }, oldHeight, config.height);
  2490. } else {
  2491. newPosition = { x: element.dataset.x, y: element.dataset.y };
  2492. }
  2493. element.dataset.x = newPosition.x;
  2494. element.dataset.y = newPosition.y;
  2495. });
  2496. updateSizes();
  2497. }
  2498. function loadScene(name = "default") {
  2499. try {
  2500. const data = JSON.parse(localStorage.getItem("macrovision-save-" + name));
  2501. if (data === null) {
  2502. return false;
  2503. }
  2504. importScene(data);
  2505. return true;
  2506. } catch (err) {
  2507. alert("Something went wrong while loading (maybe you didn't have anything saved. Check the F12 console for the error.")
  2508. console.error(err);
  2509. return false;
  2510. }
  2511. }
  2512. function saveScene(name = "default") {
  2513. try {
  2514. const string = JSON.stringify(exportScene());
  2515. localStorage.setItem("macrovision-save-" + name, string);
  2516. } catch (err) {
  2517. alert("Something went wrong while saving (maybe I don't have localStorage permissions, or exporting failed). Check the F12 console for the error.")
  2518. console.error(err);
  2519. }
  2520. }
  2521. function deleteScene(name = "default") {
  2522. try {
  2523. localStorage.removeItem("macrovision-save-" + name)
  2524. } catch (err) {
  2525. console.error(err);
  2526. }
  2527. }
  2528. function exportScene() {
  2529. const results = {};
  2530. results.entities = [];
  2531. Object.entries(entities).filter(([key, entity]) => entity.ephemeral !== true).forEach(([key, entity]) => {
  2532. const element = document.querySelector("#entity-" + key);
  2533. results.entities.push({
  2534. name: entity.identifier,
  2535. scale: entity.scale,
  2536. view: entity.view,
  2537. x: element.dataset.x,
  2538. y: element.dataset.y
  2539. });
  2540. });
  2541. const unit = document.querySelector("#options-height-unit").value;
  2542. results.world = {
  2543. height: config.height.toNumber(unit),
  2544. unit: unit,
  2545. x: config.x,
  2546. y: config.y
  2547. }
  2548. results.version = migrationDefs.length;
  2549. return results;
  2550. }
  2551. // btoa doesn't like anything that isn't ASCII
  2552. // great
  2553. // thanks to https://stackoverflow.com/questions/30106476/using-javascripts-atob-to-decode-base64-doesnt-properly-decode-utf-8-strings
  2554. // for providing an alternative
  2555. function b64EncodeUnicode(str) {
  2556. // first we use encodeURIComponent to get percent-encoded UTF-8,
  2557. // then we convert the percent encodings into raw bytes which
  2558. // can be fed into btoa.
  2559. return btoa(encodeURIComponent(str).replace(/%([0-9A-F]{2})/g,
  2560. function toSolidBytes(match, p1) {
  2561. return String.fromCharCode('0x' + p1);
  2562. }));
  2563. }
  2564. function b64DecodeUnicode(str) {
  2565. // Going backwards: from bytestream, to percent-encoding, to original string.
  2566. return decodeURIComponent(atob(str).split('').map(function (c) {
  2567. return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
  2568. }).join(''));
  2569. }
  2570. function linkScene() {
  2571. loc = new URL(window.location);
  2572. window.location = loc.protocol + "//" + loc.host + loc.pathname + "?scene=" + b64EncodeUnicode(JSON.stringify(exportScene()));
  2573. }
  2574. function copyScene() {
  2575. const results = exportScene();
  2576. navigator.clipboard.writeText(JSON.stringify(results));
  2577. }
  2578. function pasteScene() {
  2579. try {
  2580. navigator.clipboard.readText().then(text => {
  2581. const data = JSON.parse(text);
  2582. if (data.entities === undefined) {
  2583. return;
  2584. }
  2585. if (data.world === undefined) {
  2586. return;
  2587. }
  2588. importScene(data);
  2589. }).catch(err => alert(err));
  2590. } catch (err) {
  2591. console.error(err);
  2592. // probably wasn't valid data
  2593. }
  2594. }
  2595. // TODO - don't just search through every single entity
  2596. // probably just have a way to do lookups directly
  2597. function findEntity(name) {
  2598. return availableEntitiesByName[name];
  2599. }
  2600. const migrationDefs = [
  2601. /*
  2602. Migration: 0 -> 1
  2603. Adds x and y coordinates for the camera
  2604. */
  2605. data => {
  2606. data.world.x = 0;
  2607. data.world.y = 0;
  2608. }
  2609. ]
  2610. function migrateScene(data) {
  2611. if (data.version === undefined) {
  2612. alert("This save was created before save versions were tracked. The scene may import incorrectly.");
  2613. console.trace()
  2614. data.version = 0;
  2615. } else if (data.version < migrationDefs.length) {
  2616. migrationDefs[data.version](data);
  2617. data.version += 1;
  2618. migrateScene(data);
  2619. }
  2620. }
  2621. function importScene(data) {
  2622. removeAllEntities();
  2623. migrateScene(data);
  2624. data.entities.forEach(entityInfo => {
  2625. const entity = findEntity(entityInfo.name).constructor();
  2626. entity.scale = entityInfo.scale
  2627. displayEntity(entity, entityInfo.view, entityInfo.x, entityInfo.y);
  2628. });
  2629. config.height = math.unit(data.world.height, data.world.unit);
  2630. config.x = data.world.x;
  2631. config.y = data.world.y;
  2632. document.querySelector("#options-height-unit").value = data.world.unit;
  2633. if (data.canvasWidth) {
  2634. doHorizReposition(data.canvasWidth / canvasWidth);
  2635. }
  2636. updateSizes();
  2637. }
  2638. function renderToCanvas() {
  2639. const ctx = document.querySelector("#display").getContext("2d");
  2640. Object.entries(entities).sort((ent1, ent2) => {
  2641. z1 = document.querySelector("#entity-" + ent1[0]).style.zIndex;
  2642. z2 = document.querySelector("#entity-" + ent2[0]).style.zIndex;
  2643. return z1 - z2;
  2644. }).forEach(([id, entity]) => {
  2645. element = document.querySelector("#entity-" + id);
  2646. img = element.querySelector("img");
  2647. let x = parseFloat(element.dataset.x);
  2648. let y = parseFloat(element.dataset.y);
  2649. let coords = pos2pix({x: x, y: y});
  2650. let offset = img.style.getPropertyValue("--offset");
  2651. offset = parseFloat(offset.substring(0, offset.length-1))
  2652. x = coords.x - img.getBoundingClientRect().width/2;
  2653. y = coords.y - img.getBoundingClientRect().height * (-offset/100);
  2654. let xSize = img.getBoundingClientRect().width;
  2655. let ySize = img.getBoundingClientRect().height;
  2656. ctx.drawImage(img, x, y, xSize, ySize);
  2657. });
  2658. }
  2659. function exportCanvas(callback) {
  2660. /** @type {CanvasRenderingContext2D} */
  2661. const ctx = document.querySelector("#display").getContext("2d");
  2662. const blob = ctx.canvas.toBlob(callback);
  2663. }
  2664. function generateScreenshot(callback) {
  2665. renderToCanvas();
  2666. /** @type {CanvasRenderingContext2D} */
  2667. const ctx = document.querySelector("#display").getContext("2d");
  2668. ctx.fillStyle = "#555";
  2669. ctx.font = "normal normal lighter 16pt coda";
  2670. ctx.fillText("macrovision.crux.sexy", 10, 25);
  2671. exportCanvas(blob => {
  2672. callback(blob);
  2673. });
  2674. }
  2675. function copyScreenshot() {
  2676. generateScreenshot(blob => {
  2677. navigator.clipboard.write([
  2678. new ClipboardItem({
  2679. "image/png": blob
  2680. })
  2681. ]);
  2682. });
  2683. drawScale(false);
  2684. }
  2685. function saveScreenshot() {
  2686. generateScreenshot(blob => {
  2687. const a = document.createElement("a");
  2688. a.href = URL.createObjectURL(blob);
  2689. a.setAttribute("download", "macrovision.png");
  2690. a.click();
  2691. });
  2692. drawScale(false);
  2693. }
  2694. const rateLimits = {};
  2695. function toast(msg) {
  2696. let div = document.createElement("div");
  2697. div.innerHTML = msg;
  2698. div.classList.add("toast");
  2699. document.body.appendChild(div);
  2700. setTimeout(() => {
  2701. document.body.removeChild(div);
  2702. }, 5000)
  2703. }
  2704. function toastRateLimit(msg, key, delay) {
  2705. if (!rateLimits[key]) {
  2706. toast(msg);
  2707. rateLimits[key] = setTimeout(() => {
  2708. delete rateLimits[key]
  2709. }, delay);
  2710. }
  2711. }