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.
 
 
 

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