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.
 
 
 

1515 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 pixels = math.divide(entity.views[view].height, config.height) * (canvasHeight - 50);
  94. const bonus = (entity.views[view].image.extra ? entity.views[view].image.extra : 1);
  95. element.style.setProperty("--height", pixels * bonus + "px");
  96. element.style.setProperty("--extra", pixels * bonus - pixels + "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. if (author.url) {
  589. const link = document.createElement("a");
  590. link.href = author.url;
  591. link.innerText = author.name;
  592. authorEntry.appendChild(link);
  593. } else {
  594. const div = document.createElement("div");
  595. div.innerText = author.name;
  596. authorEntry.appendChild(div);
  597. }
  598. list.appendChild(authorEntry);
  599. });
  600. }
  601. if (owners === []) {
  602. const div = document.createElement("div");
  603. div.innerText = "Unknown";
  604. ownerHolder.innerHTML = "";
  605. ownerHolder.appendChild(div);
  606. } else if (owners === undefined) {
  607. const div = document.createElement("div");
  608. div.innerText = "Not yet entered";
  609. ownerHolder.innerHTML = "";
  610. ownerHolder.appendChild(div);
  611. } else {
  612. ownerHolder.innerHTML = "";
  613. const list = document.createElement("ul");
  614. ownerHolder.appendChild(list);
  615. owners.forEach(owner => {
  616. const ownerEntry = document.createElement("li");
  617. if (owner.url) {
  618. const link = document.createElement("a");
  619. link.href = owner.url;
  620. link.innerText = owner.name;
  621. ownerEntry.appendChild(link);
  622. } else {
  623. const div = document.createElement("div");
  624. div.innerText = owner.name;
  625. ownerEntry.appendChild(div);
  626. }
  627. list.appendChild(ownerEntry);
  628. });
  629. }
  630. if (source === null) {
  631. const div = document.createElement("div");
  632. div.innerText = "No link";
  633. sourceHolder.innerHTML = "";
  634. sourceHolder.appendChild(div);
  635. } else if (source === undefined) {
  636. const div = document.createElement("div");
  637. div.innerText = "Not yet entered";
  638. sourceHolder.innerHTML = "";
  639. sourceHolder.appendChild(div);
  640. } else {
  641. sourceHolder.innerHTML = "";
  642. const link = document.createElement("a");
  643. link.style.display = "block";
  644. link.href = source;
  645. link.innerText = new URL(source).host;
  646. sourceHolder.appendChild(link);
  647. }
  648. }
  649. function removeEntity(element) {
  650. if (selected == element) {
  651. deselect();
  652. }
  653. delete entities[element.dataset.key];
  654. const bottomName = document.querySelector("#bottom-name-" + element.dataset.key);
  655. bottomName.parentElement.removeChild(bottomName);
  656. element.parentElement.removeChild(element);
  657. }
  658. function displayEntity(entity, view, x, y) {
  659. const box = document.createElement("div");
  660. box.classList.add("entity-box");
  661. const img = document.createElement("img");
  662. img.classList.add("entity-image");
  663. img.addEventListener("dragstart", e => {
  664. e.preventDefault();
  665. });
  666. const nameTag = document.createElement("div");
  667. nameTag.classList.add("entity-name");
  668. nameTag.innerText = entity.name;
  669. box.appendChild(img);
  670. box.appendChild(nameTag);
  671. const image = entity.views[view].image;
  672. img.src = image.source;
  673. displayAttribution(image.source);
  674. if (image.bottom !== undefined) {
  675. img.style.setProperty("--offset", ((-1 + image.bottom) * 100) + "%")
  676. } else {
  677. img.style.setProperty("--offset", ((-1) * 100) + "%")
  678. }
  679. box.dataset.x = x;
  680. box.dataset.y = y;
  681. img.addEventListener("mousedown", e => { testClick(e); e.stopPropagation() });
  682. img.addEventListener("touchstart", e => {
  683. const fakeEvent = {
  684. target: e.target,
  685. clientX: e.touches[0].clientX,
  686. clientY: e.touches[0].clientY
  687. };
  688. testClick(fakeEvent);
  689. });
  690. box.id = "entity-" + entityIndex;
  691. box.dataset.key = entityIndex;
  692. entity.view = view;
  693. entity.priority = 0;
  694. entities[entityIndex] = entity;
  695. entity.index = entityIndex;
  696. const world = document.querySelector("#entities");
  697. world.appendChild(box);
  698. const bottomName = document.createElement("div");
  699. bottomName.classList.add("bottom-name");
  700. bottomName.id = "bottom-name-" + entityIndex;
  701. bottomName.innerText = entity.name;
  702. bottomName.addEventListener("click", () => select(box));
  703. world.appendChild(bottomName);
  704. entityIndex += 1;
  705. updateEntityElement(entity, box);
  706. if (config.autoFit) {
  707. fitWorld();
  708. }
  709. select(box);
  710. }
  711. window.onblur = function () {
  712. altHeld = false;
  713. shiftHeld = false;
  714. }
  715. window.onfocus = function () {
  716. window.dispatchEvent(new Event("keydown"));
  717. }
  718. function doSliderScale() {
  719. setWorldHeight(config.height, math.multiply(config.height, (9 + sliderScale) / 10));
  720. }
  721. function doSliderEntityScale() {
  722. if (selected) {
  723. const entity = entities[selected.dataset.key];
  724. entity.scale *= (9 + sliderEntityScale) / 10;
  725. updateSizes();
  726. updateEntityOptions(entity, entity.view);
  727. updateViewOptions(entity, entity.view);
  728. }
  729. }
  730. document.addEventListener("DOMContentLoaded", () => {
  731. prepareEntities();
  732. document.querySelector("#options-order-forward").addEventListener("click", e => {
  733. if (selected) {
  734. entities[selected.dataset.key].priority += 1;
  735. }
  736. document.querySelector("#options-order-display").innerText = entities[selected.dataset.key].priority;
  737. updateSizes();
  738. });
  739. document.querySelector("#options-order-back").addEventListener("click", e => {
  740. if (selected) {
  741. entities[selected.dataset.key].priority -= 1;
  742. }
  743. document.querySelector("#options-order-display").innerText = entities[selected.dataset.key].priority;
  744. updateSizes();
  745. });
  746. document.querySelector("#slider-scale").addEventListener("mousedown", e => {
  747. dragScaleHandle = setInterval(doSliderScale, 50);
  748. e.stopPropagation();
  749. });
  750. document.querySelector("#slider-scale").addEventListener("touchstart", e => {
  751. dragScaleHandle = setInterval(doSliderScale, 50);
  752. e.stopPropagation();
  753. });
  754. document.querySelector("#slider-scale").addEventListener("input", e => {
  755. const val = Number(e.target.value);
  756. if (val < 1) {
  757. sliderScale = (val + 1) / 2;
  758. } else {
  759. sliderScale = val;
  760. }
  761. });
  762. document.querySelector("#slider-scale").addEventListener("change", e => {
  763. clearInterval(dragScaleHandle);
  764. dragScaleHandle = null;
  765. e.target.value = 1;
  766. });
  767. document.querySelector("#slider-entity-scale").addEventListener("mousedown", e => {
  768. dragEntityScaleHandle = setInterval(doSliderEntityScale, 50);
  769. e.stopPropagation();
  770. });
  771. document.querySelector("#slider-entity-scale").addEventListener("touchstart", e => {
  772. dragEntityScaleHandle = setInterval(doSliderEntityScale, 50);
  773. e.stopPropagation();
  774. });
  775. document.querySelector("#slider-entity-scale").addEventListener("input", e => {
  776. const val = Number(e.target.value);
  777. if (val < 1) {
  778. sliderEntityScale = (val + 1) / 2;
  779. } else {
  780. sliderEntityScale = val;
  781. }
  782. });
  783. document.querySelector("#slider-entity-scale").addEventListener("change", e => {
  784. clearInterval(dragEntityScaleHandle);
  785. dragEntityScaleHandle = null;
  786. e.target.value = 1;
  787. });
  788. const sceneChoices = document.querySelector("#scene-choices");
  789. Object.entries(scenes).forEach(([id, scene]) => {
  790. const option = document.createElement("option");
  791. option.innerText = id;
  792. option.value = id;
  793. sceneChoices.appendChild(option);
  794. });
  795. document.querySelector("#load-scene").addEventListener("click", e => {
  796. const chosen = sceneChoices.value;
  797. removeAllEntities();
  798. scenes[chosen]();
  799. });
  800. entityX = document.querySelector("#entities").getBoundingClientRect().x;
  801. canvasWidth = document.querySelector("#display").clientWidth - 100;
  802. canvasHeight = document.querySelector("#display").clientHeight - 50;
  803. document.querySelector("#open-help").addEventListener("click", e => {
  804. document.querySelector("#help").classList.add("visible");
  805. });
  806. document.querySelector("#close-help").addEventListener("click", e => {
  807. document.querySelector("#help").classList.remove("visible");
  808. });
  809. const unitSelector = document.querySelector("#options-height-unit");
  810. unitChoices.length.forEach(lengthOption => {
  811. const option = document.createElement("option");
  812. option.innerText = lengthOption;
  813. option.value = lengthOption;
  814. if (lengthOption === "meters") {
  815. option.selected = true;
  816. }
  817. unitSelector.appendChild(option);
  818. });
  819. param = new URL(window.location.href).searchParams.get("scene");
  820. if (param === null)
  821. scenes["Demo"]();
  822. else {
  823. try {
  824. const data = JSON.parse(b64DecodeUnicode(param));
  825. if (data.entities === undefined) {
  826. return;
  827. }
  828. if (data.world === undefined) {
  829. return;
  830. }
  831. importScene(data);
  832. } catch (err) {
  833. console.error(err);
  834. scenes["Demo"]();
  835. // probably wasn't valid data
  836. }
  837. }
  838. fitWorld();
  839. document.querySelector("#world").addEventListener("wheel", e => {
  840. if (shiftHeld) {
  841. const dir = e.deltaY > 0 ? 0.9 : 1.1;
  842. if (selected) {
  843. const entity = entities[selected.dataset.key];
  844. entity.views[entity.view].height = math.multiply(entity.views[entity.view].height, dir);
  845. updateEntityOptions(entity, entity.view);
  846. updateViewOptions(entity, entity.view);
  847. updateSizes();
  848. }
  849. } else {
  850. const dir = e.deltaY < 0 ? 0.9 : 1.1;
  851. setWorldHeight(config.height, math.multiply(config.height, dir));
  852. updateWorldOptions();
  853. }
  854. checkFitWorld();
  855. })
  856. document.querySelector("body").appendChild(testCtx.canvas);
  857. updateSizes();
  858. document.querySelector("#options-height-value").addEventListener("input", e => {
  859. updateWorldHeight();
  860. })
  861. unitSelector.addEventListener("input", e => {
  862. checkFitWorld();
  863. updateWorldHeight();
  864. })
  865. world.addEventListener("mousedown", e => deselect());
  866. document.querySelector("#display").addEventListener("mousedown", deselect);
  867. document.addEventListener("mouseup", e => clickUp(e));
  868. document.addEventListener("touchend", e => {
  869. const fakeEvent = {
  870. target: e.target,
  871. clientX: e.changedTouches[0].clientX,
  872. clientY: e.changedTouches[0].clientY
  873. };
  874. clickUp(fakeEvent);
  875. });
  876. document.querySelector("#entity-view").addEventListener("input", e => {
  877. const entity = entities[selected.dataset.key];
  878. entity.view = e.target.value;
  879. const image = entities[selected.dataset.key].views[e.target.value].image;
  880. selected.querySelector(".entity-image").src = image.source;
  881. displayAttribution(image.source);
  882. if (image.bottom !== undefined) {
  883. selected.querySelector(".entity-image").style.setProperty("--offset", ((-1 + image.bottom) * 100) + "%")
  884. } else {
  885. selected.querySelector(".entity-image").style.setProperty("--offset", ((-1) * 100) + "%")
  886. }
  887. updateSizes();
  888. updateEntityOptions(entities[selected.dataset.key], e.target.value);
  889. updateViewOptions(entities[selected.dataset.key], e.target.value);
  890. });
  891. clearViewList();
  892. document.querySelector("#menu-clear").addEventListener("click", e => {
  893. removeAllEntities();
  894. });
  895. document.querySelector("#menu-order-height").addEventListener("click", e => {
  896. const order = Object.keys(entities).sort((a, b) => {
  897. const entA = entities[a];
  898. const entB = entities[b];
  899. const viewA = entA.view;
  900. const viewB = entB.view;
  901. const heightA = entA.views[viewA].height.to("meter").value;
  902. const heightB = entB.views[viewB].height.to("meter").value;
  903. return heightA - heightB;
  904. });
  905. arrangeEntities(order);
  906. });
  907. document.querySelector("#options-world-fit").addEventListener("click", () => fitWorld(true));
  908. document.querySelector("#options-world-autofit").addEventListener("input", e => {
  909. config.autoFit = e.target.checked;
  910. if (config.autoFit) {
  911. fitWorld();
  912. }
  913. });
  914. document.querySelector("#options-world-autofit-mode").addEventListener("input", e => {
  915. config.autoFitMode = e.target.value;
  916. if (config.autoFit) {
  917. fitWorld();
  918. }
  919. })
  920. document.addEventListener("keydown", e => {
  921. if (e.key == "Delete") {
  922. if (selected) {
  923. removeEntity(selected);
  924. selected = null;
  925. }
  926. }
  927. })
  928. document.addEventListener("keydown", e => {
  929. if (e.key == "Shift") {
  930. shiftHeld = true;
  931. e.preventDefault();
  932. } else if (e.key == "Alt") {
  933. altHeld = true;
  934. e.preventDefault();
  935. }
  936. });
  937. document.addEventListener("keyup", e => {
  938. if (e.key == "Shift") {
  939. shiftHeld = false;
  940. e.preventDefault();
  941. } else if (e.key == "Alt") {
  942. altHeld = false;
  943. e.preventDefault();
  944. }
  945. });
  946. document.addEventListener("paste", e => {
  947. try {
  948. const data = JSON.parse(e.clipboardData.getData("text"));
  949. if (data.entities === undefined) {
  950. return;
  951. }
  952. if (data.world === undefined) {
  953. return;
  954. }
  955. importScene(data);
  956. } catch (err) {
  957. console.error(err);
  958. // probably wasn't valid data
  959. }
  960. });
  961. document.querySelector("#menu-permalink").addEventListener("click", e => {
  962. linkScene();
  963. });
  964. document.querySelector("#menu-export").addEventListener("click", e => {
  965. copyScene();
  966. });
  967. document.querySelector("#menu-save").addEventListener("click", e => {
  968. saveScene();
  969. });
  970. document.querySelector("#menu-load").addEventListener("click", e => {
  971. loadScene();
  972. });
  973. });
  974. function prepareEntities() {
  975. availableEntities["buildings"] = makeBuildings();
  976. availableEntities["landmarks"] = makeLandmarks();
  977. availableEntities["characters"] = makeCharacters();
  978. availableEntities["objects"] = makeObjects();
  979. availableEntities["naturals"] = makeNaturals();
  980. availableEntities["vehicles"] = makeVehicles();
  981. availableEntities["cities"] = makeCities();
  982. availableEntities["pokemon"] = makePokemon();
  983. availableEntities["characters"].sort((x, y) => {
  984. return x.name < y.name ? -1 : 1
  985. });
  986. const holder = document.querySelector("#spawners");
  987. const categorySelect = document.createElement("select");
  988. categorySelect.id = "category-picker";
  989. holder.appendChild(categorySelect);
  990. Object.entries(availableEntities).forEach(([category, entityList]) => {
  991. const select = document.createElement("select");
  992. select.id = "create-entity-" + category;
  993. for (let i = 0; i < entityList.length; i++) {
  994. const entity = entityList[i];
  995. const option = document.createElement("option");
  996. option.value = i;
  997. option.innerText = entity.name;
  998. select.appendChild(option);
  999. availableEntitiesByName[entity.name] = entity;
  1000. };
  1001. const button = document.createElement("button");
  1002. button.id = "create-entity-" + category + "-button";
  1003. button.innerText = "Create";
  1004. button.addEventListener("click", e => {
  1005. const newEntity = entityList[select.value].constructor()
  1006. displayEntity(newEntity, newEntity.defaultView, 0.5, 1);
  1007. });
  1008. const categoryOption = document.createElement("option");
  1009. categoryOption.value = category
  1010. categoryOption.innerText = category;
  1011. if (category == "characters") {
  1012. categoryOption.selected = true;
  1013. select.classList.add("category-visible");
  1014. button.classList.add("category-visible");
  1015. }
  1016. categorySelect.appendChild(categoryOption);
  1017. holder.appendChild(select);
  1018. holder.appendChild(button);
  1019. });
  1020. categorySelect.addEventListener("input", e => {
  1021. const oldSelect = document.querySelector("select.category-visible");
  1022. oldSelect.classList.remove("category-visible");
  1023. const oldButton = document.querySelector("button.category-visible");
  1024. oldButton.classList.remove("category-visible");
  1025. const newSelect = document.querySelector("#create-entity-" + e.target.value);
  1026. newSelect.classList.add("category-visible");
  1027. const newButton = document.querySelector("#create-entity-" + e.target.value + "-button");
  1028. newButton.classList.add("category-visible");
  1029. });
  1030. }
  1031. window.addEventListener("resize", () => {
  1032. entityX = document.querySelector("#entities").getBoundingClientRect().x;
  1033. canvasWidth = document.querySelector("#display").clientWidth - 100;
  1034. canvasHeight = document.querySelector("#display").clientHeight - 50;
  1035. updateSizes();
  1036. })
  1037. document.addEventListener("mousemove", (e) => {
  1038. if (clicked) {
  1039. const position = snapRel(abs2rel({ x: e.clientX - dragOffsetX, y: e.clientY - dragOffsetY }));
  1040. clicked.dataset.x = position.x;
  1041. clicked.dataset.y = position.y;
  1042. updateEntityElement(entities[clicked.dataset.key], clicked);
  1043. if (hoveringInDeleteArea(e)) {
  1044. document.querySelector("#menubar").classList.add("hover-delete");
  1045. } else {
  1046. document.querySelector("#menubar").classList.remove("hover-delete");
  1047. }
  1048. }
  1049. });
  1050. document.addEventListener("touchmove", (e) => {
  1051. if (clicked) {
  1052. e.preventDefault();
  1053. let x = e.touches[0].clientX;
  1054. let y = e.touches[0].clientY;
  1055. const position = snapRel(abs2rel({ x: x - dragOffsetX, y: y - dragOffsetY }));
  1056. clicked.dataset.x = position.x;
  1057. clicked.dataset.y = position.y;
  1058. updateEntityElement(entities[clicked.dataset.key], clicked);
  1059. // what a hack
  1060. // I should centralize this 'fake event' creation...
  1061. if (hoveringInDeleteArea({ clientY: y })) {
  1062. document.querySelector("#menubar").classList.add("hover-delete");
  1063. } else {
  1064. document.querySelector("#menubar").classList.remove("hover-delete");
  1065. }
  1066. }
  1067. }, { passive: false });
  1068. function checkFitWorld() {
  1069. if (config.autoFit) {
  1070. fitWorld();
  1071. }
  1072. }
  1073. const fitModes = {
  1074. "max": {
  1075. start: 0,
  1076. binop: math.max,
  1077. final: (total, count) => total
  1078. },
  1079. "arithmetic mean": {
  1080. start: 0,
  1081. binop: math.add,
  1082. final: (total, count) => total / count
  1083. },
  1084. "geometric mean": {
  1085. start: 1,
  1086. binop: math.multiply,
  1087. final: (total, count) => math.pow(total, 1 / count)
  1088. }
  1089. }
  1090. function fitWorld(manual=false) {
  1091. const fitMode = fitModes[config.autoFitMode]
  1092. let max = fitMode.start
  1093. let count = 0;
  1094. Object.entries(entities).forEach(([key, entity]) => {
  1095. const view = entity.view;
  1096. let extra = entity.views[view].image.extra;
  1097. extra = extra === undefined ? 1 : extra;
  1098. let bottom = entity.views[view].image.bottom;
  1099. bottom = bottom === undefined ? 0 : bottom;
  1100. max = fitMode.binop(max, math.multiply(extra * (1 - bottom), entity.views[view].height.toNumber("meter")));
  1101. count += 1;
  1102. });
  1103. max = fitMode.final(max, count)
  1104. max = math.unit(max, "meter")
  1105. if (manual)
  1106. altHeld = true;
  1107. setWorldHeight(config.height, math.multiply(max, 1.1));
  1108. if (manual)
  1109. altHeld = false;
  1110. }
  1111. function updateWorldHeight() {
  1112. const unit = document.querySelector("#options-height-unit").value;
  1113. const value = Math.max(0.000000001, document.querySelector("#options-height-value").value);
  1114. const oldHeight = config.height;
  1115. setWorldHeight(oldHeight, math.unit(value, unit));
  1116. }
  1117. function setWorldHeight(oldHeight, newHeight) {
  1118. config.height = newHeight.to(document.querySelector("#options-height-unit").value)
  1119. const unit = document.querySelector("#options-height-unit").value;
  1120. document.querySelector("#options-height-value").value = config.height.toNumber(unit);
  1121. Object.entries(entities).forEach(([key, entity]) => {
  1122. const element = document.querySelector("#entity-" + key);
  1123. let newPosition;
  1124. if (!altHeld) {
  1125. newPosition = adjustAbs({ x: element.dataset.x, y: element.dataset.y }, oldHeight, config.height);
  1126. } else {
  1127. newPosition = { x: element.dataset.x, y: element.dataset.y };
  1128. }
  1129. element.dataset.x = newPosition.x;
  1130. element.dataset.y = newPosition.y;
  1131. });
  1132. updateSizes();
  1133. }
  1134. function loadScene() {
  1135. try {
  1136. const data = JSON.parse(localStorage.getItem("macrovision-save"));
  1137. importScene(data);
  1138. } catch (err) {
  1139. alert("Something went wrong while loading (maybe you didn't have anything saved. Check the F12 console for the error.")
  1140. console.error(err);
  1141. }
  1142. }
  1143. function saveScene() {
  1144. try {
  1145. const string = JSON.stringify(exportScene());
  1146. localStorage.setItem("macrovision-save", string);
  1147. } catch (err) {
  1148. alert("Something went wrong while saving (maybe I don't have localStorage permissions, or exporting failed). Check the F12 console for the error.")
  1149. console.error(err);
  1150. }
  1151. }
  1152. function exportScene() {
  1153. const results = {};
  1154. results.entities = [];
  1155. Object.entries(entities).forEach(([key, entity]) => {
  1156. const element = document.querySelector("#entity-" + key);
  1157. results.entities.push({
  1158. name: entity.identifier,
  1159. scale: entity.scale,
  1160. view: entity.view,
  1161. x: element.dataset.x,
  1162. y: element.dataset.y
  1163. });
  1164. });
  1165. const unit = document.querySelector("#options-height-unit").value;
  1166. results.world = {
  1167. height: config.height.toNumber(unit),
  1168. unit: unit
  1169. }
  1170. return results;
  1171. }
  1172. // btoa doesn't like anything that isn't ASCII
  1173. // great
  1174. // thanks to https://stackoverflow.com/questions/30106476/using-javascripts-atob-to-decode-base64-doesnt-properly-decode-utf-8-strings
  1175. // for providing an alternative
  1176. function b64EncodeUnicode(str) {
  1177. // first we use encodeURIComponent to get percent-encoded UTF-8,
  1178. // then we convert the percent encodings into raw bytes which
  1179. // can be fed into btoa.
  1180. return btoa(encodeURIComponent(str).replace(/%([0-9A-F]{2})/g,
  1181. function toSolidBytes(match, p1) {
  1182. return String.fromCharCode('0x' + p1);
  1183. }));
  1184. }
  1185. function b64DecodeUnicode(str) {
  1186. // Going backwards: from bytestream, to percent-encoding, to original string.
  1187. return decodeURIComponent(atob(str).split('').map(function(c) {
  1188. return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
  1189. }).join(''));
  1190. }
  1191. function linkScene() {
  1192. loc = new URL(window.location);
  1193. window.location = loc.protocol + "//" + loc.host + loc.pathname + "?scene=" + b64EncodeUnicode(JSON.stringify(exportScene()));
  1194. }
  1195. function copyScene() {
  1196. const results = exportScene();
  1197. navigator.clipboard.writeText(JSON.stringify(results))
  1198. alert("Scene copied to clipboard. Paste text into the page to load the scene.");
  1199. }
  1200. // TODO - don't just search through every single entity
  1201. // probably just have a way to do lookups directly
  1202. function findEntity(name) {
  1203. return availableEntitiesByName[name];
  1204. }
  1205. function importScene(data) {
  1206. removeAllEntities();
  1207. data.entities.forEach(entityInfo => {
  1208. const entity = findEntity(entityInfo.name).constructor();
  1209. entity.scale = entityInfo.scale
  1210. displayEntity(entity, entityInfo.view, entityInfo.x, entityInfo.y);
  1211. });
  1212. config.height = math.unit(data.world.height, data.world.unit);
  1213. document.querySelector("#options-height-unit").value = data.world.unit;
  1214. updateSizes();
  1215. }