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

5520 lines
169 KiB

  1. let selected = null;
  2. let prevSelected = null;
  3. let selectedEntity = null;
  4. let prevSelectedEntity = null;
  5. let entityIndex = 0;
  6. let firsterror = true;
  7. let clicked = null;
  8. let movingInBounds = false;
  9. let dragging = false;
  10. let clickTimeout = null;
  11. let dragOffsetX = null;
  12. let dragOffsetY = null;
  13. let preloaded = new Set();
  14. let panning = false;
  15. let panReady = true;
  16. let panOffsetX = null;
  17. let panOffsetY = null;
  18. let shiftHeld = false;
  19. let altHeld = false;
  20. let entityX;
  21. let canvasWidth;
  22. let canvasHeight;
  23. let dragScale = 1;
  24. let dragScaleHandle = null;
  25. let dragEntityScale = 1;
  26. let dragEntityScaleHandle = null;
  27. let scrollDirection = 0;
  28. let scrollHandle = null;
  29. let zoomDirection = 0;
  30. let zoomHandle = null;
  31. let sizeDirection = 0;
  32. let sizeHandle = null;
  33. let worldSizeDirty = false;
  34. let rulerMode = false;
  35. let rulers = [];
  36. let currentRuler = undefined;
  37. let webkitCanvasBug = false;
  38. const tagDefs = {
  39. "anthro": "Anthro",
  40. "feral": "Feral",
  41. "taur": "Taur",
  42. "naga": "Naga",
  43. "goo": "Goo"
  44. }
  45. math.createUnit("humans", {
  46. definition: "5.75 feet"
  47. });
  48. math.createUnit("story", {
  49. definition: "12 feet",
  50. prefixes: "long"
  51. });
  52. math.createUnit("stories", {
  53. definition: "12 feet",
  54. prefixes: "long"
  55. });
  56. math.createUnit("buses", {
  57. definition: "11.95 meters",
  58. prefixes: "long"
  59. });
  60. math.createUnit("marathons", {
  61. definition: "26.2 miles",
  62. prefixes: "long"
  63. });
  64. math.createUnit("timezones", {
  65. definition: "1037.54167 miles",
  66. prefixes: "long",
  67. aliases: ["timezone", "timezones"]
  68. });
  69. math.createUnit("nauticalMiles", {
  70. definition: "6080 feet",
  71. prefixes: "long",
  72. aliases: ["nauticalMile", "nauticalMiles"]
  73. });
  74. math.createUnit("fathoms", {
  75. definition: "6 feet",
  76. prefixes: "long",
  77. aliases: ["fathom", "fathoms"]
  78. });
  79. math.createUnit("earths", {
  80. definition: "12756km",
  81. prefixes: "long",
  82. aliases: ["earth", "earths", "Earth", "Earths"]
  83. });
  84. math.createUnit("lightsecond", {
  85. definition: "299792458 meters",
  86. prefixes: "long"
  87. });
  88. math.createUnit("lightseconds", {
  89. definition: "299792458 meters",
  90. prefixes: "long"
  91. });
  92. math.createUnit("parsec", {
  93. definition: "3.086e16 meters",
  94. prefixes: "long"
  95. })
  96. math.createUnit("parsecs", {
  97. definition: "3.086e16 meters",
  98. prefixes: "long"
  99. })
  100. math.createUnit("lightyears", {
  101. definition: "9.461e15 meters",
  102. prefixes: "long"
  103. })
  104. math.createUnit("AU", {
  105. definition: "149597870700 meters"
  106. })
  107. math.createUnit("AUs", {
  108. definition: "149597870700 meters"
  109. })
  110. math.createUnit("dalton", {
  111. definition: "1.66e-27 kg",
  112. prefixes: "long"
  113. });
  114. math.createUnit("daltons", {
  115. definition: "1.66e-27 kg",
  116. prefixes: "long"
  117. });
  118. math.createUnit("solarradii", {
  119. definition: "695990 km",
  120. prefixes: "long"
  121. });
  122. math.createUnit("solarmasses", {
  123. definition: "2e30 kg",
  124. prefixes: "long"
  125. });
  126. math.createUnit("galaxy", {
  127. definition: "105700 lightyears",
  128. prefixes: "long"
  129. });
  130. math.createUnit("galaxies", {
  131. definition: "105700 lightyears",
  132. prefixes: "long"
  133. });
  134. math.createUnit("universe", {
  135. definition: "93.016e9 lightyears",
  136. prefixes: "long"
  137. });
  138. math.createUnit("universes", {
  139. definition: "93.016e9 lightyears",
  140. prefixes: "long"
  141. });
  142. math.createUnit("multiverse", {
  143. definition: "1e30 lightyears",
  144. prefixes: "long"
  145. });
  146. math.createUnit("multiverses", {
  147. definition: "1e30 lightyears",
  148. prefixes: "long"
  149. });
  150. math.createUnit("pinHeads", {
  151. definition: "3.14159 mm^2",
  152. prefixes: "long"
  153. });
  154. math.createUnit("dinnerPlates", {
  155. definition: "95 inches^2",
  156. prefixes: "long"
  157. });
  158. math.createUnit("suburbanHouses", {
  159. definition: "2000 feet^2",
  160. prefixes: "long"
  161. });
  162. math.createUnit("footballFields", {
  163. definition: "57600 feet^2",
  164. prefixes: "long"
  165. });
  166. math.createUnit("blocks", {
  167. definition: "20000 m^2",
  168. prefixes: "long",
  169. aliases: ["block", "blocks"]
  170. });
  171. math.createUnit("peopleInRural", {
  172. definition: "0.02 miles^2"
  173. })
  174. math.createUnit("peopleInManhattan", {
  175. definition: "15 m^2"
  176. })
  177. math.createUnit("peopleInLooseCrowd", {
  178. definition: "1 m^2"
  179. })
  180. math.createUnit("peopleInCrowd", {
  181. definition: "0.3333333333333333 m^2"
  182. })
  183. math.createUnit("peopleInDenseCrowd", {
  184. definition: "0.2 m^2"
  185. })
  186. math.createUnit("people", {
  187. definition: "75 liters",
  188. prefixes: "long"
  189. });
  190. math.createUnit("shippingContainers", {
  191. definition: "1169 ft^3",
  192. prefixes: "long"
  193. });
  194. math.createUnit("olympicPools", {
  195. definition: "2500 m^3",
  196. prefixes: "long"
  197. });
  198. math.createUnit("oceans", {
  199. definition: "700000000 km^3",
  200. prefixes: "long"
  201. });
  202. math.createUnit("earthVolumes", {
  203. definition: "1.0867813e12 km^3",
  204. prefixes: "long"
  205. });
  206. math.createUnit("universeVolumes", {
  207. definition: "4.2137775e+32 lightyears^3",
  208. prefixes: "long"
  209. });
  210. math.createUnit("multiverseVolumes", {
  211. definition: "5.2359878e+89 lightyears^3",
  212. prefixes: "long"
  213. });
  214. math.createUnit("peopleMass", {
  215. definition: "80 kg",
  216. prefixes: "long"
  217. });
  218. math.createUnit("cars", {
  219. definition: "1250kg",
  220. prefixes: "long"
  221. });
  222. math.createUnit("busMasses", {
  223. definition: "15000kg",
  224. prefixes: "long"
  225. });
  226. math.createUnit("earthMass", {
  227. definition: "5.97e24 kg",
  228. prefixes: "long"
  229. });
  230. math.createUnit("kcal", {
  231. definition: "4184 joules",
  232. prefixes: "long"
  233. })
  234. math.createUnit("foodPounds", {
  235. definition: "867 kcal",
  236. prefixes: "long"
  237. })
  238. math.createUnit("foodKilograms", {
  239. definition: "1909 kcal",
  240. prefixes: "long"
  241. })
  242. math.createUnit("chickenNuggets", {
  243. definition: "42 kcal",
  244. prefixes: "long"
  245. })
  246. math.createUnit("peopleEaten", {
  247. definition: "125000 kcal",
  248. prefixes: "long"
  249. })
  250. math.createUnit("villagesEaten", {
  251. definition: "1000 peopleEaten",
  252. prefixes: "long"
  253. })
  254. math.createUnit("townsEaten", {
  255. definition: "10000 peopleEaten",
  256. prefixes: "long"
  257. })
  258. math.createUnit("citiesEaten", {
  259. definition: "100000 peopleEaten",
  260. prefixes: "long"
  261. })
  262. math.createUnit("metrosEaten", {
  263. definition: "1000000 peopleEaten",
  264. prefixes: "long"
  265. })
  266. math.createUnit("barn", {
  267. definition: "10e-28 m^2",
  268. prefixes: "long"
  269. })
  270. math.createUnit("barns", {
  271. definition: "10e-28 m^2",
  272. prefixes: "long"
  273. })
  274. math.createUnit("points", {
  275. definition: "0.013888888888888888888888888 inches",
  276. prefixes: "long"
  277. })
  278. math.createUnit("beardSeconds", {
  279. definition: "10 nanometers",
  280. prefixes: "long"
  281. })
  282. math.createUnit("smoots", {
  283. definition: "5.5833333 feet",
  284. prefixes: "long"
  285. })
  286. math.createUnit("furlongs", {
  287. definition: "660 feet",
  288. prefixes: "long"
  289. })
  290. math.createUnit("nanoacres", {
  291. definition: "1e-9 acres",
  292. prefixes: "long"
  293. })
  294. math.createUnit("barnMegaparsecs", {
  295. definition: "1 barn megaparsec",
  296. prefixes: "long"
  297. })
  298. math.createUnit("firkins", {
  299. definition: "90 lb",
  300. prefixes: "long"
  301. })
  302. math.createUnit("donkeySeconds", {
  303. definition: "250 joules",
  304. prefixes: "long"
  305. })
  306. math.createUnit("HU", {
  307. definition: "0.75 inches",
  308. aliases: [
  309. "HUs",
  310. "hammerUnits"
  311. ]
  312. });
  313. const defaultUnits = {
  314. length: {
  315. metric: "meters",
  316. customary: "feet",
  317. relative: "stories",
  318. quirky: "smoots",
  319. human: "humans"
  320. },
  321. area: {
  322. metric: "meters^2",
  323. customary: "feet^2",
  324. relative: "footballFields",
  325. quirky: "nanoacres",
  326. human: "peopleInCrowd"
  327. },
  328. volume: {
  329. metric: "liters",
  330. customary: "gallons",
  331. relative: "olympicPools",
  332. volume: "barnMegaparsecs",
  333. human: "people"
  334. },
  335. mass: {
  336. metric: "kilograms",
  337. customary: "lbs",
  338. relative: "peopleMass",
  339. quirky: "firkins",
  340. human: "peopleMass"
  341. },
  342. energy: {
  343. metric: "kJ",
  344. customary: "kcal",
  345. relative: "chickenNuggets",
  346. quirky: "donkeySeconds",
  347. human: "peopleEaten"
  348. }
  349. }
  350. const unitChoices = {
  351. length: {
  352. "metric": [
  353. "angstroms",
  354. "millimeters",
  355. "centimeters",
  356. "meters",
  357. "kilometers",
  358. ],
  359. "customary": [
  360. "inches",
  361. "feet",
  362. "yards",
  363. "miles",
  364. "nauticalMiles",
  365. ],
  366. "relative": [
  367. "stories",
  368. "buses",
  369. "marathons",
  370. "timezones",
  371. "earths",
  372. "lightseconds",
  373. "solarradii",
  374. "AUs",
  375. "lightyears",
  376. "parsecs",
  377. "galaxies",
  378. "universes",
  379. "multiverses"
  380. ],
  381. "quirky": [
  382. "beardSeconds",
  383. "points",
  384. "smoots",
  385. "furlongs",
  386. "HUs",
  387. "fathoms",
  388. ],
  389. "human": [
  390. "humans",
  391. ]
  392. },
  393. area: {
  394. "metric": [
  395. "cm^2",
  396. "meters^2",
  397. "kilometers^2",
  398. ],
  399. "customary": [
  400. "feet^2",
  401. "acres",
  402. "miles^2"
  403. ],
  404. "relative": [
  405. "pinHeads",
  406. "dinnerPlates",
  407. "suburbanHouses",
  408. "footballFields",
  409. "blocks"
  410. ],
  411. "quirky": [
  412. "barns",
  413. "nanoacres"
  414. ],
  415. "human": [
  416. "peopleInRural",
  417. "peopleInManhattan",
  418. "peopleInLooseCrowd",
  419. "peopleInCrowd",
  420. "peopleInDenseCrowd",
  421. ]
  422. },
  423. volume: {
  424. "metric": [
  425. "milliliters",
  426. "liters",
  427. "m^3",
  428. ],
  429. "customary": [
  430. "floz",
  431. "cups",
  432. "pints",
  433. "quarts",
  434. "gallons",
  435. ],
  436. "relative": [
  437. "shippingContainers",
  438. "olympicPools",
  439. "oceans",
  440. "earthVolumes",
  441. "universeVolumes",
  442. "multiverseVolumes",
  443. ],
  444. "quirky": [
  445. "barnMegaparsecs"
  446. ],
  447. "human": [
  448. "people",
  449. ]
  450. },
  451. mass: {
  452. "metric": [
  453. "kilograms",
  454. "milligrams",
  455. "grams",
  456. "tonnes",
  457. ],
  458. "customary": [
  459. "lbs",
  460. "ounces",
  461. "tons"
  462. ],
  463. "relative": [
  464. "cars",
  465. "busMasses",
  466. "earthMass",
  467. "solarmasses"
  468. ],
  469. "quirky": [
  470. "firkins"
  471. ],
  472. "human": [
  473. "peopleMass",
  474. ]
  475. },
  476. energy: {
  477. "metric": [
  478. "kJ",
  479. "foodKilograms"
  480. ],
  481. "customary": [
  482. "kcal",
  483. "foodPounds"
  484. ],
  485. "relative": [
  486. "chickenNuggets",
  487. ],
  488. "quirky": [
  489. "donkeySeconds"
  490. ],
  491. "human": [
  492. "peopleEaten",
  493. "villagesEaten",
  494. "townsEaten",
  495. "citiesEaten",
  496. "metrosEaten",
  497. ]
  498. }
  499. }
  500. const config = {
  501. height: math.unit(1500, "meters"),
  502. x: 0,
  503. y: 0,
  504. minLineSize: 100,
  505. maxLineSize: 150,
  506. autoFit: false,
  507. drawYAxis: true,
  508. drawXAxis: false,
  509. autoMass: "off",
  510. autoFoodIntake: false,
  511. autoPreyCapacity: "off"
  512. }
  513. const availableEntities = {
  514. }
  515. const availableEntitiesByName = {
  516. }
  517. const entities = {
  518. }
  519. function constrainRel(coords) {
  520. const worldWidth = config.height.toNumber("meters") / canvasHeight * canvasWidth;
  521. const worldHeight = config.height.toNumber("meters");
  522. if (altHeld) {
  523. return coords;
  524. }
  525. return {
  526. x: Math.min(Math.max(coords.x, -worldWidth / 2 + config.x), worldWidth / 2 + config.x),
  527. y: Math.min(Math.max(coords.y, config.y), worldHeight + config.y)
  528. }
  529. }
  530. // not using constrainRel anymore
  531. function snapPos(coords) {
  532. return {
  533. x: coords.x,
  534. y: (!config.groundSnap || altHeld) ? coords.y : (Math.abs(coords.y) < config.height.toNumber("meters")/20 ? 0 : coords.y)
  535. };
  536. }
  537. function adjustAbs(coords, oldHeight, newHeight) {
  538. const ratio = math.divide(newHeight, oldHeight);
  539. const x = (coords.x - config.x) * ratio + config.x;
  540. const y = (coords.y - config.y) * ratio + config.y;
  541. return { x: x, y: y};
  542. }
  543. function pos2pix(coords) {
  544. const worldWidth = config.height.toNumber("meters") / canvasHeight * canvasWidth;
  545. const worldHeight = config.height.toNumber("meters");
  546. const x = ((coords.x - config.x) / worldWidth + 0.5) * (canvasWidth - 50) + 50;
  547. const y = (1 - (coords.y - config.y) / worldHeight) * (canvasHeight - 50) + 50;
  548. return { x: x, y: y };
  549. }
  550. function pix2pos(coords) {
  551. const worldWidth = config.height.toNumber("meters") / canvasHeight * canvasWidth;
  552. const worldHeight = config.height.toNumber("meters");
  553. const x = (((coords.x - 50) / (canvasWidth - 50)) - 0.5) * worldWidth + config.x;
  554. const y = (1 - ((coords.y - 50) / (canvasHeight - 50))) * worldHeight + config.y;
  555. return { x: x, y: y };
  556. }
  557. function updateEntityElement(entity, element) {
  558. const position = pos2pix({ x: element.dataset.x, y: element.dataset.y });
  559. const view = entity.view;
  560. const form = entity.form
  561. element.style.left = position.x + "px";
  562. element.style.top = position.y + "px";
  563. element.style.setProperty("--xpos", position.x + "px");
  564. element.style.setProperty("--entity-height", "'" + entity.views[view].height.to(config.height.units[0].unit.name).format({ precision: 2 }) + "'");
  565. const pixels = math.divide(entity.views[view].height, config.height) * (canvasHeight - 50);
  566. const extra = entity.views[view].image.extra;
  567. const bottom = entity.views[view].image.bottom;
  568. const bonus = (extra ? extra : 1) * (1 / (1 - (bottom ? bottom : 0)));
  569. let height = pixels * bonus;
  570. // working around a Firefox bug here
  571. if (height > 17895698) {
  572. height = 0;
  573. }
  574. element.style.setProperty("--height", height + "px");
  575. element.style.setProperty("--extra", height - pixels + "px");
  576. element.style.setProperty("--brightness", entity.brightness);
  577. if (entity.views[view].rename)
  578. element.querySelector(".entity-name").innerText = entity.name == "" ? "" : entity.views[view].name;
  579. else if (entity.forms !== undefined && Object.keys(entity.forms).length > 0 && entity.forms[form].rename)
  580. element.querySelector(".entity-name").innerText = entity.name == "" ? "" : entity.forms[form].name;
  581. else
  582. element.querySelector(".entity-name").innerText = entity.name;
  583. const bottomName = document.querySelector("#bottom-name-" + element.dataset.key);
  584. bottomName.style.left = position.x + entityX + "px";
  585. bottomName.style.bottom = "0vh";
  586. bottomName.innerText = entity.name;
  587. const topName = document.querySelector("#top-name-" + element.dataset.key);
  588. topName.style.left = position.x + entityX + "px";
  589. topName.style.top = "20vh";
  590. topName.innerText = entity.name;
  591. if (entity.views[view].height.toNumber("meters") / 10 > config.height.toNumber("meters")) {
  592. topName.classList.add("top-name-needed");
  593. } else {
  594. topName.classList.remove("top-name-needed");
  595. }
  596. updateInfo();
  597. }
  598. let ratioInfo
  599. function updateInfo() {
  600. let text = ""
  601. if (config.showRatios) {
  602. if (selectedEntity !== null && prevSelectedEntity !== null && selectedEntity !== prevSelectedEntity) {
  603. let first = selectedEntity.currentView.height;
  604. let second = prevSelectedEntity.currentView.height;
  605. if (first.toNumber("meters") < second.toNumber("meters")) {
  606. text += selectedEntity.name + " is " + math.format(math.divide(second, first), { precision: 5 }) + " times smaller than " + prevSelectedEntity.name;
  607. } else {
  608. text += selectedEntity.name + " is " + math.format(math.divide(first, second), { precision: 5 })+ " times taller than " + prevSelectedEntity.name;
  609. }
  610. text += "\n";
  611. let apparentHeight = math.multiply(math.divide(second, first), math.unit(6, "feet"));
  612. if (config.units === "metric") {
  613. apparentHeight = apparentHeight.to("meters");
  614. }
  615. text += prevSelectedEntity.name + " looks " + math.format(apparentHeight, { precision: 3}) + " tall to " + selectedEntity.name + "\n";
  616. if (selectedEntity.currentView.weight && prevSelectedEntity.currentView.weight) {
  617. const ratio = math.divide(selectedEntity.currentView.weight, prevSelectedEntity.currentView.weight)
  618. if (ratio > 1) {
  619. text += selectedEntity.name + " is " + math.format(ratio, {precision: 2}) + " times heavier than " + prevSelectedEntity.name + "\n";
  620. } else {
  621. text += selectedEntity.name + " is " + math.format(1/ratio, {precision: 2}) + " times lighter than " + prevSelectedEntity.name + "\n";
  622. }
  623. }
  624. const capacity = selectedEntity.currentView.preyCapacity ?? selectedEntity.currentView.capacity ?? selectedEntity.currentView.volume
  625. if (capacity && prevSelectedEntity.currentView.weight) {
  626. const containCount = math.divide(capacity, math.divide(prevSelectedEntity.currentView.weight, math.unit("80kg/people")));
  627. if (containCount > 0.1) {
  628. text += selectedEntity.name + " can fit " + math.format(containCount, { precision: 1 }) + " of " + prevSelectedEntity.name + " inside them" + "\n"
  629. }
  630. }
  631. if (selectedEntity.currentView.energyIntake && prevSelectedEntity.currentView.energyValue) {
  632. const consumeCount = math.divide(selectedEntity.currentView.energyIntake, prevSelectedEntity.currentView.energyValue);
  633. if (consumeCount > 0.1) {
  634. text += selectedEntity.name + " needs to eat " + math.format(consumeCount, { precision: 1 }) + " of " + prevSelectedEntity.name + " per day" + "\n"
  635. }
  636. }
  637. }
  638. }
  639. if (config.showHorizon) {
  640. if (selectedEntity !== null) {
  641. const y = document.querySelector("#entity-" + selectedEntity.index).dataset.y;
  642. const R = math.unit(1.27560e+7, "meters")
  643. const h = math.add(selectedEntity.currentView.height, math.unit(y, "meters"))
  644. const first = math.multiply(2, math.multiply(R, h))
  645. const second = math.multiply(h, h)
  646. const sightline = math.sqrt(math.add(first, second)).to(config.height.units[0].unit.name)
  647. sightline.fixPrefix = false
  648. text += selectedEntity.name + " could see for " + math.format(sightline, { precision: 3 }) + "\n"
  649. }
  650. }
  651. if (config.showRatios && config.showHorizon) {
  652. if (selectedEntity !== null && prevSelectedEntity !== null && selectedEntity !== prevSelectedEntity) {
  653. const y1 = document.querySelector("#entity-" + selectedEntity.index).dataset.y;
  654. const y2 = document.querySelector("#entity-" + prevSelectedEntity.index).dataset.y;
  655. const R = math.unit(1.27560e+7, "meters")
  656. const R2 = math.subtract(math.subtract(R, prevSelectedEntity.currentView.height), math.unit(y2, "meters"))
  657. const h = math.add(selectedEntity.currentView.height, math.unit(y1, "meters"))
  658. const first = math.pow(math.add(R, h), 2)
  659. const second = math.pow(R2, 2)
  660. const sightline = math.sqrt(math.subtract(first, second)).to(config.height.units[0].unit.name)
  661. sightline.fixPrefix = false
  662. text += selectedEntity.name + " could see " + prevSelectedEntity.name + " from " + math.format(sightline, { precision: 3 }) + " away\n"
  663. }
  664. }
  665. ratioInfo.innerText = text;
  666. }
  667. function pickUnit() {
  668. if (!config.autoUnits) {
  669. return;
  670. }
  671. let type = null;
  672. let category = null;
  673. const heightSelect = document.querySelector("#options-height-unit");
  674. currentUnit = heightSelect.value;
  675. Object.keys(unitChoices).forEach(unitType => {
  676. Object.keys(unitChoices[unitType]).forEach(unitCategory => {
  677. if (unitChoices[unitType][unitCategory].includes(currentUnit)) {
  678. type = unitType;
  679. category = unitCategory;
  680. }
  681. })
  682. })
  683. // This should only happen if the unit selector isn't set up yet.
  684. // It doesn't really matter what goes into it.
  685. if (type === null || category === null) {
  686. return "meters"
  687. }
  688. const choices = unitChoices[type][category].map(unit => {
  689. let value = config.height.toNumber(unit);
  690. if (value < 1) {
  691. value = 1 / value / value;
  692. }
  693. return [unit, value]
  694. })
  695. heightSelect.value = choices.sort((a, b) => {
  696. return a[1] - b[1]
  697. })[0][0]
  698. selectNewUnit();
  699. }
  700. function updateSizes(dirtyOnly = false) {
  701. updateInfo();
  702. if (config.lockYAxis) {
  703. config.y = -getVerticalOffset();
  704. }
  705. drawScales(dirtyOnly);
  706. let ordered = Object.entries(entities);
  707. ordered.sort((e1, e2) => {
  708. if (e1[1].priority != e2[1].priority) {
  709. return e2[1].priority - e1[1].priority;
  710. } else {
  711. return e1[1].views[e1[1].view].height.value - e2[1].views[e2[1].view].height.value
  712. }
  713. });
  714. let zIndex = ordered.length;
  715. ordered.forEach(entity => {
  716. const element = document.querySelector("#entity-" + entity[0]);
  717. element.style.zIndex = zIndex;
  718. if (!dirtyOnly || entity[1].dirty) {
  719. updateEntityElement(entity[1], element, zIndex);
  720. entity[1].dirty = false;
  721. }
  722. zIndex -= 1;
  723. });
  724. document.querySelector("#ground").style.top = pos2pix({x: 0, y: 0}).y + "px";
  725. drawRulers();
  726. }
  727. function drawRulers() {
  728. const canvas = document.querySelector("#rulers");
  729. /** @type {CanvasRenderingContext2D} */
  730. const ctx = canvas.getContext("2d");
  731. const deviceScale = window.devicePixelRatio;
  732. ctx.canvas.width = Math.floor(canvas.clientWidth * deviceScale);
  733. ctx.canvas.height = Math.floor(canvas.clientHeight * deviceScale);
  734. ctx.scale(deviceScale, deviceScale);
  735. rulers.concat(currentRuler ? [currentRuler] : []).forEach(rulerDef => {
  736. let x0 = rulerDef.x0;
  737. let y0 = rulerDef.y0;
  738. let x1 = rulerDef.x1;
  739. let y1 = rulerDef.y1;
  740. if (rulerDef.entityKey !== null) {
  741. const entity = entities[rulerDef.entityKey]
  742. const entityElement = document.querySelector("#entity-" + rulerDef.entityKey)
  743. x0 *= entity.scale;
  744. y0 *= entity.scale;
  745. x1 *= entity.scale;
  746. y1 *= entity.scale;
  747. x0 += parseFloat(entityElement.dataset.x)
  748. x1 += parseFloat(entityElement.dataset.x)
  749. y0 += parseFloat(entityElement.dataset.y)
  750. y1 += parseFloat(entityElement.dataset.y)
  751. }
  752. ctx.save();
  753. ctx.beginPath();
  754. const start = pos2pix({x: x0, y: y0});
  755. const end = pos2pix({x: x1, y: y1});
  756. ctx.moveTo(start.x, start.y);
  757. ctx.lineTo(end.x, end.y);
  758. ctx.lineWidth = 5;
  759. ctx.strokeStyle = "#f8f";
  760. ctx.stroke();
  761. const center = { x: (start.x + end.x) / 2, y: (start.y + end.y) / 2 };
  762. ctx.fillStyle = "#eeeeee";
  763. ctx.font = 'normal 24pt coda';
  764. ctx.translate(center.x, center.y);
  765. let angle = Math.atan2(end.y - start.y, end.x - start.x);
  766. if (angle < -Math.PI/2) {
  767. angle += Math.PI;
  768. }
  769. if (angle > Math.PI/2) {
  770. angle -= Math.PI;
  771. }
  772. ctx.rotate(angle);
  773. const offsetX = Math.cos(angle + Math.PI/2);
  774. const offsetY = Math.sin(angle + Math.PI/2);
  775. const distance = Math.sqrt(Math.pow(y1 - y0, 2) + Math.pow(x1 - x0, 2));
  776. const distanceInUnits = math.unit(distance, "meters").to(document.querySelector("#options-height-unit").value);
  777. const textSize = ctx.measureText(distanceInUnits.format({ precision: 3}));
  778. ctx.fillText(distanceInUnits.format({ precision: 3}), -offsetX * 10 - textSize.width / 2, -offsetY*10);
  779. ctx.restore();
  780. });
  781. }
  782. function drawScales(ifDirty = false) {
  783. const canvas = document.querySelector("#display");
  784. /** @type {CanvasRenderingContext2D} */
  785. const ctx = canvas.getContext("2d");
  786. const deviceScale = window.devicePixelRatio;
  787. ctx.canvas.width = Math.floor(canvas.clientWidth * deviceScale);
  788. ctx.canvas.height = Math.floor(canvas.clientHeight * deviceScale);
  789. ctx.scale(deviceScale, deviceScale);
  790. ctx.beginPath();
  791. ctx.rect(0, 0, ctx.canvas.width / deviceScale, ctx.canvas.height / deviceScale);
  792. switch(config.background){
  793. case "black":
  794. ctx.fillStyle = "#000";
  795. break;
  796. case "dark":
  797. ctx.fillStyle = "#111";
  798. break;
  799. case "medium":
  800. ctx.fillStyle = "#333";
  801. break;
  802. case "light":
  803. ctx.fillStyle = "#555";
  804. break;
  805. }
  806. ctx.fill();
  807. if (config.drawYAxis || config.drawAltitudes !== "none") {
  808. drawVerticalScale(ifDirty);
  809. }
  810. if (config.drawXAxis) {
  811. drawHorizontalScale(ifDirty);
  812. }
  813. }
  814. function drawVerticalScale(ifDirty = false) {
  815. if (ifDirty && !worldSizeDirty)
  816. return;
  817. function drawTicks(/** @type {CanvasRenderingContext2D} */ ctx, pixelsPer, heightPer) {
  818. let total = heightPer.clone();
  819. total.value = config.y;
  820. let y = ctx.canvas.clientHeight - 50;
  821. let offset = total.toNumber("meters") % heightPer.toNumber("meters");
  822. y += offset / heightPer.toNumber("meters") * pixelsPer;
  823. total = math.subtract(total, math.unit(offset, "meters"));
  824. for (; y >= 50; y -= pixelsPer) {
  825. drawTick(ctx, 50, y, total.format({ precision: 3 }));
  826. total = math.add(total, heightPer);
  827. }
  828. }
  829. function drawTick(/** @type {CanvasRenderingContext2D} */ ctx, x, y, label, flipped=false) {
  830. const oldStroke = ctx.strokeStyle;
  831. const oldFill = ctx.fillStyle;
  832. x = Math.round(x);
  833. y = Math.round(y);
  834. ctx.beginPath();
  835. ctx.moveTo(x, y);
  836. ctx.lineTo(x + 20, y);
  837. ctx.strokeStyle = "#000000";
  838. ctx.stroke();
  839. ctx.beginPath();
  840. ctx.moveTo(x + 20, y);
  841. ctx.lineTo(ctx.canvas.clientWidth - 70, y);
  842. if (flipped) {
  843. ctx.strokeStyle = "#666666";
  844. } else {
  845. ctx.strokeStyle = "#aaaaaa";
  846. }
  847. ctx.stroke();
  848. ctx.beginPath();
  849. ctx.moveTo(ctx.canvas.clientWidth - 70, y);
  850. ctx.lineTo(ctx.canvas.clientWidth - 50, y);
  851. ctx.strokeStyle = "#000000";
  852. ctx.stroke();
  853. const oldFont = ctx.font;
  854. ctx.font = 'normal 24pt coda';
  855. ctx.fillStyle = "#dddddd";
  856. ctx.beginPath();
  857. if (flipped) {
  858. ctx.textAlign = "end";
  859. ctx.fillText(label, ctx.canvas.clientWidth - 70, y + 35)
  860. } else {
  861. ctx.fillText(label, x + 20, y + 35);
  862. }
  863. ctx.textAlign = "start";
  864. ctx.font = oldFont;
  865. ctx.strokeStyle = oldStroke;
  866. ctx.fillStyle = oldFill;
  867. }
  868. function drawAltitudeLine(ctx, height, label) {
  869. const pixelScale = (ctx.canvas.clientHeight - 100) / config.height.toNumber("meters");
  870. const y = ctx.canvas.clientHeight - 50 - (height.toNumber("meters") - config.y) * pixelScale;
  871. const offsetY = y + getVerticalOffset() * pixelScale;
  872. if (offsetY < ctx.canvas.clientHeight - 100) {
  873. drawTick(ctx, 50, y, label, true);
  874. }
  875. }
  876. const canvas = document.querySelector("#display");
  877. /** @type {CanvasRenderingContext2D} */
  878. const ctx = canvas.getContext("2d");
  879. const pixelScale = (ctx.canvas.clientHeight - 100) / config.height.toNumber();
  880. let pixelsPer = pixelScale;
  881. heightPer = 1;
  882. if (pixelsPer < config.minLineSize) {
  883. const factor = math.ceil(config.minLineSize / pixelsPer);
  884. heightPer *= factor;
  885. pixelsPer *= factor;
  886. }
  887. if (pixelsPer > config.maxLineSize) {
  888. const factor = math.ceil(pixelsPer / config.maxLineSize);
  889. heightPer /= factor;
  890. pixelsPer /= factor;
  891. }
  892. if (heightPer == 0) {
  893. console.error("The world size is invalid! Refusing to draw the scale...");
  894. return;
  895. }
  896. heightPer = math.unit(heightPer, document.querySelector("#options-height-unit").value);
  897. ctx.beginPath();
  898. ctx.moveTo(50, 50);
  899. ctx.lineTo(50, ctx.canvas.clientHeight - 50);
  900. ctx.stroke();
  901. ctx.beginPath();
  902. ctx.moveTo(ctx.canvas.clientWidth - 50, 50);
  903. ctx.lineTo(ctx.canvas.clientWidth - 50, ctx.canvas.clientHeight - 50);
  904. ctx.stroke();
  905. if (config.drawYAxis) {
  906. drawTicks(ctx, pixelsPer, heightPer);
  907. }
  908. if (config.drawAltitudes == "atmosphere" || config.drawAltitudes == "all") {
  909. drawAltitudeLine(ctx, math.unit(8, "km"), "Troposphere");
  910. drawAltitudeLine(ctx, math.unit(17.5, "km"), "Ozone Layer");
  911. drawAltitudeLine(ctx, math.unit(50, "km"), "Stratosphere");
  912. drawAltitudeLine(ctx, math.unit(85, "km"), "Mesosphere");
  913. drawAltitudeLine(ctx, math.unit(675, "km"), "Thermosphere");
  914. drawAltitudeLine(ctx, math.unit(10000, "km"), "Exosphere");
  915. }
  916. if (config.drawAltitudes == "orbits" || config.drawAltitudes == "all") {
  917. drawAltitudeLine(ctx, math.unit(7, "miles"), "Cruising Altitude");
  918. drawAltitudeLine(ctx, math.unit(100, "km"), "Edge of Space (Kármán line)");
  919. drawAltitudeLine(ctx, math.unit(211.3, "miles"), "Space Station");
  920. drawAltitudeLine(ctx, math.unit(369.7, "miles"), "Hubble Telescope");
  921. drawAltitudeLine(ctx, math.unit(1500, "km"), "Low Earth Orbit");
  922. drawAltitudeLine(ctx, math.unit(20350, "km"), "GPS Satellites");
  923. drawAltitudeLine(ctx, math.unit(35786, "km"), "Geosynchronous Orbit");
  924. drawAltitudeLine(ctx, math.unit(238900, "miles"), "Lunar Orbit");
  925. drawAltitudeLine(ctx, math.unit(57.9e6, "km"), "Orbit of Mercury");
  926. drawAltitudeLine(ctx, math.unit(108.2e6, "km"), "Orbit of Venus");
  927. drawAltitudeLine(ctx, math.unit(1, "AU"), "Orbit of Earth");
  928. drawAltitudeLine(ctx, math.unit(227.9e6, "km"), "Orbit of Mars");
  929. drawAltitudeLine(ctx, math.unit(778.6e6, "km"), "Orbit of Jupiter");
  930. drawAltitudeLine(ctx, math.unit(1433.5e6, "km"), "Orbit of Saturn");
  931. drawAltitudeLine(ctx, math.unit(2872.5e6, "km"), "Orbit of Uranus");
  932. drawAltitudeLine(ctx, math.unit(4495.1e6, "km"), "Orbit of Neptune");
  933. drawAltitudeLine(ctx, math.unit(5906.4e6, "km"), "Orbit of Pluto");
  934. drawAltitudeLine(ctx, math.unit(2.7, "AU"), "Asteroid Belt");
  935. drawAltitudeLine(ctx, math.unit(123, "AU"), "Heliopause");
  936. drawAltitudeLine(ctx, math.unit(26e3, "lightyears"), "Orbit of Sol");
  937. }
  938. if (config.drawAltitudes == "weather" || config.drawAltitudes == "all") {
  939. drawAltitudeLine(ctx, math.unit(1000, "meters"), "Low-level Clouds");
  940. drawAltitudeLine(ctx, math.unit(3000, "meters"), "Mid-level Clouds");
  941. drawAltitudeLine(ctx, math.unit(10000, "meters"), "High-level Clouds");
  942. drawAltitudeLine(ctx, math.unit(20, "km"), "Polar Stratospheric Clouds");
  943. drawAltitudeLine(ctx, math.unit(80, "km"), "Noctilucent Clouds");
  944. drawAltitudeLine(ctx, math.unit(100, "km"), "Aurora");
  945. }
  946. if (config.drawAltitudes == "water" || config.drawAltitudes == "all") {
  947. drawAltitudeLine(ctx, math.unit(12100, "feet"), "Average Ocean Depth");
  948. drawAltitudeLine(ctx, math.unit(8376, "meters"), "Milkwaukee Deep");
  949. drawAltitudeLine(ctx, math.unit(10984, "meters"), "Challenger Deep");
  950. drawAltitudeLine(ctx, math.unit(5550, "meters"), "Molloy Deep");
  951. drawAltitudeLine(ctx, math.unit(7290, "meters"), "Sunda Deep");
  952. drawAltitudeLine(ctx, math.unit(592, "meters"), "Crater Lake");
  953. drawAltitudeLine(ctx, math.unit(7.5, "meters"), "Littoral Zone");
  954. drawAltitudeLine(ctx, math.unit(140, "meters"), "Continental Shelf");
  955. }
  956. if (config.drawAltitudes == "geology" || config.drawAltitudes == "all") {
  957. drawAltitudeLine(ctx, math.unit(35, "km"), "Crust");
  958. drawAltitudeLine(ctx, math.unit(670, "km"), "Upper Mantle");
  959. drawAltitudeLine(ctx, math.unit(2890, "km"), "Lower Mantle");
  960. drawAltitudeLine(ctx, math.unit(5150, "km"), "Outer Core");
  961. drawAltitudeLine(ctx, math.unit(6370, "km"), "Inner Core");
  962. }
  963. if (config.drawAltitudes == "thicknesses" || config.drawAltitudes == "all") {
  964. drawAltitudeLine(ctx, math.unit(0.335, "nm"), "Monolayer Graphene");
  965. drawAltitudeLine(ctx, math.unit(3, "um"), "Spider Silk");
  966. drawAltitudeLine(ctx, math.unit(0.07, "mm"), "Human Hair");
  967. drawAltitudeLine(ctx, math.unit(0.1, "mm"), "Sheet of Paper");
  968. drawAltitudeLine(ctx, math.unit(0.5, "mm"), "Yarn");
  969. drawAltitudeLine(ctx, math.unit(0.0155, "inches"), "Thread");
  970. drawAltitudeLine(ctx, math.unit(0.1, "um"), "Gold Leaf");
  971. drawAltitudeLine(ctx, math.unit(35, "um"), "PCB Trace");
  972. }
  973. if (config.drawAltitudes == "airspaces" || config.drawAltitudes == "all") {
  974. drawAltitudeLine(ctx, math.unit(18000, "feet"), "Class A");
  975. drawAltitudeLine(ctx, math.unit(14500, "feet"), "Class E");
  976. drawAltitudeLine(ctx, math.unit(10000, "feet"), "Class B");
  977. drawAltitudeLine(ctx, math.unit(4000, "feet"), "Class C");
  978. drawAltitudeLine(ctx, math.unit(2500, "feet"), "Class D");
  979. }
  980. if (config.drawAltitudes == "races" || config.drawAltitudes == "all") {
  981. drawAltitudeLine(ctx, math.unit(100, "meters"), "100m Dash");
  982. drawAltitudeLine(ctx, math.unit(26.2188/2, "miles"), "Half Marathon");
  983. drawAltitudeLine(ctx, math.unit(26.2188, "miles"), "Marathon");
  984. drawAltitudeLine(ctx, math.unit(161.734, "miles"), "Monaco Grand Prix");
  985. drawAltitudeLine(ctx, math.unit(500, "miles"), "Daytona 500");
  986. drawAltitudeLine(ctx, math.unit(2121.6, "miles"), "Tour de France");
  987. }
  988. if (config.drawAltitudes == "olympic-records" || config.drawAltitudes == "all") {
  989. drawAltitudeLine(ctx, math.unit(2.39, "meters"), "High Jump");
  990. drawAltitudeLine(ctx, math.unit(6.03, "meters"), "Pole Vault");
  991. drawAltitudeLine(ctx, math.unit(8.90, "meters"), "Long Jump");
  992. drawAltitudeLine(ctx, math.unit(18.09, "meters"), "Triple Jump");
  993. drawAltitudeLine(ctx, math.unit(23.30, "meters"), "Shot Put");
  994. drawAltitudeLine(ctx, math.unit(72.30, "meters"), "Discus Throw");
  995. drawAltitudeLine(ctx, math.unit(84.80, "meters"), "Hammer Throw");
  996. drawAltitudeLine(ctx, math.unit(90.57, "meters"), "Javelin Throw");
  997. }
  998. if (config.drawAltitudes == "d&d-sizes" || config.drawAltitudes == "all") {
  999. drawAltitudeLine(ctx, math.unit(0.375, "feet"), "Fine");
  1000. drawAltitudeLine(ctx, math.unit(0.75, "feet"), "Dimnutive");
  1001. drawAltitudeLine(ctx, math.unit(1.5, "feet"), "Tiny");
  1002. drawAltitudeLine(ctx, math.unit(3, "feet"), "Small");
  1003. drawAltitudeLine(ctx, math.unit(6, "feet"), "Medium");
  1004. drawAltitudeLine(ctx, math.unit(12, "feet"), "Large");
  1005. drawAltitudeLine(ctx, math.unit(24, "feet"), "Huge");
  1006. drawAltitudeLine(ctx, math.unit(48, "feet"), "Gargantuan");
  1007. drawAltitudeLine(ctx, math.unit(96, "feet"), "Colossal");
  1008. }
  1009. }
  1010. // this is a lot of copypizza...
  1011. function drawHorizontalScale(ifDirty = false) {
  1012. if (ifDirty && !worldSizeDirty)
  1013. return;
  1014. function drawTicks(/** @type {CanvasRenderingContext2D} */ ctx, pixelsPer, heightPer) {
  1015. let total = heightPer.clone();
  1016. total.value = math.unit(-config.x, "meters").toNumber(config.unit);
  1017. // further adjust it to put the current position in the center
  1018. total.value -= heightPer.toNumber("meters") / pixelsPer * (canvasWidth + 50) / 2;
  1019. let x = ctx.canvas.clientWidth - 50;
  1020. let offset = total.toNumber("meters") % heightPer.toNumber("meters");
  1021. x += offset / heightPer.toNumber("meters") * pixelsPer;
  1022. total = math.subtract(total, math.unit(offset, "meters"));
  1023. for (; x >= 50 - pixelsPer; x -= pixelsPer) {
  1024. // negate it so that the left side is negative
  1025. drawTick(ctx, x, 50, math.multiply(-1, total).format({ precision: 3 }));
  1026. total = math.add(total, heightPer);
  1027. }
  1028. }
  1029. function drawTick(/** @type {CanvasRenderingContext2D} */ ctx, x, y, label) {
  1030. ctx.save()
  1031. x = Math.round(x);
  1032. y = Math.round(y);
  1033. ctx.beginPath();
  1034. ctx.moveTo(x, y);
  1035. ctx.lineTo(x, y + 20);
  1036. ctx.strokeStyle = "#000000";
  1037. ctx.stroke();
  1038. ctx.beginPath();
  1039. ctx.moveTo(x, y + 20);
  1040. ctx.lineTo(x, ctx.canvas.clientHeight - 70);
  1041. ctx.strokeStyle = "#aaaaaa";
  1042. ctx.stroke();
  1043. ctx.beginPath();
  1044. ctx.moveTo(x, ctx.canvas.clientHeight - 70);
  1045. ctx.lineTo(x, ctx.canvas.clientHeight - 50);
  1046. ctx.strokeStyle = "#000000";
  1047. ctx.stroke();
  1048. const oldFont = ctx.font;
  1049. ctx.font = 'normal 24pt coda';
  1050. ctx.fillStyle = "#dddddd";
  1051. ctx.beginPath();
  1052. ctx.fillText(label, x + 35, y + 20);
  1053. ctx.restore()
  1054. }
  1055. const canvas = document.querySelector("#display");
  1056. /** @type {CanvasRenderingContext2D} */
  1057. const ctx = canvas.getContext("2d");
  1058. let pixelsPer = (ctx.canvas.clientHeight - 100) / config.height.toNumber();
  1059. heightPer = 1;
  1060. if (pixelsPer < config.minLineSize * 2) {
  1061. const factor = math.ceil(config.minLineSize * 2/ pixelsPer);
  1062. heightPer *= factor;
  1063. pixelsPer *= factor;
  1064. }
  1065. if (pixelsPer > config.maxLineSize * 2) {
  1066. const factor = math.ceil(pixelsPer / 2/ config.maxLineSize);
  1067. heightPer /= factor;
  1068. pixelsPer /= factor;
  1069. }
  1070. if (heightPer == 0) {
  1071. console.error("The world size is invalid! Refusing to draw the scale...");
  1072. return;
  1073. }
  1074. heightPer = math.unit(heightPer, document.querySelector("#options-height-unit").value);
  1075. ctx.beginPath();
  1076. ctx.moveTo(0, 50);
  1077. ctx.lineTo(ctx.canvas.clientWidth, 50);
  1078. ctx.stroke();
  1079. ctx.beginPath();
  1080. ctx.moveTo(0, ctx.canvas.clientHeight - 50);
  1081. ctx.lineTo(ctx.canvas.clientWidth , ctx.canvas.clientHeight - 50);
  1082. ctx.stroke();
  1083. drawTicks(ctx, pixelsPer, heightPer);
  1084. }
  1085. // Entities are generated as needed, and we make a copy
  1086. // every time - the resulting objects get mutated, after all.
  1087. // But we also want to be able to read some information without
  1088. // calling the constructor -- e.g. making a list of authors and
  1089. // owners. So, this function is used to generate that information.
  1090. // It is invoked like makeEntity so that it can be dropped in easily,
  1091. // but returns an object that lets you construct many copies of an entity,
  1092. // rather than creating a new entity.
  1093. function createEntityMaker(info, views, sizes, forms) {
  1094. const maker = {};
  1095. maker.name = info.name;
  1096. maker.info = info;
  1097. maker.sizes = sizes;
  1098. maker.constructor = () => makeEntity(info, views, sizes, forms);
  1099. maker.authors = [];
  1100. maker.owners = [];
  1101. maker.nsfw = false;
  1102. Object.values(views).forEach(view => {
  1103. const authors = authorsOf(view.image.source);
  1104. if (authors) {
  1105. authors.forEach(author => {
  1106. if (maker.authors.indexOf(author) == -1) {
  1107. maker.authors.push(author);
  1108. }
  1109. });
  1110. }
  1111. const owners = ownersOf(view.image.source);
  1112. if (owners) {
  1113. owners.forEach(owner => {
  1114. if (maker.owners.indexOf(owner) == -1) {
  1115. maker.owners.push(owner);
  1116. }
  1117. });
  1118. }
  1119. if (isNsfw(view.image.source)) {
  1120. maker.nsfw = true;
  1121. }
  1122. });
  1123. return maker;
  1124. }
  1125. // This function serializes and parses its arguments to avoid sharing
  1126. // references to a common object. This allows for the objects to be
  1127. // safely mutated.
  1128. function makeEntity(info, views, sizes, forms = {}) {
  1129. const entityTemplate = {
  1130. name: info.name,
  1131. identifier: info.name,
  1132. scale: 1,
  1133. rotation: 0,
  1134. info: JSON.parse(JSON.stringify(info)),
  1135. views: JSON.parse(JSON.stringify(views), math.reviver),
  1136. sizes: sizes === undefined ? [] : JSON.parse(JSON.stringify(sizes), math.reviver),
  1137. forms: forms,
  1138. init: function () {
  1139. const entity = this;
  1140. Object.entries(this.forms).forEach(([formKey, form]) => {
  1141. if (form.default) {
  1142. this.defaultForm = formKey;
  1143. }
  1144. });
  1145. Object.entries(this.views).forEach(([viewKey, view]) => {
  1146. view.parent = this;
  1147. if (this.defaultView === undefined) {
  1148. this.defaultView = viewKey;
  1149. this.view = viewKey;
  1150. this.form = view.form;
  1151. }
  1152. if (view.default) {
  1153. if (forms === {} || this.defaultForm === view.form)
  1154. {
  1155. this.defaultView = viewKey;
  1156. this.view = viewKey;
  1157. this.form = view.form;
  1158. }
  1159. }
  1160. // to remember the units the user last picked
  1161. view.units = {};
  1162. if (config.autoMass !== "off" && view.attributes.weight === undefined) {
  1163. let base = undefined;
  1164. switch(config.autoMass) {
  1165. case "human":
  1166. baseMass = math.unit(150, "lbs")
  1167. baseHeight = math.unit(5.917, "feet")
  1168. break
  1169. case "quadruped at shoulder":
  1170. baseMass = math.unit(80, "lbs")
  1171. baseHeight = math.unit(30, "inches")
  1172. break
  1173. }
  1174. const ratio = math.divide(view.attributes.height.base, baseHeight)
  1175. view.attributes.weight = {
  1176. name: "Mass",
  1177. power: 3,
  1178. type: "mass",
  1179. base: math.multiply(baseMass, Math.pow(ratio, 3))
  1180. }
  1181. }
  1182. if (config.autoFoodIntake && view.attributes.weight !== undefined && view.attributes.energyIntake === undefined) {
  1183. view.attributes.energyIntake = {
  1184. name: "Food Intake",
  1185. power: 3 * 3/4,
  1186. type: "energy",
  1187. base: math.unit(2000 * Math.pow(view.attributes.weight.base.toNumber("lbs") / 150, 3/4), "kcal")
  1188. }
  1189. }
  1190. if (config.autoCaloricValue && view.attributes.weight !== undefined && view.attributes.energyWorth === undefined) {
  1191. view.attributes.energyValue = {
  1192. name: "Caloric Value",
  1193. power: 3,
  1194. type: "energy",
  1195. base: math.unit(860 * view.attributes.weight.base.toNumber("lbs"), "kcal")
  1196. }
  1197. }
  1198. if (config.autoPreyCapacity !== "off" && view.attributes.weight !== undefined && view.attributes.preyCapacity === undefined) {
  1199. view.attributes.preyCapacity = {
  1200. name: "Prey Capacity",
  1201. power: 3,
  1202. type: "volume",
  1203. base: math.unit((config.autoPreyCapacity == "same-size" ? 1 : 0.05) * view.attributes.weight.base.toNumber("lbs") / 150, "people")
  1204. }
  1205. }
  1206. Object.entries(view.attributes).forEach(([key, val]) => {
  1207. Object.defineProperty(
  1208. view,
  1209. key,
  1210. {
  1211. get: function () {
  1212. return math.multiply(Math.pow(this.parent.scale, this.attributes[key].power), this.attributes[key].base);
  1213. },
  1214. set: function (value) {
  1215. const newScale = Math.pow(math.divide(value, this.attributes[key].base), 1 / this.attributes[key].power);
  1216. this.parent.scale = newScale;
  1217. }
  1218. }
  1219. );
  1220. });
  1221. });
  1222. this.sizes.forEach(size => {
  1223. if (size.default === true) {
  1224. if (Object.keys(forms).length > 0) {
  1225. if (this.defaultForm !== size.form) {
  1226. return;
  1227. }
  1228. }
  1229. this.views[this.defaultView].height = size.height;
  1230. this.size = size;
  1231. }
  1232. });
  1233. if (this.size === undefined && this.sizes.length > 0) {
  1234. this.views[this.defaultView].height = this.sizes[0].height;
  1235. this.size = this.sizes[0];
  1236. console.warn("No default size set for " + info.name);
  1237. } else if (this.sizes.length == 0) {
  1238. this.sizes = [
  1239. {
  1240. name: "Normal",
  1241. height: this.views[this.defaultView].height
  1242. }
  1243. ];
  1244. this.size = this.sizes[0];
  1245. }
  1246. this.desc = {};
  1247. Object.entries(this.info).forEach(([key, value]) => {
  1248. Object.defineProperty(
  1249. this.desc,
  1250. key,
  1251. {
  1252. get: function () {
  1253. let text = value.text;
  1254. if (entity.views[entity.view].info) {
  1255. if (entity.views[entity.view].info[key]) {
  1256. text = combineInfo(text, entity.views[entity.view].info[key]);
  1257. }
  1258. }
  1259. if (entity.size.info) {
  1260. if (entity.size.info[key]) {
  1261. text = combineInfo(text, entity.size.info[key]);
  1262. }
  1263. }
  1264. return { title: value.title, text: text };
  1265. }
  1266. }
  1267. )
  1268. });
  1269. Object.defineProperty(
  1270. this,
  1271. "currentView",
  1272. {
  1273. get: function() {
  1274. return entity.views[entity.view];
  1275. }
  1276. }
  1277. )
  1278. this.formViews = {};
  1279. this.formSizes = {}
  1280. Object.entries(views).forEach(([key, value]) => {
  1281. if (value.default) {
  1282. this.formViews[value.form] = key;
  1283. }
  1284. });
  1285. Object.entries(views).forEach(([key, value]) => {
  1286. if (this.formViews[value.form] === undefined) {
  1287. this.formViews[value.form] = key;
  1288. }
  1289. });
  1290. this.sizes.forEach(size => {
  1291. if (size.default) {
  1292. this.formSizes[size.form] = size;
  1293. }
  1294. })
  1295. this.sizes.forEach(size => {
  1296. if (this.formSizes[size.form] === undefined) {
  1297. this.formSizes[size.form] = size;
  1298. }
  1299. });
  1300. Object.values(views).forEach(view => {
  1301. if (this.formSizes[view.form] === undefined) {
  1302. this.formSizes[view.form] = { name: "Normal", height: view.attributes.height.base, default: true, form: view.form };
  1303. }
  1304. });
  1305. delete this.init;
  1306. return this;
  1307. }
  1308. }.init();
  1309. return entityTemplate;
  1310. }
  1311. function combineInfo(existing, next) {
  1312. switch (next.mode) {
  1313. case "replace":
  1314. return next.text;
  1315. case "prepend":
  1316. return next.text + existing;
  1317. case "append":
  1318. return existing + next.text;
  1319. }
  1320. return existing;
  1321. }
  1322. function clickDown(target, x, y) {
  1323. clicked = target;
  1324. movingInBounds = false;
  1325. const rect = target.getBoundingClientRect();
  1326. let entX = document.querySelector("#entities").getBoundingClientRect().x;
  1327. let entY = document.querySelector("#entities").getBoundingClientRect().y;
  1328. dragOffsetX = x - rect.left + entX;
  1329. dragOffsetY = y - rect.top + entY;
  1330. x = x - dragOffsetX;
  1331. y = y - dragOffsetY;
  1332. if (x >= 0 && x <= canvasWidth && y >= 0 && y <= canvasHeight) {
  1333. movingInBounds = true;
  1334. }
  1335. clickTimeout = setTimeout(() => { dragging = true }, 200)
  1336. target.classList.add("no-transition");
  1337. }
  1338. // could we make this actually detect the menu area?
  1339. function hoveringInDeleteArea(e) {
  1340. return e.clientY < document.querySelector("#menubar").clientHeight;
  1341. }
  1342. function clickUp(e) {
  1343. if (e.which != 1) {
  1344. return;
  1345. }
  1346. clearTimeout(clickTimeout);
  1347. if (clicked) {
  1348. clicked.classList.remove("no-transition");
  1349. if (dragging) {
  1350. dragging = false;
  1351. if (hoveringInDeleteArea(e)) {
  1352. removeEntity(clicked);
  1353. document.querySelector("#menubar").classList.remove("hover-delete");
  1354. }
  1355. } else {
  1356. select(clicked);
  1357. }
  1358. clicked = null;
  1359. }
  1360. }
  1361. function deselect(e) {
  1362. if (rulerMode) {
  1363. return;
  1364. }
  1365. if (e !== undefined && e.which != 1) {
  1366. return;
  1367. }
  1368. if (selected) {
  1369. selected.classList.remove("selected");
  1370. }
  1371. if (prevSelected) {
  1372. prevSelected.classList.remove("prevSelected");
  1373. }
  1374. document.getElementById("options-selected-entity-none").selected = "selected";
  1375. document.getElementById("delete-entity").style.display = "none";
  1376. clearAttribution();
  1377. selected = null;
  1378. clearViewList();
  1379. clearEntityOptions();
  1380. clearViewOptions();
  1381. document.querySelector("#delete-entity").disabled = true;
  1382. document.querySelector("#grow").disabled = true;
  1383. document.querySelector("#shrink").disabled = true;
  1384. document.querySelector("#fit").disabled = true;
  1385. }
  1386. function select(target) {
  1387. if (prevSelected !== null) {
  1388. prevSelected.classList.remove("prevSelected");
  1389. }
  1390. prevSelected = selected;
  1391. prevSelectedEntity = selectedEntity;
  1392. deselect();
  1393. selected = target;
  1394. selectedEntity = entities[target.dataset.key];
  1395. updateInfo();
  1396. document.getElementById("options-selected-entity-" + target.dataset.key).selected = "selected";
  1397. document.getElementById("delete-entity").style.display = "";
  1398. if (prevSelected !== null && config.showRatios && selected !== prevSelected) {
  1399. prevSelected.classList.add("prevSelected");
  1400. }
  1401. selected.classList.add("selected");
  1402. displayAttribution(selectedEntity.views[selectedEntity.view].image.source);
  1403. configFormList(selectedEntity, selectedEntity.form);
  1404. configViewList(selectedEntity, selectedEntity.view);
  1405. configEntityOptions(selectedEntity, selectedEntity.view);
  1406. configViewOptions(selectedEntity, selectedEntity.view);
  1407. document.querySelector("#delete-entity").disabled = false;
  1408. document.querySelector("#grow").disabled = false;
  1409. document.querySelector("#shrink").disabled = false;
  1410. document.querySelector("#fit").disabled = false;
  1411. }
  1412. function configFormList(entity, selectedForm) {
  1413. const label = document.querySelector("#options-label-form");
  1414. const list = document.querySelector("#entity-form");
  1415. list.innerHTML = "";
  1416. if (selectedForm === undefined) {
  1417. label.style.display = "none";
  1418. list.style.display = "none";
  1419. return;
  1420. }
  1421. label.style.display = "block";
  1422. list.style.display = "block";
  1423. Object.keys(entity.forms).forEach(form => {
  1424. const option = document.createElement("option");
  1425. option.innerText = entity.forms[form].name;
  1426. option.value = form;
  1427. if (form === selectedForm) {
  1428. option.selected = true;
  1429. }
  1430. list.appendChild(option);
  1431. });
  1432. }
  1433. function configViewList(entity, selectedView) {
  1434. const list = document.querySelector("#entity-view");
  1435. list.innerHTML = "";
  1436. list.style.display = "block";
  1437. Object.keys(entity.views).forEach(view => {
  1438. if (Object.keys(entity.forms).length > 0) {
  1439. if (entity.views[view].form !== entity.form) {
  1440. return;
  1441. }
  1442. }
  1443. const option = document.createElement("option");
  1444. option.innerText = entity.views[view].name;
  1445. option.value = view;
  1446. if (isNsfw(entity.views[view].image.source)) {
  1447. option.classList.add("nsfw")
  1448. }
  1449. if (view === selectedView) {
  1450. option.selected = true;
  1451. if (option.classList.contains("nsfw")) {
  1452. list.classList.add("nsfw");
  1453. } else {
  1454. list.classList.remove("nsfw");
  1455. }
  1456. }
  1457. list.appendChild(option);
  1458. });
  1459. }
  1460. function clearViewList() {
  1461. const list = document.querySelector("#entity-view");
  1462. list.innerHTML = "";
  1463. list.style.display = "none";
  1464. }
  1465. function updateWorldOptions(entity, view) {
  1466. const heightInput = document.querySelector("#options-height-value");
  1467. const heightSelect = document.querySelector("#options-height-unit");
  1468. const converted = config.height.toNumber(heightSelect.value);
  1469. setNumericInput(heightInput, converted);
  1470. }
  1471. function configEntityOptions(entity, view) {
  1472. const holder = document.querySelector("#options-entity");
  1473. document.querySelector("#entity-category-header").style.display = "block";
  1474. document.querySelector("#entity-category").style.display = "block";
  1475. holder.innerHTML = "";
  1476. const scaleLabel = document.createElement("div");
  1477. scaleLabel.classList.add("options-label");
  1478. scaleLabel.innerText = "Scale";
  1479. const scaleRow = document.createElement("div");
  1480. scaleRow.classList.add("options-row");
  1481. const scaleInput = document.createElement("input");
  1482. scaleInput.classList.add("options-field-numeric");
  1483. scaleInput.id = "options-entity-scale";
  1484. scaleInput.addEventListener("change", e => {
  1485. try {
  1486. const newScale = e.target.value == 0 ? 1 : math.evaluate(e.target.value);
  1487. if (typeof(newScale) !== "number") {
  1488. toast("Invalid input: scale can't have any units!")
  1489. return;
  1490. }
  1491. entity.scale = newScale;
  1492. } catch {
  1493. toast("Invalid input: could not parse " + e.target.value)
  1494. }
  1495. entity.dirty = true;
  1496. if (config.autoFit) {
  1497. fitWorld();
  1498. } else {
  1499. updateSizes(true);
  1500. }
  1501. updateEntityOptions(entity, entity.view);
  1502. updateViewOptions(entity, entity.view);
  1503. });
  1504. scaleInput.addEventListener("keydown", e => {
  1505. e.stopPropagation();
  1506. })
  1507. setNumericInput(scaleInput, entity.scale);
  1508. scaleRow.appendChild(scaleInput);
  1509. holder.appendChild(scaleLabel);
  1510. holder.appendChild(scaleRow);
  1511. const nameLabel = document.createElement("div");
  1512. nameLabel.classList.add("options-label");
  1513. nameLabel.innerText = "Name";
  1514. const nameRow = document.createElement("div");
  1515. nameRow.classList.add("options-row");
  1516. const nameInput = document.createElement("input");
  1517. nameInput.classList.add("options-field-text");
  1518. nameInput.value = entity.name;
  1519. nameInput.addEventListener("input", e => {
  1520. entity.name = e.target.value;
  1521. entity.dirty = true;
  1522. updateSizes(true);
  1523. })
  1524. nameInput.addEventListener("keydown", e => {
  1525. e.stopPropagation();
  1526. })
  1527. nameRow.appendChild(nameInput);
  1528. holder.appendChild(nameLabel);
  1529. holder.appendChild(nameRow);
  1530. configSizeList(entity);
  1531. document.querySelector("#options-order-display").innerText = entity.priority;
  1532. document.querySelector("#options-brightness-display").innerText = entity.brightness;
  1533. document.querySelector("#options-ordering").style.display = "flex";
  1534. }
  1535. function configSizeList(entity) {
  1536. const defaultHolder = document.querySelector("#options-entity-defaults");
  1537. defaultHolder.innerHTML = "";
  1538. entity.sizes.forEach(defaultInfo => {
  1539. if (Object.keys(entity.forms).length > 0) {
  1540. if (defaultInfo.form !== entity.form) {
  1541. return;
  1542. }
  1543. }
  1544. const button = document.createElement("button");
  1545. button.classList.add("options-button");
  1546. button.innerText = defaultInfo.name;
  1547. button.addEventListener("click", e => {
  1548. if (Object.keys(entity.forms).length > 0) {
  1549. entity.views[entity.formViews[entity.form]].height = defaultInfo.height;
  1550. } else {
  1551. entity.views[entity.defaultView].height = defaultInfo.height;
  1552. }
  1553. entity.dirty = true;
  1554. updateEntityOptions(entity, entity.view);
  1555. updateViewOptions(entity, entity.view);
  1556. if (!checkFitWorld()) {
  1557. updateSizes(true);
  1558. }
  1559. if (config.autoFitSize) {
  1560. let targets = {};
  1561. targets[selected.dataset.key] = entities[selected.dataset.key];
  1562. fitEntities(targets);
  1563. }
  1564. });
  1565. defaultHolder.appendChild(button);
  1566. });
  1567. }
  1568. function updateEntityOptions(entity, view) {
  1569. const scaleInput = document.querySelector("#options-entity-scale");
  1570. setNumericInput(scaleInput, entity.scale);
  1571. document.querySelector("#options-order-display").innerText = entity.priority;
  1572. document.querySelector("#options-brightness-display").innerText = entity.brightness;
  1573. }
  1574. function clearEntityOptions() {
  1575. document.querySelector("#entity-category-header").style.display = "none";
  1576. document.querySelector("#entity-category").style.display = "none";
  1577. /*
  1578. const holder = document.querySelector("#options-entity");
  1579. holder.innerHTML = "";
  1580. document.querySelector("#options-entity-defaults").innerHTML = "";
  1581. document.querySelector("#options-ordering").style.display = "none";
  1582. document.querySelector("#options-ordering").style.display = "none";*/
  1583. }
  1584. function configViewOptions(entity, view) {
  1585. const holder = document.querySelector("#options-view");
  1586. document.querySelector("#view-category-header").style.display = "block";
  1587. document.querySelector("#view-category").style.display = "block";
  1588. holder.innerHTML = "";
  1589. Object.entries(entity.views[view].attributes).forEach(([key, val]) => {
  1590. const label = document.createElement("div");
  1591. label.classList.add("options-label");
  1592. label.innerText = val.name;
  1593. holder.appendChild(label);
  1594. const row = document.createElement("div");
  1595. row.classList.add("options-row");
  1596. holder.appendChild(row);
  1597. const input = document.createElement("input");
  1598. input.classList.add("options-field-numeric");
  1599. input.id = "options-view-" + key + "-input";
  1600. const select = document.createElement("select");
  1601. select.classList.add("options-field-unit");
  1602. select.id = "options-view-" + key + "-select"
  1603. Object.entries(unitChoices[val.type]).forEach(([group, entries]) => {
  1604. const optGroup = document.createElement("optgroup");
  1605. optGroup.label = group;
  1606. select.appendChild(optGroup);
  1607. entries.forEach(entry => {
  1608. const option = document.createElement("option");
  1609. option.innerText = entry;
  1610. if (entry == defaultUnits[val.type][config.units]) {
  1611. option.selected = true;
  1612. }
  1613. select.appendChild(option);
  1614. })
  1615. });
  1616. input.addEventListener("change", e => {
  1617. const raw_value = input.value == 0 ? 1 : input.value;
  1618. let value
  1619. try {
  1620. value = math.evaluate(raw_value).toNumber(select.value);
  1621. } catch {
  1622. try {
  1623. value = math.evaluate(input.value)
  1624. if (typeof(value) !== "number") {
  1625. toast("Invalid input: " + value.format() + " can't convert to " + select.value)
  1626. value = undefined
  1627. }
  1628. } catch {
  1629. toast("Invalid input: could not parse: " + input.value)
  1630. value = undefined
  1631. }
  1632. }
  1633. if (value === undefined) {
  1634. return;
  1635. }
  1636. input.value = value
  1637. entity.views[view][key] = math.unit(value, select.value);
  1638. entity.dirty = true;
  1639. if (config.autoFit) {
  1640. fitWorld();
  1641. } else {
  1642. updateSizes(true);
  1643. }
  1644. updateEntityOptions(entity, view);
  1645. updateViewOptions(entity, view, key);
  1646. });
  1647. input.addEventListener("keydown", e => {
  1648. e.stopPropagation();
  1649. })
  1650. if (entity.currentView.units[key]) {
  1651. select.value = entity.currentView.units[key];
  1652. } else {
  1653. entity.currentView.units[key] = select.value;
  1654. }
  1655. select.dataset.oldUnit = select.value;
  1656. setNumericInput(input, entity.views[view][key].toNumber(select.value));
  1657. // TODO does this ever cause a change in the world?
  1658. select.addEventListener("input", e => {
  1659. const value = input.value == 0 ? 1 : input.value;
  1660. const oldUnit = select.dataset.oldUnit;
  1661. entity.views[entity.view][key] = math.unit(value, oldUnit).to(select.value);
  1662. entity.dirty = true;
  1663. setNumericInput(input, entity.views[entity.view][key].toNumber(select.value));
  1664. select.dataset.oldUnit = select.value;
  1665. entity.views[view].units[key] = select.value;
  1666. if (config.autoFit) {
  1667. fitWorld();
  1668. } else {
  1669. updateSizes(true);
  1670. }
  1671. updateEntityOptions(entity, view);
  1672. updateViewOptions(entity, view, key);
  1673. });
  1674. row.appendChild(input);
  1675. row.appendChild(select);
  1676. });
  1677. }
  1678. function updateViewOptions(entity, view, changed) {
  1679. Object.entries(entity.views[view].attributes).forEach(([key, val]) => {
  1680. if (key != changed) {
  1681. const input = document.querySelector("#options-view-" + key + "-input");
  1682. const select = document.querySelector("#options-view-" + key + "-select");
  1683. const currentUnit = select.value;
  1684. const convertedAmount = entity.views[view][key].toNumber(currentUnit);
  1685. setNumericInput(input, convertedAmount);
  1686. }
  1687. });
  1688. }
  1689. function setNumericInput(input, value, round = 6) {
  1690. if (typeof value == "string") {
  1691. value = parseFloat(value)
  1692. }
  1693. input.value = value.toPrecision(round);
  1694. }
  1695. function getSortedEntities() {
  1696. return Object.keys(entities).sort((a, b) => {
  1697. const entA = entities[a];
  1698. const entB = entities[b];
  1699. const viewA = entA.view;
  1700. const viewB = entB.view;
  1701. const heightA = entA.views[viewA].height.to("meter").value;
  1702. const heightB = entB.views[viewB].height.to("meter").value;
  1703. return heightA - heightB;
  1704. });
  1705. }
  1706. function clearViewOptions() {
  1707. document.querySelector("#view-category-header").style.display = "none";
  1708. document.querySelector("#view-category").style.display = "none";
  1709. }
  1710. // this is a crime against humanity, and also stolen from
  1711. // stack overflow
  1712. // https://stackoverflow.com/questions/38487569/click-through-png-image-only-if-clicked-coordinate-is-transparent
  1713. const testCanvas = document.createElement("canvas");
  1714. testCanvas.id = "test-canvas";
  1715. function rotate(point, angle) {
  1716. return [
  1717. point[0] * Math.cos(angle) - point[1] * Math.sin(angle),
  1718. point[0] * Math.sin(angle) + point[1] * Math.cos(angle)
  1719. ];
  1720. }
  1721. const testCtx = testCanvas.getContext("2d");
  1722. function testClick(event) {
  1723. const target = event.target;
  1724. if (webkitCanvasBug)
  1725. {
  1726. return clickDown(target.parentElement, event.clientX, event.clientY);
  1727. }
  1728. testCtx.save();
  1729. if (rulerMode) {
  1730. return;
  1731. }
  1732. // Get click coordinates
  1733. let w = target.width;
  1734. let h = target.height;
  1735. let ratioW = 1, ratioH = 1;
  1736. // Limit the size of the canvas so that very large images don't cause problems)
  1737. if (w > 1000) {
  1738. ratioW = w / 1000;
  1739. w /= ratioW;
  1740. h /= ratioW;
  1741. }
  1742. if (h > 1000) {
  1743. ratioH = h / 1000;
  1744. w /= ratioH;
  1745. h /= ratioH;
  1746. }
  1747. // todo remove some of this unused stuff
  1748. const ratio = ratioW * ratioH;
  1749. const entity = entities[target.parentElement.dataset.key];
  1750. const angle = entity.rotation;
  1751. var x = event.clientX - target.getBoundingClientRect().x,
  1752. y = event.clientY - target.getBoundingClientRect().y,
  1753. alpha;
  1754. [xTarget,yTarget] = [x,y];
  1755. [actualW, actualH] = [target.getBoundingClientRect().width, target.getBoundingClientRect().height];
  1756. xTarget /= ratio;
  1757. yTarget /= ratio;
  1758. actualW /= ratio;
  1759. actualH /= ratio;
  1760. testCtx.canvas.width = actualW;
  1761. testCtx.canvas.height = actualH;
  1762. testCtx.save();
  1763. // dear future me: Sorry :(
  1764. testCtx.resetTransform();
  1765. testCtx.translate(actualW/2, actualH/2);
  1766. testCtx.rotate(angle);
  1767. testCtx.translate(-actualW/2, -actualH/2);
  1768. testCtx.drawImage(target, (actualW/2 - w/2), (actualH/2 - h/2), w, h);
  1769. testCtx.fillStyle = "red";
  1770. testCtx.fillRect(actualW/2,actualH/2,10,10);
  1771. testCtx.restore();
  1772. testCtx.fillStyle = "red";
  1773. alpha = testCtx.getImageData(xTarget, yTarget, 1, 1).data[3];
  1774. testCtx.fillRect(xTarget, yTarget, 3, 3);
  1775. // If the pixel is transparent,
  1776. // retrieve the element underneath and trigger its click event
  1777. if (alpha === 0) {
  1778. const oldDisplay = target.style.display;
  1779. target.style.display = "none";
  1780. const newTarget = document.elementFromPoint(event.clientX, event.clientY);
  1781. newTarget.dispatchEvent(new MouseEvent(event.type, {
  1782. "clientX": event.clientX,
  1783. "clientY": event.clientY
  1784. }));
  1785. target.style.display = oldDisplay;
  1786. } else {
  1787. clickDown(target.parentElement, event.clientX, event.clientY);
  1788. }
  1789. testCtx.restore();
  1790. }
  1791. function arrangeEntities(order) {
  1792. const worldWidth = config.height.toNumber("meters") / canvasHeight * canvasWidth;
  1793. let sum = 0;
  1794. order.forEach(key => {
  1795. const image = document.querySelector("#entity-" + key + " > .entity-image");
  1796. const meters = entities[key].views[entities[key].view].height.toNumber("meters");
  1797. let height = image.height;
  1798. let width = image.width;
  1799. if (height == 0) {
  1800. height = 100;
  1801. }
  1802. if (width == 0) {
  1803. width = height;
  1804. }
  1805. sum += meters * width / height;
  1806. });
  1807. let x = config.x - sum / 2;
  1808. order.forEach(key => {
  1809. const image = document.querySelector("#entity-" + key + " > .entity-image");
  1810. const meters = entities[key].views[entities[key].view].height.toNumber("meters");
  1811. let height = image.height;
  1812. let width = image.width;
  1813. if (height == 0) {
  1814. height = 100;
  1815. }
  1816. if (width == 0) {
  1817. width = height;
  1818. }
  1819. x += meters * width / height / 2;
  1820. document.querySelector("#entity-" + key).dataset.x = x;
  1821. document.querySelector("#entity-" + key).dataset.y = config.y;
  1822. x += meters * width / height / 2;
  1823. })
  1824. fitWorld();
  1825. updateSizes();
  1826. }
  1827. function removeAllEntities() {
  1828. Object.keys(entities).forEach(key => {
  1829. removeEntity(document.querySelector("#entity-" + key));
  1830. });
  1831. }
  1832. function clearAttribution() {
  1833. document.querySelector("#attribution-category-header").style.display = "none";
  1834. document.querySelector("#options-attribution").style.display = "none";
  1835. }
  1836. function displayAttribution(file) {
  1837. document.querySelector("#attribution-category-header").style.display = "block";
  1838. document.querySelector("#options-attribution").style.display = "inline";
  1839. const authors = authorsOfFull(file);
  1840. const owners = ownersOfFull(file);
  1841. const citations = citationsOf(file);
  1842. const source = sourceOf(file);
  1843. const authorHolder = document.querySelector("#options-attribution-authors");
  1844. const ownerHolder = document.querySelector("#options-attribution-owners");
  1845. const citationHolder = document.querySelector("#options-attribution-citations");
  1846. const sourceHolder = document.querySelector("#options-attribution-source");
  1847. if (authors === []) {
  1848. const div = document.createElement("div");
  1849. div.innerText = "Unknown";
  1850. authorHolder.innerHTML = "";
  1851. authorHolder.appendChild(div);
  1852. } else if (authors === undefined) {
  1853. const div = document.createElement("div");
  1854. div.innerText = "Not yet entered";
  1855. authorHolder.innerHTML = "";
  1856. authorHolder.appendChild(div);
  1857. } else {
  1858. authorHolder.innerHTML = "";
  1859. const list = document.createElement("ul");
  1860. authorHolder.appendChild(list);
  1861. authors.forEach(author => {
  1862. const authorEntry = document.createElement("li");
  1863. if (author.url) {
  1864. const link = document.createElement("a");
  1865. link.href = author.url;
  1866. link.innerText = author.name;
  1867. link.rel = "noreferrer no opener";
  1868. link.target = "_blank";
  1869. authorEntry.appendChild(link);
  1870. } else {
  1871. const div = document.createElement("div");
  1872. div.innerText = author.name;
  1873. authorEntry.appendChild(div);
  1874. }
  1875. list.appendChild(authorEntry);
  1876. });
  1877. }
  1878. if (owners === []) {
  1879. const div = document.createElement("div");
  1880. div.innerText = "Unknown";
  1881. ownerHolder.innerHTML = "";
  1882. ownerHolder.appendChild(div);
  1883. } else if (owners === undefined) {
  1884. const div = document.createElement("div");
  1885. div.innerText = "Not yet entered";
  1886. ownerHolder.innerHTML = "";
  1887. ownerHolder.appendChild(div);
  1888. } else {
  1889. ownerHolder.innerHTML = "";
  1890. const list = document.createElement("ul");
  1891. ownerHolder.appendChild(list);
  1892. owners.forEach(owner => {
  1893. const ownerEntry = document.createElement("li");
  1894. if (owner.url) {
  1895. const link = document.createElement("a");
  1896. link.href = owner.url;
  1897. link.innerText = owner.name;
  1898. link.rel = "noreferrer no opener";
  1899. link.target = "_blank";
  1900. ownerEntry.appendChild(link);
  1901. } else {
  1902. const div = document.createElement("div");
  1903. div.innerText = owner.name;
  1904. ownerEntry.appendChild(div);
  1905. }
  1906. list.appendChild(ownerEntry);
  1907. });
  1908. }
  1909. if (citations === [] || citations === undefined) {
  1910. } else {
  1911. citationHolder.innerHTML = "";
  1912. const list = document.createElement("ul");
  1913. citationHolder.appendChild(list);
  1914. citations.forEach(citation => {
  1915. const citationEntry = document.createElement("li");
  1916. const link = document.createElement("a");
  1917. link.style.display = "block";
  1918. link.href = citation;
  1919. link.innerText = new URL(citation).host;
  1920. link.rel = "noreferrer no opener";
  1921. link.target = "_blank";
  1922. citationEntry.appendChild(link);
  1923. list.appendChild(citationEntry);
  1924. })
  1925. }
  1926. if (source === null) {
  1927. const div = document.createElement("div");
  1928. div.innerText = "No link";
  1929. sourceHolder.innerHTML = "";
  1930. sourceHolder.appendChild(div);
  1931. } else if (source === undefined) {
  1932. const div = document.createElement("div");
  1933. div.innerText = "Not yet entered";
  1934. sourceHolder.innerHTML = "";
  1935. sourceHolder.appendChild(div);
  1936. } else {
  1937. sourceHolder.innerHTML = "";
  1938. const link = document.createElement("a");
  1939. link.style.display = "block";
  1940. link.href = source;
  1941. link.innerText = new URL(source).host;
  1942. link.rel = "noreferrer no opener";
  1943. link.target = "_blank";
  1944. sourceHolder.appendChild(link);
  1945. }
  1946. }
  1947. function removeEntity(element) {
  1948. if (selected == element) {
  1949. deselect();
  1950. }
  1951. if (clicked == element) {
  1952. clicked = null;
  1953. }
  1954. const option = document.querySelector("#options-selected-entity-" + element.dataset.key);
  1955. option.parentElement.removeChild(option);
  1956. delete entities[element.dataset.key];
  1957. const bottomName = document.querySelector("#bottom-name-" + element.dataset.key);
  1958. const topName = document.querySelector("#top-name-" + element.dataset.key);
  1959. bottomName.parentElement.removeChild(bottomName);
  1960. topName.parentElement.removeChild(topName);
  1961. element.parentElement.removeChild(element);
  1962. selectedEntity = null;
  1963. prevSelectedEntity = null;
  1964. updateInfo();
  1965. }
  1966. function checkEntity(entity) {
  1967. Object.values(entity.views).forEach(view => {
  1968. if (authorsOf(view.image.source) === undefined) {
  1969. console.warn("No authors: " + view.image.source);
  1970. }
  1971. });
  1972. }
  1973. function preloadViews(entity) {
  1974. Object.values(entity.views).forEach(view => {
  1975. if (Object.keys(entity.forms).length > 0) {
  1976. if (entity.form !== view.form){
  1977. return;
  1978. }
  1979. }
  1980. if (!preloaded.has(view.image.source)) {
  1981. let img = new Image();
  1982. img.src = view.image.source;
  1983. preloaded.add(view.image.source);
  1984. }
  1985. });
  1986. }
  1987. function displayEntity(entity, view, x, y, selectEntity = false, refresh = false) {
  1988. checkEntity(entity);
  1989. // preload all of the entity's views
  1990. preloadViews(entity);
  1991. const box = document.createElement("div");
  1992. box.classList.add("entity-box");
  1993. const img = document.createElement("img");
  1994. img.classList.add("entity-image");
  1995. img.addEventListener("dragstart", e => {
  1996. e.preventDefault();
  1997. });
  1998. const nameTag = document.createElement("div");
  1999. nameTag.classList.add("entity-name");
  2000. nameTag.innerText = entity.name;
  2001. box.appendChild(img);
  2002. box.appendChild(nameTag);
  2003. const image = entity.views[view].image;
  2004. img.src = image.source;
  2005. if (image.bottom !== undefined) {
  2006. img.style.setProperty("--offset", ((-1 + image.bottom) * 100) + "%")
  2007. } else {
  2008. img.style.setProperty("--offset", ((-1) * 100) + "%")
  2009. }
  2010. img.style.setProperty("--rotation", (entity.rotation * 180 / Math.PI) + "deg")
  2011. box.dataset.x = x;
  2012. box.dataset.y = y;
  2013. img.addEventListener("mousedown", e => { if (e.which == 1) { testClick(e); if (clicked) { e.stopPropagation() } } });
  2014. img.addEventListener("touchstart", e => {
  2015. const fakeEvent = {
  2016. target: e.target,
  2017. clientX: e.touches[0].clientX,
  2018. clientY: e.touches[0].clientY,
  2019. which: 1
  2020. };
  2021. testClick(fakeEvent);
  2022. if (clicked) { e.stopPropagation() }
  2023. });
  2024. const heightBar = document.createElement("div");
  2025. heightBar.classList.add("height-bar");
  2026. box.appendChild(heightBar);
  2027. box.id = "entity-" + entityIndex;
  2028. box.dataset.key = entityIndex;
  2029. entity.view = view;
  2030. if (entity.priority === undefined)
  2031. entity.priority = 0;
  2032. if (entity.brightness === undefined)
  2033. entity.brightness = 1;
  2034. entities[entityIndex] = entity;
  2035. entity.index = entityIndex;
  2036. const world = document.querySelector("#entities");
  2037. world.appendChild(box);
  2038. const bottomName = document.createElement("div");
  2039. bottomName.classList.add("bottom-name");
  2040. bottomName.id = "bottom-name-" + entityIndex;
  2041. bottomName.innerText = entity.name;
  2042. bottomName.addEventListener("click", () => select(box));
  2043. world.appendChild(bottomName);
  2044. const topName = document.createElement("div");
  2045. topName.classList.add("top-name");
  2046. topName.id = "top-name-" + entityIndex;
  2047. topName.innerText = entity.name;
  2048. topName.addEventListener("click", () => select(box));
  2049. world.appendChild(topName);
  2050. const entityOption = document.createElement("option");
  2051. entityOption.id = "options-selected-entity-" + entityIndex;
  2052. entityOption.value = entityIndex;
  2053. entityOption.innerText = entity.name;
  2054. document.getElementById("options-selected-entity").appendChild(entityOption);
  2055. entityIndex += 1;
  2056. if (config.autoFit) {
  2057. fitWorld();
  2058. }
  2059. if (selectEntity)
  2060. select(box);
  2061. entity.dirty = true;
  2062. if (refresh && config.autoFitAdd) {
  2063. let targets = {};
  2064. targets[entityIndex - 1] = entity;
  2065. fitEntities(targets);
  2066. }
  2067. if (refresh)
  2068. updateSizes(true);
  2069. }
  2070. window.onblur = function () {
  2071. altHeld = false;
  2072. shiftHeld = false;
  2073. }
  2074. window.onfocus = function () {
  2075. window.dispatchEvent(new Event("keydown"));
  2076. }
  2077. // thanks to https://developers.google.com/web/fundamentals/native-hardware/fullscreen
  2078. function toggleFullScreen() {
  2079. var doc = window.document;
  2080. var docEl = doc.documentElement;
  2081. var requestFullScreen = docEl.requestFullscreen || docEl.mozRequestFullScreen || docEl.webkitRequestFullScreen || docEl.msRequestFullscreen;
  2082. var cancelFullScreen = doc.exitFullscreen || doc.mozCancelFullScreen || doc.webkitExitFullscreen || doc.msExitFullscreen;
  2083. if (!doc.fullscreenElement && !doc.mozFullScreenElement && !doc.webkitFullscreenElement && !doc.msFullscreenElement) {
  2084. requestFullScreen.call(docEl);
  2085. }
  2086. else {
  2087. cancelFullScreen.call(doc);
  2088. }
  2089. }
  2090. function handleResize() {
  2091. const oldCanvasWidth = canvasWidth;
  2092. entityX = document.querySelector("#entities").getBoundingClientRect().x;
  2093. canvasWidth = document.querySelector("#display").clientWidth - 100;
  2094. canvasHeight = document.querySelector("#display").clientHeight - 50;
  2095. const change = oldCanvasWidth / canvasWidth;
  2096. updateSizes();
  2097. }
  2098. function prepareSidebar() {
  2099. const menubar = document.querySelector("#sidebar-menu");
  2100. [
  2101. {
  2102. name: "Show/hide sidebar",
  2103. id: "menu-toggle-sidebar",
  2104. icon: "fas fa-chevron-circle-down",
  2105. rotates: true
  2106. },
  2107. {
  2108. name: "Fullscreen",
  2109. id: "menu-fullscreen",
  2110. icon: "fas fa-compress"
  2111. },
  2112. {
  2113. name: "Clear",
  2114. id: "menu-clear",
  2115. icon: "fas fa-file"
  2116. },
  2117. {
  2118. name: "Sort by height",
  2119. id: "menu-order-height",
  2120. icon: "fas fa-sort-numeric-up"
  2121. },
  2122. {
  2123. name: "Permalink",
  2124. id: "menu-permalink",
  2125. icon: "fas fa-link"
  2126. },
  2127. {
  2128. name: "Export to clipboard",
  2129. id: "menu-export",
  2130. icon: "fas fa-share"
  2131. },
  2132. {
  2133. name: "Import from clipboard",
  2134. id: "menu-import",
  2135. icon: "fas fa-share",
  2136. classes: ["flipped"]
  2137. },
  2138. {
  2139. name: "Save Scene",
  2140. id: "menu-save",
  2141. icon: "fas fa-download",
  2142. input: true
  2143. },
  2144. {
  2145. name: "Load Scene",
  2146. id: "menu-load",
  2147. icon: "fas fa-upload",
  2148. select: true
  2149. },
  2150. {
  2151. name: "Delete Scene",
  2152. id: "menu-delete",
  2153. icon: "fas fa-trash",
  2154. select: true
  2155. },
  2156. {
  2157. name: "Load Autosave",
  2158. id: "menu-load-autosave",
  2159. icon: "fas fa-redo"
  2160. },
  2161. {
  2162. name: "Load Preset",
  2163. id: "menu-preset",
  2164. icon: "fas fa-play",
  2165. select: true
  2166. },
  2167. {
  2168. name: "Add Image",
  2169. id: "menu-add-image",
  2170. icon: "fas fa-camera"
  2171. },
  2172. {
  2173. name: "Clear Rulers",
  2174. id: "menu-clear-rulers",
  2175. icon: "fas fa-ruler"
  2176. }
  2177. ].forEach(entry => {
  2178. const buttonHolder = document.createElement("div");
  2179. buttonHolder.classList.add("menu-button-holder");
  2180. const button = document.createElement("button");
  2181. button.id = entry.id;
  2182. button.classList.add("menu-button");
  2183. const icon = document.createElement("i");
  2184. icon.classList.add(...entry.icon.split(" "));
  2185. if (entry.rotates) {
  2186. icon.classList.add("rotate-backward", "transitions");
  2187. }
  2188. if (entry.classes) {
  2189. entry.classes.forEach(cls => icon.classList.add(cls));
  2190. }
  2191. const actionText = document.createElement("span");
  2192. actionText.innerText = entry.name;
  2193. actionText.classList.add("menu-text");
  2194. const srText = document.createElement("span");
  2195. srText.classList.add("sr-only");
  2196. srText.innerText = entry.name;
  2197. button.appendChild(icon);
  2198. button.appendChild(srText);
  2199. buttonHolder.appendChild(button);
  2200. buttonHolder.appendChild(actionText);
  2201. if (entry.input) {
  2202. const input = document.createElement("input");
  2203. buttonHolder.appendChild(input);
  2204. input.placeholder = "default";
  2205. input.addEventListener("keyup", e => {
  2206. if (e.key === "Enter") {
  2207. const name = document.querySelector("#menu-save ~ input").value;
  2208. if (/\S/.test(name)) {
  2209. saveScene(name);
  2210. }
  2211. updateSaveInfo();
  2212. e.preventDefault();
  2213. }
  2214. })
  2215. }
  2216. if (entry.select) {
  2217. const select = document.createElement("select");
  2218. buttonHolder.appendChild(select);
  2219. }
  2220. menubar.appendChild(buttonHolder);
  2221. });
  2222. }
  2223. function checkBodyClass(cls) {
  2224. return document.body.classList.contains(cls);
  2225. }
  2226. function toggleBodyClass(cls, setting) {
  2227. if (setting) {
  2228. document.body.classList.add(cls);
  2229. } else {
  2230. document.body.classList.remove(cls);
  2231. }
  2232. }
  2233. const backgroundColors = {
  2234. "none": "#00000000",
  2235. "black": "#000",
  2236. "dark": "#111",
  2237. "medium": "#333",
  2238. "light": "#555"
  2239. }
  2240. const settingsCategories = {
  2241. "background": "Background",
  2242. "controls": "Controls",
  2243. "info": "Info",
  2244. "visuals": "Visuals"
  2245. }
  2246. const groundPosChoices = [
  2247. "very-high",
  2248. "high",
  2249. "medium",
  2250. "low",
  2251. "very-low",
  2252. "bottom",
  2253. ];
  2254. const settingsData = {
  2255. "show-vertical-scale": {
  2256. name: "Vertical Scale",
  2257. desc: "Draw vertical scale marks",
  2258. type: "toggle",
  2259. default: true,
  2260. get value() {
  2261. return config.drawYAxis;
  2262. },
  2263. set value(param) {
  2264. config.drawYAxis = param;
  2265. drawScales(false);
  2266. }
  2267. },
  2268. "show-horizontal-scale": {
  2269. name: "Horiziontal Scale",
  2270. desc: "Draw horizontal scale marks",
  2271. type: "toggle",
  2272. default: false,
  2273. get value() {
  2274. return config.drawXAxis;
  2275. },
  2276. set value(param) {
  2277. config.drawXAxis = param;
  2278. drawScales(false);
  2279. }
  2280. },
  2281. "show-altitudes": {
  2282. name: "Altitudes",
  2283. desc: "Draw interesting altitudes",
  2284. type: "select",
  2285. default: "none",
  2286. disabled: "none",
  2287. options: [
  2288. "none",
  2289. "all",
  2290. "atmosphere",
  2291. "orbits",
  2292. "weather",
  2293. "water",
  2294. "geology",
  2295. "thicknesses",
  2296. "airspaces",
  2297. "races",
  2298. "olympic-records",
  2299. "d&d-sizes"
  2300. ],
  2301. get value() {
  2302. return config.drawAltitudes;
  2303. },
  2304. set value(param) {
  2305. config.drawAltitudes = param;
  2306. drawScales(false);
  2307. }
  2308. },
  2309. "lock-y-axis": {
  2310. name: "Lock Y-Axis",
  2311. desc: "Keep the camera at ground-level",
  2312. type: "toggle",
  2313. default: true,
  2314. get value() {
  2315. return config.lockYAxis;
  2316. },
  2317. set value(param) {
  2318. config.lockYAxis = param;
  2319. updateScrollButtons();
  2320. if (param) {
  2321. updateSizes();
  2322. }
  2323. }
  2324. },
  2325. "ground-snap": {
  2326. name: "Snap to Ground",
  2327. desc: "Snap things to the ground",
  2328. type: "toggle",
  2329. default: true,
  2330. get value() {
  2331. return config.groundSnap;
  2332. },
  2333. set value(param) {
  2334. config.groundSnap = param;
  2335. }
  2336. },
  2337. "axis-spacing": {
  2338. name: "Axis Spacing",
  2339. desc: "How frequent the axis lines are",
  2340. type: "select",
  2341. default: "standard",
  2342. options: [
  2343. "dense",
  2344. "standard",
  2345. "sparse"
  2346. ],
  2347. get value() {
  2348. return config.axisSpacing;
  2349. },
  2350. set value(param) {
  2351. config.axisSpacing = param;
  2352. const factor = {
  2353. "dense": 0.5,
  2354. "standard": 1,
  2355. "sparse": 2
  2356. }[param];
  2357. config.minLineSize = factor * 100;
  2358. config.maxLineSize = factor * 150;
  2359. updateSizes();
  2360. }
  2361. },
  2362. "ground-type": {
  2363. name: "Ground",
  2364. desc: "What kind of ground to show, if any",
  2365. type: "select",
  2366. default: "black",
  2367. disabled: "none",
  2368. options: [
  2369. "none",
  2370. "black",
  2371. "dark",
  2372. "medium",
  2373. "light",
  2374. ],
  2375. get value() {
  2376. return config.groundKind;
  2377. },
  2378. set value(param) {
  2379. config.groundKind = param;
  2380. document.querySelector("#ground").style.setProperty("--ground-color", backgroundColors[param])
  2381. }
  2382. },
  2383. "ground-pos": {
  2384. name: "Ground Position",
  2385. desc: "How high the ground is if the y-axis is locked",
  2386. type: "select",
  2387. default: "bottom",
  2388. options: groundPosChoices,
  2389. get value() {
  2390. return config.groundPos;
  2391. },
  2392. set value(param) {
  2393. config.groundPos = param;
  2394. updateScrollButtons();
  2395. updateSizes();
  2396. }
  2397. },
  2398. "background-brightness": {
  2399. name: "Background Color",
  2400. desc: "How bright the background is",
  2401. type: "select",
  2402. default: "medium",
  2403. options: [
  2404. "black",
  2405. "dark",
  2406. "medium",
  2407. "light",
  2408. ],
  2409. get value() {
  2410. return config.background;
  2411. },
  2412. set value(param) {
  2413. config.background = param;
  2414. drawScales();
  2415. }
  2416. },
  2417. "auto-scale": {
  2418. name: "Auto-Size World",
  2419. desc: "Constantly zoom to fit the largest entity",
  2420. type: "toggle",
  2421. default: false,
  2422. get value() {
  2423. return config.autoFit;
  2424. },
  2425. set value(param) {
  2426. config.autoFit = param;
  2427. checkFitWorld();
  2428. }
  2429. },
  2430. "auto-units": {
  2431. name: "Auto-Select Units",
  2432. desc: "Automatically switch units when zooming in and out",
  2433. type: "toggle",
  2434. default: false,
  2435. get value() {
  2436. return config.autoUnits;
  2437. },
  2438. set value(param) {
  2439. config.autoUnits = param;
  2440. }
  2441. },
  2442. "zoom-when-adding": {
  2443. name: "Zoom On Add",
  2444. desc: "Zoom to fit when you add a new entity",
  2445. type: "toggle",
  2446. default: true,
  2447. get value() {
  2448. return config.autoFitAdd;
  2449. },
  2450. set value(param) {
  2451. config.autoFitAdd = param;
  2452. }
  2453. },
  2454. "zoom-when-sizing": {
  2455. name: "Zoom On Size",
  2456. desc: "Zoom to fit when you select an entity's size",
  2457. type: "toggle",
  2458. default: false,
  2459. get value() {
  2460. return config.autoFitSize;
  2461. },
  2462. set value(param) {
  2463. config.autoFitSize = param;
  2464. }
  2465. },
  2466. "show-ratios": {
  2467. name: "Show Ratios",
  2468. desc: "Show the proportions between the current selection and the most recent selection.",
  2469. type: "toggle",
  2470. default: false,
  2471. get value() {
  2472. return config.showRatios;
  2473. },
  2474. set value(param) {
  2475. config.showRatios = param;
  2476. updateInfo();
  2477. }
  2478. },
  2479. "show-horizon": {
  2480. name: "Show Horizon",
  2481. desc: "Show how far the horizon would be for the selected character",
  2482. type: "toggle",
  2483. default: false,
  2484. get value() {
  2485. return config.showHorizon;
  2486. },
  2487. set value(param) {
  2488. config.showHorizon = param;
  2489. updateInfo();
  2490. }
  2491. },
  2492. "attach-rulers": {
  2493. name: "Attach Rulers",
  2494. desc: "Rulers will attach to the currently-selected entity, moving around with it.",
  2495. type: "toggle",
  2496. default: true,
  2497. get value() {
  2498. return config.rulersStick;
  2499. },
  2500. set value(param) {
  2501. config.rulersStick = param;
  2502. }
  2503. },
  2504. "units": {
  2505. name: "Default Units",
  2506. desc: "Which kind of unit to use by default",
  2507. type: "select",
  2508. default: "metric",
  2509. options: [
  2510. "metric",
  2511. "customary",
  2512. "relative",
  2513. "quirky",
  2514. "human"
  2515. ],
  2516. get value() {
  2517. return config.units;
  2518. },
  2519. set value(param) {
  2520. config.units = param;
  2521. updateSizes();
  2522. }
  2523. },
  2524. "names": {
  2525. name: "Show Names",
  2526. desc: "Display names over entities",
  2527. type: "toggle",
  2528. default: true,
  2529. get value() {
  2530. return checkBodyClass("toggle-entity-name");
  2531. },
  2532. set value(param) {
  2533. toggleBodyClass("toggle-entity-name", param);
  2534. }
  2535. },
  2536. "bottom-names": {
  2537. name: "Bottom Names",
  2538. desc: "Display names at the bottom",
  2539. type: "toggle",
  2540. default: false,
  2541. get value() {
  2542. return checkBodyClass("toggle-bottom-name");
  2543. },
  2544. set value(param) {
  2545. toggleBodyClass("toggle-bottom-name", param);
  2546. }
  2547. },
  2548. "top-names": {
  2549. name: "Show Arrows",
  2550. desc: "Point to entities that are much larger than the current view",
  2551. type: "toggle",
  2552. default: false,
  2553. get value() {
  2554. return checkBodyClass("toggle-top-name");
  2555. },
  2556. set value(param) {
  2557. toggleBodyClass("toggle-top-name", param);
  2558. }
  2559. },
  2560. "height-bars": {
  2561. name: "Height Bars",
  2562. desc: "Draw dashed lines to the top of each entity",
  2563. type: "toggle",
  2564. default: false,
  2565. get value() {
  2566. return checkBodyClass("toggle-height-bars");
  2567. },
  2568. set value(param) {
  2569. toggleBodyClass("toggle-height-bars", param);
  2570. }
  2571. },
  2572. "flag-nsfw": {
  2573. name: "Flag NSFW",
  2574. desc: "Highlight NSFW things in red",
  2575. type: "toggle",
  2576. default: false,
  2577. get value() {
  2578. return checkBodyClass("flag-nsfw");
  2579. },
  2580. set value(param) {
  2581. toggleBodyClass("flag-nsfw", param);
  2582. }
  2583. },
  2584. "glowing-entities": {
  2585. name: "Glowing Edges",
  2586. desc: "Makes all entities glow",
  2587. type: "toggle",
  2588. default: false,
  2589. get value() {
  2590. return checkBodyClass("toggle-entity-glow");
  2591. },
  2592. set value(param) {
  2593. toggleBodyClass("toggle-entity-glow", param);
  2594. }
  2595. },
  2596. "select-style": {
  2597. name: "Selection Style",
  2598. desc: "How to highlight selected entities (outlines are laggier",
  2599. type: "select",
  2600. default: "color",
  2601. options: [
  2602. "color",
  2603. "outline"
  2604. ],
  2605. get value() {
  2606. if (checkBodyClass("highlight-color")) {
  2607. return "color"
  2608. }
  2609. else {
  2610. return "outline"
  2611. }
  2612. },
  2613. set value(param) {
  2614. toggleBodyClass("highlight-color", param === "color")
  2615. toggleBodyClass("highlight-outline", param === "outline")
  2616. }
  2617. },
  2618. "smoothing": {
  2619. name: "Smoothing",
  2620. desc: "Smooth out movements and size changes. Disable for better performance.",
  2621. type: "toggle",
  2622. default: true,
  2623. get value() {
  2624. return checkBodyClass("smoothing");
  2625. },
  2626. set value(param) {
  2627. toggleBodyClass("smoothing", param);
  2628. }
  2629. },
  2630. "auto-mass": {
  2631. name: "Estimate Mass",
  2632. desc: "Guess the mass of things that don't have one specified using the selected body type",
  2633. type: "select",
  2634. default: "off",
  2635. disabled: "off",
  2636. options: [
  2637. "off",
  2638. "human",
  2639. "quadruped at shoulder",
  2640. ],
  2641. get value() {
  2642. return config.autoMass
  2643. },
  2644. set value(param) {
  2645. config.autoMass = param
  2646. }
  2647. },
  2648. "auto-food-intake": {
  2649. name: "Estimate Food Intake",
  2650. desc: "Guess how much food creatures need, based on their mass -- 2000kcal per 150lbs",
  2651. type: "toggle",
  2652. default: false,
  2653. get value() {
  2654. return config.autoFoodIntake
  2655. },
  2656. set value(param) {
  2657. config.autoFoodIntake = param
  2658. }
  2659. },
  2660. "auto-caloric-value": {
  2661. name: "Estimate Caloric Value",
  2662. desc: "Guess how much food a creature is worth -- 860kcal per pound",
  2663. type: "toggle",
  2664. default: false,
  2665. get value() {
  2666. return config.autoCaloricValue
  2667. },
  2668. set value(param) {
  2669. config.autoCaloricValue = param
  2670. }
  2671. },
  2672. "auto-prey-capacity": {
  2673. name: "Estimate Prey Capacity",
  2674. desc: "Guess how much prey creatures can hold, based on their mass",
  2675. type: "select",
  2676. default: "off",
  2677. disabled: "off",
  2678. options: [
  2679. "off",
  2680. "realistic",
  2681. "same-size"
  2682. ],
  2683. get value() {
  2684. return config.autoPreyCapacity;
  2685. },
  2686. set value(param) {
  2687. config.autoPreyCapacity = param;
  2688. }
  2689. },
  2690. }
  2691. function prepareSettings(userSettings) {
  2692. const menubar = document.querySelector("#settings-menu");
  2693. Object.entries(settingsData).forEach(([id, entry]) => {
  2694. const holder = document.createElement("label");
  2695. holder.classList.add("settings-holder");
  2696. const input = document.createElement("input");
  2697. input.id = "setting-" + id;
  2698. const vertical = document.createElement("div");
  2699. vertical.classList.add("settings-vertical");
  2700. const name = document.createElement("label");
  2701. name.innerText = entry.name;
  2702. name.classList.add("settings-name");
  2703. name.setAttribute("for", input.id);
  2704. const desc = document.createElement("label");
  2705. desc.innerText = entry.desc;
  2706. desc.classList.add("settings-desc");
  2707. desc.setAttribute("for", input.id);
  2708. if (entry.type == "toggle") {
  2709. input.type = "checkbox";
  2710. input.checked = userSettings[id] === undefined ? entry.default : userSettings[id];
  2711. holder.setAttribute("for", input.id);
  2712. vertical.appendChild(name);
  2713. vertical.appendChild(desc);
  2714. holder.appendChild(vertical);
  2715. holder.appendChild(input);
  2716. menubar.appendChild(holder);
  2717. const update = () => {
  2718. if (input.checked) {
  2719. holder.classList.add("enabled");
  2720. holder.classList.remove("disabled");
  2721. } else {
  2722. holder.classList.remove("enabled");
  2723. holder.classList.add("disabled");
  2724. }
  2725. entry.value = input.checked;
  2726. }
  2727. setTimeout(update);
  2728. input.addEventListener("change", update);
  2729. } else if (entry.type == "select") {
  2730. // we don't use the input element we made!
  2731. const select = document.createElement("select");
  2732. select.id = "setting-" + id;
  2733. entry.options.forEach(choice => {
  2734. const option = document.createElement("option");
  2735. option.innerText = choice;
  2736. select.appendChild(option);
  2737. })
  2738. select.value = userSettings[id] === undefined ? entry.default : userSettings[id];
  2739. vertical.appendChild(name);
  2740. vertical.appendChild(desc);
  2741. holder.appendChild(vertical);
  2742. holder.appendChild(select);
  2743. menubar.appendChild(holder);
  2744. const update = () => {
  2745. entry.value = select.value;
  2746. if (entry.disabled !== undefined && entry.value !== entry.disabled) {
  2747. holder.classList.add("enabled");
  2748. holder.classList.remove("disabled");
  2749. } else {
  2750. holder.classList.remove("enabled");
  2751. holder.classList.add("disabled");
  2752. }
  2753. }
  2754. update();
  2755. select.addEventListener("change", update);
  2756. }
  2757. })
  2758. }
  2759. function prepareMenu() {
  2760. prepareSidebar();
  2761. updateSaveInfo();
  2762. if (checkHelpDate()) {
  2763. document.querySelector("#open-help").classList.add("highlighted");
  2764. }
  2765. }
  2766. function updateSaveInfo() {
  2767. const saves = getSaves();
  2768. const load = document.querySelector("#menu-load ~ select");
  2769. load.innerHTML = "";
  2770. saves.forEach(save => {
  2771. const option = document.createElement("option");
  2772. option.innerText = save;
  2773. option.value = save;
  2774. load.appendChild(option);
  2775. });
  2776. const del = document.querySelector("#menu-delete ~ select");
  2777. del.innerHTML = "";
  2778. saves.forEach(save => {
  2779. const option = document.createElement("option");
  2780. option.innerText = save;
  2781. option.value = save;
  2782. del.appendChild(option);
  2783. });
  2784. }
  2785. function getSaves() {
  2786. try {
  2787. const results = [];
  2788. Object.keys(localStorage).forEach(key => {
  2789. if (key.startsWith("macrovision-save-")) {
  2790. results.push(key.replace("macrovision-save-", ""));
  2791. }
  2792. })
  2793. return results;
  2794. } catch (err) {
  2795. alert("Something went wrong while loading (maybe you didn't have anything saved. Check the F12 console for the error.")
  2796. console.error(err);
  2797. return false;
  2798. }
  2799. }
  2800. function getUserSettings() {
  2801. try {
  2802. const settings = JSON.parse(localStorage.getItem("settings"));
  2803. return settings === null ? {} : settings;
  2804. } catch {
  2805. return {};
  2806. }
  2807. }
  2808. function exportUserSettings() {
  2809. const settings = {};
  2810. Object.entries(settingsData).forEach(([id, entry]) => {
  2811. settings[id] = entry.value;
  2812. });
  2813. return settings;
  2814. }
  2815. function setUserSettings(settings) {
  2816. try {
  2817. localStorage.setItem("settings", JSON.stringify(settings));
  2818. } catch {
  2819. // :(
  2820. }
  2821. }
  2822. const lastHelpChange = 1601955834693;
  2823. function checkHelpDate() {
  2824. // disabling this for now
  2825. return false;
  2826. try {
  2827. const old = localStorage.getItem("help-viewed");
  2828. if (old === null || old < lastHelpChange) {
  2829. return true;
  2830. }
  2831. return false;
  2832. } catch {
  2833. console.warn("Could not set the help-viewed date");
  2834. return false;
  2835. }
  2836. }
  2837. function setHelpDate() {
  2838. try {
  2839. localStorage.setItem("help-viewed", Date.now());
  2840. } catch {
  2841. console.warn("Could not set the help-viewed date");
  2842. }
  2843. }
  2844. function doYScroll() {
  2845. const worldHeight = config.height.toNumber("meters");
  2846. config.y += scrollDirection * worldHeight / 180;
  2847. updateSizes();
  2848. scrollDirection *= 1.05;
  2849. }
  2850. function doXScroll() {
  2851. const worldWidth = config.height.toNumber("meters") / canvasHeight * canvasWidth;
  2852. config.x += scrollDirection * worldWidth / 180 ;
  2853. updateSizes();
  2854. scrollDirection *= 1.05;
  2855. }
  2856. function doZoom() {
  2857. const oldHeight = config.height;
  2858. setWorldHeight(oldHeight, math.multiply(oldHeight, 1 + zoomDirection / 10));
  2859. zoomDirection *= 1.05;
  2860. }
  2861. function doSize() {
  2862. if (selected) {
  2863. const entity = entities[selected.dataset.key];
  2864. const oldHeight = entity.views[entity.view].height;
  2865. entity.views[entity.view].height = math.multiply(oldHeight, sizeDirection < 0 ? -1/sizeDirection : sizeDirection);
  2866. entity.dirty = true;
  2867. updateEntityOptions(entity, entity.view);
  2868. updateViewOptions(entity, entity.view);
  2869. updateSizes(true);
  2870. sizeDirection *= 1.01;
  2871. const ownHeight = entity.views[entity.view].height.toNumber("meters");
  2872. let extra = entity.views[entity.view].image.extra;
  2873. extra = extra === undefined ? 1 : extra;
  2874. const worldHeight = config.height.toNumber("meters");
  2875. if (ownHeight * extra > worldHeight) {
  2876. setWorldHeight(config.height, math.multiply(entity.views[entity.view].height, extra));
  2877. } else if (ownHeight * extra * 10 < worldHeight) {
  2878. setWorldHeight(config.height, math.multiply(entity.views[entity.view].height, extra * 10));
  2879. }
  2880. }
  2881. }
  2882. function selectNewUnit() {
  2883. const unitSelector = document.querySelector("#options-height-unit");
  2884. checkFitWorld();
  2885. const scaleInput = document.querySelector("#options-height-value");
  2886. const newVal = math.unit(scaleInput.value, unitSelector.dataset.oldUnit).toNumber(unitSelector.value);
  2887. setNumericInput(scaleInput, newVal);
  2888. updateWorldHeight();
  2889. unitSelector.dataset.oldUnit = unitSelector.value;
  2890. }
  2891. // given a world position, return the position relative to the entity at normal scale
  2892. function entityRelativePosition(pos, entityElement) {
  2893. const entity = entities[entityElement.dataset.key]
  2894. const x = parseFloat(entityElement.dataset.x)
  2895. const y = parseFloat(entityElement.dataset.y)
  2896. pos.x -= x
  2897. pos.y -= y
  2898. pos.x /= entity.scale
  2899. pos.y /= entity.scale
  2900. return pos
  2901. }
  2902. document.addEventListener("DOMContentLoaded", () => {
  2903. prepareMenu();
  2904. prepareEntities();
  2905. document.querySelector("#open-help").addEventListener("click", e => {
  2906. setHelpDate();
  2907. document.querySelector("#open-help").classList.remove("highlighted");
  2908. window.open("https://www.notion.so/Macrovision-5c7f9377424743358ddf6db5671f439e", "_blank");
  2909. });
  2910. document.querySelector("#copy-screenshot").addEventListener("click", e => {
  2911. copyScreenshot();
  2912. });
  2913. document.querySelector("#save-screenshot").addEventListener("click", e => {
  2914. saveScreenshot();
  2915. });
  2916. document.querySelector("#open-screenshot").addEventListener("click", e => {
  2917. openScreenshot();
  2918. });
  2919. document.querySelector("#toggle-menu").addEventListener("click", e => {
  2920. const popoutMenu = document.querySelector("#sidebar-menu");
  2921. if (popoutMenu.classList.contains("visible")) {
  2922. popoutMenu.classList.remove("visible");
  2923. } else {
  2924. document.querySelectorAll(".popout-menu").forEach(menu => menu.classList.remove("visible"));
  2925. const rect = e.target.getBoundingClientRect();
  2926. popoutMenu.classList.add("visible");
  2927. popoutMenu.style.left = rect.x + rect.width + 10 + "px";
  2928. popoutMenu.style.top = rect.y + rect.height + 10 + "px";
  2929. let menuWidth = popoutMenu.getBoundingClientRect().width;
  2930. let screenWidth = window.innerWidth;
  2931. if (menuWidth * 1.5 > screenWidth) {
  2932. popoutMenu.style.left = 25 + "px";
  2933. }
  2934. }
  2935. e.stopPropagation();
  2936. });
  2937. document.querySelector("#sidebar-menu").addEventListener("click", e => {
  2938. e.stopPropagation();
  2939. });
  2940. document.addEventListener("click", e => {
  2941. document.querySelector("#sidebar-menu").classList.remove("visible");
  2942. });
  2943. document.querySelector("#toggle-settings").addEventListener("click", e => {
  2944. const popoutMenu = document.querySelector("#settings-menu");
  2945. if (popoutMenu.classList.contains("visible")) {
  2946. popoutMenu.classList.remove("visible");
  2947. } else {
  2948. document.querySelectorAll(".popout-menu").forEach(menu => menu.classList.remove("visible"));
  2949. const rect = e.target.getBoundingClientRect();
  2950. popoutMenu.classList.add("visible");
  2951. popoutMenu.style.left = rect.x + rect.width + 10 + "px";
  2952. popoutMenu.style.top = rect.y + rect.height + 10 + "px";
  2953. let menuWidth = popoutMenu.getBoundingClientRect().width;
  2954. let screenWidth = window.innerWidth;
  2955. if (menuWidth * 1.5 > screenWidth) {
  2956. popoutMenu.style.left = 25 + "px";
  2957. }
  2958. }
  2959. e.stopPropagation();
  2960. });
  2961. document.querySelector("#settings-menu").addEventListener("click", e => {
  2962. e.stopPropagation();
  2963. });
  2964. document.addEventListener("click", e => {
  2965. document.querySelector("#settings-menu").classList.remove("visible");
  2966. });
  2967. window.addEventListener("unload", () => {
  2968. saveScene("autosave");
  2969. setUserSettings(exportUserSettings());
  2970. });
  2971. document.querySelector("#options-selected-entity").addEventListener("input", e => {
  2972. if (e.target.value == "None") {
  2973. deselect()
  2974. } else {
  2975. select(document.querySelector("#entity-" + e.target.value));
  2976. }
  2977. });
  2978. document.querySelector("#menu-toggle-sidebar").addEventListener("click", e => {
  2979. const sidebar = document.querySelector("#options");
  2980. if (sidebar.classList.contains("hidden")) {
  2981. sidebar.classList.remove("hidden");
  2982. e.target.classList.remove("rotate-forward");
  2983. e.target.classList.add("rotate-backward");
  2984. } else {
  2985. sidebar.classList.add("hidden");
  2986. e.target.classList.add("rotate-forward");
  2987. e.target.classList.remove("rotate-backward");
  2988. }
  2989. handleResize();
  2990. });
  2991. document.querySelector("#menu-fullscreen").addEventListener("click", toggleFullScreen);
  2992. document.querySelector("#options-order-forward").addEventListener("click", e => {
  2993. if (selected) {
  2994. entities[selected.dataset.key].priority += 1;
  2995. }
  2996. document.querySelector("#options-order-display").innerText = entities[selected.dataset.key].priority;
  2997. updateSizes();
  2998. });
  2999. document.querySelector("#options-order-back").addEventListener("click", e => {
  3000. if (selected) {
  3001. entities[selected.dataset.key].priority -= 1;
  3002. }
  3003. document.querySelector("#options-order-display").innerText = entities[selected.dataset.key].priority;
  3004. updateSizes();
  3005. });
  3006. document.querySelector("#options-brightness-up").addEventListener("click", e => {
  3007. if (selected) {
  3008. entities[selected.dataset.key].brightness += 1;
  3009. }
  3010. document.querySelector("#options-brightness-display").innerText = entities[selected.dataset.key].brightness;
  3011. updateSizes();
  3012. });
  3013. document.querySelector("#options-brightness-down").addEventListener("click", e => {
  3014. if (selected) {
  3015. entities[selected.dataset.key].brightness -= 1;
  3016. }
  3017. document.querySelector("#options-brightness-display").innerText = entities[selected.dataset.key].brightness;
  3018. updateSizes();
  3019. });
  3020. document.querySelector("#options-rotate-left").addEventListener("click", e => {
  3021. if (selected) {
  3022. entities[selected.dataset.key].rotation -= Math.PI/4;
  3023. }
  3024. selected.querySelector("img").style.setProperty("--rotation", (entities[selected.dataset.key].rotation * 180 / Math.PI) + "deg")
  3025. updateSizes();
  3026. });
  3027. document.querySelector("#options-rotate-right").addEventListener("click", e => {
  3028. if (selected) {
  3029. entities[selected.dataset.key].rotation += Math.PI/4;
  3030. }
  3031. selected.querySelector("img").style.setProperty("--rotation", (entities[selected.dataset.key].rotation * 180 / Math.PI) + "deg")
  3032. updateSizes();
  3033. });
  3034. document.querySelector("#options-flip").addEventListener("click", e => {
  3035. if (selected) {
  3036. selected.querySelector(".entity-image").classList.toggle("flipped");
  3037. }
  3038. document.querySelector("#options-brightness-display").innerText = entities[selected.dataset.key].brightness;
  3039. updateSizes();
  3040. });
  3041. const sceneChoices = document.querySelector("#menu-preset ~ select");
  3042. Object.entries(scenes).forEach(([id, scene]) => {
  3043. const option = document.createElement("option");
  3044. option.innerText = id;
  3045. option.value = id;
  3046. sceneChoices.appendChild(option);
  3047. });
  3048. document.querySelector("#menu-preset").addEventListener("click", e => {
  3049. const chosen = sceneChoices.value;
  3050. removeAllEntities();
  3051. scenes[chosen]();
  3052. });
  3053. entityX = document.querySelector("#entities").getBoundingClientRect().x;
  3054. canvasWidth = document.querySelector("#display").clientWidth - 100;
  3055. canvasHeight = document.querySelector("#display").clientHeight - 50;
  3056. document.querySelector("#options-height-value").addEventListener("change", e => {
  3057. updateWorldHeight();
  3058. })
  3059. document.querySelector("#options-height-value").addEventListener("keydown", e => {
  3060. e.stopPropagation();
  3061. })
  3062. const unitSelector = document.querySelector("#options-height-unit");
  3063. Object.entries(unitChoices.length).forEach(([group, entries]) => {
  3064. const optGroup = document.createElement("optgroup");
  3065. optGroup.label = group;
  3066. unitSelector.appendChild(optGroup);
  3067. entries.forEach(entry => {
  3068. const option = document.createElement("option");
  3069. option.innerText = entry;
  3070. // we haven't loaded user settings yet, so we can't choose the unit just yet
  3071. unitSelector.appendChild(option);
  3072. })
  3073. });
  3074. unitSelector.addEventListener("input", selectNewUnit);
  3075. param = window.location.hash;
  3076. // we now use the fragment for links, but we should still support old stuff:
  3077. if (param.length > 0) {
  3078. param = param.substring(1);
  3079. } else {
  3080. param = new URL(window.location.href).searchParams.get("scene");
  3081. }
  3082. document.querySelector("#world").addEventListener("mousedown", e => {
  3083. // only middle mouse clicks
  3084. if (e.which == 2) {
  3085. panning = true;
  3086. panOffsetX = e.clientX;
  3087. panOffsetY = e.clientY;
  3088. Object.keys(entities).forEach(key => {
  3089. document.querySelector("#entity-" + key).classList.add("no-transition");
  3090. });
  3091. }
  3092. });
  3093. document.addEventListener("mouseup", e => {
  3094. if (e.which == 2) {
  3095. panning = false;
  3096. Object.keys(entities).forEach(key => {
  3097. document.querySelector("#entity-" + key).classList.remove("no-transition");
  3098. });
  3099. }
  3100. });
  3101. document.querySelector("#world").addEventListener("touchstart", e => {
  3102. if (!rulerMode) {
  3103. panning = true;
  3104. panOffsetX = e.touches[0].clientX;
  3105. panOffsetY = e.touches[0].clientY;
  3106. e.preventDefault();
  3107. Object.keys(entities).forEach(key => {
  3108. document.querySelector("#entity-" + key).classList.add("no-transition");
  3109. });
  3110. }
  3111. });
  3112. document.querySelector("#world").addEventListener("touchend", e => {
  3113. panning = false;
  3114. Object.keys(entities).forEach(key => {
  3115. document.querySelector("#entity-" + key).classList.remove("no-transition");
  3116. });
  3117. });
  3118. document.querySelector("#world").addEventListener("mousedown", e => {
  3119. // only left mouse clicks
  3120. if (e.which == 1 && rulerMode) {
  3121. let entX = document.querySelector("#entities").getBoundingClientRect().x;
  3122. let entY = document.querySelector("#entities").getBoundingClientRect().y;
  3123. let pos = pix2pos({ x: e.clientX - entX, y: e.clientY - entY });
  3124. if (config.rulersStick && selected) {
  3125. pos = entityRelativePosition(pos, selected)
  3126. }
  3127. currentRuler = { x0: pos.x, y0: pos.y, x1: pos.y, y1: pos.y, entityKey: null };
  3128. if (config.rulersStick && selected) {
  3129. currentRuler.entityKey = selected.dataset.key
  3130. }
  3131. }
  3132. });
  3133. document.querySelector("#world").addEventListener("mouseup", e => {
  3134. // only left mouse clicks
  3135. if (e.which == 1 && currentRuler) {
  3136. rulers.push(currentRuler);
  3137. currentRuler = null;
  3138. rulerMode = false;
  3139. }
  3140. });
  3141. document.querySelector("#world").addEventListener("touchstart", e => {
  3142. if (rulerMode) {
  3143. let entX = document.querySelector("#entities").getBoundingClientRect().x;
  3144. let entY = document.querySelector("#entities").getBoundingClientRect().y;
  3145. let pos = pix2pos({ x: e.touches[0].clientX - entX, y: e.touches[0].clientY - entY });
  3146. if (config.rulersStick && selected) {
  3147. pos = entityRelativePosition(pos, selected)
  3148. }
  3149. currentRuler = { x0: pos.x, y0: pos.y, x1: pos.y, y1: pos.y, entityKey: null };
  3150. if (config.rulersStick && selected) {
  3151. currentRuler.entityKey = selected.dataset.key
  3152. }
  3153. }
  3154. });
  3155. document.querySelector("#world").addEventListener("touchend", e => {
  3156. if (currentRuler) {
  3157. rulers.push(currentRuler);
  3158. currentRuler = null;
  3159. rulerMode = false;
  3160. }
  3161. });
  3162. document.querySelector("body").appendChild(testCtx.canvas);
  3163. world.addEventListener("mousedown", e => deselect(e));
  3164. world.addEventListener("touchstart", e => deselect({
  3165. which: 1,
  3166. }));
  3167. document.querySelector("#entities").addEventListener("mousedown", deselect);
  3168. document.querySelector("#display").addEventListener("mousedown", deselect);
  3169. document.addEventListener("mouseup", e => clickUp(e));
  3170. document.addEventListener("touchend", e => {
  3171. const fakeEvent = {
  3172. target: e.target,
  3173. clientX: e.changedTouches[0].clientX,
  3174. clientY: e.changedTouches[0].clientY,
  3175. which: 1
  3176. };
  3177. clickUp(fakeEvent);
  3178. });
  3179. const formList = document.querySelector("#entity-form");
  3180. formList.addEventListener("input", e => {
  3181. const entity = entities[selected.dataset.key];
  3182. entity.form = e.target.value;
  3183. const oldView = entity.currentView
  3184. entity.view = entity.formViews[entity.form]
  3185. // to set the size properly, even if we use a non-default view
  3186. if (Object.keys(entity.forms).length > 0)
  3187. entity.views[entity.view].height = entity.formSizes[entity.form].height;
  3188. let found = Object.entries(entity.views).find(([key, view]) => {
  3189. return view.form === entity.form && view.name === oldView.name
  3190. })
  3191. const newView = found ? found[0] : entity.formViews[entity.form]
  3192. entity.view = newView;
  3193. preloadViews(entity);
  3194. configViewList(entity, entity.view);
  3195. const image = entity.views[entity.view].image;
  3196. selected.querySelector(".entity-image").src = image.source;
  3197. configViewOptions(entity, entity.view);
  3198. displayAttribution(image.source);
  3199. if (image.bottom !== undefined) {
  3200. selected.querySelector(".entity-image").style.setProperty("--offset", ((-1 + image.bottom) * 100) + "%")
  3201. } else {
  3202. selected.querySelector(".entity-image").style.setProperty("--offset", ((-1) * 100) + "%")
  3203. }
  3204. if (config.autoFitSize) {
  3205. let targets = {};
  3206. targets[selected.dataset.key] = entities[selected.dataset.key];
  3207. fitEntities(targets);
  3208. }
  3209. configSizeList(entity);
  3210. updateSizes();
  3211. updateEntityOptions(entities[selected.dataset.key], e.target.value);
  3212. updateViewOptions(entities[selected.dataset.key], entity.view);
  3213. });
  3214. const viewList = document.querySelector("#entity-view");
  3215. document.querySelector("#entity-view").addEventListener("input", e => {
  3216. const entity = entities[selected.dataset.key];
  3217. entity.view = e.target.value;
  3218. preloadViews(entity);
  3219. const image = entities[selected.dataset.key].views[e.target.value].image;
  3220. selected.querySelector(".entity-image").src = image.source;
  3221. configViewOptions(entity, entity.view);
  3222. displayAttribution(image.source);
  3223. if (image.bottom !== undefined) {
  3224. selected.querySelector(".entity-image").style.setProperty("--offset", ((-1 + image.bottom) * 100) + "%")
  3225. } else {
  3226. selected.querySelector(".entity-image").style.setProperty("--offset", ((-1) * 100) + "%")
  3227. }
  3228. updateSizes();
  3229. updateEntityOptions(entities[selected.dataset.key], e.target.value);
  3230. updateViewOptions(entities[selected.dataset.key], e.target.value);
  3231. });
  3232. document.querySelector("#entity-view").addEventListener("input", e => {
  3233. if (viewList.options[viewList.selectedIndex].classList.contains("nsfw")) {
  3234. viewList.classList.add("nsfw");
  3235. } else {
  3236. viewList.classList.remove("nsfw");
  3237. }
  3238. })
  3239. clearViewList();
  3240. document.querySelector("#menu-clear").addEventListener("click", e => {
  3241. removeAllEntities();
  3242. });
  3243. document.querySelector("#delete-entity").disabled = true;
  3244. document.querySelector("#delete-entity").addEventListener("click", e => {
  3245. if (selected) {
  3246. removeEntity(selected);
  3247. selected = null;
  3248. }
  3249. });
  3250. document.querySelector("#menu-order-height").addEventListener("click", e => {
  3251. const order = Object.keys(entities).sort((a, b) => {
  3252. const entA = entities[a];
  3253. const entB = entities[b];
  3254. const viewA = entA.view;
  3255. const viewB = entB.view;
  3256. const heightA = entA.views[viewA].height.to("meter").value;
  3257. const heightB = entB.views[viewB].height.to("meter").value;
  3258. return heightA - heightB;
  3259. });
  3260. arrangeEntities(order);
  3261. });
  3262. // TODO: write some generic logic for this lol
  3263. document.querySelector("#scroll-left").addEventListener("mousedown", e => {
  3264. scrollDirection = -1;
  3265. clearInterval(scrollHandle);
  3266. scrollHandle = setInterval(doXScroll, 1000 / 20);
  3267. e.stopPropagation();
  3268. });
  3269. document.querySelector("#scroll-right").addEventListener("mousedown", e => {
  3270. scrollDirection = 1;
  3271. clearInterval(scrollHandle);
  3272. scrollHandle = setInterval(doXScroll, 1000 / 20);
  3273. e.stopPropagation();
  3274. });
  3275. document.querySelector("#scroll-left").addEventListener("touchstart", e => {
  3276. scrollDirection = -1;
  3277. clearInterval(scrollHandle);
  3278. scrollHandle = setInterval(doXScroll, 1000 / 20);
  3279. e.stopPropagation();
  3280. });
  3281. document.querySelector("#scroll-right").addEventListener("touchstart", e => {
  3282. scrollDirection = 1;
  3283. clearInterval(scrollHandle);
  3284. scrollHandle = setInterval(doXScroll, 1000 / 20);
  3285. e.stopPropagation();
  3286. });
  3287. document.querySelector("#scroll-up").addEventListener("mousedown", e => {
  3288. if (config.lockYAxis) {
  3289. moveGround(true);
  3290. } else {
  3291. scrollDirection = 1;
  3292. clearInterval(scrollHandle);
  3293. scrollHandle = setInterval(doYScroll, 1000 / 20);
  3294. e.stopPropagation();
  3295. }
  3296. });
  3297. document.querySelector("#scroll-down").addEventListener("mousedown", e => {
  3298. if (config.lockYAxis) {
  3299. moveGround(false);
  3300. } else {
  3301. scrollDirection = -1;
  3302. clearInterval(scrollHandle);
  3303. scrollHandle = setInterval(doYScroll, 1000 / 20);
  3304. e.stopPropagation();
  3305. }
  3306. });
  3307. document.querySelector("#scroll-up").addEventListener("touchstart", e => {
  3308. if (config.lockYAxis) {
  3309. moveGround(true);
  3310. } else {
  3311. scrollDirection = 1;
  3312. clearInterval(scrollHandle);
  3313. scrollHandle = setInterval(doYScroll, 1000 / 20);
  3314. e.stopPropagation();
  3315. }
  3316. });
  3317. document.querySelector("#scroll-down").addEventListener("touchstart", e => {
  3318. if (config.lockYAxis) {
  3319. moveGround(false);
  3320. } else {
  3321. scrollDirection = -1;
  3322. clearInterval(scrollHandle);
  3323. scrollHandle = setInterval(doYScroll, 1000 / 20);
  3324. e.stopPropagation();
  3325. }
  3326. });
  3327. document.addEventListener("mouseup", e => {
  3328. clearInterval(scrollHandle);
  3329. scrollHandle = null;
  3330. });
  3331. document.addEventListener("touchend", e => {
  3332. clearInterval(scrollHandle);
  3333. scrollHandle = null;
  3334. });
  3335. document.querySelector("#zoom-in").addEventListener("mousedown", e => {
  3336. zoomDirection = -1;
  3337. clearInterval(zoomHandle);
  3338. zoomHandle = setInterval(doZoom, 1000 / 20);
  3339. e.stopPropagation();
  3340. });
  3341. document.querySelector("#zoom-out").addEventListener("mousedown", e => {
  3342. zoomDirection = 1;
  3343. clearInterval(zoomHandle);
  3344. zoomHandle = setInterval(doZoom, 1000 / 20);
  3345. e.stopPropagation();
  3346. });
  3347. document.querySelector("#zoom-in").addEventListener("touchstart", e => {
  3348. zoomDirection = -1;
  3349. clearInterval(zoomHandle);
  3350. zoomHandle = setInterval(doZoom, 1000 / 20);
  3351. e.stopPropagation();
  3352. });
  3353. document.querySelector("#zoom-out").addEventListener("touchstart", e => {
  3354. zoomDirection = 1;
  3355. clearInterval(zoomHandle);
  3356. zoomHandle = setInterval(doZoom, 1000 / 20);
  3357. e.stopPropagation();
  3358. });
  3359. document.addEventListener("mouseup", e => {
  3360. clearInterval(zoomHandle);
  3361. zoomHandle = null;
  3362. });
  3363. document.addEventListener("touchend", e => {
  3364. clearInterval(zoomHandle);
  3365. zoomHandle = null;
  3366. });
  3367. document.querySelector("#shrink").addEventListener("mousedown", e => {
  3368. sizeDirection = -1;
  3369. clearInterval(sizeHandle);
  3370. sizeHandle = setInterval(doSize, 1000 / 20);
  3371. e.stopPropagation();
  3372. });
  3373. document.querySelector("#grow").addEventListener("mousedown", e => {
  3374. sizeDirection = 1;
  3375. clearInterval(sizeHandle);
  3376. sizeHandle = setInterval(doSize, 1000 / 20);
  3377. e.stopPropagation();
  3378. });
  3379. document.querySelector("#shrink").addEventListener("touchstart", e => {
  3380. sizeDirection = -1;
  3381. clearInterval(sizeHandle);
  3382. sizeHandle = setInterval(doSize, 1000 / 20);
  3383. e.stopPropagation();
  3384. });
  3385. document.querySelector("#grow").addEventListener("touchstart", e => {
  3386. sizeDirection = 1;
  3387. clearInterval(sizeHandle);
  3388. sizeHandle = setInterval(doSize, 1000 / 20);
  3389. e.stopPropagation();
  3390. });
  3391. document.addEventListener("mouseup", e => {
  3392. clearInterval(sizeHandle);
  3393. sizeHandle = null;
  3394. });
  3395. document.addEventListener("touchend", e => {
  3396. clearInterval(sizeHandle);
  3397. sizeHandle = null;
  3398. });
  3399. document.querySelector("#ruler").addEventListener("click", e => {
  3400. rulerMode = !rulerMode;
  3401. if (rulerMode) {
  3402. toast("Ready to draw a ruler mark");
  3403. } else {
  3404. toast("Cancelled ruler mode");
  3405. }
  3406. });
  3407. document.querySelector("#ruler").addEventListener("mousedown", e => {
  3408. e.stopPropagation();
  3409. });
  3410. document.querySelector("#ruler").addEventListener("touchstart", e => {
  3411. e.stopPropagation();
  3412. });
  3413. document.querySelector("#fit").addEventListener("click", e => {
  3414. if (selected) {
  3415. let targets = {};
  3416. targets[selected.dataset.key] = entities[selected.dataset.key];
  3417. fitEntities(targets);
  3418. }
  3419. });
  3420. document.querySelector("#fit").addEventListener("mousedown", e => {
  3421. e.stopPropagation();
  3422. });
  3423. document.querySelector("#fit").addEventListener("touchstart", e => {
  3424. e.stopPropagation();
  3425. });
  3426. document.querySelector("#options-world-fit").addEventListener("click", () => fitWorld(true));
  3427. document.querySelector("#options-reset-pos-x").addEventListener("click", () => { config.x = 0; updateSizes(); });
  3428. document.querySelector("#options-reset-pos-y").addEventListener("click", () => { config.y = 0; updateSizes(); });
  3429. document.addEventListener("keydown", e => {
  3430. if (e.key == "Delete" || e.key == "Backspace") {
  3431. if (selected) {
  3432. removeEntity(selected);
  3433. selected = null;
  3434. }
  3435. }
  3436. })
  3437. document.addEventListener("keydown", e => {
  3438. if (e.key == "Shift") {
  3439. shiftHeld = true;
  3440. e.preventDefault();
  3441. } else if (e.key == "Alt") {
  3442. altHeld = true;
  3443. movingInBounds = false; // don't snap the object back in bounds when we let go
  3444. e.preventDefault();
  3445. }
  3446. });
  3447. document.addEventListener("keyup", e => {
  3448. if (e.key == "Shift") {
  3449. shiftHeld = false;
  3450. e.preventDefault();
  3451. } else if (e.key == "Alt") {
  3452. altHeld = false;
  3453. e.preventDefault();
  3454. }
  3455. });
  3456. window.addEventListener("resize", handleResize);
  3457. // TODO: further investigate why the tool initially starts out with wrong
  3458. // values under certain circumstances (seems to be narrow aspect ratios -
  3459. // maybe the menu bar is animating when it shouldn't)
  3460. setTimeout(handleResize, 250);
  3461. setTimeout(handleResize, 500);
  3462. setTimeout(handleResize, 750);
  3463. setTimeout(handleResize, 1000);
  3464. document.querySelector("#menu-permalink").addEventListener("click", e => {
  3465. linkScene();
  3466. });
  3467. document.querySelector("#menu-export").addEventListener("click", e => {
  3468. copyScene();
  3469. });
  3470. document.querySelector("#menu-import").addEventListener("click", e => {
  3471. pasteScene();
  3472. });
  3473. document.querySelector("#menu-save").addEventListener("click", e => {
  3474. const name = document.querySelector("#menu-save ~ input").value;
  3475. if (/\S/.test(name)) {
  3476. saveScene(name);
  3477. }
  3478. updateSaveInfo();
  3479. });
  3480. document.querySelector("#menu-load").addEventListener("click", e => {
  3481. const name = document.querySelector("#menu-load ~ select").value;
  3482. if (/\S/.test(name)) {
  3483. loadScene(name);
  3484. }
  3485. });
  3486. document.querySelector("#menu-delete").addEventListener("click", e => {
  3487. const name = document.querySelector("#menu-delete ~ select").value;
  3488. if (/\S/.test(name)) {
  3489. deleteScene(name);
  3490. }
  3491. });
  3492. document.querySelector("#menu-load-autosave").addEventListener("click", e => {
  3493. loadScene("autosave");
  3494. });
  3495. document.querySelector("#menu-add-image").addEventListener("click", e => {
  3496. document.querySelector("#file-upload-picker").click();
  3497. });
  3498. document.querySelector("#file-upload-picker").addEventListener("change", e => {
  3499. if (e.target.files.length > 0) {
  3500. for (let i=0; i<e.target.files.length; i++) {
  3501. customEntityFromFile(e.target.files[i]);
  3502. }
  3503. }
  3504. })
  3505. document.querySelector("#menu-clear-rulers").addEventListener("click", e => {
  3506. rulers = [];
  3507. drawRulers();
  3508. });
  3509. document.addEventListener("paste", e => {
  3510. let index = 0;
  3511. let item = null;
  3512. let found = false;
  3513. for (; index < e.clipboardData.items.length; index++) {
  3514. item = e.clipboardData.items[index];
  3515. if (item.type == "image/png") {
  3516. found = true;
  3517. break;
  3518. }
  3519. }
  3520. if (!found) {
  3521. return;
  3522. }
  3523. let url = null;
  3524. const file = item.getAsFile();
  3525. customEntityFromFile(file);
  3526. });
  3527. document.querySelector("#world").addEventListener("dragover", e => {
  3528. e.preventDefault();
  3529. })
  3530. document.querySelector("#world").addEventListener("drop", e => {
  3531. e.preventDefault();
  3532. if (e.dataTransfer.files.length > 0) {
  3533. let entX = document.querySelector("#entities").getBoundingClientRect().x;
  3534. let entY = document.querySelector("#entities").getBoundingClientRect().y;
  3535. let coords = pix2pos({x: e.clientX-entX, y: e.clientY-entY});
  3536. customEntityFromFile(e.dataTransfer.files[0], coords.x, coords.y);
  3537. }
  3538. })
  3539. clearEntityOptions();
  3540. clearViewOptions();
  3541. clearAttribution();
  3542. // we do this last because configuring settings can cause things
  3543. // to happen (e.g. auto-fit)
  3544. prepareSettings(getUserSettings());
  3545. // now that we have this loaded, we can set it
  3546. unitSelector.dataset.oldUnit = defaultUnits.length[config.units];
  3547. document.querySelector("#options-height-unit").value = defaultUnits.length[config.units];
  3548. // ...and then update the world height by setting off an input event
  3549. document.querySelector("#options-height-unit").dispatchEvent(new Event('input', {
  3550. }));
  3551. if (param === null) {
  3552. scenes["Empty"]();
  3553. }
  3554. else {
  3555. try {
  3556. const data = JSON.parse(b64DecodeUnicode(param));
  3557. if (data.entities === undefined) {
  3558. return;
  3559. }
  3560. if (data.world === undefined) {
  3561. return;
  3562. }
  3563. importScene(data);
  3564. } catch (err) {
  3565. console.error(err);
  3566. scenes["Empty"]();
  3567. // probably wasn't valid data
  3568. }
  3569. }
  3570. document.querySelector("#world").addEventListener("wheel", e => {
  3571. let magnitude = Math.abs(e.deltaY / 100);
  3572. if (shiftHeld) {
  3573. // macs do horizontal scrolling with shift held
  3574. let delta = e.deltaY
  3575. if (e.deltaY == 0) {
  3576. magnitude = Math.abs(e.deltaX / 100)
  3577. delta = e.deltaX
  3578. }
  3579. if (selected) {
  3580. let dir = delta > 0 ? 10 / 11 : 11 / 10;
  3581. dir -= 1;
  3582. dir *= magnitude;
  3583. dir += 1;
  3584. const entity = entities[selected.dataset.key];
  3585. entity.views[entity.view].height = math.multiply(entity.views[entity.view].height, dir);
  3586. entity.dirty = true;
  3587. updateEntityOptions(entity, entity.view);
  3588. updateViewOptions(entity, entity.view);
  3589. updateSizes(true);
  3590. } else {
  3591. const worldWidth = config.height.toNumber("meters") / canvasHeight * canvasWidth;
  3592. config.x += (e.deltaY > 0 ? 1 : -1) * worldWidth / 20 ;
  3593. updateSizes();
  3594. updateSizes();
  3595. }
  3596. } else {
  3597. if (config.autoFit) {
  3598. toastRateLimit("Zoom is locked! Check Settings to disable.", "zoom-lock", 1000);
  3599. } else {
  3600. let dir = e.deltaY < 0 ? 10 / 11 : 11 / 10;
  3601. dir -= 1;
  3602. dir *= magnitude;
  3603. dir += 1;
  3604. const change = config.height.toNumber("meters") - math.multiply(config.height, dir).toNumber("meters");
  3605. if (!config.lockYAxis) {
  3606. config.y += change / 2;
  3607. }
  3608. setWorldHeight(config.height, math.multiply(config.height, dir));
  3609. updateWorldOptions();
  3610. }
  3611. }
  3612. checkFitWorld();
  3613. })
  3614. document.addEventListener("mousemove", (e) => {
  3615. if (currentRuler) {
  3616. let entX = document.querySelector("#entities").getBoundingClientRect().x;
  3617. let entY = document.querySelector("#entities").getBoundingClientRect().y;
  3618. let position = pix2pos({ x: e.clientX - entX, y: e.clientY - entY });
  3619. if (config.rulersStick && selected) {
  3620. position = entityRelativePosition(position, selected)
  3621. }
  3622. currentRuler.x1 = position.x;
  3623. currentRuler.y1 = position.y;
  3624. }
  3625. drawRulers();
  3626. });
  3627. document.addEventListener("touchmove", (e) => {
  3628. if (currentRuler) {
  3629. let entX = document.querySelector("#entities").getBoundingClientRect().x;
  3630. let entY = document.querySelector("#entities").getBoundingClientRect().y;
  3631. let position = pix2pos({ x: e.touches[0].clientX - entX, y: e.touches[0].clientY - entY });
  3632. if (config.rulersStick && selected) {
  3633. position = entityRelativePosition(position, selected)
  3634. }
  3635. currentRuler.x1 = position.x;
  3636. currentRuler.y1 = position.y;
  3637. }
  3638. drawRulers();
  3639. });
  3640. document.addEventListener("mousemove", (e) => {
  3641. if (clicked) {
  3642. let position = pix2pos({ x: e.clientX - dragOffsetX, y: e.clientY - dragOffsetY });
  3643. if (movingInBounds) {
  3644. position = snapPos(position);
  3645. } else {
  3646. let x = e.clientX - dragOffsetX;
  3647. let y = e.clientY - dragOffsetY;
  3648. if (x >= 0 && x <= canvasWidth && y >= 0 && y <= canvasHeight) {
  3649. movingInBounds = true;
  3650. }
  3651. }
  3652. clicked.dataset.x = position.x;
  3653. clicked.dataset.y = position.y;
  3654. updateEntityElement(entities[clicked.dataset.key], clicked);
  3655. if (hoveringInDeleteArea(e)) {
  3656. document.querySelector("#menubar").classList.add("hover-delete");
  3657. } else {
  3658. document.querySelector("#menubar").classList.remove("hover-delete");
  3659. }
  3660. }
  3661. if (panning && panReady) {
  3662. const worldWidth = config.height.toNumber("meters") / canvasHeight * canvasWidth;
  3663. const worldHeight = config.height.toNumber("meters");
  3664. config.x -= (e.clientX - panOffsetX) / canvasWidth * worldWidth;
  3665. config.y += (e.clientY - panOffsetY) / canvasHeight * worldHeight;
  3666. panOffsetX = e.clientX;
  3667. panOffsetY = e.clientY;
  3668. updateSizes();
  3669. panReady = false;
  3670. setTimeout(() => panReady=true, 1000/120);
  3671. }
  3672. });
  3673. document.addEventListener("touchmove", (e) => {
  3674. if (clicked) {
  3675. e.preventDefault();
  3676. let x = e.touches[0].clientX;
  3677. let y = e.touches[0].clientY;
  3678. const position = snapPos(pix2pos({ x: x - dragOffsetX, y: y - dragOffsetY }));
  3679. clicked.dataset.x = position.x;
  3680. clicked.dataset.y = position.y;
  3681. updateEntityElement(entities[clicked.dataset.key], clicked);
  3682. // what a hack
  3683. // I should centralize this 'fake event' creation...
  3684. if (hoveringInDeleteArea({ clientY: y })) {
  3685. document.querySelector("#menubar").classList.add("hover-delete");
  3686. } else {
  3687. document.querySelector("#menubar").classList.remove("hover-delete");
  3688. }
  3689. }
  3690. if (panning && panReady) {
  3691. const worldWidth = config.height.toNumber("meters") / canvasHeight * canvasWidth;
  3692. const worldHeight = config.height.toNumber("meters");
  3693. config.x -= (e.touches[0].clientX - panOffsetX) / canvasWidth * worldWidth;
  3694. config.y += (e.touches[0].clientY - panOffsetY) / canvasHeight * worldHeight;
  3695. panOffsetX = e.touches[0].clientX;
  3696. panOffsetY = e.touches[0].clientY;
  3697. updateSizes();
  3698. panReady = false;
  3699. setTimeout(() => panReady=true, 1000/60);
  3700. }
  3701. }, { passive: false });
  3702. updateWorldHeight();
  3703. document.querySelector("#search-box").addEventListener("change", e => doSearch(e.target.value));
  3704. // Webkit doesn't draw resized SVGs correctly. It will always draw them at their intrinsic size, I think
  3705. // This checks for that.
  3706. webkitBugTest.onload = () => {
  3707. testCtx.canvas.width = 500;
  3708. testCtx.canvas.height = 500;
  3709. testCtx.clearRect(0, 0, 500, 500);
  3710. testCtx.drawImage(webkitBugTest, 0, 0, 500, 500);
  3711. webkitCanvasBug = testCtx.getImageData(250, 250, 1, 1).data[3] == 0
  3712. if (webkitCanvasBug) {
  3713. toast("Heads up: Safari can't select through gaps or take screenshots (check the console for info!)")
  3714. console.log("Webkit messes up the process of drawing an SVG image to a canvas. This is important for both selecting things (it lets you click through a gap and hit something else) and for taking screenshots (since it needs to render them to a canvas). Sorry :(")
  3715. }
  3716. }
  3717. });
  3718. let searchText = "";
  3719. function doSearch(value) {
  3720. searchText = value;
  3721. updateFilter();
  3722. }
  3723. function customEntityFromFile(file, x=0.5, y=0.5) {
  3724. file.arrayBuffer().then(buf => {
  3725. arr = new Uint8Array(buf);
  3726. blob = new Blob([arr], {type: file.type });
  3727. url = window.URL.createObjectURL(blob)
  3728. makeCustomEntity(url, x, y);
  3729. });
  3730. }
  3731. function makeCustomEntity(url, x=0.5, y=0.5) {
  3732. const maker = createEntityMaker(
  3733. {
  3734. name: "Custom Entity"
  3735. },
  3736. {
  3737. custom: {
  3738. attributes: {
  3739. height: {
  3740. name: "Height",
  3741. power: 1,
  3742. type: "length",
  3743. base: math.unit(6, "feet")
  3744. }
  3745. },
  3746. image: {
  3747. source: url
  3748. },
  3749. name: "Image",
  3750. info: {},
  3751. rename: false
  3752. }
  3753. },
  3754. []
  3755. );
  3756. const entity = maker.constructor();
  3757. entity.scale = config.height.toNumber("feet") / 20;
  3758. entity.ephemeral = true;
  3759. displayEntity(entity, "custom", x, y, true, true);
  3760. }
  3761. const filterDefs = {
  3762. none: {
  3763. id: "none",
  3764. name: "No Filter",
  3765. extract: maker => [],
  3766. render: name => name,
  3767. sort: (tag1, tag2) => tag1[1].localeCompare(tag2[1])
  3768. },
  3769. author: {
  3770. id: "author",
  3771. name: "Authors",
  3772. extract: maker => maker.authors ? maker.authors : [],
  3773. render: author => attributionData.people[author].name,
  3774. sort: (tag1, tag2) => tag1[1].localeCompare(tag2[1])
  3775. },
  3776. owner: {
  3777. id: "owner",
  3778. name: "Owners",
  3779. extract: maker => maker.owners ? maker.owners : [],
  3780. render: owner => attributionData.people[owner].name,
  3781. sort: (tag1, tag2) => tag1[1].localeCompare(tag2[1])
  3782. },
  3783. species: {
  3784. id: "species",
  3785. name: "Species",
  3786. extract: maker => maker.info && maker.info.species ? getSpeciesInfo(maker.info.species) : [],
  3787. render: species => speciesData[species].name,
  3788. sort: (tag1, tag2) => tag1[1].localeCompare(tag2[1])
  3789. },
  3790. tags: {
  3791. id: "tags",
  3792. name: "Tags",
  3793. extract: maker => maker.info && maker.info.tags ? maker.info.tags : [],
  3794. render: tag => tagDefs[tag],
  3795. sort: (tag1, tag2) => tag1[1].localeCompare(tag2[1])
  3796. },
  3797. size: {
  3798. id: "size",
  3799. name: "Normal Size",
  3800. extract: maker => maker.sizes && maker.sizes.length > 0 ? Array.from(maker.sizes.reduce((result, size) => {
  3801. if (result && !size.default) {
  3802. return result;
  3803. }
  3804. let meters = size.height.toNumber("meters");
  3805. if (meters < 1e-1) {
  3806. return ["micro"];
  3807. } else if (meters < 1e1) {
  3808. return ["moderate"];
  3809. } else {
  3810. return ["macro"];
  3811. }
  3812. }, null)) : [],
  3813. render: tag => { return {
  3814. "micro": "Micro",
  3815. "moderate": "Moderate",
  3816. "macro": "Macro"
  3817. }[tag]},
  3818. sort: (tag1, tag2) => {
  3819. const order = {
  3820. "micro": 0,
  3821. "moderate": 1,
  3822. "macro": 2
  3823. };
  3824. return order[tag1[0]] - order[tag2[0]];
  3825. }
  3826. },
  3827. allSizes: {
  3828. id: "allSizes",
  3829. name: "Possible Size",
  3830. extract: maker => maker.sizes ? Array.from(maker.sizes.reduce((set, size) => {
  3831. const height = size.height;
  3832. let result = Object.entries(sizeCategories).reduce((result, [name, value]) => {
  3833. if (result) {
  3834. return result;
  3835. } else {
  3836. if (math.compare(height, value) <= 0) {
  3837. return name;
  3838. }
  3839. }
  3840. }, null);
  3841. set.add(result ? result : "infinite");
  3842. return set;
  3843. }, new Set())) : [],
  3844. render: tag => tag[0].toUpperCase() + tag.slice(1),
  3845. sort: (tag1, tag2) => {
  3846. const order = [
  3847. "atomic", "microscopic", "tiny", "small", "moderate", "large", "macro", "megamacro", "planetary", "stellar",
  3848. "galactic", "universal", "omniversal", "infinite"
  3849. ]
  3850. return order.indexOf(tag1[0]) - order.indexOf(tag2[0]);
  3851. }
  3852. }
  3853. }
  3854. const sizeCategories = {
  3855. "atomic": math.unit(100, "angstroms"),
  3856. "microscopic": math.unit(100, "micrometers"),
  3857. "tiny": math.unit(100, "millimeters"),
  3858. "small": math.unit(1, "meter"),
  3859. "moderate": math.unit(3, "meters"),
  3860. "large": math.unit(10, "meters"),
  3861. "macro": math.unit(300, "meters"),
  3862. "megamacro": math.unit(1000, "kilometers"),
  3863. "planetary": math.unit(10, "earths"),
  3864. "stellar": math.unit(10, "solarradii"),
  3865. "galactic": math.unit(10, "galaxies"),
  3866. "universal": math.unit(10, "universes"),
  3867. "omniversal": math.unit(10, "multiverses")
  3868. };
  3869. function prepareEntities() {
  3870. availableEntities["buildings"] = makeBuildings();
  3871. availableEntities["characters"] = makeCharacters();
  3872. availableEntities["clothing"] = makeClothing();
  3873. availableEntities["creatures"] = makeCreatures();
  3874. availableEntities["fiction"] = makeFiction();
  3875. availableEntities["food"] = makeFood();
  3876. availableEntities["furniture"] = makeFurniture();
  3877. availableEntities["landmarks"] = makeLandmarks();
  3878. availableEntities["naturals"] = makeNaturals();
  3879. availableEntities["objects"] = makeObjects();
  3880. availableEntities["pokemon"] = makePokemon();
  3881. availableEntities["real-buildings"] = makeRealBuildings();
  3882. availableEntities["real-terrain"] = makeRealTerrains();
  3883. availableEntities["species"] = makeSpecies();
  3884. availableEntities["vehicles"] = makeVehicles();
  3885. availableEntities["species"].forEach(x => {
  3886. if (x.name == "Human") {
  3887. availableEntities["food"].push(x);
  3888. }
  3889. })
  3890. availableEntities["characters"].sort((x, y) => {
  3891. return x.name.localeCompare(y.name)
  3892. });
  3893. availableEntities["species"].sort((x, y) => {
  3894. return x.name.localeCompare(y.name)
  3895. });
  3896. availableEntities["objects"].sort((x, y) => {
  3897. return x.name.localeCompare(y.name)
  3898. });
  3899. availableEntities["furniture"].sort((x, y) => {
  3900. return x.name.localeCompare(y.name)
  3901. });
  3902. const holder = document.querySelector("#spawners");
  3903. const filterHolder = document.querySelector("#filters");
  3904. const categorySelect = document.createElement("select");
  3905. categorySelect.id = "category-picker";
  3906. const filterSelect = document.createElement("select");
  3907. filterSelect.id = "filter-picker";
  3908. holder.appendChild(categorySelect);
  3909. filterHolder.appendChild(filterSelect);
  3910. const filterSets = {};
  3911. Object.values(filterDefs).forEach(filter => {
  3912. filterSets[filter.id] = new Set();
  3913. })
  3914. Object.entries(availableEntities).forEach(([category, entityList]) => {
  3915. const select = document.createElement("select");
  3916. select.id = "create-entity-" + category;
  3917. select.classList.add("entity-select");
  3918. for (let i = 0; i < entityList.length; i++) {
  3919. const entity = entityList[i];
  3920. const option = document.createElement("option");
  3921. option.value = i;
  3922. option.innerText = entity.name;
  3923. select.appendChild(option);
  3924. if (entity.nsfw) {
  3925. option.classList.add("nsfw");
  3926. }
  3927. Object.values(filterDefs).forEach(filter => {
  3928. filter.extract(entity).forEach(result => {
  3929. filterSets[filter.id].add(result);
  3930. });
  3931. });
  3932. availableEntitiesByName[entity.name] = entity;
  3933. };
  3934. select.addEventListener("change", e => {
  3935. if (select.options[select.selectedIndex]?.classList.contains("nsfw")) {
  3936. select.classList.add("nsfw");
  3937. } else {
  3938. select.classList.remove("nsfw");
  3939. }
  3940. // preload the entity's first image
  3941. const entity = entityList[select.selectedIndex]?.constructor();
  3942. if (entity)
  3943. {
  3944. let img = new Image();
  3945. img.src = entity.currentView.image.source;
  3946. }
  3947. })
  3948. const button = document.createElement("button");
  3949. button.id = "create-entity-" + category + "-button";
  3950. button.classList.add("entity-button");
  3951. button.innerHTML = "<i class=\"far fa-plus-square\"></i>";
  3952. button.addEventListener("click", e => {
  3953. if (entityList[select.value] == null)
  3954. return;
  3955. const newEntity = entityList[select.value].constructor()
  3956. let yOffset = 0;
  3957. if (config.lockYAxis) {
  3958. yOffset = getVerticalOffset();
  3959. } else {
  3960. yOffset = (config.lockYAxis ? 0 : config.height.toNumber("meters")/2);
  3961. }
  3962. displayEntity(newEntity, newEntity.defaultView, config.x, config.y + yOffset, true, true);
  3963. });
  3964. const categoryOption = document.createElement("option");
  3965. categoryOption.value = category
  3966. categoryOption.innerText = category;
  3967. if (category == "characters") {
  3968. categoryOption.selected = true;
  3969. select.classList.add("category-visible");
  3970. button.classList.add("category-visible");
  3971. }
  3972. categorySelect.appendChild(categoryOption);
  3973. holder.appendChild(select);
  3974. holder.appendChild(button);
  3975. });
  3976. Object.values(filterDefs).forEach(filter => {
  3977. const option = document.createElement("option");
  3978. option.innerText = filter.name;
  3979. option.value = filter.id;
  3980. filterSelect.appendChild(option);
  3981. const filterNameSelect = document.createElement("select");
  3982. filterNameSelect.classList.add("filter-select");
  3983. filterNameSelect.id = "filter-" + filter.id;
  3984. filterHolder.appendChild(filterNameSelect);
  3985. const button = document.createElement("button");
  3986. button.classList.add("filter-button");
  3987. button.id = "create-filtered-" + filter.id + "-button";
  3988. filterHolder.appendChild(button);
  3989. const counter = document.createElement("div");
  3990. counter.classList.add("button-counter");
  3991. counter.innerText = "10";
  3992. button.appendChild(counter);
  3993. const i = document.createElement("i");
  3994. i.classList.add("fas");
  3995. i.classList.add("fa-plus");
  3996. button.appendChild(i);
  3997. button.addEventListener("click", e => {
  3998. const makers = Array.from(document.querySelector(".entity-select.category-visible")).filter(element => !element.classList.contains("filtered"));
  3999. const count = makers.length + 2;
  4000. let index = 1;
  4001. if (makers.length > 50) {
  4002. if (!confirm("Really spawn " + makers.length + " things at once?")) {
  4003. return;
  4004. }
  4005. }
  4006. const worldWidth = config.height.toNumber("meters") / canvasHeight * canvasWidth;
  4007. const spawned = makers.map(element => {
  4008. const category = document.querySelector("#category-picker").value;
  4009. const maker = availableEntities[category][element.value];
  4010. const entity = maker.constructor()
  4011. displayEntity(entity, entity.view, -worldWidth * 0.45 + config.x + worldWidth * 0.9 * index / (count - 1), config.y);
  4012. index += 1;
  4013. return entityIndex - 1;
  4014. });
  4015. updateSizes(true);
  4016. if (config.autoFitAdd) {
  4017. let targets = {};
  4018. spawned.forEach(key => {
  4019. targets[key] = entities[key];
  4020. })
  4021. fitEntities(targets);
  4022. }
  4023. });
  4024. Array.from(filterSets[filter.id]).map(name => [name, filter.render(name)]).sort(filterDefs[filter.id].sort).forEach(name => {
  4025. const option = document.createElement("option");
  4026. option.innerText = name[1];
  4027. option.value = name[0];
  4028. filterNameSelect.appendChild(option);
  4029. });
  4030. filterNameSelect.addEventListener("change", e => {
  4031. updateFilter();
  4032. });
  4033. });
  4034. console.log("Loaded " + Object.keys(availableEntitiesByName).length + " entities");
  4035. categorySelect.addEventListener("input", e => {
  4036. const oldSelect = document.querySelector(".entity-select.category-visible");
  4037. oldSelect.classList.remove("category-visible");
  4038. const oldButton = document.querySelector(".entity-button.category-visible");
  4039. oldButton.classList.remove("category-visible");
  4040. const newSelect = document.querySelector("#create-entity-" + e.target.value);
  4041. newSelect.classList.add("category-visible");
  4042. const newButton = document.querySelector("#create-entity-" + e.target.value + "-button");
  4043. newButton.classList.add("category-visible");
  4044. recomputeFilters();
  4045. updateFilter();
  4046. });
  4047. recomputeFilters();
  4048. filterSelect.addEventListener("input", e => {
  4049. const oldSelect = document.querySelector(".filter-select.category-visible");
  4050. if (oldSelect)
  4051. oldSelect.classList.remove("category-visible");
  4052. const newSelect = document.querySelector("#filter-" + e.target.value);
  4053. if (newSelect && e.target.value != "none")
  4054. newSelect.classList.add("category-visible");
  4055. updateFilter();
  4056. });
  4057. ratioInfo = document.body.querySelector(".extra-info")
  4058. }
  4059. // Only display authors and owners if they appear
  4060. // somewhere in the current entity list
  4061. function recomputeFilters() {
  4062. const category = document.querySelector("#category-picker").value;
  4063. const filterSets = {};
  4064. Object.values(filterDefs).forEach(filter => {
  4065. filterSets[filter.id] = new Set();
  4066. });
  4067. document.querySelectorAll(".entity-select.category-visible > option").forEach(element => {
  4068. const entity = availableEntities[category][element.value];
  4069. Object.values(filterDefs).forEach(filter => {
  4070. filter.extract(entity).forEach(result => {
  4071. filterSets[filter.id].add(result);
  4072. });
  4073. });
  4074. });
  4075. Object.values(filterDefs).forEach(filter => {
  4076. // always show the "none" option
  4077. let found = filter.id == "none";
  4078. document.querySelectorAll("#filter-" + filter.id + " > option").forEach(element => {
  4079. if (filterSets[filter.id].has(element.value) || filter.id == "none") {
  4080. element.classList.remove("filtered");
  4081. element.disabled = false;
  4082. found = true;
  4083. } else {
  4084. element.classList.add("filtered");
  4085. element.disabled = true;
  4086. }
  4087. });
  4088. const filterOption = document.querySelector("#filter-picker > option[value='" + filter.id + "']");
  4089. if (found) {
  4090. filterOption.classList.remove("filtered");
  4091. filterOption.disabled = false;
  4092. } else {
  4093. filterOption.classList.add("filtered");
  4094. filterOption.disabled = true;
  4095. }
  4096. });
  4097. document.querySelector("#filter-picker").value = "none";
  4098. document.querySelector("#filter-picker").dispatchEvent(new Event("input"));
  4099. }
  4100. function updateFilter() {
  4101. const category = document.querySelector("#category-picker").value;
  4102. const type = document.querySelector("#filter-picker").value;
  4103. const filterKeySelect = document.querySelector(".filter-select.category-visible");
  4104. clearFilter();
  4105. const noFilter = !filterKeySelect;
  4106. let key;
  4107. let current = document.querySelector(".entity-select.category-visible").value;
  4108. if (!noFilter)
  4109. {
  4110. key = filterKeySelect.value;
  4111. current
  4112. }
  4113. let replace = current == "";
  4114. let first = null;
  4115. let count = 0;
  4116. const lowerSearchText = searchText !== "" ? searchText.toLowerCase() : null;
  4117. document.querySelectorAll(".entity-select.category-visible > option").forEach(element => {
  4118. let keep = noFilter;
  4119. if (!noFilter && filterDefs[type].extract(availableEntities[category][element.value]).indexOf(key) >= 0) {
  4120. keep = true;
  4121. }
  4122. if (searchText != "" && !availableEntities[category][element.value].name.toLowerCase().includes(lowerSearchText))
  4123. {
  4124. keep = false;
  4125. }
  4126. if (!keep) {
  4127. element.classList.add("filtered");
  4128. element.disabled = true;
  4129. if (current == element.value) {
  4130. replace = true;
  4131. }
  4132. } else {
  4133. count += 1;
  4134. if (!first) {
  4135. first = element.value;
  4136. }
  4137. }
  4138. });
  4139. const button = document.querySelector(".filter-select.category-visible + button");
  4140. if (button) {
  4141. button.querySelector(".button-counter").innerText = count;
  4142. }
  4143. if (replace) {
  4144. document.querySelector(".entity-select.category-visible").value = first;
  4145. document.querySelector("#create-entity-" + category).dispatchEvent(new Event("change"));
  4146. }
  4147. }
  4148. function clearFilter() {
  4149. document.querySelectorAll(".entity-select.category-visible > option").forEach(element => {
  4150. element.classList.remove("filtered");
  4151. element.disabled = false;
  4152. });
  4153. }
  4154. function checkFitWorld() {
  4155. if (config.autoFit) {
  4156. fitWorld();
  4157. return true;
  4158. }
  4159. return false;
  4160. }
  4161. function fitWorld(manual = false, factor = 1.1) {
  4162. if (Object.keys(entities).length > 0) {
  4163. fitEntities(entities, factor);
  4164. }
  4165. }
  4166. function fitEntities(targetEntities, manual = false, factor = 1.1) {
  4167. let minX = Infinity;
  4168. let maxX = -Infinity;
  4169. let minY = Infinity;
  4170. let maxY = -Infinity;
  4171. let count = 0;
  4172. const worldWidth = config.height.toNumber("meters") / canvasHeight * canvasWidth;
  4173. const worldHeight = config.height.toNumber("meters");
  4174. Object.entries(targetEntities).forEach(([key, entity]) => {
  4175. const view = entity.view;
  4176. let extra = entity.views[view].image.extra;
  4177. extra = extra === undefined ? 1 : extra;
  4178. const image = document.querySelector("#entity-" + key + " > .entity-image");
  4179. const x = parseFloat(document.querySelector("#entity-" + key).dataset.x);
  4180. let width = image.width;
  4181. let height = image.height;
  4182. // only really relevant if the images haven't loaded in yet
  4183. if (height == 0) {
  4184. height = 100;
  4185. }
  4186. if (width == 0) {
  4187. width = height;
  4188. }
  4189. const xBottom = x - entity.views[view].height.toNumber("meters") * width / height / 2;
  4190. const xTop = x + entity.views[view].height.toNumber("meters") * width / height / 2;
  4191. const y = parseFloat(document.querySelector("#entity-" + key).dataset.y);
  4192. const yBottom = y;
  4193. const yTop = entity.views[view].height.toNumber("meters") + yBottom;
  4194. minX = Math.min(minX, xBottom);
  4195. maxX = Math.max(maxX, xTop);
  4196. minY = Math.min(minY, yBottom);
  4197. maxY = Math.max(maxY, yTop);
  4198. count += 1;
  4199. });
  4200. if (config.lockYAxis) {
  4201. minY = 0;
  4202. }
  4203. let ySize = (maxY - minY) * factor;
  4204. let xSize = (maxX - minX) * factor;
  4205. if (xSize / ySize > worldWidth / worldHeight) {
  4206. ySize *= ((xSize / ySize) / (worldWidth / worldHeight));
  4207. }
  4208. config.x = (maxX + minX) / 2;
  4209. config.y = minY;
  4210. height = math.unit(ySize, "meter")
  4211. setWorldHeight(config.height, math.multiply(height, factor));
  4212. }
  4213. function updateWorldHeight() {
  4214. const unit = document.querySelector("#options-height-unit").value;
  4215. const rawValue = document.querySelector("#options-height-value").value;
  4216. var value
  4217. try {
  4218. value = math.evaluate(rawValue)
  4219. if (typeof(value) !== "number") {
  4220. try {
  4221. value = value.toNumber(unit)
  4222. } catch {
  4223. toast("Invalid input: " + rawValue + " can't be converted to " + unit)
  4224. }
  4225. }
  4226. } catch {
  4227. toast("Invalid input: could not parse " + rawValue)
  4228. return;
  4229. }
  4230. const newHeight = Math.max(0.000000001, value);
  4231. const oldHeight = config.height;
  4232. setWorldHeight(oldHeight, math.unit(newHeight, unit), true);
  4233. }
  4234. function setWorldHeight(oldHeight, newHeight, keepUnit=false) {
  4235. worldSizeDirty = true;
  4236. config.height = newHeight.to(document.querySelector("#options-height-unit").value)
  4237. const unit = document.querySelector("#options-height-unit").value;
  4238. setNumericInput(document.querySelector("#options-height-value"), config.height.toNumber(unit));
  4239. Object.entries(entities).forEach(([key, entity]) => {
  4240. const element = document.querySelector("#entity-" + key);
  4241. let newPosition;
  4242. if (altHeld) {
  4243. newPosition = adjustAbs({ x: element.dataset.x, y: element.dataset.y }, oldHeight, config.height);
  4244. } else {
  4245. newPosition = { x: element.dataset.x, y: element.dataset.y };
  4246. }
  4247. element.dataset.x = newPosition.x;
  4248. element.dataset.y = newPosition.y;
  4249. });
  4250. if (!keepUnit) {
  4251. pickUnit()
  4252. }
  4253. updateSizes();
  4254. }
  4255. function loadScene(name = "default") {
  4256. if (name === "") {
  4257. name = "default"
  4258. }
  4259. try {
  4260. const data = JSON.parse(localStorage.getItem("macrovision-save-" + name));
  4261. if (data === null) {
  4262. console.error("Couldn't load " + name)
  4263. return false;
  4264. }
  4265. importScene(data);
  4266. toast("Loaded " + name);
  4267. return true;
  4268. } catch (err) {
  4269. alert("Something went wrong while loading (maybe you didn't have anything saved. Check the F12 console for the error.")
  4270. console.error(err);
  4271. return false;
  4272. }
  4273. }
  4274. function saveScene(name = "default") {
  4275. try {
  4276. const string = JSON.stringify(exportScene());
  4277. localStorage.setItem("macrovision-save-" + name, string);
  4278. toast("Saved as " + name);
  4279. } catch (err) {
  4280. alert("Something went wrong while saving (maybe I don't have localStorage permissions, or exporting failed). Check the F12 console for the error.")
  4281. console.error(err);
  4282. }
  4283. }
  4284. function deleteScene(name = "default") {
  4285. if (confirm("Really delete the " + name + " scene?")) {
  4286. try {
  4287. localStorage.removeItem("macrovision-save-" + name)
  4288. toast("Deleted " + name);
  4289. } catch (err) {
  4290. console.error(err);
  4291. }
  4292. }
  4293. updateSaveInfo();
  4294. }
  4295. function exportScene() {
  4296. const results = {};
  4297. results.entities = [];
  4298. Object.entries(entities).filter(([key, entity]) => entity.ephemeral !== true).forEach(([key, entity]) => {
  4299. const element = document.querySelector("#entity-" + key);
  4300. results.entities.push({
  4301. name: entity.identifier,
  4302. customName: entity.name,
  4303. scale: entity.scale,
  4304. rotation: entity.rotation,
  4305. view: entity.view,
  4306. form: entity.form,
  4307. x: element.dataset.x,
  4308. y: element.dataset.y,
  4309. priority: entity.priority,
  4310. brightness: entity.brightness
  4311. });
  4312. });
  4313. const unit = document.querySelector("#options-height-unit").value;
  4314. results.world = {
  4315. height: config.height.toNumber(unit),
  4316. unit: unit,
  4317. x: config.x,
  4318. y: config.y
  4319. }
  4320. results.version = migrationDefs.length;
  4321. return results;
  4322. }
  4323. // btoa doesn't like anything that isn't ASCII
  4324. // great
  4325. // thanks to https://stackoverflow.com/questions/30106476/using-javascripts-atob-to-decode-base64-doesnt-properly-decode-utf-8-strings
  4326. // for providing an alternative
  4327. function b64EncodeUnicode(str) {
  4328. // first we use encodeURIComponent to get percent-encoded UTF-8,
  4329. // then we convert the percent encodings into raw bytes which
  4330. // can be fed into btoa.
  4331. return btoa(encodeURIComponent(str).replace(/%([0-9A-F]{2})/g,
  4332. function toSolidBytes(match, p1) {
  4333. return String.fromCharCode('0x' + p1);
  4334. }));
  4335. }
  4336. function b64DecodeUnicode(str) {
  4337. // Going backwards: from bytestream, to percent-encoding, to original string.
  4338. return decodeURIComponent(atob(str).split('').map(function (c) {
  4339. return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
  4340. }).join(''));
  4341. }
  4342. function linkScene() {
  4343. loc = new URL(window.location);
  4344. const link = loc.protocol + "//" + loc.host + loc.pathname + "#" + b64EncodeUnicode(JSON.stringify(exportScene()));
  4345. window.history.replaceState(null, "Macrovision", link);
  4346. try {
  4347. navigator.clipboard.writeText(link);
  4348. toast("Copied permalink to clipboard");
  4349. } catch {
  4350. toast("Couldn't copy permalink");
  4351. }
  4352. }
  4353. function copyScene() {
  4354. const results = exportScene();
  4355. navigator.clipboard.writeText(JSON.stringify(results));
  4356. }
  4357. function pasteScene() {
  4358. try {
  4359. navigator.clipboard.readText().then(text => {
  4360. const data = JSON.parse(text);
  4361. if (data.entities === undefined) {
  4362. return;
  4363. }
  4364. if (data.world === undefined) {
  4365. return;
  4366. }
  4367. importScene(data);
  4368. }).catch(err => alert(err));
  4369. } catch (err) {
  4370. console.error(err);
  4371. // probably wasn't valid data
  4372. }
  4373. }
  4374. // TODO - don't just search through every single entity
  4375. // probably just have a way to do lookups directly
  4376. function findEntity(name) {
  4377. return availableEntitiesByName[name];
  4378. }
  4379. const migrationDefs = [
  4380. /*
  4381. Migration: 0 -> 1
  4382. Adds x and y coordinates for the camera
  4383. */
  4384. data => {
  4385. data.world.x = 0;
  4386. data.world.y = 0;
  4387. },
  4388. /*
  4389. Migration: 1 -> 2
  4390. Adds priority and brightness to each entity
  4391. */
  4392. data => {
  4393. data.entities.forEach(entity => {
  4394. entity.priority = 0;
  4395. entity.brightness = 1;
  4396. });
  4397. },
  4398. /*
  4399. Migration: 2 -> 3
  4400. Custom names are exported
  4401. */
  4402. data => {
  4403. data.entities.forEach(entity => {
  4404. entity.customName = entity.name
  4405. });
  4406. },
  4407. /*
  4408. Migration: 3 -> 4
  4409. Rotation is now stored
  4410. */
  4411. data => {
  4412. data.entities.forEach(entity => {
  4413. entity.rotation = 0
  4414. });
  4415. }
  4416. ]
  4417. function migrateScene(data) {
  4418. if (data.version === undefined) {
  4419. alert("This save was created before save versions were tracked. The scene may import incorrectly.");
  4420. console.trace()
  4421. data.version = 0;
  4422. } else if (data.version < migrationDefs.length) {
  4423. migrationDefs[data.version](data);
  4424. data.version += 1;
  4425. migrateScene(data);
  4426. }
  4427. }
  4428. function importScene(data) {
  4429. removeAllEntities();
  4430. migrateScene(data);
  4431. data.entities.forEach(entityInfo => {
  4432. const entity = findEntity(entityInfo.name).constructor();
  4433. entity.name = entityInfo.customName;
  4434. entity.scale = entityInfo.scale;
  4435. entity.rotation = entityInfo.rotation;
  4436. entity.priority = entityInfo.priority;
  4437. entity.brightness = entityInfo.brightness;
  4438. entity.form = entityInfo.form;
  4439. displayEntity(entity, entityInfo.view, entityInfo.x, entityInfo.y);
  4440. });
  4441. config.height = math.unit(data.world.height, data.world.unit);
  4442. config.x = data.world.x;
  4443. config.y = data.world.y;
  4444. const height = math.unit(data.world.height, data.world.unit).toNumber(defaultUnits.length[config.units]);
  4445. document.querySelector("#options-height-value").value = height;
  4446. document.querySelector("#options-height-unit").dataset.oldUnit = defaultUnits.length[config.units];
  4447. document.querySelector("#options-height-unit").value = defaultUnits.length[config.units];
  4448. if (data.canvasWidth) {
  4449. doHorizReposition(data.canvasWidth / canvasWidth);
  4450. }
  4451. updateSizes();
  4452. }
  4453. function renderToCanvas() {
  4454. const ctx = document.querySelector("#display").getContext("2d");
  4455. Object.entries(entities).sort((ent1, ent2) => {
  4456. z1 = document.querySelector("#entity-" + ent1[0]).style.zIndex;
  4457. z2 = document.querySelector("#entity-" + ent2[0]).style.zIndex;
  4458. return z1 - z2;
  4459. }).forEach(([id, entity]) => {
  4460. element = document.querySelector("#entity-" + id);
  4461. img = element.querySelector("img");
  4462. let x = parseFloat(element.dataset.x);
  4463. let y = parseFloat(element.dataset.y);
  4464. let coords = pos2pix({x: x, y: y});
  4465. let offset = img.style.getPropertyValue("--offset");
  4466. offset = parseFloat(offset.substring(0, offset.length-1))
  4467. let xSize = img.width;
  4468. let ySize = img.height;
  4469. x = coords.x
  4470. y = coords.y + ySize/2 + ySize * offset / 100;
  4471. const oldFilter = ctx.filter
  4472. const brightness = getComputedStyle(element).getPropertyValue("--brightness")
  4473. ctx.filter = `brightness(${brightness})`;
  4474. ctx.save();
  4475. ctx.resetTransform();
  4476. ctx.scale(window.devicePixelRatio, window.devicePixelRatio)
  4477. ctx.translate(x, y);
  4478. ctx.rotate(entity.rotation);
  4479. ctx.drawImage(img, -xSize/2, -ySize/2, xSize, ySize);
  4480. ctx.restore();
  4481. ctx.filter = oldFilter
  4482. });
  4483. ctx.save();
  4484. ctx.resetTransform();
  4485. ctx.drawImage(document.querySelector("#rulers"), 0, 0);
  4486. ctx.restore();
  4487. }
  4488. function exportCanvas(callback) {
  4489. /** @type {CanvasRenderingContext2D} */
  4490. const ctx = document.querySelector("#display").getContext("2d");
  4491. const blob = ctx.canvas.toBlob(callback);
  4492. }
  4493. function generateScreenshot(callback) {
  4494. /** @type {CanvasRenderingContext2D} */
  4495. const ctx = document.querySelector("#display").getContext("2d");
  4496. if (config.groundKind !== "none") {
  4497. ctx.fillStyle = backgroundColors[config.groundKind];
  4498. ctx.fillRect(0, pos2pix({x: 0, y: 0}).y, canvasWidth + 100, canvasHeight);
  4499. }
  4500. renderToCanvas();
  4501. ctx.resetTransform();
  4502. ctx.fillStyle = "#999";
  4503. ctx.font = "normal normal lighter 16pt coda";
  4504. ctx.fillText("macrovision.crux.sexy", 10, 25);
  4505. exportCanvas(blob => {
  4506. callback(blob);
  4507. });
  4508. }
  4509. function copyScreenshot() {
  4510. if (window.ClipboardItem === undefined) {
  4511. alert("Sorry, this browser doesn't yet support writing images to the clipboard.");
  4512. return;
  4513. }
  4514. generateScreenshot(blob => {
  4515. navigator.clipboard.write([
  4516. new ClipboardItem({
  4517. "image/png": blob
  4518. })
  4519. ]).then(e =>
  4520. toast("Copied to clipboard!"))
  4521. .catch(e => {
  4522. console.error(e);
  4523. toast("Couldn't write to the clipboard. Make sure the screenshot completes before switching tabs. Also, currently busted in Safari :(")
  4524. })
  4525. });
  4526. drawScales(false);
  4527. }
  4528. function saveScreenshot() {
  4529. generateScreenshot(blob => {
  4530. const a = document.createElement("a");
  4531. a.href = URL.createObjectURL(blob);
  4532. a.setAttribute("download", "macrovision.png");
  4533. a.click();
  4534. });
  4535. drawScales(false);
  4536. }
  4537. function openScreenshot() {
  4538. generateScreenshot(blob => {
  4539. const a = document.createElement("a");
  4540. a.href = URL.createObjectURL(blob);
  4541. a.setAttribute("target", "_blank");
  4542. a.click();
  4543. });
  4544. drawScales(false);
  4545. }
  4546. const rateLimits = {};
  4547. function toast(msg) {
  4548. let div = document.createElement("div");
  4549. div.innerHTML = msg;
  4550. div.classList.add("toast");
  4551. document.body.appendChild(div);
  4552. setTimeout(() => {
  4553. document.body.removeChild(div);
  4554. }, 5000)
  4555. }
  4556. function toastRateLimit(msg, key, delay) {
  4557. if (!rateLimits[key]) {
  4558. toast(msg);
  4559. rateLimits[key] = setTimeout(() => {
  4560. delete rateLimits[key]
  4561. }, delay);
  4562. }
  4563. }
  4564. let lastTime = undefined;
  4565. function pan(fromX, fromY, fromHeight, toX, toY, toHeight, duration) {
  4566. Object.keys(entities).forEach(key => {
  4567. document.querySelector("#entity-" + key).classList.add("no-transition");
  4568. });
  4569. config.x = fromX;
  4570. config.y = fromY;
  4571. config.height = math.unit(fromHeight, "meters")
  4572. updateSizes();
  4573. lastTime = undefined;
  4574. requestAnimationFrame((timestamp) => panTo(toX, toY, toHeight, (toX - fromX) / duration, (toY - fromY) / duration, (toHeight - fromHeight) / duration, timestamp, duration));
  4575. }
  4576. function panTo(x, y, height, xSpeed, ySpeed, heightSpeed, timestamp, remaining) {
  4577. if (lastTime === undefined) {
  4578. lastTime = timestamp;
  4579. }
  4580. dt = timestamp - lastTime;
  4581. remaining -= dt;
  4582. if (remaining < 0) {
  4583. dt += remaining
  4584. }
  4585. let newX = config.x + xSpeed * dt;
  4586. let newY = config.y + ySpeed * dt;
  4587. let newHeight = config.height.toNumber("meters") + heightSpeed * dt;
  4588. if (remaining > 0) {
  4589. requestAnimationFrame((timestamp) => panTo(x, y, height, xSpeed, ySpeed, heightSpeed, timestamp, remaining))
  4590. } else {
  4591. Object.keys(entities).forEach(key => {
  4592. document.querySelector("#entity-" + key).classList.remove("no-transition");
  4593. });
  4594. }
  4595. config.x = newX;
  4596. config.y = newY;
  4597. config.height = math.unit(newHeight, "meters");
  4598. updateSizes();
  4599. }
  4600. function getVerticalOffset() {
  4601. if (config.groundPos === "very-high") {
  4602. return config.height.toNumber("meters") / 12 * 5;
  4603. } else if (config.groundPos === "high") {
  4604. return config.height.toNumber("meters") / 12 * 4;
  4605. } else if (config.groundPos === "medium") {
  4606. return config.height.toNumber("meters") / 12 * 3;
  4607. } else if (config.groundPos === "low") {
  4608. return config.height.toNumber("meters") / 12 * 2;
  4609. } else if (config.groundPos === "very-low") {
  4610. return config.height.toNumber("meters") / 12;
  4611. } else {
  4612. return 0;
  4613. }
  4614. }
  4615. function moveGround(down) {
  4616. const index = groundPosChoices.indexOf(config.groundPos);
  4617. if (down) {
  4618. if (index < groundPosChoices.length - 1) {
  4619. config.groundPos = groundPosChoices[index + 1]
  4620. }
  4621. } else {
  4622. if (index > 0) {
  4623. config.groundPos = groundPosChoices[index - 1]
  4624. }
  4625. }
  4626. updateScrollButtons();
  4627. updateSizes();
  4628. }
  4629. function updateScrollButtons() {
  4630. const up = document.querySelector("#scroll-up")
  4631. const down = document.querySelector("#scroll-down")
  4632. up.disabled = false;
  4633. down.disabled = false;
  4634. document.querySelector("#setting-ground-pos").value = config.groundPos;
  4635. if (config.lockYAxis) {
  4636. const index = groundPosChoices.indexOf(config.groundPos);
  4637. if (index == 0) {
  4638. down.disabled = true;
  4639. }
  4640. if (index == groundPosChoices.length - 1) {
  4641. up.disabled = true;
  4642. }
  4643. }
  4644. }