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

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