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

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