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

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