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

5192 líneas
158 KiB

  1. let selected = null;
  2. let prevSelected = null;
  3. let selectedEntity = null;
  4. let prevSelectedEntity = null;
  5. let entityIndex = 0;
  6. let firsterror = true;
  7. let clicked = null;
  8. let movingInBounds = false;
  9. let dragging = false;
  10. let clickTimeout = null;
  11. let dragOffsetX = null;
  12. let dragOffsetY = null;
  13. let preloaded = new Set();
  14. let panning = false;
  15. let panReady = true;
  16. let panOffsetX = null;
  17. let panOffsetY = null;
  18. let shiftHeld = false;
  19. let altHeld = false;
  20. let entityX;
  21. let canvasWidth;
  22. let canvasHeight;
  23. let dragScale = 1;
  24. let dragScaleHandle = null;
  25. let dragEntityScale = 1;
  26. let dragEntityScaleHandle = null;
  27. let scrollDirection = 0;
  28. let scrollHandle = null;
  29. let zoomDirection = 0;
  30. let zoomHandle = null;
  31. let sizeDirection = 0;
  32. let sizeHandle = null;
  33. let worldSizeDirty = false;
  34. let rulerMode = false;
  35. let rulers = [];
  36. let currentRuler = undefined;
  37. const tagDefs = {
  38. "anthro": "Anthro",
  39. "feral": "Feral",
  40. "taur": "Taur",
  41. "naga": "Naga",
  42. "goo": "Goo"
  43. }
  44. math.createUnit("humans", {
  45. definition: "5.75 feet"
  46. });
  47. math.createUnit("story", {
  48. definition: "12 feet",
  49. prefixes: "long"
  50. });
  51. math.createUnit("stories", {
  52. definition: "12 feet",
  53. prefixes: "long"
  54. });
  55. math.createUnit("buses", {
  56. definition: "11.95 meters",
  57. prefixes: "long"
  58. });
  59. math.createUnit("marathons", {
  60. definition: "26.2 miles",
  61. prefixes: "long"
  62. });
  63. math.createUnit("timezones", {
  64. definition: "1037.54167 miles",
  65. prefixes: "long",
  66. aliases: ["timezone", "timezones"]
  67. });
  68. math.createUnit("nauticalMiles", {
  69. definition: "6080 feet",
  70. prefixes: "long",
  71. aliases: ["nauticalMile", "nauticalMiles"]
  72. });
  73. math.createUnit("fathoms", {
  74. definition: "6 feet",
  75. prefixes: "long",
  76. aliases: ["fathom", "fathoms"]
  77. });
  78. math.createUnit("earths", {
  79. definition: "12756km",
  80. prefixes: "long"
  81. });
  82. math.createUnit("lightsecond", {
  83. definition: "299792458 meters",
  84. prefixes: "long"
  85. });
  86. math.createUnit("lightseconds", {
  87. definition: "299792458 meters",
  88. prefixes: "long"
  89. });
  90. math.createUnit("parsec", {
  91. definition: "3.086e16 meters",
  92. prefixes: "long"
  93. })
  94. math.createUnit("parsecs", {
  95. definition: "3.086e16 meters",
  96. prefixes: "long"
  97. })
  98. math.createUnit("lightyears", {
  99. definition: "9.461e15 meters",
  100. prefixes: "long"
  101. })
  102. math.createUnit("AU", {
  103. definition: "149597870700 meters"
  104. })
  105. math.createUnit("AUs", {
  106. definition: "149597870700 meters"
  107. })
  108. math.createUnit("dalton", {
  109. definition: "1.66e-27 kg",
  110. prefixes: "long"
  111. });
  112. math.createUnit("daltons", {
  113. definition: "1.66e-27 kg",
  114. prefixes: "long"
  115. });
  116. math.createUnit("solarradii", {
  117. definition: "695990 km",
  118. prefixes: "long"
  119. });
  120. math.createUnit("solarmasses", {
  121. definition: "2e30 kg",
  122. prefixes: "long"
  123. });
  124. math.createUnit("galaxy", {
  125. definition: "105700 lightyears",
  126. prefixes: "long"
  127. });
  128. math.createUnit("galaxies", {
  129. definition: "105700 lightyears",
  130. prefixes: "long"
  131. });
  132. math.createUnit("universe", {
  133. definition: "93.016e9 lightyears",
  134. prefixes: "long"
  135. });
  136. math.createUnit("universes", {
  137. definition: "93.016e9 lightyears",
  138. prefixes: "long"
  139. });
  140. math.createUnit("multiverse", {
  141. definition: "1e30 lightyears",
  142. prefixes: "long"
  143. });
  144. math.createUnit("multiverses", {
  145. definition: "1e30 lightyears",
  146. prefixes: "long"
  147. });
  148. math.createUnit("footballFields", {
  149. definition: "57600 feet^2",
  150. prefixes: "long"
  151. });
  152. math.createUnit("people", {
  153. definition: "75 liters",
  154. prefixes: "long"
  155. });
  156. math.createUnit("shippingContainers", {
  157. definition: "1169 ft^3",
  158. prefixes: "long"
  159. });
  160. math.createUnit("olympicPools", {
  161. definition: "2500 m^3",
  162. prefixes: "long"
  163. });
  164. math.createUnit("oceans", {
  165. definition: "700000000 km^3",
  166. prefixes: "long"
  167. });
  168. math.createUnit("earthVolumes", {
  169. definition: "1.0867813e12 km^3",
  170. prefixes: "long"
  171. });
  172. math.createUnit("universeVolumes", {
  173. definition: "4.2137775e+32 lightyears^3",
  174. prefixes: "long"
  175. });
  176. math.createUnit("multiverseVolumes", {
  177. definition: "5.2359878e+89 lightyears^3",
  178. prefixes: "long"
  179. });
  180. math.createUnit("peopleMass", {
  181. definition: "80 kg",
  182. prefixes: "long"
  183. });
  184. math.createUnit("cars", {
  185. definition: "1250kg",
  186. prefixes: "long"
  187. });
  188. math.createUnit("busMasses", {
  189. definition: "15000kg",
  190. prefixes: "long"
  191. });
  192. math.createUnit("earthMass", {
  193. definition: "5.97e24 kg",
  194. prefixes: "long"
  195. });
  196. math.createUnit("kcal", {
  197. definition: "4184 joules",
  198. prefixes: "long"
  199. })
  200. math.createUnit("foodPounds", {
  201. definition: "867 kcal",
  202. prefixes: "long"
  203. })
  204. math.createUnit("foodKilograms", {
  205. definition: "1909 kcal",
  206. prefixes: "long"
  207. })
  208. math.createUnit("peopleEaten", {
  209. definition: "125000 kcal",
  210. prefixes: "long"
  211. })
  212. math.createUnit("barn", {
  213. definition: "10e-28 m^2",
  214. prefixes: "long"
  215. })
  216. math.createUnit("barns", {
  217. definition: "10e-28 m^2",
  218. prefixes: "long"
  219. })
  220. math.createUnit("points", {
  221. definition: "0.013888888888888888888888888 inches",
  222. prefixes: "long"
  223. })
  224. math.createUnit("beardSeconds", {
  225. definition: "10 nanometers",
  226. prefixes: "long"
  227. })
  228. math.createUnit("smoots", {
  229. definition: "5.5833333 feet",
  230. prefixes: "long"
  231. })
  232. math.createUnit("furlongs", {
  233. definition: "660 feet",
  234. prefixes: "long"
  235. })
  236. math.createUnit("nanoacres", {
  237. definition: "1e-9 acres",
  238. prefixes: "long"
  239. })
  240. math.createUnit("barnMegaparsecs", {
  241. definition: "1 barn megaparsec",
  242. prefixes: "long"
  243. })
  244. math.createUnit("firkins", {
  245. definition: "90 lb",
  246. prefixes: "long"
  247. })
  248. math.createUnit("donkeySeconds", {
  249. definition: "250 joules",
  250. prefixes: "long"
  251. })
  252. math.createUnit("HU", {
  253. definition: "0.75 inches",
  254. aliases: [
  255. "HUs",
  256. "hammerUnits"
  257. ]
  258. });
  259. const defaultUnits = {
  260. length: {
  261. metric: "meters",
  262. customary: "feet",
  263. relative: "stories",
  264. quirky: "smoots"
  265. },
  266. area: {
  267. metric: "meters^2",
  268. customary: "feet^2",
  269. relative: "footballFields",
  270. quirky: "nanoacres"
  271. },
  272. volume: {
  273. metric: "liters",
  274. customary: "gallons",
  275. relative: "olympicPools",
  276. volume: "barnMegaparsecs"
  277. },
  278. mass: {
  279. metric: "kilograms",
  280. customary: "lbs",
  281. relative: "peopleMass",
  282. quirky: "firkins"
  283. },
  284. energy: {
  285. metric: "kJ",
  286. customary: "kcal",
  287. relative: "peopleEaten",
  288. quirky: "donkeySeconds"
  289. }
  290. }
  291. const unitChoices = {
  292. length: {
  293. "metric": [
  294. "angstroms",
  295. "millimeters",
  296. "centimeters",
  297. "meters",
  298. "kilometers",
  299. ],
  300. "customary": [
  301. "inches",
  302. "feet",
  303. "yards",
  304. "miles",
  305. "nauticalMiles",
  306. ],
  307. "relative": [
  308. "humans",
  309. "stories",
  310. "buses",
  311. "marathons",
  312. "timezones",
  313. "earths",
  314. "lightseconds",
  315. "solarradii",
  316. "AUs",
  317. "lightyears",
  318. "parsecs",
  319. "galaxies",
  320. "universes",
  321. "multiverses"
  322. ],
  323. "quirky": [
  324. "beardSeconds",
  325. "points",
  326. "smoots",
  327. "furlongs",
  328. "HUs",
  329. "fathoms",
  330. ]
  331. },
  332. area: {
  333. "metric": [
  334. "cm^2",
  335. "meters^2",
  336. "kilometers^2",
  337. ],
  338. "customary": [
  339. "feet^2",
  340. "acres",
  341. "miles^2"
  342. ],
  343. "relative": [
  344. "footballFields"
  345. ],
  346. "quirky": [
  347. "barns",
  348. "nanoacres"
  349. ]
  350. },
  351. volume: {
  352. "metric": [
  353. "milliliters",
  354. "liters",
  355. "m^3",
  356. ],
  357. "customary": [
  358. "floz",
  359. "cups",
  360. "pints",
  361. "quarts",
  362. "gallons",
  363. ],
  364. "relative": [
  365. "people",
  366. "shippingContainers",
  367. "olympicPools",
  368. "oceans",
  369. "earthVolumes",
  370. "universeVolumes",
  371. "multiverseVolumes",
  372. ],
  373. "quirky": [
  374. "barnMegaparsecs"
  375. ]
  376. },
  377. mass: {
  378. "metric": [
  379. "kilograms",
  380. "milligrams",
  381. "grams",
  382. "tonnes",
  383. ],
  384. "customary": [
  385. "lbs",
  386. "ounces",
  387. "tons"
  388. ],
  389. "relative": [
  390. "peopleMass",
  391. "cars",
  392. "busMasses",
  393. "earthMass",
  394. "solarmasses"
  395. ],
  396. "quirky": [
  397. "firkins"
  398. ]
  399. },
  400. energy: {
  401. "metric": [
  402. "kJ",
  403. "foodKilograms"
  404. ],
  405. "customary": [
  406. "kcal",
  407. "foodPounds"
  408. ],
  409. "relative": [
  410. "peopleEaten"
  411. ],
  412. "quirky": [
  413. "donkeySeconds"
  414. ]
  415. }
  416. }
  417. const config = {
  418. height: math.unit(1500, "meters"),
  419. x: 0,
  420. y: 0,
  421. minLineSize: 100,
  422. maxLineSize: 150,
  423. autoFit: false,
  424. drawYAxis: true,
  425. drawXAxis: false,
  426. autoMass: "off",
  427. autoFoodIntake: false,
  428. autoPreyCapacity: false
  429. }
  430. const availableEntities = {
  431. }
  432. const availableEntitiesByName = {
  433. }
  434. const entities = {
  435. }
  436. function constrainRel(coords) {
  437. const worldWidth = config.height.toNumber("meters") / canvasHeight * canvasWidth;
  438. const worldHeight = config.height.toNumber("meters");
  439. if (altHeld) {
  440. return coords;
  441. }
  442. return {
  443. x: Math.min(Math.max(coords.x, -worldWidth / 2 + config.x), worldWidth / 2 + config.x),
  444. y: Math.min(Math.max(coords.y, config.y), worldHeight + config.y)
  445. }
  446. }
  447. // not using constrainRel anymore
  448. function snapPos(coords) {
  449. return {
  450. x: coords.x,
  451. y: (!config.lockYAxis || altHeld) ? coords.y : (Math.abs(coords.y) < config.height.toNumber("meters")/20 ? 0 : coords.y)
  452. };
  453. }
  454. function adjustAbs(coords, oldHeight, newHeight) {
  455. const ratio = math.divide(newHeight, oldHeight);
  456. const x = (coords.x - config.x) * ratio + config.x;
  457. const y = (coords.y - config.y) * ratio + config.y;
  458. return { x: x, y: y};
  459. }
  460. function pos2pix(coords) {
  461. const worldWidth = config.height.toNumber("meters") / canvasHeight * canvasWidth;
  462. const worldHeight = config.height.toNumber("meters");
  463. const x = ((coords.x - config.x) / worldWidth + 0.5) * (canvasWidth - 50) + 50;
  464. const y = (1 - (coords.y - config.y) / worldHeight) * (canvasHeight - 50) + 50;
  465. return { x: x, y: y };
  466. }
  467. function pix2pos(coords) {
  468. const worldWidth = config.height.toNumber("meters") / canvasHeight * canvasWidth;
  469. const worldHeight = config.height.toNumber("meters");
  470. const x = (((coords.x - 50) / (canvasWidth - 50)) - 0.5) * worldWidth + config.x;
  471. const y = (1 - ((coords.y - 50) / (canvasHeight - 50))) * worldHeight + config.y;
  472. return { x: x, y: y };
  473. }
  474. function updateEntityElement(entity, element) {
  475. const position = pos2pix({ x: element.dataset.x, y: element.dataset.y });
  476. const view = entity.view;
  477. element.style.left = position.x + "px";
  478. element.style.top = position.y + "px";
  479. element.style.setProperty("--xpos", position.x + "px");
  480. element.style.setProperty("--entity-height", "'" + entity.views[view].height.to(config.height.units[0].unit.name).format({ precision: 2 }) + "'");
  481. const pixels = math.divide(entity.views[view].height, config.height) * (canvasHeight - 50);
  482. const extra = entity.views[view].image.extra;
  483. const bottom = entity.views[view].image.bottom;
  484. const bonus = (extra ? extra : 1) * (1 / (1 - (bottom ? bottom : 0)));
  485. let height = pixels * bonus;
  486. // working around a Firefox bug here
  487. if (height > 17895698) {
  488. height = 0;
  489. }
  490. element.style.setProperty("--height", height + "px");
  491. element.style.setProperty("--extra", height - pixels + "px");
  492. element.style.setProperty("--brightness", entity.brightness);
  493. if (entity.views[view].rename)
  494. element.querySelector(".entity-name").innerText = entity.name == "" ? "" : entity.views[view].name;
  495. else
  496. element.querySelector(".entity-name").innerText = entity.name;
  497. const bottomName = document.querySelector("#bottom-name-" + element.dataset.key);
  498. bottomName.style.left = position.x + entityX + "px";
  499. bottomName.style.bottom = "0vh";
  500. bottomName.innerText = entity.name;
  501. const topName = document.querySelector("#top-name-" + element.dataset.key);
  502. topName.style.left = position.x + entityX + "px";
  503. topName.style.top = "20vh";
  504. topName.innerText = entity.name;
  505. if (entity.views[view].height.toNumber("meters") / 10 > config.height.toNumber("meters")) {
  506. topName.classList.add("top-name-needed");
  507. } else {
  508. topName.classList.remove("top-name-needed");
  509. }
  510. }
  511. let ratioInfo
  512. function updateRatios() {
  513. if (config.showRatios) {
  514. if (selectedEntity !== null && prevSelectedEntity !== null && selectedEntity !== prevSelectedEntity) {
  515. let first = selectedEntity.currentView.height;
  516. let second = prevSelectedEntity.currentView.height;
  517. let text = ""
  518. if (first.toNumber("meters") < second.toNumber("meters")) {
  519. text += selectedEntity.name + " is " + math.format(math.divide(second, first), { precision: 5 }) + " times smaller than " + prevSelectedEntity.name;
  520. } else {
  521. text += selectedEntity.name + " is " + math.format(math.divide(first, second), { precision: 5 })+ " times taller than " + prevSelectedEntity.name;
  522. }
  523. text += "\n";
  524. let apparentHeight = math.multiply(math.divide(second, first), math.unit(6, "feet"));
  525. if (config.units === "metric") {
  526. apparentHeight = apparentHeight.to("meters");
  527. }
  528. text += prevSelectedEntity.name + " looks " + math.format(apparentHeight, { precision: 3}) + " tall to " + selectedEntity.name;
  529. ratioInfo.innerText = text;
  530. } else {
  531. //ratioInfo.innerText = "";
  532. }
  533. }
  534. }
  535. function pickUnit() {
  536. if (!config.autoUnits) {
  537. return;
  538. }
  539. let type = null;
  540. let category = null;
  541. const heightSelect = document.querySelector("#options-height-unit");
  542. currentUnit = heightSelect.value;
  543. Object.keys(unitChoices).forEach(unitType => {
  544. Object.keys(unitChoices[unitType]).forEach(unitCategory => {
  545. if (unitChoices[unitType][unitCategory].includes(currentUnit)) {
  546. type = unitType;
  547. category = unitCategory;
  548. }
  549. })
  550. })
  551. // This should only happen if the unit selector isn't set up yet.
  552. // It doesn't really matter what goes into it.
  553. if (type === null || category === null) {
  554. return "meters"
  555. }
  556. const choices = unitChoices[type][category].map(unit => {
  557. let value = config.height.toNumber(unit);
  558. if (value < 1) {
  559. value = 1 / value / value;
  560. }
  561. return [unit, value]
  562. })
  563. heightSelect.value = choices.sort((a, b) => {
  564. return a[1] - b[1]
  565. })[0][0]
  566. selectNewUnit();
  567. }
  568. function updateSizes(dirtyOnly = false) {
  569. updateRatios();
  570. if (config.lockYAxis) {
  571. if (config.groundPos === "very-high") {
  572. config.y = -config.height.toNumber("meters") / 12 * 5;
  573. } else if (config.groundPos === "high") {
  574. config.y = -config.height.toNumber("meters") / 12 * 4;
  575. } else if (config.groundPos === "medium") {
  576. config.y = -config.height.toNumber("meters") / 12 * 3;
  577. } else if (config.groundPos === "low") {
  578. config.y = -config.height.toNumber("meters") / 12 * 2;
  579. } else if (config.groundPos === "very-low") {
  580. config.y = -config.height.toNumber("meters") / 12;
  581. } else {
  582. config.y = 0;
  583. }
  584. }
  585. drawScales(dirtyOnly);
  586. let ordered = Object.entries(entities);
  587. ordered.sort((e1, e2) => {
  588. if (e1[1].priority != e2[1].priority) {
  589. return e2[1].priority - e1[1].priority;
  590. } else {
  591. return e1[1].views[e1[1].view].height.value - e2[1].views[e2[1].view].height.value
  592. }
  593. });
  594. let zIndex = ordered.length;
  595. ordered.forEach(entity => {
  596. const element = document.querySelector("#entity-" + entity[0]);
  597. element.style.zIndex = zIndex;
  598. if (!dirtyOnly || entity[1].dirty) {
  599. updateEntityElement(entity[1], element, zIndex);
  600. entity[1].dirty = false;
  601. }
  602. zIndex -= 1;
  603. });
  604. document.querySelector("#ground").style.top = pos2pix({x: 0, y: 0}).y + "px";
  605. drawRulers();
  606. }
  607. function drawRulers() {
  608. const canvas = document.querySelector("#rulers");
  609. /** @type {CanvasRenderingContext2D} */
  610. const ctx = canvas.getContext("2d");
  611. const deviceScale = window.devicePixelRatio;
  612. ctx.canvas.width = Math.floor(canvas.clientWidth * deviceScale);
  613. ctx.canvas.height = Math.floor(canvas.clientHeight * deviceScale);
  614. ctx.scale(deviceScale, deviceScale);
  615. rulers.concat(currentRuler ? [currentRuler] : []).forEach(rulerDef => {
  616. let x0 = rulerDef.x0;
  617. let y0 = rulerDef.y0;
  618. let x1 = rulerDef.x1;
  619. let y1 = rulerDef.y1;
  620. if (rulerDef.entityKey !== null) {
  621. const entity = entities[rulerDef.entityKey]
  622. const entityElement = document.querySelector("#entity-" + rulerDef.entityKey)
  623. x0 *= entity.scale;
  624. y0 *= entity.scale;
  625. x1 *= entity.scale;
  626. y1 *= entity.scale;
  627. x0 += parseFloat(entityElement.dataset.x)
  628. x1 += parseFloat(entityElement.dataset.x)
  629. y0 += parseFloat(entityElement.dataset.y)
  630. y1 += parseFloat(entityElement.dataset.y)
  631. }
  632. ctx.save();
  633. ctx.beginPath();
  634. const start = pos2pix({x: x0, y: y0});
  635. const end = pos2pix({x: x1, y: y1});
  636. ctx.moveTo(start.x, start.y);
  637. ctx.lineTo(end.x, end.y);
  638. ctx.lineWidth = 5;
  639. ctx.strokeStyle = "#f8f";
  640. ctx.stroke();
  641. const center = { x: (start.x + end.x) / 2, y: (start.y + end.y) / 2 };
  642. ctx.fillStyle = "#eeeeee";
  643. ctx.font = 'normal 24pt coda';
  644. ctx.translate(center.x, center.y);
  645. let angle = Math.atan2(end.y - start.y, end.x - start.x);
  646. if (angle < -Math.PI/2) {
  647. angle += Math.PI;
  648. }
  649. if (angle > Math.PI/2) {
  650. angle -= Math.PI;
  651. }
  652. ctx.rotate(angle);
  653. const offsetX = Math.cos(angle + Math.PI/2);
  654. const offsetY = Math.sin(angle + Math.PI/2);
  655. const distance = Math.sqrt(Math.pow(y1 - y0, 2) + Math.pow(x1 - x0, 2));
  656. const distanceInUnits = math.unit(distance, "meters").to(document.querySelector("#options-height-unit").value);
  657. const textSize = ctx.measureText(distanceInUnits.format({ precision: 3}));
  658. ctx.fillText(distanceInUnits.format({ precision: 3}), -offsetX * 10 - textSize.width / 2, -offsetY*10);
  659. ctx.restore();
  660. });
  661. }
  662. function drawScales(ifDirty = false) {
  663. const canvas = document.querySelector("#display");
  664. /** @type {CanvasRenderingContext2D} */
  665. const ctx = canvas.getContext("2d");
  666. const deviceScale = window.devicePixelRatio;
  667. ctx.canvas.width = Math.floor(canvas.clientWidth * deviceScale);
  668. ctx.canvas.height = Math.floor(canvas.clientHeight * deviceScale);
  669. ctx.scale(deviceScale, deviceScale);
  670. ctx.beginPath();
  671. ctx.rect(0, 0, ctx.canvas.width / deviceScale, ctx.canvas.height / deviceScale);
  672. switch(config.background){
  673. case "black":
  674. ctx.fillStyle = "#000";
  675. break;
  676. case "dark":
  677. ctx.fillStyle = "#111";
  678. break;
  679. case "medium":
  680. ctx.fillStyle = "#333";
  681. break;
  682. case "light":
  683. ctx.fillStyle = "#555";
  684. break;
  685. }
  686. ctx.fill();
  687. if (config.drawYAxis || config.drawAltitudes !== "none") {
  688. drawVerticalScale(ifDirty);
  689. }
  690. if (config.drawXAxis) {
  691. drawHorizontalScale(ifDirty);
  692. }
  693. }
  694. function drawVerticalScale(ifDirty = false) {
  695. if (ifDirty && !worldSizeDirty)
  696. return;
  697. function drawTicks(/** @type {CanvasRenderingContext2D} */ ctx, pixelsPer, heightPer) {
  698. let total = heightPer.clone();
  699. total.value = config.y;
  700. let y = ctx.canvas.clientHeight - 50;
  701. let offset = total.toNumber("meters") % heightPer.toNumber("meters");
  702. y += offset / heightPer.toNumber("meters") * pixelsPer;
  703. total = math.subtract(total, math.unit(offset, "meters"));
  704. for (; y >= 50; y -= pixelsPer) {
  705. drawTick(ctx, 50, y, total.format({ precision: 3 }));
  706. total = math.add(total, heightPer);
  707. }
  708. }
  709. function drawTick(/** @type {CanvasRenderingContext2D} */ ctx, x, y, label, flipped=false) {
  710. const oldStroke = ctx.strokeStyle;
  711. const oldFill = ctx.fillStyle;
  712. x = Math.round(x);
  713. y = Math.round(y);
  714. ctx.beginPath();
  715. ctx.moveTo(x, y);
  716. ctx.lineTo(x + 20, y);
  717. ctx.strokeStyle = "#000000";
  718. ctx.stroke();
  719. ctx.beginPath();
  720. ctx.moveTo(x + 20, y);
  721. ctx.lineTo(ctx.canvas.clientWidth - 70, y);
  722. if (flipped) {
  723. ctx.strokeStyle = "#666666";
  724. } else {
  725. ctx.strokeStyle = "#aaaaaa";
  726. }
  727. ctx.stroke();
  728. ctx.beginPath();
  729. ctx.moveTo(ctx.canvas.clientWidth - 70, y);
  730. ctx.lineTo(ctx.canvas.clientWidth - 50, y);
  731. ctx.strokeStyle = "#000000";
  732. ctx.stroke();
  733. const oldFont = ctx.font;
  734. ctx.font = 'normal 24pt coda';
  735. ctx.fillStyle = "#dddddd";
  736. ctx.beginPath();
  737. if (flipped) {
  738. ctx.textAlign = "end";
  739. ctx.fillText(label, ctx.canvas.clientWidth - 70, y + 35)
  740. } else {
  741. ctx.fillText(label, x + 20, y + 35);
  742. }
  743. ctx.textAlign = "start";
  744. ctx.font = oldFont;
  745. ctx.strokeStyle = oldStroke;
  746. ctx.fillStyle = oldFill;
  747. }
  748. function drawAltitudeLine(ctx, height, label) {
  749. const pixelScale = (ctx.canvas.clientHeight - 100) / config.height.toNumber("meters");
  750. const y = ctx.canvas.clientHeight - 50 - (height.toNumber("meters") - config.y) * pixelScale;
  751. if (y < ctx.canvas.clientHeight - 100) {
  752. drawTick(ctx, 50, y, label, true);
  753. }
  754. }
  755. const canvas = document.querySelector("#display");
  756. /** @type {CanvasRenderingContext2D} */
  757. const ctx = canvas.getContext("2d");
  758. const pixelScale = (ctx.canvas.clientHeight - 100) / config.height.toNumber();
  759. let pixelsPer = pixelScale;
  760. heightPer = 1;
  761. if (pixelsPer < config.minLineSize) {
  762. const factor = math.ceil(config.minLineSize / pixelsPer);
  763. heightPer *= factor;
  764. pixelsPer *= factor;
  765. }
  766. if (pixelsPer > config.maxLineSize) {
  767. const factor = math.ceil(pixelsPer / config.maxLineSize);
  768. heightPer /= factor;
  769. pixelsPer /= factor;
  770. }
  771. if (heightPer == 0) {
  772. console.error("The world size is invalid! Refusing to draw the scale...");
  773. return;
  774. }
  775. heightPer = math.unit(heightPer, document.querySelector("#options-height-unit").value);
  776. ctx.beginPath();
  777. ctx.moveTo(50, 50);
  778. ctx.lineTo(50, ctx.canvas.clientHeight - 50);
  779. ctx.stroke();
  780. ctx.beginPath();
  781. ctx.moveTo(ctx.canvas.clientWidth - 50, 50);
  782. ctx.lineTo(ctx.canvas.clientWidth - 50, ctx.canvas.clientHeight - 50);
  783. ctx.stroke();
  784. if (config.drawYAxis) {
  785. drawTicks(ctx, pixelsPer, heightPer);
  786. }
  787. if (config.drawAltitudes == "atmosphere" || config.drawAltitudes == "all") {
  788. drawAltitudeLine(ctx, math.unit(8, "km"), "Troposphere");
  789. drawAltitudeLine(ctx, math.unit(17.5, "km"), "Ozone Layer");
  790. drawAltitudeLine(ctx, math.unit(50, "km"), "Stratosphere");
  791. drawAltitudeLine(ctx, math.unit(85, "km"), "Mesosphere");
  792. drawAltitudeLine(ctx, math.unit(675, "km"), "Thermosphere");
  793. drawAltitudeLine(ctx, math.unit(10000, "km"), "Exosphere");
  794. }
  795. if (config.drawAltitudes == "orbits" || config.drawAltitudes == "all") {
  796. drawAltitudeLine(ctx, math.unit(7, "miles"), "Cruising Altitude");
  797. drawAltitudeLine(ctx, math.unit(100, "km"), "Edge of Space (Kármán line)");
  798. drawAltitudeLine(ctx, math.unit(211.3, "miles"), "Space Station");
  799. drawAltitudeLine(ctx, math.unit(369.7, "miles"), "Hubble Telescope");
  800. drawAltitudeLine(ctx, math.unit(1500, "km"), "Low Earth Orbit");
  801. drawAltitudeLine(ctx, math.unit(20350, "km"), "GPS Satellites");
  802. drawAltitudeLine(ctx, math.unit(35786, "km"), "Geosynchronous Orbit");
  803. drawAltitudeLine(ctx, math.unit(238900, "miles"), "Lunar Orbit");
  804. drawAltitudeLine(ctx, math.unit(57.9e6, "km"), "Orbit of Mercury");
  805. drawAltitudeLine(ctx, math.unit(108.2e6, "km"), "Orbit of Venus");
  806. drawAltitudeLine(ctx, math.unit(1, "AU"), "Orbit of Earth");
  807. drawAltitudeLine(ctx, math.unit(227.9e6, "km"), "Orbit of Mars");
  808. drawAltitudeLine(ctx, math.unit(778.6e6, "km"), "Orbit of Jupiter");
  809. drawAltitudeLine(ctx, math.unit(1433.5e6, "km"), "Orbit of Saturn");
  810. drawAltitudeLine(ctx, math.unit(2872.5e6, "km"), "Orbit of Uranus");
  811. drawAltitudeLine(ctx, math.unit(4495.1e6, "km"), "Orbit of Neptune");
  812. drawAltitudeLine(ctx, math.unit(5906.4e6, "km"), "Orbit of Pluto");
  813. drawAltitudeLine(ctx, math.unit(2.7, "AU"), "Asteroid Belt");
  814. drawAltitudeLine(ctx, math.unit(123, "AU"), "Heliopause");
  815. drawAltitudeLine(ctx, math.unit(26e3, "lightyears"), "Orbit of Sol");
  816. }
  817. if (config.drawAltitudes == "weather" || config.drawAltitudes == "all") {
  818. drawAltitudeLine(ctx, math.unit(1000, "meters"), "Low-level Clouds");
  819. drawAltitudeLine(ctx, math.unit(3000, "meters"), "Mid-level Clouds");
  820. drawAltitudeLine(ctx, math.unit(10000, "meters"), "High-level Clouds");
  821. drawAltitudeLine(ctx, math.unit(20, "km"), "Polar Stratospheric Clouds");
  822. drawAltitudeLine(ctx, math.unit(80, "km"), "Noctilucent Clouds");
  823. drawAltitudeLine(ctx, math.unit(100, "km"), "Aurora");
  824. }
  825. if (config.drawAltitudes == "water" || config.drawAltitudes == "all") {
  826. drawAltitudeLine(ctx, math.unit(12100, "feet"), "Average Ocean Depth");
  827. drawAltitudeLine(ctx, math.unit(8376, "meters"), "Milkwaukee Deep");
  828. drawAltitudeLine(ctx, math.unit(10984, "meters"), "Challenger Deep");
  829. drawAltitudeLine(ctx, math.unit(5550, "meters"), "Molloy Deep");
  830. drawAltitudeLine(ctx, math.unit(7290, "meters"), "Sunda Deep");
  831. drawAltitudeLine(ctx, math.unit(592, "meters"), "Crater Lake");
  832. drawAltitudeLine(ctx, math.unit(7.5, "meters"), "Littoral Zone");
  833. drawAltitudeLine(ctx, math.unit(140, "meters"), "Continental Shelf");
  834. }
  835. if (config.drawAltitudes == "geology" || config.drawAltitudes == "all") {
  836. drawAltitudeLine(ctx, math.unit(35, "km"), "Crust");
  837. drawAltitudeLine(ctx, math.unit(670, "km"), "Upper Mantle");
  838. drawAltitudeLine(ctx, math.unit(2890, "km"), "Lower Mantle");
  839. drawAltitudeLine(ctx, math.unit(5150, "km"), "Outer Core");
  840. drawAltitudeLine(ctx, math.unit(6370, "km"), "Inner Core");
  841. }
  842. if (config.drawAltitudes == "thicknesses" || config.drawAltitudes == "all") {
  843. drawAltitudeLine(ctx, math.unit(0.335, "nm"), "Monolayer Graphene");
  844. drawAltitudeLine(ctx, math.unit(3, "um"), "Spider Silk");
  845. drawAltitudeLine(ctx, math.unit(0.07, "mm"), "Human Hair");
  846. drawAltitudeLine(ctx, math.unit(0.1, "mm"), "Sheet of Paper");
  847. drawAltitudeLine(ctx, math.unit(0.5, "mm"), "Yarn");
  848. drawAltitudeLine(ctx, math.unit(0.0155, "inches"), "Thread");
  849. drawAltitudeLine(ctx, math.unit(0.1, "um"), "Gold Leaf");
  850. drawAltitudeLine(ctx, math.unit(35, "um"), "PCB Trace");
  851. }
  852. if (config.drawAltitudes == "airspaces" || config.drawAltitudes == "all") {
  853. drawAltitudeLine(ctx, math.unit(18000, "feet"), "Class A");
  854. drawAltitudeLine(ctx, math.unit(14500, "feet"), "Class E");
  855. drawAltitudeLine(ctx, math.unit(10000, "feet"), "Class B");
  856. drawAltitudeLine(ctx, math.unit(4000, "feet"), "Class C");
  857. drawAltitudeLine(ctx, math.unit(2500, "feet"), "Class D");
  858. }
  859. if (config.drawAltitudes == "races" || config.drawAltitudes == "all") {
  860. drawAltitudeLine(ctx, math.unit(100, "meters"), "100m Dash");
  861. drawAltitudeLine(ctx, math.unit(26.2188/2, "miles"), "Half Marathon");
  862. drawAltitudeLine(ctx, math.unit(26.2188, "miles"), "Marathon");
  863. drawAltitudeLine(ctx, math.unit(161.734, "miles"), "Monaco Grand Prix");
  864. drawAltitudeLine(ctx, math.unit(500, "miles"), "Daytona 500");
  865. drawAltitudeLine(ctx, math.unit(2121.6, "miles"), "Tour de France");
  866. }
  867. if (config.drawAltitudes == "olympic-records" || config.drawAltitudes == "all") {
  868. drawAltitudeLine(ctx, math.unit(2.39, "meters"), "High Jump");
  869. drawAltitudeLine(ctx, math.unit(6.03, "meters"), "Pole Vault");
  870. drawAltitudeLine(ctx, math.unit(8.90, "meters"), "Long Jump");
  871. drawAltitudeLine(ctx, math.unit(18.09, "meters"), "Triple Jump");
  872. drawAltitudeLine(ctx, math.unit(23.30, "meters"), "Shot Put");
  873. drawAltitudeLine(ctx, math.unit(72.30, "meters"), "Discus Throw");
  874. drawAltitudeLine(ctx, math.unit(84.80, "meters"), "Hammer Throw");
  875. drawAltitudeLine(ctx, math.unit(90.57, "meters"), "Javelin Throw");
  876. }
  877. }
  878. // this is a lot of copypizza...
  879. function drawHorizontalScale(ifDirty = false) {
  880. if (ifDirty && !worldSizeDirty)
  881. return;
  882. function drawTicks(/** @type {CanvasRenderingContext2D} */ ctx, pixelsPer, heightPer) {
  883. let total = heightPer.clone();
  884. total.value = math.unit(-config.x, "meters").toNumber(config.unit);
  885. // further adjust it to put the current position in the center
  886. total.value -= heightPer.toNumber("meters") / pixelsPer * (canvasWidth + 50) / 2;
  887. let x = ctx.canvas.clientWidth - 50;
  888. let offset = total.toNumber("meters") % heightPer.toNumber("meters");
  889. x += offset / heightPer.toNumber("meters") * pixelsPer;
  890. total = math.subtract(total, math.unit(offset, "meters"));
  891. for (; x >= 50 - pixelsPer; x -= pixelsPer) {
  892. // negate it so that the left side is negative
  893. drawTick(ctx, x, 50, math.multiply(-1, total).format({ precision: 3 }));
  894. total = math.add(total, heightPer);
  895. }
  896. }
  897. function drawTick(/** @type {CanvasRenderingContext2D} */ ctx, x, y, label) {
  898. ctx.save()
  899. x = Math.round(x);
  900. y = Math.round(y);
  901. ctx.beginPath();
  902. ctx.moveTo(x, y);
  903. ctx.lineTo(x, y + 20);
  904. ctx.strokeStyle = "#000000";
  905. ctx.stroke();
  906. ctx.beginPath();
  907. ctx.moveTo(x, y + 20);
  908. ctx.lineTo(x, ctx.canvas.clientHeight - 70);
  909. ctx.strokeStyle = "#aaaaaa";
  910. ctx.stroke();
  911. ctx.beginPath();
  912. ctx.moveTo(x, ctx.canvas.clientHeight - 70);
  913. ctx.lineTo(x, ctx.canvas.clientHeight - 50);
  914. ctx.strokeStyle = "#000000";
  915. ctx.stroke();
  916. const oldFont = ctx.font;
  917. ctx.font = 'normal 24pt coda';
  918. ctx.fillStyle = "#dddddd";
  919. ctx.beginPath();
  920. ctx.fillText(label, x + 35, y + 20);
  921. ctx.restore()
  922. }
  923. const canvas = document.querySelector("#display");
  924. /** @type {CanvasRenderingContext2D} */
  925. const ctx = canvas.getContext("2d");
  926. let pixelsPer = (ctx.canvas.clientHeight - 100) / config.height.toNumber();
  927. heightPer = 1;
  928. if (pixelsPer < config.minLineSize * 2) {
  929. const factor = math.ceil(config.minLineSize * 2/ pixelsPer);
  930. heightPer *= factor;
  931. pixelsPer *= factor;
  932. }
  933. if (pixelsPer > config.maxLineSize * 2) {
  934. const factor = math.ceil(pixelsPer / 2/ config.maxLineSize);
  935. heightPer /= factor;
  936. pixelsPer /= factor;
  937. }
  938. if (heightPer == 0) {
  939. console.error("The world size is invalid! Refusing to draw the scale...");
  940. return;
  941. }
  942. heightPer = math.unit(heightPer, document.querySelector("#options-height-unit").value);
  943. ctx.beginPath();
  944. ctx.moveTo(0, 50);
  945. ctx.lineTo(ctx.canvas.clientWidth, 50);
  946. ctx.stroke();
  947. ctx.beginPath();
  948. ctx.moveTo(0, ctx.canvas.clientHeight - 50);
  949. ctx.lineTo(ctx.canvas.clientWidth , ctx.canvas.clientHeight - 50);
  950. ctx.stroke();
  951. drawTicks(ctx, pixelsPer, heightPer);
  952. }
  953. // Entities are generated as needed, and we make a copy
  954. // every time - the resulting objects get mutated, after all.
  955. // But we also want to be able to read some information without
  956. // calling the constructor -- e.g. making a list of authors and
  957. // owners. So, this function is used to generate that information.
  958. // It is invoked like makeEntity so that it can be dropped in easily,
  959. // but returns an object that lets you construct many copies of an entity,
  960. // rather than creating a new entity.
  961. function createEntityMaker(info, views, sizes, forms) {
  962. const maker = {};
  963. maker.name = info.name;
  964. maker.info = info;
  965. maker.sizes = sizes;
  966. maker.constructor = () => makeEntity(info, views, sizes, forms);
  967. maker.authors = [];
  968. maker.owners = [];
  969. maker.nsfw = false;
  970. Object.values(views).forEach(view => {
  971. const authors = authorsOf(view.image.source);
  972. if (authors) {
  973. authors.forEach(author => {
  974. if (maker.authors.indexOf(author) == -1) {
  975. maker.authors.push(author);
  976. }
  977. });
  978. }
  979. const owners = ownersOf(view.image.source);
  980. if (owners) {
  981. owners.forEach(owner => {
  982. if (maker.owners.indexOf(owner) == -1) {
  983. maker.owners.push(owner);
  984. }
  985. });
  986. }
  987. if (isNsfw(view.image.source)) {
  988. maker.nsfw = true;
  989. }
  990. });
  991. return maker;
  992. }
  993. // This function serializes and parses its arguments to avoid sharing
  994. // references to a common object. This allows for the objects to be
  995. // safely mutated.
  996. function makeEntity(info, views, sizes, forms = {}) {
  997. const entityTemplate = {
  998. name: info.name,
  999. identifier: info.name,
  1000. scale: 1,
  1001. rotation: 0,
  1002. info: JSON.parse(JSON.stringify(info)),
  1003. views: JSON.parse(JSON.stringify(views), math.reviver),
  1004. sizes: sizes === undefined ? [] : JSON.parse(JSON.stringify(sizes), math.reviver),
  1005. forms: forms,
  1006. init: function () {
  1007. const entity = this;
  1008. Object.entries(this.forms).forEach(([formKey, form]) => {
  1009. if (form.default) {
  1010. this.defaultForm = formKey;
  1011. }
  1012. });
  1013. Object.entries(this.views).forEach(([viewKey, view]) => {
  1014. view.parent = this;
  1015. if (this.defaultView === undefined) {
  1016. this.defaultView = viewKey;
  1017. this.view = viewKey;
  1018. this.form = view.form;
  1019. }
  1020. if (view.default) {
  1021. if (forms === {} || this.defaultForm === view.form)
  1022. {
  1023. this.defaultView = viewKey;
  1024. this.view = viewKey;
  1025. this.form = view.form;
  1026. }
  1027. }
  1028. // to remember the units the user last picked
  1029. view.units = {};
  1030. if (config.autoMass !== "off" && view.attributes.weight === undefined) {
  1031. let base = undefined;
  1032. switch(config.autoMass) {
  1033. case "human":
  1034. base = math.divide(math.unit(150, "lbs"), math.unit(5.917, "feet"))
  1035. break
  1036. case "quadruped at shoulder":
  1037. base = math.divide(math.unit(80, "lbs"), math.unit(30, "inches"))
  1038. break
  1039. }
  1040. view.attributes.weight = {
  1041. name: "Mass",
  1042. power: 3,
  1043. type: "mass",
  1044. base: math.multiply(base, view.attributes.height.base)
  1045. }
  1046. }
  1047. if (config.autoFoodIntake && view.attributes.weight !== undefined && view.attributes.energyNeed === undefined) {
  1048. view.attributes.energyIntake = {
  1049. name: "Food Intake",
  1050. power: 3,
  1051. type: "energy",
  1052. base: math.unit(2000 * view.attributes.weight.base.toNumber("lbs") / 150, "kcal")
  1053. }
  1054. }
  1055. if (config.autoCaloricValue && view.attributes.weight !== undefined && view.attributes.energyWorth === undefined) {
  1056. view.attributes.energyNeed = {
  1057. name: "Caloric Value",
  1058. power: 3,
  1059. type: "energy",
  1060. base: math.unit(860 * view.attributes.weight.base.toNumber("lbs"), "kcal")
  1061. }
  1062. }
  1063. if (config.autoPreyCapacity !== "none" && view.attributes.weight !== undefined && view.attributes.capacity === undefined) {
  1064. view.attributes.capacity = {
  1065. name: "Capacity",
  1066. power: 3,
  1067. type: "volume",
  1068. base: math.unit((config.autoPreyCapacity == "same-size" ? 1 : 0.05) * view.attributes.weight.base.toNumber("lbs") / 150, "people")
  1069. }
  1070. }
  1071. Object.entries(view.attributes).forEach(([key, val]) => {
  1072. Object.defineProperty(
  1073. view,
  1074. key,
  1075. {
  1076. get: function () {
  1077. return math.multiply(Math.pow(this.parent.scale, this.attributes[key].power), this.attributes[key].base);
  1078. },
  1079. set: function (value) {
  1080. const newScale = Math.pow(math.divide(value, this.attributes[key].base), 1 / this.attributes[key].power);
  1081. this.parent.scale = newScale;
  1082. }
  1083. }
  1084. );
  1085. });
  1086. });
  1087. this.sizes.forEach(size => {
  1088. if (size.default === true) {
  1089. if (Object.keys(forms).length > 0) {
  1090. if (this.defaultForm !== size.form) {
  1091. return;
  1092. }
  1093. }
  1094. this.views[this.defaultView].height = size.height;
  1095. this.size = size;
  1096. }
  1097. });
  1098. if (this.size === undefined && this.sizes.length > 0) {
  1099. this.views[this.defaultView].height = this.sizes[0].height;
  1100. this.size = this.sizes[0];
  1101. console.warn("No default size set for " + info.name);
  1102. } else if (this.sizes.length == 0) {
  1103. this.sizes = [
  1104. {
  1105. name: "Normal",
  1106. height: this.views[this.defaultView].height
  1107. }
  1108. ];
  1109. this.size = this.sizes[0];
  1110. }
  1111. this.desc = {};
  1112. Object.entries(this.info).forEach(([key, value]) => {
  1113. Object.defineProperty(
  1114. this.desc,
  1115. key,
  1116. {
  1117. get: function () {
  1118. let text = value.text;
  1119. if (entity.views[entity.view].info) {
  1120. if (entity.views[entity.view].info[key]) {
  1121. text = combineInfo(text, entity.views[entity.view].info[key]);
  1122. }
  1123. }
  1124. if (entity.size.info) {
  1125. if (entity.size.info[key]) {
  1126. text = combineInfo(text, entity.size.info[key]);
  1127. }
  1128. }
  1129. return { title: value.title, text: text };
  1130. }
  1131. }
  1132. )
  1133. });
  1134. Object.defineProperty(
  1135. this,
  1136. "currentView",
  1137. {
  1138. get: function() {
  1139. return entity.views[entity.view];
  1140. }
  1141. }
  1142. )
  1143. this.formViews = {};
  1144. this.formSizes = {}
  1145. Object.entries(views).forEach(([key, value]) => {
  1146. if (value.default) {
  1147. this.formViews[value.form] = key;
  1148. }
  1149. });
  1150. Object.entries(views).forEach(([key, value]) => {
  1151. if (this.formViews[value.form] === undefined) {
  1152. this.formViews[value.form] = key;
  1153. }
  1154. });
  1155. this.sizes.forEach(size => {
  1156. if (size.default) {
  1157. this.formSizes[size.form] = size;
  1158. }
  1159. })
  1160. this.sizes.forEach(size => {
  1161. if (this.formSizes[size.form] === undefined) {
  1162. this.formSizes[size.form] = size;
  1163. }
  1164. });
  1165. Object.values(views).forEach(view => {
  1166. if (this.formSizes[view.form] === undefined) {
  1167. this.formSizes[view.form] = { name: "Normal", height: view.attributes.height.base, default: true, form: view.form };
  1168. }
  1169. });
  1170. delete this.init;
  1171. return this;
  1172. }
  1173. }.init();
  1174. return entityTemplate;
  1175. }
  1176. function combineInfo(existing, next) {
  1177. switch (next.mode) {
  1178. case "replace":
  1179. return next.text;
  1180. case "prepend":
  1181. return next.text + existing;
  1182. case "append":
  1183. return existing + next.text;
  1184. }
  1185. return existing;
  1186. }
  1187. function clickDown(target, x, y) {
  1188. clicked = target;
  1189. movingInBounds = false;
  1190. const rect = target.getBoundingClientRect();
  1191. let entX = document.querySelector("#entities").getBoundingClientRect().x;
  1192. let entY = document.querySelector("#entities").getBoundingClientRect().y;
  1193. dragOffsetX = x - rect.left + entX;
  1194. dragOffsetY = y - rect.top + entY;
  1195. x = x - dragOffsetX;
  1196. y = y - dragOffsetY;
  1197. if (x >= 0 && x <= canvasWidth && y >= 0 && y <= canvasHeight) {
  1198. movingInBounds = true;
  1199. }
  1200. clickTimeout = setTimeout(() => { dragging = true }, 200)
  1201. target.classList.add("no-transition");
  1202. }
  1203. // could we make this actually detect the menu area?
  1204. function hoveringInDeleteArea(e) {
  1205. return e.clientY < document.querySelector("#menubar").clientHeight;
  1206. }
  1207. function clickUp(e) {
  1208. if (e.which != 1) {
  1209. return;
  1210. }
  1211. clearTimeout(clickTimeout);
  1212. if (clicked) {
  1213. clicked.classList.remove("no-transition");
  1214. if (dragging) {
  1215. dragging = false;
  1216. if (hoveringInDeleteArea(e)) {
  1217. removeEntity(clicked);
  1218. document.querySelector("#menubar").classList.remove("hover-delete");
  1219. }
  1220. } else {
  1221. select(clicked);
  1222. }
  1223. clicked = null;
  1224. }
  1225. }
  1226. function deselect(e) {
  1227. if (rulerMode) {
  1228. return;
  1229. }
  1230. if (e !== undefined && e.which != 1) {
  1231. return;
  1232. }
  1233. if (selected) {
  1234. selected.classList.remove("selected");
  1235. }
  1236. if (prevSelected) {
  1237. prevSelected.classList.remove("prevSelected");
  1238. }
  1239. document.getElementById("options-selected-entity-none").selected = "selected";
  1240. clearAttribution();
  1241. selected = null;
  1242. clearViewList();
  1243. clearEntityOptions();
  1244. clearViewOptions();
  1245. document.querySelector("#delete-entity").disabled = true;
  1246. document.querySelector("#grow").disabled = true;
  1247. document.querySelector("#shrink").disabled = true;
  1248. document.querySelector("#fit").disabled = true;
  1249. }
  1250. function select(target) {
  1251. if (prevSelected !== null) {
  1252. prevSelected.classList.remove("prevSelected");
  1253. }
  1254. prevSelected = selected;
  1255. prevSelectedEntity = selectedEntity;
  1256. deselect();
  1257. selected = target;
  1258. selectedEntity = entities[target.dataset.key];
  1259. updateRatios();
  1260. document.getElementById("options-selected-entity-" + target.dataset.key).selected = "selected";
  1261. if (prevSelected !== null && config.showRatios && selected !== prevSelected) {
  1262. prevSelected.classList.add("prevSelected");
  1263. }
  1264. selected.classList.add("selected");
  1265. displayAttribution(selectedEntity.views[selectedEntity.view].image.source);
  1266. configFormList(selectedEntity, selectedEntity.form);
  1267. configViewList(selectedEntity, selectedEntity.view);
  1268. configEntityOptions(selectedEntity, selectedEntity.view);
  1269. configViewOptions(selectedEntity, selectedEntity.view);
  1270. document.querySelector("#delete-entity").disabled = false;
  1271. document.querySelector("#grow").disabled = false;
  1272. document.querySelector("#shrink").disabled = false;
  1273. document.querySelector("#fit").disabled = false;
  1274. }
  1275. function configFormList(entity, selectedForm) {
  1276. const label = document.querySelector("#options-label-form");
  1277. const list = document.querySelector("#entity-form");
  1278. list.innerHTML = "";
  1279. if (selectedForm === undefined) {
  1280. label.style.display = "none";
  1281. list.style.display = "none";
  1282. return;
  1283. }
  1284. label.style.display = "block";
  1285. list.style.display = "block";
  1286. Object.keys(entity.forms).forEach(form => {
  1287. const option = document.createElement("option");
  1288. option.innerText = entity.forms[form].name;
  1289. option.value = form;
  1290. if (form === selectedForm) {
  1291. option.selected = true;
  1292. }
  1293. list.appendChild(option);
  1294. });
  1295. }
  1296. function configViewList(entity, selectedView) {
  1297. const list = document.querySelector("#entity-view");
  1298. list.innerHTML = "";
  1299. list.style.display = "block";
  1300. Object.keys(entity.views).forEach(view => {
  1301. if (Object.keys(entity.forms).length > 0) {
  1302. if (entity.views[view].form !== entity.form) {
  1303. return;
  1304. }
  1305. }
  1306. const option = document.createElement("option");
  1307. option.innerText = entity.views[view].name;
  1308. option.value = view;
  1309. if (isNsfw(entity.views[view].image.source)) {
  1310. option.classList.add("nsfw")
  1311. }
  1312. if (view === selectedView) {
  1313. option.selected = true;
  1314. if (option.classList.contains("nsfw")) {
  1315. list.classList.add("nsfw");
  1316. } else {
  1317. list.classList.remove("nsfw");
  1318. }
  1319. }
  1320. list.appendChild(option);
  1321. });
  1322. }
  1323. function clearViewList() {
  1324. const list = document.querySelector("#entity-view");
  1325. list.innerHTML = "";
  1326. list.style.display = "none";
  1327. }
  1328. function updateWorldOptions(entity, view) {
  1329. const heightInput = document.querySelector("#options-height-value");
  1330. const heightSelect = document.querySelector("#options-height-unit");
  1331. const converted = config.height.toNumber(heightSelect.value);
  1332. setNumericInput(heightInput, converted);
  1333. }
  1334. function configEntityOptions(entity, view) {
  1335. const holder = document.querySelector("#options-entity");
  1336. document.querySelector("#entity-category-header").style.display = "block";
  1337. document.querySelector("#entity-category").style.display = "block";
  1338. holder.innerHTML = "";
  1339. const scaleLabel = document.createElement("div");
  1340. scaleLabel.classList.add("options-label");
  1341. scaleLabel.innerText = "Scale";
  1342. const scaleRow = document.createElement("div");
  1343. scaleRow.classList.add("options-row");
  1344. const scaleInput = document.createElement("input");
  1345. scaleInput.classList.add("options-field-numeric");
  1346. scaleInput.id = "options-entity-scale";
  1347. scaleInput.addEventListener("change", e => {
  1348. try {
  1349. const newScale = e.target.value == 0 ? 1 : math.evaluate(e.target.value);
  1350. if (typeof(newScale) !== "number") {
  1351. toast("Invalid input: scale can't have any units!")
  1352. return;
  1353. }
  1354. entity.scale = newScale;
  1355. } catch {
  1356. toast("Invalid input: could not parse " + e.target.value)
  1357. }
  1358. entity.dirty = true;
  1359. if (config.autoFit) {
  1360. fitWorld();
  1361. } else {
  1362. updateSizes(true);
  1363. }
  1364. updateEntityOptions(entity, entity.view);
  1365. updateViewOptions(entity, entity.view);
  1366. });
  1367. scaleInput.addEventListener("keydown", e => {
  1368. e.stopPropagation();
  1369. })
  1370. setNumericInput(scaleInput, entity.scale);
  1371. scaleRow.appendChild(scaleInput);
  1372. holder.appendChild(scaleLabel);
  1373. holder.appendChild(scaleRow);
  1374. const nameLabel = document.createElement("div");
  1375. nameLabel.classList.add("options-label");
  1376. nameLabel.innerText = "Name";
  1377. const nameRow = document.createElement("div");
  1378. nameRow.classList.add("options-row");
  1379. const nameInput = document.createElement("input");
  1380. nameInput.classList.add("options-field-text");
  1381. nameInput.value = entity.name;
  1382. nameInput.addEventListener("input", e => {
  1383. entity.name = e.target.value;
  1384. entity.dirty = true;
  1385. updateSizes(true);
  1386. })
  1387. nameInput.addEventListener("keydown", e => {
  1388. e.stopPropagation();
  1389. })
  1390. nameRow.appendChild(nameInput);
  1391. holder.appendChild(nameLabel);
  1392. holder.appendChild(nameRow);
  1393. configSizeList(entity);
  1394. document.querySelector("#options-order-display").innerText = entity.priority;
  1395. document.querySelector("#options-brightness-display").innerText = entity.brightness;
  1396. document.querySelector("#options-ordering").style.display = "flex";
  1397. }
  1398. function configSizeList(entity) {
  1399. const defaultHolder = document.querySelector("#options-entity-defaults");
  1400. defaultHolder.innerHTML = "";
  1401. entity.sizes.forEach(defaultInfo => {
  1402. if (Object.keys(entity.forms).length > 0) {
  1403. if (defaultInfo.form !== entity.form) {
  1404. return;
  1405. }
  1406. }
  1407. const button = document.createElement("button");
  1408. button.classList.add("options-button");
  1409. button.innerText = defaultInfo.name;
  1410. button.addEventListener("click", e => {
  1411. if (Object.keys(entity.forms).length > 0) {
  1412. entity.views[entity.formViews[entity.form]].height = defaultInfo.height;
  1413. } else {
  1414. entity.views[entity.defaultView].height = defaultInfo.height;
  1415. }
  1416. entity.dirty = true;
  1417. updateEntityOptions(entity, entity.view);
  1418. updateViewOptions(entity, entity.view);
  1419. if (!checkFitWorld()) {
  1420. updateSizes(true);
  1421. }
  1422. if (config.autoFitSize) {
  1423. let targets = {};
  1424. targets[selected.dataset.key] = entities[selected.dataset.key];
  1425. fitEntities(targets);
  1426. }
  1427. });
  1428. defaultHolder.appendChild(button);
  1429. });
  1430. }
  1431. function updateEntityOptions(entity, view) {
  1432. const scaleInput = document.querySelector("#options-entity-scale");
  1433. setNumericInput(scaleInput, entity.scale);
  1434. document.querySelector("#options-order-display").innerText = entity.priority;
  1435. document.querySelector("#options-brightness-display").innerText = entity.brightness;
  1436. }
  1437. function clearEntityOptions() {
  1438. document.querySelector("#entity-category-header").style.display = "none";
  1439. document.querySelector("#entity-category").style.display = "none";
  1440. /*
  1441. const holder = document.querySelector("#options-entity");
  1442. holder.innerHTML = "";
  1443. document.querySelector("#options-entity-defaults").innerHTML = "";
  1444. document.querySelector("#options-ordering").style.display = "none";
  1445. document.querySelector("#options-ordering").style.display = "none";*/
  1446. }
  1447. function configViewOptions(entity, view) {
  1448. const holder = document.querySelector("#options-view");
  1449. document.querySelector("#view-category-header").style.display = "block";
  1450. document.querySelector("#view-category").style.display = "block";
  1451. holder.innerHTML = "";
  1452. Object.entries(entity.views[view].attributes).forEach(([key, val]) => {
  1453. const label = document.createElement("div");
  1454. label.classList.add("options-label");
  1455. label.innerText = val.name;
  1456. holder.appendChild(label);
  1457. const row = document.createElement("div");
  1458. row.classList.add("options-row");
  1459. holder.appendChild(row);
  1460. const input = document.createElement("input");
  1461. input.classList.add("options-field-numeric");
  1462. input.id = "options-view-" + key + "-input";
  1463. const select = document.createElement("select");
  1464. select.classList.add("options-field-unit");
  1465. select.id = "options-view-" + key + "-select"
  1466. Object.entries(unitChoices[val.type]).forEach(([group, entries]) => {
  1467. const optGroup = document.createElement("optgroup");
  1468. optGroup.label = group;
  1469. select.appendChild(optGroup);
  1470. entries.forEach(entry => {
  1471. const option = document.createElement("option");
  1472. option.innerText = entry;
  1473. if (entry == defaultUnits[val.type][config.units]) {
  1474. option.selected = true;
  1475. }
  1476. select.appendChild(option);
  1477. })
  1478. });
  1479. input.addEventListener("change", e => {
  1480. const raw_value = input.value == 0 ? 1 : input.value;
  1481. let value
  1482. try {
  1483. value = math.evaluate(raw_value).toNumber(select.value);
  1484. } catch {
  1485. try {
  1486. value = math.evaluate(input.value)
  1487. if (typeof(value) !== "number") {
  1488. toast("Invalid input: " + value.format() + " can't convert to " + select.value)
  1489. value = undefined
  1490. }
  1491. } catch {
  1492. toast("Invalid input: could not parse: " + input.value)
  1493. value = undefined
  1494. }
  1495. }
  1496. if (value === undefined) {
  1497. return;
  1498. }
  1499. input.value = value
  1500. entity.views[view][key] = math.unit(value, select.value);
  1501. entity.dirty = true;
  1502. if (config.autoFit) {
  1503. fitWorld();
  1504. } else {
  1505. updateSizes(true);
  1506. }
  1507. updateEntityOptions(entity, view);
  1508. updateViewOptions(entity, view, key);
  1509. });
  1510. input.addEventListener("keydown", e => {
  1511. e.stopPropagation();
  1512. })
  1513. if (entity.currentView.units[key]) {
  1514. select.value = entity.currentView.units[key];
  1515. } else {
  1516. entity.currentView.units[key] = select.value;
  1517. }
  1518. select.dataset.oldUnit = select.value;
  1519. setNumericInput(input, entity.views[view][key].toNumber(select.value));
  1520. // TODO does this ever cause a change in the world?
  1521. select.addEventListener("input", e => {
  1522. const value = input.value == 0 ? 1 : input.value;
  1523. const oldUnit = select.dataset.oldUnit;
  1524. entity.views[entity.view][key] = math.unit(value, oldUnit).to(select.value);
  1525. entity.dirty = true;
  1526. setNumericInput(input, entity.views[entity.view][key].toNumber(select.value));
  1527. select.dataset.oldUnit = select.value;
  1528. entity.views[view].units[key] = select.value;
  1529. if (config.autoFit) {
  1530. fitWorld();
  1531. } else {
  1532. updateSizes(true);
  1533. }
  1534. updateEntityOptions(entity, view);
  1535. updateViewOptions(entity, view, key);
  1536. });
  1537. row.appendChild(input);
  1538. row.appendChild(select);
  1539. });
  1540. }
  1541. function updateViewOptions(entity, view, changed) {
  1542. Object.entries(entity.views[view].attributes).forEach(([key, val]) => {
  1543. if (key != changed) {
  1544. const input = document.querySelector("#options-view-" + key + "-input");
  1545. const select = document.querySelector("#options-view-" + key + "-select");
  1546. const currentUnit = select.value;
  1547. const convertedAmount = entity.views[view][key].toNumber(currentUnit);
  1548. setNumericInput(input, convertedAmount);
  1549. }
  1550. });
  1551. }
  1552. function setNumericInput(input, value, round = 6) {
  1553. if (typeof value == "string") {
  1554. value = parseFloat(value)
  1555. }
  1556. input.value = value.toPrecision(round);
  1557. }
  1558. function getSortedEntities() {
  1559. return Object.keys(entities).sort((a, b) => {
  1560. const entA = entities[a];
  1561. const entB = entities[b];
  1562. const viewA = entA.view;
  1563. const viewB = entB.view;
  1564. const heightA = entA.views[viewA].height.to("meter").value;
  1565. const heightB = entB.views[viewB].height.to("meter").value;
  1566. return heightA - heightB;
  1567. });
  1568. }
  1569. function clearViewOptions() {
  1570. document.querySelector("#view-category-header").style.display = "none";
  1571. document.querySelector("#view-category").style.display = "none";
  1572. }
  1573. // this is a crime against humanity, and also stolen from
  1574. // stack overflow
  1575. // https://stackoverflow.com/questions/38487569/click-through-png-image-only-if-clicked-coordinate-is-transparent
  1576. const testCanvas = document.createElement("canvas");
  1577. testCanvas.id = "test-canvas";
  1578. function rotate(point, angle) {
  1579. return [
  1580. point[0] * Math.cos(angle) - point[1] * Math.sin(angle),
  1581. point[0] * Math.sin(angle) + point[1] * Math.cos(angle)
  1582. ];
  1583. }
  1584. const testCtx = testCanvas.getContext("2d");
  1585. function testClick(event) {
  1586. testCtx.save();
  1587. const target = event.target;
  1588. if (rulerMode) {
  1589. return;
  1590. }
  1591. // Get click coordinates
  1592. let w = target.width;
  1593. let h = target.height;
  1594. let ratioW = 1, ratioH = 1;
  1595. // Limit the size of the canvas so that very large images don't cause problems)
  1596. if (w > 1000) {
  1597. ratioW = w / 1000;
  1598. w /= ratioW;
  1599. h /= ratioW;
  1600. }
  1601. if (h > 1000) {
  1602. ratioH = h / 1000;
  1603. w /= ratioH;
  1604. h /= ratioH;
  1605. }
  1606. // todo remove some of this unused stuff
  1607. const ratio = ratioW * ratioH;
  1608. const entity = entities[target.parentElement.dataset.key];
  1609. const angle = entity.rotation;
  1610. var x = event.clientX - target.getBoundingClientRect().x,
  1611. y = event.clientY - target.getBoundingClientRect().y,
  1612. alpha;
  1613. [xTarget,yTarget] = [x,y];
  1614. [actualW, actualH] = [target.getBoundingClientRect().width, target.getBoundingClientRect().height];
  1615. xTarget /= ratio;
  1616. yTarget /= ratio;
  1617. actualW /= ratio;
  1618. actualH /= ratio;
  1619. testCtx.canvas.width = actualW;
  1620. testCtx.canvas.height = actualH;
  1621. testCtx.save();
  1622. // dear future me: Sorry :(
  1623. testCtx.resetTransform();
  1624. testCtx.translate(actualW/2, actualH/2);
  1625. testCtx.rotate(angle);
  1626. testCtx.translate(-actualW/2, -actualH/2);
  1627. testCtx.drawImage(target, (actualW/2 - w/2), (actualH/2 - h/2), w, h);
  1628. testCtx.fillStyle = "red";
  1629. testCtx.fillRect(actualW/2,actualH/2,10,10);
  1630. testCtx.restore();
  1631. testCtx.fillStyle = "red";
  1632. alpha = testCtx.getImageData(xTarget, yTarget, 1, 1).data[3];
  1633. testCtx.fillRect(xTarget, yTarget, 3, 3);
  1634. // If the pixel is transparent,
  1635. // retrieve the element underneath and trigger its click event
  1636. if (alpha === 0) {
  1637. const oldDisplay = target.style.display;
  1638. target.style.display = "none";
  1639. const newTarget = document.elementFromPoint(event.clientX, event.clientY);
  1640. newTarget.dispatchEvent(new MouseEvent(event.type, {
  1641. "clientX": event.clientX,
  1642. "clientY": event.clientY
  1643. }));
  1644. target.style.display = oldDisplay;
  1645. } else {
  1646. clickDown(target.parentElement, event.clientX, event.clientY);
  1647. }
  1648. testCtx.restore();
  1649. }
  1650. function arrangeEntities(order) {
  1651. const worldWidth = config.height.toNumber("meters") / canvasHeight * canvasWidth;
  1652. let sum = 0;
  1653. order.forEach(key => {
  1654. const image = document.querySelector("#entity-" + key + " > .entity-image");
  1655. const meters = entities[key].views[entities[key].view].height.toNumber("meters");
  1656. let height = image.height;
  1657. let width = image.width;
  1658. if (height == 0) {
  1659. height = 100;
  1660. }
  1661. if (width == 0) {
  1662. width = height;
  1663. }
  1664. sum += meters * width / height;
  1665. });
  1666. let x = config.x - sum / 2;
  1667. order.forEach(key => {
  1668. const image = document.querySelector("#entity-" + key + " > .entity-image");
  1669. const meters = entities[key].views[entities[key].view].height.toNumber("meters");
  1670. let height = image.height;
  1671. let width = image.width;
  1672. if (height == 0) {
  1673. height = 100;
  1674. }
  1675. if (width == 0) {
  1676. width = height;
  1677. }
  1678. x += meters * width / height / 2;
  1679. document.querySelector("#entity-" + key).dataset.x = x;
  1680. document.querySelector("#entity-" + key).dataset.y = config.y;
  1681. x += meters * width / height / 2;
  1682. })
  1683. fitWorld();
  1684. updateSizes();
  1685. }
  1686. function removeAllEntities() {
  1687. Object.keys(entities).forEach(key => {
  1688. removeEntity(document.querySelector("#entity-" + key));
  1689. });
  1690. }
  1691. function clearAttribution() {
  1692. document.querySelector("#attribution-category-header").style.display = "none";
  1693. document.querySelector("#options-attribution").style.display = "none";
  1694. }
  1695. function displayAttribution(file) {
  1696. document.querySelector("#attribution-category-header").style.display = "block";
  1697. document.querySelector("#options-attribution").style.display = "inline";
  1698. const authors = authorsOfFull(file);
  1699. const owners = ownersOfFull(file);
  1700. const citations = citationsOf(file);
  1701. const source = sourceOf(file);
  1702. const authorHolder = document.querySelector("#options-attribution-authors");
  1703. const ownerHolder = document.querySelector("#options-attribution-owners");
  1704. const citationHolder = document.querySelector("#options-attribution-citations");
  1705. const sourceHolder = document.querySelector("#options-attribution-source");
  1706. if (authors === []) {
  1707. const div = document.createElement("div");
  1708. div.innerText = "Unknown";
  1709. authorHolder.innerHTML = "";
  1710. authorHolder.appendChild(div);
  1711. } else if (authors === undefined) {
  1712. const div = document.createElement("div");
  1713. div.innerText = "Not yet entered";
  1714. authorHolder.innerHTML = "";
  1715. authorHolder.appendChild(div);
  1716. } else {
  1717. authorHolder.innerHTML = "";
  1718. const list = document.createElement("ul");
  1719. authorHolder.appendChild(list);
  1720. authors.forEach(author => {
  1721. const authorEntry = document.createElement("li");
  1722. if (author.url) {
  1723. const link = document.createElement("a");
  1724. link.href = author.url;
  1725. link.innerText = author.name;
  1726. link.rel = "noreferrer no opener";
  1727. link.target = "_blank";
  1728. authorEntry.appendChild(link);
  1729. } else {
  1730. const div = document.createElement("div");
  1731. div.innerText = author.name;
  1732. authorEntry.appendChild(div);
  1733. }
  1734. list.appendChild(authorEntry);
  1735. });
  1736. }
  1737. if (owners === []) {
  1738. const div = document.createElement("div");
  1739. div.innerText = "Unknown";
  1740. ownerHolder.innerHTML = "";
  1741. ownerHolder.appendChild(div);
  1742. } else if (owners === undefined) {
  1743. const div = document.createElement("div");
  1744. div.innerText = "Not yet entered";
  1745. ownerHolder.innerHTML = "";
  1746. ownerHolder.appendChild(div);
  1747. } else {
  1748. ownerHolder.innerHTML = "";
  1749. const list = document.createElement("ul");
  1750. ownerHolder.appendChild(list);
  1751. owners.forEach(owner => {
  1752. const ownerEntry = document.createElement("li");
  1753. if (owner.url) {
  1754. const link = document.createElement("a");
  1755. link.href = owner.url;
  1756. link.innerText = owner.name;
  1757. link.rel = "noreferrer no opener";
  1758. link.target = "_blank";
  1759. ownerEntry.appendChild(link);
  1760. } else {
  1761. const div = document.createElement("div");
  1762. div.innerText = owner.name;
  1763. ownerEntry.appendChild(div);
  1764. }
  1765. list.appendChild(ownerEntry);
  1766. });
  1767. }
  1768. if (citations === [] || citations === undefined) {
  1769. } else {
  1770. citationHolder.innerHTML = "";
  1771. const list = document.createElement("ul");
  1772. citationHolder.appendChild(list);
  1773. citations.forEach(citation => {
  1774. const citationEntry = document.createElement("li");
  1775. const link = document.createElement("a");
  1776. link.style.display = "block";
  1777. link.href = citation;
  1778. link.innerText = new URL(citation).host;
  1779. link.rel = "noreferrer no opener";
  1780. link.target = "_blank";
  1781. citationEntry.appendChild(link);
  1782. list.appendChild(citationEntry);
  1783. })
  1784. }
  1785. if (source === null) {
  1786. const div = document.createElement("div");
  1787. div.innerText = "No link";
  1788. sourceHolder.innerHTML = "";
  1789. sourceHolder.appendChild(div);
  1790. } else if (source === undefined) {
  1791. const div = document.createElement("div");
  1792. div.innerText = "Not yet entered";
  1793. sourceHolder.innerHTML = "";
  1794. sourceHolder.appendChild(div);
  1795. } else {
  1796. sourceHolder.innerHTML = "";
  1797. const link = document.createElement("a");
  1798. link.style.display = "block";
  1799. link.href = source;
  1800. link.innerText = new URL(source).host;
  1801. link.rel = "noreferrer no opener";
  1802. link.target = "_blank";
  1803. sourceHolder.appendChild(link);
  1804. }
  1805. }
  1806. function removeEntity(element) {
  1807. if (selected == element) {
  1808. deselect();
  1809. }
  1810. if (clicked == element) {
  1811. clicked = null;
  1812. }
  1813. const option = document.querySelector("#options-selected-entity-" + element.dataset.key);
  1814. option.parentElement.removeChild(option);
  1815. delete entities[element.dataset.key];
  1816. const bottomName = document.querySelector("#bottom-name-" + element.dataset.key);
  1817. const topName = document.querySelector("#top-name-" + element.dataset.key);
  1818. bottomName.parentElement.removeChild(bottomName);
  1819. topName.parentElement.removeChild(topName);
  1820. element.parentElement.removeChild(element);
  1821. }
  1822. function checkEntity(entity) {
  1823. Object.values(entity.views).forEach(view => {
  1824. if (authorsOf(view.image.source) === undefined) {
  1825. console.warn("No authors: " + view.image.source);
  1826. }
  1827. });
  1828. }
  1829. function preloadViews(entity) {
  1830. Object.values(entity.views).forEach(view => {
  1831. if (Object.keys(entity.forms).length > 0) {
  1832. if (entity.form !== view.form){
  1833. return;
  1834. }
  1835. }
  1836. if (!preloaded.has(view.image.source)) {
  1837. let img = new Image();
  1838. img.src = view.image.source;
  1839. preloaded.add(view.image.source);
  1840. }
  1841. });
  1842. }
  1843. function displayEntity(entity, view, x, y, selectEntity = false, refresh = false) {
  1844. checkEntity(entity);
  1845. // preload all of the entity's views
  1846. preloadViews(entity);
  1847. const box = document.createElement("div");
  1848. box.classList.add("entity-box");
  1849. const img = document.createElement("img");
  1850. img.classList.add("entity-image");
  1851. img.addEventListener("dragstart", e => {
  1852. e.preventDefault();
  1853. });
  1854. const nameTag = document.createElement("div");
  1855. nameTag.classList.add("entity-name");
  1856. nameTag.innerText = entity.name;
  1857. box.appendChild(img);
  1858. box.appendChild(nameTag);
  1859. const image = entity.views[view].image;
  1860. img.src = image.source;
  1861. if (image.bottom !== undefined) {
  1862. img.style.setProperty("--offset", ((-1 + image.bottom) * 100) + "%")
  1863. } else {
  1864. img.style.setProperty("--offset", ((-1) * 100) + "%")
  1865. }
  1866. img.style.setProperty("--rotation", (entity.rotation * 180 / Math.PI) + "deg")
  1867. box.dataset.x = x;
  1868. box.dataset.y = y;
  1869. img.addEventListener("mousedown", e => { if (e.which == 1) { testClick(e); if (clicked) { e.stopPropagation() } } });
  1870. img.addEventListener("touchstart", e => {
  1871. const fakeEvent = {
  1872. target: e.target,
  1873. clientX: e.touches[0].clientX,
  1874. clientY: e.touches[0].clientY,
  1875. which: 1
  1876. };
  1877. testClick(fakeEvent);
  1878. if (clicked) { e.stopPropagation() }
  1879. });
  1880. const heightBar = document.createElement("div");
  1881. heightBar.classList.add("height-bar");
  1882. box.appendChild(heightBar);
  1883. box.id = "entity-" + entityIndex;
  1884. box.dataset.key = entityIndex;
  1885. entity.view = view;
  1886. if (entity.priority === undefined)
  1887. entity.priority = 0;
  1888. if (entity.brightness === undefined)
  1889. entity.brightness = 1;
  1890. entities[entityIndex] = entity;
  1891. entity.index = entityIndex;
  1892. const world = document.querySelector("#entities");
  1893. world.appendChild(box);
  1894. const bottomName = document.createElement("div");
  1895. bottomName.classList.add("bottom-name");
  1896. bottomName.id = "bottom-name-" + entityIndex;
  1897. bottomName.innerText = entity.name;
  1898. bottomName.addEventListener("click", () => select(box));
  1899. world.appendChild(bottomName);
  1900. const topName = document.createElement("div");
  1901. topName.classList.add("top-name");
  1902. topName.id = "top-name-" + entityIndex;
  1903. topName.innerText = entity.name;
  1904. topName.addEventListener("click", () => select(box));
  1905. world.appendChild(topName);
  1906. const entityOption = document.createElement("option");
  1907. entityOption.id = "options-selected-entity-" + entityIndex;
  1908. entityOption.value = entityIndex;
  1909. entityOption.innerText = entity.name;
  1910. document.getElementById("options-selected-entity").appendChild(entityOption);
  1911. entityIndex += 1;
  1912. if (config.autoFit) {
  1913. fitWorld();
  1914. }
  1915. if (selectEntity)
  1916. select(box);
  1917. entity.dirty = true;
  1918. if (refresh && config.autoFitAdd) {
  1919. let targets = {};
  1920. targets[entityIndex - 1] = entity;
  1921. fitEntities(targets);
  1922. }
  1923. if (refresh)
  1924. updateSizes(true);
  1925. }
  1926. window.onblur = function () {
  1927. altHeld = false;
  1928. shiftHeld = false;
  1929. }
  1930. window.onfocus = function () {
  1931. window.dispatchEvent(new Event("keydown"));
  1932. }
  1933. // thanks to https://developers.google.com/web/fundamentals/native-hardware/fullscreen
  1934. function toggleFullScreen() {
  1935. var doc = window.document;
  1936. var docEl = doc.documentElement;
  1937. var requestFullScreen = docEl.requestFullscreen || docEl.mozRequestFullScreen || docEl.webkitRequestFullScreen || docEl.msRequestFullscreen;
  1938. var cancelFullScreen = doc.exitFullscreen || doc.mozCancelFullScreen || doc.webkitExitFullscreen || doc.msExitFullscreen;
  1939. if (!doc.fullscreenElement && !doc.mozFullScreenElement && !doc.webkitFullscreenElement && !doc.msFullscreenElement) {
  1940. requestFullScreen.call(docEl);
  1941. }
  1942. else {
  1943. cancelFullScreen.call(doc);
  1944. }
  1945. }
  1946. function handleResize() {
  1947. const oldCanvasWidth = canvasWidth;
  1948. entityX = document.querySelector("#entities").getBoundingClientRect().x;
  1949. canvasWidth = document.querySelector("#display").clientWidth - 100;
  1950. canvasHeight = document.querySelector("#display").clientHeight - 50;
  1951. const change = oldCanvasWidth / canvasWidth;
  1952. updateSizes();
  1953. }
  1954. function prepareSidebar() {
  1955. const menubar = document.querySelector("#sidebar-menu");
  1956. [
  1957. {
  1958. name: "Show/hide sidebar",
  1959. id: "menu-toggle-sidebar",
  1960. icon: "fas fa-chevron-circle-down",
  1961. rotates: true
  1962. },
  1963. {
  1964. name: "Fullscreen",
  1965. id: "menu-fullscreen",
  1966. icon: "fas fa-compress"
  1967. },
  1968. {
  1969. name: "Clear",
  1970. id: "menu-clear",
  1971. icon: "fas fa-file"
  1972. },
  1973. {
  1974. name: "Sort by height",
  1975. id: "menu-order-height",
  1976. icon: "fas fa-sort-numeric-up"
  1977. },
  1978. {
  1979. name: "Permalink",
  1980. id: "menu-permalink",
  1981. icon: "fas fa-link"
  1982. },
  1983. {
  1984. name: "Export to clipboard",
  1985. id: "menu-export",
  1986. icon: "fas fa-share"
  1987. },
  1988. {
  1989. name: "Import from clipboard",
  1990. id: "menu-import",
  1991. icon: "fas fa-share",
  1992. classes: ["flipped"]
  1993. },
  1994. {
  1995. name: "Save Scene",
  1996. id: "menu-save",
  1997. icon: "fas fa-download",
  1998. input: true
  1999. },
  2000. {
  2001. name: "Load Scene",
  2002. id: "menu-load",
  2003. icon: "fas fa-upload",
  2004. select: true
  2005. },
  2006. {
  2007. name: "Delete Scene",
  2008. id: "menu-delete",
  2009. icon: "fas fa-trash",
  2010. select: true
  2011. },
  2012. {
  2013. name: "Load Autosave",
  2014. id: "menu-load-autosave",
  2015. icon: "fas fa-redo"
  2016. },
  2017. {
  2018. name: "Add Image",
  2019. id: "menu-add-image",
  2020. icon: "fas fa-camera"
  2021. },
  2022. {
  2023. name: "Clear Rulers",
  2024. id: "menu-clear-rulers",
  2025. icon: "fas fa-ruler"
  2026. }
  2027. ].forEach(entry => {
  2028. const buttonHolder = document.createElement("div");
  2029. buttonHolder.classList.add("menu-button-holder");
  2030. const button = document.createElement("button");
  2031. button.id = entry.id;
  2032. button.classList.add("menu-button");
  2033. const icon = document.createElement("i");
  2034. icon.classList.add(...entry.icon.split(" "));
  2035. if (entry.rotates) {
  2036. icon.classList.add("rotate-backward", "transitions");
  2037. }
  2038. if (entry.classes) {
  2039. entry.classes.forEach(cls => icon.classList.add(cls));
  2040. }
  2041. const actionText = document.createElement("span");
  2042. actionText.innerText = entry.name;
  2043. actionText.classList.add("menu-text");
  2044. const srText = document.createElement("span");
  2045. srText.classList.add("sr-only");
  2046. srText.innerText = entry.name;
  2047. button.appendChild(icon);
  2048. button.appendChild(srText);
  2049. buttonHolder.appendChild(button);
  2050. buttonHolder.appendChild(actionText);
  2051. if (entry.input) {
  2052. const input = document.createElement("input");
  2053. buttonHolder.appendChild(input);
  2054. input.placeholder = "default";
  2055. input.addEventListener("keyup", e => {
  2056. if (e.key === "Enter") {
  2057. const name = document.querySelector("#menu-save ~ input").value;
  2058. if (/\S/.test(name)) {
  2059. saveScene(name);
  2060. }
  2061. updateSaveInfo();
  2062. e.preventDefault();
  2063. }
  2064. })
  2065. }
  2066. if (entry.select) {
  2067. const select = document.createElement("select");
  2068. buttonHolder.appendChild(select);
  2069. }
  2070. menubar.appendChild(buttonHolder);
  2071. });
  2072. }
  2073. function checkBodyClass(cls) {
  2074. return document.body.classList.contains(cls);
  2075. }
  2076. function toggleBodyClass(cls, setting) {
  2077. if (setting) {
  2078. document.body.classList.add(cls);
  2079. } else {
  2080. document.body.classList.remove(cls);
  2081. }
  2082. }
  2083. const backgroundColors = {
  2084. "none": "#00000000",
  2085. "black": "#000",
  2086. "dark": "#111",
  2087. "medium": "#333",
  2088. "light": "#555"
  2089. }
  2090. const settingsData = {
  2091. "show-vertical-scale": {
  2092. name: "Vertical Scale",
  2093. desc: "Draw vertical scale marks",
  2094. type: "toggle",
  2095. default: true,
  2096. get value() {
  2097. return config.drawYAxis;
  2098. },
  2099. set value(param) {
  2100. config.drawYAxis = param;
  2101. drawScales(false);
  2102. }
  2103. },
  2104. "show-horizontal-scale": {
  2105. name: "Horiziontal Scale",
  2106. desc: "Draw horizontal scale marks",
  2107. type: "toggle",
  2108. default: false,
  2109. get value() {
  2110. return config.drawXAxis;
  2111. },
  2112. set value(param) {
  2113. config.drawXAxis = param;
  2114. drawScales(false);
  2115. }
  2116. },
  2117. "show-altitudes": {
  2118. name: "Altitudes",
  2119. desc: "Draw interesting altitudes",
  2120. type: "select",
  2121. default: "none",
  2122. disabled: "none",
  2123. options: [
  2124. "none",
  2125. "all",
  2126. "atmosphere",
  2127. "orbits",
  2128. "weather",
  2129. "water",
  2130. "geology",
  2131. "thicknesses",
  2132. "airspaces",
  2133. "races",
  2134. "olympic-records",
  2135. ],
  2136. get value() {
  2137. return config.drawAltitudes;
  2138. },
  2139. set value(param) {
  2140. config.drawAltitudes = param;
  2141. drawScales(false);
  2142. }
  2143. },
  2144. "lock-y-axis": {
  2145. name: "Lock Y-Axis",
  2146. desc: "Keep the camera at ground-level",
  2147. type: "toggle",
  2148. default: true,
  2149. get value() {
  2150. return config.lockYAxis;
  2151. },
  2152. set value(param) {
  2153. config.lockYAxis = param;
  2154. if (param) {
  2155. config.y = 0;
  2156. updateSizes();
  2157. document.querySelector("#scroll-up").disabled = true;
  2158. document.querySelector("#scroll-down").disabled = true;
  2159. } else {
  2160. document.querySelector("#scroll-up").disabled = false;
  2161. document.querySelector("#scroll-down").disabled = false;
  2162. }
  2163. }
  2164. },
  2165. "axis-spacing": {
  2166. name: "Axis Spacing",
  2167. desc: "How frequent the axis lines are",
  2168. type: "select",
  2169. default: "standard",
  2170. options: [
  2171. "dense",
  2172. "standard",
  2173. "sparse"
  2174. ],
  2175. get value() {
  2176. return config.axisSpacing;
  2177. },
  2178. set value(param) {
  2179. config.axisSpacing = param;
  2180. const factor = {
  2181. "dense": 0.5,
  2182. "standard": 1,
  2183. "sparse": 2
  2184. }[param];
  2185. config.minLineSize = factor * 100;
  2186. config.maxLineSize = factor * 150;
  2187. updateSizes();
  2188. }
  2189. },
  2190. "ground-type": {
  2191. name: "Ground",
  2192. desc: "What kind of ground to show, if any",
  2193. type: "select",
  2194. default: "black",
  2195. disabled: "none",
  2196. options: [
  2197. "none",
  2198. "black",
  2199. "dark",
  2200. "medium",
  2201. "light",
  2202. ],
  2203. get value() {
  2204. return config.groundKind;
  2205. },
  2206. set value(param) {
  2207. config.groundKind = param;
  2208. document.querySelector("#ground").style.setProperty("--ground-color", backgroundColors[param])
  2209. }
  2210. },
  2211. "ground-pos": {
  2212. name: "Ground Position",
  2213. desc: "How high the ground is if the y-axis is locked",
  2214. type: "select",
  2215. default: "bottom",
  2216. options: [
  2217. "very-high",
  2218. "high",
  2219. "medium",
  2220. "low",
  2221. "very-low",
  2222. "bottom",
  2223. ],
  2224. get value() {
  2225. return config.groundPos;
  2226. },
  2227. set value(param) {
  2228. config.groundPos = param;
  2229. updateSizes();
  2230. }
  2231. },
  2232. "auto-scale": {
  2233. name: "Auto-Size World",
  2234. desc: "Constantly zoom to fit the largest entity",
  2235. type: "toggle",
  2236. default: false,
  2237. get value() {
  2238. return config.autoFit;
  2239. },
  2240. set value(param) {
  2241. config.autoFit = param;
  2242. checkFitWorld();
  2243. }
  2244. },
  2245. "auto-units": {
  2246. name: "Auto-Select Units",
  2247. desc: "Automatically switch units when zooming in and out",
  2248. type: "toggle",
  2249. default: false,
  2250. get value() {
  2251. return config.autoUnits;
  2252. },
  2253. set value(param) {
  2254. config.autoUnits = param;
  2255. }
  2256. },
  2257. "zoom-when-adding": {
  2258. name: "Zoom On Add",
  2259. desc: "Zoom to fit when you add a new entity",
  2260. type: "toggle",
  2261. default: true,
  2262. get value() {
  2263. return config.autoFitAdd;
  2264. },
  2265. set value(param) {
  2266. config.autoFitAdd = param;
  2267. }
  2268. },
  2269. "zoom-when-sizing": {
  2270. name: "Zoom On Size",
  2271. desc: "Zoom to fit when you select an entity's size",
  2272. type: "toggle",
  2273. default: true,
  2274. get value() {
  2275. return config.autoFitSize;
  2276. },
  2277. set value(param) {
  2278. config.autoFitSize = param;
  2279. }
  2280. },
  2281. "show-ratios": {
  2282. name: "Show Ratios",
  2283. desc: "Show the proportions between the current selection and the most recent selection.",
  2284. type: "toggle",
  2285. default: true,
  2286. get value() {
  2287. return config.showRatios;
  2288. },
  2289. set value(param) {
  2290. config.showRatios = param;
  2291. if (param) {
  2292. document.body.querySelector(".ratio-info").style.display = "block";
  2293. } else {
  2294. document.body.querySelector(".ratio-info").style.display = "none";
  2295. }
  2296. }
  2297. },
  2298. "attach-rulers": {
  2299. name: "Attach Rulers",
  2300. desc: "Rulers will attach to the currently-selected entity, moving around with it.",
  2301. type: "toggle",
  2302. default: true,
  2303. get value() {
  2304. return config.rulersStick;
  2305. },
  2306. set value(param) {
  2307. config.rulersStick = param;
  2308. }
  2309. },
  2310. "units": {
  2311. name: "Default Units",
  2312. desc: "Which kind of unit to use by default",
  2313. type: "select",
  2314. default: "metric",
  2315. options: [
  2316. "metric",
  2317. "customary",
  2318. "relative",
  2319. "quirky"
  2320. ],
  2321. get value() {
  2322. return config.units;
  2323. },
  2324. set value(param) {
  2325. config.units = param;
  2326. updateSizes();
  2327. }
  2328. },
  2329. "names": {
  2330. name: "Show Names",
  2331. desc: "Display names over entities",
  2332. type: "toggle",
  2333. default: true,
  2334. get value() {
  2335. return checkBodyClass("toggle-entity-name");
  2336. },
  2337. set value(param) {
  2338. toggleBodyClass("toggle-entity-name", param);
  2339. }
  2340. },
  2341. "bottom-names": {
  2342. name: "Bottom Names",
  2343. desc: "Display names at the bottom",
  2344. type: "toggle",
  2345. default: false,
  2346. get value() {
  2347. return checkBodyClass("toggle-bottom-name");
  2348. },
  2349. set value(param) {
  2350. toggleBodyClass("toggle-bottom-name", param);
  2351. }
  2352. },
  2353. "top-names": {
  2354. name: "Show Arrows",
  2355. desc: "Point to entities that are much larger than the current view",
  2356. type: "toggle",
  2357. default: false,
  2358. get value() {
  2359. return checkBodyClass("toggle-top-name");
  2360. },
  2361. set value(param) {
  2362. toggleBodyClass("toggle-top-name", param);
  2363. }
  2364. },
  2365. "height-bars": {
  2366. name: "Height Bars",
  2367. desc: "Draw dashed lines to the top of each entity",
  2368. type: "toggle",
  2369. default: false,
  2370. get value() {
  2371. return checkBodyClass("toggle-height-bars");
  2372. },
  2373. set value(param) {
  2374. toggleBodyClass("toggle-height-bars", param);
  2375. }
  2376. },
  2377. "glowing-entities": {
  2378. name: "Glowing Edges",
  2379. desc: "Makes all entities glow",
  2380. type: "toggle",
  2381. default: false,
  2382. get value() {
  2383. return checkBodyClass("toggle-entity-glow");
  2384. },
  2385. set value(param) {
  2386. toggleBodyClass("toggle-entity-glow", param);
  2387. }
  2388. },
  2389. "background-brightness": {
  2390. name: "Background Brightness",
  2391. desc: "How bright the background is",
  2392. type: "select",
  2393. default: "medium",
  2394. options: [
  2395. "black",
  2396. "dark",
  2397. "medium",
  2398. "light",
  2399. ],
  2400. get value() {
  2401. return config.background;
  2402. },
  2403. set value(param) {
  2404. config.background = param;
  2405. drawScales();
  2406. }
  2407. },
  2408. "smoothing": {
  2409. name: "Smoothing",
  2410. desc: "Smooth out movements and size changes. Disable for better performance.",
  2411. type: "toggle",
  2412. default: true,
  2413. get value() {
  2414. return checkBodyClass("smoothing");
  2415. },
  2416. set value(param) {
  2417. toggleBodyClass("smoothing", param);
  2418. }
  2419. },
  2420. "auto-mass": {
  2421. name: "Estimate Mass",
  2422. desc: "Guess the mass of things that don't have one specified using the selected body type",
  2423. type: "select",
  2424. default: "off",
  2425. disabled: "off",
  2426. options: [
  2427. "off",
  2428. "human",
  2429. "quadruped at shoulder",
  2430. ],
  2431. get value() {
  2432. return config.autoMass
  2433. },
  2434. set value(param) {
  2435. config.autoMass = param
  2436. }
  2437. },
  2438. "auto-food-intake": {
  2439. name: "Estimate Food Intake",
  2440. desc: "Guess how much food creatures need, based on their mass -- 2000kcal per 150lbs",
  2441. type: "toggle",
  2442. default: false,
  2443. get value() {
  2444. return config.autoFoodIntake
  2445. },
  2446. set value(param) {
  2447. config.autoFoodIntake = param
  2448. }
  2449. },
  2450. "auto-caloric-value": {
  2451. name: "Estimate Caloric Value",
  2452. desc: "Guess how much food a creature is worth -- 860kcal per pound",
  2453. type: "toggle",
  2454. default: false,
  2455. get value() {
  2456. return config.autoCaloricValue
  2457. },
  2458. set value(param) {
  2459. config.autoCaloricValue = param
  2460. }
  2461. },
  2462. "auto-prey-capacity": {
  2463. name: "Estimate Prey Capacity",
  2464. desc: "Guess how much prey creatures can hold, based on their mass",
  2465. type: "select",
  2466. default: "none",
  2467. options: [
  2468. "none",
  2469. "realistic",
  2470. "same-size"
  2471. ],
  2472. get value() {
  2473. return config.autoPreyCapacity;
  2474. },
  2475. set value(param) {
  2476. config.autoPreyCapacity = param;
  2477. }
  2478. },
  2479. }
  2480. function getBoundingBox(entities, margin = 0.05) {
  2481. }
  2482. function prepareSettings(userSettings) {
  2483. const menubar = document.querySelector("#settings-menu");
  2484. Object.entries(settingsData).forEach(([id, entry]) => {
  2485. const holder = document.createElement("label");
  2486. holder.classList.add("settings-holder");
  2487. const input = document.createElement("input");
  2488. input.id = "setting-" + id;
  2489. const vertical = document.createElement("div");
  2490. vertical.classList.add("settings-vertical");
  2491. const name = document.createElement("label");
  2492. name.innerText = entry.name;
  2493. name.classList.add("settings-name");
  2494. name.setAttribute("for", input.id);
  2495. const desc = document.createElement("label");
  2496. desc.innerText = entry.desc;
  2497. desc.classList.add("settings-desc");
  2498. desc.setAttribute("for", input.id);
  2499. if (entry.type == "toggle") {
  2500. input.type = "checkbox";
  2501. input.checked = userSettings[id] === undefined ? entry.default : userSettings[id];
  2502. holder.setAttribute("for", input.id);
  2503. vertical.appendChild(name);
  2504. vertical.appendChild(desc);
  2505. holder.appendChild(vertical);
  2506. holder.appendChild(input);
  2507. menubar.appendChild(holder);
  2508. const update = () => {
  2509. if (input.checked) {
  2510. holder.classList.add("enabled");
  2511. holder.classList.remove("disabled");
  2512. } else {
  2513. holder.classList.remove("enabled");
  2514. holder.classList.add("disabled");
  2515. }
  2516. entry.value = input.checked;
  2517. }
  2518. update();
  2519. input.addEventListener("change", update);
  2520. } else if (entry.type == "select") {
  2521. // we don't use the input element we made!
  2522. const select = document.createElement("select");
  2523. select.id = "setting-" + id;
  2524. entry.options.forEach(choice => {
  2525. const option = document.createElement("option");
  2526. option.innerText = choice;
  2527. select.appendChild(option);
  2528. })
  2529. select.value = userSettings[id] === undefined ? entry.default : userSettings[id];
  2530. vertical.appendChild(name);
  2531. vertical.appendChild(desc);
  2532. holder.appendChild(vertical);
  2533. holder.appendChild(select);
  2534. menubar.appendChild(holder);
  2535. const update = () => {
  2536. entry.value = select.value;
  2537. if (entry.disabled !== undefined && entry.value !== entry.disabled) {
  2538. holder.classList.add("enabled");
  2539. holder.classList.remove("disabled");
  2540. } else {
  2541. holder.classList.remove("enabled");
  2542. holder.classList.add("disabled");
  2543. }
  2544. }
  2545. update();
  2546. select.addEventListener("change", update);
  2547. }
  2548. })
  2549. }
  2550. function prepareMenu() {
  2551. prepareSidebar();
  2552. updateSaveInfo();
  2553. if (checkHelpDate()) {
  2554. document.querySelector("#open-help").classList.add("highlighted");
  2555. }
  2556. }
  2557. function updateSaveInfo() {
  2558. const saves = getSaves();
  2559. const load = document.querySelector("#menu-load ~ select");
  2560. load.innerHTML = "";
  2561. saves.forEach(save => {
  2562. const option = document.createElement("option");
  2563. option.innerText = save;
  2564. option.value = save;
  2565. load.appendChild(option);
  2566. });
  2567. const del = document.querySelector("#menu-delete ~ select");
  2568. del.innerHTML = "";
  2569. saves.forEach(save => {
  2570. const option = document.createElement("option");
  2571. option.innerText = save;
  2572. option.value = save;
  2573. del.appendChild(option);
  2574. });
  2575. }
  2576. function getSaves() {
  2577. try {
  2578. const results = [];
  2579. Object.keys(localStorage).forEach(key => {
  2580. if (key.startsWith("macrovision-save-")) {
  2581. results.push(key.replace("macrovision-save-", ""));
  2582. }
  2583. })
  2584. return results;
  2585. } catch (err) {
  2586. alert("Something went wrong while loading (maybe you didn't have anything saved. Check the F12 console for the error.")
  2587. console.error(err);
  2588. return false;
  2589. }
  2590. }
  2591. function getUserSettings() {
  2592. try {
  2593. const settings = JSON.parse(localStorage.getItem("settings"));
  2594. return settings === null ? {} : settings;
  2595. } catch {
  2596. return {};
  2597. }
  2598. }
  2599. function exportUserSettings() {
  2600. const settings = {};
  2601. Object.entries(settingsData).forEach(([id, entry]) => {
  2602. settings[id] = entry.value;
  2603. });
  2604. return settings;
  2605. }
  2606. function setUserSettings(settings) {
  2607. try {
  2608. localStorage.setItem("settings", JSON.stringify(settings));
  2609. } catch {
  2610. // :(
  2611. }
  2612. }
  2613. const lastHelpChange = 1601955834693;
  2614. function checkHelpDate() {
  2615. // disabling this for now
  2616. return false;
  2617. try {
  2618. const old = localStorage.getItem("help-viewed");
  2619. if (old === null || old < lastHelpChange) {
  2620. return true;
  2621. }
  2622. return false;
  2623. } catch {
  2624. console.warn("Could not set the help-viewed date");
  2625. return false;
  2626. }
  2627. }
  2628. function setHelpDate() {
  2629. try {
  2630. localStorage.setItem("help-viewed", Date.now());
  2631. } catch {
  2632. console.warn("Could not set the help-viewed date");
  2633. }
  2634. }
  2635. function doYScroll() {
  2636. const worldHeight = config.height.toNumber("meters");
  2637. config.y += scrollDirection * worldHeight / 180;
  2638. updateSizes();
  2639. scrollDirection *= 1.05;
  2640. }
  2641. function doXScroll() {
  2642. const worldWidth = config.height.toNumber("meters") / canvasHeight * canvasWidth;
  2643. config.x += scrollDirection * worldWidth / 180 ;
  2644. updateSizes();
  2645. scrollDirection *= 1.05;
  2646. }
  2647. function doZoom() {
  2648. const oldHeight = config.height;
  2649. setWorldHeight(oldHeight, math.multiply(oldHeight, 1 + zoomDirection / 10));
  2650. zoomDirection *= 1.05;
  2651. }
  2652. function doSize() {
  2653. if (selected) {
  2654. const entity = entities[selected.dataset.key];
  2655. const oldHeight = entity.views[entity.view].height;
  2656. entity.views[entity.view].height = math.multiply(oldHeight, sizeDirection < 0 ? -1/sizeDirection : sizeDirection);
  2657. entity.dirty = true;
  2658. updateEntityOptions(entity, entity.view);
  2659. updateViewOptions(entity, entity.view);
  2660. updateSizes(true);
  2661. sizeDirection *= 1.01;
  2662. const ownHeight = entity.views[entity.view].height.toNumber("meters");
  2663. let extra = entity.views[entity.view].image.extra;
  2664. extra = extra === undefined ? 1 : extra;
  2665. const worldHeight = config.height.toNumber("meters");
  2666. if (ownHeight * extra > worldHeight) {
  2667. setWorldHeight(config.height, math.multiply(entity.views[entity.view].height, extra));
  2668. } else if (ownHeight * extra * 10 < worldHeight) {
  2669. setWorldHeight(config.height, math.multiply(entity.views[entity.view].height, extra * 10));
  2670. }
  2671. }
  2672. }
  2673. function selectNewUnit() {
  2674. const unitSelector = document.querySelector("#options-height-unit");
  2675. checkFitWorld();
  2676. const scaleInput = document.querySelector("#options-height-value");
  2677. const newVal = math.unit(scaleInput.value, unitSelector.dataset.oldUnit).toNumber(unitSelector.value);
  2678. setNumericInput(scaleInput, newVal);
  2679. updateWorldHeight();
  2680. unitSelector.dataset.oldUnit = unitSelector.value;
  2681. }
  2682. // given a world position, return the position relative to the entity at normal scale
  2683. function entityRelativePosition(pos, entityElement) {
  2684. const entity = entities[entityElement.dataset.key]
  2685. const x = parseFloat(entityElement.dataset.x)
  2686. const y = parseFloat(entityElement.dataset.y)
  2687. pos.x -= x
  2688. pos.y -= y
  2689. pos.x /= entity.scale
  2690. pos.y /= entity.scale
  2691. return pos
  2692. }
  2693. document.addEventListener("DOMContentLoaded", () => {
  2694. prepareMenu();
  2695. prepareEntities();
  2696. document.querySelector("#open-help").addEventListener("click", e => {
  2697. setHelpDate();
  2698. document.querySelector("#open-help").classList.remove("highlighted");
  2699. window.open("https://www.notion.so/Macrovision-5c7f9377424743358ddf6db5671f439e", "_blank");
  2700. });
  2701. document.querySelector("#copy-screenshot").addEventListener("click", e => {
  2702. copyScreenshot();
  2703. });
  2704. document.querySelector("#save-screenshot").addEventListener("click", e => {
  2705. saveScreenshot();
  2706. });
  2707. document.querySelector("#open-screenshot").addEventListener("click", e => {
  2708. openScreenshot();
  2709. });
  2710. document.querySelector("#toggle-menu").addEventListener("click", e => {
  2711. const popoutMenu = document.querySelector("#sidebar-menu");
  2712. if (popoutMenu.classList.contains("visible")) {
  2713. popoutMenu.classList.remove("visible");
  2714. } else {
  2715. document.querySelectorAll(".popout-menu").forEach(menu => menu.classList.remove("visible"));
  2716. const rect = e.target.getBoundingClientRect();
  2717. popoutMenu.classList.add("visible");
  2718. popoutMenu.style.left = rect.x + rect.width + 10 + "px";
  2719. popoutMenu.style.top = rect.y + rect.height + 10 + "px";
  2720. let menuWidth = popoutMenu.getBoundingClientRect().width;
  2721. let screenWidth = window.innerWidth;
  2722. if (menuWidth * 1.5 > screenWidth) {
  2723. popoutMenu.style.left = 25 + "px";
  2724. }
  2725. }
  2726. e.stopPropagation();
  2727. });
  2728. document.querySelector("#sidebar-menu").addEventListener("click", e => {
  2729. e.stopPropagation();
  2730. });
  2731. document.addEventListener("click", e => {
  2732. document.querySelector("#sidebar-menu").classList.remove("visible");
  2733. });
  2734. document.querySelector("#toggle-settings").addEventListener("click", e => {
  2735. const popoutMenu = document.querySelector("#settings-menu");
  2736. if (popoutMenu.classList.contains("visible")) {
  2737. popoutMenu.classList.remove("visible");
  2738. } else {
  2739. document.querySelectorAll(".popout-menu").forEach(menu => menu.classList.remove("visible"));
  2740. const rect = e.target.getBoundingClientRect();
  2741. popoutMenu.classList.add("visible");
  2742. popoutMenu.style.left = rect.x + rect.width + 10 + "px";
  2743. popoutMenu.style.top = rect.y + rect.height + 10 + "px";
  2744. let menuWidth = popoutMenu.getBoundingClientRect().width;
  2745. let screenWidth = window.innerWidth;
  2746. if (menuWidth * 1.5 > screenWidth) {
  2747. popoutMenu.style.left = 25 + "px";
  2748. }
  2749. }
  2750. e.stopPropagation();
  2751. });
  2752. document.querySelector("#settings-menu").addEventListener("click", e => {
  2753. e.stopPropagation();
  2754. });
  2755. document.addEventListener("click", e => {
  2756. document.querySelector("#settings-menu").classList.remove("visible");
  2757. });
  2758. window.addEventListener("unload", () => {
  2759. saveScene("autosave");
  2760. setUserSettings(exportUserSettings());
  2761. });
  2762. document.querySelector("#options-selected-entity").addEventListener("input", e => {
  2763. if (e.target.value == "None") {
  2764. deselect()
  2765. } else {
  2766. select(document.querySelector("#entity-" + e.target.value));
  2767. }
  2768. });
  2769. document.querySelector("#menu-toggle-sidebar").addEventListener("click", e => {
  2770. const sidebar = document.querySelector("#options");
  2771. if (sidebar.classList.contains("hidden")) {
  2772. sidebar.classList.remove("hidden");
  2773. e.target.classList.remove("rotate-forward");
  2774. e.target.classList.add("rotate-backward");
  2775. } else {
  2776. sidebar.classList.add("hidden");
  2777. e.target.classList.add("rotate-forward");
  2778. e.target.classList.remove("rotate-backward");
  2779. }
  2780. handleResize();
  2781. });
  2782. document.querySelector("#menu-fullscreen").addEventListener("click", toggleFullScreen);
  2783. document.querySelector("#options-order-forward").addEventListener("click", e => {
  2784. if (selected) {
  2785. entities[selected.dataset.key].priority += 1;
  2786. }
  2787. document.querySelector("#options-order-display").innerText = entities[selected.dataset.key].priority;
  2788. updateSizes();
  2789. });
  2790. document.querySelector("#options-order-back").addEventListener("click", e => {
  2791. if (selected) {
  2792. entities[selected.dataset.key].priority -= 1;
  2793. }
  2794. document.querySelector("#options-order-display").innerText = entities[selected.dataset.key].priority;
  2795. updateSizes();
  2796. });
  2797. document.querySelector("#options-brightness-up").addEventListener("click", e => {
  2798. if (selected) {
  2799. entities[selected.dataset.key].brightness += 1;
  2800. }
  2801. document.querySelector("#options-brightness-display").innerText = entities[selected.dataset.key].brightness;
  2802. updateSizes();
  2803. });
  2804. document.querySelector("#options-brightness-down").addEventListener("click", e => {
  2805. if (selected) {
  2806. entities[selected.dataset.key].brightness -= 1;
  2807. }
  2808. document.querySelector("#options-brightness-display").innerText = entities[selected.dataset.key].brightness;
  2809. updateSizes();
  2810. });
  2811. document.querySelector("#options-rotate-left").addEventListener("click", e => {
  2812. if (selected) {
  2813. entities[selected.dataset.key].rotation -= Math.PI/4;
  2814. }
  2815. selected.querySelector("img").style.setProperty("--rotation", (entities[selected.dataset.key].rotation * 180 / Math.PI) + "deg")
  2816. updateSizes();
  2817. });
  2818. document.querySelector("#options-rotate-right").addEventListener("click", e => {
  2819. if (selected) {
  2820. entities[selected.dataset.key].rotation += Math.PI/4;
  2821. }
  2822. selected.querySelector("img").style.setProperty("--rotation", (entities[selected.dataset.key].rotation * 180 / Math.PI) + "deg")
  2823. updateSizes();
  2824. });
  2825. document.querySelector("#options-flip").addEventListener("click", e => {
  2826. if (selected) {
  2827. selected.querySelector(".entity-image").classList.toggle("flipped");
  2828. }
  2829. document.querySelector("#options-brightness-display").innerText = entities[selected.dataset.key].brightness;
  2830. updateSizes();
  2831. });
  2832. const sceneChoices = document.querySelector("#scene-choices");
  2833. Object.entries(scenes).forEach(([id, scene]) => {
  2834. const option = document.createElement("option");
  2835. option.innerText = id;
  2836. option.value = id;
  2837. sceneChoices.appendChild(option);
  2838. });
  2839. document.querySelector("#load-scene").addEventListener("click", e => {
  2840. const chosen = sceneChoices.value;
  2841. removeAllEntities();
  2842. scenes[chosen]();
  2843. });
  2844. entityX = document.querySelector("#entities").getBoundingClientRect().x;
  2845. canvasWidth = document.querySelector("#display").clientWidth - 100;
  2846. canvasHeight = document.querySelector("#display").clientHeight - 50;
  2847. document.querySelector("#options-height-value").addEventListener("change", e => {
  2848. updateWorldHeight();
  2849. })
  2850. document.querySelector("#options-height-value").addEventListener("keydown", e => {
  2851. e.stopPropagation();
  2852. })
  2853. const unitSelector = document.querySelector("#options-height-unit");
  2854. Object.entries(unitChoices.length).forEach(([group, entries]) => {
  2855. const optGroup = document.createElement("optgroup");
  2856. optGroup.label = group;
  2857. unitSelector.appendChild(optGroup);
  2858. entries.forEach(entry => {
  2859. const option = document.createElement("option");
  2860. option.innerText = entry;
  2861. // we haven't loaded user settings yet, so we can't choose the unit just yet
  2862. unitSelector.appendChild(option);
  2863. })
  2864. });
  2865. unitSelector.addEventListener("input", selectNewUnit);
  2866. param = window.location.hash;
  2867. // we now use the fragment for links, but we should still support old stuff:
  2868. if (param.length > 0) {
  2869. param = param.substring(1);
  2870. } else {
  2871. param = new URL(window.location.href).searchParams.get("scene");
  2872. }
  2873. document.querySelector("#world").addEventListener("mousedown", e => {
  2874. // only middle mouse clicks
  2875. if (e.which == 2) {
  2876. panning = true;
  2877. panOffsetX = e.clientX;
  2878. panOffsetY = e.clientY;
  2879. Object.keys(entities).forEach(key => {
  2880. document.querySelector("#entity-" + key).classList.add("no-transition");
  2881. });
  2882. }
  2883. });
  2884. document.addEventListener("mouseup", e => {
  2885. if (e.which == 2) {
  2886. panning = false;
  2887. Object.keys(entities).forEach(key => {
  2888. document.querySelector("#entity-" + key).classList.remove("no-transition");
  2889. });
  2890. }
  2891. });
  2892. document.querySelector("#world").addEventListener("touchstart", e => {
  2893. if (!rulerMode) {
  2894. panning = true;
  2895. panOffsetX = e.touches[0].clientX;
  2896. panOffsetY = e.touches[0].clientY;
  2897. e.preventDefault();
  2898. Object.keys(entities).forEach(key => {
  2899. document.querySelector("#entity-" + key).classList.add("no-transition");
  2900. });
  2901. }
  2902. });
  2903. document.querySelector("#world").addEventListener("touchend", e => {
  2904. panning = false;
  2905. Object.keys(entities).forEach(key => {
  2906. document.querySelector("#entity-" + key).classList.remove("no-transition");
  2907. });
  2908. });
  2909. document.querySelector("#world").addEventListener("mousedown", e => {
  2910. // only left mouse clicks
  2911. if (e.which == 1 && rulerMode) {
  2912. let entX = document.querySelector("#entities").getBoundingClientRect().x;
  2913. let entY = document.querySelector("#entities").getBoundingClientRect().y;
  2914. let pos = pix2pos({ x: e.clientX - entX, y: e.clientY - entY });
  2915. if (config.rulersStick && selected) {
  2916. pos = entityRelativePosition(pos, selected)
  2917. }
  2918. currentRuler = { x0: pos.x, y0: pos.y, x1: pos.y, y1: pos.y, entityKey: null };
  2919. if (config.rulersStick && selected) {
  2920. currentRuler.entityKey = selected.dataset.key
  2921. }
  2922. }
  2923. });
  2924. document.querySelector("#world").addEventListener("mouseup", e => {
  2925. // only left mouse clicks
  2926. if (e.which == 1 && currentRuler) {
  2927. rulers.push(currentRuler);
  2928. currentRuler = null;
  2929. rulerMode = false;
  2930. }
  2931. });
  2932. document.querySelector("#world").addEventListener("touchstart", e => {
  2933. if (rulerMode) {
  2934. let entX = document.querySelector("#entities").getBoundingClientRect().x;
  2935. let entY = document.querySelector("#entities").getBoundingClientRect().y;
  2936. let pos = pix2pos({ x: e.touches[0].clientX - entX, y: e.touches[0].clientY - entY });
  2937. if (config.rulersStick && selected) {
  2938. pos = entityRelativePosition(pos, selected)
  2939. }
  2940. currentRuler = { x0: pos.x, y0: pos.y, x1: pos.y, y1: pos.y, entityKey: null };
  2941. if (config.rulersStick && selected) {
  2942. currentRuler.entityKey = selected.dataset.key
  2943. }
  2944. }
  2945. });
  2946. document.querySelector("#world").addEventListener("touchend", e => {
  2947. if (currentRuler) {
  2948. rulers.push(currentRuler);
  2949. currentRuler = null;
  2950. rulerMode = false;
  2951. }
  2952. });
  2953. document.querySelector("body").appendChild(testCtx.canvas);
  2954. world.addEventListener("mousedown", e => deselect(e));
  2955. world.addEventListener("touchstart", e => deselect({
  2956. which: 1,
  2957. }));
  2958. document.querySelector("#entities").addEventListener("mousedown", deselect);
  2959. document.querySelector("#display").addEventListener("mousedown", deselect);
  2960. document.addEventListener("mouseup", e => clickUp(e));
  2961. document.addEventListener("touchend", e => {
  2962. const fakeEvent = {
  2963. target: e.target,
  2964. clientX: e.changedTouches[0].clientX,
  2965. clientY: e.changedTouches[0].clientY,
  2966. which: 1
  2967. };
  2968. clickUp(fakeEvent);
  2969. });
  2970. const formList = document.querySelector("#entity-form");
  2971. formList.addEventListener("input", e => {
  2972. const entity = entities[selected.dataset.key];
  2973. entity.form = e.target.value;
  2974. entity.view = entity.formViews[entity.form];
  2975. if (Object.keys(entity.forms).length > 0)
  2976. entity.views[entity.view].height = entity.formSizes[entity.form].height;
  2977. preloadViews(entity);
  2978. configViewList(entity, entity.view);
  2979. const image = entity.views[entity.view].image;
  2980. selected.querySelector(".entity-image").src = image.source;
  2981. configViewOptions(entity, entity.view);
  2982. displayAttribution(image.source);
  2983. if (image.bottom !== undefined) {
  2984. selected.querySelector(".entity-image").style.setProperty("--offset", ((-1 + image.bottom) * 100) + "%")
  2985. } else {
  2986. selected.querySelector(".entity-image").style.setProperty("--offset", ((-1) * 100) + "%")
  2987. }
  2988. if (config.autoFitSize) {
  2989. let targets = {};
  2990. targets[selected.dataset.key] = entities[selected.dataset.key];
  2991. fitEntities(targets);
  2992. }
  2993. configSizeList(entity);
  2994. updateSizes();
  2995. updateEntityOptions(entities[selected.dataset.key], e.target.value);
  2996. updateViewOptions(entities[selected.dataset.key], entity.view);
  2997. });
  2998. const viewList = document.querySelector("#entity-view");
  2999. document.querySelector("#entity-view").addEventListener("input", e => {
  3000. const entity = entities[selected.dataset.key];
  3001. entity.view = e.target.value;
  3002. preloadViews(entity);
  3003. const image = entities[selected.dataset.key].views[e.target.value].image;
  3004. selected.querySelector(".entity-image").src = image.source;
  3005. configViewOptions(entity, entity.view);
  3006. displayAttribution(image.source);
  3007. if (image.bottom !== undefined) {
  3008. selected.querySelector(".entity-image").style.setProperty("--offset", ((-1 + image.bottom) * 100) + "%")
  3009. } else {
  3010. selected.querySelector(".entity-image").style.setProperty("--offset", ((-1) * 100) + "%")
  3011. }
  3012. updateSizes();
  3013. updateEntityOptions(entities[selected.dataset.key], e.target.value);
  3014. updateViewOptions(entities[selected.dataset.key], e.target.value);
  3015. });
  3016. document.querySelector("#entity-view").addEventListener("input", e => {
  3017. if (viewList.options[viewList.selectedIndex].classList.contains("nsfw")) {
  3018. viewList.classList.add("nsfw");
  3019. } else {
  3020. viewList.classList.remove("nsfw");
  3021. }
  3022. })
  3023. clearViewList();
  3024. document.querySelector("#menu-clear").addEventListener("click", e => {
  3025. removeAllEntities();
  3026. });
  3027. document.querySelector("#delete-entity").disabled = true;
  3028. document.querySelector("#delete-entity").addEventListener("click", e => {
  3029. if (selected) {
  3030. removeEntity(selected);
  3031. selected = null;
  3032. }
  3033. });
  3034. document.querySelector("#menu-order-height").addEventListener("click", e => {
  3035. const order = Object.keys(entities).sort((a, b) => {
  3036. const entA = entities[a];
  3037. const entB = entities[b];
  3038. const viewA = entA.view;
  3039. const viewB = entB.view;
  3040. const heightA = entA.views[viewA].height.to("meter").value;
  3041. const heightB = entB.views[viewB].height.to("meter").value;
  3042. return heightA - heightB;
  3043. });
  3044. arrangeEntities(order);
  3045. });
  3046. // TODO: write some generic logic for this lol
  3047. document.querySelector("#scroll-left").addEventListener("mousedown", e => {
  3048. scrollDirection = -1;
  3049. clearInterval(scrollHandle);
  3050. scrollHandle = setInterval(doXScroll, 1000 / 20);
  3051. e.stopPropagation();
  3052. });
  3053. document.querySelector("#scroll-right").addEventListener("mousedown", e => {
  3054. scrollDirection = 1;
  3055. clearInterval(scrollHandle);
  3056. scrollHandle = setInterval(doXScroll, 1000 / 20);
  3057. e.stopPropagation();
  3058. });
  3059. document.querySelector("#scroll-left").addEventListener("touchstart", e => {
  3060. scrollDirection = -1;
  3061. clearInterval(scrollHandle);
  3062. scrollHandle = setInterval(doXScroll, 1000 / 20);
  3063. e.stopPropagation();
  3064. });
  3065. document.querySelector("#scroll-right").addEventListener("touchstart", e => {
  3066. scrollDirection = 1;
  3067. clearInterval(scrollHandle);
  3068. scrollHandle = setInterval(doXScroll, 1000 / 20);
  3069. e.stopPropagation();
  3070. });
  3071. document.querySelector("#scroll-up").addEventListener("mousedown", e => {
  3072. scrollDirection = 1;
  3073. clearInterval(scrollHandle);
  3074. scrollHandle = setInterval(doYScroll, 1000 / 20);
  3075. e.stopPropagation();
  3076. });
  3077. document.querySelector("#scroll-down").addEventListener("mousedown", e => {
  3078. scrollDirection = -1;
  3079. clearInterval(scrollHandle);
  3080. scrollHandle = setInterval(doYScroll, 1000 / 20);
  3081. e.stopPropagation();
  3082. });
  3083. document.querySelector("#scroll-up").addEventListener("touchstart", e => {
  3084. scrollDirection = 1;
  3085. clearInterval(scrollHandle);
  3086. scrollHandle = setInterval(doYScroll, 1000 / 20);
  3087. e.stopPropagation();
  3088. });
  3089. document.querySelector("#scroll-down").addEventListener("touchstart", e => {
  3090. scrollDirection = -1;
  3091. clearInterval(scrollHandle);
  3092. scrollHandle = setInterval(doYScroll, 1000 / 20);
  3093. e.stopPropagation();
  3094. });
  3095. document.addEventListener("mouseup", e => {
  3096. clearInterval(scrollHandle);
  3097. scrollHandle = null;
  3098. });
  3099. document.addEventListener("touchend", e => {
  3100. clearInterval(scrollHandle);
  3101. scrollHandle = null;
  3102. });
  3103. document.querySelector("#zoom-in").addEventListener("mousedown", e => {
  3104. zoomDirection = -1;
  3105. clearInterval(zoomHandle);
  3106. zoomHandle = setInterval(doZoom, 1000 / 20);
  3107. e.stopPropagation();
  3108. });
  3109. document.querySelector("#zoom-out").addEventListener("mousedown", e => {
  3110. zoomDirection = 1;
  3111. clearInterval(zoomHandle);
  3112. zoomHandle = setInterval(doZoom, 1000 / 20);
  3113. e.stopPropagation();
  3114. });
  3115. document.querySelector("#zoom-in").addEventListener("touchstart", e => {
  3116. zoomDirection = -1;
  3117. clearInterval(zoomHandle);
  3118. zoomHandle = setInterval(doZoom, 1000 / 20);
  3119. e.stopPropagation();
  3120. });
  3121. document.querySelector("#zoom-out").addEventListener("touchstart", e => {
  3122. zoomDirection = 1;
  3123. clearInterval(zoomHandle);
  3124. zoomHandle = setInterval(doZoom, 1000 / 20);
  3125. e.stopPropagation();
  3126. });
  3127. document.addEventListener("mouseup", e => {
  3128. clearInterval(zoomHandle);
  3129. zoomHandle = null;
  3130. });
  3131. document.addEventListener("touchend", e => {
  3132. clearInterval(zoomHandle);
  3133. zoomHandle = null;
  3134. });
  3135. document.querySelector("#shrink").addEventListener("mousedown", e => {
  3136. sizeDirection = -1;
  3137. clearInterval(sizeHandle);
  3138. sizeHandle = setInterval(doSize, 1000 / 20);
  3139. e.stopPropagation();
  3140. });
  3141. document.querySelector("#grow").addEventListener("mousedown", e => {
  3142. sizeDirection = 1;
  3143. clearInterval(sizeHandle);
  3144. sizeHandle = setInterval(doSize, 1000 / 20);
  3145. e.stopPropagation();
  3146. });
  3147. document.querySelector("#shrink").addEventListener("touchstart", e => {
  3148. sizeDirection = -1;
  3149. clearInterval(sizeHandle);
  3150. sizeHandle = setInterval(doSize, 1000 / 20);
  3151. e.stopPropagation();
  3152. });
  3153. document.querySelector("#grow").addEventListener("touchstart", e => {
  3154. sizeDirection = 1;
  3155. clearInterval(sizeHandle);
  3156. sizeHandle = setInterval(doSize, 1000 / 20);
  3157. e.stopPropagation();
  3158. });
  3159. document.addEventListener("mouseup", e => {
  3160. clearInterval(sizeHandle);
  3161. sizeHandle = null;
  3162. });
  3163. document.addEventListener("touchend", e => {
  3164. clearInterval(sizeHandle);
  3165. sizeHandle = null;
  3166. });
  3167. document.querySelector("#ruler").addEventListener("click", e => {
  3168. rulerMode = !rulerMode;
  3169. if (rulerMode) {
  3170. toast("Ready to draw a ruler mark");
  3171. } else {
  3172. toast("Cancelled ruler mode");
  3173. }
  3174. });
  3175. document.querySelector("#ruler").addEventListener("mousedown", e => {
  3176. e.stopPropagation();
  3177. });
  3178. document.querySelector("#ruler").addEventListener("touchstart", e => {
  3179. e.stopPropagation();
  3180. });
  3181. document.querySelector("#fit").addEventListener("click", e => {
  3182. if (selected) {
  3183. let targets = {};
  3184. targets[selected.dataset.key] = entities[selected.dataset.key];
  3185. fitEntities(targets);
  3186. }
  3187. });
  3188. document.querySelector("#fit").addEventListener("mousedown", e => {
  3189. e.stopPropagation();
  3190. });
  3191. document.querySelector("#fit").addEventListener("touchstart", e => {
  3192. e.stopPropagation();
  3193. });
  3194. document.querySelector("#options-world-fit").addEventListener("click", () => fitWorld(true));
  3195. document.querySelector("#options-reset-pos-x").addEventListener("click", () => { config.x = 0; updateSizes(); });
  3196. document.querySelector("#options-reset-pos-y").addEventListener("click", () => { config.y = 0; updateSizes(); });
  3197. document.addEventListener("keydown", e => {
  3198. if (e.key == "Delete") {
  3199. if (selected) {
  3200. removeEntity(selected);
  3201. selected = null;
  3202. }
  3203. }
  3204. })
  3205. document.addEventListener("keydown", e => {
  3206. if (e.key == "Shift") {
  3207. shiftHeld = true;
  3208. e.preventDefault();
  3209. } else if (e.key == "Alt") {
  3210. altHeld = true;
  3211. movingInBounds = false; // don't snap the object back in bounds when we let go
  3212. e.preventDefault();
  3213. }
  3214. });
  3215. document.addEventListener("keyup", e => {
  3216. if (e.key == "Shift") {
  3217. shiftHeld = false;
  3218. e.preventDefault();
  3219. } else if (e.key == "Alt") {
  3220. altHeld = false;
  3221. e.preventDefault();
  3222. }
  3223. });
  3224. window.addEventListener("resize", handleResize);
  3225. // TODO: further investigate why the tool initially starts out with wrong
  3226. // values under certain circumstances (seems to be narrow aspect ratios -
  3227. // maybe the menu bar is animating when it shouldn't)
  3228. setTimeout(handleResize, 250);
  3229. setTimeout(handleResize, 500);
  3230. setTimeout(handleResize, 750);
  3231. setTimeout(handleResize, 1000);
  3232. document.querySelector("#menu-permalink").addEventListener("click", e => {
  3233. linkScene();
  3234. });
  3235. document.querySelector("#menu-export").addEventListener("click", e => {
  3236. copyScene();
  3237. });
  3238. document.querySelector("#menu-import").addEventListener("click", e => {
  3239. pasteScene();
  3240. });
  3241. document.querySelector("#menu-save").addEventListener("click", e => {
  3242. const name = document.querySelector("#menu-save ~ input").value;
  3243. if (/\S/.test(name)) {
  3244. saveScene(name);
  3245. }
  3246. updateSaveInfo();
  3247. });
  3248. document.querySelector("#menu-load").addEventListener("click", e => {
  3249. const name = document.querySelector("#menu-load ~ select").value;
  3250. if (/\S/.test(name)) {
  3251. loadScene(name);
  3252. }
  3253. });
  3254. document.querySelector("#menu-delete").addEventListener("click", e => {
  3255. const name = document.querySelector("#menu-delete ~ select").value;
  3256. if (/\S/.test(name)) {
  3257. deleteScene(name);
  3258. }
  3259. });
  3260. document.querySelector("#menu-load-autosave").addEventListener("click", e => {
  3261. loadScene("autosave");
  3262. });
  3263. document.querySelector("#menu-add-image").addEventListener("click", e => {
  3264. document.querySelector("#file-upload-picker").click();
  3265. });
  3266. document.querySelector("#file-upload-picker").addEventListener("change", e => {
  3267. if (e.target.files.length > 0) {
  3268. for (let i=0; i<e.target.files.length; i++) {
  3269. customEntityFromFile(e.target.files[i]);
  3270. }
  3271. }
  3272. })
  3273. document.querySelector("#menu-clear-rulers").addEventListener("click", e => {
  3274. rulers = [];
  3275. drawRulers();
  3276. });
  3277. document.addEventListener("paste", e => {
  3278. let index = 0;
  3279. let item = null;
  3280. let found = false;
  3281. for (; index < e.clipboardData.items.length; index++) {
  3282. item = e.clipboardData.items[index];
  3283. if (item.type == "image/png") {
  3284. found = true;
  3285. break;
  3286. }
  3287. }
  3288. if (!found) {
  3289. return;
  3290. }
  3291. let url = null;
  3292. const file = item.getAsFile();
  3293. customEntityFromFile(file);
  3294. });
  3295. document.querySelector("#world").addEventListener("dragover", e => {
  3296. e.preventDefault();
  3297. })
  3298. document.querySelector("#world").addEventListener("drop", e => {
  3299. e.preventDefault();
  3300. if (e.dataTransfer.files.length > 0) {
  3301. let entX = document.querySelector("#entities").getBoundingClientRect().x;
  3302. let entY = document.querySelector("#entities").getBoundingClientRect().y;
  3303. let coords = pix2pos({x: e.clientX-entX, y: e.clientY-entY});
  3304. customEntityFromFile(e.dataTransfer.files[0], coords.x, coords.y);
  3305. }
  3306. })
  3307. clearEntityOptions();
  3308. clearViewOptions();
  3309. clearAttribution();
  3310. // we do this last because configuring settings can cause things
  3311. // to happen (e.g. auto-fit)
  3312. prepareSettings(getUserSettings());
  3313. // now that we have this loaded, we can set it
  3314. unitSelector.dataset.oldUnit = defaultUnits.length[config.units];
  3315. document.querySelector("#options-height-unit").value = defaultUnits.length[config.units];
  3316. // ...and then update the world height by setting off an input event
  3317. document.querySelector("#options-height-unit").dispatchEvent(new Event('input', {
  3318. }));
  3319. if (param === null) {
  3320. scenes["Empty"]();
  3321. }
  3322. else {
  3323. try {
  3324. const data = JSON.parse(b64DecodeUnicode(param));
  3325. if (data.entities === undefined) {
  3326. return;
  3327. }
  3328. if (data.world === undefined) {
  3329. return;
  3330. }
  3331. importScene(data);
  3332. } catch (err) {
  3333. console.error(err);
  3334. scenes["Empty"]();
  3335. // probably wasn't valid data
  3336. }
  3337. }
  3338. document.querySelector("#world").addEventListener("wheel", e => {
  3339. if (shiftHeld) {
  3340. if (selected) {
  3341. const dir = e.deltaY > 0 ? 10 / 11 : 11 / 10;
  3342. const entity = entities[selected.dataset.key];
  3343. entity.views[entity.view].height = math.multiply(entity.views[entity.view].height, dir);
  3344. entity.dirty = true;
  3345. updateEntityOptions(entity, entity.view);
  3346. updateViewOptions(entity, entity.view);
  3347. updateSizes(true);
  3348. } else {
  3349. const worldWidth = config.height.toNumber("meters") / canvasHeight * canvasWidth;
  3350. config.x += (e.deltaY > 0 ? 1 : -1) * worldWidth / 20 ;
  3351. updateSizes();
  3352. updateSizes();
  3353. }
  3354. } else {
  3355. if (config.autoFit) {
  3356. toastRateLimit("Zoom is locked! Check Settings to disable.", "zoom-lock", 1000);
  3357. } else {
  3358. const dir = e.deltaY < 0 ? 10 / 11 : 11 / 10;
  3359. const change = config.height.toNumber("meters") - math.multiply(config.height, dir).toNumber("meters");
  3360. if (!config.lockYAxis) {
  3361. config.y += change / 2;
  3362. }
  3363. setWorldHeight(config.height, math.multiply(config.height, dir));
  3364. updateWorldOptions();
  3365. }
  3366. }
  3367. checkFitWorld();
  3368. })
  3369. updateWorldHeight();
  3370. document.querySelector("#search-box").addEventListener("change", e => doSearch(e.target.value));
  3371. });
  3372. let searchText = "";
  3373. function doSearch(value) {
  3374. searchText = value;
  3375. updateFilter();
  3376. }
  3377. function customEntityFromFile(file, x=0.5, y=0.5) {
  3378. file.arrayBuffer().then(buf => {
  3379. arr = new Uint8Array(buf);
  3380. blob = new Blob([arr], {type: file.type });
  3381. url = window.URL.createObjectURL(blob)
  3382. makeCustomEntity(url, x, y);
  3383. });
  3384. }
  3385. function makeCustomEntity(url, x=0.5, y=0.5) {
  3386. const maker = createEntityMaker(
  3387. {
  3388. name: "Custom Entity"
  3389. },
  3390. {
  3391. custom: {
  3392. attributes: {
  3393. height: {
  3394. name: "Height",
  3395. power: 1,
  3396. type: "length",
  3397. base: math.unit(6, "feet")
  3398. }
  3399. },
  3400. image: {
  3401. source: url
  3402. },
  3403. name: "Image",
  3404. info: {},
  3405. rename: false
  3406. }
  3407. },
  3408. []
  3409. );
  3410. const entity = maker.constructor();
  3411. entity.scale = config.height.toNumber("feet") / 20;
  3412. entity.ephemeral = true;
  3413. displayEntity(entity, "custom", x, y, true, true);
  3414. }
  3415. const filterDefs = {
  3416. none: {
  3417. id: "none",
  3418. name: "No Filter",
  3419. extract: maker => [],
  3420. render: name => name,
  3421. sort: (tag1, tag2) => tag1[1].localeCompare(tag2[1])
  3422. },
  3423. author: {
  3424. id: "author",
  3425. name: "Authors",
  3426. extract: maker => maker.authors ? maker.authors : [],
  3427. render: author => attributionData.people[author].name,
  3428. sort: (tag1, tag2) => tag1[1].localeCompare(tag2[1])
  3429. },
  3430. owner: {
  3431. id: "owner",
  3432. name: "Owners",
  3433. extract: maker => maker.owners ? maker.owners : [],
  3434. render: owner => attributionData.people[owner].name,
  3435. sort: (tag1, tag2) => tag1[1].localeCompare(tag2[1])
  3436. },
  3437. species: {
  3438. id: "species",
  3439. name: "Species",
  3440. extract: maker => maker.info && maker.info.species ? getSpeciesInfo(maker.info.species) : [],
  3441. render: species => speciesData[species].name,
  3442. sort: (tag1, tag2) => tag1[1].localeCompare(tag2[1])
  3443. },
  3444. tags: {
  3445. id: "tags",
  3446. name: "Tags",
  3447. extract: maker => maker.info && maker.info.tags ? maker.info.tags : [],
  3448. render: tag => tagDefs[tag],
  3449. sort: (tag1, tag2) => tag1[1].localeCompare(tag2[1])
  3450. },
  3451. size: {
  3452. id: "size",
  3453. name: "Normal Size",
  3454. extract: maker => maker.sizes && maker.sizes.length > 0 ? Array.from(maker.sizes.reduce((result, size) => {
  3455. if (result && !size.default) {
  3456. return result;
  3457. }
  3458. let meters = size.height.toNumber("meters");
  3459. if (meters < 1e-1) {
  3460. return ["micro"];
  3461. } else if (meters < 1e1) {
  3462. return ["moderate"];
  3463. } else {
  3464. return ["macro"];
  3465. }
  3466. }, null)) : [],
  3467. render: tag => { return {
  3468. "micro": "Micro",
  3469. "moderate": "Moderate",
  3470. "macro": "Macro"
  3471. }[tag]},
  3472. sort: (tag1, tag2) => {
  3473. const order = {
  3474. "micro": 0,
  3475. "moderate": 1,
  3476. "macro": 2
  3477. };
  3478. return order[tag1[0]] - order[tag2[0]];
  3479. }
  3480. },
  3481. allSizes: {
  3482. id: "allSizes",
  3483. name: "Possible Size",
  3484. extract: maker => maker.sizes ? Array.from(maker.sizes.reduce((set, size) => {
  3485. const height = size.height;
  3486. let result = Object.entries(sizeCategories).reduce((result, [name, value]) => {
  3487. if (result) {
  3488. return result;
  3489. } else {
  3490. if (math.compare(height, value) <= 0) {
  3491. return name;
  3492. }
  3493. }
  3494. }, null);
  3495. set.add(result ? result : "infinite");
  3496. return set;
  3497. }, new Set())) : [],
  3498. render: tag => tag[0].toUpperCase() + tag.slice(1),
  3499. sort: (tag1, tag2) => {
  3500. const order = [
  3501. "atomic", "microscopic", "tiny", "small", "moderate", "large", "macro", "megamacro", "planetary", "stellar",
  3502. "galactic", "universal", "omniversal", "infinite"
  3503. ]
  3504. return order.indexOf(tag1[0]) - order.indexOf(tag2[0]);
  3505. }
  3506. }
  3507. }
  3508. const sizeCategories = {
  3509. "atomic": math.unit(100, "angstroms"),
  3510. "microscopic": math.unit(100, "micrometers"),
  3511. "tiny": math.unit(100, "millimeters"),
  3512. "small": math.unit(1, "meter"),
  3513. "moderate": math.unit(3, "meters"),
  3514. "large": math.unit(10, "meters"),
  3515. "macro": math.unit(300, "meters"),
  3516. "megamacro": math.unit(1000, "kilometers"),
  3517. "planetary": math.unit(10, "earths"),
  3518. "stellar": math.unit(10, "solarradii"),
  3519. "galactic": math.unit(10, "galaxies"),
  3520. "universal": math.unit(10, "universes"),
  3521. "omniversal": math.unit(10, "multiverses")
  3522. };
  3523. function prepareEntities() {
  3524. availableEntities["buildings"] = makeBuildings();
  3525. availableEntities["characters"] = makeCharacters();
  3526. availableEntities["clothing"] = makeClothing();
  3527. availableEntities["creatures"] = makeCreatures();
  3528. availableEntities["dildos"] = makeDildos();
  3529. availableEntities["fiction"] = makeFiction();
  3530. availableEntities["food"] = makeFood();
  3531. availableEntities["furniture"] = makeFurniture();
  3532. availableEntities["landmarks"] = makeLandmarks();
  3533. availableEntities["naturals"] = makeNaturals();
  3534. availableEntities["objects"] = makeObjects();
  3535. availableEntities["pokemon"] = makePokemon();
  3536. availableEntities["real-buildings"] = makeRealBuildings();
  3537. availableEntities["real-terrain"] = makeRealTerrains();
  3538. availableEntities["species"] = makeSpecies();
  3539. availableEntities["vehicles"] = makeVehicles();
  3540. availableEntities["species"].forEach(x => {
  3541. if (x.name == "Human") {
  3542. availableEntities["food"].push(x);
  3543. }
  3544. })
  3545. availableEntities["characters"].sort((x, y) => {
  3546. return x.name.localeCompare(y.name)
  3547. });
  3548. availableEntities["species"].sort((x, y) => {
  3549. return x.name.localeCompare(y.name)
  3550. });
  3551. availableEntities["objects"].sort((x, y) => {
  3552. return x.name.localeCompare(y.name)
  3553. });
  3554. const holder = document.querySelector("#spawners");
  3555. const filterHolder = document.querySelector("#filters");
  3556. const categorySelect = document.createElement("select");
  3557. categorySelect.id = "category-picker";
  3558. const filterSelect = document.createElement("select");
  3559. filterSelect.id = "filter-picker";
  3560. holder.appendChild(categorySelect);
  3561. filterHolder.appendChild(filterSelect);
  3562. const filterSets = {};
  3563. Object.values(filterDefs).forEach(filter => {
  3564. filterSets[filter.id] = new Set();
  3565. })
  3566. Object.entries(availableEntities).forEach(([category, entityList]) => {
  3567. const select = document.createElement("select");
  3568. select.id = "create-entity-" + category;
  3569. select.classList.add("entity-select");
  3570. for (let i = 0; i < entityList.length; i++) {
  3571. const entity = entityList[i];
  3572. const option = document.createElement("option");
  3573. option.value = i;
  3574. option.innerText = entity.name;
  3575. select.appendChild(option);
  3576. if (entity.nsfw) {
  3577. option.classList.add("nsfw");
  3578. }
  3579. Object.values(filterDefs).forEach(filter => {
  3580. filter.extract(entity).forEach(result => {
  3581. filterSets[filter.id].add(result);
  3582. });
  3583. });
  3584. availableEntitiesByName[entity.name] = entity;
  3585. };
  3586. select.addEventListener("change", e => {
  3587. if (select.options[select.selectedIndex]?.classList.contains("nsfw")) {
  3588. select.classList.add("nsfw");
  3589. } else {
  3590. select.classList.remove("nsfw");
  3591. }
  3592. // preload the entity's first image
  3593. const entity = entityList[select.selectedIndex]?.constructor();
  3594. if (entity)
  3595. {
  3596. let img = new Image();
  3597. img.src = entity.currentView.image.source;
  3598. }
  3599. })
  3600. const button = document.createElement("button");
  3601. button.id = "create-entity-" + category + "-button";
  3602. button.classList.add("entity-button");
  3603. button.innerHTML = "<i class=\"far fa-plus-square\"></i>";
  3604. button.addEventListener("click", e => {
  3605. if (entityList[select.value] == null)
  3606. return;
  3607. const newEntity = entityList[select.value].constructor()
  3608. let yOffset = 0;
  3609. if (config.lockYAxis) {
  3610. if (config.groundPos === "very-high") {
  3611. yOffset = config.height.toNumber("meters") / 12 * 5;
  3612. }
  3613. else if (config.groundPos === "high") {
  3614. yOffset = config.height.toNumber("meters") / 12 * 4;
  3615. }
  3616. else if (config.groundPos === "medium") {
  3617. yOffset = config.height.toNumber("meters") / 12 * 3;
  3618. }
  3619. else if (config.groundPos === "low") {
  3620. yOffset = config.height.toNumber("meters") / 12 * 2;
  3621. }
  3622. else if (config.groundPos === "very-low") {
  3623. yOffset = config.height.toNumber("meters") / 12 * 1;
  3624. }
  3625. else if (config.groundPos === "bottom") {
  3626. yOffset = 0;
  3627. }
  3628. } else {
  3629. yOffset = (config.lockYAxis ? 0 : config.height.toNumber("meters")/2);
  3630. }
  3631. displayEntity(newEntity, newEntity.defaultView, config.x, config.y + yOffset, true, true);
  3632. });
  3633. const categoryOption = document.createElement("option");
  3634. categoryOption.value = category
  3635. categoryOption.innerText = category;
  3636. if (category == "characters") {
  3637. categoryOption.selected = true;
  3638. select.classList.add("category-visible");
  3639. button.classList.add("category-visible");
  3640. }
  3641. categorySelect.appendChild(categoryOption);
  3642. holder.appendChild(select);
  3643. holder.appendChild(button);
  3644. });
  3645. Object.values(filterDefs).forEach(filter => {
  3646. const option = document.createElement("option");
  3647. option.innerText = filter.name;
  3648. option.value = filter.id;
  3649. filterSelect.appendChild(option);
  3650. const filterNameSelect = document.createElement("select");
  3651. filterNameSelect.classList.add("filter-select");
  3652. filterNameSelect.id = "filter-" + filter.id;
  3653. filterHolder.appendChild(filterNameSelect);
  3654. const button = document.createElement("button");
  3655. button.classList.add("filter-button");
  3656. button.id = "create-filtered-" + filter.id + "-button";
  3657. filterHolder.appendChild(button);
  3658. const counter = document.createElement("div");
  3659. counter.classList.add("button-counter");
  3660. counter.innerText = "10";
  3661. button.appendChild(counter);
  3662. const i = document.createElement("i");
  3663. i.classList.add("fas");
  3664. i.classList.add("fa-plus");
  3665. button.appendChild(i);
  3666. button.addEventListener("click", e => {
  3667. const makers = Array.from(document.querySelector(".entity-select.category-visible")).filter(element => !element.classList.contains("filtered"));
  3668. const count = makers.length + 2;
  3669. let index = 1;
  3670. if (makers.length > 50) {
  3671. if (!confirm("Really spawn " + makers.length + " things at once?")) {
  3672. return;
  3673. }
  3674. }
  3675. const worldWidth = config.height.toNumber("meters") / canvasHeight * canvasWidth;
  3676. const spawned = makers.map(element => {
  3677. const category = document.querySelector("#category-picker").value;
  3678. const maker = availableEntities[category][element.value];
  3679. const entity = maker.constructor()
  3680. displayEntity(entity, entity.view, -worldWidth * 0.45 + config.x + worldWidth * 0.9 * index / (count - 1), config.y);
  3681. index += 1;
  3682. return entityIndex - 1;
  3683. });
  3684. updateSizes(true);
  3685. if (config.autoFitAdd) {
  3686. let targets = {};
  3687. spawned.forEach(key => {
  3688. targets[key] = entities[key];
  3689. })
  3690. fitEntities(targets);
  3691. }
  3692. });
  3693. Array.from(filterSets[filter.id]).map(name => [name, filter.render(name)]).sort(filterDefs[filter.id].sort).forEach(name => {
  3694. const option = document.createElement("option");
  3695. option.innerText = name[1];
  3696. option.value = name[0];
  3697. filterNameSelect.appendChild(option);
  3698. });
  3699. filterNameSelect.addEventListener("change", e => {
  3700. updateFilter();
  3701. });
  3702. });
  3703. console.log("Loaded " + Object.keys(availableEntitiesByName).length + " entities");
  3704. categorySelect.addEventListener("input", e => {
  3705. const oldSelect = document.querySelector(".entity-select.category-visible");
  3706. oldSelect.classList.remove("category-visible");
  3707. const oldButton = document.querySelector(".entity-button.category-visible");
  3708. oldButton.classList.remove("category-visible");
  3709. const newSelect = document.querySelector("#create-entity-" + e.target.value);
  3710. newSelect.classList.add("category-visible");
  3711. const newButton = document.querySelector("#create-entity-" + e.target.value + "-button");
  3712. newButton.classList.add("category-visible");
  3713. recomputeFilters();
  3714. updateFilter();
  3715. });
  3716. recomputeFilters();
  3717. filterSelect.addEventListener("input", e => {
  3718. const oldSelect = document.querySelector(".filter-select.category-visible");
  3719. if (oldSelect)
  3720. oldSelect.classList.remove("category-visible");
  3721. const newSelect = document.querySelector("#filter-" + e.target.value);
  3722. if (newSelect && e.target.value != "none")
  3723. newSelect.classList.add("category-visible");
  3724. updateFilter();
  3725. });
  3726. ratioInfo = document.body.querySelector(".ratio-info")
  3727. }
  3728. // Only display authors and owners if they appear
  3729. // somewhere in the current entity list
  3730. function recomputeFilters() {
  3731. const category = document.querySelector("#category-picker").value;
  3732. const filterSets = {};
  3733. Object.values(filterDefs).forEach(filter => {
  3734. filterSets[filter.id] = new Set();
  3735. });
  3736. document.querySelectorAll(".entity-select.category-visible > option").forEach(element => {
  3737. const entity = availableEntities[category][element.value];
  3738. Object.values(filterDefs).forEach(filter => {
  3739. filter.extract(entity).forEach(result => {
  3740. filterSets[filter.id].add(result);
  3741. });
  3742. });
  3743. });
  3744. Object.values(filterDefs).forEach(filter => {
  3745. // always show the "none" option
  3746. let found = filter.id == "none";
  3747. document.querySelectorAll("#filter-" + filter.id + " > option").forEach(element => {
  3748. if (filterSets[filter.id].has(element.value) || filter.id == "none") {
  3749. element.classList.remove("filtered");
  3750. element.disabled = false;
  3751. found = true;
  3752. } else {
  3753. element.classList.add("filtered");
  3754. element.disabled = true;
  3755. }
  3756. });
  3757. const filterOption = document.querySelector("#filter-picker > option[value='" + filter.id + "']");
  3758. if (found) {
  3759. filterOption.classList.remove("filtered");
  3760. filterOption.disabled = false;
  3761. } else {
  3762. filterOption.classList.add("filtered");
  3763. filterOption.disabled = true;
  3764. }
  3765. });
  3766. document.querySelector("#filter-picker").value = "none";
  3767. document.querySelector("#filter-picker").dispatchEvent(new Event("input"));
  3768. }
  3769. function updateFilter() {
  3770. const category = document.querySelector("#category-picker").value;
  3771. const type = document.querySelector("#filter-picker").value;
  3772. const filterKeySelect = document.querySelector(".filter-select.category-visible");
  3773. clearFilter();
  3774. const noFilter = !filterKeySelect;
  3775. let key;
  3776. let current = document.querySelector(".entity-select.category-visible").value;
  3777. if (!noFilter)
  3778. {
  3779. key = filterKeySelect.value;
  3780. current
  3781. }
  3782. let replace = current == "";
  3783. let first = null;
  3784. let count = 0;
  3785. const lowerSearchText = searchText !== "" ? searchText.toLowerCase() : null;
  3786. document.querySelectorAll(".entity-select.category-visible > option").forEach(element => {
  3787. let keep = noFilter;
  3788. if (!noFilter && filterDefs[type].extract(availableEntities[category][element.value]).indexOf(key) >= 0) {
  3789. keep = true;
  3790. }
  3791. if (searchText != "" && !availableEntities[category][element.value].name.toLowerCase().includes(lowerSearchText))
  3792. {
  3793. keep = false;
  3794. }
  3795. if (!keep) {
  3796. element.classList.add("filtered");
  3797. element.disabled = true;
  3798. if (current == element.value) {
  3799. replace = true;
  3800. }
  3801. } else {
  3802. count += 1;
  3803. if (!first) {
  3804. first = element.value;
  3805. }
  3806. }
  3807. });
  3808. const button = document.querySelector(".filter-select.category-visible + button");
  3809. if (button) {
  3810. button.querySelector(".button-counter").innerText = count;
  3811. }
  3812. if (replace) {
  3813. document.querySelector(".entity-select.category-visible").value = first;
  3814. document.querySelector("#create-entity-" + category).dispatchEvent(new Event("change"));
  3815. }
  3816. }
  3817. function clearFilter() {
  3818. document.querySelectorAll(".entity-select.category-visible > option").forEach(element => {
  3819. element.classList.remove("filtered");
  3820. element.disabled = false;
  3821. });
  3822. }
  3823. document.addEventListener("mousemove", (e) => {
  3824. if (currentRuler) {
  3825. let entX = document.querySelector("#entities").getBoundingClientRect().x;
  3826. let entY = document.querySelector("#entities").getBoundingClientRect().y;
  3827. let position = pix2pos({ x: e.clientX - entX, y: e.clientY - entY });
  3828. if (config.rulersStick && selected) {
  3829. position = entityRelativePosition(position, selected)
  3830. }
  3831. currentRuler.x1 = position.x;
  3832. currentRuler.y1 = position.y;
  3833. }
  3834. drawRulers();
  3835. });
  3836. document.addEventListener("touchmove", (e) => {
  3837. if (currentRuler) {
  3838. let entX = document.querySelector("#entities").getBoundingClientRect().x;
  3839. let entY = document.querySelector("#entities").getBoundingClientRect().y;
  3840. let position = pix2pos({ x: e.touches[0].clientX - entX, y: e.touches[0].clientY - entY });
  3841. if (config.rulersStick && selected) {
  3842. position = entityRelativePosition(position, selected)
  3843. }
  3844. currentRuler.x1 = position.x;
  3845. currentRuler.y1 = position.y;
  3846. }
  3847. drawRulers();
  3848. });
  3849. document.addEventListener("mousemove", (e) => {
  3850. if (clicked) {
  3851. let position = pix2pos({ x: e.clientX - dragOffsetX, y: e.clientY - dragOffsetY });
  3852. if (movingInBounds) {
  3853. position = snapPos(position);
  3854. } else {
  3855. let x = e.clientX - dragOffsetX;
  3856. let y = e.clientY - dragOffsetY;
  3857. if (x >= 0 && x <= canvasWidth && y >= 0 && y <= canvasHeight) {
  3858. movingInBounds = true;
  3859. }
  3860. }
  3861. clicked.dataset.x = position.x;
  3862. clicked.dataset.y = position.y;
  3863. updateEntityElement(entities[clicked.dataset.key], clicked);
  3864. if (hoveringInDeleteArea(e)) {
  3865. document.querySelector("#menubar").classList.add("hover-delete");
  3866. } else {
  3867. document.querySelector("#menubar").classList.remove("hover-delete");
  3868. }
  3869. }
  3870. if (panning && panReady) {
  3871. const worldWidth = config.height.toNumber("meters") / canvasHeight * canvasWidth;
  3872. const worldHeight = config.height.toNumber("meters");
  3873. config.x -= (e.clientX - panOffsetX) / canvasWidth * worldWidth;
  3874. config.y += (e.clientY - panOffsetY) / canvasHeight * worldHeight;
  3875. panOffsetX = e.clientX;
  3876. panOffsetY = e.clientY;
  3877. updateSizes();
  3878. panReady = false;
  3879. setTimeout(() => panReady=true, 1000/120);
  3880. }
  3881. });
  3882. document.addEventListener("touchmove", (e) => {
  3883. if (clicked) {
  3884. e.preventDefault();
  3885. let x = e.touches[0].clientX;
  3886. let y = e.touches[0].clientY;
  3887. const position = snapPos(pix2pos({ x: x - dragOffsetX, y: y - dragOffsetY }));
  3888. clicked.dataset.x = position.x;
  3889. clicked.dataset.y = position.y;
  3890. updateEntityElement(entities[clicked.dataset.key], clicked);
  3891. // what a hack
  3892. // I should centralize this 'fake event' creation...
  3893. if (hoveringInDeleteArea({ clientY: y })) {
  3894. document.querySelector("#menubar").classList.add("hover-delete");
  3895. } else {
  3896. document.querySelector("#menubar").classList.remove("hover-delete");
  3897. }
  3898. }
  3899. if (panning && panReady) {
  3900. const worldWidth = config.height.toNumber("meters") / canvasHeight * canvasWidth;
  3901. const worldHeight = config.height.toNumber("meters");
  3902. config.x -= (e.touches[0].clientX - panOffsetX) / canvasWidth * worldWidth;
  3903. config.y += (e.touches[0].clientY - panOffsetY) / canvasHeight * worldHeight;
  3904. panOffsetX = e.touches[0].clientX;
  3905. panOffsetY = e.touches[0].clientY;
  3906. updateSizes();
  3907. panReady = false;
  3908. setTimeout(() => panReady=true, 1000/60);
  3909. }
  3910. }, { passive: false });
  3911. function checkFitWorld() {
  3912. if (config.autoFit) {
  3913. fitWorld();
  3914. return true;
  3915. }
  3916. return false;
  3917. }
  3918. function fitWorld(manual = false, factor = 1.1) {
  3919. if (Object.keys(entities).length > 0) {
  3920. fitEntities(entities, factor);
  3921. }
  3922. }
  3923. function fitEntities(targetEntities, manual = false, factor = 1.1) {
  3924. let minX = Infinity;
  3925. let maxX = -Infinity;
  3926. let minY = Infinity;
  3927. let maxY = -Infinity;
  3928. let count = 0;
  3929. const worldWidth = config.height.toNumber("meters") / canvasHeight * canvasWidth;
  3930. const worldHeight = config.height.toNumber("meters");
  3931. Object.entries(targetEntities).forEach(([key, entity]) => {
  3932. const view = entity.view;
  3933. let extra = entity.views[view].image.extra;
  3934. extra = extra === undefined ? 1 : extra;
  3935. const image = document.querySelector("#entity-" + key + " > .entity-image");
  3936. const x = parseFloat(document.querySelector("#entity-" + key).dataset.x);
  3937. let width = image.width;
  3938. let height = image.height;
  3939. // only really relevant if the images haven't loaded in yet
  3940. if (height == 0) {
  3941. height = 100;
  3942. }
  3943. if (width == 0) {
  3944. width = height;
  3945. }
  3946. const xBottom = x - entity.views[view].height.toNumber("meters") * width / height / 2;
  3947. const xTop = x + entity.views[view].height.toNumber("meters") * width / height / 2;
  3948. const y = parseFloat(document.querySelector("#entity-" + key).dataset.y);
  3949. const yBottom = y;
  3950. const yTop = entity.views[view].height.toNumber("meters") + yBottom;
  3951. minX = Math.min(minX, xBottom);
  3952. maxX = Math.max(maxX, xTop);
  3953. minY = Math.min(minY, yBottom);
  3954. maxY = Math.max(maxY, yTop);
  3955. count += 1;
  3956. });
  3957. if (config.lockYAxis) {
  3958. minY = 0;
  3959. }
  3960. let ySize = (maxY - minY) * factor;
  3961. let xSize = (maxX - minX) * factor;
  3962. if (xSize / ySize > worldWidth / worldHeight) {
  3963. ySize *= ((xSize / ySize) / (worldWidth / worldHeight));
  3964. }
  3965. config.x = (maxX + minX) / 2;
  3966. config.y = minY;
  3967. height = math.unit(ySize, "meter")
  3968. setWorldHeight(config.height, math.multiply(height, factor));
  3969. }
  3970. function updateWorldHeight() {
  3971. const unit = document.querySelector("#options-height-unit").value;
  3972. const rawValue = document.querySelector("#options-height-value").value;
  3973. var value
  3974. try {
  3975. value = math.evaluate(rawValue)
  3976. if (typeof(value) !== "number") {
  3977. try {
  3978. value = value.toNumber(unit)
  3979. } catch {
  3980. toast("Invalid input: " + rawValue + " can't be converted to " + unit)
  3981. }
  3982. }
  3983. } catch {
  3984. toast("Invalid input: could not parse " + rawValue)
  3985. return;
  3986. }
  3987. const newHeight = Math.max(0.000000001, value);
  3988. const oldHeight = config.height;
  3989. setWorldHeight(oldHeight, math.unit(newHeight, unit), true);
  3990. }
  3991. function setWorldHeight(oldHeight, newHeight, keepUnit=false) {
  3992. worldSizeDirty = true;
  3993. config.height = newHeight.to(document.querySelector("#options-height-unit").value)
  3994. const unit = document.querySelector("#options-height-unit").value;
  3995. setNumericInput(document.querySelector("#options-height-value"), config.height.toNumber(unit));
  3996. Object.entries(entities).forEach(([key, entity]) => {
  3997. const element = document.querySelector("#entity-" + key);
  3998. let newPosition;
  3999. if (altHeld) {
  4000. newPosition = adjustAbs({ x: element.dataset.x, y: element.dataset.y }, oldHeight, config.height);
  4001. } else {
  4002. newPosition = { x: element.dataset.x, y: element.dataset.y };
  4003. }
  4004. element.dataset.x = newPosition.x;
  4005. element.dataset.y = newPosition.y;
  4006. });
  4007. if (!keepUnit) {
  4008. pickUnit()
  4009. }
  4010. updateSizes();
  4011. }
  4012. function loadScene(name = "default") {
  4013. if (name === "") {
  4014. name = "default"
  4015. }
  4016. try {
  4017. const data = JSON.parse(localStorage.getItem("macrovision-save-" + name));
  4018. if (data === null) {
  4019. console.error("Couldn't load " + name)
  4020. return false;
  4021. }
  4022. importScene(data);
  4023. toast("Loaded " + name);
  4024. return true;
  4025. } catch (err) {
  4026. alert("Something went wrong while loading (maybe you didn't have anything saved. Check the F12 console for the error.")
  4027. console.error(err);
  4028. return false;
  4029. }
  4030. }
  4031. function saveScene(name = "default") {
  4032. try {
  4033. const string = JSON.stringify(exportScene());
  4034. localStorage.setItem("macrovision-save-" + name, string);
  4035. toast("Saved as " + name);
  4036. } catch (err) {
  4037. alert("Something went wrong while saving (maybe I don't have localStorage permissions, or exporting failed). Check the F12 console for the error.")
  4038. console.error(err);
  4039. }
  4040. }
  4041. function deleteScene(name = "default") {
  4042. if (confirm("Really delete the " + name + " scene?")) {
  4043. try {
  4044. localStorage.removeItem("macrovision-save-" + name)
  4045. toast("Deleted " + name);
  4046. } catch (err) {
  4047. console.error(err);
  4048. }
  4049. }
  4050. updateSaveInfo();
  4051. }
  4052. function exportScene() {
  4053. const results = {};
  4054. results.entities = [];
  4055. Object.entries(entities).filter(([key, entity]) => entity.ephemeral !== true).forEach(([key, entity]) => {
  4056. const element = document.querySelector("#entity-" + key);
  4057. results.entities.push({
  4058. name: entity.identifier,
  4059. customName: entity.name,
  4060. scale: entity.scale,
  4061. rotation: entity.rotation,
  4062. view: entity.view,
  4063. form: entity.form,
  4064. x: element.dataset.x,
  4065. y: element.dataset.y,
  4066. priority: entity.priority,
  4067. brightness: entity.brightness
  4068. });
  4069. });
  4070. const unit = document.querySelector("#options-height-unit").value;
  4071. results.world = {
  4072. height: config.height.toNumber(unit),
  4073. unit: unit,
  4074. x: config.x,
  4075. y: config.y
  4076. }
  4077. results.version = migrationDefs.length;
  4078. return results;
  4079. }
  4080. // btoa doesn't like anything that isn't ASCII
  4081. // great
  4082. // thanks to https://stackoverflow.com/questions/30106476/using-javascripts-atob-to-decode-base64-doesnt-properly-decode-utf-8-strings
  4083. // for providing an alternative
  4084. function b64EncodeUnicode(str) {
  4085. // first we use encodeURIComponent to get percent-encoded UTF-8,
  4086. // then we convert the percent encodings into raw bytes which
  4087. // can be fed into btoa.
  4088. return btoa(encodeURIComponent(str).replace(/%([0-9A-F]{2})/g,
  4089. function toSolidBytes(match, p1) {
  4090. return String.fromCharCode('0x' + p1);
  4091. }));
  4092. }
  4093. function b64DecodeUnicode(str) {
  4094. // Going backwards: from bytestream, to percent-encoding, to original string.
  4095. return decodeURIComponent(atob(str).split('').map(function (c) {
  4096. return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
  4097. }).join(''));
  4098. }
  4099. function linkScene() {
  4100. loc = new URL(window.location);
  4101. const link = loc.protocol + "//" + loc.host + loc.pathname + "#" + b64EncodeUnicode(JSON.stringify(exportScene()));
  4102. window.history.replaceState(null, "Macrovision", link);
  4103. try {
  4104. navigator.clipboard.writeText(link);
  4105. toast("Copied permalink to clipboard");
  4106. } catch {
  4107. toast("Couldn't copy permalink");
  4108. }
  4109. }
  4110. function copyScene() {
  4111. const results = exportScene();
  4112. navigator.clipboard.writeText(JSON.stringify(results));
  4113. }
  4114. function pasteScene() {
  4115. try {
  4116. navigator.clipboard.readText().then(text => {
  4117. const data = JSON.parse(text);
  4118. if (data.entities === undefined) {
  4119. return;
  4120. }
  4121. if (data.world === undefined) {
  4122. return;
  4123. }
  4124. importScene(data);
  4125. }).catch(err => alert(err));
  4126. } catch (err) {
  4127. console.error(err);
  4128. // probably wasn't valid data
  4129. }
  4130. }
  4131. // TODO - don't just search through every single entity
  4132. // probably just have a way to do lookups directly
  4133. function findEntity(name) {
  4134. return availableEntitiesByName[name];
  4135. }
  4136. const migrationDefs = [
  4137. /*
  4138. Migration: 0 -> 1
  4139. Adds x and y coordinates for the camera
  4140. */
  4141. data => {
  4142. data.world.x = 0;
  4143. data.world.y = 0;
  4144. },
  4145. /*
  4146. Migration: 1 -> 2
  4147. Adds priority and brightness to each entity
  4148. */
  4149. data => {
  4150. data.entities.forEach(entity => {
  4151. entity.priority = 0;
  4152. entity.brightness = 1;
  4153. });
  4154. },
  4155. /*
  4156. Migration: 2 -> 3
  4157. Custom names are exported
  4158. */
  4159. data => {
  4160. data.entities.forEach(entity => {
  4161. entity.customName = entity.name
  4162. });
  4163. },
  4164. /*
  4165. Migration: 3 -> 4
  4166. Rotation is now stored
  4167. */
  4168. data => {
  4169. data.entities.forEach(entity => {
  4170. entity.rotation = 0
  4171. });
  4172. }
  4173. ]
  4174. function migrateScene(data) {
  4175. if (data.version === undefined) {
  4176. alert("This save was created before save versions were tracked. The scene may import incorrectly.");
  4177. console.trace()
  4178. data.version = 0;
  4179. } else if (data.version < migrationDefs.length) {
  4180. migrationDefs[data.version](data);
  4181. data.version += 1;
  4182. migrateScene(data);
  4183. }
  4184. }
  4185. function importScene(data) {
  4186. removeAllEntities();
  4187. migrateScene(data);
  4188. data.entities.forEach(entityInfo => {
  4189. const entity = findEntity(entityInfo.name).constructor();
  4190. entity.name = entityInfo.customName;
  4191. entity.scale = entityInfo.scale;
  4192. entity.rotation = entityInfo.rotation;
  4193. entity.priority = entityInfo.priority;
  4194. entity.brightness = entityInfo.brightness;
  4195. entity.form = entityInfo.form;
  4196. displayEntity(entity, entityInfo.view, entityInfo.x, entityInfo.y);
  4197. });
  4198. config.height = math.unit(data.world.height, data.world.unit);
  4199. config.x = data.world.x;
  4200. config.y = data.world.y;
  4201. const height = math.unit(data.world.height, data.world.unit).toNumber(defaultUnits.length[config.units]);
  4202. document.querySelector("#options-height-value").value = height;
  4203. document.querySelector("#options-height-unit").dataset.oldUnit = defaultUnits.length[config.units];
  4204. document.querySelector("#options-height-unit").value = defaultUnits.length[config.units];
  4205. if (data.canvasWidth) {
  4206. doHorizReposition(data.canvasWidth / canvasWidth);
  4207. }
  4208. updateSizes();
  4209. }
  4210. function renderToCanvas() {
  4211. const ctx = document.querySelector("#display").getContext("2d");
  4212. Object.entries(entities).sort((ent1, ent2) => {
  4213. z1 = document.querySelector("#entity-" + ent1[0]).style.zIndex;
  4214. z2 = document.querySelector("#entity-" + ent2[0]).style.zIndex;
  4215. return z1 - z2;
  4216. }).forEach(([id, entity]) => {
  4217. element = document.querySelector("#entity-" + id);
  4218. img = element.querySelector("img");
  4219. let x = parseFloat(element.dataset.x);
  4220. let y = parseFloat(element.dataset.y);
  4221. let coords = pos2pix({x: x, y: y});
  4222. let offset = img.style.getPropertyValue("--offset");
  4223. offset = parseFloat(offset.substring(0, offset.length-1))
  4224. let xSize = img.width;
  4225. let ySize = img.height;
  4226. x = coords.x
  4227. y = coords.y + ySize/2 + ySize * offset / 100;
  4228. const oldFilter = ctx.filter
  4229. const brightness = getComputedStyle(element).getPropertyValue("--brightness")
  4230. ctx.filter = `brightness(${brightness})`;
  4231. ctx.save();
  4232. ctx.resetTransform();
  4233. ctx.scale(window.devicePixelRatio, window.devicePixelRatio)
  4234. ctx.translate(x, y);
  4235. ctx.rotate(entity.rotation);
  4236. ctx.drawImage(img, -xSize/2, -ySize/2, xSize, ySize);
  4237. ctx.restore();
  4238. ctx.filter = oldFilter
  4239. });
  4240. ctx.drawImage(document.querySelector("#rulers"), 0, 0);
  4241. }
  4242. function exportCanvas(callback) {
  4243. /** @type {CanvasRenderingContext2D} */
  4244. const ctx = document.querySelector("#display").getContext("2d");
  4245. const blob = ctx.canvas.toBlob(callback);
  4246. }
  4247. function generateScreenshot(callback) {
  4248. /** @type {CanvasRenderingContext2D} */
  4249. const ctx = document.querySelector("#display").getContext("2d");
  4250. if (config.groundKind !== "none") {
  4251. ctx.fillStyle = backgroundColors[config.groundKind];
  4252. ctx.fillRect(0, pos2pix({x: 0, y: 0}).y, canvasWidth + 100, canvasHeight);
  4253. }
  4254. renderToCanvas();
  4255. ctx.resetTransform();
  4256. ctx.fillStyle = "#999";
  4257. ctx.font = "normal normal lighter 16pt coda";
  4258. ctx.fillText("macrovision.crux.sexy", 10, 25);
  4259. exportCanvas(blob => {
  4260. callback(blob);
  4261. });
  4262. }
  4263. function copyScreenshot() {
  4264. if (window.ClipboardItem === undefined) {
  4265. alert("Sorry, this browser doesn't yet support writing images to the clipboard.");
  4266. return;
  4267. }
  4268. generateScreenshot(blob => {
  4269. navigator.clipboard.write([
  4270. new ClipboardItem({
  4271. "image/png": blob
  4272. })
  4273. ]).then(e =>
  4274. toast("Copied to clipboard!"))
  4275. .catch(e => {
  4276. toast("Couldn't write to the clipboard. Make sure the screenshot completes before switching tabs.")
  4277. })
  4278. });
  4279. drawScales(false);
  4280. }
  4281. function saveScreenshot() {
  4282. generateScreenshot(blob => {
  4283. const a = document.createElement("a");
  4284. a.href = URL.createObjectURL(blob);
  4285. a.setAttribute("download", "macrovision.png");
  4286. a.click();
  4287. });
  4288. drawScales(false);
  4289. }
  4290. function openScreenshot() {
  4291. generateScreenshot(blob => {
  4292. const a = document.createElement("a");
  4293. a.href = URL.createObjectURL(blob);
  4294. a.setAttribute("target", "_blank");
  4295. a.click();
  4296. });
  4297. drawScales(false);
  4298. }
  4299. const rateLimits = {};
  4300. function toast(msg) {
  4301. let div = document.createElement("div");
  4302. div.innerHTML = msg;
  4303. div.classList.add("toast");
  4304. document.body.appendChild(div);
  4305. setTimeout(() => {
  4306. document.body.removeChild(div);
  4307. }, 5000)
  4308. }
  4309. function toastRateLimit(msg, key, delay) {
  4310. if (!rateLimits[key]) {
  4311. toast(msg);
  4312. rateLimits[key] = setTimeout(() => {
  4313. delete rateLimits[key]
  4314. }, delay);
  4315. }
  4316. }
  4317. let lastTime = undefined;
  4318. function pan(fromX, fromY, fromHeight, toX, toY, toHeight, duration) {
  4319. Object.keys(entities).forEach(key => {
  4320. document.querySelector("#entity-" + key).classList.add("no-transition");
  4321. });
  4322. config.x = fromX;
  4323. config.y = fromY;
  4324. config.height = math.unit(fromHeight, "meters")
  4325. updateSizes();
  4326. lastTime = undefined;
  4327. requestAnimationFrame((timestamp) => panTo(toX, toY, toHeight, (toX - fromX) / duration, (toY - fromY) / duration, (toHeight - fromHeight) / duration, timestamp, duration));
  4328. }
  4329. function panTo(x, y, height, xSpeed, ySpeed, heightSpeed, timestamp, remaining) {
  4330. if (lastTime === undefined) {
  4331. lastTime = timestamp;
  4332. }
  4333. dt = timestamp - lastTime;
  4334. remaining -= dt;
  4335. if (remaining < 0) {
  4336. dt += remaining
  4337. }
  4338. let newX = config.x + xSpeed * dt;
  4339. let newY = config.y + ySpeed * dt;
  4340. let newHeight = config.height.toNumber("meters") + heightSpeed * dt;
  4341. if (remaining > 0) {
  4342. requestAnimationFrame((timestamp) => panTo(x, y, height, xSpeed, ySpeed, heightSpeed, timestamp, remaining))
  4343. } else {
  4344. Object.keys(entities).forEach(key => {
  4345. document.querySelector("#entity-" + key).classList.remove("no-transition");
  4346. });
  4347. }
  4348. config.x = newX;
  4349. config.y = newY;
  4350. config.height = math.unit(newHeight, "meters");
  4351. updateSizes();
  4352. }