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

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