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.
 
 
 

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