less copy protection, more size visualization
Du kannst nicht mehr als 25 Themen auswählen Themen müssen entweder mit einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.
 
 
 

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