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

5185 satır
158 KiB

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