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

2072 lines
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 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. }
  450. function select(target) {
  451. deselect();
  452. selected = target;
  453. selectedEntity = entities[target.dataset.key];
  454. document.getElementById("options-selected-entity-" + target.dataset.key).selected = "selected";
  455. selected.classList.add("selected");
  456. displayAttribution(selectedEntity.views[selectedEntity.view].image.source);
  457. configViewList(selectedEntity, selectedEntity.view);
  458. configEntityOptions(selectedEntity, selectedEntity.view);
  459. configViewOptions(selectedEntity, selectedEntity.view);
  460. document.querySelector("#delete-entity").disabled = false;
  461. }
  462. function configViewList(entity, selectedView) {
  463. const list = document.querySelector("#entity-view");
  464. list.innerHTML = "";
  465. list.style.display = "block";
  466. Object.keys(entity.views).forEach(view => {
  467. const option = document.createElement("option");
  468. option.innerText = entity.views[view].name;
  469. option.value = view;
  470. if (view === selectedView) {
  471. option.selected = true;
  472. }
  473. list.appendChild(option);
  474. });
  475. }
  476. function clearViewList() {
  477. const list = document.querySelector("#entity-view");
  478. list.innerHTML = "";
  479. list.style.display = "none";
  480. }
  481. function updateWorldOptions(entity, view) {
  482. const heightInput = document.querySelector("#options-height-value");
  483. const heightSelect = document.querySelector("#options-height-unit");
  484. const converted = config.height.toNumber(heightSelect.value);
  485. setNumericInput(heightInput, converted);
  486. }
  487. function configEntityOptions(entity, view) {
  488. const holder = document.querySelector("#options-entity");
  489. document.querySelector("#entity-category-header").style.display = "block";
  490. document.querySelector("#entity-category").style.display = "block";
  491. holder.innerHTML = "";
  492. const scaleLabel = document.createElement("div");
  493. scaleLabel.classList.add("options-label");
  494. scaleLabel.innerText = "Scale";
  495. const scaleRow = document.createElement("div");
  496. scaleRow.classList.add("options-row");
  497. const scaleInput = document.createElement("input");
  498. scaleInput.classList.add("options-field-numeric");
  499. scaleInput.id = "options-entity-scale";
  500. scaleInput.addEventListener("change", e => {
  501. entity.scale = e.target.value == 0 ? 1 : e.target.value;
  502. entity.dirty = true;
  503. if (config.autoFit) {
  504. fitWorld();
  505. } else {
  506. updateSizes(true);
  507. }
  508. updateEntityOptions(entity, view);
  509. updateViewOptions(entity, view);
  510. });
  511. scaleInput.addEventListener("keydown", e => {
  512. e.stopPropagation();
  513. })
  514. scaleInput.setAttribute("min", 1);
  515. scaleInput.setAttribute("type", "number");
  516. setNumericInput(scaleInput, entity.scale);
  517. scaleRow.appendChild(scaleInput);
  518. holder.appendChild(scaleLabel);
  519. holder.appendChild(scaleRow);
  520. const nameLabel = document.createElement("div");
  521. nameLabel.classList.add("options-label");
  522. nameLabel.innerText = "Name";
  523. const nameRow = document.createElement("div");
  524. nameRow.classList.add("options-row");
  525. const nameInput = document.createElement("input");
  526. nameInput.classList.add("options-field-text");
  527. nameInput.value = entity.name;
  528. nameInput.addEventListener("input", e => {
  529. entity.name = e.target.value;
  530. entity.dirty = true;
  531. updateSizes(true);
  532. })
  533. nameInput.addEventListener("keydown", e => {
  534. e.stopPropagation();
  535. })
  536. nameRow.appendChild(nameInput);
  537. holder.appendChild(nameLabel);
  538. holder.appendChild(nameRow);
  539. const defaultHolder = document.querySelector("#options-entity-defaults");
  540. defaultHolder.innerHTML = "";
  541. entity.sizes.forEach(defaultInfo => {
  542. const button = document.createElement("button");
  543. button.classList.add("options-button");
  544. button.innerText = defaultInfo.name;
  545. button.addEventListener("click", e => {
  546. entity.views[entity.defaultView].height = defaultInfo.height;
  547. entity.dirty = true;
  548. updateEntityOptions(entity, entity.view);
  549. updateViewOptions(entity, entity.view);
  550. if (!checkFitWorld()){
  551. updateSizes(true);
  552. }
  553. });
  554. defaultHolder.appendChild(button);
  555. });
  556. document.querySelector("#options-order-display").innerText = entity.priority;
  557. document.querySelector("#options-ordering").style.display = "flex";
  558. }
  559. function updateEntityOptions(entity, view) {
  560. const scaleInput = document.querySelector("#options-entity-scale");
  561. setNumericInput(scaleInput, entity.scale);
  562. document.querySelector("#options-order-display").innerText = entity.priority;
  563. }
  564. function clearEntityOptions() {
  565. document.querySelector("#entity-category-header").style.display = "none";
  566. document.querySelector("#entity-category").style.display = "none";
  567. /*
  568. const holder = document.querySelector("#options-entity");
  569. holder.innerHTML = "";
  570. document.querySelector("#options-entity-defaults").innerHTML = "";
  571. document.querySelector("#options-ordering").style.display = "none";
  572. document.querySelector("#options-ordering").style.display = "none";*/
  573. }
  574. function configViewOptions(entity, view) {
  575. const holder = document.querySelector("#options-view");
  576. document.querySelector("#view-category-header").style.display = "block";
  577. document.querySelector("#view-category").style.display = "block";
  578. holder.innerHTML = "";
  579. Object.entries(entity.views[view].attributes).forEach(([key, val]) => {
  580. const label = document.createElement("div");
  581. label.classList.add("options-label");
  582. label.innerText = val.name;
  583. holder.appendChild(label);
  584. const row = document.createElement("div");
  585. row.classList.add("options-row");
  586. holder.appendChild(row);
  587. const input = document.createElement("input");
  588. input.classList.add("options-field-numeric");
  589. input.id = "options-view-" + key + "-input";
  590. input.setAttribute("type", "number");
  591. input.setAttribute("min", 1);
  592. setNumericInput(input, entity.views[view][key].value);
  593. const select = document.createElement("select");
  594. select.classList.add("options-field-unit");
  595. select.id = "options-view-" + key + "-select"
  596. unitChoices[val.type].forEach(name => {
  597. const option = document.createElement("option");
  598. option.innerText = name;
  599. select.appendChild(option);
  600. });
  601. input.addEventListener("change", e => {
  602. const value = input.value == 0 ? 1 : input.value;
  603. entity.views[view][key] = math.unit(value, select.value);
  604. entity.dirty = true;
  605. if (config.autoFit) {
  606. fitWorld();
  607. } else {
  608. updateSizes(true);
  609. }
  610. updateEntityOptions(entity, view);
  611. updateViewOptions(entity, view, key);
  612. });
  613. input.addEventListener("keydown", e => {
  614. e.stopPropagation();
  615. })
  616. select.setAttribute("oldUnit", select.value);
  617. // TODO does this ever cause a change in the world?
  618. select.addEventListener("input", e => {
  619. const value = input.value == 0 ? 1 : input.value;
  620. const oldUnit = select.getAttribute("oldUnit");
  621. entity.views[entity.view][key] = math.unit(value, oldUnit).to(select.value);
  622. entity.dirty = true;
  623. setNumericInput(input, entity.views[entity.view][key].toNumber(select.value));
  624. select.setAttribute("oldUnit", select.value);
  625. if (config.autoFit) {
  626. fitWorld();
  627. } else {
  628. updateSizes(true);
  629. }
  630. updateEntityOptions(entity, view);
  631. updateViewOptions(entity, view, key);
  632. });
  633. row.appendChild(input);
  634. row.appendChild(select);
  635. });
  636. }
  637. function updateViewOptions(entity, view, changed) {
  638. Object.entries(entity.views[view].attributes).forEach(([key, val]) => {
  639. if (key != changed) {
  640. const input = document.querySelector("#options-view-" + key + "-input");
  641. const select = document.querySelector("#options-view-" + key + "-select");
  642. const currentUnit = select.value;
  643. const convertedAmount = entity.views[view][key].toNumber(currentUnit);
  644. setNumericInput(input, convertedAmount);
  645. }
  646. });
  647. }
  648. function setNumericInput(input, value, round=3) {
  649. input.value = math.round(value, round);
  650. }
  651. function getSortedEntities() {
  652. return Object.keys(entities).sort((a, b) => {
  653. const entA = entities[a];
  654. const entB = entities[b];
  655. const viewA = entA.view;
  656. const viewB = entB.view;
  657. const heightA = entA.views[viewA].height.to("meter").value;
  658. const heightB = entB.views[viewB].height.to("meter").value;
  659. return heightA - heightB;
  660. });
  661. }
  662. function clearViewOptions() {
  663. document.querySelector("#view-category-header").style.display = "none";
  664. document.querySelector("#view-category").style.display = "none";
  665. }
  666. // this is a crime against humanity, and also stolen from
  667. // stack overflow
  668. // https://stackoverflow.com/questions/38487569/click-through-png-image-only-if-clicked-coordinate-is-transparent
  669. const testCanvas = document.createElement("canvas");
  670. testCanvas.id = "test-canvas";
  671. const testCtx = testCanvas.getContext("2d");
  672. function testClick(event) {
  673. // oh my god I can't believe I'm doing this
  674. const target = event.target;
  675. if (navigator.userAgent.indexOf("Firefox") != -1) {
  676. clickDown(target.parentElement, event.clientX, event.clientY);
  677. return;
  678. }
  679. // Get click coordinates
  680. let w = target.width;
  681. let h = target.height;
  682. let ratioW = 1, ratioH = 1;
  683. // Limit the size of the canvas so that very large images don't cause problems)
  684. if (w > 1000) {
  685. ratioW = w / 1000;
  686. w /= ratioW;
  687. h /= ratioW;
  688. }
  689. if (h > 1000) {
  690. ratioH = h / 1000;
  691. w /= ratioH;
  692. h /= ratioH;
  693. }
  694. const ratio = ratioW * ratioH;
  695. var x = event.clientX - target.getBoundingClientRect().x,
  696. y = event.clientY - target.getBoundingClientRect().y,
  697. alpha;
  698. testCtx.canvas.width = w;
  699. testCtx.canvas.height = h;
  700. // Draw image to canvas
  701. // and read Alpha channel value
  702. testCtx.drawImage(target, 0, 0, w, h);
  703. alpha = testCtx.getImageData(Math.floor(x / ratio), Math.floor(y / ratio), 1, 1).data[3]; // [0]R [1]G [2]B [3]A
  704. // If pixel is transparent,
  705. // retrieve the element underneath and trigger its click event
  706. if (alpha === 0) {
  707. const oldDisplay = target.style.display;
  708. target.style.display = "none";
  709. const newTarget = document.elementFromPoint(event.clientX, event.clientY);
  710. newTarget.dispatchEvent(new MouseEvent(event.type, {
  711. "clientX": event.clientX,
  712. "clientY": event.clientY
  713. }));
  714. target.style.display = oldDisplay;
  715. } else {
  716. clickDown(target.parentElement, event.clientX, event.clientY);
  717. }
  718. }
  719. function arrangeEntities(order) {
  720. let x = 0.1;
  721. order.forEach(key => {
  722. document.querySelector("#entity-" + key).dataset.x = x;
  723. x += 0.8 / (order.length - 1);
  724. });
  725. updateSizes();
  726. }
  727. function removeAllEntities() {
  728. Object.keys(entities).forEach(key => {
  729. removeEntity(document.querySelector("#entity-" + key));
  730. });
  731. }
  732. function clearAttribution() {
  733. document.querySelector("#attribution-category-header").style.display = "none";
  734. document.querySelector("#options-attribution").style.display = "none";
  735. }
  736. function displayAttribution(file) {
  737. document.querySelector("#attribution-category-header").style.display = "block";
  738. document.querySelector("#options-attribution").style.display = "inline";
  739. const authors = authorsOfFull(file);
  740. const owners = ownersOfFull(file);
  741. const source = sourceOf(file);
  742. const authorHolder = document.querySelector("#options-attribution-authors");
  743. const ownerHolder = document.querySelector("#options-attribution-owners");
  744. const sourceHolder = document.querySelector("#options-attribution-source");
  745. if (authors === []) {
  746. const div = document.createElement("div");
  747. div.innerText = "Unknown";
  748. authorHolder.innerHTML = "";
  749. authorHolder.appendChild(div);
  750. } else if (authors === undefined) {
  751. const div = document.createElement("div");
  752. div.innerText = "Not yet entered";
  753. authorHolder.innerHTML = "";
  754. authorHolder.appendChild(div);
  755. } else {
  756. authorHolder.innerHTML = "";
  757. const list = document.createElement("ul");
  758. authorHolder.appendChild(list);
  759. authors.forEach(author => {
  760. const authorEntry = document.createElement("li");
  761. if (author.url) {
  762. const link = document.createElement("a");
  763. link.href = author.url;
  764. link.innerText = author.name;
  765. authorEntry.appendChild(link);
  766. } else {
  767. const div = document.createElement("div");
  768. div.innerText = author.name;
  769. authorEntry.appendChild(div);
  770. }
  771. list.appendChild(authorEntry);
  772. });
  773. }
  774. if (owners === []) {
  775. const div = document.createElement("div");
  776. div.innerText = "Unknown";
  777. ownerHolder.innerHTML = "";
  778. ownerHolder.appendChild(div);
  779. } else if (owners === undefined) {
  780. const div = document.createElement("div");
  781. div.innerText = "Not yet entered";
  782. ownerHolder.innerHTML = "";
  783. ownerHolder.appendChild(div);
  784. } else {
  785. ownerHolder.innerHTML = "";
  786. const list = document.createElement("ul");
  787. ownerHolder.appendChild(list);
  788. owners.forEach(owner => {
  789. const ownerEntry = document.createElement("li");
  790. if (owner.url) {
  791. const link = document.createElement("a");
  792. link.href = owner.url;
  793. link.innerText = owner.name;
  794. ownerEntry.appendChild(link);
  795. } else {
  796. const div = document.createElement("div");
  797. div.innerText = owner.name;
  798. ownerEntry.appendChild(div);
  799. }
  800. list.appendChild(ownerEntry);
  801. });
  802. }
  803. if (source === null) {
  804. const div = document.createElement("div");
  805. div.innerText = "No link";
  806. sourceHolder.innerHTML = "";
  807. sourceHolder.appendChild(div);
  808. } else if (source === undefined) {
  809. const div = document.createElement("div");
  810. div.innerText = "Not yet entered";
  811. sourceHolder.innerHTML = "";
  812. sourceHolder.appendChild(div);
  813. } else {
  814. sourceHolder.innerHTML = "";
  815. const link = document.createElement("a");
  816. link.style.display = "block";
  817. link.href = source;
  818. link.innerText = new URL(source).host;
  819. sourceHolder.appendChild(link);
  820. }
  821. }
  822. function removeEntity(element) {
  823. if (selected == element) {
  824. deselect();
  825. }
  826. const option = document.querySelector("#options-selected-entity-" + element.dataset.key);
  827. option.parentElement.removeChild(option);
  828. delete entities[element.dataset.key];
  829. const bottomName = document.querySelector("#bottom-name-" + element.dataset.key);
  830. const topName = document.querySelector("#top-name-" + element.dataset.key);
  831. bottomName.parentElement.removeChild(bottomName);
  832. topName.parentElement.removeChild(topName);
  833. element.parentElement.removeChild(element);
  834. }
  835. function checkEntity(entity) {
  836. Object.values(entity.views).forEach(view => {
  837. if (authorsOf(view.image.source) === undefined) {
  838. console.warn("No authors: " + view.image.source);
  839. }
  840. });
  841. }
  842. function displayEntity(entity, view, x, y, selectEntity=false, refresh=false) {
  843. checkEntity(entity);
  844. const box = document.createElement("div");
  845. box.classList.add("entity-box");
  846. const img = document.createElement("img");
  847. img.classList.add("entity-image");
  848. img.addEventListener("dragstart", e => {
  849. e.preventDefault();
  850. });
  851. const nameTag = document.createElement("div");
  852. nameTag.classList.add("entity-name");
  853. nameTag.innerText = entity.name;
  854. box.appendChild(img);
  855. box.appendChild(nameTag);
  856. const image = entity.views[view].image;
  857. img.src = image.source;
  858. if (image.bottom !== undefined) {
  859. img.style.setProperty("--offset", ((-1 + image.bottom) * 100) + "%")
  860. } else {
  861. img.style.setProperty("--offset", ((-1) * 100) + "%")
  862. }
  863. box.dataset.x = x;
  864. box.dataset.y = y;
  865. img.addEventListener("mousedown", e => { testClick(e); e.stopPropagation() });
  866. img.addEventListener("touchstart", e => {
  867. const fakeEvent = {
  868. target: e.target,
  869. clientX: e.touches[0].clientX,
  870. clientY: e.touches[0].clientY
  871. };
  872. testClick(fakeEvent);
  873. });
  874. const heightBar = document.createElement("div");
  875. heightBar.classList.add("height-bar");
  876. box.appendChild(heightBar);
  877. box.id = "entity-" + entityIndex;
  878. box.dataset.key = entityIndex;
  879. entity.view = view;
  880. entity.priority = 0;
  881. entities[entityIndex] = entity;
  882. entity.index = entityIndex;
  883. const world = document.querySelector("#entities");
  884. world.appendChild(box);
  885. const bottomName = document.createElement("div");
  886. bottomName.classList.add("bottom-name");
  887. bottomName.id = "bottom-name-" + entityIndex;
  888. bottomName.innerText = entity.name;
  889. bottomName.addEventListener("click", () => select(box));
  890. world.appendChild(bottomName);
  891. const topName = document.createElement("div");
  892. topName.classList.add("top-name");
  893. topName.id = "top-name-" + entityIndex;
  894. topName.innerText = entity.name;
  895. topName.addEventListener("click", () => select(box));
  896. world.appendChild(topName);
  897. const entityOption = document.createElement("option");
  898. entityOption.id = "options-selected-entity-" + entityIndex;
  899. entityOption.value = entityIndex;
  900. entityOption.innerText = entity.name;
  901. document.getElementById("options-selected-entity").appendChild(entityOption);
  902. entityIndex += 1;
  903. if (config.autoFit) {
  904. fitWorld();
  905. }
  906. if (selectEntity)
  907. select(box);
  908. entity.dirty = true;
  909. if (refresh)
  910. updateSizes(true);
  911. }
  912. window.onblur = function () {
  913. altHeld = false;
  914. shiftHeld = false;
  915. }
  916. window.onfocus = function () {
  917. window.dispatchEvent(new Event("keydown"));
  918. }
  919. // thanks to https://developers.google.com/web/fundamentals/native-hardware/fullscreen
  920. function toggleFullScreen() {
  921. var doc = window.document;
  922. var docEl = doc.documentElement;
  923. var requestFullScreen = docEl.requestFullscreen || docEl.mozRequestFullScreen || docEl.webkitRequestFullScreen || docEl.msRequestFullscreen;
  924. var cancelFullScreen = doc.exitFullscreen || doc.mozCancelFullScreen || doc.webkitExitFullscreen || doc.msExitFullscreen;
  925. if(!doc.fullscreenElement && !doc.mozFullScreenElement && !doc.webkitFullscreenElement && !doc.msFullscreenElement) {
  926. requestFullScreen.call(docEl);
  927. }
  928. else {
  929. cancelFullScreen.call(doc);
  930. }
  931. }
  932. function handleResize() {
  933. entityX = document.querySelector("#entities").getBoundingClientRect().x;
  934. canvasWidth = document.querySelector("#display").clientWidth - 100;
  935. canvasHeight = document.querySelector("#display").clientHeight - 50;
  936. updateSizes();
  937. }
  938. function prepareMenu() {
  939. const menubar = document.querySelector("#menubar");
  940. const help = document.querySelector("#help-icons");
  941. const before = document.querySelector("#scenes");
  942. [
  943. [
  944. {
  945. name: "Show/hide sidebar",
  946. id: "menu-toggle-sidebar",
  947. icon: "fas fa-chevron-circle-down",
  948. rotates: true
  949. },
  950. {
  951. name: "Fullscreen",
  952. id: "menu-fullscreen",
  953. icon: "fas fa-compress"
  954. }
  955. ],
  956. [
  957. {
  958. name: "Clear",
  959. id: "menu-clear",
  960. icon: "fas fa-file"
  961. }
  962. ],
  963. [
  964. {
  965. name: "Sort by height",
  966. id: "menu-order-height",
  967. icon: "fas fa-sort-numeric-up"
  968. }
  969. ],
  970. [
  971. {
  972. name: "Permalink",
  973. id: "menu-permalink",
  974. icon: "fas fa-link"
  975. },
  976. {
  977. name: "Export",
  978. id: "menu-export",
  979. icon: "fas fa-share"
  980. },
  981. {
  982. name: "Save",
  983. id: "menu-save",
  984. icon: "fas fa-download"
  985. },
  986. {
  987. name: "Load",
  988. id: "menu-load",
  989. icon: "fas fa-upload"
  990. },
  991. {
  992. name: "Load Autosave",
  993. id: "menu-load-autosave",
  994. icon: "fas fa-redo"
  995. }
  996. ]
  997. ].forEach(group => {
  998. const span = document.createElement("span");
  999. span.classList.add("menubar-group");
  1000. group.forEach(entry => {
  1001. const button = document.createElement("button");
  1002. button.id = entry.id;
  1003. const icon = document.createElement("i");
  1004. icon.classList.add(...entry.icon.split(" "));
  1005. if (entry.rotates) {
  1006. icon.classList.add("rotate-backward", "transitions");
  1007. }
  1008. const srText = document.createElement("span");
  1009. srText.classList.add("sr-only");
  1010. srText.innerText = entry.name;
  1011. button.appendChild(icon);
  1012. button.appendChild(srText);
  1013. span.appendChild(button);
  1014. const helperEntry = document.createElement("div");
  1015. const helperIcon = document.createElement("icon");
  1016. const helperText = document.createElement("span");
  1017. helperIcon.classList.add(...entry.icon.split(" "));
  1018. helperText.innerText = entry.name;
  1019. helperEntry.appendChild(helperIcon);
  1020. helperEntry.appendChild(helperText);
  1021. help.appendChild(helperEntry);
  1022. });
  1023. menubar.insertBefore(span, before);
  1024. });
  1025. if (checkHelpDate()) {
  1026. document.querySelector("#open-help").classList.add("highlighted");
  1027. }
  1028. }
  1029. const lastHelpChange = 1585487259753;
  1030. function checkHelpDate() {
  1031. try {
  1032. const old = localStorage.getItem("help-viewed");
  1033. if (old === null || old < lastHelpChange) {
  1034. return true;
  1035. }
  1036. return false;
  1037. } catch {
  1038. console.warn("Could not set the help-viewed date");
  1039. return false;
  1040. }
  1041. }
  1042. function setHelpDate() {
  1043. try {
  1044. localStorage.setItem("help-viewed", Date.now());
  1045. } catch {
  1046. console.warn("Could not set the help-viewed date");
  1047. }
  1048. }
  1049. function doScroll() {
  1050. document.querySelectorAll(".entity-box").forEach(element => {
  1051. element.dataset.x = parseFloat(element.dataset.x) + scrollDirection/180;
  1052. });
  1053. updateSizes();
  1054. scrollDirection *= 1.05;
  1055. }
  1056. function doZoom() {
  1057. const oldHeight = config.height;
  1058. setWorldHeight(oldHeight, math.multiply(oldHeight, 1 + zoomDirection / 10));
  1059. zoomDirection *= 1.05;
  1060. }
  1061. function doSize() {
  1062. if (selected) {
  1063. const entity = entities[selected.dataset.key];
  1064. const oldHeight = entity.views[entity.view].height;
  1065. entity.views[entity.view].height = math.multiply(oldHeight, 1 + sizeDirection/20);
  1066. entity.dirty = true;
  1067. updateSizes(true);
  1068. sizeDirection *= 1.05;
  1069. }
  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-bottom-cover").addEventListener("input", e => {
  1115. document.body.classList[e.target.checked ? "add" : "remove"]("toggle-bottom-cover");
  1116. });
  1117. document.querySelector("#options-world-show-scale").addEventListener("input", e => {
  1118. document.body.classList[e.target.checked ? "add" : "remove"]("toggle-scale");
  1119. });
  1120. document.querySelector("#options-order-forward").addEventListener("click", e => {
  1121. if (selected) {
  1122. entities[selected.dataset.key].priority += 1;
  1123. }
  1124. document.querySelector("#options-order-display").innerText = entities[selected.dataset.key].priority;
  1125. updateSizes();
  1126. });
  1127. document.querySelector("#options-order-back").addEventListener("click", e => {
  1128. if (selected) {
  1129. entities[selected.dataset.key].priority -= 1;
  1130. }
  1131. document.querySelector("#options-order-display").innerText = entities[selected.dataset.key].priority;
  1132. updateSizes();
  1133. });
  1134. const sceneChoices = document.querySelector("#scene-choices");
  1135. Object.entries(scenes).forEach(([id, scene]) => {
  1136. const option = document.createElement("option");
  1137. option.innerText = id;
  1138. option.value = id;
  1139. sceneChoices.appendChild(option);
  1140. });
  1141. document.querySelector("#load-scene").addEventListener("click", e => {
  1142. const chosen = sceneChoices.value;
  1143. removeAllEntities();
  1144. scenes[chosen]();
  1145. });
  1146. entityX = document.querySelector("#entities").getBoundingClientRect().x;
  1147. canvasWidth = document.querySelector("#display").clientWidth - 100;
  1148. canvasHeight = document.querySelector("#display").clientHeight - 50;
  1149. document.querySelector("#open-help").addEventListener("click", e => {
  1150. setHelpDate();
  1151. document.querySelector("#open-help").classList.remove("highlighted");
  1152. document.querySelector("#help").classList.add("visible");
  1153. });
  1154. document.querySelector("#close-help").addEventListener("click", e => {
  1155. document.querySelector("#help").classList.remove("visible");
  1156. });
  1157. const unitSelector = document.querySelector("#options-height-unit");
  1158. unitChoices.length.forEach(lengthOption => {
  1159. const option = document.createElement("option");
  1160. option.innerText = lengthOption;
  1161. option.value = lengthOption;
  1162. if (lengthOption === "meters") {
  1163. option.selected = true;
  1164. }
  1165. unitSelector.appendChild(option);
  1166. });
  1167. param = new URL(window.location.href).searchParams.get("scene");
  1168. if (param === null) {
  1169. scenes["Default"]();
  1170. }
  1171. else {
  1172. try {
  1173. const data = JSON.parse(b64DecodeUnicode(param));
  1174. if (data.entities === undefined) {
  1175. return;
  1176. }
  1177. if (data.world === undefined) {
  1178. return;
  1179. }
  1180. importScene(data);
  1181. } catch (err) {
  1182. console.error(err);
  1183. scenes["Default"]();
  1184. // probably wasn't valid data
  1185. }
  1186. }
  1187. document.querySelector("#world").addEventListener("wheel", e => {
  1188. if (shiftHeld) {
  1189. if (selected) {
  1190. const dir = e.deltaY > 0 ? 10/11 : 11/10;
  1191. const entity = entities[selected.dataset.key];
  1192. entity.views[entity.view].height = math.multiply(entity.views[entity.view].height, dir);
  1193. entity.dirty = true;
  1194. updateEntityOptions(entity, entity.view);
  1195. updateViewOptions(entity, entity.view);
  1196. updateSizes(true);
  1197. } else {
  1198. document.querySelectorAll(".entity-box").forEach(element => {
  1199. element.dataset.x = parseFloat(element.dataset.x) + (e.deltaY < 0 ? 0.1 : -0.1);
  1200. });
  1201. updateSizes();
  1202. }
  1203. } else {
  1204. const dir = e.deltaY < 0 ? 10/11 : 11/10;
  1205. setWorldHeight(config.height, math.multiply(config.height, dir));
  1206. updateWorldOptions();
  1207. }
  1208. checkFitWorld();
  1209. })
  1210. document.querySelector("body").appendChild(testCtx.canvas);
  1211. updateSizes();
  1212. document.querySelector("#options-height-value").addEventListener("change", e => {
  1213. updateWorldHeight();
  1214. })
  1215. document.querySelector("#options-height-value").addEventListener("keydown", e => {
  1216. e.stopPropagation();
  1217. })
  1218. unitSelector.addEventListener("input", e => {
  1219. checkFitWorld();
  1220. updateWorldHeight();
  1221. })
  1222. world.addEventListener("mousedown", e => deselect());
  1223. document.querySelector("#entities").addEventListener("mousedown", deselect);
  1224. document.querySelector("#display").addEventListener("mousedown", deselect);
  1225. document.addEventListener("mouseup", e => clickUp(e));
  1226. document.addEventListener("touchend", e => {
  1227. const fakeEvent = {
  1228. target: e.target,
  1229. clientX: e.changedTouches[0].clientX,
  1230. clientY: e.changedTouches[0].clientY
  1231. };
  1232. clickUp(fakeEvent);
  1233. });
  1234. document.querySelector("#entity-view").addEventListener("input", e => {
  1235. const entity = entities[selected.dataset.key];
  1236. entity.view = e.target.value;
  1237. const image = entities[selected.dataset.key].views[e.target.value].image;
  1238. selected.querySelector(".entity-image").src = image.source;
  1239. displayAttribution(image.source);
  1240. if (image.bottom !== undefined) {
  1241. selected.querySelector(".entity-image").style.setProperty("--offset", ((-1 + image.bottom) * 100) + "%")
  1242. } else {
  1243. selected.querySelector(".entity-image").style.setProperty("--offset", ((-1) * 100) + "%")
  1244. }
  1245. updateSizes();
  1246. updateEntityOptions(entities[selected.dataset.key], e.target.value);
  1247. updateViewOptions(entities[selected.dataset.key], e.target.value);
  1248. });
  1249. clearViewList();
  1250. document.querySelector("#menu-clear").addEventListener("click", e => {
  1251. removeAllEntities();
  1252. });
  1253. document.querySelector("#delete-entity").disabled = true;
  1254. document.querySelector("#delete-entity").addEventListener("click", e => {
  1255. if (selected) {
  1256. removeEntity(selected);
  1257. selected = null;
  1258. }
  1259. });
  1260. document.querySelector("#menu-order-height").addEventListener("click", e => {
  1261. const order = Object.keys(entities).sort((a, b) => {
  1262. const entA = entities[a];
  1263. const entB = entities[b];
  1264. const viewA = entA.view;
  1265. const viewB = entB.view;
  1266. const heightA = entA.views[viewA].height.to("meter").value;
  1267. const heightB = entB.views[viewB].height.to("meter").value;
  1268. return heightA - heightB;
  1269. });
  1270. arrangeEntities(order);
  1271. });
  1272. // TODO: write some generic logic for this lol
  1273. document.querySelector("#scroll-left").addEventListener("mousedown", e => {
  1274. scrollDirection = -1;
  1275. scrollHandle = setInterval(doScroll, 1000/20);
  1276. e.stopPropagation();
  1277. });
  1278. document.querySelector("#scroll-right").addEventListener("mousedown", e => {
  1279. scrollDirection = 1;
  1280. scrollHandle = setInterval(doScroll, 1000/20);
  1281. e.stopPropagation();
  1282. });
  1283. document.querySelector("#scroll-left").addEventListener("touchstart", e => {
  1284. scrollDirection = -1;
  1285. scrollHandle = setInterval(doScroll, 1000/20);
  1286. e.stopPropagation();
  1287. });
  1288. document.querySelector("#scroll-right").addEventListener("touchstart", e => {
  1289. scrollDirection = 1;
  1290. scrollHandle = setInterval(doScroll, 1000/20);
  1291. e.stopPropagation();
  1292. });
  1293. document.addEventListener("mouseup", e => {
  1294. clearInterval(scrollHandle);
  1295. scrollHandle = null;
  1296. });
  1297. document.addEventListener("touchend", e => {
  1298. clearInterval(scrollHandle);
  1299. scrollHandle = null;
  1300. });
  1301. document.querySelector("#zoom-in").addEventListener("mousedown", e => {
  1302. zoomDirection = -1;
  1303. zoomHandle = setInterval(doZoom, 1000/20);
  1304. e.stopPropagation();
  1305. });
  1306. document.querySelector("#zoom-out").addEventListener("mousedown", e => {
  1307. zoomDirection = 1;
  1308. zoomHandle = setInterval(doZoom, 1000/20);
  1309. e.stopPropagation();
  1310. });
  1311. document.querySelector("#zoom-in").addEventListener("touchstart", e => {
  1312. zoomDirection = -1;
  1313. zoomHandle = setInterval(doZoom, 1000/20);
  1314. e.stopPropagation();
  1315. });
  1316. document.querySelector("#zoom-out").addEventListener("touchstart", e => {
  1317. zoomDirection = 1;
  1318. zoomHandle = setInterval(doZoom, 1000/20);
  1319. e.stopPropagation();
  1320. });
  1321. document.addEventListener("mouseup", e => {
  1322. clearInterval(zoomHandle);
  1323. zoomHandle = null;
  1324. });
  1325. document.addEventListener("touchend", e => {
  1326. clearInterval(zoomHandle);
  1327. zoomHandle = null;
  1328. });
  1329. document.querySelector("#shrink").addEventListener("mousedown", e => {
  1330. sizeDirection = -1;
  1331. sizeHandle = setInterval(doSize, 1000/20);
  1332. e.stopPropagation();
  1333. });
  1334. document.querySelector("#grow").addEventListener("mousedown", e => {
  1335. sizeDirection = 1;
  1336. sizeHandle = setInterval(doSize, 1000/20);
  1337. e.stopPropagation();
  1338. });
  1339. document.querySelector("#shrink").addEventListener("touchstart", e => {
  1340. sizeDirection = -1;
  1341. sizeHandle = setInterval(doSize, 1000/20);
  1342. e.stopPropagation();
  1343. });
  1344. document.querySelector("#grow").addEventListener("touchstart", e => {
  1345. sizeDirection = 1;
  1346. sizeHandle = setInterval(doSize, 1000/20);
  1347. e.stopPropagation();
  1348. });
  1349. document.addEventListener("mouseup", e => {
  1350. clearInterval(sizeHandle);
  1351. sizeHandle = null;
  1352. });
  1353. document.addEventListener("touchend", e => {
  1354. clearInterval(sizeHandle);
  1355. sizeHandle = null;
  1356. });
  1357. document.querySelector("#options-world-fit").addEventListener("click", () => fitWorld(true));
  1358. document.querySelector("#options-world-autofit").addEventListener("input", e => {
  1359. config.autoFit = e.target.checked;
  1360. if (config.autoFit) {
  1361. fitWorld();
  1362. }
  1363. });
  1364. document.addEventListener("keydown", e => {
  1365. if (e.key == "Delete") {
  1366. if (selected) {
  1367. removeEntity(selected);
  1368. selected = null;
  1369. }
  1370. }
  1371. })
  1372. document.addEventListener("keydown", e => {
  1373. if (e.key == "Shift") {
  1374. shiftHeld = true;
  1375. e.preventDefault();
  1376. } else if (e.key == "Alt") {
  1377. altHeld = true;
  1378. e.preventDefault();
  1379. }
  1380. });
  1381. document.addEventListener("keyup", e => {
  1382. if (e.key == "Shift") {
  1383. shiftHeld = false;
  1384. e.preventDefault();
  1385. } else if (e.key == "Alt") {
  1386. altHeld = false;
  1387. e.preventDefault();
  1388. }
  1389. });
  1390. document.addEventListener("paste", e => {
  1391. try {
  1392. const data = JSON.parse(e.clipboardData.getData("text"));
  1393. if (data.entities === undefined) {
  1394. return;
  1395. }
  1396. if (data.world === undefined) {
  1397. return;
  1398. }
  1399. importScene(data);
  1400. } catch (err) {
  1401. console.error(err);
  1402. // probably wasn't valid data
  1403. }
  1404. });
  1405. window.addEventListener("resize", handleResize);
  1406. // TODO: further investigate why the tool initially starts out with wrong
  1407. // values under certain circumstances (seems to be narrow aspect ratios -
  1408. // maybe the menu bar is animating when it shouldn't)
  1409. setTimeout(handleResize, 250);
  1410. document.querySelector("#menu-permalink").addEventListener("click", e => {
  1411. linkScene();
  1412. });
  1413. document.querySelector("#menu-export").addEventListener("click", e => {
  1414. copyScene();
  1415. });
  1416. document.querySelector("#menu-save").addEventListener("click", e => {
  1417. saveScene();
  1418. });
  1419. document.querySelector("#menu-load").addEventListener("click", e => {
  1420. loadScene();
  1421. });
  1422. document.querySelector("#menu-load-autosave").addEventListener("click", e => {
  1423. loadScene("autosave");
  1424. });
  1425. clearEntityOptions();
  1426. clearViewOptions();
  1427. clearAttribution();
  1428. });
  1429. function prepareEntities() {
  1430. availableEntities["buildings"] = makeBuildings();
  1431. availableEntities["characters"] = makeCharacters();
  1432. availableEntities["cities"] = makeCities();
  1433. availableEntities["fiction"] = makeFiction();
  1434. availableEntities["food"] = makeFood();
  1435. availableEntities["landmarks"] = makeLandmarks();
  1436. availableEntities["naturals"] = makeNaturals();
  1437. availableEntities["objects"] = makeObjects();
  1438. availableEntities["pokemon"] = makePokemon();
  1439. availableEntities["species"] = makeSpecies();
  1440. availableEntities["vehicles"] = makeVehicles();
  1441. availableEntities["characters"].sort((x, y) => {
  1442. return x.name.toLowerCase() < y.name.toLowerCase() ? -1 : 1
  1443. });
  1444. const holder = document.querySelector("#spawners-entities");
  1445. const categorySelect = document.querySelector("#spawners-categories");
  1446. Object.entries(availableEntities).forEach(([category, entityList]) => {
  1447. const select = document.createElement("select");
  1448. select.id = "create-entity-" + category;
  1449. select.classList.add("options-field-picker");
  1450. for (let i = 0; i < entityList.length; i++) {
  1451. const entity = entityList[i];
  1452. const option = document.createElement("option");
  1453. option.value = i;
  1454. option.innerText = entity.name;
  1455. select.appendChild(option);
  1456. availableEntitiesByName[entity.name] = entity;
  1457. };
  1458. const button = document.createElement("button");
  1459. button.id = "create-entity-" + category + "-button";
  1460. button.innerHTML = "<i class=\"far fa-plus-square\"></i>";
  1461. button.addEventListener("click", e => {
  1462. const newEntity = entityList[select.value].constructor()
  1463. displayEntity(newEntity, newEntity.defaultView, 0.5, 1, true, true);
  1464. });
  1465. const categoryOption = document.createElement("option");
  1466. categoryOption.value = category
  1467. categoryOption.innerText = category;
  1468. if (category == "characters") {
  1469. categoryOption.selected = true;
  1470. select.classList.add("category-visible");
  1471. button.classList.add("category-visible");
  1472. }
  1473. categorySelect.appendChild(categoryOption);
  1474. holder.appendChild(select);
  1475. holder.appendChild(button);
  1476. });
  1477. categorySelect.addEventListener("input", e => {
  1478. const oldSelect = document.querySelector("select.category-visible");
  1479. oldSelect.classList.remove("category-visible");
  1480. const oldButton = document.querySelector("button.category-visible");
  1481. oldButton.classList.remove("category-visible");
  1482. const newSelect = document.querySelector("#create-entity-" + e.target.value);
  1483. newSelect.classList.add("category-visible");
  1484. const newButton = document.querySelector("#create-entity-" + e.target.value + "-button");
  1485. newButton.classList.add("category-visible");
  1486. });
  1487. }
  1488. document.addEventListener("mousemove", (e) => {
  1489. if (clicked) {
  1490. const position = snapRel(abs2rel({ x: e.clientX - dragOffsetX, y: e.clientY - dragOffsetY }));
  1491. clicked.dataset.x = position.x;
  1492. clicked.dataset.y = position.y;
  1493. updateEntityElement(entities[clicked.dataset.key], clicked);
  1494. if (hoveringInDeleteArea(e)) {
  1495. document.querySelector("#menubar").classList.add("hover-delete");
  1496. } else {
  1497. document.querySelector("#menubar").classList.remove("hover-delete");
  1498. }
  1499. }
  1500. });
  1501. document.addEventListener("touchmove", (e) => {
  1502. if (clicked) {
  1503. e.preventDefault();
  1504. let x = e.touches[0].clientX;
  1505. let y = e.touches[0].clientY;
  1506. const position = snapRel(abs2rel({ x: x - dragOffsetX, y: y - dragOffsetY }));
  1507. clicked.dataset.x = position.x;
  1508. clicked.dataset.y = position.y;
  1509. updateEntityElement(entities[clicked.dataset.key], clicked);
  1510. // what a hack
  1511. // I should centralize this 'fake event' creation...
  1512. if (hoveringInDeleteArea({ clientY: y })) {
  1513. document.querySelector("#menubar").classList.add("hover-delete");
  1514. } else {
  1515. document.querySelector("#menubar").classList.remove("hover-delete");
  1516. }
  1517. }
  1518. }, { passive: false });
  1519. function checkFitWorld() {
  1520. if (config.autoFit) {
  1521. fitWorld();
  1522. return true;
  1523. }
  1524. return false;
  1525. }
  1526. const fitModes = {
  1527. "max": {
  1528. start: 0,
  1529. binop: Math.max,
  1530. final: (total, count) => total
  1531. },
  1532. "arithmetic mean": {
  1533. start: 0,
  1534. binop: math.add,
  1535. final: (total, count) => total / count
  1536. },
  1537. "geometric mean": {
  1538. start: 1,
  1539. binop: math.multiply,
  1540. final: (total, count) => math.pow(total, 1 / count)
  1541. }
  1542. }
  1543. function fitWorld(manual=false, factor=1.1) {
  1544. const fitMode = fitModes[config.autoFitMode]
  1545. let max = fitMode.start
  1546. let count = 0;
  1547. Object.entries(entities).forEach(([key, entity]) => {
  1548. const view = entity.view;
  1549. let extra = entity.views[view].image.extra;
  1550. extra = extra === undefined ? 1 : extra;
  1551. max = fitMode.binop(max, math.multiply(extra, entity.views[view].height.toNumber("meter")));
  1552. count += 1;
  1553. });
  1554. max = fitMode.final(max, count)
  1555. max = math.unit(max, "meter")
  1556. if (manual)
  1557. altHeld = true;
  1558. setWorldHeight(config.height, math.multiply(max, factor));
  1559. if (manual)
  1560. altHeld = false;
  1561. }
  1562. function updateWorldHeight() {
  1563. const unit = document.querySelector("#options-height-unit").value;
  1564. const value = Math.max(0.000000001, document.querySelector("#options-height-value").value);
  1565. const oldHeight = config.height;
  1566. setWorldHeight(oldHeight, math.unit(value, unit));
  1567. }
  1568. function setWorldHeight(oldHeight, newHeight) {
  1569. worldSizeDirty = true;
  1570. config.height = newHeight.to(document.querySelector("#options-height-unit").value)
  1571. const unit = document.querySelector("#options-height-unit").value;
  1572. setNumericInput(document.querySelector("#options-height-value"), config.height.toNumber(unit));
  1573. Object.entries(entities).forEach(([key, entity]) => {
  1574. const element = document.querySelector("#entity-" + key);
  1575. let newPosition;
  1576. if (!altHeld) {
  1577. newPosition = adjustAbs({ x: element.dataset.x, y: element.dataset.y }, oldHeight, config.height);
  1578. } else {
  1579. newPosition = { x: element.dataset.x, y: element.dataset.y };
  1580. }
  1581. element.dataset.x = newPosition.x;
  1582. element.dataset.y = newPosition.y;
  1583. });
  1584. updateSizes();
  1585. }
  1586. function loadScene(name="default") {
  1587. try {
  1588. const data = JSON.parse(localStorage.getItem("macrovision-save-" + name));
  1589. if (data === null) {
  1590. return false;
  1591. }
  1592. importScene(data);
  1593. return true;
  1594. } catch (err) {
  1595. alert("Something went wrong while loading (maybe you didn't have anything saved. Check the F12 console for the error.")
  1596. console.error(err);
  1597. return false;
  1598. }
  1599. }
  1600. function saveScene(name="default") {
  1601. try {
  1602. const string = JSON.stringify(exportScene());
  1603. localStorage.setItem("macrovision-save-" + name, string);
  1604. } catch (err) {
  1605. alert("Something went wrong while saving (maybe I don't have localStorage permissions, or exporting failed). Check the F12 console for the error.")
  1606. console.error(err);
  1607. }
  1608. }
  1609. function deleteScene(name="default") {
  1610. try {
  1611. localStorage.removeItem("macrovision-save-" + name)
  1612. } catch(err) {
  1613. console.error(err);
  1614. }
  1615. }
  1616. function exportScene() {
  1617. const results = {};
  1618. results.entities = [];
  1619. Object.entries(entities).forEach(([key, entity]) => {
  1620. const element = document.querySelector("#entity-" + key);
  1621. results.entities.push({
  1622. name: entity.identifier,
  1623. scale: entity.scale,
  1624. view: entity.view,
  1625. x: element.dataset.x,
  1626. y: element.dataset.y
  1627. });
  1628. });
  1629. const unit = document.querySelector("#options-height-unit").value;
  1630. results.world = {
  1631. height: config.height.toNumber(unit),
  1632. unit: unit
  1633. }
  1634. return results;
  1635. }
  1636. // btoa doesn't like anything that isn't ASCII
  1637. // great
  1638. // thanks to https://stackoverflow.com/questions/30106476/using-javascripts-atob-to-decode-base64-doesnt-properly-decode-utf-8-strings
  1639. // for providing an alternative
  1640. function b64EncodeUnicode(str) {
  1641. // first we use encodeURIComponent to get percent-encoded UTF-8,
  1642. // then we convert the percent encodings into raw bytes which
  1643. // can be fed into btoa.
  1644. return btoa(encodeURIComponent(str).replace(/%([0-9A-F]{2})/g,
  1645. function toSolidBytes(match, p1) {
  1646. return String.fromCharCode('0x' + p1);
  1647. }));
  1648. }
  1649. function b64DecodeUnicode(str) {
  1650. // Going backwards: from bytestream, to percent-encoding, to original string.
  1651. return decodeURIComponent(atob(str).split('').map(function(c) {
  1652. return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
  1653. }).join(''));
  1654. }
  1655. function linkScene() {
  1656. loc = new URL(window.location);
  1657. window.location = loc.protocol + "//" + loc.host + loc.pathname + "?scene=" + b64EncodeUnicode(JSON.stringify(exportScene()));
  1658. }
  1659. function copyScene() {
  1660. const results = exportScene();
  1661. navigator.clipboard.writeText(JSON.stringify(results))
  1662. alert("Scene copied to clipboard. Paste text into the page to load the scene.");
  1663. }
  1664. // TODO - don't just search through every single entity
  1665. // probably just have a way to do lookups directly
  1666. function findEntity(name) {
  1667. return availableEntitiesByName[name];
  1668. }
  1669. function importScene(data) {
  1670. removeAllEntities();
  1671. data.entities.forEach(entityInfo => {
  1672. const entity = findEntity(entityInfo.name).constructor();
  1673. entity.scale = entityInfo.scale
  1674. displayEntity(entity, entityInfo.view, entityInfo.x, entityInfo.y);
  1675. });
  1676. config.height = math.unit(data.world.height, data.world.unit);
  1677. document.querySelector("#options-height-unit").value = data.world.unit;
  1678. updateSizes();
  1679. }