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

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