less copy protection, more size visualization
Nie możesz wybrać więcej, niż 25 tematów Tematy muszą się zaczynać od litery lub cyfry, mogą zawierać myślniki ('-') i mogą mieć do 35 znaków.
 
 
 

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