less copy protection, more size visualization
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

2968 lines
88 KiB

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