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

5007 строки
152 KiB

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