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.
 
 
 

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