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

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