less copy protection, more size visualization
Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.
 
 
 

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