less copy protection, more size visualization
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

1518 lines
45 KiB

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