less copy protection, more size visualization
Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.
 
 
 

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