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

4057 строки
121 KiB

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