less copy protection, more size visualization
Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.
 
 
 

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