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.
 
 
 

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