less copy protection, more size visualization
Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.
 
 
 

1572 řádky
47 KiB

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