less copy protection, more size visualization
Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.
 
 
 

2893 rindas
87 KiB

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