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.
 
 
 

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