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

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