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

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