less copy protection, more size visualization
Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.
 
 
 

1456 řádky
43 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. const unitChoices = {
  19. length: [
  20. "meters",
  21. "angstroms",
  22. "millimeters",
  23. "centimeters",
  24. "kilometers",
  25. "inches",
  26. "feet",
  27. "stories",
  28. "miles",
  29. "parsecs",
  30. ],
  31. area: [
  32. "meters^2",
  33. "cm^2",
  34. "kilometers^2",
  35. "acres",
  36. "miles^2"
  37. ],
  38. mass: [
  39. "kilograms",
  40. "lbs",
  41. "tons"
  42. ]
  43. }
  44. const config = {
  45. height: math.unit(1500, "meters"),
  46. minLineSize: 50,
  47. maxLineSize: 250,
  48. autoFit: false,
  49. autoFitMode: "max"
  50. }
  51. const availableEntities = {
  52. }
  53. const availableEntitiesByName = {
  54. }
  55. const entities = {
  56. }
  57. function constrainRel(coords) {
  58. if (altHeld) {
  59. return coords;
  60. }
  61. return {
  62. x: Math.min(Math.max(coords.x, 0), 1),
  63. y: Math.min(Math.max(coords.y, 0), 1)
  64. }
  65. }
  66. function snapRel(coords) {
  67. return constrainRel({
  68. x: coords.x,
  69. y: altHeld ? coords.y : (Math.abs(coords.y - 1) < 0.05 ? 1 : coords.y)
  70. });
  71. }
  72. function adjustAbs(coords, oldHeight, newHeight) {
  73. return { x: coords.x, y: 1 + (coords.y - 1) * math.divide(oldHeight, newHeight) };
  74. }
  75. function rel2abs(coords) {
  76. return { x: coords.x * canvasWidth + 50, y: coords.y * canvasHeight };
  77. }
  78. function abs2rel(coords) {
  79. return { x: (coords.x - 50) / canvasWidth, y: coords.y / canvasHeight };
  80. }
  81. function updateEntityElement(entity, element, zIndex) {
  82. const position = rel2abs({ x: element.dataset.x, y: element.dataset.y });
  83. const view = entity.view;
  84. element.style.left = position.x + "px";
  85. element.style.top = position.y + "px";
  86. const canvasHeight = document.querySelector("#display").clientHeight;
  87. const pixels = math.divide(entity.views[view].height, config.height) * (canvasHeight - 100);
  88. const bonus = (entity.views[view].image.extra ? entity.views[view].image.extra : 1);
  89. element.style.setProperty("--height", pixels * bonus + "px");
  90. if (entity.views[view].rename)
  91. element.querySelector(".entity-name").innerText = entity.name == "" ? "" : entity.views[view].name;
  92. else
  93. element.querySelector(".entity-name").innerText = entity.name;
  94. const bottomName = document.querySelector("#bottom-name-" + element.dataset.key);
  95. bottomName.style.left = position.x + entityX + "px";
  96. bottomName.style.top = "95vh";
  97. bottomName.innerText = entity.name;
  98. if (zIndex) {
  99. element.style.zIndex = zIndex;
  100. }
  101. }
  102. function updateSizes() {
  103. drawScale();
  104. let ordered = Object.entries(entities);
  105. ordered.sort((e1, e2) => {
  106. return e1[1].views[e1[1].view].height.toNumber("meters") - e2[1].views[e2[1].view].height.toNumber("meters")
  107. });
  108. let zIndex = ordered.length;
  109. ordered.forEach(entity => {
  110. const element = document.querySelector("#entity-" + entity[0]);
  111. updateEntityElement(entity[1], element, zIndex);
  112. zIndex -= 1;
  113. });
  114. }
  115. function drawScale() {
  116. function drawTicks(/** @type {CanvasRenderingContext2D} */ ctx, pixelsPer, heightPer) {
  117. let total = heightPer.clone();
  118. total.value = 0;
  119. for (let y = ctx.canvas.clientHeight - 50; y >= 50; y -= pixelsPer) {
  120. drawTick(ctx, 50, y, total);
  121. total = math.add(total, heightPer);
  122. }
  123. }
  124. function drawTick(/** @type {CanvasRenderingContext2D} */ ctx, x, y, value) {
  125. const oldStroke = ctx.strokeStyle;
  126. const oldFill = ctx.fillStyle;
  127. ctx.beginPath();
  128. ctx.moveTo(x, y);
  129. ctx.lineTo(x + 20, y);
  130. ctx.strokeStyle = "#000000";
  131. ctx.stroke();
  132. ctx.beginPath();
  133. ctx.moveTo(x + 20, y);
  134. ctx.lineTo(ctx.canvas.clientWidth - 70, y);
  135. ctx.strokeStyle = "#aaaaaa";
  136. ctx.stroke();
  137. ctx.beginPath();
  138. ctx.moveTo(ctx.canvas.clientWidth - 70, y);
  139. ctx.lineTo(ctx.canvas.clientWidth - 50, y);
  140. ctx.strokeStyle = "#000000";
  141. ctx.stroke();
  142. const oldFont = ctx.font;
  143. ctx.font = 'normal 24pt coda';
  144. ctx.fillStyle = "#dddddd";
  145. ctx.beginPath();
  146. ctx.fillText(value.format({ precision: 3 }), x + 20, y + 35);
  147. ctx.font = oldFont;
  148. ctx.strokeStyle = oldStroke;
  149. ctx.fillStyle = oldFill;
  150. }
  151. const canvas = document.querySelector("#display");
  152. /** @type {CanvasRenderingContext2D} */
  153. const ctx = canvas.getContext("2d");
  154. let pixelsPer = (ctx.canvas.clientHeight - 100) / config.height.value;
  155. let heightPer = config.height.clone();
  156. heightPer.value = 1;
  157. if (pixelsPer < config.minLineSize) {
  158. heightPer.value /= pixelsPer / config.minLineSize;
  159. pixelsPer = config.minLineSize;
  160. }
  161. if (pixelsPer > config.maxLineSize) {
  162. heightPer.value /= pixelsPer / config.maxLineSize;
  163. pixelsPer = config.maxLineSize;
  164. }
  165. ctx.clearRect(0, 0, canvas.width, canvas.height);
  166. ctx.scale(1, 1);
  167. ctx.canvas.width = canvas.clientWidth;
  168. ctx.canvas.height = canvas.clientHeight;
  169. ctx.beginPath();
  170. ctx.moveTo(50, 50);
  171. ctx.lineTo(50, ctx.canvas.clientHeight - 50);
  172. ctx.stroke();
  173. ctx.beginPath();
  174. ctx.moveTo(ctx.canvas.clientWidth - 50, 50);
  175. ctx.lineTo(ctx.canvas.clientWidth - 50, ctx.canvas.clientHeight - 50);
  176. ctx.stroke();
  177. drawTicks(ctx, pixelsPer, heightPer);
  178. }
  179. function makeEntity(info, views, sizes) {
  180. const entityTemplate = {
  181. name: info.name,
  182. identifier: info.name,
  183. scale: 1,
  184. info: info,
  185. views: views,
  186. sizes: sizes === undefined ? [] : sizes,
  187. init: function () {
  188. const entity = this;
  189. Object.entries(this.views).forEach(([viewKey, view]) => {
  190. view.parent = this;
  191. if (this.defaultView === undefined) {
  192. this.defaultView = viewKey;
  193. this.view = viewKey;
  194. }
  195. Object.entries(view.attributes).forEach(([key, val]) => {
  196. Object.defineProperty(
  197. view,
  198. key,
  199. {
  200. get: function () {
  201. return math.multiply(Math.pow(this.parent.scale, this.attributes[key].power), this.attributes[key].base);
  202. },
  203. set: function (value) {
  204. const newScale = Math.pow(math.divide(value, this.attributes[key].base), 1 / this.attributes[key].power);
  205. this.parent.scale = newScale;
  206. }
  207. }
  208. )
  209. });
  210. });
  211. this.sizes.forEach(size => {
  212. if (size.default === true) {
  213. this.views[this.defaultView].height = size.height;
  214. this.size = size;
  215. }
  216. });
  217. if (this.size === undefined && this.sizes.length > 0) {
  218. this.views[this.defaultView].height = this.sizes[0].height;
  219. this.size = this.sizes[0];
  220. }
  221. this.desc = {};
  222. Object.entries(this.info).forEach(([key, value]) => {
  223. Object.defineProperty(
  224. this.desc,
  225. key,
  226. {
  227. get: function () {
  228. let text = value.text;
  229. if (entity.views[entity.view].info) {
  230. if (entity.views[entity.view].info[key]) {
  231. text = combineInfo(text, entity.views[entity.view].info[key]);
  232. }
  233. }
  234. if (entity.size.info) {
  235. if (entity.size.info[key]) {
  236. text = combineInfo(text, entity.size.info[key]);
  237. }
  238. }
  239. return { title: value.title, text: text };
  240. }
  241. }
  242. )
  243. });
  244. delete this.init;
  245. return this;
  246. }
  247. }.init();
  248. return entityTemplate;
  249. }
  250. function combineInfo(existing, next) {
  251. switch (next.mode) {
  252. case "replace":
  253. return next.text;
  254. case "prepend":
  255. return next.text + existing;
  256. case "append":
  257. return existing + next.text;
  258. }
  259. return existing;
  260. }
  261. function clickDown(target, x, y) {
  262. clicked = target;
  263. const rect = target.getBoundingClientRect();
  264. let entX = document.querySelector("#entities").getBoundingClientRect().x;
  265. let entY = document.querySelector("#entities").getBoundingClientRect().y;
  266. dragOffsetX = x - rect.left + entX;
  267. dragOffsetY = y - rect.top + entY;
  268. clickTimeout = setTimeout(() => { dragging = true }, 200)
  269. }
  270. // could we make this actually detect the menu area?
  271. function hoveringInDeleteArea(e) {
  272. return e.clientY < document.body.clientHeight / 10;
  273. }
  274. function clickUp(e) {
  275. clearTimeout(clickTimeout);
  276. if (clicked) {
  277. if (dragging) {
  278. dragging = false;
  279. if (hoveringInDeleteArea(e)) {
  280. removeEntity(clicked);
  281. document.querySelector("#menubar").classList.remove("hover-delete");
  282. }
  283. } else {
  284. select(clicked);
  285. }
  286. clicked = null;
  287. }
  288. }
  289. function deselect() {
  290. if (selected) {
  291. selected.classList.remove("selected");
  292. }
  293. clearAttribution();
  294. selected = null;
  295. clearViewList();
  296. clearEntityOptions();
  297. clearViewOptions();
  298. }
  299. function select(target) {
  300. deselect();
  301. selected = target;
  302. selectedEntity = entities[target.dataset.key];
  303. selected.classList.add("selected");
  304. displayAttribution(selectedEntity.views[selectedEntity.view].image.source);
  305. configViewList(selectedEntity, selectedEntity.view);
  306. configEntityOptions(selectedEntity, selectedEntity.view);
  307. configViewOptions(selectedEntity, selectedEntity.view);
  308. }
  309. function configViewList(entity, selectedView) {
  310. const list = document.querySelector("#entity-view");
  311. list.innerHTML = "";
  312. list.style.display = "block";
  313. Object.keys(entity.views).forEach(view => {
  314. const option = document.createElement("option");
  315. option.innerText = entity.views[view].name;
  316. option.value = view;
  317. if (view === selectedView) {
  318. option.selected = true;
  319. }
  320. list.appendChild(option);
  321. });
  322. }
  323. function clearViewList() {
  324. const list = document.querySelector("#entity-view");
  325. list.innerHTML = "";
  326. list.style.display = "none";
  327. }
  328. function updateWorldOptions(entity, view) {
  329. const heightInput = document.querySelector("#options-height-value");
  330. const heightSelect = document.querySelector("#options-height-unit");
  331. const converted = config.height.toNumber(heightSelect.value);
  332. heightInput.value = math.round(converted, 3);
  333. }
  334. function configEntityOptions(entity, view) {
  335. const holder = document.querySelector("#options-entity");
  336. holder.innerHTML = "";
  337. const scaleLabel = document.createElement("div");
  338. scaleLabel.classList.add("options-label");
  339. scaleLabel.innerText = "Scale";
  340. const scaleRow = document.createElement("div");
  341. scaleRow.classList.add("options-row");
  342. const scaleInput = document.createElement("input");
  343. scaleInput.classList.add("options-field-numeric");
  344. scaleInput.id = "options-entity-scale";
  345. scaleInput.addEventListener("input", e => {
  346. entity.scale = e.target.value == 0 ? 1 : e.target.value;
  347. if (config.autoFit) {
  348. fitWorld();
  349. }
  350. updateSizes();
  351. updateEntityOptions(entity, view);
  352. updateViewOptions(entity, view);
  353. });
  354. scaleInput.setAttribute("min", 1);
  355. scaleInput.setAttribute("type", "number");
  356. scaleInput.value = entity.scale;
  357. scaleRow.appendChild(scaleInput);
  358. holder.appendChild(scaleLabel);
  359. holder.appendChild(scaleRow);
  360. const nameLabel = document.createElement("div");
  361. nameLabel.classList.add("options-label");
  362. nameLabel.innerText = "Name";
  363. const nameRow = document.createElement("div");
  364. nameRow.classList.add("options-row");
  365. const nameInput = document.createElement("input");
  366. nameInput.classList.add("options-field-text");
  367. nameInput.value = entity.name;
  368. nameInput.addEventListener("input", e => {
  369. entity.name = e.target.value;
  370. updateSizes();
  371. })
  372. nameRow.appendChild(nameInput);
  373. holder.appendChild(nameLabel);
  374. holder.appendChild(nameRow);
  375. const defaultHolder = document.querySelector("#options-entity-defaults");
  376. defaultHolder.innerHTML = "";
  377. entity.sizes.forEach(defaultInfo => {
  378. const button = document.createElement("button");
  379. button.classList.add("options-button");
  380. button.innerText = defaultInfo.name;
  381. button.addEventListener("click", e => {
  382. entity.views[entity.defaultView].height = defaultInfo.height;
  383. updateEntityOptions(entity, view);
  384. updateViewOptions(entity, view);
  385. updateSizes();
  386. });
  387. defaultHolder.appendChild(button);
  388. });
  389. }
  390. function updateEntityOptions(entity, view) {
  391. const scaleInput = document.querySelector("#options-entity-scale");
  392. scaleInput.value = entity.scale;
  393. }
  394. function clearEntityOptions() {
  395. const holder = document.querySelector("#options-entity");
  396. holder.innerHTML = "";
  397. document.querySelector("#options-entity-defaults").innerHTML = "";
  398. }
  399. function configViewOptions(entity, view) {
  400. const holder = document.querySelector("#options-view");
  401. holder.innerHTML = "";
  402. Object.entries(entity.views[view].attributes).forEach(([key, val]) => {
  403. const label = document.createElement("div");
  404. label.classList.add("options-label");
  405. label.innerText = val.name;
  406. holder.appendChild(label);
  407. const row = document.createElement("div");
  408. row.classList.add("options-row");
  409. holder.appendChild(row);
  410. const input = document.createElement("input");
  411. input.classList.add("options-field-numeric");
  412. input.id = "options-view-" + key + "-input";
  413. input.setAttribute("type", "number");
  414. input.setAttribute("min", 1);
  415. input.value = entity.views[view][key].value;
  416. const select = document.createElement("select");
  417. select.id = "options-view-" + key + "-select"
  418. unitChoices[val.type].forEach(name => {
  419. const option = document.createElement("option");
  420. option.innerText = name;
  421. select.appendChild(option);
  422. });
  423. input.addEventListener("input", e => {
  424. const value = input.value == 0 ? 1 : input.value;
  425. entity.views[view][key] = math.unit(value, select.value);
  426. if (config.autoFit) {
  427. fitWorld();
  428. }
  429. updateSizes();
  430. updateEntityOptions(entity, view);
  431. updateViewOptions(entity, view, key);
  432. });
  433. select.setAttribute("oldUnit", select.value);
  434. select.addEventListener("input", e => {
  435. const value = input.value == 0 ? 1 : input.value;
  436. const oldUnit = select.getAttribute("oldUnit");
  437. entity.views[view][key] = math.unit(value, oldUnit).to(select.value);
  438. input.value = entity.views[view][key].toNumber(select.value);
  439. select.setAttribute("oldUnit", select.value);
  440. if (config.autoFit) {
  441. fitWorld();
  442. }
  443. updateSizes();
  444. updateEntityOptions(entity, view);
  445. updateViewOptions(entity, view, key);
  446. });
  447. row.appendChild(input);
  448. row.appendChild(select);
  449. });
  450. }
  451. function updateViewOptions(entity, view, changed) {
  452. Object.entries(entity.views[view].attributes).forEach(([key, val]) => {
  453. if (key != changed) {
  454. const input = document.querySelector("#options-view-" + key + "-input");
  455. const select = document.querySelector("#options-view-" + key + "-select");
  456. const currentUnit = select.value;
  457. const convertedAmount = entity.views[view][key].toNumber(currentUnit);
  458. input.value = math.round(convertedAmount, 5);
  459. }
  460. });
  461. }
  462. function getSortedEntities() {
  463. return Object.keys(entities).sort((a, b) => {
  464. const entA = entities[a];
  465. const entB = entities[b];
  466. const viewA = entA.view;
  467. const viewB = entB.view;
  468. const heightA = entA.views[viewA].height.to("meter").value;
  469. const heightB = entB.views[viewB].height.to("meter").value;
  470. return heightA - heightB;
  471. });
  472. }
  473. function clearViewOptions() {
  474. const holder = document.querySelector("#options-view");
  475. holder.innerHTML = "";
  476. }
  477. // this is a crime against humanity, and also stolen from
  478. // stack overflow
  479. // https://stackoverflow.com/questions/38487569/click-through-png-image-only-if-clicked-coordinate-is-transparent
  480. const testCanvas = document.createElement("canvas");
  481. testCanvas.id = "test-canvas";
  482. const testCtx = testCanvas.getContext("2d");
  483. function testClick(event) {
  484. // oh my god I can't believe I'm doing this
  485. const target = event.target;
  486. if (navigator.userAgent.indexOf("Firefox") != -1) {
  487. clickDown(target.parentElement, event.clientX, event.clientY);
  488. return;
  489. }
  490. // Get click coordinates
  491. let w = target.width;
  492. let h = target.height;
  493. let ratioW = 1, ratioH = 1;
  494. // Limit the size of the canvas so that very large images don't cause problems)
  495. if (w > 1000) {
  496. ratioW = w / 1000;
  497. w /= ratioW;
  498. h /= ratioW;
  499. }
  500. if (h > 1000) {
  501. ratioH = h / 1000;
  502. w /= ratioH;
  503. h /= ratioH;
  504. }
  505. const ratio = ratioW * ratioH;
  506. var x = event.clientX - target.getBoundingClientRect().x,
  507. y = event.clientY - target.getBoundingClientRect().y,
  508. alpha;
  509. testCtx.canvas.width = w;
  510. testCtx.canvas.height = h;
  511. // Draw image to canvas
  512. // and read Alpha channel value
  513. testCtx.drawImage(target, 0, 0, w, h);
  514. alpha = testCtx.getImageData(Math.floor(x / ratio), Math.floor(y / ratio), 1, 1).data[3]; // [0]R [1]G [2]B [3]A
  515. // If pixel is transparent,
  516. // retrieve the element underneath and trigger it's click event
  517. if (alpha === 0) {
  518. const oldDisplay = target.style.display;
  519. target.style.display = "none";
  520. const newTarget = document.elementFromPoint(event.clientX, event.clientY);
  521. newTarget.dispatchEvent(new MouseEvent(event.type, {
  522. "clientX": event.clientX,
  523. "clientY": event.clientY
  524. }));
  525. target.style.display = oldDisplay;
  526. } else {
  527. clickDown(target.parentElement, event.clientX, event.clientY);
  528. }
  529. }
  530. function arrangeEntities(order) {
  531. let x = 0.1;
  532. order.forEach(key => {
  533. document.querySelector("#entity-" + key).dataset.x = x;
  534. x += 0.8 / (order.length - 1);
  535. });
  536. updateSizes();
  537. }
  538. function removeAllEntities() {
  539. Object.keys(entities).forEach(key => {
  540. removeEntity(document.querySelector("#entity-" + key));
  541. });
  542. }
  543. function clearAttribution() {
  544. document.querySelector("#options-attribution").style.display = "none";
  545. }
  546. function displayAttribution(file) {
  547. document.querySelector("#options-attribution").style.display = "inline";
  548. const authors = authorsOfFull(file);
  549. const owners = ownersOfFull(file);
  550. const source = sourceOf(file);
  551. const authorHolder = document.querySelector("#options-attribution-authors");
  552. const ownerHolder = document.querySelector("#options-attribution-owners");
  553. const sourceHolder = document.querySelector("#options-attribution-source");
  554. if (authors === []) {
  555. const div = document.createElement("div");
  556. div.innerText = "Unknown";
  557. authorHolder.innerHTML = "";
  558. authorHolder.appendChild(div);
  559. } else if (authors === undefined) {
  560. const div = document.createElement("div");
  561. div.innerText = "Not yet entered";
  562. authorHolder.innerHTML = "";
  563. authorHolder.appendChild(div);
  564. } else {
  565. authorHolder.innerHTML = "";
  566. const list = document.createElement("ul");
  567. authorHolder.appendChild(list);
  568. authors.forEach(author => {
  569. const authorEntry = document.createElement("li");
  570. const link = document.createElement("a");
  571. link.href = author.url;
  572. link.innerText = author.name;
  573. authorEntry.appendChild(link);
  574. list.appendChild(authorEntry);
  575. });
  576. }
  577. if (owners === []) {
  578. const div = document.createElement("div");
  579. div.innerText = "Unknown";
  580. ownerHolder.innerHTML = "";
  581. ownerHolder.appendChild(div);
  582. } else if (owners === undefined) {
  583. const div = document.createElement("div");
  584. div.innerText = "Not yet entered";
  585. ownerHolder.innerHTML = "";
  586. ownerHolder.appendChild(div);
  587. } else {
  588. ownerHolder.innerHTML = "";
  589. const list = document.createElement("ul");
  590. ownerHolder.appendChild(list);
  591. owners.forEach(owner => {
  592. const ownerEntry = document.createElement("li");
  593. const link = document.createElement("a");
  594. link.href = owner.url;
  595. link.innerText = owner.name;
  596. ownerEntry.appendChild(link);
  597. list.appendChild(ownerEntry);
  598. });
  599. }
  600. if (source === null) {
  601. const div = document.createElement("div");
  602. div.innerText = "No link";
  603. sourceHolder.innerHTML = "";
  604. sourceHolder.appendChild(div);
  605. } else if (source === undefined) {
  606. const div = document.createElement("div");
  607. div.innerText = "Not yet entered";
  608. sourceHolder.innerHTML = "";
  609. sourceHolder.appendChild(div);
  610. } else {
  611. sourceHolder.innerHTML = "";
  612. const link = document.createElement("a");
  613. link.style.display = "block";
  614. link.href = source;
  615. link.innerText = new URL(source).host;
  616. sourceHolder.appendChild(link);
  617. }
  618. }
  619. function removeEntity(element) {
  620. if (selected == element) {
  621. deselect();
  622. }
  623. delete entities[element.dataset.key];
  624. const bottomName = document.querySelector("#bottom-name-" + element.dataset.key);
  625. bottomName.parentElement.removeChild(bottomName);
  626. element.parentElement.removeChild(element);
  627. }
  628. function displayEntity(entity, view, x, y) {
  629. const box = document.createElement("div");
  630. box.classList.add("entity-box");
  631. const img = document.createElement("img");
  632. img.classList.add("entity-image");
  633. img.addEventListener("dragstart", e => {
  634. e.preventDefault();
  635. });
  636. const nameTag = document.createElement("div");
  637. nameTag.classList.add("entity-name");
  638. nameTag.innerText = entity.name;
  639. box.appendChild(img);
  640. box.appendChild(nameTag);
  641. const image = entity.views[view].image;
  642. img.src = image.source;
  643. displayAttribution(image.source);
  644. if (image.bottom !== undefined) {
  645. img.style.setProperty("--offset", ((-1 + image.bottom) * 100) + "%")
  646. } else {
  647. img.style.setProperty("--offset", ((-1) * 100) + "%")
  648. }
  649. box.dataset.x = x;
  650. box.dataset.y = y;
  651. img.addEventListener("mousedown", e => { testClick(e); e.stopPropagation() });
  652. img.addEventListener("touchstart", e => {
  653. const fakeEvent = {
  654. target: e.target,
  655. clientX: e.touches[0].clientX,
  656. clientY: e.touches[0].clientY
  657. };
  658. testClick(fakeEvent);
  659. });
  660. box.id = "entity-" + entityIndex;
  661. box.dataset.key = entityIndex;
  662. entity.view = view;
  663. entities[entityIndex] = entity;
  664. entity.index = entityIndex;
  665. const world = document.querySelector("#entities");
  666. world.appendChild(box);
  667. const bottomName = document.createElement("div");
  668. bottomName.classList.add("bottom-name");
  669. bottomName.id = "bottom-name-" + entityIndex;
  670. bottomName.innerText = entity.name;
  671. bottomName.addEventListener("click", () => select(box));
  672. world.appendChild(bottomName);
  673. entityIndex += 1;
  674. updateEntityElement(entity, box);
  675. if (config.autoFit) {
  676. fitWorld();
  677. }
  678. select(box);
  679. }
  680. window.onblur = function () {
  681. altHeld = false;
  682. shiftHeld = false;
  683. }
  684. window.onfocus = function () {
  685. window.dispatchEvent(new Event("keydown"));
  686. }
  687. function doSliderScale() {
  688. setWorldHeight(config.height, math.multiply(config.height, (9 + sliderScale) / 10));
  689. }
  690. function doSliderEntityScale() {
  691. if (selected) {
  692. const entity = entities[selected.dataset.key];
  693. entity.scale *= (9 + sliderEntityScale) / 10;
  694. updateSizes();
  695. updateEntityOptions(entity, entity.view);
  696. updateViewOptions(entity, entity.view);
  697. }
  698. }
  699. document.addEventListener("DOMContentLoaded", () => {
  700. prepareEntities();
  701. document.querySelector("#slider-scale").addEventListener("mousedown", e => {
  702. dragScaleHandle = setInterval(doSliderScale, 50);
  703. e.stopPropagation();
  704. });
  705. document.querySelector("#slider-scale").addEventListener("touchstart", e => {
  706. dragScaleHandle = setInterval(doSliderScale, 50);
  707. e.stopPropagation();
  708. });
  709. document.querySelector("#slider-scale").addEventListener("input", e => {
  710. const val = Number(e.target.value);
  711. if (val < 1) {
  712. sliderScale = (val + 1) / 2;
  713. } else {
  714. sliderScale = val;
  715. }
  716. });
  717. document.querySelector("#slider-scale").addEventListener("change", e => {
  718. clearInterval(dragScaleHandle);
  719. dragScaleHandle = null;
  720. e.target.value = 1;
  721. });
  722. document.querySelector("#slider-entity-scale").addEventListener("mousedown", e => {
  723. dragEntityScaleHandle = setInterval(doSliderEntityScale, 50);
  724. e.stopPropagation();
  725. });
  726. document.querySelector("#slider-entity-scale").addEventListener("touchstart", e => {
  727. dragEntityScaleHandle = setInterval(doSliderEntityScale, 50);
  728. e.stopPropagation();
  729. });
  730. document.querySelector("#slider-entity-scale").addEventListener("input", e => {
  731. const val = Number(e.target.value);
  732. if (val < 1) {
  733. sliderEntityScale = (val + 1) / 2;
  734. } else {
  735. sliderEntityScale = val;
  736. }
  737. });
  738. document.querySelector("#slider-entity-scale").addEventListener("change", e => {
  739. clearInterval(dragEntityScaleHandle);
  740. dragEntityScaleHandle = null;
  741. e.target.value = 1;
  742. });
  743. const sceneChoices = document.querySelector("#scene-choices");
  744. Object.entries(scenes).forEach(([id, scene]) => {
  745. const option = document.createElement("option");
  746. option.innerText = id;
  747. option.value = id;
  748. sceneChoices.appendChild(option);
  749. });
  750. document.querySelector("#load-scene").addEventListener("click", e => {
  751. const chosen = sceneChoices.value;
  752. removeAllEntities();
  753. scenes[chosen]();
  754. });
  755. entityX = document.querySelector("#entities").getBoundingClientRect().x;
  756. canvasWidth = document.querySelector("#display").clientWidth - 100;
  757. canvasHeight = document.querySelector("#display").clientHeight - 50;
  758. document.querySelector("#open-help").addEventListener("click", e => {
  759. document.querySelector("#help").classList.add("visible");
  760. });
  761. document.querySelector("#close-help").addEventListener("click", e => {
  762. document.querySelector("#help").classList.remove("visible");
  763. });
  764. const unitSelector = document.querySelector("#options-height-unit");
  765. unitChoices.length.forEach(lengthOption => {
  766. const option = document.createElement("option");
  767. option.innerText = lengthOption;
  768. option.value = lengthOption;
  769. if (lengthOption === "meters") {
  770. option.selected = true;
  771. }
  772. unitSelector.appendChild(option);
  773. });
  774. param = new URL(window.location.href).searchParams.get("scene");
  775. if (param === null)
  776. scenes["Demo"]();
  777. else {
  778. try {
  779. const data = JSON.parse(b64DecodeUnicode(param));
  780. if (data.entities === undefined) {
  781. return;
  782. }
  783. if (data.world === undefined) {
  784. return;
  785. }
  786. importScene(data);
  787. } catch (err) {
  788. console.error(err);
  789. scenes["Demo"]();
  790. // probably wasn't valid data
  791. }
  792. }
  793. fitWorld();
  794. document.querySelector("#world").addEventListener("wheel", e => {
  795. if (shiftHeld) {
  796. const dir = e.deltaY > 0 ? 0.9 : 1.1;
  797. if (selected) {
  798. const entity = entities[selected.dataset.key];
  799. entity.views[entity.view].height = math.multiply(entity.views[entity.view].height, dir);
  800. updateEntityOptions(entity, entity.view);
  801. updateViewOptions(entity, entity.view);
  802. updateSizes();
  803. }
  804. } else {
  805. const dir = e.deltaY < 0 ? 0.9 : 1.1;
  806. setWorldHeight(config.height, math.multiply(config.height, dir));
  807. updateWorldOptions();
  808. }
  809. checkFitWorld();
  810. })
  811. document.querySelector("body").appendChild(testCtx.canvas);
  812. updateSizes();
  813. document.querySelector("#options-height-value").addEventListener("input", e => {
  814. updateWorldHeight();
  815. })
  816. unitSelector.addEventListener("input", e => {
  817. checkFitWorld();
  818. updateWorldHeight();
  819. })
  820. world.addEventListener("mousedown", e => deselect());
  821. document.querySelector("#display").addEventListener("mousedown", deselect);
  822. document.addEventListener("mouseup", e => clickUp(e));
  823. document.addEventListener("touchend", e => {
  824. const fakeEvent = {
  825. target: e.target,
  826. clientX: e.changedTouches[0].clientX,
  827. clientY: e.changedTouches[0].clientY
  828. };
  829. clickUp(fakeEvent);
  830. });
  831. document.querySelector("#entity-view").addEventListener("input", e => {
  832. const entity = entities[selected.dataset.key];
  833. entity.view = e.target.value;
  834. const image = entities[selected.dataset.key].views[e.target.value].image;
  835. selected.querySelector(".entity-image").src = image.source;
  836. displayAttribution(image.source);
  837. if (image.bottom !== undefined) {
  838. selected.querySelector(".entity-image").style.setProperty("--offset", ((-1 + image.bottom) * 100) + "%")
  839. } else {
  840. selected.querySelector(".entity-image").style.setProperty("--offset", ((-1) * 100) + "%")
  841. }
  842. updateSizes();
  843. updateEntityOptions(entities[selected.dataset.key], e.target.value);
  844. updateViewOptions(entities[selected.dataset.key], e.target.value);
  845. });
  846. clearViewList();
  847. document.querySelector("#menu-clear").addEventListener("click", e => {
  848. removeAllEntities();
  849. });
  850. document.querySelector("#menu-order-height").addEventListener("click", e => {
  851. const order = Object.keys(entities).sort((a, b) => {
  852. const entA = entities[a];
  853. const entB = entities[b];
  854. const viewA = entA.view;
  855. const viewB = entB.view;
  856. const heightA = entA.views[viewA].height.to("meter").value;
  857. const heightB = entB.views[viewB].height.to("meter").value;
  858. return heightA - heightB;
  859. });
  860. arrangeEntities(order);
  861. });
  862. document.querySelector("#options-world-fit").addEventListener("click", fitWorld);
  863. document.querySelector("#options-world-autofit").addEventListener("input", e => {
  864. config.autoFit = e.target.checked;
  865. if (config.autoFit) {
  866. fitWorld();
  867. }
  868. });
  869. document.querySelector("#options-world-autofit-mode").addEventListener("input", e => {
  870. config.autoFitMode = e.target.value;
  871. if (config.autoFit) {
  872. fitWorld();
  873. }
  874. })
  875. document.addEventListener("keydown", e => {
  876. if (e.key == "Delete") {
  877. if (selected) {
  878. removeEntity(selected);
  879. selected = null;
  880. }
  881. }
  882. })
  883. document.addEventListener("keydown", e => {
  884. if (e.key == "Shift") {
  885. shiftHeld = true;
  886. e.preventDefault();
  887. } else if (e.key == "Alt") {
  888. altHeld = true;
  889. e.preventDefault();
  890. }
  891. });
  892. document.addEventListener("keyup", e => {
  893. if (e.key == "Shift") {
  894. shiftHeld = false;
  895. e.preventDefault();
  896. } else if (e.key == "Alt") {
  897. altHeld = false;
  898. e.preventDefault();
  899. }
  900. });
  901. document.addEventListener("paste", e => {
  902. try {
  903. const data = JSON.parse(e.clipboardData.getData("text"));
  904. if (data.entities === undefined) {
  905. return;
  906. }
  907. if (data.world === undefined) {
  908. return;
  909. }
  910. importScene(data);
  911. } catch (err) {
  912. console.error(err);
  913. // probably wasn't valid data
  914. }
  915. });
  916. document.querySelector("#menu-permalink").addEventListener("click", e => {
  917. linkScene();
  918. });
  919. document.querySelector("#menu-export").addEventListener("click", e => {
  920. copyScene();
  921. });
  922. document.querySelector("#menu-save").addEventListener("click", e => {
  923. saveScene();
  924. });
  925. document.querySelector("#menu-load").addEventListener("click", e => {
  926. loadScene();
  927. });
  928. });
  929. function prepareEntities() {
  930. availableEntities["buildings"] = makeBuildings();
  931. availableEntities["landmarks"] = makeLandmarks();
  932. availableEntities["characters"] = makeCharacters();
  933. availableEntities["objects"] = makeObjects();
  934. availableEntities["naturals"] = makeNaturals();
  935. availableEntities["vehicles"] = makeVehicles();
  936. availableEntities["cities"] = makeCities();
  937. availableEntities["pokemon"] = makePokemon();
  938. availableEntities["characters"].sort((x, y) => {
  939. return x.name < y.name ? -1 : 1
  940. });
  941. const holder = document.querySelector("#spawners");
  942. const categorySelect = document.createElement("select");
  943. categorySelect.id = "category-picker";
  944. holder.appendChild(categorySelect);
  945. Object.entries(availableEntities).forEach(([category, entityList]) => {
  946. const select = document.createElement("select");
  947. select.id = "create-entity-" + category;
  948. for (let i = 0; i < entityList.length; i++) {
  949. const entity = entityList[i];
  950. const option = document.createElement("option");
  951. option.value = i;
  952. option.innerText = entity.name;
  953. select.appendChild(option);
  954. availableEntitiesByName[entity.name] = entity;
  955. };
  956. const button = document.createElement("button");
  957. button.id = "create-entity-" + category + "-button";
  958. button.innerText = "Create";
  959. button.addEventListener("click", e => {
  960. const newEntity = entityList[select.value].constructor()
  961. displayEntity(newEntity, newEntity.defaultView, 0.5, 1);
  962. });
  963. const categoryOption = document.createElement("option");
  964. categoryOption.value = category
  965. categoryOption.innerText = category;
  966. if (category == "characters") {
  967. categoryOption.selected = true;
  968. select.classList.add("category-visible");
  969. button.classList.add("category-visible");
  970. }
  971. categorySelect.appendChild(categoryOption);
  972. holder.appendChild(select);
  973. holder.appendChild(button);
  974. });
  975. categorySelect.addEventListener("input", e => {
  976. const oldSelect = document.querySelector("select.category-visible");
  977. oldSelect.classList.remove("category-visible");
  978. const oldButton = document.querySelector("button.category-visible");
  979. oldButton.classList.remove("category-visible");
  980. const newSelect = document.querySelector("#create-entity-" + e.target.value);
  981. newSelect.classList.add("category-visible");
  982. const newButton = document.querySelector("#create-entity-" + e.target.value + "-button");
  983. newButton.classList.add("category-visible");
  984. });
  985. }
  986. window.addEventListener("resize", () => {
  987. entityX = document.querySelector("#entities").getBoundingClientRect().x;
  988. canvasWidth = document.querySelector("#display").clientWidth - 100;
  989. canvasHeight = document.querySelector("#display").clientHeight - 50;
  990. updateSizes();
  991. })
  992. document.addEventListener("mousemove", (e) => {
  993. if (clicked) {
  994. const position = snapRel(abs2rel({ x: e.clientX - dragOffsetX, y: e.clientY - dragOffsetY }));
  995. clicked.dataset.x = position.x;
  996. clicked.dataset.y = position.y;
  997. updateEntityElement(entities[clicked.dataset.key], clicked);
  998. if (hoveringInDeleteArea(e)) {
  999. document.querySelector("#menubar").classList.add("hover-delete");
  1000. } else {
  1001. document.querySelector("#menubar").classList.remove("hover-delete");
  1002. }
  1003. }
  1004. });
  1005. document.addEventListener("touchmove", (e) => {
  1006. if (clicked) {
  1007. e.preventDefault();
  1008. let x = e.touches[0].clientX;
  1009. let y = e.touches[0].clientY;
  1010. const position = snapRel(abs2rel({ x: x - dragOffsetX, y: y - dragOffsetY }));
  1011. clicked.dataset.x = position.x;
  1012. clicked.dataset.y = position.y;
  1013. updateEntityElement(entities[clicked.dataset.key], clicked);
  1014. // what a hack
  1015. // I should centralize this 'fake event' creation...
  1016. if (hoveringInDeleteArea({ clientY: y })) {
  1017. document.querySelector("#menubar").classList.add("hover-delete");
  1018. } else {
  1019. document.querySelector("#menubar").classList.remove("hover-delete");
  1020. }
  1021. }
  1022. }, { passive: false });
  1023. function checkFitWorld() {
  1024. if (config.autoFit) {
  1025. fitWorld();
  1026. }
  1027. }
  1028. const fitModes = {
  1029. "max": {
  1030. start: 0,
  1031. binop: math.max,
  1032. final: (total, count) => total
  1033. },
  1034. "arithmetic mean": {
  1035. start: 0,
  1036. binop: math.add,
  1037. final: (total, count) => total / count
  1038. },
  1039. "geometric mean": {
  1040. start: 1,
  1041. binop: math.multiply,
  1042. final: (total, count) => math.pow(total, 1 / count)
  1043. }
  1044. }
  1045. function fitWorld() {
  1046. const fitMode = fitModes[config.autoFitMode]
  1047. let max = fitMode.start
  1048. let count = 0;
  1049. Object.entries(entities).forEach(([key, entity]) => {
  1050. const view = entity.view;
  1051. max = fitMode.binop(max, entity.views[view].height.toNumber("meter"));
  1052. count += 1;
  1053. });
  1054. max = fitMode.final(max, count)
  1055. max = math.unit(max, "meter")
  1056. setWorldHeight(config.height, math.multiply(max, 1.1));
  1057. }
  1058. function updateWorldHeight() {
  1059. const unit = document.querySelector("#options-height-unit").value;
  1060. const value = Math.max(0.000000001, document.querySelector("#options-height-value").value);
  1061. const oldHeight = config.height;
  1062. setWorldHeight(oldHeight, math.unit(value, unit));
  1063. }
  1064. function setWorldHeight(oldHeight, newHeight) {
  1065. config.height = newHeight.to(document.querySelector("#options-height-unit").value)
  1066. const unit = document.querySelector("#options-height-unit").value;
  1067. document.querySelector("#options-height-value").value = config.height.toNumber(unit);
  1068. Object.entries(entities).forEach(([key, entity]) => {
  1069. const element = document.querySelector("#entity-" + key);
  1070. let newPosition;
  1071. if (!altHeld) {
  1072. newPosition = adjustAbs({ x: element.dataset.x, y: element.dataset.y }, oldHeight, config.height);
  1073. } else {
  1074. newPosition = { x: element.dataset.x, y: element.dataset.y };
  1075. }
  1076. element.dataset.x = newPosition.x;
  1077. element.dataset.y = newPosition.y;
  1078. });
  1079. updateSizes();
  1080. }
  1081. function loadScene() {
  1082. try {
  1083. const data = JSON.parse(localStorage.getItem("macrovision-save"));
  1084. importScene(data);
  1085. } catch (err) {
  1086. alert("Something went wrong while loading (maybe you didn't have anything saved. Check the F12 console for the error.")
  1087. console.error(err);
  1088. }
  1089. }
  1090. function saveScene() {
  1091. try {
  1092. const string = JSON.stringify(exportScene());
  1093. localStorage.setItem("macrovision-save", string);
  1094. } catch (err) {
  1095. alert("Something went wrong while saving (maybe I don't have localStorage permissions, or exporting failed). Check the F12 console for the error.")
  1096. console.error(err);
  1097. }
  1098. }
  1099. function exportScene() {
  1100. const results = {};
  1101. results.entities = [];
  1102. Object.entries(entities).forEach(([key, entity]) => {
  1103. const element = document.querySelector("#entity-" + key);
  1104. results.entities.push({
  1105. name: entity.identifier,
  1106. scale: entity.scale,
  1107. view: entity.view,
  1108. x: element.dataset.x,
  1109. y: element.dataset.y
  1110. });
  1111. });
  1112. const unit = document.querySelector("#options-height-unit").value;
  1113. results.world = {
  1114. height: config.height.toNumber(unit),
  1115. unit: unit
  1116. }
  1117. return results;
  1118. }
  1119. // btoa doesn't like anything that isn't ASCII
  1120. // great
  1121. // thanks to https://stackoverflow.com/questions/30106476/using-javascripts-atob-to-decode-base64-doesnt-properly-decode-utf-8-strings
  1122. // for providing an alternative
  1123. function b64EncodeUnicode(str) {
  1124. // first we use encodeURIComponent to get percent-encoded UTF-8,
  1125. // then we convert the percent encodings into raw bytes which
  1126. // can be fed into btoa.
  1127. return btoa(encodeURIComponent(str).replace(/%([0-9A-F]{2})/g,
  1128. function toSolidBytes(match, p1) {
  1129. return String.fromCharCode('0x' + p1);
  1130. }));
  1131. }
  1132. function b64DecodeUnicode(str) {
  1133. // Going backwards: from bytestream, to percent-encoding, to original string.
  1134. return decodeURIComponent(atob(str).split('').map(function(c) {
  1135. return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
  1136. }).join(''));
  1137. }
  1138. function linkScene() {
  1139. loc = new URL(window.location);
  1140. window.location = loc.protocol + "//" + loc.host + loc.pathname + "?scene=" + b64EncodeUnicode(JSON.stringify(exportScene()));
  1141. }
  1142. function copyScene() {
  1143. const results = exportScene();
  1144. navigator.clipboard.writeText(JSON.stringify(results))
  1145. alert("Scene copied to clipboard. Paste text into the page to load the scene.");
  1146. }
  1147. // TODO - don't just search through every single entity
  1148. // probably just have a way to do lookups directly
  1149. function findEntity(name) {
  1150. return availableEntitiesByName[name];
  1151. }
  1152. function importScene(data) {
  1153. removeAllEntities();
  1154. data.entities.forEach(entityInfo => {
  1155. const entity = findEntity(entityInfo.name).constructor();
  1156. entity.scale = entityInfo.scale
  1157. displayEntity(entity, entityInfo.view, entityInfo.x, entityInfo.y);
  1158. });
  1159. config.height = math.unit(data.world.height, data.world.unit);
  1160. document.querySelector("#options-height-unit").value = data.world.unit;
  1161. updateSizes();
  1162. }