less copy protection, more size visualization
Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.
 
 
 

3990 lignes
120 KiB

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