less copy protection, more size visualization
選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。
 
 
 

4982 行
151 KiB

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