less copy protection, more size visualization
25'ten fazla konu seçemezsiniz Konular bir harf veya rakamla başlamalı, kısa çizgiler ('-') içerebilir ve en fazla 35 karakter uzunluğunda olabilir.
 
 
 

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