less copy protection, more size visualization
Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.
 
 
 

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