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

2925 строки
87 KiB

  1. let selected = null;
  2. let selectedEntity = null;
  3. let entityIndex = 0;
  4. let clicked = null;
  5. let dragging = false;
  6. let clickTimeout = null;
  7. let dragOffsetX = null;
  8. let dragOffsetY = null;
  9. let shiftHeld = false;
  10. let altHeld = false;
  11. let entityX;
  12. let canvasWidth;
  13. let canvasHeight;
  14. let dragScale = 1;
  15. let dragScaleHandle = null;
  16. let dragEntityScale = 1;
  17. let dragEntityScaleHandle = null;
  18. let scrollDirection = 0;
  19. let scrollHandle = null;
  20. let zoomDirection = 0;
  21. let zoomHandle = null;
  22. let sizeDirection = 0;
  23. let sizeHandle = null;
  24. let worldSizeDirty = false;
  25. const tagDefs = {
  26. "anthro": "Anthro",
  27. "feral": "Feral",
  28. "taur": "Taur"
  29. }
  30. math.createUnit("humans", {
  31. definition: "5.75 feet"
  32. });
  33. math.createUnit("story", {
  34. definition: "12 feet",
  35. prefixes: "long"
  36. });
  37. math.createUnit("stories", {
  38. definition: "12 feet",
  39. prefixes: "long"
  40. });
  41. math.createUnit("earths", {
  42. definition: "12756km",
  43. prefixes: "long"
  44. });
  45. math.createUnit("parsec", {
  46. definition: "3.086e16 meters",
  47. prefixes: "long"
  48. })
  49. math.createUnit("parsecs", {
  50. definition: "3.086e16 meters",
  51. prefixes: "long"
  52. })
  53. math.createUnit("lightyears", {
  54. definition: "9.461e15 meters",
  55. prefixes: "long"
  56. })
  57. math.createUnit("AU", {
  58. definition: "149597870700 meters"
  59. })
  60. math.createUnit("AUs", {
  61. definition: "149597870700 meters"
  62. })
  63. math.createUnit("dalton", {
  64. definition: "1.66e-27 kg",
  65. prefixes: "long"
  66. });
  67. math.createUnit("daltons", {
  68. definition: "1.66e-27 kg",
  69. prefixes: "long"
  70. });
  71. math.createUnit("solarradii", {
  72. definition: "695990 km",
  73. prefixes: "long"
  74. });
  75. math.createUnit("solarmasses", {
  76. definition: "2e30 kg",
  77. prefixes: "long"
  78. });
  79. math.createUnit("galaxy", {
  80. definition: "105700 lightyears",
  81. prefixes: "long"
  82. });
  83. math.createUnit("galaxies", {
  84. definition: "105700 lightyears",
  85. prefixes: "long"
  86. });
  87. math.createUnit("universe", {
  88. definition: "93.016e9 lightyears",
  89. prefixes: "long"
  90. });
  91. math.createUnit("universes", {
  92. definition: "93.016e9 lightyears",
  93. prefixes: "long"
  94. });
  95. math.createUnit("multiverse", {
  96. definition: "1e30 lightyears",
  97. prefixes: "long"
  98. });
  99. math.createUnit("multiverses", {
  100. definition: "1e30 lightyears",
  101. prefixes: "long"
  102. });
  103. math.createUnit("people", {
  104. definition: "75 liters",
  105. prefixes: "long"
  106. });
  107. math.createUnit("olympicPools", {
  108. definition: "2500 m^3",
  109. prefixes: "long"
  110. });
  111. math.createUnit("oceans", {
  112. definition: "700000000 km^3",
  113. prefixes: "long"
  114. });
  115. math.createUnit("earthVolumes", {
  116. definition: "1.0867813e12 km^3",
  117. prefixes: "long"
  118. });
  119. math.createUnit("universeVolumes", {
  120. definition: "4.2137775e+32 lightyears^3",
  121. prefixes: "long"
  122. });
  123. math.createUnit("multiverseVolumes", {
  124. definition: "5.2359878e+89 lightyears^3",
  125. prefixes: "long"
  126. });
  127. const unitChoices = {
  128. length: [
  129. "meters",
  130. "angstroms",
  131. "millimeters",
  132. "centimeters",
  133. "kilometers",
  134. "inches",
  135. "feet",
  136. "humans",
  137. "stories",
  138. "miles",
  139. "earths",
  140. "solarradii",
  141. "AUs",
  142. "lightyears",
  143. "parsecs",
  144. "galaxies",
  145. "universes",
  146. "multiverses"
  147. ],
  148. area: [
  149. "meters^2",
  150. "cm^2",
  151. "kilometers^2",
  152. "acres",
  153. "miles^2"
  154. ],
  155. volume: [
  156. "liters",
  157. "milliliters",
  158. "m^3",
  159. "gallons",
  160. "people",
  161. "olympicPools",
  162. "oceans",
  163. "earthVolumes",
  164. "universeVolumes",
  165. "multiverseVolumes",
  166. ],
  167. mass: [
  168. "kilograms",
  169. "milligrams",
  170. "grams",
  171. "tonnes",
  172. "lbs",
  173. "ounces",
  174. "tons"
  175. ]
  176. }
  177. const config = {
  178. height: math.unit(1500, "meters"),
  179. minLineSize: 100,
  180. maxLineSize: 150,
  181. autoFit: false,
  182. autoFitMode: "max"
  183. }
  184. const availableEntities = {
  185. }
  186. const availableEntitiesByName = {
  187. }
  188. const entities = {
  189. }
  190. function constrainRel(coords) {
  191. if (altHeld) {
  192. return coords;
  193. }
  194. return {
  195. x: Math.min(Math.max(coords.x, 0), 1),
  196. y: Math.min(Math.max(coords.y, 0), 1)
  197. }
  198. }
  199. function snapRel(coords) {
  200. return constrainRel({
  201. x: coords.x,
  202. y: altHeld ? coords.y : (Math.abs(coords.y - 1) < 0.05 ? 1 : coords.y)
  203. });
  204. }
  205. function adjustAbs(coords, oldHeight, newHeight) {
  206. const ratio = math.divide(oldHeight, newHeight);
  207. return { x: 0.5 + (coords.x - 0.5) * math.divide(oldHeight, newHeight), y: 1 + (coords.y - 1) * math.divide(oldHeight, newHeight) };
  208. }
  209. function rel2abs(coords) {
  210. return { x: coords.x * canvasWidth + 50, y: coords.y * canvasHeight };
  211. }
  212. function abs2rel(coords) {
  213. return { x: (coords.x - 50) / canvasWidth, y: coords.y / canvasHeight };
  214. }
  215. function updateEntityElement(entity, element) {
  216. const position = rel2abs({ x: element.dataset.x, y: element.dataset.y });
  217. const view = entity.view;
  218. element.style.left = position.x + "px";
  219. element.style.top = position.y + "px";
  220. element.style.setProperty("--xpos", position.x + "px");
  221. element.style.setProperty("--entity-height", "'" + entity.views[view].height.to(config.height.units[0].unit.name).format({ precision: 2 }) + "'");
  222. const pixels = math.divide(entity.views[view].height, config.height) * (canvasHeight - 50);
  223. const extra = entity.views[view].image.extra;
  224. const bottom = entity.views[view].image.bottom;
  225. const bonus = (extra ? extra : 1) * (1 / (1 - (bottom ? bottom : 0)));
  226. element.style.setProperty("--height", pixels * bonus + "px");
  227. element.style.setProperty("--extra", pixels * bonus - pixels + "px");
  228. if (entity.views[view].rename)
  229. element.querySelector(".entity-name").innerText = entity.name == "" ? "" : entity.views[view].name;
  230. else
  231. element.querySelector(".entity-name").innerText = entity.name;
  232. const bottomName = document.querySelector("#bottom-name-" + element.dataset.key);
  233. bottomName.style.left = position.x + entityX + "px";
  234. bottomName.style.bottom = "0vh";
  235. bottomName.innerText = entity.name;
  236. const topName = document.querySelector("#top-name-" + element.dataset.key);
  237. topName.style.left = position.x + entityX + "px";
  238. topName.style.top = "20vh";
  239. topName.innerText = entity.name;
  240. if (entity.views[view].height.toNumber("meters") / 10 > config.height.toNumber("meters")) {
  241. topName.classList.add("top-name-needed");
  242. } else {
  243. topName.classList.remove("top-name-needed");
  244. }
  245. }
  246. function updateSizes(dirtyOnly = false) {
  247. drawScale(dirtyOnly);
  248. let ordered = Object.entries(entities);
  249. ordered.sort((e1, e2) => {
  250. if (e1[1].priority != e2[1].priority) {
  251. return e2[1].priority - e1[1].priority;
  252. } else {
  253. return e1[1].views[e1[1].view].height.value - e2[1].views[e2[1].view].height.value
  254. }
  255. });
  256. let zIndex = ordered.length;
  257. ordered.forEach(entity => {
  258. const element = document.querySelector("#entity-" + entity[0]);
  259. element.style.zIndex = zIndex;
  260. if (!dirtyOnly || entity[1].dirty) {
  261. updateEntityElement(entity[1], element, zIndex);
  262. entity[1].dirty = false;
  263. }
  264. zIndex -= 1;
  265. });
  266. }
  267. function drawScale(ifDirty = false) {
  268. if (ifDirty && !worldSizeDirty)
  269. return;
  270. function drawTicks(/** @type {CanvasRenderingContext2D} */ ctx, pixelsPer, heightPer) {
  271. let total = heightPer.clone();
  272. total.value = 0;
  273. for (let y = ctx.canvas.clientHeight - 50; y >= 50; y -= pixelsPer) {
  274. drawTick(ctx, 50, y, total);
  275. total = math.add(total, heightPer);
  276. }
  277. }
  278. function drawTick(/** @type {CanvasRenderingContext2D} */ ctx, x, y, value) {
  279. const oldStroke = ctx.strokeStyle;
  280. const oldFill = ctx.fillStyle;
  281. ctx.beginPath();
  282. ctx.moveTo(x, y);
  283. ctx.lineTo(x + 20, y);
  284. ctx.strokeStyle = "#000000";
  285. ctx.stroke();
  286. ctx.beginPath();
  287. ctx.moveTo(x + 20, y);
  288. ctx.lineTo(ctx.canvas.clientWidth - 70, y);
  289. ctx.strokeStyle = "#aaaaaa";
  290. ctx.stroke();
  291. ctx.beginPath();
  292. ctx.moveTo(ctx.canvas.clientWidth - 70, y);
  293. ctx.lineTo(ctx.canvas.clientWidth - 50, y);
  294. ctx.strokeStyle = "#000000";
  295. ctx.stroke();
  296. const oldFont = ctx.font;
  297. ctx.font = 'normal 24pt coda';
  298. ctx.fillStyle = "#dddddd";
  299. ctx.beginPath();
  300. ctx.fillText(value.format({ precision: 3 }), x + 20, y + 35);
  301. ctx.font = oldFont;
  302. ctx.strokeStyle = oldStroke;
  303. ctx.fillStyle = oldFill;
  304. }
  305. const canvas = document.querySelector("#display");
  306. /** @type {CanvasRenderingContext2D} */
  307. const ctx = canvas.getContext("2d");
  308. let pixelsPer = (ctx.canvas.clientHeight - 100) / config.height.toNumber();
  309. heightPer = 1;
  310. if (pixelsPer < config.minLineSize) {
  311. const factor = math.ceil(config.minLineSize / pixelsPer);
  312. heightPer *= factor;
  313. pixelsPer *= factor;
  314. }
  315. if (pixelsPer > config.maxLineSize) {
  316. const factor = math.ceil(pixelsPer / config.maxLineSize);
  317. heightPer /= factor;
  318. pixelsPer /= factor;
  319. }
  320. heightPer = math.unit(heightPer, document.querySelector("#options-height-unit").value);
  321. ctx.scale(1, 1);
  322. ctx.canvas.width = canvas.clientWidth;
  323. ctx.canvas.height = canvas.clientHeight;
  324. ctx.beginPath();
  325. ctx.rect(0, 0, canvas.width, canvas.height);
  326. ctx.fillStyle = "#333";
  327. ctx.fill();
  328. ctx.beginPath();
  329. ctx.moveTo(50, 50);
  330. ctx.lineTo(50, ctx.canvas.clientHeight - 50);
  331. ctx.stroke();
  332. ctx.beginPath();
  333. ctx.moveTo(ctx.canvas.clientWidth - 50, 50);
  334. ctx.lineTo(ctx.canvas.clientWidth - 50, ctx.canvas.clientHeight - 50);
  335. ctx.stroke();
  336. drawTicks(ctx, pixelsPer, heightPer);
  337. }
  338. // Entities are generated as needed, and we make a copy
  339. // every time - the resulting objects get mutated, after all.
  340. // But we also want to be able to read some information without
  341. // calling the constructor -- e.g. making a list of authors and
  342. // owners. So, this function is used to generate that information.
  343. // It is invoked like makeEntity so that it can be dropped in easily,
  344. // but returns an object that lets you construct many copies of an entity,
  345. // rather than creating a new entity.
  346. function createEntityMaker(info, views, sizes) {
  347. const maker = {};
  348. maker.name = info.name;
  349. maker.info = info;
  350. maker.constructor = () => makeEntity(info, views, sizes);
  351. maker.authors = [];
  352. maker.owners = [];
  353. maker.nsfw = false;
  354. Object.values(views).forEach(view => {
  355. const authors = authorsOf(view.image.source);
  356. if (authors) {
  357. authors.forEach(author => {
  358. if (maker.authors.indexOf(author) == -1) {
  359. maker.authors.push(author);
  360. }
  361. });
  362. }
  363. const owners = ownersOf(view.image.source);
  364. if (owners) {
  365. owners.forEach(owner => {
  366. if (maker.owners.indexOf(owner) == -1) {
  367. maker.owners.push(owner);
  368. }
  369. });
  370. }
  371. if (isNsfw(view.image.source)) {
  372. maker.nsfw = true;
  373. }
  374. });
  375. return maker;
  376. }
  377. // This function serializes and parses its arguments to avoid sharing
  378. // references to a common object. This allows for the objects to be
  379. // safely mutated.
  380. function makeEntity(info, views, sizes) {
  381. const entityTemplate = {
  382. name: info.name,
  383. identifier: info.name,
  384. scale: 1,
  385. info: JSON.parse(JSON.stringify(info)),
  386. views: JSON.parse(JSON.stringify(views), math.reviver),
  387. sizes: sizes === undefined ? [] : JSON.parse(JSON.stringify(sizes), math.reviver),
  388. init: function () {
  389. const entity = this;
  390. Object.entries(this.views).forEach(([viewKey, view]) => {
  391. view.parent = this;
  392. if (this.defaultView === undefined) {
  393. this.defaultView = viewKey;
  394. this.view = viewKey;
  395. }
  396. if (view.default) {
  397. this.defaultView = viewKey;
  398. this.view = viewKey;
  399. }
  400. Object.entries(view.attributes).forEach(([key, val]) => {
  401. Object.defineProperty(
  402. view,
  403. key,
  404. {
  405. get: function () {
  406. return math.multiply(Math.pow(this.parent.scale, this.attributes[key].power), this.attributes[key].base);
  407. },
  408. set: function (value) {
  409. const newScale = Math.pow(math.divide(value, this.attributes[key].base), 1 / this.attributes[key].power);
  410. this.parent.scale = newScale;
  411. }
  412. }
  413. )
  414. });
  415. });
  416. this.sizes.forEach(size => {
  417. if (size.default === true) {
  418. this.views[this.defaultView].height = size.height;
  419. this.size = size;
  420. }
  421. });
  422. if (this.size === undefined && this.sizes.length > 0) {
  423. this.views[this.defaultView].height = this.sizes[0].height;
  424. this.size = this.sizes[0];
  425. console.warn("No default size set for " + info.name);
  426. } else if (this.sizes.length == 0) {
  427. this.sizes = [
  428. {
  429. name: "Normal",
  430. height: this.views[this.defaultView].height
  431. }
  432. ];
  433. this.size = this.sizes[0];
  434. }
  435. this.desc = {};
  436. Object.entries(this.info).forEach(([key, value]) => {
  437. Object.defineProperty(
  438. this.desc,
  439. key,
  440. {
  441. get: function () {
  442. let text = value.text;
  443. if (entity.views[entity.view].info) {
  444. if (entity.views[entity.view].info[key]) {
  445. text = combineInfo(text, entity.views[entity.view].info[key]);
  446. }
  447. }
  448. if (entity.size.info) {
  449. if (entity.size.info[key]) {
  450. text = combineInfo(text, entity.size.info[key]);
  451. }
  452. }
  453. return { title: value.title, text: text };
  454. }
  455. }
  456. )
  457. });
  458. delete this.init;
  459. return this;
  460. }
  461. }.init();
  462. return entityTemplate;
  463. }
  464. function combineInfo(existing, next) {
  465. switch (next.mode) {
  466. case "replace":
  467. return next.text;
  468. case "prepend":
  469. return next.text + existing;
  470. case "append":
  471. return existing + next.text;
  472. }
  473. return existing;
  474. }
  475. function clickDown(target, x, y) {
  476. clicked = target;
  477. const rect = target.getBoundingClientRect();
  478. let entX = document.querySelector("#entities").getBoundingClientRect().x;
  479. let entY = document.querySelector("#entities").getBoundingClientRect().y;
  480. dragOffsetX = x - rect.left + entX;
  481. dragOffsetY = y - rect.top + entY;
  482. clickTimeout = setTimeout(() => { dragging = true }, 200)
  483. target.classList.add("no-transition");
  484. }
  485. // could we make this actually detect the menu area?
  486. function hoveringInDeleteArea(e) {
  487. return e.clientY < document.body.clientHeight / 10;
  488. }
  489. function clickUp(e) {
  490. clearTimeout(clickTimeout);
  491. if (clicked) {
  492. if (dragging) {
  493. dragging = false;
  494. if (hoveringInDeleteArea(e)) {
  495. removeEntity(clicked);
  496. document.querySelector("#menubar").classList.remove("hover-delete");
  497. }
  498. } else {
  499. select(clicked);
  500. }
  501. clicked.classList.remove("no-transition");
  502. clicked = null;
  503. }
  504. }
  505. function deselect() {
  506. if (selected) {
  507. selected.classList.remove("selected");
  508. }
  509. document.getElementById("options-selected-entity-none").selected = "selected";
  510. clearAttribution();
  511. selected = null;
  512. clearViewList();
  513. clearEntityOptions();
  514. clearViewOptions();
  515. document.querySelector("#delete-entity").disabled = true;
  516. document.querySelector("#grow").disabled = true;
  517. document.querySelector("#shrink").disabled = true;
  518. document.querySelector("#fit").disabled = true;
  519. }
  520. function select(target) {
  521. deselect();
  522. selected = target;
  523. selectedEntity = entities[target.dataset.key];
  524. document.getElementById("options-selected-entity-" + target.dataset.key).selected = "selected";
  525. selected.classList.add("selected");
  526. displayAttribution(selectedEntity.views[selectedEntity.view].image.source);
  527. configViewList(selectedEntity, selectedEntity.view);
  528. configEntityOptions(selectedEntity, selectedEntity.view);
  529. configViewOptions(selectedEntity, selectedEntity.view);
  530. document.querySelector("#delete-entity").disabled = false;
  531. document.querySelector("#grow").disabled = false;
  532. document.querySelector("#shrink").disabled = false;
  533. document.querySelector("#fit").disabled = false;
  534. }
  535. function configViewList(entity, selectedView) {
  536. const list = document.querySelector("#entity-view");
  537. list.innerHTML = "";
  538. list.style.display = "block";
  539. Object.keys(entity.views).forEach(view => {
  540. const option = document.createElement("option");
  541. option.innerText = entity.views[view].name;
  542. option.value = view;
  543. if (isNsfw(entity.views[view].image.source)) {
  544. option.classList.add("nsfw")
  545. }
  546. if (view === selectedView) {
  547. option.selected = true;
  548. if (option.classList.contains("nsfw")) {
  549. list.classList.add("nsfw");
  550. } else {
  551. list.classList.remove("nsfw");
  552. }
  553. }
  554. list.appendChild(option);
  555. });
  556. }
  557. function clearViewList() {
  558. const list = document.querySelector("#entity-view");
  559. list.innerHTML = "";
  560. list.style.display = "none";
  561. }
  562. function updateWorldOptions(entity, view) {
  563. const heightInput = document.querySelector("#options-height-value");
  564. const heightSelect = document.querySelector("#options-height-unit");
  565. const converted = config.height.toNumber(heightSelect.value);
  566. setNumericInput(heightInput, converted);
  567. }
  568. function configEntityOptions(entity, view) {
  569. const holder = document.querySelector("#options-entity");
  570. document.querySelector("#entity-category-header").style.display = "block";
  571. document.querySelector("#entity-category").style.display = "block";
  572. holder.innerHTML = "";
  573. const scaleLabel = document.createElement("div");
  574. scaleLabel.classList.add("options-label");
  575. scaleLabel.innerText = "Scale";
  576. const scaleRow = document.createElement("div");
  577. scaleRow.classList.add("options-row");
  578. const scaleInput = document.createElement("input");
  579. scaleInput.classList.add("options-field-numeric");
  580. scaleInput.id = "options-entity-scale";
  581. scaleInput.addEventListener("change", e => {
  582. entity.scale = e.target.value == 0 ? 1 : e.target.value;
  583. entity.dirty = true;
  584. if (config.autoFit) {
  585. fitWorld();
  586. } else {
  587. updateSizes(true);
  588. }
  589. updateEntityOptions(entity, view);
  590. updateViewOptions(entity, view);
  591. });
  592. scaleInput.addEventListener("keydown", e => {
  593. e.stopPropagation();
  594. })
  595. scaleInput.setAttribute("min", 1);
  596. scaleInput.setAttribute("type", "number");
  597. setNumericInput(scaleInput, entity.scale);
  598. scaleRow.appendChild(scaleInput);
  599. holder.appendChild(scaleLabel);
  600. holder.appendChild(scaleRow);
  601. const nameLabel = document.createElement("div");
  602. nameLabel.classList.add("options-label");
  603. nameLabel.innerText = "Name";
  604. const nameRow = document.createElement("div");
  605. nameRow.classList.add("options-row");
  606. const nameInput = document.createElement("input");
  607. nameInput.classList.add("options-field-text");
  608. nameInput.value = entity.name;
  609. nameInput.addEventListener("input", e => {
  610. entity.name = e.target.value;
  611. entity.dirty = true;
  612. updateSizes(true);
  613. })
  614. nameInput.addEventListener("keydown", e => {
  615. e.stopPropagation();
  616. })
  617. nameRow.appendChild(nameInput);
  618. holder.appendChild(nameLabel);
  619. holder.appendChild(nameRow);
  620. const defaultHolder = document.querySelector("#options-entity-defaults");
  621. defaultHolder.innerHTML = "";
  622. entity.sizes.forEach(defaultInfo => {
  623. const button = document.createElement("button");
  624. button.classList.add("options-button");
  625. button.innerText = defaultInfo.name;
  626. button.addEventListener("click", e => {
  627. entity.views[entity.defaultView].height = defaultInfo.height;
  628. entity.dirty = true;
  629. updateEntityOptions(entity, entity.view);
  630. updateViewOptions(entity, entity.view);
  631. if (!checkFitWorld()) {
  632. updateSizes(true);
  633. }
  634. if (config.autoFitSize) {
  635. const x = parseFloat(selected.dataset.x);
  636. Object.keys(entities).forEach(id => {
  637. const element = document.querySelector("#entity-" + id);
  638. const newX = parseFloat(element.dataset.x) - x + 0.5;
  639. element.dataset.x = newX;
  640. });
  641. const entity = entities[selected.dataset.key];
  642. const height = math.multiply(entity.views[entity.view].height, 1.1);
  643. setWorldHeight(config.height, height);
  644. }
  645. });
  646. defaultHolder.appendChild(button);
  647. });
  648. document.querySelector("#options-order-display").innerText = entity.priority;
  649. document.querySelector("#options-ordering").style.display = "flex";
  650. }
  651. function updateEntityOptions(entity, view) {
  652. const scaleInput = document.querySelector("#options-entity-scale");
  653. setNumericInput(scaleInput, entity.scale);
  654. document.querySelector("#options-order-display").innerText = entity.priority;
  655. }
  656. function clearEntityOptions() {
  657. document.querySelector("#entity-category-header").style.display = "none";
  658. document.querySelector("#entity-category").style.display = "none";
  659. /*
  660. const holder = document.querySelector("#options-entity");
  661. holder.innerHTML = "";
  662. document.querySelector("#options-entity-defaults").innerHTML = "";
  663. document.querySelector("#options-ordering").style.display = "none";
  664. document.querySelector("#options-ordering").style.display = "none";*/
  665. }
  666. function configViewOptions(entity, view) {
  667. const holder = document.querySelector("#options-view");
  668. document.querySelector("#view-category-header").style.display = "block";
  669. document.querySelector("#view-category").style.display = "block";
  670. holder.innerHTML = "";
  671. Object.entries(entity.views[view].attributes).forEach(([key, val]) => {
  672. const label = document.createElement("div");
  673. label.classList.add("options-label");
  674. label.innerText = val.name;
  675. holder.appendChild(label);
  676. const row = document.createElement("div");
  677. row.classList.add("options-row");
  678. holder.appendChild(row);
  679. const input = document.createElement("input");
  680. input.classList.add("options-field-numeric");
  681. input.id = "options-view-" + key + "-input";
  682. input.setAttribute("type", "number");
  683. input.setAttribute("min", 1);
  684. const select = document.createElement("select");
  685. select.classList.add("options-field-unit");
  686. select.id = "options-view-" + key + "-select"
  687. unitChoices[val.type].forEach(name => {
  688. const option = document.createElement("option");
  689. option.innerText = name;
  690. select.appendChild(option);
  691. });
  692. input.addEventListener("change", e => {
  693. const value = input.value == 0 ? 1 : input.value;
  694. entity.views[view][key] = math.unit(value, select.value);
  695. entity.dirty = true;
  696. if (config.autoFit) {
  697. fitWorld();
  698. } else {
  699. updateSizes(true);
  700. }
  701. updateEntityOptions(entity, view);
  702. updateViewOptions(entity, view, key);
  703. });
  704. input.addEventListener("keydown", e => {
  705. e.stopPropagation();
  706. })
  707. select.setAttribute("oldUnit", select.value);
  708. setNumericInput(input, entity.views[view][key].toNumber(select.value));
  709. // TODO does this ever cause a change in the world?
  710. select.addEventListener("input", e => {
  711. const value = input.value == 0 ? 1 : input.value;
  712. const oldUnit = select.getAttribute("oldUnit");
  713. entity.views[entity.view][key] = math.unit(value, oldUnit).to(select.value);
  714. entity.dirty = true;
  715. setNumericInput(input, entity.views[entity.view][key].toNumber(select.value));
  716. select.setAttribute("oldUnit", select.value);
  717. if (config.autoFit) {
  718. fitWorld();
  719. } else {
  720. updateSizes(true);
  721. }
  722. updateEntityOptions(entity, view);
  723. updateViewOptions(entity, view, key);
  724. });
  725. row.appendChild(input);
  726. row.appendChild(select);
  727. });
  728. }
  729. function updateViewOptions(entity, view, changed) {
  730. Object.entries(entity.views[view].attributes).forEach(([key, val]) => {
  731. if (key != changed) {
  732. const input = document.querySelector("#options-view-" + key + "-input");
  733. const select = document.querySelector("#options-view-" + key + "-select");
  734. const currentUnit = select.value;
  735. const convertedAmount = entity.views[view][key].toNumber(currentUnit);
  736. setNumericInput(input, convertedAmount);
  737. }
  738. });
  739. }
  740. function setNumericInput(input, value, round = 6) {
  741. if (typeof value == "string") {
  742. value = parseFloat(value)
  743. }
  744. input.value = value.toPrecision(round);
  745. }
  746. function getSortedEntities() {
  747. return Object.keys(entities).sort((a, b) => {
  748. const entA = entities[a];
  749. const entB = entities[b];
  750. const viewA = entA.view;
  751. const viewB = entB.view;
  752. const heightA = entA.views[viewA].height.to("meter").value;
  753. const heightB = entB.views[viewB].height.to("meter").value;
  754. return heightA - heightB;
  755. });
  756. }
  757. function clearViewOptions() {
  758. document.querySelector("#view-category-header").style.display = "none";
  759. document.querySelector("#view-category").style.display = "none";
  760. }
  761. // this is a crime against humanity, and also stolen from
  762. // stack overflow
  763. // https://stackoverflow.com/questions/38487569/click-through-png-image-only-if-clicked-coordinate-is-transparent
  764. const testCanvas = document.createElement("canvas");
  765. testCanvas.id = "test-canvas";
  766. const testCtx = testCanvas.getContext("2d");
  767. function testClick(event) {
  768. // oh my god I can't believe I'm doing this
  769. const target = event.target;
  770. if (navigator.userAgent.indexOf("Firefox") != -1) {
  771. clickDown(target.parentElement, event.clientX, event.clientY);
  772. return;
  773. }
  774. // Get click coordinates
  775. let w = target.width;
  776. let h = target.height;
  777. let ratioW = 1, ratioH = 1;
  778. // Limit the size of the canvas so that very large images don't cause problems)
  779. if (w > 1000) {
  780. ratioW = w / 1000;
  781. w /= ratioW;
  782. h /= ratioW;
  783. }
  784. if (h > 1000) {
  785. ratioH = h / 1000;
  786. w /= ratioH;
  787. h /= ratioH;
  788. }
  789. const ratio = ratioW * ratioH;
  790. var x = event.clientX - target.getBoundingClientRect().x,
  791. y = event.clientY - target.getBoundingClientRect().y,
  792. alpha;
  793. testCtx.canvas.width = w;
  794. testCtx.canvas.height = h;
  795. // Draw image to canvas
  796. // and read Alpha channel value
  797. testCtx.drawImage(target, 0, 0, w, h);
  798. alpha = testCtx.getImageData(Math.floor(x / ratio), Math.floor(y / ratio), 1, 1).data[3]; // [0]R [1]G [2]B [3]A
  799. // If pixel is transparent,
  800. // retrieve the element underneath and trigger its click event
  801. if (alpha === 0) {
  802. const oldDisplay = target.style.display;
  803. target.style.display = "none";
  804. const newTarget = document.elementFromPoint(event.clientX, event.clientY);
  805. newTarget.dispatchEvent(new MouseEvent(event.type, {
  806. "clientX": event.clientX,
  807. "clientY": event.clientY
  808. }));
  809. target.style.display = oldDisplay;
  810. } else {
  811. clickDown(target.parentElement, event.clientX, event.clientY);
  812. }
  813. }
  814. function arrangeEntities(order) {
  815. let x = 0.1;
  816. order.forEach(key => {
  817. document.querySelector("#entity-" + key).dataset.x = x;
  818. x += 0.8 / (order.length - 1);
  819. });
  820. updateSizes();
  821. }
  822. function removeAllEntities() {
  823. Object.keys(entities).forEach(key => {
  824. removeEntity(document.querySelector("#entity-" + key));
  825. });
  826. }
  827. function clearAttribution() {
  828. document.querySelector("#attribution-category-header").style.display = "none";
  829. document.querySelector("#options-attribution").style.display = "none";
  830. }
  831. function displayAttribution(file) {
  832. document.querySelector("#attribution-category-header").style.display = "block";
  833. document.querySelector("#options-attribution").style.display = "inline";
  834. const authors = authorsOfFull(file);
  835. const owners = ownersOfFull(file);
  836. const source = sourceOf(file);
  837. const authorHolder = document.querySelector("#options-attribution-authors");
  838. const ownerHolder = document.querySelector("#options-attribution-owners");
  839. const sourceHolder = document.querySelector("#options-attribution-source");
  840. if (authors === []) {
  841. const div = document.createElement("div");
  842. div.innerText = "Unknown";
  843. authorHolder.innerHTML = "";
  844. authorHolder.appendChild(div);
  845. } else if (authors === undefined) {
  846. const div = document.createElement("div");
  847. div.innerText = "Not yet entered";
  848. authorHolder.innerHTML = "";
  849. authorHolder.appendChild(div);
  850. } else {
  851. authorHolder.innerHTML = "";
  852. const list = document.createElement("ul");
  853. authorHolder.appendChild(list);
  854. authors.forEach(author => {
  855. const authorEntry = document.createElement("li");
  856. if (author.url) {
  857. const link = document.createElement("a");
  858. link.href = author.url;
  859. link.innerText = author.name;
  860. authorEntry.appendChild(link);
  861. } else {
  862. const div = document.createElement("div");
  863. div.innerText = author.name;
  864. authorEntry.appendChild(div);
  865. }
  866. list.appendChild(authorEntry);
  867. });
  868. }
  869. if (owners === []) {
  870. const div = document.createElement("div");
  871. div.innerText = "Unknown";
  872. ownerHolder.innerHTML = "";
  873. ownerHolder.appendChild(div);
  874. } else if (owners === undefined) {
  875. const div = document.createElement("div");
  876. div.innerText = "Not yet entered";
  877. ownerHolder.innerHTML = "";
  878. ownerHolder.appendChild(div);
  879. } else {
  880. ownerHolder.innerHTML = "";
  881. const list = document.createElement("ul");
  882. ownerHolder.appendChild(list);
  883. owners.forEach(owner => {
  884. const ownerEntry = document.createElement("li");
  885. if (owner.url) {
  886. const link = document.createElement("a");
  887. link.href = owner.url;
  888. link.innerText = owner.name;
  889. ownerEntry.appendChild(link);
  890. } else {
  891. const div = document.createElement("div");
  892. div.innerText = owner.name;
  893. ownerEntry.appendChild(div);
  894. }
  895. list.appendChild(ownerEntry);
  896. });
  897. }
  898. if (source === null) {
  899. const div = document.createElement("div");
  900. div.innerText = "No link";
  901. sourceHolder.innerHTML = "";
  902. sourceHolder.appendChild(div);
  903. } else if (source === undefined) {
  904. const div = document.createElement("div");
  905. div.innerText = "Not yet entered";
  906. sourceHolder.innerHTML = "";
  907. sourceHolder.appendChild(div);
  908. } else {
  909. sourceHolder.innerHTML = "";
  910. const link = document.createElement("a");
  911. link.style.display = "block";
  912. link.href = source;
  913. link.innerText = new URL(source).host;
  914. sourceHolder.appendChild(link);
  915. }
  916. }
  917. function removeEntity(element) {
  918. if (selected == element) {
  919. deselect();
  920. }
  921. const option = document.querySelector("#options-selected-entity-" + element.dataset.key);
  922. option.parentElement.removeChild(option);
  923. delete entities[element.dataset.key];
  924. const bottomName = document.querySelector("#bottom-name-" + element.dataset.key);
  925. const topName = document.querySelector("#top-name-" + element.dataset.key);
  926. bottomName.parentElement.removeChild(bottomName);
  927. topName.parentElement.removeChild(topName);
  928. element.parentElement.removeChild(element);
  929. }
  930. function checkEntity(entity) {
  931. Object.values(entity.views).forEach(view => {
  932. if (authorsOf(view.image.source) === undefined) {
  933. console.warn("No authors: " + view.image.source);
  934. }
  935. });
  936. }
  937. function displayEntity(entity, view, x, y, selectEntity = false, refresh = false) {
  938. checkEntity(entity);
  939. const box = document.createElement("div");
  940. box.classList.add("entity-box");
  941. const img = document.createElement("img");
  942. img.classList.add("entity-image");
  943. img.addEventListener("dragstart", e => {
  944. e.preventDefault();
  945. });
  946. const nameTag = document.createElement("div");
  947. nameTag.classList.add("entity-name");
  948. nameTag.innerText = entity.name;
  949. box.appendChild(img);
  950. box.appendChild(nameTag);
  951. const image = entity.views[view].image;
  952. img.src = image.source;
  953. if (image.bottom !== undefined) {
  954. img.style.setProperty("--offset", ((-1 + image.bottom) * 100) + "%")
  955. } else {
  956. img.style.setProperty("--offset", ((-1) * 100) + "%")
  957. }
  958. box.dataset.x = x;
  959. box.dataset.y = y;
  960. img.addEventListener("mousedown", e => { testClick(e); e.stopPropagation() });
  961. img.addEventListener("touchstart", e => {
  962. const fakeEvent = {
  963. target: e.target,
  964. clientX: e.touches[0].clientX,
  965. clientY: e.touches[0].clientY
  966. };
  967. testClick(fakeEvent);
  968. });
  969. const heightBar = document.createElement("div");
  970. heightBar.classList.add("height-bar");
  971. box.appendChild(heightBar);
  972. box.id = "entity-" + entityIndex;
  973. box.dataset.key = entityIndex;
  974. entity.view = view;
  975. entity.priority = 0;
  976. entities[entityIndex] = entity;
  977. entity.index = entityIndex;
  978. const world = document.querySelector("#entities");
  979. world.appendChild(box);
  980. const bottomName = document.createElement("div");
  981. bottomName.classList.add("bottom-name");
  982. bottomName.id = "bottom-name-" + entityIndex;
  983. bottomName.innerText = entity.name;
  984. bottomName.addEventListener("click", () => select(box));
  985. world.appendChild(bottomName);
  986. const topName = document.createElement("div");
  987. topName.classList.add("top-name");
  988. topName.id = "top-name-" + entityIndex;
  989. topName.innerText = entity.name;
  990. topName.addEventListener("click", () => select(box));
  991. world.appendChild(topName);
  992. const entityOption = document.createElement("option");
  993. entityOption.id = "options-selected-entity-" + entityIndex;
  994. entityOption.value = entityIndex;
  995. entityOption.innerText = entity.name;
  996. document.getElementById("options-selected-entity").appendChild(entityOption);
  997. entityIndex += 1;
  998. if (config.autoFit) {
  999. fitWorld();
  1000. }
  1001. if (selectEntity)
  1002. select(box);
  1003. entity.dirty = true;
  1004. if (refresh && config.autoFitAdd) {
  1005. const x = parseFloat(selected.dataset.x);
  1006. Object.keys(entities).forEach(id => {
  1007. const element = document.querySelector("#entity-" + id);
  1008. const newX = parseFloat(element.dataset.x) - x + 0.5;
  1009. element.dataset.x = newX;
  1010. });
  1011. const entity = entities[selected.dataset.key];
  1012. const height = math.multiply(entity.views[entity.view].height, 1.1);
  1013. setWorldHeight(config.height, height);
  1014. }
  1015. if (refresh)
  1016. updateSizes(true);
  1017. }
  1018. window.onblur = function () {
  1019. altHeld = false;
  1020. shiftHeld = false;
  1021. }
  1022. window.onfocus = function () {
  1023. window.dispatchEvent(new Event("keydown"));
  1024. }
  1025. // thanks to https://developers.google.com/web/fundamentals/native-hardware/fullscreen
  1026. function toggleFullScreen() {
  1027. var doc = window.document;
  1028. var docEl = doc.documentElement;
  1029. var requestFullScreen = docEl.requestFullscreen || docEl.mozRequestFullScreen || docEl.webkitRequestFullScreen || docEl.msRequestFullscreen;
  1030. var cancelFullScreen = doc.exitFullscreen || doc.mozCancelFullScreen || doc.webkitExitFullscreen || doc.msExitFullscreen;
  1031. if (!doc.fullscreenElement && !doc.mozFullScreenElement && !doc.webkitFullscreenElement && !doc.msFullscreenElement) {
  1032. requestFullScreen.call(docEl);
  1033. }
  1034. else {
  1035. cancelFullScreen.call(doc);
  1036. }
  1037. }
  1038. function handleResize() {
  1039. const oldCanvasWidth = canvasWidth;
  1040. entityX = document.querySelector("#entities").getBoundingClientRect().x;
  1041. canvasWidth = document.querySelector("#display").clientWidth - 100;
  1042. canvasHeight = document.querySelector("#display").clientHeight - 50;
  1043. const change = oldCanvasWidth / canvasWidth;
  1044. doHorizReposition(change);
  1045. updateSizes();
  1046. }
  1047. function doHorizReposition(change) {
  1048. Object.keys(entities).forEach(key => {
  1049. const element = document.querySelector("#entity-" + key);
  1050. const x = element.dataset.x;
  1051. element.dataset.x = (x - 0.5) * change + 0.5;
  1052. });
  1053. }
  1054. function prepareSidebar() {
  1055. const menubar = document.querySelector("#sidebar-menu");
  1056. [
  1057. {
  1058. name: "Show/hide sidebar",
  1059. id: "menu-toggle-sidebar",
  1060. icon: "fas fa-chevron-circle-down",
  1061. rotates: true
  1062. },
  1063. {
  1064. name: "Fullscreen",
  1065. id: "menu-fullscreen",
  1066. icon: "fas fa-compress"
  1067. },
  1068. {
  1069. name: "Clear",
  1070. id: "menu-clear",
  1071. icon: "fas fa-file"
  1072. },
  1073. {
  1074. name: "Sort by height",
  1075. id: "menu-order-height",
  1076. icon: "fas fa-sort-numeric-up"
  1077. },
  1078. {
  1079. name: "Permalink",
  1080. id: "menu-permalink",
  1081. icon: "fas fa-link"
  1082. },
  1083. {
  1084. name: "Export to clipboard",
  1085. id: "menu-export",
  1086. icon: "fas fa-share"
  1087. },
  1088. {
  1089. name: "Import from clipboard",
  1090. id: "menu-import",
  1091. icon: "fas fa-share",
  1092. classes: ["flipped"]
  1093. },
  1094. {
  1095. name: "Save",
  1096. id: "menu-save",
  1097. icon: "fas fa-download"
  1098. },
  1099. {
  1100. name: "Load",
  1101. id: "menu-load",
  1102. icon: "fas fa-upload"
  1103. },
  1104. {
  1105. name: "Load Autosave",
  1106. id: "menu-load-autosave",
  1107. icon: "fas fa-redo"
  1108. },
  1109. {
  1110. name: "Add Image",
  1111. id: "menu-add-image",
  1112. icon: "fas fa-camera"
  1113. }
  1114. ].forEach(entry => {
  1115. const buttonHolder = document.createElement("div");
  1116. buttonHolder.classList.add("menu-button-holder");
  1117. const button = document.createElement("button");
  1118. button.id = entry.id;
  1119. button.classList.add("menu-button");
  1120. const icon = document.createElement("i");
  1121. icon.classList.add(...entry.icon.split(" "));
  1122. if (entry.rotates) {
  1123. icon.classList.add("rotate-backward", "transitions");
  1124. }
  1125. if (entry.classes) {
  1126. entry.classes.forEach(cls => icon.classList.add(cls));
  1127. }
  1128. const actionText = document.createElement("span");
  1129. actionText.innerText = entry.name;
  1130. actionText.classList.add("menu-text");
  1131. const srText = document.createElement("span");
  1132. srText.classList.add("sr-only");
  1133. srText.innerText = entry.name;
  1134. button.appendChild(icon);
  1135. button.appendChild(srText);
  1136. buttonHolder.appendChild(button);
  1137. buttonHolder.appendChild(actionText);
  1138. menubar.appendChild(buttonHolder);
  1139. });
  1140. }
  1141. function checkBodyClass(cls) {
  1142. return document.body.classList.contains(cls);
  1143. }
  1144. function toggleBodyClass(cls, setting) {
  1145. if (setting) {
  1146. document.body.classList.add(cls);
  1147. } else {
  1148. document.body.classList.remove(cls);
  1149. }
  1150. }
  1151. const settingsData = {
  1152. "auto-scale": {
  1153. name: "Auto-Size World",
  1154. desc: "Constantly zoom to fit the largest entity",
  1155. type: "toggle",
  1156. default: false,
  1157. get value() {
  1158. return config.autoFit;
  1159. },
  1160. set value(param) {
  1161. config.autoFit = param;
  1162. checkFitWorld();
  1163. }
  1164. },
  1165. "zoom-when-adding": {
  1166. name: "Zoom When Adding",
  1167. desc: "Zoom to fit when you add a new entity",
  1168. type: "toggle",
  1169. default: true,
  1170. get value() {
  1171. return config.autoFitAdd;
  1172. },
  1173. set value(param) {
  1174. config.autoFitAdd = param;
  1175. }
  1176. },
  1177. "zoom-when-sizing": {
  1178. name: "Zoom When Sizing",
  1179. desc: "Zoom to fit when you select an entity's size",
  1180. type: "toggle",
  1181. default: true,
  1182. get value() {
  1183. return config.autoFitSize;
  1184. },
  1185. set value(param) {
  1186. config.autoFitSize = param;
  1187. }
  1188. },
  1189. "names": {
  1190. name: "Show Names",
  1191. desc: "Display names over entities",
  1192. type: "toggle",
  1193. default: true,
  1194. get value() {
  1195. return checkBodyClass("toggle-entity-name");
  1196. },
  1197. set value(param) {
  1198. toggleBodyClass("toggle-entity-name", param);
  1199. }
  1200. },
  1201. "bottom-names": {
  1202. name: "Bottom Names",
  1203. desc: "Display names at the bottom",
  1204. type: "toggle",
  1205. default: false,
  1206. get value() {
  1207. return checkBodyClass("toggle-bottom-name");
  1208. },
  1209. set value(param) {
  1210. toggleBodyClass("toggle-bottom-name", param);
  1211. }
  1212. },
  1213. "top-names": {
  1214. name: "Show Arrows",
  1215. desc: "Point to entities that are much larger than the current view",
  1216. type: "toggle",
  1217. default: false,
  1218. get value() {
  1219. return checkBodyClass("toggle-top-name");
  1220. },
  1221. set value(param) {
  1222. toggleBodyClass("toggle-top-name", param);
  1223. }
  1224. },
  1225. "height-bars": {
  1226. name: "Height Bars",
  1227. desc: "Draw dashed lines to the top of each entity",
  1228. type: "toggle",
  1229. default: false,
  1230. get value() {
  1231. return checkBodyClass("toggle-height-bars");
  1232. },
  1233. set value(param) {
  1234. toggleBodyClass("toggle-height-bars", param);
  1235. }
  1236. },
  1237. "glowing-entities": {
  1238. name: "Glowing Edges",
  1239. desc: "Makes all entities glow",
  1240. type: "toggle",
  1241. default: false,
  1242. get value() {
  1243. return checkBodyClass("toggle-entity-glow");
  1244. },
  1245. set value(param) {
  1246. toggleBodyClass("toggle-entity-glow", param);
  1247. }
  1248. },
  1249. "solid-ground": {
  1250. name: "Solid Ground",
  1251. desc: "Draw solid ground at the y=0 line",
  1252. type: "toggle",
  1253. default: false,
  1254. get value() {
  1255. return checkBodyClass("toggle-bottom-cover");
  1256. },
  1257. set value(param) {
  1258. toggleBodyClass("toggle-bottom-cover", param);
  1259. }
  1260. },
  1261. "show-scale": {
  1262. name: "Show Scale",
  1263. desc: "Show the scale",
  1264. type: "toggle",
  1265. default: true,
  1266. get value() {
  1267. return checkBodyClass("toggle-scale");
  1268. },
  1269. set value(param) {
  1270. toggleBodyClass("toggle-scale", param);
  1271. }
  1272. },
  1273. }
  1274. function prepareSettings(userSettings) {
  1275. const menubar = document.querySelector("#settings-menu");
  1276. Object.entries(settingsData).forEach(([id, entry]) => {
  1277. const holder = document.createElement("label");
  1278. holder.classList.add("settings-holder");
  1279. const input = document.createElement("input");
  1280. input.id = "setting-" + id;
  1281. const name = document.createElement("label");
  1282. name.innerText = entry.name;
  1283. name.classList.add("settings-name");
  1284. name.setAttribute("for", input.id);
  1285. const desc = document.createElement("label");
  1286. desc.innerText = entry.desc;
  1287. desc.classList.add("settings-desc");
  1288. desc.setAttribute("for", input.id);
  1289. if (entry.type == "toggle") {
  1290. input.type = "checkbox";
  1291. input.checked = userSettings[id] === undefined ? entry.default : userSettings[id];
  1292. holder.setAttribute("for", input.id);
  1293. input.appendChild(name);
  1294. input.appendChild(desc);
  1295. holder.appendChild(input);
  1296. holder.appendChild(name);
  1297. holder.appendChild(desc);
  1298. menubar.appendChild(holder);
  1299. const update = () => {
  1300. if (input.checked) {
  1301. holder.classList.add("enabled");
  1302. holder.classList.remove("disabled");
  1303. } else {
  1304. holder.classList.remove("enabled");
  1305. holder.classList.add("disabled");
  1306. }
  1307. entry.value = input.checked;
  1308. }
  1309. update();
  1310. input.addEventListener("change", update);
  1311. }
  1312. })
  1313. }
  1314. function prepareMenu() {
  1315. prepareSidebar();
  1316. if (checkHelpDate()) {
  1317. document.querySelector("#open-help").classList.add("highlighted");
  1318. }
  1319. }
  1320. function getUserSettings() {
  1321. try {
  1322. const settings = JSON.parse(localStorage.getItem("settings"));
  1323. return settings === null ? {} : settings;
  1324. } catch {
  1325. return {};
  1326. }
  1327. }
  1328. function exportUserSettings() {
  1329. const settings = {};
  1330. Object.entries(settingsData).forEach(([id, entry]) => {
  1331. settings[id] = entry.value;
  1332. });
  1333. return settings;
  1334. }
  1335. function setUserSettings(settings) {
  1336. try {
  1337. localStorage.setItem("settings", JSON.stringify(settings));
  1338. } catch {
  1339. // :(
  1340. }
  1341. }
  1342. const lastHelpChange = 1587847743294;
  1343. function checkHelpDate() {
  1344. try {
  1345. const old = localStorage.getItem("help-viewed");
  1346. if (old === null || old < lastHelpChange) {
  1347. return true;
  1348. }
  1349. return false;
  1350. } catch {
  1351. console.warn("Could not set the help-viewed date");
  1352. return false;
  1353. }
  1354. }
  1355. function setHelpDate() {
  1356. try {
  1357. localStorage.setItem("help-viewed", Date.now());
  1358. } catch {
  1359. console.warn("Could not set the help-viewed date");
  1360. }
  1361. }
  1362. function doScroll() {
  1363. document.querySelectorAll(".entity-box").forEach(element => {
  1364. element.dataset.x = parseFloat(element.dataset.x) + scrollDirection / 180;
  1365. });
  1366. updateSizes();
  1367. scrollDirection *= 1.05;
  1368. }
  1369. function doZoom() {
  1370. const oldHeight = config.height;
  1371. setWorldHeight(oldHeight, math.multiply(oldHeight, 1 + zoomDirection / 10));
  1372. zoomDirection *= 1.05;
  1373. }
  1374. function doSize() {
  1375. if (selected) {
  1376. const entity = entities[selected.dataset.key];
  1377. const oldHeight = entity.views[entity.view].height;
  1378. entity.views[entity.view].height = math.multiply(oldHeight, 1 + sizeDirection / 20);
  1379. entity.dirty = true;
  1380. updateEntityOptions(entity, entity.view);
  1381. updateViewOptions(entity, entity.view);
  1382. updateSizes(true);
  1383. sizeDirection *= 1.05;
  1384. const ownHeight = entity.views[entity.view].height.toNumber("meters");
  1385. const worldHeight = config.height.toNumber("meters");
  1386. if (ownHeight > worldHeight) {
  1387. setWorldHeight(config.height, entity.views[entity.view].height)
  1388. } else if (ownHeight * 10 < worldHeight) {
  1389. setWorldHeight(config.height, math.multiply(entity.views[entity.view].height, 10));
  1390. }
  1391. }
  1392. }
  1393. function prepareHelp() {
  1394. const toc = document.querySelector("#table-of-contents");
  1395. const holder = document.querySelector("#help-contents-holder");
  1396. document.querySelectorAll("#help-contents h2").forEach(header => {
  1397. const li = document.createElement("li");
  1398. li.innerText = header.textContent;
  1399. li.addEventListener("click", e => {
  1400. holder.scrollTop = header.offsetTop;
  1401. });
  1402. toc.appendChild(li);
  1403. });
  1404. }
  1405. document.addEventListener("DOMContentLoaded", () => {
  1406. prepareMenu();
  1407. prepareEntities();
  1408. prepareHelp();
  1409. document.querySelector("#open-help").addEventListener("click", e => {
  1410. setHelpDate();
  1411. document.querySelector("#help-menu").classList.add("visible");
  1412. document.querySelector("#open-help").classList.remove("highlighted");
  1413. });
  1414. document.querySelector("#close-help").addEventListener("click", e => {
  1415. document.querySelector("#help-menu").classList.remove("visible");
  1416. });
  1417. document.querySelector("#copy-screenshot").addEventListener("click", e => {
  1418. copyScreenshot();
  1419. toast("Copied to clipboard!");
  1420. });
  1421. document.querySelector("#save-screenshot").addEventListener("click", e => {
  1422. saveScreenshot();
  1423. });
  1424. document.querySelector("#toggle-menu").addEventListener("click", e => {
  1425. const popoutMenu = document.querySelector("#sidebar-menu");
  1426. if (popoutMenu.classList.contains("visible")) {
  1427. popoutMenu.classList.remove("visible");
  1428. } else {
  1429. document.querySelectorAll(".popout-menu").forEach(menu => menu.classList.remove("visible"));
  1430. const rect = e.target.getBoundingClientRect();
  1431. popoutMenu.classList.add("visible");
  1432. popoutMenu.style.left = rect.x + rect.width + 10 + "px";
  1433. popoutMenu.style.top = rect.y + rect.height + 10 + "px";
  1434. }
  1435. e.stopPropagation();
  1436. });
  1437. document.querySelector("#sidebar-menu").addEventListener("click", e => {
  1438. e.stopPropagation();
  1439. });
  1440. document.addEventListener("click", e => {
  1441. document.querySelector("#sidebar-menu").classList.remove("visible");
  1442. });
  1443. document.querySelector("#toggle-settings").addEventListener("click", e => {
  1444. const popoutMenu = document.querySelector("#settings-menu");
  1445. if (popoutMenu.classList.contains("visible")) {
  1446. popoutMenu.classList.remove("visible");
  1447. } else {
  1448. document.querySelectorAll(".popout-menu").forEach(menu => menu.classList.remove("visible"));
  1449. const rect = e.target.getBoundingClientRect();
  1450. popoutMenu.classList.add("visible");
  1451. popoutMenu.style.left = rect.x + rect.width + 10 + "px";
  1452. popoutMenu.style.top = rect.y + rect.height + 10 + "px";
  1453. }
  1454. e.stopPropagation();
  1455. });
  1456. document.querySelector("#settings-menu").addEventListener("click", e => {
  1457. e.stopPropagation();
  1458. });
  1459. document.addEventListener("click", e => {
  1460. document.querySelector("#settings-menu").classList.remove("visible");
  1461. });
  1462. window.addEventListener("unload", () => {
  1463. saveScene("autosave");
  1464. setUserSettings(exportUserSettings());
  1465. });
  1466. document.querySelector("#options-selected-entity").addEventListener("input", e => {
  1467. if (e.target.value == "None") {
  1468. deselect()
  1469. } else {
  1470. select(document.querySelector("#entity-" + e.target.value));
  1471. }
  1472. });
  1473. document.querySelector("#menu-toggle-sidebar").addEventListener("click", e => {
  1474. const sidebar = document.querySelector("#options");
  1475. if (sidebar.classList.contains("hidden")) {
  1476. sidebar.classList.remove("hidden");
  1477. e.target.classList.remove("rotate-forward");
  1478. e.target.classList.add("rotate-backward");
  1479. } else {
  1480. sidebar.classList.add("hidden");
  1481. e.target.classList.add("rotate-forward");
  1482. e.target.classList.remove("rotate-backward");
  1483. }
  1484. handleResize();
  1485. });
  1486. document.querySelector("#menu-fullscreen").addEventListener("click", toggleFullScreen);
  1487. document.querySelector("#options-order-forward").addEventListener("click", e => {
  1488. if (selected) {
  1489. entities[selected.dataset.key].priority += 1;
  1490. }
  1491. document.querySelector("#options-order-display").innerText = entities[selected.dataset.key].priority;
  1492. updateSizes();
  1493. });
  1494. document.querySelector("#options-order-back").addEventListener("click", e => {
  1495. if (selected) {
  1496. entities[selected.dataset.key].priority -= 1;
  1497. }
  1498. document.querySelector("#options-order-display").innerText = entities[selected.dataset.key].priority;
  1499. updateSizes();
  1500. });
  1501. const sceneChoices = document.querySelector("#scene-choices");
  1502. Object.entries(scenes).forEach(([id, scene]) => {
  1503. const option = document.createElement("option");
  1504. option.innerText = id;
  1505. option.value = id;
  1506. sceneChoices.appendChild(option);
  1507. });
  1508. document.querySelector("#load-scene").addEventListener("click", e => {
  1509. const chosen = sceneChoices.value;
  1510. removeAllEntities();
  1511. scenes[chosen]();
  1512. });
  1513. entityX = document.querySelector("#entities").getBoundingClientRect().x;
  1514. canvasWidth = document.querySelector("#display").clientWidth - 100;
  1515. canvasHeight = document.querySelector("#display").clientHeight - 50;
  1516. document.querySelector("#options-height-value").addEventListener("change", e => {
  1517. updateWorldHeight();
  1518. })
  1519. document.querySelector("#options-height-value").addEventListener("keydown", e => {
  1520. e.stopPropagation();
  1521. })
  1522. const unitSelector = document.querySelector("#options-height-unit");
  1523. unitChoices.length.forEach(lengthOption => {
  1524. const option = document.createElement("option");
  1525. option.innerText = lengthOption;
  1526. option.value = lengthOption;
  1527. if (lengthOption === "meters") {
  1528. option.selected = true;
  1529. }
  1530. unitSelector.appendChild(option);
  1531. });
  1532. unitSelector.setAttribute("oldUnit", "meters");
  1533. unitSelector.addEventListener("input", e => {
  1534. checkFitWorld();
  1535. const scaleInput = document.querySelector("#options-height-value");
  1536. const newVal = math.unit(scaleInput.value, unitSelector.getAttribute("oldUnit")).toNumber(e.target.value);
  1537. setNumericInput(scaleInput, newVal);
  1538. updateWorldHeight();
  1539. unitSelector.setAttribute("oldUnit", unitSelector.value);
  1540. });
  1541. param = new URL(window.location.href).searchParams.get("scene");
  1542. if (param === null) {
  1543. scenes["Default"]();
  1544. }
  1545. else {
  1546. try {
  1547. const data = JSON.parse(b64DecodeUnicode(param));
  1548. if (data.entities === undefined) {
  1549. return;
  1550. }
  1551. if (data.world === undefined) {
  1552. return;
  1553. }
  1554. importScene(data);
  1555. } catch (err) {
  1556. console.error(err);
  1557. scenes["Default"]();
  1558. // probably wasn't valid data
  1559. }
  1560. }
  1561. document.querySelector("#world").addEventListener("wheel", e => {
  1562. if (shiftHeld) {
  1563. if (selected) {
  1564. const dir = e.deltaY > 0 ? 10 / 11 : 11 / 10;
  1565. const entity = entities[selected.dataset.key];
  1566. entity.views[entity.view].height = math.multiply(entity.views[entity.view].height, dir);
  1567. entity.dirty = true;
  1568. updateEntityOptions(entity, entity.view);
  1569. updateViewOptions(entity, entity.view);
  1570. updateSizes(true);
  1571. } else {
  1572. document.querySelectorAll(".entity-box").forEach(element => {
  1573. element.dataset.x = parseFloat(element.dataset.x) + (e.deltaY < 0 ? 0.1 : -0.1);
  1574. });
  1575. updateSizes();
  1576. }
  1577. } else {
  1578. if (config.autoFit) {
  1579. toastRateLimit("Zoom is locked! Check Settings to disable.", "zoom-lock", 1000);
  1580. } else {
  1581. const dir = e.deltaY < 0 ? 10 / 11 : 11 / 10;
  1582. setWorldHeight(config.height, math.multiply(config.height, dir));
  1583. updateWorldOptions();
  1584. }
  1585. }
  1586. checkFitWorld();
  1587. })
  1588. document.querySelector("body").appendChild(testCtx.canvas);
  1589. updateSizes();
  1590. world.addEventListener("mousedown", e => deselect());
  1591. document.querySelector("#entities").addEventListener("mousedown", deselect);
  1592. document.querySelector("#display").addEventListener("mousedown", deselect);
  1593. document.addEventListener("mouseup", e => clickUp(e));
  1594. document.addEventListener("touchend", e => {
  1595. const fakeEvent = {
  1596. target: e.target,
  1597. clientX: e.changedTouches[0].clientX,
  1598. clientY: e.changedTouches[0].clientY
  1599. };
  1600. clickUp(fakeEvent);
  1601. });
  1602. const viewList = document.querySelector("#entity-view");
  1603. document.querySelector("#entity-view").addEventListener("input", e => {
  1604. const entity = entities[selected.dataset.key];
  1605. entity.view = e.target.value;
  1606. const image = entities[selected.dataset.key].views[e.target.value].image;
  1607. selected.querySelector(".entity-image").src = image.source;
  1608. configViewOptions(entity, entity.view);
  1609. displayAttribution(image.source);
  1610. if (image.bottom !== undefined) {
  1611. selected.querySelector(".entity-image").style.setProperty("--offset", ((-1 + image.bottom) * 100) + "%")
  1612. } else {
  1613. selected.querySelector(".entity-image").style.setProperty("--offset", ((-1) * 100) + "%")
  1614. }
  1615. updateSizes();
  1616. updateEntityOptions(entities[selected.dataset.key], e.target.value);
  1617. updateViewOptions(entities[selected.dataset.key], e.target.value);
  1618. });
  1619. document.querySelector("#entity-view").addEventListener("input", e => {
  1620. if (viewList.options[viewList.selectedIndex].classList.contains("nsfw")) {
  1621. viewList.classList.add("nsfw");
  1622. } else {
  1623. viewList.classList.remove("nsfw");
  1624. }
  1625. })
  1626. clearViewList();
  1627. document.querySelector("#menu-clear").addEventListener("click", e => {
  1628. removeAllEntities();
  1629. });
  1630. document.querySelector("#delete-entity").disabled = true;
  1631. document.querySelector("#delete-entity").addEventListener("click", e => {
  1632. if (selected) {
  1633. removeEntity(selected);
  1634. selected = null;
  1635. }
  1636. });
  1637. document.querySelector("#menu-order-height").addEventListener("click", e => {
  1638. const order = Object.keys(entities).sort((a, b) => {
  1639. const entA = entities[a];
  1640. const entB = entities[b];
  1641. const viewA = entA.view;
  1642. const viewB = entB.view;
  1643. const heightA = entA.views[viewA].height.to("meter").value;
  1644. const heightB = entB.views[viewB].height.to("meter").value;
  1645. return heightA - heightB;
  1646. });
  1647. arrangeEntities(order);
  1648. });
  1649. // TODO: write some generic logic for this lol
  1650. document.querySelector("#scroll-left").addEventListener("mousedown", e => {
  1651. scrollDirection = 1;
  1652. clearInterval(scrollHandle);
  1653. scrollHandle = setInterval(doScroll, 1000 / 20);
  1654. e.stopPropagation();
  1655. });
  1656. document.querySelector("#scroll-right").addEventListener("mousedown", e => {
  1657. scrollDirection = -1;
  1658. clearInterval(scrollHandle);
  1659. scrollHandle = setInterval(doScroll, 1000 / 20);
  1660. e.stopPropagation();
  1661. });
  1662. document.querySelector("#scroll-left").addEventListener("touchstart", e => {
  1663. scrollDirection = 1;
  1664. clearInterval(scrollHandle);
  1665. scrollHandle = setInterval(doScroll, 1000 / 20);
  1666. e.stopPropagation();
  1667. });
  1668. document.querySelector("#scroll-right").addEventListener("touchstart", e => {
  1669. scrollDirection = -1;
  1670. clearInterval(scrollHandle);
  1671. scrollHandle = setInterval(doScroll, 1000 / 20);
  1672. e.stopPropagation();
  1673. });
  1674. document.addEventListener("mouseup", e => {
  1675. clearInterval(scrollHandle);
  1676. scrollHandle = null;
  1677. });
  1678. document.addEventListener("touchend", e => {
  1679. clearInterval(scrollHandle);
  1680. scrollHandle = null;
  1681. });
  1682. document.querySelector("#zoom-in").addEventListener("mousedown", e => {
  1683. zoomDirection = -1;
  1684. clearInterval(zoomHandle);
  1685. zoomHandle = setInterval(doZoom, 1000 / 20);
  1686. e.stopPropagation();
  1687. });
  1688. document.querySelector("#zoom-out").addEventListener("mousedown", e => {
  1689. zoomDirection = 1;
  1690. clearInterval(zoomHandle);
  1691. zoomHandle = setInterval(doZoom, 1000 / 20);
  1692. e.stopPropagation();
  1693. });
  1694. document.querySelector("#zoom-in").addEventListener("touchstart", e => {
  1695. zoomDirection = -1;
  1696. clearInterval(zoomHandle);
  1697. zoomHandle = setInterval(doZoom, 1000 / 20);
  1698. e.stopPropagation();
  1699. });
  1700. document.querySelector("#zoom-out").addEventListener("touchstart", e => {
  1701. zoomDirection = 1;
  1702. clearInterval(zoomHandle);
  1703. zoomHandle = setInterval(doZoom, 1000 / 20);
  1704. e.stopPropagation();
  1705. });
  1706. document.addEventListener("mouseup", e => {
  1707. clearInterval(zoomHandle);
  1708. zoomHandle = null;
  1709. });
  1710. document.addEventListener("touchend", e => {
  1711. clearInterval(zoomHandle);
  1712. zoomHandle = null;
  1713. });
  1714. document.querySelector("#shrink").addEventListener("mousedown", e => {
  1715. sizeDirection = -1;
  1716. clearInterval(sizeHandle);
  1717. sizeHandle = setInterval(doSize, 1000 / 20);
  1718. e.stopPropagation();
  1719. });
  1720. document.querySelector("#grow").addEventListener("mousedown", e => {
  1721. sizeDirection = 1;
  1722. clearInterval(sizeHandle);
  1723. sizeHandle = setInterval(doSize, 1000 / 20);
  1724. e.stopPropagation();
  1725. });
  1726. document.querySelector("#shrink").addEventListener("touchstart", e => {
  1727. sizeDirection = -1;
  1728. clearInterval(sizeHandle);
  1729. sizeHandle = setInterval(doSize, 1000 / 20);
  1730. e.stopPropagation();
  1731. });
  1732. document.querySelector("#grow").addEventListener("touchstart", e => {
  1733. sizeDirection = 1;
  1734. clearInterval(sizeHandle);
  1735. sizeHandle = setInterval(doSize, 1000 / 20);
  1736. e.stopPropagation();
  1737. });
  1738. document.addEventListener("mouseup", e => {
  1739. clearInterval(sizeHandle);
  1740. sizeHandle = null;
  1741. });
  1742. document.addEventListener("touchend", e => {
  1743. clearInterval(sizeHandle);
  1744. sizeHandle = null;
  1745. });
  1746. document.querySelector("#fit").addEventListener("click", e => {
  1747. const x = parseFloat(selected.dataset.x);
  1748. Object.keys(entities).forEach(id => {
  1749. const element = document.querySelector("#entity-" + id);
  1750. const newX = parseFloat(element.dataset.x) - x + 0.5;
  1751. element.dataset.x = newX;
  1752. });
  1753. const entity = entities[selected.dataset.key];
  1754. const height = math.multiply(entity.views[entity.view].height, 1.1);
  1755. setWorldHeight(config.height, height);
  1756. });
  1757. document.querySelector("#fit").addEventListener("mousedown", e => {
  1758. e.stopPropagation();
  1759. });
  1760. document.querySelector("#fit").addEventListener("touchstart", e => {
  1761. e.stopPropagation();
  1762. });
  1763. document.querySelector("#options-world-fit").addEventListener("click", () => fitWorld(true));
  1764. document.addEventListener("keydown", e => {
  1765. if (e.key == "Delete") {
  1766. if (selected) {
  1767. removeEntity(selected);
  1768. selected = null;
  1769. }
  1770. }
  1771. })
  1772. document.addEventListener("keydown", e => {
  1773. if (e.key == "Shift") {
  1774. shiftHeld = true;
  1775. e.preventDefault();
  1776. } else if (e.key == "Alt") {
  1777. altHeld = true;
  1778. e.preventDefault();
  1779. }
  1780. });
  1781. document.addEventListener("keyup", e => {
  1782. if (e.key == "Shift") {
  1783. shiftHeld = false;
  1784. e.preventDefault();
  1785. } else if (e.key == "Alt") {
  1786. altHeld = false;
  1787. e.preventDefault();
  1788. }
  1789. });
  1790. window.addEventListener("resize", handleResize);
  1791. // TODO: further investigate why the tool initially starts out with wrong
  1792. // values under certain circumstances (seems to be narrow aspect ratios -
  1793. // maybe the menu bar is animating when it shouldn't)
  1794. setTimeout(handleResize, 250);
  1795. setTimeout(handleResize, 500);
  1796. setTimeout(handleResize, 750);
  1797. setTimeout(handleResize, 1000);
  1798. document.querySelector("#menu-permalink").addEventListener("click", e => {
  1799. linkScene();
  1800. });
  1801. document.querySelector("#menu-export").addEventListener("click", e => {
  1802. copyScene();
  1803. });
  1804. document.querySelector("#menu-import").addEventListener("click", e => {
  1805. pasteScene();
  1806. });
  1807. document.querySelector("#menu-save").addEventListener("click", e => {
  1808. saveScene();
  1809. });
  1810. document.querySelector("#menu-load").addEventListener("click", e => {
  1811. loadScene();
  1812. });
  1813. document.querySelector("#menu-load-autosave").addEventListener("click", e => {
  1814. loadScene("autosave");
  1815. });
  1816. document.querySelector("#menu-add-image").addEventListener("click", e => {
  1817. document.querySelector("#file-upload-picker").click();
  1818. });
  1819. document.querySelector("#file-upload-picker").addEventListener("change", e => {
  1820. if (e.target.files.length > 0) {
  1821. for (let i=0; i<e.target.files.length; i++) {
  1822. customEntityFromFile(e.target.files[i]);
  1823. }
  1824. }
  1825. })
  1826. document.addEventListener("paste", e => {
  1827. let index = 0;
  1828. let item = null;
  1829. let found = false;
  1830. for (; index < e.clipboardData.items.length; index++) {
  1831. item = e.clipboardData.items[index];
  1832. if (item.type == "image/png") {
  1833. found = true;
  1834. break;
  1835. }
  1836. }
  1837. if (!found) {
  1838. return;
  1839. }
  1840. let url = null;
  1841. const file = item.getAsFile();
  1842. customEntityFromFile(file);
  1843. });
  1844. document.querySelector("#world").addEventListener("dragover", e => {
  1845. e.preventDefault();
  1846. })
  1847. document.querySelector("#world").addEventListener("drop", e => {
  1848. e.preventDefault();
  1849. if (e.dataTransfer.files.length > 0) {
  1850. let entX = document.querySelector("#entities").getBoundingClientRect().x;
  1851. let entY = document.querySelector("#entities").getBoundingClientRect().y;
  1852. let coords = abs2rel({x: e.clientX-entX, y: e.clientY-entY});
  1853. customEntityFromFile(e.dataTransfer.files[0], coords.x, coords.y);
  1854. }
  1855. })
  1856. clearEntityOptions();
  1857. clearViewOptions();
  1858. clearAttribution();
  1859. // we do this last because configuring settings can cause things
  1860. // to happen (e.g. auto-fit)
  1861. prepareSettings(getUserSettings());
  1862. });
  1863. function customEntityFromFile(file, x=0.5, y=0.5) {
  1864. file.arrayBuffer().then(buf => {
  1865. arr = new Uint8Array(buf);
  1866. blob = new Blob([arr], {type: file.type });
  1867. url = window.URL.createObjectURL(blob)
  1868. makeCustomEntity(url, x, y);
  1869. });
  1870. }
  1871. function makeCustomEntity(url, x=0.5, y=0.5) {
  1872. const maker = createEntityMaker(
  1873. {
  1874. name: "Custom Entity"
  1875. },
  1876. {
  1877. custom: {
  1878. attributes: {
  1879. height: {
  1880. name: "Height",
  1881. power: 1,
  1882. type: "length",
  1883. base: math.unit(6, "feet")
  1884. }
  1885. },
  1886. image: {
  1887. source: url
  1888. },
  1889. name: "Image",
  1890. info: {},
  1891. rename: false
  1892. }
  1893. },
  1894. []
  1895. );
  1896. const entity = maker.constructor();
  1897. entity.scale = config.height.toNumber("feet") / 20;
  1898. entity.ephemeral = true;
  1899. displayEntity(entity, "custom", x, y, true, true);
  1900. }
  1901. const filterDefs = {
  1902. none: {
  1903. id: "none",
  1904. name: "No Filter",
  1905. extract: maker => [],
  1906. render: name => name
  1907. },
  1908. author: {
  1909. id: "author",
  1910. name: "Authors",
  1911. extract: maker => maker.authors ? maker.authors : [],
  1912. render: author => attributionData.people[author].name
  1913. },
  1914. owner: {
  1915. id: "owner",
  1916. name: "Owners",
  1917. extract: maker => maker.owners ? maker.owners : [],
  1918. render: owner => attributionData.people[owner].name
  1919. },
  1920. species: {
  1921. id: "species",
  1922. name: "Species",
  1923. extract: maker => maker.info && maker.info.species ? getSpeciesInfo(maker.info.species) : [],
  1924. render: species => speciesData[species].name
  1925. },
  1926. tags: {
  1927. id: "tags",
  1928. name: "Tags",
  1929. extract: maker => maker.info && maker.info.tags ? maker.info.tags : [],
  1930. render: tag => tagDefs[tag]
  1931. }
  1932. }
  1933. function prepareEntities() {
  1934. availableEntities["buildings"] = makeBuildings();
  1935. availableEntities["characters"] = makeCharacters();
  1936. availableEntities["cities"] = makeCities();
  1937. availableEntities["fiction"] = makeFiction();
  1938. availableEntities["food"] = makeFood();
  1939. availableEntities["landmarks"] = makeLandmarks();
  1940. availableEntities["naturals"] = makeNaturals();
  1941. availableEntities["objects"] = makeObjects();
  1942. availableEntities["dildos"] = makeDildos();
  1943. availableEntities["pokemon"] = makePokemon();
  1944. availableEntities["species"] = makeSpecies();
  1945. availableEntities["vehicles"] = makeVehicles();
  1946. availableEntities["characters"].sort((x, y) => {
  1947. return x.name.toLowerCase() < y.name.toLowerCase() ? -1 : 1
  1948. });
  1949. const holder = document.querySelector("#spawners");
  1950. const filterHolder = document.querySelector("#filters");
  1951. const categorySelect = document.createElement("select");
  1952. categorySelect.id = "category-picker";
  1953. const filterSelect = document.createElement("select");
  1954. filterSelect.id = "filter-picker";
  1955. holder.appendChild(categorySelect);
  1956. filterHolder.appendChild(filterSelect);
  1957. const filterSets = {};
  1958. Object.values(filterDefs).forEach(filter => {
  1959. filterSets[filter.id] = new Set();
  1960. })
  1961. Object.entries(availableEntities).forEach(([category, entityList]) => {
  1962. const select = document.createElement("select");
  1963. select.id = "create-entity-" + category;
  1964. select.classList.add("entity-select");
  1965. for (let i = 0; i < entityList.length; i++) {
  1966. const entity = entityList[i];
  1967. const option = document.createElement("option");
  1968. option.value = i;
  1969. option.innerText = entity.name;
  1970. select.appendChild(option);
  1971. if (entity.nsfw) {
  1972. option.classList.add("nsfw");
  1973. }
  1974. Object.values(filterDefs).forEach(filter => {
  1975. filter.extract(entity).forEach(result => {
  1976. filterSets[filter.id].add(result);
  1977. });
  1978. });
  1979. availableEntitiesByName[entity.name] = entity;
  1980. };
  1981. select.addEventListener("change", e => {
  1982. if (select.options[select.selectedIndex].classList.contains("nsfw")) {
  1983. select.classList.add("nsfw");
  1984. } else {
  1985. select.classList.remove("nsfw");
  1986. }
  1987. })
  1988. const button = document.createElement("button");
  1989. button.id = "create-entity-" + category + "-button";
  1990. button.classList.add("entity-button");
  1991. button.innerHTML = "<i class=\"far fa-plus-square\"></i>";
  1992. button.addEventListener("click", e => {
  1993. const newEntity = entityList[select.value].constructor()
  1994. displayEntity(newEntity, newEntity.defaultView, 0.5, 1, true, true);
  1995. });
  1996. const categoryOption = document.createElement("option");
  1997. categoryOption.value = category
  1998. categoryOption.innerText = category;
  1999. if (category == "characters") {
  2000. categoryOption.selected = true;
  2001. select.classList.add("category-visible");
  2002. button.classList.add("category-visible");
  2003. }
  2004. categorySelect.appendChild(categoryOption);
  2005. holder.appendChild(select);
  2006. holder.appendChild(button);
  2007. });
  2008. Object.values(filterDefs).forEach(filter => {
  2009. const option = document.createElement("option");
  2010. option.innerText = filter.name;
  2011. option.value = filter.id;
  2012. filterSelect.appendChild(option);
  2013. const filterNameSelect = document.createElement("select");
  2014. filterNameSelect.classList.add("filter-select");
  2015. filterNameSelect.id = "filter-" + filter.id;
  2016. filterHolder.appendChild(filterNameSelect);
  2017. Array.from(filterSets[filter.id]).map(name => [name, filter.render(name)]).sort((e1, e2) => e1[1].toLowerCase().localeCompare(e2[1].toLowerCase())).forEach(name => {
  2018. const option = document.createElement("option");
  2019. option.innerText = name[1];
  2020. option.value = name[0];
  2021. filterNameSelect.appendChild(option);
  2022. });
  2023. filterNameSelect.addEventListener("change", e => {
  2024. updateFilter();
  2025. });
  2026. });
  2027. console.log("Loaded " + Object.keys(availableEntitiesByName).length + " entities");
  2028. categorySelect.addEventListener("input", e => {
  2029. const oldSelect = document.querySelector(".entity-select.category-visible");
  2030. oldSelect.classList.remove("category-visible");
  2031. const oldButton = document.querySelector(".entity-button.category-visible");
  2032. oldButton.classList.remove("category-visible");
  2033. const newSelect = document.querySelector("#create-entity-" + e.target.value);
  2034. newSelect.classList.add("category-visible");
  2035. const newButton = document.querySelector("#create-entity-" + e.target.value + "-button");
  2036. newButton.classList.add("category-visible");
  2037. recomputeFilters();
  2038. updateFilter();
  2039. });
  2040. recomputeFilters();
  2041. filterSelect.addEventListener("input", e => {
  2042. const oldSelect = document.querySelector(".filter-select.category-visible");
  2043. if (oldSelect)
  2044. oldSelect.classList.remove("category-visible");
  2045. const newSelect = document.querySelector("#filter-" + e.target.value);
  2046. if (newSelect)
  2047. newSelect.classList.add("category-visible");
  2048. updateFilter();
  2049. });
  2050. }
  2051. // Only display authors and owners if they appear
  2052. // somewhere in the current entity list
  2053. function recomputeFilters() {
  2054. const category = document.querySelector("#category-picker").value;
  2055. const filterSets = {};
  2056. Object.values(filterDefs).forEach(filter => {
  2057. filterSets[filter.id] = new Set();
  2058. });
  2059. document.querySelectorAll(".entity-select.category-visible > option").forEach(element => {
  2060. const entity = availableEntities[category][element.value];
  2061. Object.values(filterDefs).forEach(filter => {
  2062. filter.extract(entity).forEach(result => {
  2063. filterSets[filter.id].add(result);
  2064. });
  2065. });
  2066. });
  2067. Object.values(filterDefs).forEach(filter => {
  2068. // always show the "none" option
  2069. let found = filter.id == "none";
  2070. document.querySelectorAll("#filter-" + filter.id + " > option").forEach(element => {
  2071. if (filterSets[filter.id].has(element.value) || filter.id == "none") {
  2072. element.classList.remove("filtered");
  2073. found = true;
  2074. } else {
  2075. element.classList.add("filtered");
  2076. }
  2077. });
  2078. const filterOption = document.querySelector("#filter-picker > option[value='" + filter.id + "']");
  2079. if (found) {
  2080. filterOption.classList.remove("filtered");
  2081. } else {
  2082. filterOption.classList.add("filtered");
  2083. }
  2084. });
  2085. document.querySelector("#filter-picker").value = "none";
  2086. document.querySelector("#filter-picker").dispatchEvent(new Event("input"));
  2087. }
  2088. function updateFilter() {
  2089. const category = document.querySelector("#category-picker").value;
  2090. const type = document.querySelector("#filter-picker").value;
  2091. const filterKeySelect = document.querySelector(".filter-select.category-visible");
  2092. clearFilter();
  2093. if (!filterKeySelect) {
  2094. return;
  2095. }
  2096. const key = filterKeySelect.value;
  2097. let current = document.querySelector(".entity-select.category-visible").value;
  2098. let replace = false;
  2099. let first = null;
  2100. document.querySelectorAll(".entity-select.category-visible > option").forEach(element => {
  2101. let keep = type == "none";
  2102. if (filterDefs[type].extract(availableEntities[category][element.value]).indexOf(key) >= 0) {
  2103. keep = true;
  2104. }
  2105. if (!keep) {
  2106. element.classList.add("filtered");
  2107. if (current == element.value) {
  2108. replace = true;
  2109. }
  2110. } else if (!first) {
  2111. first = element.value;
  2112. }
  2113. });
  2114. if (replace) {
  2115. document.querySelector(".entity-select.category-visible").value = first;
  2116. document.querySelector("#create-entity-" + category).dispatchEvent(new Event("change"));
  2117. }
  2118. }
  2119. function clearFilter() {
  2120. document.querySelectorAll(".entity-select.category-visible > option").forEach(element => {
  2121. element.classList.remove("filtered");
  2122. });
  2123. }
  2124. document.addEventListener("mousemove", (e) => {
  2125. if (clicked) {
  2126. const position = snapRel(abs2rel({ x: e.clientX - dragOffsetX, y: e.clientY - dragOffsetY }));
  2127. clicked.dataset.x = position.x;
  2128. clicked.dataset.y = position.y;
  2129. updateEntityElement(entities[clicked.dataset.key], clicked);
  2130. if (hoveringInDeleteArea(e)) {
  2131. document.querySelector("#menubar").classList.add("hover-delete");
  2132. } else {
  2133. document.querySelector("#menubar").classList.remove("hover-delete");
  2134. }
  2135. }
  2136. });
  2137. document.addEventListener("touchmove", (e) => {
  2138. if (clicked) {
  2139. e.preventDefault();
  2140. let x = e.touches[0].clientX;
  2141. let y = e.touches[0].clientY;
  2142. const position = snapRel(abs2rel({ x: x - dragOffsetX, y: y - dragOffsetY }));
  2143. clicked.dataset.x = position.x;
  2144. clicked.dataset.y = position.y;
  2145. updateEntityElement(entities[clicked.dataset.key], clicked);
  2146. // what a hack
  2147. // I should centralize this 'fake event' creation...
  2148. if (hoveringInDeleteArea({ clientY: y })) {
  2149. document.querySelector("#menubar").classList.add("hover-delete");
  2150. } else {
  2151. document.querySelector("#menubar").classList.remove("hover-delete");
  2152. }
  2153. }
  2154. }, { passive: false });
  2155. function checkFitWorld() {
  2156. if (config.autoFit) {
  2157. fitWorld();
  2158. return true;
  2159. }
  2160. return false;
  2161. }
  2162. const fitModes = {
  2163. "max": {
  2164. start: 0,
  2165. binop: Math.max,
  2166. final: (total, count) => total
  2167. },
  2168. "arithmetic mean": {
  2169. start: 0,
  2170. binop: math.add,
  2171. final: (total, count) => total / count
  2172. },
  2173. "geometric mean": {
  2174. start: 1,
  2175. binop: math.multiply,
  2176. final: (total, count) => math.pow(total, 1 / count)
  2177. }
  2178. }
  2179. function fitWorld(manual = false, factor = 1.1) {
  2180. const fitMode = fitModes[config.autoFitMode]
  2181. let max = fitMode.start
  2182. let count = 0;
  2183. Object.entries(entities).forEach(([key, entity]) => {
  2184. const view = entity.view;
  2185. let extra = entity.views[view].image.extra;
  2186. extra = extra === undefined ? 1 : extra;
  2187. max = fitMode.binop(max, math.multiply(extra, entity.views[view].height.toNumber("meter")));
  2188. count += 1;
  2189. });
  2190. max = fitMode.final(max, count)
  2191. max = math.unit(max, "meter")
  2192. if (manual)
  2193. altHeld = true;
  2194. setWorldHeight(config.height, math.multiply(max, factor));
  2195. if (manual)
  2196. altHeld = false;
  2197. }
  2198. // TODO why am I doing this
  2199. function updateWorldHeight() {
  2200. const unit = document.querySelector("#options-height-unit").value;
  2201. const value = Math.max(0.000000001, document.querySelector("#options-height-value").value);
  2202. const oldHeight = config.height;
  2203. setWorldHeight(oldHeight, math.unit(value, unit));
  2204. }
  2205. function setWorldHeight(oldHeight, newHeight) {
  2206. worldSizeDirty = true;
  2207. config.height = newHeight.to(document.querySelector("#options-height-unit").value)
  2208. const unit = document.querySelector("#options-height-unit").value;
  2209. setNumericInput(document.querySelector("#options-height-value"), config.height.toNumber(unit));
  2210. Object.entries(entities).forEach(([key, entity]) => {
  2211. const element = document.querySelector("#entity-" + key);
  2212. let newPosition;
  2213. if (!altHeld) {
  2214. newPosition = adjustAbs({ x: element.dataset.x, y: element.dataset.y }, oldHeight, config.height);
  2215. } else {
  2216. newPosition = { x: element.dataset.x, y: element.dataset.y };
  2217. }
  2218. element.dataset.x = newPosition.x;
  2219. element.dataset.y = newPosition.y;
  2220. });
  2221. updateSizes();
  2222. }
  2223. function loadScene(name = "default") {
  2224. try {
  2225. const data = JSON.parse(localStorage.getItem("macrovision-save-" + name));
  2226. if (data === null) {
  2227. return false;
  2228. }
  2229. importScene(data);
  2230. return true;
  2231. } catch (err) {
  2232. alert("Something went wrong while loading (maybe you didn't have anything saved. Check the F12 console for the error.")
  2233. console.error(err);
  2234. return false;
  2235. }
  2236. }
  2237. function saveScene(name = "default") {
  2238. try {
  2239. const string = JSON.stringify(exportScene());
  2240. localStorage.setItem("macrovision-save-" + name, string);
  2241. } catch (err) {
  2242. alert("Something went wrong while saving (maybe I don't have localStorage permissions, or exporting failed). Check the F12 console for the error.")
  2243. console.error(err);
  2244. }
  2245. }
  2246. function deleteScene(name = "default") {
  2247. try {
  2248. localStorage.removeItem("macrovision-save-" + name)
  2249. } catch (err) {
  2250. console.error(err);
  2251. }
  2252. }
  2253. function exportScene() {
  2254. const results = {};
  2255. results.entities = [];
  2256. Object.entries(entities).filter(([key, entity]) => entity.ephemeral !== true).forEach(([key, entity]) => {
  2257. const element = document.querySelector("#entity-" + key);
  2258. results.entities.push({
  2259. name: entity.identifier,
  2260. scale: entity.scale,
  2261. view: entity.view,
  2262. x: element.dataset.x,
  2263. y: element.dataset.y
  2264. });
  2265. });
  2266. const unit = document.querySelector("#options-height-unit").value;
  2267. results.world = {
  2268. height: config.height.toNumber(unit),
  2269. unit: unit
  2270. }
  2271. results.canvasWidth = canvasWidth;
  2272. return results;
  2273. }
  2274. // btoa doesn't like anything that isn't ASCII
  2275. // great
  2276. // thanks to https://stackoverflow.com/questions/30106476/using-javascripts-atob-to-decode-base64-doesnt-properly-decode-utf-8-strings
  2277. // for providing an alternative
  2278. function b64EncodeUnicode(str) {
  2279. // first we use encodeURIComponent to get percent-encoded UTF-8,
  2280. // then we convert the percent encodings into raw bytes which
  2281. // can be fed into btoa.
  2282. return btoa(encodeURIComponent(str).replace(/%([0-9A-F]{2})/g,
  2283. function toSolidBytes(match, p1) {
  2284. return String.fromCharCode('0x' + p1);
  2285. }));
  2286. }
  2287. function b64DecodeUnicode(str) {
  2288. // Going backwards: from bytestream, to percent-encoding, to original string.
  2289. return decodeURIComponent(atob(str).split('').map(function (c) {
  2290. return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
  2291. }).join(''));
  2292. }
  2293. function linkScene() {
  2294. loc = new URL(window.location);
  2295. window.location = loc.protocol + "//" + loc.host + loc.pathname + "?scene=" + b64EncodeUnicode(JSON.stringify(exportScene()));
  2296. }
  2297. function copyScene() {
  2298. const results = exportScene();
  2299. navigator.clipboard.writeText(JSON.stringify(results));
  2300. }
  2301. function pasteScene() {
  2302. try {
  2303. navigator.clipboard.readText().then(text => {
  2304. const data = JSON.parse(text);
  2305. if (data.entities === undefined) {
  2306. return;
  2307. }
  2308. if (data.world === undefined) {
  2309. return;
  2310. }
  2311. importScene(data);
  2312. }).catch(err => alert(err));
  2313. } catch (err) {
  2314. console.error(err);
  2315. // probably wasn't valid data
  2316. }
  2317. }
  2318. // TODO - don't just search through every single entity
  2319. // probably just have a way to do lookups directly
  2320. function findEntity(name) {
  2321. return availableEntitiesByName[name];
  2322. }
  2323. function importScene(data) {
  2324. removeAllEntities();
  2325. data.entities.forEach(entityInfo => {
  2326. const entity = findEntity(entityInfo.name).constructor();
  2327. entity.scale = entityInfo.scale
  2328. displayEntity(entity, entityInfo.view, entityInfo.x, entityInfo.y);
  2329. });
  2330. config.height = math.unit(data.world.height, data.world.unit);
  2331. document.querySelector("#options-height-unit").value = data.world.unit;
  2332. if (data.canvasWidth) {
  2333. doHorizReposition(data.canvasWidth / canvasWidth);
  2334. }
  2335. updateSizes();
  2336. }
  2337. function renderToCanvas() {
  2338. const ctx = document.querySelector("#display").getContext("2d");
  2339. Object.entries(entities).sort((ent1, ent2) => {
  2340. z1 = document.querySelector("#entity-" + ent1[0]).style.zIndex;
  2341. z2 = document.querySelector("#entity-" + ent2[0]).style.zIndex;
  2342. return z1 - z2;
  2343. }).forEach(([id, entity]) => {
  2344. element = document.querySelector("#entity-" + id);
  2345. img = element.querySelector("img");
  2346. let x = parseFloat(element.dataset.x);
  2347. let y = parseFloat(element.dataset.y);
  2348. let coords = rel2abs({x: x, y: y});
  2349. let offset = img.style.getPropertyValue("--offset");
  2350. offset = parseFloat(offset.substring(0, offset.length-1))
  2351. x = coords.x - img.getBoundingClientRect().width/2;
  2352. y = coords.y - img.getBoundingClientRect().height * (-offset/100);
  2353. let xSize = img.getBoundingClientRect().width;
  2354. let ySize = img.getBoundingClientRect().height;
  2355. ctx.drawImage(img, x, y, xSize, ySize);
  2356. });
  2357. }
  2358. function exportCanvas(callback) {
  2359. /** @type {CanvasRenderingContext2D} */
  2360. const ctx = document.querySelector("#display").getContext("2d");
  2361. const blob = ctx.canvas.toBlob(callback);
  2362. }
  2363. function generateScreenshot(callback) {
  2364. renderToCanvas();
  2365. /** @type {CanvasRenderingContext2D} */
  2366. const ctx = document.querySelector("#display").getContext("2d");
  2367. ctx.fillStyle = "#555";
  2368. ctx.font = "normal normal lighter 16pt coda";
  2369. ctx.fillText("macrovision.crux.sexy", 10, 25);
  2370. exportCanvas(blob => {
  2371. callback(blob);
  2372. });
  2373. }
  2374. function copyScreenshot() {
  2375. generateScreenshot(blob => {
  2376. navigator.clipboard.write([
  2377. new ClipboardItem({
  2378. "image/png": blob
  2379. })
  2380. ]);
  2381. });
  2382. drawScale(false);
  2383. }
  2384. function saveScreenshot() {
  2385. generateScreenshot(blob => {
  2386. const a = document.createElement("a");
  2387. a.href = URL.createObjectURL(blob);
  2388. a.setAttribute("download", "macrovision.png");
  2389. a.click();
  2390. });
  2391. drawScale(false);
  2392. }
  2393. const rateLimits = {};
  2394. function toast(msg) {
  2395. let div = document.createElement("div");
  2396. div.innerHTML = msg;
  2397. div.classList.add("toast");
  2398. document.body.appendChild(div);
  2399. setTimeout(() => {
  2400. document.body.removeChild(div);
  2401. }, 5000)
  2402. }
  2403. function toastRateLimit(msg, key, delay) {
  2404. if (!rateLimits[key]) {
  2405. toast(msg);
  2406. rateLimits[key] = setTimeout(() => {
  2407. delete rateLimits[key]
  2408. }, delay);
  2409. }
  2410. }