less copy protection, more size visualization
Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.
 
 
 

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