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

2151 строка
65 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("parsec", {
  37. definition: "3.086e16 meters",
  38. prefixes: "long"
  39. })
  40. math.createUnit("parsecs", {
  41. definition: "3.086e16 meters",
  42. prefixes: "long"
  43. })
  44. math.createUnit("lightyears", {
  45. definition: "9.461e15 meters",
  46. prefixes: "long"
  47. })
  48. math.createUnit("AU", {
  49. definition: "149597870700 meters"
  50. })
  51. math.createUnit("AUs", {
  52. definition: "149597870700 meters"
  53. })
  54. math.createUnit("dalton", {
  55. definition: "1.66e-27 kg",
  56. prefixes: "long"
  57. });
  58. math.createUnit("daltons", {
  59. definition: "1.66e-27 kg",
  60. prefixes: "long"
  61. });
  62. math.createUnit("solarradii", {
  63. definition: "695990 km",
  64. prefixes: "long"
  65. });
  66. math.createUnit("solarmasses", {
  67. definition: "2e30 kg",
  68. prefixes: "long"
  69. });
  70. math.createUnit("galaxy", {
  71. definition: "105700 lightyears",
  72. prefixes: "long"
  73. });
  74. math.createUnit("galaxies", {
  75. definition: "105700 lightyears",
  76. prefixes: "long"
  77. });
  78. math.createUnit("universe", {
  79. definition: "93.016e9 lightyears",
  80. prefixes: "long"
  81. });
  82. math.createUnit("universes", {
  83. definition: "93.016e9 lightyears",
  84. prefixes: "long"
  85. });
  86. const unitChoices = {
  87. length: [
  88. "meters",
  89. "angstroms",
  90. "millimeters",
  91. "centimeters",
  92. "kilometers",
  93. "inches",
  94. "feet",
  95. "humans",
  96. "stories",
  97. "miles",
  98. "solarradii",
  99. "AUs",
  100. "lightyears",
  101. "parsecs",
  102. "galaxies",
  103. "universes"
  104. ],
  105. area: [
  106. "meters^2",
  107. "cm^2",
  108. "kilometers^2",
  109. "acres",
  110. "miles^2"
  111. ],
  112. mass: [
  113. "kilograms",
  114. "milligrams",
  115. "grams",
  116. "tonnes",
  117. "lbs",
  118. "ounces",
  119. "tons"
  120. ]
  121. }
  122. const config = {
  123. height: math.unit(1500, "meters"),
  124. minLineSize: 100,
  125. maxLineSize: 150,
  126. autoFit: false,
  127. autoFitMode: "max"
  128. }
  129. const availableEntities = {
  130. }
  131. const availableEntitiesByName = {
  132. }
  133. const entities = {
  134. }
  135. function constrainRel(coords) {
  136. if (altHeld) {
  137. return coords;
  138. }
  139. return {
  140. x: Math.min(Math.max(coords.x, 0), 1),
  141. y: Math.min(Math.max(coords.y, 0), 1)
  142. }
  143. }
  144. function snapRel(coords) {
  145. return constrainRel({
  146. x: coords.x,
  147. y: altHeld ? coords.y : (Math.abs(coords.y - 1) < 0.05 ? 1 : coords.y)
  148. });
  149. }
  150. function adjustAbs(coords, oldHeight, newHeight) {
  151. const ratio = math.divide(oldHeight, newHeight);
  152. return { x: 0.5 + (coords.x - 0.5) * math.divide(oldHeight, newHeight), y: 1 + (coords.y - 1) * math.divide(oldHeight, newHeight) };
  153. }
  154. function rel2abs(coords) {
  155. return { x: coords.x * canvasWidth + 50, y: coords.y * canvasHeight };
  156. }
  157. function abs2rel(coords) {
  158. return { x: (coords.x - 50) / canvasWidth, y: coords.y / canvasHeight };
  159. }
  160. function updateEntityElement(entity, element) {
  161. const position = rel2abs({ x: element.dataset.x, y: element.dataset.y });
  162. const view = entity.view;
  163. element.style.left = position.x + "px";
  164. element.style.top = position.y + "px";
  165. element.style.setProperty("--xpos", position.x + "px");
  166. element.style.setProperty("--entity-height", "'" + entity.views[view].height.to(config.height.units[0].unit.name).format({precision: 2}) + "'");
  167. const pixels = math.divide(entity.views[view].height, config.height) * (canvasHeight - 50);
  168. const extra = entity.views[view].image.extra;
  169. const bottom = entity.views[view].image.bottom;
  170. const bonus = (extra ? extra : 1) * (1 / (1 - (bottom ? bottom : 0)));
  171. element.style.setProperty("--height", pixels * bonus + "px");
  172. element.style.setProperty("--extra", pixels * bonus - pixels + "px");
  173. if (entity.views[view].rename)
  174. element.querySelector(".entity-name").innerText = entity.name == "" ? "" : entity.views[view].name;
  175. else
  176. element.querySelector(".entity-name").innerText = entity.name;
  177. const bottomName = document.querySelector("#bottom-name-" + element.dataset.key);
  178. bottomName.style.left = position.x + entityX + "px";
  179. bottomName.style.bottom = "0vh";
  180. bottomName.innerText = entity.name;
  181. const topName = document.querySelector("#top-name-" + element.dataset.key);
  182. topName.style.left = position.x + entityX + "px";
  183. topName.style.top = "20vh";
  184. topName.innerText = entity.name;
  185. if (entity.views[view].height.toNumber("meters") / 10 > config.height.toNumber("meters")) {
  186. topName.classList.add("top-name-needed");
  187. } else {
  188. topName.classList.remove("top-name-needed");
  189. }
  190. }
  191. function updateSizes(dirtyOnly = false) {
  192. drawScale(dirtyOnly);
  193. let ordered = Object.entries(entities);
  194. ordered.sort((e1, e2) => {
  195. if (e1[1].priority != e2[1].priority) {
  196. return e2[1].priority - e1[1].priority;
  197. } else {
  198. return e1[1].views[e1[1].view].height.value - e2[1].views[e2[1].view].height.value
  199. }
  200. });
  201. let zIndex = ordered.length;
  202. ordered.forEach(entity => {
  203. const element = document.querySelector("#entity-" + entity[0]);
  204. element.style.zIndex = zIndex;
  205. if (!dirtyOnly || entity[1].dirty) {
  206. updateEntityElement(entity[1], element, zIndex);
  207. entity[1].dirty = false;
  208. }
  209. zIndex -= 1;
  210. });
  211. }
  212. function drawScale(ifDirty=false) {
  213. if (ifDirty && !worldSizeDirty)
  214. return;
  215. function drawTicks(/** @type {CanvasRenderingContext2D} */ ctx, pixelsPer, heightPer) {
  216. let total = heightPer.clone();
  217. total.value = 0;
  218. for (let y = ctx.canvas.clientHeight - 50; y >= 50; y -= pixelsPer) {
  219. drawTick(ctx, 50, y, total);
  220. total = math.add(total, heightPer);
  221. }
  222. }
  223. function drawTick(/** @type {CanvasRenderingContext2D} */ ctx, x, y, value) {
  224. const oldStroke = ctx.strokeStyle;
  225. const oldFill = ctx.fillStyle;
  226. ctx.beginPath();
  227. ctx.moveTo(x, y);
  228. ctx.lineTo(x + 20, y);
  229. ctx.strokeStyle = "#000000";
  230. ctx.stroke();
  231. ctx.beginPath();
  232. ctx.moveTo(x + 20, y);
  233. ctx.lineTo(ctx.canvas.clientWidth - 70, y);
  234. ctx.strokeStyle = "#aaaaaa";
  235. ctx.stroke();
  236. ctx.beginPath();
  237. ctx.moveTo(ctx.canvas.clientWidth - 70, y);
  238. ctx.lineTo(ctx.canvas.clientWidth - 50, y);
  239. ctx.strokeStyle = "#000000";
  240. ctx.stroke();
  241. const oldFont = ctx.font;
  242. ctx.font = 'normal 24pt coda';
  243. ctx.fillStyle = "#dddddd";
  244. ctx.beginPath();
  245. ctx.fillText(value.format({ precision: 3 }), x + 20, y + 35);
  246. ctx.font = oldFont;
  247. ctx.strokeStyle = oldStroke;
  248. ctx.fillStyle = oldFill;
  249. }
  250. const canvas = document.querySelector("#display");
  251. /** @type {CanvasRenderingContext2D} */
  252. const ctx = canvas.getContext("2d");
  253. let pixelsPer = (ctx.canvas.clientHeight - 100) / config.height.toNumber();
  254. heightPer = 1;
  255. if (pixelsPer < config.minLineSize) {
  256. const factor = math.ceil(config.minLineSize / pixelsPer);
  257. heightPer *= factor;
  258. pixelsPer *= factor;
  259. }
  260. if (pixelsPer > config.maxLineSize) {
  261. const factor = math.ceil(pixelsPer / config.maxLineSize);
  262. heightPer /= factor;
  263. pixelsPer /= factor;
  264. }
  265. heightPer = math.unit(heightPer, config.height.units[0].unit.name)
  266. ctx.clearRect(0, 0, canvas.width, canvas.height);
  267. ctx.scale(1, 1);
  268. ctx.canvas.width = canvas.clientWidth;
  269. ctx.canvas.height = canvas.clientHeight;
  270. ctx.beginPath();
  271. ctx.moveTo(50, 50);
  272. ctx.lineTo(50, ctx.canvas.clientHeight - 50);
  273. ctx.stroke();
  274. ctx.beginPath();
  275. ctx.moveTo(ctx.canvas.clientWidth - 50, 50);
  276. ctx.lineTo(ctx.canvas.clientWidth - 50, ctx.canvas.clientHeight - 50);
  277. ctx.stroke();
  278. drawTicks(ctx, pixelsPer, heightPer);
  279. }
  280. // Entities are generated as needed, and we make a copy
  281. // every time - the resulting objects get mutated, after all.
  282. // But we also want to be able to read some information without
  283. // calling the constructor -- e.g. making a list of authors and
  284. // owners. So, this function is used to generate that information.
  285. // It is invoked like makeEntity so that it can be dropped in easily,
  286. // but returns an object that lets you construct many copies of an entity,
  287. // rather than creating a new entity.
  288. function createEntityMaker(info, views, sizes) {
  289. const maker = {};
  290. maker.name = info.name;
  291. maker.constructor = () => makeEntity(info, views, sizes);
  292. maker.authors = [];
  293. maker.owners = [];
  294. Object.values(views).forEach(view => {
  295. const authors = authorsOf(view.image.source);
  296. if (authors) {
  297. authors.forEach(author => {
  298. if (maker.authors.indexOf(author) == -1) {
  299. maker.authors.push(author);
  300. }
  301. });
  302. }
  303. const owners = ownersOf(view.image.source);
  304. if (owners) {
  305. owners.forEach(owner => {
  306. if (maker.owners.indexOf(owner) == -1) {
  307. maker.owners.push(owner);
  308. }
  309. });
  310. }
  311. });
  312. return maker;
  313. }
  314. // This function serializes and parses its arguments to avoid sharing
  315. // references to a common object. This allows for the objects to be
  316. // safely mutated.
  317. function makeEntity(info, views, sizes) {
  318. const entityTemplate = {
  319. name: info.name,
  320. identifier: info.name,
  321. scale: 1,
  322. info: JSON.parse(JSON.stringify(info)),
  323. views: JSON.parse(JSON.stringify(views), math.reviver),
  324. sizes: sizes === undefined ? [] : JSON.parse(JSON.stringify(sizes), math.reviver),
  325. init: function () {
  326. const entity = this;
  327. Object.entries(this.views).forEach(([viewKey, view]) => {
  328. view.parent = this;
  329. if (this.defaultView === undefined) {
  330. this.defaultView = viewKey;
  331. this.view = viewKey;
  332. }
  333. Object.entries(view.attributes).forEach(([key, val]) => {
  334. Object.defineProperty(
  335. view,
  336. key,
  337. {
  338. get: function () {
  339. return math.multiply(Math.pow(this.parent.scale, this.attributes[key].power), this.attributes[key].base);
  340. },
  341. set: function (value) {
  342. const newScale = Math.pow(math.divide(value, this.attributes[key].base), 1 / this.attributes[key].power);
  343. this.parent.scale = newScale;
  344. }
  345. }
  346. )
  347. });
  348. });
  349. this.sizes.forEach(size => {
  350. if (size.default === true) {
  351. this.views[this.defaultView].height = size.height;
  352. this.size = size;
  353. }
  354. });
  355. if (this.size === undefined && this.sizes.length > 0) {
  356. this.views[this.defaultView].height = this.sizes[0].height;
  357. this.size = this.sizes[0];
  358. console.warn("No default size set for " + info.name);
  359. } else if (this.sizes.length == 0) {
  360. this.sizes = [
  361. {
  362. name: "Normal",
  363. height: this.views[this.defaultView].height
  364. }
  365. ];
  366. this.size = this.sizes[0];
  367. }
  368. this.desc = {};
  369. Object.entries(this.info).forEach(([key, value]) => {
  370. Object.defineProperty(
  371. this.desc,
  372. key,
  373. {
  374. get: function () {
  375. let text = value.text;
  376. if (entity.views[entity.view].info) {
  377. if (entity.views[entity.view].info[key]) {
  378. text = combineInfo(text, entity.views[entity.view].info[key]);
  379. }
  380. }
  381. if (entity.size.info) {
  382. if (entity.size.info[key]) {
  383. text = combineInfo(text, entity.size.info[key]);
  384. }
  385. }
  386. return { title: value.title, text: text };
  387. }
  388. }
  389. )
  390. });
  391. delete this.init;
  392. return this;
  393. }
  394. }.init();
  395. return entityTemplate;
  396. }
  397. function combineInfo(existing, next) {
  398. switch (next.mode) {
  399. case "replace":
  400. return next.text;
  401. case "prepend":
  402. return next.text + existing;
  403. case "append":
  404. return existing + next.text;
  405. }
  406. return existing;
  407. }
  408. function clickDown(target, x, y) {
  409. clicked = target;
  410. const rect = target.getBoundingClientRect();
  411. let entX = document.querySelector("#entities").getBoundingClientRect().x;
  412. let entY = document.querySelector("#entities").getBoundingClientRect().y;
  413. dragOffsetX = x - rect.left + entX;
  414. dragOffsetY = y - rect.top + entY;
  415. clickTimeout = setTimeout(() => { dragging = true }, 200)
  416. target.classList.add("no-transition");
  417. }
  418. // could we make this actually detect the menu area?
  419. function hoveringInDeleteArea(e) {
  420. return e.clientY < document.body.clientHeight / 10;
  421. }
  422. function clickUp(e) {
  423. clearTimeout(clickTimeout);
  424. if (clicked) {
  425. if (dragging) {
  426. dragging = false;
  427. if (hoveringInDeleteArea(e)) {
  428. removeEntity(clicked);
  429. document.querySelector("#menubar").classList.remove("hover-delete");
  430. }
  431. } else {
  432. select(clicked);
  433. }
  434. clicked.classList.remove("no-transition");
  435. clicked = null;
  436. }
  437. }
  438. function deselect() {
  439. if (selected) {
  440. selected.classList.remove("selected");
  441. }
  442. document.getElementById("options-selected-entity-none").selected = "selected";
  443. clearAttribution();
  444. selected = null;
  445. clearViewList();
  446. clearEntityOptions();
  447. clearViewOptions();
  448. document.querySelector("#delete-entity").disabled = true;
  449. document.querySelector("#grow").disabled = true;
  450. document.querySelector("#shrink").disabled = true;
  451. document.querySelector("#fit").disabled = true;
  452. }
  453. function select(target) {
  454. deselect();
  455. selected = target;
  456. selectedEntity = entities[target.dataset.key];
  457. document.getElementById("options-selected-entity-" + target.dataset.key).selected = "selected";
  458. selected.classList.add("selected");
  459. displayAttribution(selectedEntity.views[selectedEntity.view].image.source);
  460. configViewList(selectedEntity, selectedEntity.view);
  461. configEntityOptions(selectedEntity, selectedEntity.view);
  462. configViewOptions(selectedEntity, selectedEntity.view);
  463. document.querySelector("#delete-entity").disabled = false;
  464. document.querySelector("#grow").disabled = false;
  465. document.querySelector("#shrink").disabled = false;
  466. document.querySelector("#fit").disabled = false;
  467. }
  468. function configViewList(entity, selectedView) {
  469. const list = document.querySelector("#entity-view");
  470. list.innerHTML = "";
  471. list.style.display = "block";
  472. Object.keys(entity.views).forEach(view => {
  473. const option = document.createElement("option");
  474. option.innerText = entity.views[view].name;
  475. option.value = view;
  476. if (view === selectedView) {
  477. option.selected = true;
  478. }
  479. list.appendChild(option);
  480. });
  481. }
  482. function clearViewList() {
  483. const list = document.querySelector("#entity-view");
  484. list.innerHTML = "";
  485. list.style.display = "none";
  486. }
  487. function updateWorldOptions(entity, view) {
  488. const heightInput = document.querySelector("#options-height-value");
  489. const heightSelect = document.querySelector("#options-height-unit");
  490. const converted = config.height.toNumber(heightSelect.value);
  491. setNumericInput(heightInput, converted);
  492. }
  493. function configEntityOptions(entity, view) {
  494. const holder = document.querySelector("#options-entity");
  495. document.querySelector("#entity-category-header").style.display = "block";
  496. document.querySelector("#entity-category").style.display = "block";
  497. holder.innerHTML = "";
  498. const scaleLabel = document.createElement("div");
  499. scaleLabel.classList.add("options-label");
  500. scaleLabel.innerText = "Scale";
  501. const scaleRow = document.createElement("div");
  502. scaleRow.classList.add("options-row");
  503. const scaleInput = document.createElement("input");
  504. scaleInput.classList.add("options-field-numeric");
  505. scaleInput.id = "options-entity-scale";
  506. scaleInput.addEventListener("change", e => {
  507. entity.scale = e.target.value == 0 ? 1 : e.target.value;
  508. entity.dirty = true;
  509. if (config.autoFit) {
  510. fitWorld();
  511. } else {
  512. updateSizes(true);
  513. }
  514. updateEntityOptions(entity, view);
  515. updateViewOptions(entity, view);
  516. });
  517. scaleInput.addEventListener("keydown", e => {
  518. e.stopPropagation();
  519. })
  520. scaleInput.setAttribute("min", 1);
  521. scaleInput.setAttribute("type", "number");
  522. setNumericInput(scaleInput, entity.scale);
  523. scaleRow.appendChild(scaleInput);
  524. holder.appendChild(scaleLabel);
  525. holder.appendChild(scaleRow);
  526. const nameLabel = document.createElement("div");
  527. nameLabel.classList.add("options-label");
  528. nameLabel.innerText = "Name";
  529. const nameRow = document.createElement("div");
  530. nameRow.classList.add("options-row");
  531. const nameInput = document.createElement("input");
  532. nameInput.classList.add("options-field-text");
  533. nameInput.value = entity.name;
  534. nameInput.addEventListener("input", e => {
  535. entity.name = e.target.value;
  536. entity.dirty = true;
  537. updateSizes(true);
  538. })
  539. nameInput.addEventListener("keydown", e => {
  540. e.stopPropagation();
  541. })
  542. nameRow.appendChild(nameInput);
  543. holder.appendChild(nameLabel);
  544. holder.appendChild(nameRow);
  545. const defaultHolder = document.querySelector("#options-entity-defaults");
  546. defaultHolder.innerHTML = "";
  547. entity.sizes.forEach(defaultInfo => {
  548. const button = document.createElement("button");
  549. button.classList.add("options-button");
  550. button.innerText = defaultInfo.name;
  551. button.addEventListener("click", e => {
  552. entity.views[entity.defaultView].height = defaultInfo.height;
  553. entity.dirty = true;
  554. updateEntityOptions(entity, entity.view);
  555. updateViewOptions(entity, entity.view);
  556. if (!checkFitWorld()){
  557. updateSizes(true);
  558. }
  559. });
  560. defaultHolder.appendChild(button);
  561. });
  562. document.querySelector("#options-order-display").innerText = entity.priority;
  563. document.querySelector("#options-ordering").style.display = "flex";
  564. }
  565. function updateEntityOptions(entity, view) {
  566. const scaleInput = document.querySelector("#options-entity-scale");
  567. setNumericInput(scaleInput, entity.scale);
  568. document.querySelector("#options-order-display").innerText = entity.priority;
  569. }
  570. function clearEntityOptions() {
  571. document.querySelector("#entity-category-header").style.display = "none";
  572. document.querySelector("#entity-category").style.display = "none";
  573. /*
  574. const holder = document.querySelector("#options-entity");
  575. holder.innerHTML = "";
  576. document.querySelector("#options-entity-defaults").innerHTML = "";
  577. document.querySelector("#options-ordering").style.display = "none";
  578. document.querySelector("#options-ordering").style.display = "none";*/
  579. }
  580. function configViewOptions(entity, view) {
  581. const holder = document.querySelector("#options-view");
  582. document.querySelector("#view-category-header").style.display = "block";
  583. document.querySelector("#view-category").style.display = "block";
  584. holder.innerHTML = "";
  585. Object.entries(entity.views[view].attributes).forEach(([key, val]) => {
  586. const label = document.createElement("div");
  587. label.classList.add("options-label");
  588. label.innerText = val.name;
  589. holder.appendChild(label);
  590. const row = document.createElement("div");
  591. row.classList.add("options-row");
  592. holder.appendChild(row);
  593. const input = document.createElement("input");
  594. input.classList.add("options-field-numeric");
  595. input.id = "options-view-" + key + "-input";
  596. input.setAttribute("type", "number");
  597. input.setAttribute("min", 1);
  598. setNumericInput(input, entity.views[view][key].value);
  599. const select = document.createElement("select");
  600. select.classList.add("options-field-unit");
  601. select.id = "options-view-" + key + "-select"
  602. unitChoices[val.type].forEach(name => {
  603. const option = document.createElement("option");
  604. option.innerText = name;
  605. select.appendChild(option);
  606. });
  607. input.addEventListener("change", e => {
  608. const value = input.value == 0 ? 1 : input.value;
  609. entity.views[view][key] = math.unit(value, select.value);
  610. entity.dirty = true;
  611. if (config.autoFit) {
  612. fitWorld();
  613. } else {
  614. updateSizes(true);
  615. }
  616. updateEntityOptions(entity, view);
  617. updateViewOptions(entity, view, key);
  618. });
  619. input.addEventListener("keydown", e => {
  620. e.stopPropagation();
  621. })
  622. select.setAttribute("oldUnit", select.value);
  623. // TODO does this ever cause a change in the world?
  624. select.addEventListener("input", e => {
  625. const value = input.value == 0 ? 1 : input.value;
  626. const oldUnit = select.getAttribute("oldUnit");
  627. entity.views[entity.view][key] = math.unit(value, oldUnit).to(select.value);
  628. entity.dirty = true;
  629. setNumericInput(input, entity.views[entity.view][key].toNumber(select.value));
  630. select.setAttribute("oldUnit", select.value);
  631. if (config.autoFit) {
  632. fitWorld();
  633. } else {
  634. updateSizes(true);
  635. }
  636. updateEntityOptions(entity, view);
  637. updateViewOptions(entity, view, key);
  638. });
  639. row.appendChild(input);
  640. row.appendChild(select);
  641. });
  642. }
  643. function updateViewOptions(entity, view, changed) {
  644. Object.entries(entity.views[view].attributes).forEach(([key, val]) => {
  645. if (key != changed) {
  646. const input = document.querySelector("#options-view-" + key + "-input");
  647. const select = document.querySelector("#options-view-" + key + "-select");
  648. const currentUnit = select.value;
  649. const convertedAmount = entity.views[view][key].toNumber(currentUnit);
  650. setNumericInput(input, convertedAmount);
  651. }
  652. });
  653. }
  654. function setNumericInput(input, value, round=3) {
  655. input.value = math.round(value, round);
  656. }
  657. function getSortedEntities() {
  658. return Object.keys(entities).sort((a, b) => {
  659. const entA = entities[a];
  660. const entB = entities[b];
  661. const viewA = entA.view;
  662. const viewB = entB.view;
  663. const heightA = entA.views[viewA].height.to("meter").value;
  664. const heightB = entB.views[viewB].height.to("meter").value;
  665. return heightA - heightB;
  666. });
  667. }
  668. function clearViewOptions() {
  669. document.querySelector("#view-category-header").style.display = "none";
  670. document.querySelector("#view-category").style.display = "none";
  671. }
  672. // this is a crime against humanity, and also stolen from
  673. // stack overflow
  674. // https://stackoverflow.com/questions/38487569/click-through-png-image-only-if-clicked-coordinate-is-transparent
  675. const testCanvas = document.createElement("canvas");
  676. testCanvas.id = "test-canvas";
  677. const testCtx = testCanvas.getContext("2d");
  678. function testClick(event) {
  679. // oh my god I can't believe I'm doing this
  680. const target = event.target;
  681. if (navigator.userAgent.indexOf("Firefox") != -1) {
  682. clickDown(target.parentElement, event.clientX, event.clientY);
  683. return;
  684. }
  685. // Get click coordinates
  686. let w = target.width;
  687. let h = target.height;
  688. let ratioW = 1, ratioH = 1;
  689. // Limit the size of the canvas so that very large images don't cause problems)
  690. if (w > 1000) {
  691. ratioW = w / 1000;
  692. w /= ratioW;
  693. h /= ratioW;
  694. }
  695. if (h > 1000) {
  696. ratioH = h / 1000;
  697. w /= ratioH;
  698. h /= ratioH;
  699. }
  700. const ratio = ratioW * ratioH;
  701. var x = event.clientX - target.getBoundingClientRect().x,
  702. y = event.clientY - target.getBoundingClientRect().y,
  703. alpha;
  704. testCtx.canvas.width = w;
  705. testCtx.canvas.height = h;
  706. // Draw image to canvas
  707. // and read Alpha channel value
  708. testCtx.drawImage(target, 0, 0, w, h);
  709. alpha = testCtx.getImageData(Math.floor(x / ratio), Math.floor(y / ratio), 1, 1).data[3]; // [0]R [1]G [2]B [3]A
  710. // If pixel is transparent,
  711. // retrieve the element underneath and trigger its click event
  712. if (alpha === 0) {
  713. const oldDisplay = target.style.display;
  714. target.style.display = "none";
  715. const newTarget = document.elementFromPoint(event.clientX, event.clientY);
  716. newTarget.dispatchEvent(new MouseEvent(event.type, {
  717. "clientX": event.clientX,
  718. "clientY": event.clientY
  719. }));
  720. target.style.display = oldDisplay;
  721. } else {
  722. clickDown(target.parentElement, event.clientX, event.clientY);
  723. }
  724. }
  725. function arrangeEntities(order) {
  726. let x = 0.1;
  727. order.forEach(key => {
  728. document.querySelector("#entity-" + key).dataset.x = x;
  729. x += 0.8 / (order.length - 1);
  730. });
  731. updateSizes();
  732. }
  733. function removeAllEntities() {
  734. Object.keys(entities).forEach(key => {
  735. removeEntity(document.querySelector("#entity-" + key));
  736. });
  737. }
  738. function clearAttribution() {
  739. document.querySelector("#attribution-category-header").style.display = "none";
  740. document.querySelector("#options-attribution").style.display = "none";
  741. }
  742. function displayAttribution(file) {
  743. document.querySelector("#attribution-category-header").style.display = "block";
  744. document.querySelector("#options-attribution").style.display = "inline";
  745. const authors = authorsOfFull(file);
  746. const owners = ownersOfFull(file);
  747. const source = sourceOf(file);
  748. const authorHolder = document.querySelector("#options-attribution-authors");
  749. const ownerHolder = document.querySelector("#options-attribution-owners");
  750. const sourceHolder = document.querySelector("#options-attribution-source");
  751. if (authors === []) {
  752. const div = document.createElement("div");
  753. div.innerText = "Unknown";
  754. authorHolder.innerHTML = "";
  755. authorHolder.appendChild(div);
  756. } else if (authors === undefined) {
  757. const div = document.createElement("div");
  758. div.innerText = "Not yet entered";
  759. authorHolder.innerHTML = "";
  760. authorHolder.appendChild(div);
  761. } else {
  762. authorHolder.innerHTML = "";
  763. const list = document.createElement("ul");
  764. authorHolder.appendChild(list);
  765. authors.forEach(author => {
  766. const authorEntry = document.createElement("li");
  767. if (author.url) {
  768. const link = document.createElement("a");
  769. link.href = author.url;
  770. link.innerText = author.name;
  771. authorEntry.appendChild(link);
  772. } else {
  773. const div = document.createElement("div");
  774. div.innerText = author.name;
  775. authorEntry.appendChild(div);
  776. }
  777. list.appendChild(authorEntry);
  778. });
  779. }
  780. if (owners === []) {
  781. const div = document.createElement("div");
  782. div.innerText = "Unknown";
  783. ownerHolder.innerHTML = "";
  784. ownerHolder.appendChild(div);
  785. } else if (owners === undefined) {
  786. const div = document.createElement("div");
  787. div.innerText = "Not yet entered";
  788. ownerHolder.innerHTML = "";
  789. ownerHolder.appendChild(div);
  790. } else {
  791. ownerHolder.innerHTML = "";
  792. const list = document.createElement("ul");
  793. ownerHolder.appendChild(list);
  794. owners.forEach(owner => {
  795. const ownerEntry = document.createElement("li");
  796. if (owner.url) {
  797. const link = document.createElement("a");
  798. link.href = owner.url;
  799. link.innerText = owner.name;
  800. ownerEntry.appendChild(link);
  801. } else {
  802. const div = document.createElement("div");
  803. div.innerText = owner.name;
  804. ownerEntry.appendChild(div);
  805. }
  806. list.appendChild(ownerEntry);
  807. });
  808. }
  809. if (source === null) {
  810. const div = document.createElement("div");
  811. div.innerText = "No link";
  812. sourceHolder.innerHTML = "";
  813. sourceHolder.appendChild(div);
  814. } else if (source === undefined) {
  815. const div = document.createElement("div");
  816. div.innerText = "Not yet entered";
  817. sourceHolder.innerHTML = "";
  818. sourceHolder.appendChild(div);
  819. } else {
  820. sourceHolder.innerHTML = "";
  821. const link = document.createElement("a");
  822. link.style.display = "block";
  823. link.href = source;
  824. link.innerText = new URL(source).host;
  825. sourceHolder.appendChild(link);
  826. }
  827. }
  828. function removeEntity(element) {
  829. if (selected == element) {
  830. deselect();
  831. }
  832. const option = document.querySelector("#options-selected-entity-" + element.dataset.key);
  833. option.parentElement.removeChild(option);
  834. delete entities[element.dataset.key];
  835. const bottomName = document.querySelector("#bottom-name-" + element.dataset.key);
  836. const topName = document.querySelector("#top-name-" + element.dataset.key);
  837. bottomName.parentElement.removeChild(bottomName);
  838. topName.parentElement.removeChild(topName);
  839. element.parentElement.removeChild(element);
  840. }
  841. function checkEntity(entity) {
  842. Object.values(entity.views).forEach(view => {
  843. if (authorsOf(view.image.source) === undefined) {
  844. console.warn("No authors: " + view.image.source);
  845. }
  846. });
  847. }
  848. function displayEntity(entity, view, x, y, selectEntity=false, refresh=false) {
  849. checkEntity(entity);
  850. const box = document.createElement("div");
  851. box.classList.add("entity-box");
  852. const img = document.createElement("img");
  853. img.classList.add("entity-image");
  854. img.addEventListener("dragstart", e => {
  855. e.preventDefault();
  856. });
  857. const nameTag = document.createElement("div");
  858. nameTag.classList.add("entity-name");
  859. nameTag.innerText = entity.name;
  860. box.appendChild(img);
  861. box.appendChild(nameTag);
  862. const image = entity.views[view].image;
  863. img.src = image.source;
  864. if (image.bottom !== undefined) {
  865. img.style.setProperty("--offset", ((-1 + image.bottom) * 100) + "%")
  866. } else {
  867. img.style.setProperty("--offset", ((-1) * 100) + "%")
  868. }
  869. box.dataset.x = x;
  870. box.dataset.y = y;
  871. img.addEventListener("mousedown", e => { testClick(e); e.stopPropagation() });
  872. img.addEventListener("touchstart", e => {
  873. const fakeEvent = {
  874. target: e.target,
  875. clientX: e.touches[0].clientX,
  876. clientY: e.touches[0].clientY
  877. };
  878. testClick(fakeEvent);
  879. });
  880. const heightBar = document.createElement("div");
  881. heightBar.classList.add("height-bar");
  882. box.appendChild(heightBar);
  883. box.id = "entity-" + entityIndex;
  884. box.dataset.key = entityIndex;
  885. entity.view = view;
  886. entity.priority = 0;
  887. entities[entityIndex] = entity;
  888. entity.index = entityIndex;
  889. const world = document.querySelector("#entities");
  890. world.appendChild(box);
  891. const bottomName = document.createElement("div");
  892. bottomName.classList.add("bottom-name");
  893. bottomName.id = "bottom-name-" + entityIndex;
  894. bottomName.innerText = entity.name;
  895. bottomName.addEventListener("click", () => select(box));
  896. world.appendChild(bottomName);
  897. const topName = document.createElement("div");
  898. topName.classList.add("top-name");
  899. topName.id = "top-name-" + entityIndex;
  900. topName.innerText = entity.name;
  901. topName.addEventListener("click", () => select(box));
  902. world.appendChild(topName);
  903. const entityOption = document.createElement("option");
  904. entityOption.id = "options-selected-entity-" + entityIndex;
  905. entityOption.value = entityIndex;
  906. entityOption.innerText = entity.name;
  907. document.getElementById("options-selected-entity").appendChild(entityOption);
  908. entityIndex += 1;
  909. if (config.autoFit) {
  910. fitWorld();
  911. }
  912. if (selectEntity)
  913. select(box);
  914. entity.dirty = true;
  915. if (refresh)
  916. updateSizes(true);
  917. }
  918. window.onblur = function () {
  919. altHeld = false;
  920. shiftHeld = false;
  921. }
  922. window.onfocus = function () {
  923. window.dispatchEvent(new Event("keydown"));
  924. }
  925. // thanks to https://developers.google.com/web/fundamentals/native-hardware/fullscreen
  926. function toggleFullScreen() {
  927. var doc = window.document;
  928. var docEl = doc.documentElement;
  929. var requestFullScreen = docEl.requestFullscreen || docEl.mozRequestFullScreen || docEl.webkitRequestFullScreen || docEl.msRequestFullscreen;
  930. var cancelFullScreen = doc.exitFullscreen || doc.mozCancelFullScreen || doc.webkitExitFullscreen || doc.msExitFullscreen;
  931. if(!doc.fullscreenElement && !doc.mozFullScreenElement && !doc.webkitFullscreenElement && !doc.msFullscreenElement) {
  932. requestFullScreen.call(docEl);
  933. }
  934. else {
  935. cancelFullScreen.call(doc);
  936. }
  937. }
  938. function handleResize() {
  939. entityX = document.querySelector("#entities").getBoundingClientRect().x;
  940. canvasWidth = document.querySelector("#display").clientWidth - 100;
  941. canvasHeight = document.querySelector("#display").clientHeight - 50;
  942. updateSizes();
  943. }
  944. function prepareMenu() {
  945. const menubar = document.querySelector("#popout-menu");
  946. [
  947. [
  948. {
  949. name: "Show/hide sidebar",
  950. id: "menu-toggle-sidebar",
  951. icon: "fas fa-chevron-circle-down",
  952. rotates: true
  953. },
  954. {
  955. name: "Fullscreen",
  956. id: "menu-fullscreen",
  957. icon: "fas fa-compress"
  958. }
  959. ],
  960. [
  961. {
  962. name: "Clear",
  963. id: "menu-clear",
  964. icon: "fas fa-file"
  965. }
  966. ],
  967. [
  968. {
  969. name: "Sort by height",
  970. id: "menu-order-height",
  971. icon: "fas fa-sort-numeric-up"
  972. }
  973. ],
  974. [
  975. {
  976. name: "Permalink",
  977. id: "menu-permalink",
  978. icon: "fas fa-link"
  979. },
  980. {
  981. name: "Export to clipboard",
  982. id: "menu-export",
  983. icon: "fas fa-share"
  984. },
  985. {
  986. name: "Import from clipboard",
  987. id: "menu-import",
  988. icon: "fas fa-share"
  989. },
  990. {
  991. name: "Save",
  992. id: "menu-save",
  993. icon: "fas fa-download"
  994. },
  995. {
  996. name: "Load",
  997. id: "menu-load",
  998. icon: "fas fa-upload"
  999. },
  1000. {
  1001. name: "Load Autosave",
  1002. id: "menu-load-autosave",
  1003. icon: "fas fa-redo"
  1004. }
  1005. ]
  1006. ].forEach(group => {
  1007. const span = document.createElement("span");
  1008. span.classList.add("popout-group");
  1009. group.forEach(entry => {
  1010. const buttonHolder = document.createElement("div");
  1011. buttonHolder.classList.add("menu-button-holder");
  1012. const button = document.createElement("button");
  1013. button.id = entry.id;
  1014. button.classList.add("menu-button");
  1015. const icon = document.createElement("i");
  1016. icon.classList.add(...entry.icon.split(" "));
  1017. if (entry.rotates) {
  1018. icon.classList.add("rotate-backward", "transitions");
  1019. }
  1020. const actionText = document.createElement("span");
  1021. actionText.innerText = entry.name;
  1022. actionText.classList.add("menu-text");
  1023. const srText = document.createElement("span");
  1024. srText.classList.add("sr-only");
  1025. srText.innerText = entry.name;
  1026. button.appendChild(icon);
  1027. button.appendChild(srText);
  1028. buttonHolder.appendChild(button);
  1029. buttonHolder.appendChild(actionText);
  1030. span.appendChild(buttonHolder);
  1031. });
  1032. menubar.appendChild(span);
  1033. });
  1034. if (checkHelpDate()) {
  1035. document.querySelector("#open-help").classList.add("highlighted");
  1036. }
  1037. }
  1038. const lastHelpChange = 1585487259753;
  1039. function checkHelpDate() {
  1040. try {
  1041. const old = localStorage.getItem("help-viewed");
  1042. if (old === null || old < lastHelpChange) {
  1043. return true;
  1044. }
  1045. return false;
  1046. } catch {
  1047. console.warn("Could not set the help-viewed date");
  1048. return false;
  1049. }
  1050. }
  1051. function setHelpDate() {
  1052. try {
  1053. localStorage.setItem("help-viewed", Date.now());
  1054. } catch {
  1055. console.warn("Could not set the help-viewed date");
  1056. }
  1057. }
  1058. function doScroll() {
  1059. document.querySelectorAll(".entity-box").forEach(element => {
  1060. element.dataset.x = parseFloat(element.dataset.x) + scrollDirection/180;
  1061. });
  1062. updateSizes();
  1063. scrollDirection *= 1.05;
  1064. }
  1065. function doZoom() {
  1066. const oldHeight = config.height;
  1067. setWorldHeight(oldHeight, math.multiply(oldHeight, 1 + zoomDirection / 10));
  1068. zoomDirection *= 1.05;
  1069. }
  1070. function doSize() {
  1071. if (selected) {
  1072. const entity = entities[selected.dataset.key];
  1073. const oldHeight = entity.views[entity.view].height;
  1074. entity.views[entity.view].height = math.multiply(oldHeight, 1 + sizeDirection/20);
  1075. entity.dirty = true;
  1076. updateEntityOptions(entity, entity.view);
  1077. updateViewOptions(entity, entity.view);
  1078. updateSizes(true);
  1079. sizeDirection *= 1.05;
  1080. }
  1081. }
  1082. document.addEventListener("DOMContentLoaded", () => {
  1083. prepareMenu();
  1084. prepareEntities();
  1085. document.querySelector("#toggle-menu").addEventListener("click", e => {
  1086. const popoutMenu = document.querySelector("#popout-menu");
  1087. console.log("hi")
  1088. if (popoutMenu.classList.contains("visible")) {
  1089. popoutMenu.classList.remove("visible");
  1090. } else {
  1091. const rect = e.target.getBoundingClientRect();
  1092. popoutMenu.classList.add("visible");
  1093. popoutMenu.style.left = rect.x + rect.width + 10 + "px";
  1094. popoutMenu.style.top = rect.y + rect.height + 10 + "px";
  1095. }
  1096. e.stopPropagation();
  1097. });
  1098. document.querySelector("#popout-menu").addEventListener("click", e => {
  1099. e.stopPropagation();
  1100. });
  1101. document.addEventListener("click", e => {
  1102. console.log("hiii")
  1103. document.querySelector("#popout-menu").classList.remove("visible");
  1104. });
  1105. window.addEventListener("unload", () => saveScene("autosave"));
  1106. document.querySelector("#options-selected-entity").addEventListener("input", e => {
  1107. if (e.target.value == "none") {
  1108. deselect()
  1109. } else {
  1110. select(document.querySelector("#entity-" + e.target.value));
  1111. }
  1112. });
  1113. document.querySelector("#menu-toggle-sidebar").addEventListener("click", e => {
  1114. const sidebar = document.querySelector("#options");
  1115. if (sidebar.classList.contains("hidden")) {
  1116. sidebar.classList.remove("hidden");
  1117. e.target.classList.remove("rotate-forward");
  1118. e.target.classList.add("rotate-backward");
  1119. } else {
  1120. sidebar.classList.add("hidden");
  1121. e.target.classList.add("rotate-forward");
  1122. e.target.classList.remove("rotate-backward");
  1123. }
  1124. handleResize();
  1125. });
  1126. document.querySelector("#menu-fullscreen").addEventListener("click", toggleFullScreen);
  1127. document.querySelector("#options-show-extra").addEventListener("input", e => {
  1128. document.body.classList[e.target.checked ? "add" : "remove"]("show-extra-options");
  1129. });
  1130. document.querySelector("#options-world-show-names").addEventListener("input", e => {
  1131. document.body.classList[e.target.checked ? "add" : "remove"]("toggle-entity-name");
  1132. });
  1133. document.querySelector("#options-world-show-bottom-names").addEventListener("input", e => {
  1134. document.body.classList[e.target.checked ? "add" : "remove"]("toggle-bottom-name");
  1135. });
  1136. document.querySelector("#options-world-show-top-names").addEventListener("input", e => {
  1137. document.body.classList[e.target.checked ? "add" : "remove"]("toggle-top-name");
  1138. });
  1139. document.querySelector("#options-world-show-height-bars").addEventListener("input", e => {
  1140. document.body.classList[e.target.checked ? "add" : "remove"]("toggle-height-bars");
  1141. });
  1142. document.querySelector("#options-world-show-entity-glow").addEventListener("input", e => {
  1143. document.body.classList[e.target.checked ? "add" : "remove"]("toggle-entity-glow");
  1144. });
  1145. document.querySelector("#options-world-show-bottom-cover").addEventListener("input", e => {
  1146. document.body.classList[e.target.checked ? "add" : "remove"]("toggle-bottom-cover");
  1147. });
  1148. document.querySelector("#options-world-show-scale").addEventListener("input", e => {
  1149. document.body.classList[e.target.checked ? "add" : "remove"]("toggle-scale");
  1150. });
  1151. document.querySelector("#options-order-forward").addEventListener("click", e => {
  1152. if (selected) {
  1153. entities[selected.dataset.key].priority += 1;
  1154. }
  1155. document.querySelector("#options-order-display").innerText = entities[selected.dataset.key].priority;
  1156. updateSizes();
  1157. });
  1158. document.querySelector("#options-order-back").addEventListener("click", e => {
  1159. if (selected) {
  1160. entities[selected.dataset.key].priority -= 1;
  1161. }
  1162. document.querySelector("#options-order-display").innerText = entities[selected.dataset.key].priority;
  1163. updateSizes();
  1164. });
  1165. const sceneChoices = document.querySelector("#scene-choices");
  1166. Object.entries(scenes).forEach(([id, scene]) => {
  1167. const option = document.createElement("option");
  1168. option.innerText = id;
  1169. option.value = id;
  1170. sceneChoices.appendChild(option);
  1171. });
  1172. document.querySelector("#load-scene").addEventListener("click", e => {
  1173. const chosen = sceneChoices.value;
  1174. removeAllEntities();
  1175. scenes[chosen]();
  1176. });
  1177. entityX = document.querySelector("#entities").getBoundingClientRect().x;
  1178. canvasWidth = document.querySelector("#display").clientWidth - 100;
  1179. canvasHeight = document.querySelector("#display").clientHeight - 50;
  1180. document.querySelector("#open-help").addEventListener("click", e => {
  1181. setHelpDate();
  1182. document.querySelector("#open-help").classList.remove("highlighted");
  1183. document.querySelector("#help").classList.add("visible");
  1184. });
  1185. document.querySelector("#close-help").addEventListener("click", e => {
  1186. document.querySelector("#help").classList.remove("visible");
  1187. });
  1188. document.querySelector("#options-height-value").addEventListener("change", e => {
  1189. updateWorldHeight();
  1190. })
  1191. document.querySelector("#options-height-value").addEventListener("keydown", e => {
  1192. e.stopPropagation();
  1193. })
  1194. const unitSelector = document.querySelector("#options-height-unit");
  1195. unitChoices.length.forEach(lengthOption => {
  1196. const option = document.createElement("option");
  1197. option.innerText = lengthOption;
  1198. option.value = lengthOption;
  1199. if (lengthOption === "meters") {
  1200. option.selected = true;
  1201. }
  1202. unitSelector.appendChild(option);
  1203. });
  1204. unitSelector.setAttribute("oldUnit", "meters");
  1205. unitSelector.addEventListener("input", e => {
  1206. checkFitWorld();
  1207. const scaleInput = document.querySelector("#options-height-value");
  1208. const newVal = math.unit(scaleInput.value, unitSelector.getAttribute("oldUnit")).toNumber(e.target.value);
  1209. setNumericInput(scaleInput, newVal);
  1210. updateWorldHeight();
  1211. unitSelector.setAttribute("oldUnit", unitSelector.value);
  1212. });
  1213. param = new URL(window.location.href).searchParams.get("scene");
  1214. if (param === null) {
  1215. scenes["Default"]();
  1216. }
  1217. else {
  1218. try {
  1219. const data = JSON.parse(b64DecodeUnicode(param));
  1220. if (data.entities === undefined) {
  1221. return;
  1222. }
  1223. if (data.world === undefined) {
  1224. return;
  1225. }
  1226. importScene(data);
  1227. } catch (err) {
  1228. console.error(err);
  1229. scenes["Default"]();
  1230. // probably wasn't valid data
  1231. }
  1232. }
  1233. document.querySelector("#world").addEventListener("wheel", e => {
  1234. if (shiftHeld) {
  1235. if (selected) {
  1236. const dir = e.deltaY > 0 ? 10/11 : 11/10;
  1237. const entity = entities[selected.dataset.key];
  1238. entity.views[entity.view].height = math.multiply(entity.views[entity.view].height, dir);
  1239. entity.dirty = true;
  1240. updateEntityOptions(entity, entity.view);
  1241. updateViewOptions(entity, entity.view);
  1242. updateSizes(true);
  1243. } else {
  1244. document.querySelectorAll(".entity-box").forEach(element => {
  1245. element.dataset.x = parseFloat(element.dataset.x) + (e.deltaY < 0 ? 0.1 : -0.1);
  1246. });
  1247. updateSizes();
  1248. }
  1249. } else {
  1250. const dir = e.deltaY < 0 ? 10/11 : 11/10;
  1251. setWorldHeight(config.height, math.multiply(config.height, dir));
  1252. updateWorldOptions();
  1253. }
  1254. checkFitWorld();
  1255. })
  1256. document.querySelector("body").appendChild(testCtx.canvas);
  1257. updateSizes();
  1258. world.addEventListener("mousedown", e => deselect());
  1259. document.querySelector("#entities").addEventListener("mousedown", deselect);
  1260. document.querySelector("#display").addEventListener("mousedown", deselect);
  1261. document.addEventListener("mouseup", e => clickUp(e));
  1262. document.addEventListener("touchend", e => {
  1263. const fakeEvent = {
  1264. target: e.target,
  1265. clientX: e.changedTouches[0].clientX,
  1266. clientY: e.changedTouches[0].clientY
  1267. };
  1268. clickUp(fakeEvent);
  1269. });
  1270. document.querySelector("#entity-view").addEventListener("input", e => {
  1271. const entity = entities[selected.dataset.key];
  1272. entity.view = e.target.value;
  1273. const image = entities[selected.dataset.key].views[e.target.value].image;
  1274. selected.querySelector(".entity-image").src = image.source;
  1275. displayAttribution(image.source);
  1276. if (image.bottom !== undefined) {
  1277. selected.querySelector(".entity-image").style.setProperty("--offset", ((-1 + image.bottom) * 100) + "%")
  1278. } else {
  1279. selected.querySelector(".entity-image").style.setProperty("--offset", ((-1) * 100) + "%")
  1280. }
  1281. updateSizes();
  1282. updateEntityOptions(entities[selected.dataset.key], e.target.value);
  1283. updateViewOptions(entities[selected.dataset.key], e.target.value);
  1284. });
  1285. clearViewList();
  1286. document.querySelector("#menu-clear").addEventListener("click", e => {
  1287. removeAllEntities();
  1288. });
  1289. document.querySelector("#delete-entity").disabled = true;
  1290. document.querySelector("#delete-entity").addEventListener("click", e => {
  1291. if (selected) {
  1292. removeEntity(selected);
  1293. selected = null;
  1294. }
  1295. });
  1296. document.querySelector("#menu-order-height").addEventListener("click", e => {
  1297. const order = Object.keys(entities).sort((a, b) => {
  1298. const entA = entities[a];
  1299. const entB = entities[b];
  1300. const viewA = entA.view;
  1301. const viewB = entB.view;
  1302. const heightA = entA.views[viewA].height.to("meter").value;
  1303. const heightB = entB.views[viewB].height.to("meter").value;
  1304. return heightA - heightB;
  1305. });
  1306. arrangeEntities(order);
  1307. });
  1308. // TODO: write some generic logic for this lol
  1309. document.querySelector("#scroll-left").addEventListener("mousedown", e => {
  1310. scrollDirection = 1;
  1311. clearInterval(scrollHandle);
  1312. scrollHandle = setInterval(doScroll, 1000/20);
  1313. e.stopPropagation();
  1314. });
  1315. document.querySelector("#scroll-right").addEventListener("mousedown", e => {
  1316. scrollDirection = -1;
  1317. clearInterval(scrollHandle);
  1318. scrollHandle = setInterval(doScroll, 1000/20);
  1319. e.stopPropagation();
  1320. });
  1321. document.querySelector("#scroll-left").addEventListener("touchstart", e => {
  1322. scrollDirection = 1;
  1323. clearInterval(scrollHandle);
  1324. scrollHandle = setInterval(doScroll, 1000/20);
  1325. e.stopPropagation();
  1326. });
  1327. document.querySelector("#scroll-right").addEventListener("touchstart", e => {
  1328. scrollDirection = -1;
  1329. clearInterval(scrollHandle);
  1330. scrollHandle = setInterval(doScroll, 1000/20);
  1331. e.stopPropagation();
  1332. });
  1333. document.addEventListener("mouseup", e => {
  1334. clearInterval(scrollHandle);
  1335. scrollHandle = null;
  1336. });
  1337. document.addEventListener("touchend", e => {
  1338. clearInterval(scrollHandle);
  1339. scrollHandle = null;
  1340. });
  1341. document.querySelector("#zoom-in").addEventListener("mousedown", e => {
  1342. zoomDirection = -1;
  1343. clearInterval(zoomHandle);
  1344. zoomHandle = setInterval(doZoom, 1000/20);
  1345. e.stopPropagation();
  1346. });
  1347. document.querySelector("#zoom-out").addEventListener("mousedown", e => {
  1348. zoomDirection = 1;
  1349. clearInterval(zoomHandle);
  1350. zoomHandle = setInterval(doZoom, 1000/20);
  1351. e.stopPropagation();
  1352. });
  1353. document.querySelector("#zoom-in").addEventListener("touchstart", e => {
  1354. zoomDirection = -1;
  1355. clearInterval(zoomHandle);
  1356. zoomHandle = setInterval(doZoom, 1000/20);
  1357. e.stopPropagation();
  1358. });
  1359. document.querySelector("#zoom-out").addEventListener("touchstart", e => {
  1360. zoomDirection = 1;
  1361. clearInterval(zoomHandle);
  1362. zoomHandle = setInterval(doZoom, 1000/20);
  1363. e.stopPropagation();
  1364. });
  1365. document.addEventListener("mouseup", e => {
  1366. clearInterval(zoomHandle);
  1367. zoomHandle = null;
  1368. });
  1369. document.addEventListener("touchend", e => {
  1370. clearInterval(zoomHandle);
  1371. zoomHandle = null;
  1372. });
  1373. document.querySelector("#shrink").addEventListener("mousedown", e => {
  1374. sizeDirection = -1;
  1375. clearInterval(sizeHandle);
  1376. sizeHandle = setInterval(doSize, 1000/20);
  1377. e.stopPropagation();
  1378. });
  1379. document.querySelector("#grow").addEventListener("mousedown", e => {
  1380. sizeDirection = 1;
  1381. clearInterval(sizeHandle);
  1382. sizeHandle = setInterval(doSize, 1000/20);
  1383. e.stopPropagation();
  1384. });
  1385. document.querySelector("#shrink").addEventListener("touchstart", e => {
  1386. sizeDirection = -1;
  1387. clearInterval(sizeHandle);
  1388. sizeHandle = setInterval(doSize, 1000/20);
  1389. e.stopPropagation();
  1390. });
  1391. document.querySelector("#grow").addEventListener("touchstart", e => {
  1392. sizeDirection = 1;
  1393. clearInterval(sizeHandle);
  1394. sizeHandle = setInterval(doSize, 1000/20);
  1395. e.stopPropagation();
  1396. });
  1397. document.addEventListener("mouseup", e => {
  1398. clearInterval(sizeHandle);
  1399. sizeHandle = null;
  1400. });
  1401. document.addEventListener("touchend", e => {
  1402. clearInterval(sizeHandle);
  1403. sizeHandle = null;
  1404. });
  1405. document.querySelector("#fit").addEventListener("click", e => {
  1406. const x = parseFloat(selected.dataset.x);
  1407. Object.keys(entities).forEach(id => {
  1408. const element = document.querySelector("#entity-" + id);
  1409. const newX = parseFloat(element.dataset.x) - x + 0.5;
  1410. element.dataset.x = newX;
  1411. });
  1412. const entity = entities[selected.dataset.key];
  1413. const height = math.multiply(entity.views[entity.view].height, 1.1);
  1414. setWorldHeight(config.height, height);
  1415. });
  1416. document.querySelector("#fit").addEventListener("mousedown", e => {
  1417. e.stopPropagation();
  1418. });
  1419. document.querySelector("#fit").addEventListener("touchstart", e => {
  1420. e.stopPropagation();
  1421. });
  1422. document.querySelector("#options-world-fit").addEventListener("click", () => fitWorld(true));
  1423. document.querySelector("#options-world-autofit").addEventListener("input", e => {
  1424. config.autoFit = e.target.checked;
  1425. if (config.autoFit) {
  1426. fitWorld();
  1427. }
  1428. });
  1429. document.addEventListener("keydown", e => {
  1430. if (e.key == "Delete") {
  1431. if (selected) {
  1432. removeEntity(selected);
  1433. selected = null;
  1434. }
  1435. }
  1436. })
  1437. document.addEventListener("keydown", e => {
  1438. if (e.key == "Shift") {
  1439. shiftHeld = true;
  1440. e.preventDefault();
  1441. } else if (e.key == "Alt") {
  1442. altHeld = true;
  1443. e.preventDefault();
  1444. }
  1445. });
  1446. document.addEventListener("keyup", e => {
  1447. if (e.key == "Shift") {
  1448. shiftHeld = false;
  1449. e.preventDefault();
  1450. } else if (e.key == "Alt") {
  1451. altHeld = false;
  1452. e.preventDefault();
  1453. }
  1454. });
  1455. window.addEventListener("resize", handleResize);
  1456. // TODO: further investigate why the tool initially starts out with wrong
  1457. // values under certain circumstances (seems to be narrow aspect ratios -
  1458. // maybe the menu bar is animating when it shouldn't)
  1459. setTimeout(handleResize, 250);
  1460. setTimeout(handleResize, 500);
  1461. setTimeout(handleResize, 750);
  1462. setTimeout(handleResize, 1000);
  1463. document.querySelector("#menu-permalink").addEventListener("click", e => {
  1464. linkScene();
  1465. });
  1466. document.querySelector("#menu-export").addEventListener("click", e => {
  1467. copyScene();
  1468. });
  1469. document.querySelector("#menu-import").addEventListener("click", e => {
  1470. pasteScene();
  1471. });
  1472. document.querySelector("#menu-save").addEventListener("click", e => {
  1473. saveScene();
  1474. });
  1475. document.querySelector("#menu-load").addEventListener("click", e => {
  1476. loadScene();
  1477. });
  1478. document.querySelector("#menu-load-autosave").addEventListener("click", e => {
  1479. loadScene("autosave");
  1480. });
  1481. clearEntityOptions();
  1482. clearViewOptions();
  1483. clearAttribution();
  1484. });
  1485. function prepareEntities() {
  1486. availableEntities["buildings"] = makeBuildings();
  1487. availableEntities["characters"] = makeCharacters();
  1488. availableEntities["cities"] = makeCities();
  1489. availableEntities["fiction"] = makeFiction();
  1490. availableEntities["food"] = makeFood();
  1491. availableEntities["landmarks"] = makeLandmarks();
  1492. availableEntities["naturals"] = makeNaturals();
  1493. availableEntities["objects"] = makeObjects();
  1494. availableEntities["pokemon"] = makePokemon();
  1495. availableEntities["species"] = makeSpecies();
  1496. availableEntities["vehicles"] = makeVehicles();
  1497. availableEntities["characters"].sort((x, y) => {
  1498. return x.name.toLowerCase() < y.name.toLowerCase() ? -1 : 1
  1499. });
  1500. const holder = document.querySelector("#spawners");
  1501. const categorySelect = document.createElement("select");
  1502. categorySelect.id = "category-picker";
  1503. holder.appendChild(categorySelect);
  1504. Object.entries(availableEntities).forEach(([category, entityList]) => {
  1505. const select = document.createElement("select");
  1506. select.id = "create-entity-" + category;
  1507. for (let i = 0; i < entityList.length; i++) {
  1508. const entity = entityList[i];
  1509. const option = document.createElement("option");
  1510. option.value = i;
  1511. option.innerText = entity.name;
  1512. select.appendChild(option);
  1513. availableEntitiesByName[entity.name] = entity;
  1514. };
  1515. const button = document.createElement("button");
  1516. button.id = "create-entity-" + category + "-button";
  1517. button.innerHTML = "<i class=\"far fa-plus-square\"></i>";
  1518. button.addEventListener("click", e => {
  1519. const newEntity = entityList[select.value].constructor()
  1520. displayEntity(newEntity, newEntity.defaultView, 0.5, 1, true, true);
  1521. });
  1522. const categoryOption = document.createElement("option");
  1523. categoryOption.value = category
  1524. categoryOption.innerText = category;
  1525. if (category == "characters") {
  1526. categoryOption.selected = true;
  1527. select.classList.add("category-visible");
  1528. button.classList.add("category-visible");
  1529. }
  1530. categorySelect.appendChild(categoryOption);
  1531. holder.appendChild(select);
  1532. holder.appendChild(button);
  1533. });
  1534. categorySelect.addEventListener("input", e => {
  1535. const oldSelect = document.querySelector("select.category-visible");
  1536. oldSelect.classList.remove("category-visible");
  1537. const oldButton = document.querySelector("button.category-visible");
  1538. oldButton.classList.remove("category-visible");
  1539. const newSelect = document.querySelector("#create-entity-" + e.target.value);
  1540. newSelect.classList.add("category-visible");
  1541. const newButton = document.querySelector("#create-entity-" + e.target.value + "-button");
  1542. newButton.classList.add("category-visible");
  1543. });
  1544. }
  1545. document.addEventListener("mousemove", (e) => {
  1546. if (clicked) {
  1547. const position = snapRel(abs2rel({ x: e.clientX - dragOffsetX, y: e.clientY - dragOffsetY }));
  1548. clicked.dataset.x = position.x;
  1549. clicked.dataset.y = position.y;
  1550. updateEntityElement(entities[clicked.dataset.key], clicked);
  1551. if (hoveringInDeleteArea(e)) {
  1552. document.querySelector("#menubar").classList.add("hover-delete");
  1553. } else {
  1554. document.querySelector("#menubar").classList.remove("hover-delete");
  1555. }
  1556. }
  1557. });
  1558. document.addEventListener("touchmove", (e) => {
  1559. if (clicked) {
  1560. e.preventDefault();
  1561. let x = e.touches[0].clientX;
  1562. let y = e.touches[0].clientY;
  1563. const position = snapRel(abs2rel({ x: x - dragOffsetX, y: y - dragOffsetY }));
  1564. clicked.dataset.x = position.x;
  1565. clicked.dataset.y = position.y;
  1566. updateEntityElement(entities[clicked.dataset.key], clicked);
  1567. // what a hack
  1568. // I should centralize this 'fake event' creation...
  1569. if (hoveringInDeleteArea({ clientY: y })) {
  1570. document.querySelector("#menubar").classList.add("hover-delete");
  1571. } else {
  1572. document.querySelector("#menubar").classList.remove("hover-delete");
  1573. }
  1574. }
  1575. }, { passive: false });
  1576. function checkFitWorld() {
  1577. if (config.autoFit) {
  1578. fitWorld();
  1579. return true;
  1580. }
  1581. return false;
  1582. }
  1583. const fitModes = {
  1584. "max": {
  1585. start: 0,
  1586. binop: Math.max,
  1587. final: (total, count) => total
  1588. },
  1589. "arithmetic mean": {
  1590. start: 0,
  1591. binop: math.add,
  1592. final: (total, count) => total / count
  1593. },
  1594. "geometric mean": {
  1595. start: 1,
  1596. binop: math.multiply,
  1597. final: (total, count) => math.pow(total, 1 / count)
  1598. }
  1599. }
  1600. function fitWorld(manual=false, factor=1.1) {
  1601. const fitMode = fitModes[config.autoFitMode]
  1602. let max = fitMode.start
  1603. let count = 0;
  1604. Object.entries(entities).forEach(([key, entity]) => {
  1605. const view = entity.view;
  1606. let extra = entity.views[view].image.extra;
  1607. extra = extra === undefined ? 1 : extra;
  1608. max = fitMode.binop(max, math.multiply(extra, entity.views[view].height.toNumber("meter")));
  1609. count += 1;
  1610. });
  1611. max = fitMode.final(max, count)
  1612. max = math.unit(max, "meter")
  1613. if (manual)
  1614. altHeld = true;
  1615. setWorldHeight(config.height, math.multiply(max, factor));
  1616. if (manual)
  1617. altHeld = false;
  1618. }
  1619. function updateWorldHeight() {
  1620. const unit = document.querySelector("#options-height-unit").value;
  1621. const value = Math.max(0.000000001, document.querySelector("#options-height-value").value);
  1622. const oldHeight = config.height;
  1623. setWorldHeight(oldHeight, math.unit(value, unit));
  1624. }
  1625. function setWorldHeight(oldHeight, newHeight) {
  1626. worldSizeDirty = true;
  1627. config.height = newHeight.to(document.querySelector("#options-height-unit").value)
  1628. const unit = document.querySelector("#options-height-unit").value;
  1629. setNumericInput(document.querySelector("#options-height-value"), config.height.toNumber(unit));
  1630. Object.entries(entities).forEach(([key, entity]) => {
  1631. const element = document.querySelector("#entity-" + key);
  1632. let newPosition;
  1633. if (!altHeld) {
  1634. newPosition = adjustAbs({ x: element.dataset.x, y: element.dataset.y }, oldHeight, config.height);
  1635. } else {
  1636. newPosition = { x: element.dataset.x, y: element.dataset.y };
  1637. }
  1638. element.dataset.x = newPosition.x;
  1639. element.dataset.y = newPosition.y;
  1640. });
  1641. updateSizes();
  1642. }
  1643. function loadScene(name="default") {
  1644. try {
  1645. const data = JSON.parse(localStorage.getItem("macrovision-save-" + name));
  1646. if (data === null) {
  1647. return false;
  1648. }
  1649. importScene(data);
  1650. return true;
  1651. } catch (err) {
  1652. alert("Something went wrong while loading (maybe you didn't have anything saved. Check the F12 console for the error.")
  1653. console.error(err);
  1654. return false;
  1655. }
  1656. }
  1657. function saveScene(name="default") {
  1658. try {
  1659. const string = JSON.stringify(exportScene());
  1660. localStorage.setItem("macrovision-save-" + name, string);
  1661. } catch (err) {
  1662. alert("Something went wrong while saving (maybe I don't have localStorage permissions, or exporting failed). Check the F12 console for the error.")
  1663. console.error(err);
  1664. }
  1665. }
  1666. function deleteScene(name="default") {
  1667. try {
  1668. localStorage.removeItem("macrovision-save-" + name)
  1669. } catch(err) {
  1670. console.error(err);
  1671. }
  1672. }
  1673. function exportScene() {
  1674. const results = {};
  1675. results.entities = [];
  1676. Object.entries(entities).forEach(([key, entity]) => {
  1677. const element = document.querySelector("#entity-" + key);
  1678. results.entities.push({
  1679. name: entity.identifier,
  1680. scale: entity.scale,
  1681. view: entity.view,
  1682. x: element.dataset.x,
  1683. y: element.dataset.y
  1684. });
  1685. });
  1686. const unit = document.querySelector("#options-height-unit").value;
  1687. results.world = {
  1688. height: config.height.toNumber(unit),
  1689. unit: unit
  1690. }
  1691. return results;
  1692. }
  1693. // btoa doesn't like anything that isn't ASCII
  1694. // great
  1695. // thanks to https://stackoverflow.com/questions/30106476/using-javascripts-atob-to-decode-base64-doesnt-properly-decode-utf-8-strings
  1696. // for providing an alternative
  1697. function b64EncodeUnicode(str) {
  1698. // first we use encodeURIComponent to get percent-encoded UTF-8,
  1699. // then we convert the percent encodings into raw bytes which
  1700. // can be fed into btoa.
  1701. return btoa(encodeURIComponent(str).replace(/%([0-9A-F]{2})/g,
  1702. function toSolidBytes(match, p1) {
  1703. return String.fromCharCode('0x' + p1);
  1704. }));
  1705. }
  1706. function b64DecodeUnicode(str) {
  1707. // Going backwards: from bytestream, to percent-encoding, to original string.
  1708. return decodeURIComponent(atob(str).split('').map(function(c) {
  1709. return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
  1710. }).join(''));
  1711. }
  1712. function linkScene() {
  1713. loc = new URL(window.location);
  1714. window.location = loc.protocol + "//" + loc.host + loc.pathname + "?scene=" + b64EncodeUnicode(JSON.stringify(exportScene()));
  1715. }
  1716. function copyScene() {
  1717. const results = exportScene();
  1718. navigator.clipboard.writeText(JSON.stringify(results));
  1719. }
  1720. function pasteScene() {
  1721. try {
  1722. navigator.clipboard.readText().then(text => {
  1723. const data = JSON.parse(text);
  1724. if (data.entities === undefined) {
  1725. return;
  1726. }
  1727. if (data.world === undefined) {
  1728. return;
  1729. }
  1730. importScene(data);
  1731. }).catch(err => alert(err));
  1732. } catch (err) {
  1733. console.error(err);
  1734. // probably wasn't valid data
  1735. }
  1736. }
  1737. // TODO - don't just search through every single entity
  1738. // probably just have a way to do lookups directly
  1739. function findEntity(name) {
  1740. return availableEntitiesByName[name];
  1741. }
  1742. function importScene(data) {
  1743. removeAllEntities();
  1744. data.entities.forEach(entityInfo => {
  1745. const entity = findEntity(entityInfo.name).constructor();
  1746. entity.scale = entityInfo.scale
  1747. displayEntity(entity, entityInfo.view, entityInfo.x, entityInfo.y);
  1748. });
  1749. config.height = math.unit(data.world.height, data.world.unit);
  1750. document.querySelector("#options-height-unit").value = data.world.unit;
  1751. updateSizes();
  1752. }