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

3971 строка
119 KiB

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