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.
 
 
 

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