less copy protection, more size visualization
25개 이상의 토픽을 선택하실 수 없습니다. Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

4817 lines
145 KiB

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