less copy protection, more size visualization
Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.
 
 
 

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