less copy protection, more size visualization
25'ten fazla konu seçemezsiniz Konular bir harf veya rakamla başlamalı, kısa çizgiler ('-') içerebilir ve en fazla 35 karakter uzunluğunda olabilir.
 
 
 

3206 satır
96 KiB

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