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

3991 строка
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. console.log(entity, view)
  1060. Object.entries(entity.views[view].attributes).forEach(([key, val]) => {
  1061. if (key != changed) {
  1062. const input = document.querySelector("#options-view-" + key + "-input");
  1063. const select = document.querySelector("#options-view-" + key + "-select");
  1064. const currentUnit = select.value;
  1065. const convertedAmount = entity.views[view][key].toNumber(currentUnit);
  1066. setNumericInput(input, convertedAmount);
  1067. }
  1068. });
  1069. }
  1070. function setNumericInput(input, value, round = 6) {
  1071. if (typeof value == "string") {
  1072. value = parseFloat(value)
  1073. }
  1074. input.value = value.toPrecision(round);
  1075. }
  1076. function getSortedEntities() {
  1077. return Object.keys(entities).sort((a, b) => {
  1078. const entA = entities[a];
  1079. const entB = entities[b];
  1080. const viewA = entA.view;
  1081. const viewB = entB.view;
  1082. const heightA = entA.views[viewA].height.to("meter").value;
  1083. const heightB = entB.views[viewB].height.to("meter").value;
  1084. return heightA - heightB;
  1085. });
  1086. }
  1087. function clearViewOptions() {
  1088. document.querySelector("#view-category-header").style.display = "none";
  1089. document.querySelector("#view-category").style.display = "none";
  1090. }
  1091. // this is a crime against humanity, and also stolen from
  1092. // stack overflow
  1093. // https://stackoverflow.com/questions/38487569/click-through-png-image-only-if-clicked-coordinate-is-transparent
  1094. const testCanvas = document.createElement("canvas");
  1095. testCanvas.id = "test-canvas";
  1096. const testCtx = testCanvas.getContext("2d");
  1097. function testClick(event) {
  1098. // oh my god I can't believe I'm doing this
  1099. const target = event.target;
  1100. // Get click coordinates
  1101. let w = target.width;
  1102. let h = target.height;
  1103. let ratioW = 1, ratioH = 1;
  1104. // Limit the size of the canvas so that very large images don't cause problems)
  1105. if (w > 1000) {
  1106. ratioW = w / 1000;
  1107. w /= ratioW;
  1108. h /= ratioW;
  1109. }
  1110. if (h > 1000) {
  1111. ratioH = h / 1000;
  1112. w /= ratioH;
  1113. h /= ratioH;
  1114. }
  1115. const ratio = ratioW * ratioH;
  1116. var x = event.clientX - target.getBoundingClientRect().x,
  1117. y = event.clientY - target.getBoundingClientRect().y,
  1118. alpha;
  1119. testCtx.canvas.width = w;
  1120. testCtx.canvas.height = h;
  1121. // Draw image to canvas
  1122. // and read Alpha channel value
  1123. testCtx.drawImage(target, 0, 0, w, h);
  1124. alpha = testCtx.getImageData(Math.floor(x / ratio), Math.floor(y / ratio), 1, 1).data[3]; // [0]R [1]G [2]B [3]A
  1125. // If pixel is transparent,
  1126. // retrieve the element underneath and trigger its click event
  1127. if (alpha === 0) {
  1128. const oldDisplay = target.style.display;
  1129. target.style.display = "none";
  1130. const newTarget = document.elementFromPoint(event.clientX, event.clientY);
  1131. newTarget.dispatchEvent(new MouseEvent(event.type, {
  1132. "clientX": event.clientX,
  1133. "clientY": event.clientY
  1134. }));
  1135. target.style.display = oldDisplay;
  1136. } else {
  1137. clickDown(target.parentElement, event.clientX, event.clientY);
  1138. }
  1139. }
  1140. function arrangeEntities(order) {
  1141. const worldWidth = config.height.toNumber("meters") / canvasHeight * canvasWidth;
  1142. let sum = 0;
  1143. order.forEach(key => {
  1144. const image = document.querySelector("#entity-" + key + " > .entity-image");
  1145. const meters = entities[key].views[entities[key].view].height.toNumber("meters");
  1146. let height = image.height;
  1147. let width = image.width;
  1148. if (height == 0) {
  1149. height = 100;
  1150. }
  1151. if (width == 0) {
  1152. width = height;
  1153. }
  1154. sum += meters * width / height;
  1155. });
  1156. let x = config.x - sum / 2;
  1157. order.forEach(key => {
  1158. const image = document.querySelector("#entity-" + key + " > .entity-image");
  1159. const meters = entities[key].views[entities[key].view].height.toNumber("meters");
  1160. let height = image.height;
  1161. let width = image.width;
  1162. if (height == 0) {
  1163. height = 100;
  1164. }
  1165. if (width == 0) {
  1166. width = height;
  1167. }
  1168. x += meters * width / height / 2;
  1169. document.querySelector("#entity-" + key).dataset.x = x;
  1170. document.querySelector("#entity-" + key).dataset.y = config.y;
  1171. x += meters * width / height / 2;
  1172. })
  1173. fitWorld();
  1174. updateSizes();
  1175. }
  1176. function removeAllEntities() {
  1177. Object.keys(entities).forEach(key => {
  1178. removeEntity(document.querySelector("#entity-" + key));
  1179. });
  1180. }
  1181. function clearAttribution() {
  1182. document.querySelector("#attribution-category-header").style.display = "none";
  1183. document.querySelector("#options-attribution").style.display = "none";
  1184. }
  1185. function displayAttribution(file) {
  1186. document.querySelector("#attribution-category-header").style.display = "block";
  1187. document.querySelector("#options-attribution").style.display = "inline";
  1188. const authors = authorsOfFull(file);
  1189. const owners = ownersOfFull(file);
  1190. const source = sourceOf(file);
  1191. const authorHolder = document.querySelector("#options-attribution-authors");
  1192. const ownerHolder = document.querySelector("#options-attribution-owners");
  1193. const sourceHolder = document.querySelector("#options-attribution-source");
  1194. if (authors === []) {
  1195. const div = document.createElement("div");
  1196. div.innerText = "Unknown";
  1197. authorHolder.innerHTML = "";
  1198. authorHolder.appendChild(div);
  1199. } else if (authors === undefined) {
  1200. const div = document.createElement("div");
  1201. div.innerText = "Not yet entered";
  1202. authorHolder.innerHTML = "";
  1203. authorHolder.appendChild(div);
  1204. } else {
  1205. authorHolder.innerHTML = "";
  1206. const list = document.createElement("ul");
  1207. authorHolder.appendChild(list);
  1208. authors.forEach(author => {
  1209. const authorEntry = document.createElement("li");
  1210. if (author.url) {
  1211. const link = document.createElement("a");
  1212. link.href = author.url;
  1213. link.innerText = author.name;
  1214. authorEntry.appendChild(link);
  1215. } else {
  1216. const div = document.createElement("div");
  1217. div.innerText = author.name;
  1218. authorEntry.appendChild(div);
  1219. }
  1220. list.appendChild(authorEntry);
  1221. });
  1222. }
  1223. if (owners === []) {
  1224. const div = document.createElement("div");
  1225. div.innerText = "Unknown";
  1226. ownerHolder.innerHTML = "";
  1227. ownerHolder.appendChild(div);
  1228. } else if (owners === undefined) {
  1229. const div = document.createElement("div");
  1230. div.innerText = "Not yet entered";
  1231. ownerHolder.innerHTML = "";
  1232. ownerHolder.appendChild(div);
  1233. } else {
  1234. ownerHolder.innerHTML = "";
  1235. const list = document.createElement("ul");
  1236. ownerHolder.appendChild(list);
  1237. owners.forEach(owner => {
  1238. const ownerEntry = document.createElement("li");
  1239. if (owner.url) {
  1240. const link = document.createElement("a");
  1241. link.href = owner.url;
  1242. link.innerText = owner.name;
  1243. ownerEntry.appendChild(link);
  1244. } else {
  1245. const div = document.createElement("div");
  1246. div.innerText = owner.name;
  1247. ownerEntry.appendChild(div);
  1248. }
  1249. list.appendChild(ownerEntry);
  1250. });
  1251. }
  1252. if (source === null) {
  1253. const div = document.createElement("div");
  1254. div.innerText = "No link";
  1255. sourceHolder.innerHTML = "";
  1256. sourceHolder.appendChild(div);
  1257. } else if (source === undefined) {
  1258. const div = document.createElement("div");
  1259. div.innerText = "Not yet entered";
  1260. sourceHolder.innerHTML = "";
  1261. sourceHolder.appendChild(div);
  1262. } else {
  1263. sourceHolder.innerHTML = "";
  1264. const link = document.createElement("a");
  1265. link.style.display = "block";
  1266. link.href = source;
  1267. link.innerText = new URL(source).host;
  1268. sourceHolder.appendChild(link);
  1269. }
  1270. }
  1271. function removeEntity(element) {
  1272. if (selected == element) {
  1273. deselect();
  1274. }
  1275. if (clicked == element) {
  1276. clicked = null;
  1277. }
  1278. const option = document.querySelector("#options-selected-entity-" + element.dataset.key);
  1279. option.parentElement.removeChild(option);
  1280. delete entities[element.dataset.key];
  1281. const bottomName = document.querySelector("#bottom-name-" + element.dataset.key);
  1282. const topName = document.querySelector("#top-name-" + element.dataset.key);
  1283. bottomName.parentElement.removeChild(bottomName);
  1284. topName.parentElement.removeChild(topName);
  1285. element.parentElement.removeChild(element);
  1286. }
  1287. function checkEntity(entity) {
  1288. Object.values(entity.views).forEach(view => {
  1289. if (authorsOf(view.image.source) === undefined) {
  1290. console.warn("No authors: " + view.image.source);
  1291. }
  1292. });
  1293. }
  1294. function displayEntity(entity, view, x, y, selectEntity = false, refresh = false) {
  1295. checkEntity(entity);
  1296. // preload all of the entity's views
  1297. Object.values(entity.views).forEach(view => {
  1298. if (!preloaded.has(view.image.source)) {
  1299. let img = new Image();
  1300. img.src = view.image.source;
  1301. preloaded.add(view.image.source);
  1302. }
  1303. });
  1304. const box = document.createElement("div");
  1305. box.classList.add("entity-box");
  1306. const img = document.createElement("img");
  1307. img.classList.add("entity-image");
  1308. img.addEventListener("dragstart", e => {
  1309. e.preventDefault();
  1310. });
  1311. const nameTag = document.createElement("div");
  1312. nameTag.classList.add("entity-name");
  1313. nameTag.innerText = entity.name;
  1314. box.appendChild(img);
  1315. box.appendChild(nameTag);
  1316. const image = entity.views[view].image;
  1317. img.src = image.source;
  1318. if (image.bottom !== undefined) {
  1319. img.style.setProperty("--offset", ((-1 + image.bottom) * 100) + "%")
  1320. } else {
  1321. img.style.setProperty("--offset", ((-1) * 100) + "%")
  1322. }
  1323. box.dataset.x = x;
  1324. box.dataset.y = y;
  1325. img.addEventListener("mousedown", e => { if (e.which == 1) { testClick(e); if (clicked) { e.stopPropagation() } } });
  1326. img.addEventListener("touchstart", e => {
  1327. const fakeEvent = {
  1328. target: e.target,
  1329. clientX: e.touches[0].clientX,
  1330. clientY: e.touches[0].clientY,
  1331. which: 1
  1332. };
  1333. testClick(fakeEvent);
  1334. if (clicked) { e.stopPropagation() }
  1335. });
  1336. const heightBar = document.createElement("div");
  1337. heightBar.classList.add("height-bar");
  1338. box.appendChild(heightBar);
  1339. box.id = "entity-" + entityIndex;
  1340. box.dataset.key = entityIndex;
  1341. entity.view = view;
  1342. if (entity.priority === undefined)
  1343. entity.priority = 0;
  1344. if (entity.brightness === undefined)
  1345. entity.brightness = 1;
  1346. entities[entityIndex] = entity;
  1347. entity.index = entityIndex;
  1348. const world = document.querySelector("#entities");
  1349. world.appendChild(box);
  1350. const bottomName = document.createElement("div");
  1351. bottomName.classList.add("bottom-name");
  1352. bottomName.id = "bottom-name-" + entityIndex;
  1353. bottomName.innerText = entity.name;
  1354. bottomName.addEventListener("click", () => select(box));
  1355. world.appendChild(bottomName);
  1356. const topName = document.createElement("div");
  1357. topName.classList.add("top-name");
  1358. topName.id = "top-name-" + entityIndex;
  1359. topName.innerText = entity.name;
  1360. topName.addEventListener("click", () => select(box));
  1361. world.appendChild(topName);
  1362. const entityOption = document.createElement("option");
  1363. entityOption.id = "options-selected-entity-" + entityIndex;
  1364. entityOption.value = entityIndex;
  1365. entityOption.innerText = entity.name;
  1366. document.getElementById("options-selected-entity").appendChild(entityOption);
  1367. entityIndex += 1;
  1368. if (config.autoFit) {
  1369. fitWorld();
  1370. }
  1371. if (selectEntity)
  1372. select(box);
  1373. entity.dirty = true;
  1374. if (refresh && config.autoFitAdd) {
  1375. let targets = {};
  1376. targets[entityIndex - 1] = entity;
  1377. fitEntities(targets);
  1378. }
  1379. if (refresh)
  1380. updateSizes(true);
  1381. }
  1382. window.onblur = function () {
  1383. altHeld = false;
  1384. shiftHeld = false;
  1385. }
  1386. window.onfocus = function () {
  1387. window.dispatchEvent(new Event("keydown"));
  1388. }
  1389. // thanks to https://developers.google.com/web/fundamentals/native-hardware/fullscreen
  1390. function toggleFullScreen() {
  1391. var doc = window.document;
  1392. var docEl = doc.documentElement;
  1393. var requestFullScreen = docEl.requestFullscreen || docEl.mozRequestFullScreen || docEl.webkitRequestFullScreen || docEl.msRequestFullscreen;
  1394. var cancelFullScreen = doc.exitFullscreen || doc.mozCancelFullScreen || doc.webkitExitFullscreen || doc.msExitFullscreen;
  1395. if (!doc.fullscreenElement && !doc.mozFullScreenElement && !doc.webkitFullscreenElement && !doc.msFullscreenElement) {
  1396. requestFullScreen.call(docEl);
  1397. }
  1398. else {
  1399. cancelFullScreen.call(doc);
  1400. }
  1401. }
  1402. function handleResize() {
  1403. const oldCanvasWidth = canvasWidth;
  1404. entityX = document.querySelector("#entities").getBoundingClientRect().x;
  1405. canvasWidth = document.querySelector("#display").clientWidth - 100;
  1406. canvasHeight = document.querySelector("#display").clientHeight - 50;
  1407. const change = oldCanvasWidth / canvasWidth;
  1408. updateSizes();
  1409. }
  1410. function prepareSidebar() {
  1411. const menubar = document.querySelector("#sidebar-menu");
  1412. [
  1413. {
  1414. name: "Show/hide sidebar",
  1415. id: "menu-toggle-sidebar",
  1416. icon: "fas fa-chevron-circle-down",
  1417. rotates: true
  1418. },
  1419. {
  1420. name: "Fullscreen",
  1421. id: "menu-fullscreen",
  1422. icon: "fas fa-compress"
  1423. },
  1424. {
  1425. name: "Clear",
  1426. id: "menu-clear",
  1427. icon: "fas fa-file"
  1428. },
  1429. {
  1430. name: "Sort by height",
  1431. id: "menu-order-height",
  1432. icon: "fas fa-sort-numeric-up"
  1433. },
  1434. {
  1435. name: "Permalink",
  1436. id: "menu-permalink",
  1437. icon: "fas fa-link"
  1438. },
  1439. {
  1440. name: "Export to clipboard",
  1441. id: "menu-export",
  1442. icon: "fas fa-share"
  1443. },
  1444. {
  1445. name: "Import from clipboard",
  1446. id: "menu-import",
  1447. icon: "fas fa-share",
  1448. classes: ["flipped"]
  1449. },
  1450. {
  1451. name: "Save Scene",
  1452. id: "menu-save",
  1453. icon: "fas fa-download",
  1454. input: true
  1455. },
  1456. {
  1457. name: "Load Scene",
  1458. id: "menu-load",
  1459. icon: "fas fa-upload",
  1460. select: true
  1461. },
  1462. {
  1463. name: "Delete Scene",
  1464. id: "menu-delete",
  1465. icon: "fas fa-trash",
  1466. select: true
  1467. },
  1468. {
  1469. name: "Load Autosave",
  1470. id: "menu-load-autosave",
  1471. icon: "fas fa-redo"
  1472. },
  1473. {
  1474. name: "Add Image",
  1475. id: "menu-add-image",
  1476. icon: "fas fa-camera"
  1477. }
  1478. ].forEach(entry => {
  1479. const buttonHolder = document.createElement("div");
  1480. buttonHolder.classList.add("menu-button-holder");
  1481. const button = document.createElement("button");
  1482. button.id = entry.id;
  1483. button.classList.add("menu-button");
  1484. const icon = document.createElement("i");
  1485. icon.classList.add(...entry.icon.split(" "));
  1486. if (entry.rotates) {
  1487. icon.classList.add("rotate-backward", "transitions");
  1488. }
  1489. if (entry.classes) {
  1490. entry.classes.forEach(cls => icon.classList.add(cls));
  1491. }
  1492. const actionText = document.createElement("span");
  1493. actionText.innerText = entry.name;
  1494. actionText.classList.add("menu-text");
  1495. const srText = document.createElement("span");
  1496. srText.classList.add("sr-only");
  1497. srText.innerText = entry.name;
  1498. button.appendChild(icon);
  1499. button.appendChild(srText);
  1500. buttonHolder.appendChild(button);
  1501. buttonHolder.appendChild(actionText);
  1502. if (entry.input) {
  1503. const input = document.createElement("input");
  1504. buttonHolder.appendChild(input);
  1505. input.placeholder = "default";
  1506. input.addEventListener("keyup", e => {
  1507. if (e.key === "Enter") {
  1508. const name = document.querySelector("#menu-save ~ input").value;
  1509. if (/\S/.test(name)) {
  1510. saveScene(name);
  1511. }
  1512. updateSaveInfo();
  1513. e.preventDefault();
  1514. }
  1515. })
  1516. }
  1517. if (entry.select) {
  1518. const select = document.createElement("select");
  1519. buttonHolder.appendChild(select);
  1520. }
  1521. menubar.appendChild(buttonHolder);
  1522. });
  1523. }
  1524. function checkBodyClass(cls) {
  1525. return document.body.classList.contains(cls);
  1526. }
  1527. function toggleBodyClass(cls, setting) {
  1528. if (setting) {
  1529. document.body.classList.add(cls);
  1530. } else {
  1531. document.body.classList.remove(cls);
  1532. }
  1533. }
  1534. const settingsData = {
  1535. "lock-y-axis": {
  1536. name: "Lock Y-Axis",
  1537. desc: "Keep the camera at ground-level",
  1538. type: "toggle",
  1539. default: true,
  1540. get value() {
  1541. return config.lockYAxis;
  1542. },
  1543. set value(param) {
  1544. config.lockYAxis = param;
  1545. if (param) {
  1546. config.y = 0;
  1547. updateSizes();
  1548. document.querySelector("#scroll-up").disabled = true;
  1549. document.querySelector("#scroll-down").disabled = true;
  1550. } else {
  1551. document.querySelector("#scroll-up").disabled = false;
  1552. document.querySelector("#scroll-down").disabled = false;
  1553. }
  1554. }
  1555. },
  1556. "auto-scale": {
  1557. name: "Auto-Size World",
  1558. desc: "Constantly zoom to fit the largest entity",
  1559. type: "toggle",
  1560. default: false,
  1561. get value() {
  1562. return config.autoFit;
  1563. },
  1564. set value(param) {
  1565. config.autoFit = param;
  1566. checkFitWorld();
  1567. }
  1568. },
  1569. "show-vertical-scale": {
  1570. name: "Show Vertical Scale",
  1571. desc: "Draw vertical scale marks",
  1572. type: "toggle",
  1573. default: true,
  1574. get value() {
  1575. return config.drawYAxis;
  1576. },
  1577. set value(param) {
  1578. config.drawYAxis = param;
  1579. drawScales(false);
  1580. }
  1581. },
  1582. "show-altitudes": {
  1583. name: "Show Altitudes",
  1584. desc: "Draw interesting altitudes",
  1585. type: "toggle",
  1586. default: true,
  1587. get value() {
  1588. return config.drawAltitudes;
  1589. },
  1590. set value(param) {
  1591. config.drawAltitudes = param;
  1592. drawScales(false);
  1593. }
  1594. },
  1595. "show-horizontal-scale": {
  1596. name: "Show Horiziontal Scale",
  1597. desc: "Draw horizontal scale marks",
  1598. type: "toggle",
  1599. default: false,
  1600. get value() {
  1601. return config.drawXAxis;
  1602. },
  1603. set value(param) {
  1604. config.drawXAxis = param;
  1605. drawScales(false);
  1606. }
  1607. },
  1608. "zoom-when-adding": {
  1609. name: "Zoom When Adding",
  1610. desc: "Zoom to fit when you add a new entity",
  1611. type: "toggle",
  1612. default: true,
  1613. get value() {
  1614. return config.autoFitAdd;
  1615. },
  1616. set value(param) {
  1617. config.autoFitAdd = param;
  1618. }
  1619. },
  1620. "zoom-when-sizing": {
  1621. name: "Zoom When Sizing",
  1622. desc: "Zoom to fit when you select an entity's size",
  1623. type: "toggle",
  1624. default: true,
  1625. get value() {
  1626. return config.autoFitSize;
  1627. },
  1628. set value(param) {
  1629. config.autoFitSize = param;
  1630. }
  1631. },
  1632. "units": {
  1633. name: "Default Units",
  1634. desc: "Which kind of unit to use by default",
  1635. type: "select",
  1636. default: "metric",
  1637. options: [
  1638. "metric",
  1639. "customary",
  1640. "relative"
  1641. ],
  1642. get value() {
  1643. return config.units;
  1644. },
  1645. set value(param) {
  1646. config.units = param;
  1647. }
  1648. },
  1649. "names": {
  1650. name: "Show Names",
  1651. desc: "Display names over entities",
  1652. type: "toggle",
  1653. default: true,
  1654. get value() {
  1655. return checkBodyClass("toggle-entity-name");
  1656. },
  1657. set value(param) {
  1658. toggleBodyClass("toggle-entity-name", param);
  1659. }
  1660. },
  1661. "bottom-names": {
  1662. name: "Bottom Names",
  1663. desc: "Display names at the bottom",
  1664. type: "toggle",
  1665. default: false,
  1666. get value() {
  1667. return checkBodyClass("toggle-bottom-name");
  1668. },
  1669. set value(param) {
  1670. toggleBodyClass("toggle-bottom-name", param);
  1671. }
  1672. },
  1673. "top-names": {
  1674. name: "Show Arrows",
  1675. desc: "Point to entities that are much larger than the current view",
  1676. type: "toggle",
  1677. default: false,
  1678. get value() {
  1679. return checkBodyClass("toggle-top-name");
  1680. },
  1681. set value(param) {
  1682. toggleBodyClass("toggle-top-name", param);
  1683. }
  1684. },
  1685. "height-bars": {
  1686. name: "Height Bars",
  1687. desc: "Draw dashed lines to the top of each entity",
  1688. type: "toggle",
  1689. default: false,
  1690. get value() {
  1691. return checkBodyClass("toggle-height-bars");
  1692. },
  1693. set value(param) {
  1694. toggleBodyClass("toggle-height-bars", param);
  1695. }
  1696. },
  1697. "glowing-entities": {
  1698. name: "Glowing Edges",
  1699. desc: "Makes all entities glow",
  1700. type: "toggle",
  1701. default: false,
  1702. get value() {
  1703. return checkBodyClass("toggle-entity-glow");
  1704. },
  1705. set value(param) {
  1706. toggleBodyClass("toggle-entity-glow", param);
  1707. }
  1708. },
  1709. "solid-ground": {
  1710. name: "Solid Ground",
  1711. desc: "Draw solid ground at the y=0 line",
  1712. type: "toggle",
  1713. default: true,
  1714. get value() {
  1715. return checkBodyClass("toggle-bottom-cover");
  1716. },
  1717. set value(param) {
  1718. toggleBodyClass("toggle-bottom-cover", param);
  1719. }
  1720. },
  1721. "auto-food-intake": {
  1722. name: "Estimate Food Intake",
  1723. desc: "Guess how much food creatures need, based on their mass -- 2000kcal per 150lbs",
  1724. type: "toggle",
  1725. default: false,
  1726. get value() {
  1727. return config.autoFoodIntake
  1728. },
  1729. set value(param) {
  1730. config.autoFoodIntake = param
  1731. }
  1732. },
  1733. "auto-prey-capacity": {
  1734. name: "Estimate Prey Capacity",
  1735. desc: "Guess how much prey creatures can hold, based on their mass",
  1736. type: "select",
  1737. default: "none",
  1738. options: [
  1739. "none",
  1740. "realistic",
  1741. "same-size"
  1742. ],
  1743. get value() {
  1744. return config.autoPreyCapacity;
  1745. },
  1746. set value(param) {
  1747. config.autoPreyCapacity = param;
  1748. }
  1749. },
  1750. }
  1751. function getBoundingBox(entities, margin = 0.05) {
  1752. }
  1753. function prepareSettings(userSettings) {
  1754. const menubar = document.querySelector("#settings-menu");
  1755. Object.entries(settingsData).forEach(([id, entry]) => {
  1756. const holder = document.createElement("label");
  1757. holder.classList.add("settings-holder");
  1758. const input = document.createElement("input");
  1759. input.id = "setting-" + id;
  1760. const name = document.createElement("label");
  1761. name.innerText = entry.name;
  1762. name.classList.add("settings-name");
  1763. name.setAttribute("for", input.id);
  1764. const desc = document.createElement("label");
  1765. desc.innerText = entry.desc;
  1766. desc.classList.add("settings-desc");
  1767. desc.setAttribute("for", input.id);
  1768. if (entry.type == "toggle") {
  1769. input.type = "checkbox";
  1770. input.checked = userSettings[id] === undefined ? entry.default : userSettings[id];
  1771. holder.setAttribute("for", input.id);
  1772. holder.appendChild(name);
  1773. holder.appendChild(input);
  1774. holder.appendChild(desc);
  1775. menubar.appendChild(holder);
  1776. const update = () => {
  1777. if (input.checked) {
  1778. holder.classList.add("enabled");
  1779. holder.classList.remove("disabled");
  1780. } else {
  1781. holder.classList.remove("enabled");
  1782. holder.classList.add("disabled");
  1783. }
  1784. entry.value = input.checked;
  1785. }
  1786. update();
  1787. input.addEventListener("change", update);
  1788. } else if (entry.type == "select") {
  1789. // we don't use the input element we made!
  1790. const select = document.createElement("select");
  1791. select.id = "setting-" + id;
  1792. entry.options.forEach(choice => {
  1793. const option = document.createElement("option");
  1794. option.innerText = choice;
  1795. select.appendChild(option);
  1796. })
  1797. select.value = userSettings[id] === undefined ? entry.default : userSettings[id];
  1798. holder.appendChild(name);
  1799. holder.appendChild(select);
  1800. holder.appendChild(desc);
  1801. menubar.appendChild(holder);
  1802. holder.classList.add("enabled");
  1803. const update = () => {
  1804. entry.value = select.value;
  1805. }
  1806. update();
  1807. select.addEventListener("change", update);
  1808. }
  1809. })
  1810. }
  1811. function prepareMenu() {
  1812. prepareSidebar();
  1813. updateSaveInfo();
  1814. if (checkHelpDate()) {
  1815. document.querySelector("#open-help").classList.add("highlighted");
  1816. }
  1817. }
  1818. function updateSaveInfo() {
  1819. const saves = getSaves();
  1820. const load = document.querySelector("#menu-load ~ select");
  1821. load.innerHTML = "";
  1822. saves.forEach(save => {
  1823. const option = document.createElement("option");
  1824. option.innerText = save;
  1825. option.value = save;
  1826. load.appendChild(option);
  1827. });
  1828. const del = document.querySelector("#menu-delete ~ select");
  1829. del.innerHTML = "";
  1830. saves.forEach(save => {
  1831. const option = document.createElement("option");
  1832. option.innerText = save;
  1833. option.value = save;
  1834. del.appendChild(option);
  1835. });
  1836. }
  1837. function getSaves() {
  1838. try {
  1839. const results = [];
  1840. Object.keys(localStorage).forEach(key => {
  1841. if (key.startsWith("macrovision-save-")) {
  1842. results.push(key.replace("macrovision-save-", ""));
  1843. }
  1844. })
  1845. return results;
  1846. } catch (err) {
  1847. alert("Something went wrong while loading (maybe you didn't have anything saved. Check the F12 console for the error.")
  1848. console.error(err);
  1849. return false;
  1850. }
  1851. }
  1852. function getUserSettings() {
  1853. try {
  1854. const settings = JSON.parse(localStorage.getItem("settings"));
  1855. return settings === null ? {} : settings;
  1856. } catch {
  1857. return {};
  1858. }
  1859. }
  1860. function exportUserSettings() {
  1861. const settings = {};
  1862. Object.entries(settingsData).forEach(([id, entry]) => {
  1863. settings[id] = entry.value;
  1864. });
  1865. return settings;
  1866. }
  1867. function setUserSettings(settings) {
  1868. try {
  1869. localStorage.setItem("settings", JSON.stringify(settings));
  1870. } catch {
  1871. // :(
  1872. }
  1873. }
  1874. const lastHelpChange = 1601955834693;
  1875. function checkHelpDate() {
  1876. try {
  1877. const old = localStorage.getItem("help-viewed");
  1878. if (old === null || old < lastHelpChange) {
  1879. return true;
  1880. }
  1881. return false;
  1882. } catch {
  1883. console.warn("Could not set the help-viewed date");
  1884. return false;
  1885. }
  1886. }
  1887. function setHelpDate() {
  1888. try {
  1889. localStorage.setItem("help-viewed", Date.now());
  1890. } catch {
  1891. console.warn("Could not set the help-viewed date");
  1892. }
  1893. }
  1894. function doYScroll() {
  1895. const worldHeight = config.height.toNumber("meters");
  1896. config.y += scrollDirection * worldHeight / 180;
  1897. updateSizes();
  1898. scrollDirection *= 1.05;
  1899. }
  1900. function doXScroll() {
  1901. const worldWidth = config.height.toNumber("meters") / canvasHeight * canvasWidth;
  1902. config.x += scrollDirection * worldWidth / 180 ;
  1903. updateSizes();
  1904. scrollDirection *= 1.05;
  1905. }
  1906. function doZoom() {
  1907. const oldHeight = config.height;
  1908. setWorldHeight(oldHeight, math.multiply(oldHeight, 1 + zoomDirection / 10));
  1909. zoomDirection *= 1.05;
  1910. }
  1911. function doSize() {
  1912. if (selected) {
  1913. const entity = entities[selected.dataset.key];
  1914. const oldHeight = entity.views[entity.view].height;
  1915. entity.views[entity.view].height = math.multiply(oldHeight, sizeDirection < 0 ? -1/sizeDirection : sizeDirection);
  1916. entity.dirty = true;
  1917. updateEntityOptions(entity, entity.view);
  1918. updateViewOptions(entity, entity.view);
  1919. updateSizes(true);
  1920. sizeDirection *= 1.01;
  1921. const ownHeight = entity.views[entity.view].height.toNumber("meters");
  1922. const worldHeight = config.height.toNumber("meters");
  1923. if (ownHeight > worldHeight) {
  1924. setWorldHeight(config.height, entity.views[entity.view].height)
  1925. } else if (ownHeight * 10 < worldHeight) {
  1926. setWorldHeight(config.height, math.multiply(entity.views[entity.view].height, 10));
  1927. }
  1928. }
  1929. }
  1930. document.addEventListener("DOMContentLoaded", () => {
  1931. prepareMenu();
  1932. prepareEntities();
  1933. document.querySelector("#open-help").addEventListener("click", e => {
  1934. setHelpDate();
  1935. document.querySelector("#open-help").classList.remove("highlighted");
  1936. window.open("https://www.notion.so/Macrovision-5c7f9377424743358ddf6db5671f439e", "_blank");
  1937. });
  1938. document.querySelector("#copy-screenshot").addEventListener("click", e => {
  1939. copyScreenshot();
  1940. toast("Copied to clipboard!");
  1941. });
  1942. document.querySelector("#save-screenshot").addEventListener("click", e => {
  1943. saveScreenshot();
  1944. });
  1945. document.querySelector("#open-screenshot").addEventListener("click", e => {
  1946. openScreenshot();
  1947. });
  1948. document.querySelector("#toggle-menu").addEventListener("click", e => {
  1949. const popoutMenu = document.querySelector("#sidebar-menu");
  1950. if (popoutMenu.classList.contains("visible")) {
  1951. popoutMenu.classList.remove("visible");
  1952. } else {
  1953. document.querySelectorAll(".popout-menu").forEach(menu => menu.classList.remove("visible"));
  1954. const rect = e.target.getBoundingClientRect();
  1955. popoutMenu.classList.add("visible");
  1956. popoutMenu.style.left = rect.x + rect.width + 10 + "px";
  1957. popoutMenu.style.top = rect.y + rect.height + 10 + "px";
  1958. }
  1959. e.stopPropagation();
  1960. });
  1961. document.querySelector("#sidebar-menu").addEventListener("click", e => {
  1962. e.stopPropagation();
  1963. });
  1964. document.addEventListener("click", e => {
  1965. document.querySelector("#sidebar-menu").classList.remove("visible");
  1966. });
  1967. document.querySelector("#toggle-settings").addEventListener("click", e => {
  1968. const popoutMenu = document.querySelector("#settings-menu");
  1969. if (popoutMenu.classList.contains("visible")) {
  1970. popoutMenu.classList.remove("visible");
  1971. } else {
  1972. document.querySelectorAll(".popout-menu").forEach(menu => menu.classList.remove("visible"));
  1973. const rect = e.target.getBoundingClientRect();
  1974. popoutMenu.classList.add("visible");
  1975. popoutMenu.style.left = rect.x + rect.width + 10 + "px";
  1976. popoutMenu.style.top = rect.y + rect.height + 10 + "px";
  1977. }
  1978. e.stopPropagation();
  1979. });
  1980. document.querySelector("#settings-menu").addEventListener("click", e => {
  1981. e.stopPropagation();
  1982. });
  1983. document.addEventListener("click", e => {
  1984. document.querySelector("#settings-menu").classList.remove("visible");
  1985. });
  1986. window.addEventListener("unload", () => {
  1987. saveScene("autosave");
  1988. setUserSettings(exportUserSettings());
  1989. });
  1990. document.querySelector("#options-selected-entity").addEventListener("input", e => {
  1991. if (e.target.value == "None") {
  1992. deselect()
  1993. } else {
  1994. select(document.querySelector("#entity-" + e.target.value));
  1995. }
  1996. });
  1997. document.querySelector("#menu-toggle-sidebar").addEventListener("click", e => {
  1998. const sidebar = document.querySelector("#options");
  1999. if (sidebar.classList.contains("hidden")) {
  2000. sidebar.classList.remove("hidden");
  2001. e.target.classList.remove("rotate-forward");
  2002. e.target.classList.add("rotate-backward");
  2003. } else {
  2004. sidebar.classList.add("hidden");
  2005. e.target.classList.add("rotate-forward");
  2006. e.target.classList.remove("rotate-backward");
  2007. }
  2008. handleResize();
  2009. });
  2010. document.querySelector("#menu-fullscreen").addEventListener("click", toggleFullScreen);
  2011. document.querySelector("#options-order-forward").addEventListener("click", e => {
  2012. if (selected) {
  2013. entities[selected.dataset.key].priority += 1;
  2014. }
  2015. document.querySelector("#options-order-display").innerText = entities[selected.dataset.key].priority;
  2016. updateSizes();
  2017. });
  2018. document.querySelector("#options-order-back").addEventListener("click", e => {
  2019. if (selected) {
  2020. entities[selected.dataset.key].priority -= 1;
  2021. }
  2022. document.querySelector("#options-order-display").innerText = entities[selected.dataset.key].priority;
  2023. updateSizes();
  2024. });
  2025. document.querySelector("#options-brightness-up").addEventListener("click", e => {
  2026. if (selected) {
  2027. entities[selected.dataset.key].brightness += 1;
  2028. }
  2029. document.querySelector("#options-brightness-display").innerText = entities[selected.dataset.key].brightness;
  2030. updateSizes();
  2031. });
  2032. document.querySelector("#options-brightness-down").addEventListener("click", e => {
  2033. if (selected) {
  2034. entities[selected.dataset.key].brightness = Math.max(entities[selected.dataset.key].brightness -1, 0);
  2035. }
  2036. document.querySelector("#options-brightness-display").innerText = entities[selected.dataset.key].brightness;
  2037. updateSizes();
  2038. });
  2039. document.querySelector("#options-flip").addEventListener("click", e => {
  2040. if (selected) {
  2041. selected.querySelector(".entity-image").classList.toggle("flipped");
  2042. }
  2043. document.querySelector("#options-brightness-display").innerText = entities[selected.dataset.key].brightness;
  2044. updateSizes();
  2045. });
  2046. const sceneChoices = document.querySelector("#scene-choices");
  2047. Object.entries(scenes).forEach(([id, scene]) => {
  2048. const option = document.createElement("option");
  2049. option.innerText = id;
  2050. option.value = id;
  2051. sceneChoices.appendChild(option);
  2052. });
  2053. document.querySelector("#load-scene").addEventListener("click", e => {
  2054. const chosen = sceneChoices.value;
  2055. removeAllEntities();
  2056. scenes[chosen]();
  2057. });
  2058. entityX = document.querySelector("#entities").getBoundingClientRect().x;
  2059. canvasWidth = document.querySelector("#display").clientWidth - 100;
  2060. canvasHeight = document.querySelector("#display").clientHeight - 50;
  2061. document.querySelector("#options-height-value").addEventListener("change", e => {
  2062. updateWorldHeight();
  2063. })
  2064. document.querySelector("#options-height-value").addEventListener("keydown", e => {
  2065. e.stopPropagation();
  2066. })
  2067. const unitSelector = document.querySelector("#options-height-unit");
  2068. Object.entries(unitChoices.length).forEach(([group, entries]) => {
  2069. const optGroup = document.createElement("optgroup");
  2070. optGroup.label = group;
  2071. unitSelector.appendChild(optGroup);
  2072. entries.forEach(entry => {
  2073. const option = document.createElement("option");
  2074. option.innerText = entry;
  2075. // we haven't loaded user settings yet, so we can't choose the unit just yet
  2076. unitSelector.appendChild(option);
  2077. })
  2078. });
  2079. unitSelector.addEventListener("input", e => {
  2080. checkFitWorld();
  2081. const scaleInput = document.querySelector("#options-height-value");
  2082. const newVal = math.unit(scaleInput.value, unitSelector.dataset.oldUnit).toNumber(e.target.value);
  2083. setNumericInput(scaleInput, newVal);
  2084. updateWorldHeight();
  2085. unitSelector.dataset.oldUnit = unitSelector.value;
  2086. });
  2087. param = new URL(window.location.href).searchParams.get("scene");
  2088. document.querySelector("#world").addEventListener("mousedown", e => {
  2089. // only middle mouse clicks
  2090. if (e.which == 2) {
  2091. panning = true;
  2092. panOffsetX = e.clientX;
  2093. panOffsetY = e.clientY;
  2094. Object.keys(entities).forEach(key => {
  2095. document.querySelector("#entity-" + key).classList.add("no-transition");
  2096. });
  2097. }
  2098. });
  2099. document.addEventListener("mouseup", e => {
  2100. if (e.which == 2) {
  2101. panning = false;
  2102. Object.keys(entities).forEach(key => {
  2103. document.querySelector("#entity-" + key).classList.remove("no-transition");
  2104. });
  2105. }
  2106. });
  2107. document.querySelector("#world").addEventListener("touchstart", e => {
  2108. panning = true;
  2109. panOffsetX = e.touches[0].clientX;
  2110. panOffsetY = e.touches[0].clientY;
  2111. e.preventDefault();
  2112. Object.keys(entities).forEach(key => {
  2113. document.querySelector("#entity-" + key).classList.add("no-transition");
  2114. });
  2115. });
  2116. document.querySelector("#world").addEventListener("touchend", e => {
  2117. panning = false;
  2118. Object.keys(entities).forEach(key => {
  2119. document.querySelector("#entity-" + key).classList.remove("no-transition");
  2120. });
  2121. });
  2122. document.querySelector("body").appendChild(testCtx.canvas);
  2123. updateSizes();
  2124. world.addEventListener("mousedown", e => deselect(e));
  2125. world.addEventListener("touchstart", e => deselect({
  2126. which: 1,
  2127. }));
  2128. document.querySelector("#entities").addEventListener("mousedown", deselect);
  2129. document.querySelector("#display").addEventListener("mousedown", deselect);
  2130. document.addEventListener("mouseup", e => clickUp(e));
  2131. document.addEventListener("touchend", e => {
  2132. const fakeEvent = {
  2133. target: e.target,
  2134. clientX: e.changedTouches[0].clientX,
  2135. clientY: e.changedTouches[0].clientY,
  2136. which: 1
  2137. };
  2138. clickUp(fakeEvent);
  2139. });
  2140. const viewList = document.querySelector("#entity-view");
  2141. document.querySelector("#entity-view").addEventListener("input", e => {
  2142. const entity = entities[selected.dataset.key];
  2143. entity.view = e.target.value;
  2144. const image = entities[selected.dataset.key].views[e.target.value].image;
  2145. selected.querySelector(".entity-image").src = image.source;
  2146. configViewOptions(entity, entity.view);
  2147. displayAttribution(image.source);
  2148. if (image.bottom !== undefined) {
  2149. selected.querySelector(".entity-image").style.setProperty("--offset", ((-1 + image.bottom) * 100) + "%")
  2150. } else {
  2151. selected.querySelector(".entity-image").style.setProperty("--offset", ((-1) * 100) + "%")
  2152. }
  2153. updateSizes();
  2154. updateEntityOptions(entities[selected.dataset.key], e.target.value);
  2155. updateViewOptions(entities[selected.dataset.key], e.target.value);
  2156. });
  2157. document.querySelector("#entity-view").addEventListener("input", e => {
  2158. if (viewList.options[viewList.selectedIndex].classList.contains("nsfw")) {
  2159. viewList.classList.add("nsfw");
  2160. } else {
  2161. viewList.classList.remove("nsfw");
  2162. }
  2163. })
  2164. clearViewList();
  2165. document.querySelector("#menu-clear").addEventListener("click", e => {
  2166. removeAllEntities();
  2167. });
  2168. document.querySelector("#delete-entity").disabled = true;
  2169. document.querySelector("#delete-entity").addEventListener("click", e => {
  2170. if (selected) {
  2171. removeEntity(selected);
  2172. selected = null;
  2173. }
  2174. });
  2175. document.querySelector("#menu-order-height").addEventListener("click", e => {
  2176. const order = Object.keys(entities).sort((a, b) => {
  2177. const entA = entities[a];
  2178. const entB = entities[b];
  2179. const viewA = entA.view;
  2180. const viewB = entB.view;
  2181. const heightA = entA.views[viewA].height.to("meter").value;
  2182. const heightB = entB.views[viewB].height.to("meter").value;
  2183. return heightA - heightB;
  2184. });
  2185. arrangeEntities(order);
  2186. });
  2187. // TODO: write some generic logic for this lol
  2188. document.querySelector("#scroll-left").addEventListener("mousedown", e => {
  2189. scrollDirection = -1;
  2190. clearInterval(scrollHandle);
  2191. scrollHandle = setInterval(doXScroll, 1000 / 20);
  2192. e.stopPropagation();
  2193. });
  2194. document.querySelector("#scroll-right").addEventListener("mousedown", e => {
  2195. scrollDirection = 1;
  2196. clearInterval(scrollHandle);
  2197. scrollHandle = setInterval(doXScroll, 1000 / 20);
  2198. e.stopPropagation();
  2199. });
  2200. document.querySelector("#scroll-left").addEventListener("touchstart", e => {
  2201. scrollDirection = -1;
  2202. clearInterval(scrollHandle);
  2203. scrollHandle = setInterval(doXScroll, 1000 / 20);
  2204. e.stopPropagation();
  2205. });
  2206. document.querySelector("#scroll-right").addEventListener("touchstart", e => {
  2207. scrollDirection = 1;
  2208. clearInterval(scrollHandle);
  2209. scrollHandle = setInterval(doXScroll, 1000 / 20);
  2210. e.stopPropagation();
  2211. });
  2212. document.querySelector("#scroll-up").addEventListener("mousedown", e => {
  2213. scrollDirection = 1;
  2214. clearInterval(scrollHandle);
  2215. scrollHandle = setInterval(doYScroll, 1000 / 20);
  2216. e.stopPropagation();
  2217. });
  2218. document.querySelector("#scroll-down").addEventListener("mousedown", e => {
  2219. scrollDirection = -1;
  2220. clearInterval(scrollHandle);
  2221. scrollHandle = setInterval(doYScroll, 1000 / 20);
  2222. e.stopPropagation();
  2223. });
  2224. document.querySelector("#scroll-up").addEventListener("touchstart", e => {
  2225. scrollDirection = 1;
  2226. clearInterval(scrollHandle);
  2227. scrollHandle = setInterval(doYScroll, 1000 / 20);
  2228. e.stopPropagation();
  2229. });
  2230. document.querySelector("#scroll-down").addEventListener("touchstart", e => {
  2231. scrollDirection = -1;
  2232. clearInterval(scrollHandle);
  2233. scrollHandle = setInterval(doYScroll, 1000 / 20);
  2234. e.stopPropagation();
  2235. });
  2236. document.addEventListener("mouseup", e => {
  2237. clearInterval(scrollHandle);
  2238. scrollHandle = null;
  2239. });
  2240. document.addEventListener("touchend", e => {
  2241. clearInterval(scrollHandle);
  2242. scrollHandle = null;
  2243. });
  2244. document.querySelector("#zoom-in").addEventListener("mousedown", e => {
  2245. zoomDirection = -1;
  2246. clearInterval(zoomHandle);
  2247. zoomHandle = setInterval(doZoom, 1000 / 20);
  2248. e.stopPropagation();
  2249. });
  2250. document.querySelector("#zoom-out").addEventListener("mousedown", e => {
  2251. zoomDirection = 1;
  2252. clearInterval(zoomHandle);
  2253. zoomHandle = setInterval(doZoom, 1000 / 20);
  2254. e.stopPropagation();
  2255. });
  2256. document.querySelector("#zoom-in").addEventListener("touchstart", e => {
  2257. zoomDirection = -1;
  2258. clearInterval(zoomHandle);
  2259. zoomHandle = setInterval(doZoom, 1000 / 20);
  2260. e.stopPropagation();
  2261. });
  2262. document.querySelector("#zoom-out").addEventListener("touchstart", e => {
  2263. zoomDirection = 1;
  2264. clearInterval(zoomHandle);
  2265. zoomHandle = setInterval(doZoom, 1000 / 20);
  2266. e.stopPropagation();
  2267. });
  2268. document.addEventListener("mouseup", e => {
  2269. clearInterval(zoomHandle);
  2270. zoomHandle = null;
  2271. });
  2272. document.addEventListener("touchend", e => {
  2273. clearInterval(zoomHandle);
  2274. zoomHandle = null;
  2275. });
  2276. document.querySelector("#shrink").addEventListener("mousedown", e => {
  2277. sizeDirection = -1;
  2278. clearInterval(sizeHandle);
  2279. sizeHandle = setInterval(doSize, 1000 / 20);
  2280. e.stopPropagation();
  2281. });
  2282. document.querySelector("#grow").addEventListener("mousedown", e => {
  2283. sizeDirection = 1;
  2284. clearInterval(sizeHandle);
  2285. sizeHandle = setInterval(doSize, 1000 / 20);
  2286. e.stopPropagation();
  2287. });
  2288. document.querySelector("#shrink").addEventListener("touchstart", e => {
  2289. sizeDirection = -1;
  2290. clearInterval(sizeHandle);
  2291. sizeHandle = setInterval(doSize, 1000 / 20);
  2292. e.stopPropagation();
  2293. });
  2294. document.querySelector("#grow").addEventListener("touchstart", e => {
  2295. sizeDirection = 1;
  2296. clearInterval(sizeHandle);
  2297. sizeHandle = setInterval(doSize, 1000 / 20);
  2298. e.stopPropagation();
  2299. });
  2300. document.addEventListener("mouseup", e => {
  2301. clearInterval(sizeHandle);
  2302. sizeHandle = null;
  2303. });
  2304. document.addEventListener("touchend", e => {
  2305. clearInterval(sizeHandle);
  2306. sizeHandle = null;
  2307. });
  2308. document.querySelector("#fit").addEventListener("click", e => {
  2309. if (selected) {
  2310. let targets = {};
  2311. targets[selected.dataset.key] = entities[selected.dataset.key];
  2312. fitEntities(targets);
  2313. }
  2314. });
  2315. document.querySelector("#fit").addEventListener("mousedown", e => {
  2316. e.stopPropagation();
  2317. });
  2318. document.querySelector("#fit").addEventListener("touchstart", e => {
  2319. e.stopPropagation();
  2320. });
  2321. document.querySelector("#options-world-fit").addEventListener("click", () => fitWorld(true));
  2322. document.querySelector("#options-reset-pos-x").addEventListener("click", () => { config.x = 0; updateSizes(); });
  2323. document.querySelector("#options-reset-pos-y").addEventListener("click", () => { config.y = 0; updateSizes(); });
  2324. document.addEventListener("keydown", e => {
  2325. if (e.key == "Delete") {
  2326. if (selected) {
  2327. removeEntity(selected);
  2328. selected = null;
  2329. }
  2330. }
  2331. })
  2332. document.addEventListener("keydown", e => {
  2333. if (e.key == "Shift") {
  2334. shiftHeld = true;
  2335. e.preventDefault();
  2336. } else if (e.key == "Alt") {
  2337. altHeld = true;
  2338. movingInBounds = false; // don't snap the object back in bounds when we let go
  2339. e.preventDefault();
  2340. }
  2341. });
  2342. document.addEventListener("keyup", e => {
  2343. if (e.key == "Shift") {
  2344. shiftHeld = false;
  2345. e.preventDefault();
  2346. } else if (e.key == "Alt") {
  2347. altHeld = false;
  2348. e.preventDefault();
  2349. }
  2350. });
  2351. window.addEventListener("resize", handleResize);
  2352. // TODO: further investigate why the tool initially starts out with wrong
  2353. // values under certain circumstances (seems to be narrow aspect ratios -
  2354. // maybe the menu bar is animating when it shouldn't)
  2355. setTimeout(handleResize, 250);
  2356. setTimeout(handleResize, 500);
  2357. setTimeout(handleResize, 750);
  2358. setTimeout(handleResize, 1000);
  2359. document.querySelector("#menu-permalink").addEventListener("click", e => {
  2360. linkScene();
  2361. });
  2362. document.querySelector("#menu-export").addEventListener("click", e => {
  2363. copyScene();
  2364. });
  2365. document.querySelector("#menu-import").addEventListener("click", e => {
  2366. pasteScene();
  2367. });
  2368. document.querySelector("#menu-save").addEventListener("click", e => {
  2369. const name = document.querySelector("#menu-save ~ input").value;
  2370. if (/\S/.test(name)) {
  2371. saveScene(name);
  2372. }
  2373. updateSaveInfo();
  2374. });
  2375. document.querySelector("#menu-load").addEventListener("click", e => {
  2376. const name = document.querySelector("#menu-load ~ select").value;
  2377. if (/\S/.test(name)) {
  2378. loadScene(name);
  2379. }
  2380. });
  2381. document.querySelector("#menu-delete").addEventListener("click", e => {
  2382. const name = document.querySelector("#menu-delete ~ select").value;
  2383. if (/\S/.test(name)) {
  2384. deleteScene(name);
  2385. }
  2386. });
  2387. document.querySelector("#menu-load-autosave").addEventListener("click", e => {
  2388. loadScene("autosave");
  2389. });
  2390. document.querySelector("#menu-add-image").addEventListener("click", e => {
  2391. document.querySelector("#file-upload-picker").click();
  2392. });
  2393. document.querySelector("#file-upload-picker").addEventListener("change", e => {
  2394. if (e.target.files.length > 0) {
  2395. for (let i=0; i<e.target.files.length; i++) {
  2396. customEntityFromFile(e.target.files[i]);
  2397. }
  2398. }
  2399. })
  2400. document.addEventListener("paste", e => {
  2401. let index = 0;
  2402. let item = null;
  2403. let found = false;
  2404. for (; index < e.clipboardData.items.length; index++) {
  2405. item = e.clipboardData.items[index];
  2406. if (item.type == "image/png") {
  2407. found = true;
  2408. break;
  2409. }
  2410. }
  2411. if (!found) {
  2412. return;
  2413. }
  2414. let url = null;
  2415. const file = item.getAsFile();
  2416. customEntityFromFile(file);
  2417. });
  2418. document.querySelector("#world").addEventListener("dragover", e => {
  2419. e.preventDefault();
  2420. })
  2421. document.querySelector("#world").addEventListener("drop", e => {
  2422. e.preventDefault();
  2423. if (e.dataTransfer.files.length > 0) {
  2424. let entX = document.querySelector("#entities").getBoundingClientRect().x;
  2425. let entY = document.querySelector("#entities").getBoundingClientRect().y;
  2426. let coords = pix2pos({x: e.clientX-entX, y: e.clientY-entY});
  2427. customEntityFromFile(e.dataTransfer.files[0], coords.x, coords.y);
  2428. }
  2429. })
  2430. clearEntityOptions();
  2431. clearViewOptions();
  2432. clearAttribution();
  2433. // we do this last because configuring settings can cause things
  2434. // to happen (e.g. auto-fit)
  2435. prepareSettings(getUserSettings());
  2436. // now that we have this loaded, we can set it
  2437. unitSelector.dataset.oldUnit = defaultUnits.length[config.units];
  2438. document.querySelector("#options-height-unit").value = defaultUnits.length[config.units];
  2439. // ...and then update the world height by setting off an input event
  2440. document.querySelector("#options-height-unit").dispatchEvent(new Event('input', {
  2441. }));
  2442. if (param === null) {
  2443. scenes["Empty"]();
  2444. }
  2445. else {
  2446. try {
  2447. const data = JSON.parse(b64DecodeUnicode(param));
  2448. if (data.entities === undefined) {
  2449. return;
  2450. }
  2451. if (data.world === undefined) {
  2452. return;
  2453. }
  2454. importScene(data);
  2455. } catch (err) {
  2456. console.error(err);
  2457. scenes["Empty"]();
  2458. // probably wasn't valid data
  2459. }
  2460. }
  2461. document.querySelector("#world").addEventListener("wheel", e => {
  2462. if (shiftHeld) {
  2463. if (selected) {
  2464. const dir = e.deltaY > 0 ? 10 / 11 : 11 / 10;
  2465. const entity = entities[selected.dataset.key];
  2466. entity.views[entity.view].height = math.multiply(entity.views[entity.view].height, dir);
  2467. entity.dirty = true;
  2468. updateEntityOptions(entity, entity.view);
  2469. updateViewOptions(entity, entity.view);
  2470. updateSizes(true);
  2471. } else {
  2472. const worldWidth = config.height.toNumber("meters") / canvasHeight * canvasWidth;
  2473. config.x += (e.deltaY > 0 ? 1 : -1) * worldWidth / 20 ;
  2474. updateSizes();
  2475. updateSizes();
  2476. }
  2477. } else {
  2478. if (config.autoFit) {
  2479. toastRateLimit("Zoom is locked! Check Settings to disable.", "zoom-lock", 1000);
  2480. } else {
  2481. const dir = e.deltaY < 0 ? 10 / 11 : 11 / 10;
  2482. const change = config.height.toNumber("meters") - math.multiply(config.height, dir).toNumber("meters");
  2483. if (!config.lockYAxis) {
  2484. config.y += change / 2;
  2485. }
  2486. setWorldHeight(config.height, math.multiply(config.height, dir));
  2487. updateWorldOptions();
  2488. }
  2489. }
  2490. checkFitWorld();
  2491. })
  2492. });
  2493. function customEntityFromFile(file, x=0.5, y=0.5) {
  2494. file.arrayBuffer().then(buf => {
  2495. arr = new Uint8Array(buf);
  2496. blob = new Blob([arr], {type: file.type });
  2497. url = window.URL.createObjectURL(blob)
  2498. makeCustomEntity(url, x, y);
  2499. });
  2500. }
  2501. function makeCustomEntity(url, x=0.5, y=0.5) {
  2502. const maker = createEntityMaker(
  2503. {
  2504. name: "Custom Entity"
  2505. },
  2506. {
  2507. custom: {
  2508. attributes: {
  2509. height: {
  2510. name: "Height",
  2511. power: 1,
  2512. type: "length",
  2513. base: math.unit(6, "feet")
  2514. }
  2515. },
  2516. image: {
  2517. source: url
  2518. },
  2519. name: "Image",
  2520. info: {},
  2521. rename: false
  2522. }
  2523. },
  2524. []
  2525. );
  2526. const entity = maker.constructor();
  2527. entity.scale = config.height.toNumber("feet") / 20;
  2528. entity.ephemeral = true;
  2529. displayEntity(entity, "custom", x, y, true, true);
  2530. }
  2531. const filterDefs = {
  2532. none: {
  2533. id: "none",
  2534. name: "No Filter",
  2535. extract: maker => [],
  2536. render: name => name,
  2537. sort: (tag1, tag2) => tag1[1].localeCompare(tag2[1])
  2538. },
  2539. author: {
  2540. id: "author",
  2541. name: "Authors",
  2542. extract: maker => maker.authors ? maker.authors : [],
  2543. render: author => attributionData.people[author].name,
  2544. sort: (tag1, tag2) => tag1[1].localeCompare(tag2[1])
  2545. },
  2546. owner: {
  2547. id: "owner",
  2548. name: "Owners",
  2549. extract: maker => maker.owners ? maker.owners : [],
  2550. render: owner => attributionData.people[owner].name,
  2551. sort: (tag1, tag2) => tag1[1].localeCompare(tag2[1])
  2552. },
  2553. species: {
  2554. id: "species",
  2555. name: "Species",
  2556. extract: maker => maker.info && maker.info.species ? getSpeciesInfo(maker.info.species) : [],
  2557. render: species => speciesData[species].name,
  2558. sort: (tag1, tag2) => tag1[1].localeCompare(tag2[1])
  2559. },
  2560. tags: {
  2561. id: "tags",
  2562. name: "Tags",
  2563. extract: maker => maker.info && maker.info.tags ? maker.info.tags : [],
  2564. render: tag => tagDefs[tag],
  2565. sort: (tag1, tag2) => tag1[1].localeCompare(tag2[1])
  2566. },
  2567. size: {
  2568. id: "size",
  2569. name: "Normal Size",
  2570. extract: maker => maker.sizes && maker.sizes.length > 0 ? Array.from(maker.sizes.reduce((result, size) => {
  2571. if (result && !size.default) {
  2572. return result;
  2573. }
  2574. let meters = size.height.toNumber("meters");
  2575. if (meters < 1e-1) {
  2576. return ["micro"];
  2577. } else if (meters < 1e1) {
  2578. return ["moderate"];
  2579. } else {
  2580. return ["macro"];
  2581. }
  2582. }, null)) : [],
  2583. render: tag => { return {
  2584. "micro": "Micro",
  2585. "moderate": "Moderate",
  2586. "macro": "Macro"
  2587. }[tag]},
  2588. sort: (tag1, tag2) => {
  2589. const order = {
  2590. "micro": 0,
  2591. "moderate": 1,
  2592. "macro": 2
  2593. };
  2594. return order[tag1[0]] - order[tag2[0]];
  2595. }
  2596. },
  2597. allSizes: {
  2598. id: "allSizes",
  2599. name: "Possible Size",
  2600. extract: maker => maker.sizes ? Array.from(maker.sizes.reduce((set, size) => {
  2601. const height = size.height;
  2602. let result = Object.entries(sizeCategories).reduce((result, [name, value]) => {
  2603. if (result) {
  2604. return result;
  2605. } else {
  2606. if (math.compare(height, value) <= 0) {
  2607. return name;
  2608. }
  2609. }
  2610. }, null);
  2611. set.add(result ? result : "infinite");
  2612. return set;
  2613. }, new Set())) : [],
  2614. render: tag => tag[0].toUpperCase() + tag.slice(1),
  2615. sort: (tag1, tag2) => {
  2616. const order = [
  2617. "atomic", "microscopic", "tiny", "small", "moderate", "large", "macro", "megamacro", "planetary", "stellar",
  2618. "galactic", "universal", "omniversal", "infinite"
  2619. ]
  2620. return order.indexOf(tag1[0]) - order.indexOf(tag2[0]);
  2621. }
  2622. }
  2623. }
  2624. const sizeCategories = {
  2625. "atomic": math.unit(100, "angstroms"),
  2626. "microscopic": math.unit(100, "micrometers"),
  2627. "tiny": math.unit(100, "millimeters"),
  2628. "small": math.unit(1, "meter"),
  2629. "moderate": math.unit(3, "meters"),
  2630. "large": math.unit(10, "meters"),
  2631. "macro": math.unit(300, "meters"),
  2632. "megamacro": math.unit(1000, "kilometers"),
  2633. "planetary": math.unit(10, "earths"),
  2634. "stellar": math.unit(10, "solarradii"),
  2635. "galactic": math.unit(10, "galaxies"),
  2636. "universal": math.unit(10, "universes"),
  2637. "omniversal": math.unit(10, "multiverses")
  2638. };
  2639. function prepareEntities() {
  2640. availableEntities["buildings"] = makeBuildings();
  2641. availableEntities["characters"] = makeCharacters();
  2642. availableEntities["creatures"] = makeCreatures();
  2643. availableEntities["dildos"] = makeDildos();
  2644. availableEntities["fiction"] = makeFiction();
  2645. availableEntities["food"] = makeFood();
  2646. availableEntities["landmarks"] = makeLandmarks();
  2647. availableEntities["naturals"] = makeNaturals();
  2648. availableEntities["objects"] = makeObjects();
  2649. availableEntities["pokemon"] = makePokemon();
  2650. availableEntities["real-buildings"] = makeRealBuildings();
  2651. availableEntities["real-terrain"] = makeRealTerrains();
  2652. availableEntities["species"] = makeSpecies();
  2653. availableEntities["vehicles"] = makeVehicles();
  2654. availableEntities["characters"].sort((x, y) => {
  2655. return x.name.toLowerCase() < y.name.toLowerCase() ? -1 : 1
  2656. });
  2657. const holder = document.querySelector("#spawners");
  2658. const filterHolder = document.querySelector("#filters");
  2659. const categorySelect = document.createElement("select");
  2660. categorySelect.id = "category-picker";
  2661. const filterSelect = document.createElement("select");
  2662. filterSelect.id = "filter-picker";
  2663. holder.appendChild(categorySelect);
  2664. filterHolder.appendChild(filterSelect);
  2665. const filterSets = {};
  2666. Object.values(filterDefs).forEach(filter => {
  2667. filterSets[filter.id] = new Set();
  2668. })
  2669. Object.entries(availableEntities).forEach(([category, entityList]) => {
  2670. const select = document.createElement("select");
  2671. select.id = "create-entity-" + category;
  2672. select.classList.add("entity-select");
  2673. for (let i = 0; i < entityList.length; i++) {
  2674. const entity = entityList[i];
  2675. const option = document.createElement("option");
  2676. option.value = i;
  2677. option.innerText = entity.name;
  2678. select.appendChild(option);
  2679. if (entity.nsfw) {
  2680. option.classList.add("nsfw");
  2681. }
  2682. Object.values(filterDefs).forEach(filter => {
  2683. filter.extract(entity).forEach(result => {
  2684. filterSets[filter.id].add(result);
  2685. });
  2686. });
  2687. availableEntitiesByName[entity.name] = entity;
  2688. };
  2689. select.addEventListener("change", e => {
  2690. if (select.options[select.selectedIndex].classList.contains("nsfw")) {
  2691. select.classList.add("nsfw");
  2692. } else {
  2693. select.classList.remove("nsfw");
  2694. }
  2695. // preload the entity's first image
  2696. const entity = entityList[select.selectedIndex].constructor();
  2697. let img = new Image();
  2698. img.src = entity.currentView.image.source;
  2699. })
  2700. const button = document.createElement("button");
  2701. button.id = "create-entity-" + category + "-button";
  2702. button.classList.add("entity-button");
  2703. button.innerHTML = "<i class=\"far fa-plus-square\"></i>";
  2704. button.addEventListener("click", e => {
  2705. const newEntity = entityList[select.value].constructor()
  2706. displayEntity(newEntity, newEntity.defaultView, config.x, config.y + (config.lockYAxis ? 0 : config.height.toNumber("meters")/2), true, true);
  2707. });
  2708. const categoryOption = document.createElement("option");
  2709. categoryOption.value = category
  2710. categoryOption.innerText = category;
  2711. if (category == "characters") {
  2712. categoryOption.selected = true;
  2713. select.classList.add("category-visible");
  2714. button.classList.add("category-visible");
  2715. }
  2716. categorySelect.appendChild(categoryOption);
  2717. holder.appendChild(select);
  2718. holder.appendChild(button);
  2719. });
  2720. Object.values(filterDefs).forEach(filter => {
  2721. const option = document.createElement("option");
  2722. option.innerText = filter.name;
  2723. option.value = filter.id;
  2724. filterSelect.appendChild(option);
  2725. const filterNameSelect = document.createElement("select");
  2726. filterNameSelect.classList.add("filter-select");
  2727. filterNameSelect.id = "filter-" + filter.id;
  2728. filterHolder.appendChild(filterNameSelect);
  2729. const button = document.createElement("button");
  2730. button.classList.add("filter-button");
  2731. button.id = "create-filtered-" + filter.id + "-button";
  2732. filterHolder.appendChild(button);
  2733. const counter = document.createElement("div");
  2734. counter.classList.add("button-counter");
  2735. counter.innerText = "10";
  2736. button.appendChild(counter);
  2737. const i = document.createElement("i");
  2738. i.classList.add("fas");
  2739. i.classList.add("fa-plus");
  2740. button.appendChild(i);
  2741. button.addEventListener("click", e => {
  2742. const makers = Array.from(document.querySelector(".entity-select.category-visible")).filter(element => !element.classList.contains("filtered"));
  2743. const count = makers.length + 2;
  2744. let index = 1;
  2745. if (makers.length > 50) {
  2746. if (!confirm("Really spawn " + makers.length + " things at once?")) {
  2747. return;
  2748. }
  2749. }
  2750. const worldWidth = config.height.toNumber("meters") / canvasHeight * canvasWidth;
  2751. const spawned = makers.map(element => {
  2752. const category = document.querySelector("#category-picker").value;
  2753. const maker = availableEntities[category][element.value];
  2754. const entity = maker.constructor()
  2755. displayEntity(entity, entity.view, -worldWidth * 0.45 + config.x + worldWidth * 0.9 * index / (count - 1), config.y);
  2756. index += 1;
  2757. return entityIndex - 1;
  2758. });
  2759. updateSizes(true);
  2760. if (config.autoFitAdd) {
  2761. let targets = {};
  2762. spawned.forEach(key => {
  2763. targets[key] = entities[key];
  2764. })
  2765. fitEntities(targets);
  2766. }
  2767. });
  2768. Array.from(filterSets[filter.id]).map(name => [name, filter.render(name)]).sort(filterDefs[filter.id].sort).forEach(name => {
  2769. const option = document.createElement("option");
  2770. option.innerText = name[1];
  2771. option.value = name[0];
  2772. filterNameSelect.appendChild(option);
  2773. });
  2774. filterNameSelect.addEventListener("change", e => {
  2775. updateFilter();
  2776. });
  2777. });
  2778. console.log("Loaded " + Object.keys(availableEntitiesByName).length + " entities");
  2779. categorySelect.addEventListener("input", e => {
  2780. const oldSelect = document.querySelector(".entity-select.category-visible");
  2781. oldSelect.classList.remove("category-visible");
  2782. const oldButton = document.querySelector(".entity-button.category-visible");
  2783. oldButton.classList.remove("category-visible");
  2784. const newSelect = document.querySelector("#create-entity-" + e.target.value);
  2785. newSelect.classList.add("category-visible");
  2786. const newButton = document.querySelector("#create-entity-" + e.target.value + "-button");
  2787. newButton.classList.add("category-visible");
  2788. recomputeFilters();
  2789. updateFilter();
  2790. });
  2791. recomputeFilters();
  2792. filterSelect.addEventListener("input", e => {
  2793. const oldSelect = document.querySelector(".filter-select.category-visible");
  2794. if (oldSelect)
  2795. oldSelect.classList.remove("category-visible");
  2796. const newSelect = document.querySelector("#filter-" + e.target.value);
  2797. if (newSelect && e.target.value != "none")
  2798. newSelect.classList.add("category-visible");
  2799. updateFilter();
  2800. });
  2801. }
  2802. // Only display authors and owners if they appear
  2803. // somewhere in the current entity list
  2804. function recomputeFilters() {
  2805. const category = document.querySelector("#category-picker").value;
  2806. const filterSets = {};
  2807. Object.values(filterDefs).forEach(filter => {
  2808. filterSets[filter.id] = new Set();
  2809. });
  2810. document.querySelectorAll(".entity-select.category-visible > option").forEach(element => {
  2811. const entity = availableEntities[category][element.value];
  2812. Object.values(filterDefs).forEach(filter => {
  2813. filter.extract(entity).forEach(result => {
  2814. filterSets[filter.id].add(result);
  2815. });
  2816. });
  2817. });
  2818. Object.values(filterDefs).forEach(filter => {
  2819. // always show the "none" option
  2820. let found = filter.id == "none";
  2821. document.querySelectorAll("#filter-" + filter.id + " > option").forEach(element => {
  2822. if (filterSets[filter.id].has(element.value) || filter.id == "none") {
  2823. element.classList.remove("filtered");
  2824. element.disabled = false;
  2825. found = true;
  2826. } else {
  2827. element.classList.add("filtered");
  2828. element.disabled = true;
  2829. }
  2830. });
  2831. const filterOption = document.querySelector("#filter-picker > option[value='" + filter.id + "']");
  2832. if (found) {
  2833. filterOption.classList.remove("filtered");
  2834. filterOption.disabled = false;
  2835. } else {
  2836. filterOption.classList.add("filtered");
  2837. filterOption.disabled = true;
  2838. }
  2839. });
  2840. document.querySelector("#filter-picker").value = "none";
  2841. document.querySelector("#filter-picker").dispatchEvent(new Event("input"));
  2842. }
  2843. function updateFilter() {
  2844. const category = document.querySelector("#category-picker").value;
  2845. const type = document.querySelector("#filter-picker").value;
  2846. const filterKeySelect = document.querySelector(".filter-select.category-visible");
  2847. clearFilter();
  2848. if (!filterKeySelect) {
  2849. return;
  2850. }
  2851. const key = filterKeySelect.value;
  2852. let current = document.querySelector(".entity-select.category-visible").value;
  2853. let replace = false;
  2854. let first = null;
  2855. let count = 0;
  2856. document.querySelectorAll(".entity-select.category-visible > option").forEach(element => {
  2857. let keep = type == "none";
  2858. if (filterDefs[type].extract(availableEntities[category][element.value]).indexOf(key) >= 0) {
  2859. keep = true;
  2860. }
  2861. if (!keep) {
  2862. element.classList.add("filtered");
  2863. element.disabled = true;
  2864. if (current == element.value) {
  2865. replace = true;
  2866. }
  2867. } else {
  2868. count += 1;
  2869. if (!first) {
  2870. first = element.value;
  2871. }
  2872. }
  2873. });
  2874. const button = document.querySelector(".filter-select.category-visible + button");
  2875. if (button) {
  2876. button.querySelector(".button-counter").innerText = count;
  2877. }
  2878. if (replace) {
  2879. document.querySelector(".entity-select.category-visible").value = first;
  2880. document.querySelector("#create-entity-" + category).dispatchEvent(new Event("change"));
  2881. }
  2882. }
  2883. function clearFilter() {
  2884. document.querySelectorAll(".entity-select.category-visible > option").forEach(element => {
  2885. element.classList.remove("filtered");
  2886. element.disabled = false;
  2887. });
  2888. }
  2889. document.addEventListener("mousemove", (e) => {
  2890. if (clicked) {
  2891. let position = pix2pos({ x: e.clientX - dragOffsetX, y: e.clientY - dragOffsetY });
  2892. if (movingInBounds) {
  2893. position = snapPos(position);
  2894. } else {
  2895. let x = e.clientX - dragOffsetX;
  2896. let y = e.clientY - dragOffsetY;
  2897. if (x >= 0 && x <= canvasWidth && y >= 0 && y <= canvasHeight) {
  2898. movingInBounds = true;
  2899. }
  2900. }
  2901. clicked.dataset.x = position.x;
  2902. clicked.dataset.y = position.y;
  2903. updateEntityElement(entities[clicked.dataset.key], clicked);
  2904. if (hoveringInDeleteArea(e)) {
  2905. document.querySelector("#menubar").classList.add("hover-delete");
  2906. } else {
  2907. document.querySelector("#menubar").classList.remove("hover-delete");
  2908. }
  2909. }
  2910. if (panning && panReady) {
  2911. const worldWidth = config.height.toNumber("meters") / canvasHeight * canvasWidth;
  2912. const worldHeight = config.height.toNumber("meters");
  2913. config.x -= (e.clientX - panOffsetX) / canvasWidth * worldWidth;
  2914. config.y += (e.clientY - panOffsetY) / canvasHeight * worldHeight;
  2915. panOffsetX = e.clientX;
  2916. panOffsetY = e.clientY;
  2917. updateSizes();
  2918. panReady = false;
  2919. setTimeout(() => panReady=true, 1000/120);
  2920. }
  2921. });
  2922. document.addEventListener("touchmove", (e) => {
  2923. if (clicked) {
  2924. e.preventDefault();
  2925. let x = e.touches[0].clientX;
  2926. let y = e.touches[0].clientY;
  2927. const position = snapPos(pix2pos({ x: x - dragOffsetX, y: y - dragOffsetY }));
  2928. clicked.dataset.x = position.x;
  2929. clicked.dataset.y = position.y;
  2930. updateEntityElement(entities[clicked.dataset.key], clicked);
  2931. // what a hack
  2932. // I should centralize this 'fake event' creation...
  2933. if (hoveringInDeleteArea({ clientY: y })) {
  2934. document.querySelector("#menubar").classList.add("hover-delete");
  2935. } else {
  2936. document.querySelector("#menubar").classList.remove("hover-delete");
  2937. }
  2938. }
  2939. if (panning && panReady) {
  2940. const worldWidth = config.height.toNumber("meters") / canvasHeight * canvasWidth;
  2941. const worldHeight = config.height.toNumber("meters");
  2942. config.x -= (e.touches[0].clientX - panOffsetX) / canvasWidth * worldWidth;
  2943. config.y += (e.touches[0].clientY - panOffsetY) / canvasHeight * worldHeight;
  2944. panOffsetX = e.touches[0].clientX;
  2945. panOffsetY = e.touches[0].clientY;
  2946. updateSizes();
  2947. panReady = false;
  2948. setTimeout(() => panReady=true, 1000/60);
  2949. }
  2950. }, { passive: false });
  2951. function checkFitWorld() {
  2952. if (config.autoFit) {
  2953. fitWorld();
  2954. return true;
  2955. }
  2956. return false;
  2957. }
  2958. function fitWorld(manual = false, factor = 1.1) {
  2959. if (Object.keys(entities).length > 0) {
  2960. fitEntities(entities, factor);
  2961. }
  2962. }
  2963. function fitEntities(targetEntities, manual = false, factor = 1.1) {
  2964. let minX = Infinity;
  2965. let maxX = -Infinity;
  2966. let minY = Infinity;
  2967. let maxY = -Infinity;
  2968. let count = 0;
  2969. const worldWidth = config.height.toNumber("meters") / canvasHeight * canvasWidth;
  2970. const worldHeight = config.height.toNumber("meters");
  2971. Object.entries(targetEntities).forEach(([key, entity]) => {
  2972. const view = entity.view;
  2973. let extra = entity.views[view].image.extra;
  2974. extra = extra === undefined ? 1 : extra;
  2975. const image = document.querySelector("#entity-" + key + " > .entity-image");
  2976. const x = parseFloat(document.querySelector("#entity-" + key).dataset.x);
  2977. let width = image.width;
  2978. let height = image.height;
  2979. // only really relevant if the images haven't loaded in yet
  2980. if (height == 0) {
  2981. height = 100;
  2982. }
  2983. if (width == 0) {
  2984. width = height;
  2985. }
  2986. const xBottom = x - entity.views[view].height.toNumber("meters") * width / height / 2;
  2987. const xTop = x + entity.views[view].height.toNumber("meters") * width / height / 2;
  2988. const y = parseFloat(document.querySelector("#entity-" + key).dataset.y);
  2989. const yBottom = y;
  2990. const yTop = entity.views[view].height.toNumber("meters") + yBottom;
  2991. minX = Math.min(minX, xBottom);
  2992. maxX = Math.max(maxX, xTop);
  2993. minY = Math.min(minY, yBottom);
  2994. maxY = Math.max(maxY, yTop);
  2995. count += 1;
  2996. });
  2997. if (config.lockYAxis) {
  2998. minY = 0;
  2999. }
  3000. let ySize = (maxY - minY) * factor;
  3001. let xSize = (maxX - minX) * factor;
  3002. if (xSize / ySize > worldWidth / worldHeight) {
  3003. ySize *= ((xSize / ySize) / (worldWidth / worldHeight));
  3004. }
  3005. config.x = (maxX + minX) / 2;
  3006. config.y = minY;
  3007. height = math.unit(ySize, "meter")
  3008. setWorldHeight(config.height, math.multiply(height, factor));
  3009. }
  3010. // TODO why am I doing this
  3011. function updateWorldHeight() {
  3012. const unit = document.querySelector("#options-height-unit").value;
  3013. const value = Math.max(0.000000001, document.querySelector("#options-height-value").value);
  3014. const oldHeight = config.height;
  3015. setWorldHeight(oldHeight, math.unit(value, unit));
  3016. }
  3017. function setWorldHeight(oldHeight, newHeight) {
  3018. worldSizeDirty = true;
  3019. config.height = newHeight.to(document.querySelector("#options-height-unit").value)
  3020. const unit = document.querySelector("#options-height-unit").value;
  3021. setNumericInput(document.querySelector("#options-height-value"), config.height.toNumber(unit));
  3022. Object.entries(entities).forEach(([key, entity]) => {
  3023. const element = document.querySelector("#entity-" + key);
  3024. let newPosition;
  3025. if (altHeld) {
  3026. newPosition = adjustAbs({ x: element.dataset.x, y: element.dataset.y }, oldHeight, config.height);
  3027. } else {
  3028. newPosition = { x: element.dataset.x, y: element.dataset.y };
  3029. }
  3030. element.dataset.x = newPosition.x;
  3031. element.dataset.y = newPosition.y;
  3032. });
  3033. updateSizes();
  3034. }
  3035. function loadScene(name = "default") {
  3036. if (name === "") {
  3037. name = "default"
  3038. }
  3039. try {
  3040. const data = JSON.parse(localStorage.getItem("macrovision-save-" + name));
  3041. if (data === null) {
  3042. console.error("Couldn't load " + name)
  3043. return false;
  3044. }
  3045. importScene(data);
  3046. toast("Loaded " + name);
  3047. return true;
  3048. } catch (err) {
  3049. alert("Something went wrong while loading (maybe you didn't have anything saved. Check the F12 console for the error.")
  3050. console.error(err);
  3051. return false;
  3052. }
  3053. }
  3054. function saveScene(name = "default") {
  3055. try {
  3056. const string = JSON.stringify(exportScene());
  3057. localStorage.setItem("macrovision-save-" + name, string);
  3058. toast("Saved as " + name);
  3059. } catch (err) {
  3060. alert("Something went wrong while saving (maybe I don't have localStorage permissions, or exporting failed). Check the F12 console for the error.")
  3061. console.error(err);
  3062. }
  3063. }
  3064. function deleteScene(name = "default") {
  3065. if (confirm("Really delete the " + name + " scene?")) {
  3066. try {
  3067. localStorage.removeItem("macrovision-save-" + name)
  3068. toast("Deleted " + name);
  3069. } catch (err) {
  3070. console.error(err);
  3071. }
  3072. }
  3073. updateSaveInfo();
  3074. }
  3075. function exportScene() {
  3076. const results = {};
  3077. results.entities = [];
  3078. Object.entries(entities).filter(([key, entity]) => entity.ephemeral !== true).forEach(([key, entity]) => {
  3079. const element = document.querySelector("#entity-" + key);
  3080. results.entities.push({
  3081. name: entity.identifier,
  3082. customName: entity.name,
  3083. scale: entity.scale,
  3084. view: entity.view,
  3085. x: element.dataset.x,
  3086. y: element.dataset.y,
  3087. priority: entity.priority,
  3088. brightness: entity.brightness
  3089. });
  3090. });
  3091. const unit = document.querySelector("#options-height-unit").value;
  3092. results.world = {
  3093. height: config.height.toNumber(unit),
  3094. unit: unit,
  3095. x: config.x,
  3096. y: config.y
  3097. }
  3098. results.version = migrationDefs.length;
  3099. return results;
  3100. }
  3101. // btoa doesn't like anything that isn't ASCII
  3102. // great
  3103. // thanks to https://stackoverflow.com/questions/30106476/using-javascripts-atob-to-decode-base64-doesnt-properly-decode-utf-8-strings
  3104. // for providing an alternative
  3105. function b64EncodeUnicode(str) {
  3106. // first we use encodeURIComponent to get percent-encoded UTF-8,
  3107. // then we convert the percent encodings into raw bytes which
  3108. // can be fed into btoa.
  3109. return btoa(encodeURIComponent(str).replace(/%([0-9A-F]{2})/g,
  3110. function toSolidBytes(match, p1) {
  3111. return String.fromCharCode('0x' + p1);
  3112. }));
  3113. }
  3114. function b64DecodeUnicode(str) {
  3115. // Going backwards: from bytestream, to percent-encoding, to original string.
  3116. return decodeURIComponent(atob(str).split('').map(function (c) {
  3117. return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
  3118. }).join(''));
  3119. }
  3120. function linkScene() {
  3121. loc = new URL(window.location);
  3122. const link = loc.protocol + "//" + loc.host + loc.pathname + "?scene=" + b64EncodeUnicode(JSON.stringify(exportScene()));
  3123. window.history.replaceState(null, "Macrovision", link);
  3124. navigator.clipboard.writeText(link);
  3125. toast("Copied permalink to clipboard");
  3126. }
  3127. function copyScene() {
  3128. const results = exportScene();
  3129. navigator.clipboard.writeText(JSON.stringify(results));
  3130. }
  3131. function pasteScene() {
  3132. try {
  3133. navigator.clipboard.readText().then(text => {
  3134. const data = JSON.parse(text);
  3135. if (data.entities === undefined) {
  3136. return;
  3137. }
  3138. if (data.world === undefined) {
  3139. return;
  3140. }
  3141. importScene(data);
  3142. }).catch(err => alert(err));
  3143. } catch (err) {
  3144. console.error(err);
  3145. // probably wasn't valid data
  3146. }
  3147. }
  3148. // TODO - don't just search through every single entity
  3149. // probably just have a way to do lookups directly
  3150. function findEntity(name) {
  3151. return availableEntitiesByName[name];
  3152. }
  3153. const migrationDefs = [
  3154. /*
  3155. Migration: 0 -> 1
  3156. Adds x and y coordinates for the camera
  3157. */
  3158. data => {
  3159. data.world.x = 0;
  3160. data.world.y = 0;
  3161. },
  3162. /*
  3163. Migration: 1 -> 2
  3164. Adds priority and brightness to each entity
  3165. */
  3166. data => {
  3167. data.entities.forEach(entity => {
  3168. entity.priority = 0;
  3169. entity.brightness = 1;
  3170. });
  3171. },
  3172. /*
  3173. Migration: 2 -> 3
  3174. Custom names are exported
  3175. */
  3176. data => {
  3177. data.entities.forEach(entity => {
  3178. entity.customName = entity.name
  3179. });
  3180. }
  3181. ]
  3182. function migrateScene(data) {
  3183. if (data.version === undefined) {
  3184. alert("This save was created before save versions were tracked. The scene may import incorrectly.");
  3185. console.trace()
  3186. data.version = 0;
  3187. } else if (data.version < migrationDefs.length) {
  3188. migrationDefs[data.version](data);
  3189. data.version += 1;
  3190. migrateScene(data);
  3191. }
  3192. }
  3193. function importScene(data) {
  3194. removeAllEntities();
  3195. migrateScene(data);
  3196. data.entities.forEach(entityInfo => {
  3197. const entity = findEntity(entityInfo.name).constructor();
  3198. entity.name = entityInfo.customName;
  3199. entity.scale = entityInfo.scale;
  3200. entity.priority = entityInfo.priority;
  3201. entity.brightness = entityInfo.brightness;
  3202. displayEntity(entity, entityInfo.view, entityInfo.x, entityInfo.y);
  3203. });
  3204. config.height = math.unit(data.world.height, data.world.unit);
  3205. config.x = data.world.x;
  3206. config.y = data.world.y;
  3207. const height = math.unit(data.world.height, data.world.unit).toNumber(defaultUnits.length[config.units]);
  3208. document.querySelector("#options-height-value").value = height;
  3209. document.querySelector("#options-height-unit").dataset.oldUnit = defaultUnits.length[config.units];
  3210. document.querySelector("#options-height-unit").value = defaultUnits.length[config.units];
  3211. if (data.canvasWidth) {
  3212. doHorizReposition(data.canvasWidth / canvasWidth);
  3213. }
  3214. updateSizes();
  3215. }
  3216. function renderToCanvas() {
  3217. const ctx = document.querySelector("#display").getContext("2d");
  3218. Object.entries(entities).sort((ent1, ent2) => {
  3219. z1 = document.querySelector("#entity-" + ent1[0]).style.zIndex;
  3220. z2 = document.querySelector("#entity-" + ent2[0]).style.zIndex;
  3221. return z1 - z2;
  3222. }).forEach(([id, entity]) => {
  3223. element = document.querySelector("#entity-" + id);
  3224. img = element.querySelector("img");
  3225. let x = parseFloat(element.dataset.x);
  3226. let y = parseFloat(element.dataset.y);
  3227. let coords = pos2pix({x: x, y: y});
  3228. let offset = img.style.getPropertyValue("--offset");
  3229. offset = parseFloat(offset.substring(0, offset.length-1))
  3230. x = coords.x - img.getBoundingClientRect().width/2;
  3231. y = coords.y - img.getBoundingClientRect().height * (-offset/100);
  3232. let xSize = img.getBoundingClientRect().width;
  3233. let ySize = img.getBoundingClientRect().height;
  3234. const oldFilter = ctx.filter
  3235. const brightness = getComputedStyle(element).getPropertyValue("--brightness")
  3236. ctx.filter = `brightness(${brightness})`;
  3237. ctx.drawImage(img, x, y, xSize, ySize);
  3238. ctx.filter = oldFilter
  3239. });
  3240. }
  3241. function exportCanvas(callback) {
  3242. /** @type {CanvasRenderingContext2D} */
  3243. const ctx = document.querySelector("#display").getContext("2d");
  3244. const blob = ctx.canvas.toBlob(callback);
  3245. }
  3246. function generateScreenshot(callback) {
  3247. /** @type {CanvasRenderingContext2D} */
  3248. const ctx = document.querySelector("#display").getContext("2d");
  3249. if (checkBodyClass("toggle-bottom-cover")) {
  3250. ctx.fillStyle = "#000";
  3251. ctx.fillRect(0, pos2pix({x: 0, y: 0}).y, canvasWidth + 100, canvasHeight);
  3252. }
  3253. renderToCanvas();
  3254. ctx.fillStyle = "#777";
  3255. ctx.font = "normal normal lighter 16pt coda";
  3256. ctx.fillText("macrovision.crux.sexy", 10, 25);
  3257. exportCanvas(blob => {
  3258. callback(blob);
  3259. });
  3260. }
  3261. function copyScreenshot() {
  3262. if (window.ClipboardItem === undefined) {
  3263. alert("Sorry, this browser doesn't yet support writing images to the clipboard.");
  3264. return;
  3265. }
  3266. generateScreenshot(blob => {
  3267. navigator.clipboard.write([
  3268. new ClipboardItem({
  3269. "image/png": blob
  3270. })
  3271. ]);
  3272. });
  3273. drawScales(false);
  3274. }
  3275. function saveScreenshot() {
  3276. generateScreenshot(blob => {
  3277. const a = document.createElement("a");
  3278. a.href = URL.createObjectURL(blob);
  3279. a.setAttribute("download", "macrovision.png");
  3280. a.click();
  3281. });
  3282. drawScales(false);
  3283. }
  3284. function openScreenshot() {
  3285. generateScreenshot(blob => {
  3286. const a = document.createElement("a");
  3287. a.href = URL.createObjectURL(blob);
  3288. a.setAttribute("target", "_blank");
  3289. a.click();
  3290. });
  3291. drawScales(false);
  3292. }
  3293. const rateLimits = {};
  3294. function toast(msg) {
  3295. let div = document.createElement("div");
  3296. div.innerHTML = msg;
  3297. div.classList.add("toast");
  3298. document.body.appendChild(div);
  3299. setTimeout(() => {
  3300. document.body.removeChild(div);
  3301. }, 5000)
  3302. }
  3303. function toastRateLimit(msg, key, delay) {
  3304. if (!rateLimits[key]) {
  3305. toast(msg);
  3306. rateLimits[key] = setTimeout(() => {
  3307. delete rateLimits[key]
  3308. }, delay);
  3309. }
  3310. }