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.
 
 
 

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