less copy protection, more size visualization
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

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