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.
 
 
 

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