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

1214 строки
35 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. const unitChoices = {
  15. length: [
  16. "meters",
  17. "angstroms",
  18. "millimeters",
  19. "centimeters",
  20. "kilometers",
  21. "inches",
  22. "feet",
  23. "stories",
  24. "miles",
  25. "parsecs",
  26. ],
  27. area: [
  28. "meters^2",
  29. "cm^2",
  30. "kilometers^2",
  31. "acres",
  32. "miles^2"
  33. ],
  34. mass: [
  35. "kilograms",
  36. "lbs",
  37. "tons"
  38. ]
  39. }
  40. const config = {
  41. height: math.unit(1500, "meters"),
  42. minLineSize: 50,
  43. maxLineSize: 250,
  44. autoFit: false,
  45. autoFitMode: "max"
  46. }
  47. const availableEntities = {
  48. }
  49. const availableEntitiesByName = {
  50. }
  51. const entities = {
  52. }
  53. function constrainRel(coords) {
  54. return {
  55. x: Math.min(Math.max(coords.x, 0), 1),
  56. y: Math.min(Math.max(coords.y, 0), 1)
  57. }
  58. }
  59. function snapRel(coords) {
  60. return constrainRel({
  61. x: coords.x,
  62. y: altHeld ? coords.y : (Math.abs(coords.y - 1) < 0.05 ? 1 : coords.y)
  63. });
  64. }
  65. function adjustAbs(coords, oldHeight, newHeight) {
  66. return { x: coords.x, y: 1 + (coords.y - 1) * math.divide(oldHeight, newHeight) };
  67. }
  68. function rel2abs(coords) {
  69. return { x: coords.x * canvasWidth + 50, y: coords.y * canvasHeight };
  70. }
  71. function abs2rel(coords) {
  72. return { x: (coords.x - 50) / canvasWidth, y: coords.y / canvasHeight };
  73. }
  74. function updateEntityElement(entity, element, zIndex) {
  75. const position = rel2abs({ x: element.dataset.x, y: element.dataset.y });
  76. const view = entity.view;
  77. element.style.left = position.x + "px";
  78. element.style.top = position.y + "px";
  79. const canvasHeight = document.querySelector("#display").clientHeight;
  80. const pixels = math.divide(entity.views[view].height, config.height) * (canvasHeight - 100);
  81. const bonus = (entity.views[view].image.extra ? entity.views[view].image.extra : 1);
  82. element.style.setProperty("--height", pixels * bonus + "px");
  83. element.querySelector(".entity-name").innerText = entity.name;
  84. const bottomName = document.querySelector("#bottom-name-" + element.dataset.key);
  85. bottomName.style.left = position.x + entityX + "px";
  86. bottomName.style.top = "95vh";
  87. bottomName.innerText = entity.name;
  88. if (zIndex) {
  89. element.style.zIndex = zIndex;
  90. }
  91. }
  92. function updateSizes() {
  93. drawScale();
  94. let ordered = Object.entries(entities);
  95. ordered.sort((e1, e2) => {
  96. return e1[1].views[e1[1].view].height.toNumber("meters") - e2[1].views[e2[1].view].height.toNumber("meters")
  97. });
  98. let zIndex = ordered.length;
  99. ordered.forEach(entity => {
  100. const element = document.querySelector("#entity-" + entity[0]);
  101. updateEntityElement(entity[1], element, zIndex);
  102. zIndex -= 1;
  103. });
  104. }
  105. function drawScale() {
  106. function drawTicks(/** @type {CanvasRenderingContext2D} */ ctx, pixelsPer, heightPer) {
  107. let total = heightPer.clone();
  108. total.value = 0;
  109. for (let y = ctx.canvas.clientHeight - 50; y >= 50; y -= pixelsPer) {
  110. drawTick(ctx, 50, y, total);
  111. total = math.add(total, heightPer);
  112. }
  113. }
  114. function drawTick(/** @type {CanvasRenderingContext2D} */ ctx, x, y, value) {
  115. const oldStroke = ctx.strokeStyle;
  116. const oldFill = ctx.fillStyle;
  117. ctx.beginPath();
  118. ctx.moveTo(x, y);
  119. ctx.lineTo(x + 20, y);
  120. ctx.strokeStyle = "#000000";
  121. ctx.stroke();
  122. ctx.beginPath();
  123. ctx.moveTo(x + 20, y);
  124. ctx.lineTo(ctx.canvas.clientWidth - 70, y);
  125. ctx.strokeStyle = "#aaaaaa";
  126. ctx.stroke();
  127. ctx.beginPath();
  128. ctx.moveTo(ctx.canvas.clientWidth - 70, y);
  129. ctx.lineTo(ctx.canvas.clientWidth - 50, y);
  130. ctx.strokeStyle = "#000000";
  131. ctx.stroke();
  132. const oldFont = ctx.font;
  133. ctx.font = 'normal 24pt coda';
  134. ctx.fillStyle = "#dddddd";
  135. ctx.beginPath();
  136. ctx.fillText(value.format({ precision: 3 }), x + 20, y + 35);
  137. ctx.font = oldFont;
  138. ctx.strokeStyle = oldStroke;
  139. ctx.fillStyle = oldFill;
  140. }
  141. const canvas = document.querySelector("#display");
  142. /** @type {CanvasRenderingContext2D} */
  143. const ctx = canvas.getContext("2d");
  144. let pixelsPer = (ctx.canvas.clientHeight - 100) / config.height.value;
  145. let heightPer = config.height.clone();
  146. heightPer.value = 1;
  147. if (pixelsPer < config.minLineSize) {
  148. heightPer.value /= pixelsPer / config.minLineSize;
  149. pixelsPer = config.minLineSize;
  150. }
  151. if (pixelsPer > config.maxLineSize) {
  152. heightPer.value /= pixelsPer / config.maxLineSize;
  153. pixelsPer = config.maxLineSize;
  154. }
  155. ctx.clearRect(0, 0, canvas.width, canvas.height);
  156. ctx.scale(1, 1);
  157. ctx.canvas.width = canvas.clientWidth;
  158. ctx.canvas.height = canvas.clientHeight;
  159. ctx.beginPath();
  160. ctx.moveTo(50, 50);
  161. ctx.lineTo(50, ctx.canvas.clientHeight - 50);
  162. ctx.stroke();
  163. ctx.beginPath();
  164. ctx.moveTo(ctx.canvas.clientWidth - 50, 50);
  165. ctx.lineTo(ctx.canvas.clientWidth - 50, ctx.canvas.clientHeight - 50);
  166. ctx.stroke();
  167. drawTicks(ctx, pixelsPer, heightPer);
  168. }
  169. function makeEntity(info, views, sizes) {
  170. const entityTemplate = {
  171. name: info.name,
  172. identifier: info.name,
  173. scale: 1,
  174. info: info,
  175. views: views,
  176. sizes: sizes === undefined ? [] : sizes,
  177. init: function () {
  178. const entity = this;
  179. Object.entries(this.views).forEach(([viewKey, view]) => {
  180. view.parent = this;
  181. if (this.defaultView === undefined) {
  182. this.defaultView = viewKey;
  183. this.view = viewKey;
  184. }
  185. Object.entries(view.attributes).forEach(([key, val]) => {
  186. Object.defineProperty(
  187. view,
  188. key,
  189. {
  190. get: function () {
  191. return math.multiply(Math.pow(this.parent.scale, this.attributes[key].power), this.attributes[key].base);
  192. },
  193. set: function (value) {
  194. const newScale = Math.pow(math.divide(value, this.attributes[key].base), 1 / this.attributes[key].power);
  195. this.parent.scale = newScale;
  196. }
  197. }
  198. )
  199. });
  200. });
  201. this.sizes.forEach(size => {
  202. if (size.default === true) {
  203. this.views[this.defaultView].height = size.height;
  204. this.size = size;
  205. }
  206. });
  207. if (this.size === undefined && this.sizes.length > 0) {
  208. this.views[this.defaultView].height = this.sizes[0].height;
  209. this.size = this.sizes[0];
  210. }
  211. this.desc = {};
  212. Object.entries(this.info).forEach(([key, value]) => {
  213. Object.defineProperty(
  214. this.desc,
  215. key,
  216. {
  217. get: function() {
  218. let text = value.text;
  219. if (entity.views[entity.view].info) {
  220. if (entity.views[entity.view].info[key]) {
  221. text = combineInfo(text, entity.views[entity.view].info[key]);
  222. }
  223. }
  224. if (entity.size.info) {
  225. if (entity.size.info[key]) {
  226. text = combineInfo(text, entity.size.info[key]);
  227. }
  228. }
  229. return {title: value.title, text: text};
  230. }
  231. }
  232. )
  233. });
  234. delete this.init;
  235. return this;
  236. }
  237. }.init();
  238. return entityTemplate;
  239. }
  240. function combineInfo(existing, next) {
  241. switch(next.mode) {
  242. case "replace":
  243. return next.text;
  244. case "prepend":
  245. return next.text + existing;
  246. case "append":
  247. return existing + next.text;
  248. }
  249. return existing;
  250. }
  251. function clickDown(target, x, y) {
  252. clicked = target;
  253. const rect = target.getBoundingClientRect();
  254. let entX = document.querySelector("#entities").getBoundingClientRect().x;
  255. let entY = document.querySelector("#entities").getBoundingClientRect().y;
  256. dragOffsetX = x - rect.left + entX;
  257. dragOffsetY = y - rect.top + entY;
  258. clickTimeout = setTimeout(() => { dragging = true }, 200)
  259. }
  260. // could we make this actually detect the menu area?
  261. function hoveringInDeleteArea(e) {
  262. return e.clientY < document.body.clientHeight / 10;
  263. }
  264. function clickUp(e) {
  265. clearTimeout(clickTimeout);
  266. if (clicked) {
  267. if (dragging) {
  268. dragging = false;
  269. if (hoveringInDeleteArea(e)) {
  270. removeEntity(clicked);
  271. document.querySelector("#menubar").classList.remove("hover-delete");
  272. }
  273. } else {
  274. select(clicked);
  275. }
  276. clicked = null;
  277. }
  278. }
  279. function deselect() {
  280. if (selected) {
  281. selected.classList.remove("selected");
  282. }
  283. selected = null;
  284. clearViewList();
  285. clearEntityOptions();
  286. clearViewOptions();
  287. }
  288. function select(target) {
  289. deselect();
  290. selected = target;
  291. selectedEntity = entities[target.dataset.key];
  292. selected.classList.add("selected");
  293. configViewList(selectedEntity, selectedEntity.view);
  294. configEntityOptions(selectedEntity, selectedEntity.view);
  295. configViewOptions(selectedEntity, selectedEntity.view);
  296. }
  297. function configViewList(entity, selectedView) {
  298. const list = document.querySelector("#entity-view");
  299. list.innerHTML = "";
  300. list.style.display = "block";
  301. Object.keys(entity.views).forEach(view => {
  302. const option = document.createElement("option");
  303. option.innerText = entity.views[view].name;
  304. option.value = view;
  305. if (view === selectedView) {
  306. option.selected = true;
  307. }
  308. list.appendChild(option);
  309. });
  310. }
  311. function clearViewList() {
  312. const list = document.querySelector("#entity-view");
  313. list.innerHTML = "";
  314. list.style.display = "none";
  315. }
  316. function updateWorldOptions(entity, view) {
  317. const heightInput = document.querySelector("#options-height-value");
  318. const heightSelect = document.querySelector("#options-height-unit");
  319. const converted = config.height.toNumber(heightSelect.value);
  320. heightInput.value = math.round(converted, 3);
  321. }
  322. function configEntityOptions(entity, view) {
  323. const holder = document.querySelector("#options-entity");
  324. holder.innerHTML = "";
  325. const scaleLabel = document.createElement("div");
  326. scaleLabel.classList.add("options-label");
  327. scaleLabel.innerText = "Scale";
  328. const scaleRow = document.createElement("div");
  329. scaleRow.classList.add("options-row");
  330. const scaleInput = document.createElement("input");
  331. scaleInput.classList.add("options-field-numeric");
  332. scaleInput.id = "options-entity-scale";
  333. scaleInput.addEventListener("input", e => {
  334. entity.scale = e.target.value == 0 ? 1 : e.target.value;
  335. if (config.autoFit) {
  336. fitWorld();
  337. }
  338. updateSizes();
  339. updateEntityOptions(entity, view);
  340. updateViewOptions(entity, view);
  341. });
  342. scaleInput.setAttribute("min", 1);
  343. scaleInput.setAttribute("type", "number");
  344. scaleInput.value = entity.scale;
  345. scaleRow.appendChild(scaleInput);
  346. holder.appendChild(scaleLabel);
  347. holder.appendChild(scaleRow);
  348. const nameLabel = document.createElement("div");
  349. nameLabel.classList.add("options-label");
  350. nameLabel.innerText = "Name";
  351. const nameRow = document.createElement("div");
  352. nameRow.classList.add("options-row");
  353. const nameInput = document.createElement("input");
  354. nameInput.classList.add("options-field-text");
  355. nameInput.value = entity.name;
  356. nameInput.addEventListener("input", e => {
  357. entity.name = e.target.value;
  358. updateSizes();
  359. })
  360. nameRow.appendChild(nameInput);
  361. holder.appendChild(nameLabel);
  362. holder.appendChild(nameRow);
  363. const defaultHolder = document.querySelector("#options-entity-defaults");
  364. defaultHolder.innerHTML = "";
  365. entity.sizes.forEach(defaultInfo => {
  366. const button = document.createElement("button");
  367. button.classList.add("options-button");
  368. button.innerText = defaultInfo.name;
  369. button.addEventListener("click", e => {
  370. entity.views[entity.defaultView].height = defaultInfo.height;
  371. updateEntityOptions(entity, view);
  372. updateViewOptions(entity, view);
  373. updateSizes();
  374. });
  375. defaultHolder.appendChild(button);
  376. });
  377. }
  378. function updateEntityOptions(entity, view) {
  379. const scaleInput = document.querySelector("#options-entity-scale");
  380. scaleInput.value = entity.scale;
  381. }
  382. function clearEntityOptions() {
  383. const holder = document.querySelector("#options-entity");
  384. holder.innerHTML = "";
  385. document.querySelector("#options-entity-defaults").innerHTML = "";
  386. }
  387. function configViewOptions(entity, view) {
  388. const holder = document.querySelector("#options-view");
  389. holder.innerHTML = "";
  390. Object.entries(entity.views[view].attributes).forEach(([key, val]) => {
  391. const label = document.createElement("div");
  392. label.classList.add("options-label");
  393. label.innerText = val.name;
  394. holder.appendChild(label);
  395. const row = document.createElement("div");
  396. row.classList.add("options-row");
  397. holder.appendChild(row);
  398. const input = document.createElement("input");
  399. input.classList.add("options-field-numeric");
  400. input.id = "options-view-" + key + "-input";
  401. input.setAttribute("type", "number");
  402. input.setAttribute("min", 1);
  403. input.value = entity.views[view][key].value;
  404. const select = document.createElement("select");
  405. select.id = "options-view-" + key + "-select"
  406. unitChoices[val.type].forEach(name => {
  407. const option = document.createElement("option");
  408. option.innerText = name;
  409. select.appendChild(option);
  410. });
  411. input.addEventListener("input", e => {
  412. const value = input.value == 0 ? 1 : input.value;
  413. entity.views[view][key] = math.unit(value, select.value);
  414. if (config.autoFit) {
  415. fitWorld();
  416. }
  417. updateSizes();
  418. updateEntityOptions(entity, view);
  419. updateViewOptions(entity, view, key);
  420. });
  421. select.setAttribute("oldUnit", select.value);
  422. select.addEventListener("input", e => {
  423. const value = input.value == 0 ? 1 : input.value;
  424. const oldUnit = select.getAttribute("oldUnit");
  425. entity.views[view][key] = math.unit(value, oldUnit).to(select.value);
  426. input.value = entity.views[view][key].toNumber(select.value);
  427. select.setAttribute("oldUnit", select.value);
  428. if (config.autoFit) {
  429. fitWorld();
  430. }
  431. updateSizes();
  432. updateEntityOptions(entity, view);
  433. updateViewOptions(entity, view, key);
  434. });
  435. row.appendChild(input);
  436. row.appendChild(select);
  437. });
  438. }
  439. function updateViewOptions(entity, view, changed) {
  440. Object.entries(entity.views[view].attributes).forEach(([key, val]) => {
  441. if (key != changed) {
  442. const input = document.querySelector("#options-view-" + key + "-input");
  443. const select = document.querySelector("#options-view-" + key + "-select");
  444. const currentUnit = select.value;
  445. const convertedAmount = entity.views[view][key].toNumber(currentUnit);
  446. input.value = math.round(convertedAmount, 5);
  447. }
  448. });
  449. }
  450. function clearViewOptions() {
  451. const holder = document.querySelector("#options-view");
  452. holder.innerHTML = "";
  453. }
  454. // this is a crime against humanity, and also stolen from
  455. // stack overflow
  456. // https://stackoverflow.com/questions/38487569/click-through-png-image-only-if-clicked-coordinate-is-transparent
  457. const testCanvas = document.createElement("canvas");
  458. testCanvas.id = "test-canvas";
  459. const testCtx = testCanvas.getContext("2d");
  460. function testClick(event) {
  461. // oh my god I can't believe I'm doing this
  462. const target = event.target;
  463. if (navigator.userAgent.indexOf("Firefox") != -1) {
  464. clickDown(target.parentElement, event.clientX, event.clientY);
  465. return;
  466. }
  467. // Get click coordinates
  468. let w = target.width;
  469. let h = target.height;
  470. let ratioW = 1, ratioH = 1;
  471. // Limit the size of the canvas so that very large images don't cause problems)
  472. if (w > 1000) {
  473. ratioW = w / 1000;
  474. w /= ratioW;
  475. h /= ratioW;
  476. }
  477. if (h > 1000) {
  478. ratioH = h / 1000;
  479. w /= ratioH;
  480. h /= ratioH;
  481. }
  482. const ratio = ratioW * ratioH;
  483. var x = event.clientX - target.getBoundingClientRect().x,
  484. y = event.clientY - target.getBoundingClientRect().y,
  485. alpha;
  486. testCtx.canvas.width = w;
  487. testCtx.canvas.height = h;
  488. // Draw image to canvas
  489. // and read Alpha channel value
  490. testCtx.drawImage(target, 0, 0, w, h);
  491. alpha = testCtx.getImageData(Math.floor(x / ratio), Math.floor(y / ratio), 1, 1).data[3]; // [0]R [1]G [2]B [3]A
  492. // If pixel is transparent,
  493. // retrieve the element underneath and trigger it's click event
  494. if (alpha === 0) {
  495. const oldDisplay = target.style.display;
  496. target.style.display = "none";
  497. const newTarget = document.elementFromPoint(event.clientX, event.clientY);
  498. newTarget.dispatchEvent(new MouseEvent(event.type, {
  499. "clientX": event.clientX,
  500. "clientY": event.clientY
  501. }));
  502. target.style.display = oldDisplay;
  503. } else {
  504. clickDown(target.parentElement, event.clientX, event.clientY);
  505. }
  506. }
  507. function arrangeEntities(order) {
  508. let x = 0.1;
  509. order.forEach(key => {
  510. document.querySelector("#entity-" + key).dataset.x = x;
  511. x += 0.8 / order.length
  512. });
  513. updateSizes();
  514. }
  515. function removeAllEntities() {
  516. Object.keys(entities).forEach(key => {
  517. removeEntity(document.querySelector("#entity-" + key));
  518. });
  519. }
  520. function removeEntity(element) {
  521. if (selected == element) {
  522. deselect();
  523. }
  524. delete entities[element.dataset.key];
  525. const bottomName = document.querySelector("#bottom-name-" + element.dataset.key);
  526. bottomName.parentElement.removeChild(bottomName);
  527. element.parentElement.removeChild(element);
  528. }
  529. function displayEntity(entity, view, x, y) {
  530. const box = document.createElement("div");
  531. box.classList.add("entity-box");
  532. const img = document.createElement("img");
  533. img.classList.add("entity-image");
  534. img.addEventListener("dragstart", e => {
  535. e.preventDefault();
  536. });
  537. const nameTag = document.createElement("div");
  538. nameTag.classList.add("entity-name");
  539. nameTag.innerText = entity.name;
  540. box.appendChild(img);
  541. box.appendChild(nameTag);
  542. const image = entity.views[view].image;
  543. img.src = image.source;
  544. if (image.bottom !== undefined) {
  545. img.style.setProperty("--offset", ((-1 + image.bottom) * 100) + "%")
  546. } else {
  547. img.style.setProperty("--offset", ((-1) * 100) + "%")
  548. }
  549. box.dataset.x = x;
  550. box.dataset.y = y;
  551. img.addEventListener("mousedown", e => { testClick(e); e.stopPropagation() });
  552. img.addEventListener("touchstart", e => {
  553. const fakeEvent = {
  554. target: e.target,
  555. clientX: e.touches[0].clientX,
  556. clientY: e.touches[0].clientY
  557. };
  558. testClick(fakeEvent);
  559. });
  560. box.id = "entity-" + entityIndex;
  561. box.dataset.key = entityIndex;
  562. entity.view = view;
  563. entities[entityIndex] = entity;
  564. entity.index = entityIndex;
  565. const world = document.querySelector("#entities");
  566. world.appendChild(box);
  567. const bottomName = document.createElement("div");
  568. bottomName.classList.add("bottom-name");
  569. bottomName.id = "bottom-name-" + entityIndex;
  570. bottomName.innerText = entity.name;
  571. bottomName.addEventListener("click", () => select(box));
  572. world.appendChild(bottomName);
  573. entityIndex += 1;
  574. updateEntityElement(entity, box);
  575. if (config.autoFit) {
  576. fitWorld();
  577. }
  578. select(box);
  579. }
  580. document.addEventListener("DOMContentLoaded", () => {
  581. prepareEntities();
  582. entityX = document.querySelector("#entities").getBoundingClientRect().x;
  583. canvasWidth = document.querySelector("#display").clientWidth - 100;
  584. canvasHeight = document.querySelector("#display").clientHeight - 50;
  585. document.querySelector("#open-help").addEventListener("click", e => {
  586. document.querySelector("#help").classList.add("visible");
  587. });
  588. document.querySelector("#close-help").addEventListener("click", e => {
  589. document.querySelector("#help").classList.remove("visible");
  590. });
  591. const unitSelector = document.querySelector("#options-height-unit");
  592. unitChoices.length.forEach(lengthOption => {
  593. const option = document.createElement("option");
  594. option.innerText = lengthOption;
  595. option.value = lengthOption;
  596. if (lengthOption === "meters") {
  597. option.selected = true;
  598. }
  599. unitSelector.appendChild(option);
  600. });
  601. const stuff = availableEntities.characters.map(x => x.constructor).filter(x => {
  602. const result = x();
  603. return result.views[result.defaultView].height.toNumber("meters") < 1000;
  604. })
  605. let x = 0.2;
  606. stuff.forEach(entity => {
  607. displayEntity(entity(), entity().defaultView, x, 1);
  608. x += 0.7 / stuff.length;
  609. })
  610. const order = Object.keys(entities).sort((a, b) => {
  611. const entA = entities[a];
  612. const entB = entities[b];
  613. const viewA = entA.view;
  614. const viewB = entB.view;
  615. const heightA = entA.views[viewA].height.to("meter").value;
  616. const heightB = entB.views[viewB].height.to("meter").value;
  617. return heightA - heightB;
  618. });
  619. arrangeEntities(order);
  620. fitWorld();
  621. document.querySelector("#world").addEventListener("wheel", e => {
  622. if (shiftHeld) {
  623. const dir = e.deltaY > 0 ? 0.9 : 1.1;
  624. if (selected) {
  625. const entity = entities[selected.dataset.key];
  626. entity.views[entity.view].height = math.multiply(entity.views[entity.view].height, dir);
  627. updateEntityOptions(entity, entity.view);
  628. updateViewOptions(entity, entity.view);
  629. updateSizes();
  630. }
  631. } else {
  632. const dir = e.deltaY < 0 ? 0.9 : 1.1;
  633. setWorldHeight(config.height, math.multiply(config.height, dir));
  634. updateWorldOptions();
  635. }
  636. checkFitWorld();
  637. })
  638. document.querySelector("body").appendChild(testCtx.canvas);
  639. updateSizes();
  640. document.querySelector("#options-height-value").addEventListener("input", e => {
  641. updateWorldHeight();
  642. })
  643. unitSelector.addEventListener("input", e => {
  644. checkFitWorld();
  645. updateWorldHeight();
  646. })
  647. world.addEventListener("mousedown", e => deselect());
  648. document.querySelector("#display").addEventListener("mousedown", deselect);
  649. document.addEventListener("mouseup", e => clickUp(e));
  650. document.addEventListener("touchend", e => {
  651. const fakeEvent = {
  652. target: e.target,
  653. clientX: e.changedTouches[0].clientX,
  654. clientY: e.changedTouches[0].clientY
  655. };
  656. clickUp(fakeEvent);
  657. });
  658. document.querySelector("#entity-view").addEventListener("input", e => {
  659. entities[selected.dataset.key].view = e.target.value;
  660. const image = entities[selected.dataset.key].views[e.target.value].image;
  661. selected.querySelector(".entity-image").src = image.source;
  662. if (image.bottom !== undefined) {
  663. selected.querySelector(".entity-image").style.setProperty("--offset", ((-1 + image.bottom) * 100) + "%")
  664. } else {
  665. selected.querySelector(".entity-image").style.setProperty("--offset", ((-1) * 100) + "%")
  666. }
  667. updateSizes();
  668. updateEntityOptions(entities[selected.dataset.key], e.target.value);
  669. updateViewOptions(entities[selected.dataset.key], e.target.value);
  670. });
  671. clearViewList();
  672. document.querySelector("#menu-clear").addEventListener("click", e => {
  673. removeAllEntities();
  674. });
  675. document.querySelector("#menu-order-height").addEventListener("click", e => {
  676. const order = Object.keys(entities).sort((a, b) => {
  677. const entA = entities[a];
  678. const entB = entities[b];
  679. const viewA = entA.view;
  680. const viewB = entB.view;
  681. const heightA = entA.views[viewA].height.to("meter").value;
  682. const heightB = entB.views[viewB].height.to("meter").value;
  683. return heightA - heightB;
  684. });
  685. arrangeEntities(order);
  686. });
  687. document.querySelector("#options-world-fit").addEventListener("click", fitWorld);
  688. document.querySelector("#options-world-autofit").addEventListener("input", e => {
  689. config.autoFit = e.target.checked;
  690. if (config.autoFit) {
  691. fitWorld();
  692. }
  693. });
  694. document.querySelector("#options-world-autofit-mode").addEventListener("input", e => {
  695. config.autoFitMode = e.target.value;
  696. if (config.autoFit) {
  697. fitWorld();
  698. }
  699. })
  700. document.addEventListener("keydown", e => {
  701. if (e.key == "Delete") {
  702. if (selected) {
  703. removeEntity(selected);
  704. selected = null;
  705. }
  706. }
  707. })
  708. document.addEventListener("keydown", e => {
  709. if (e.key == "Shift") {
  710. shiftHeld = true;
  711. e.preventDefault();
  712. } else if (e.key == "Alt") {
  713. altHeld = true;
  714. e.preventDefault();
  715. }
  716. });
  717. document.addEventListener("keyup", e => {
  718. if (e.key == "Shift") {
  719. shiftHeld = false;
  720. e.preventDefault();
  721. } else if (e.key == "Alt") {
  722. altHeld = false;
  723. e.preventDefault();
  724. }
  725. });
  726. document.addEventListener("paste", e => {
  727. try {
  728. const data = JSON.parse(e.clipboardData.getData("text"));
  729. if (data.entities === undefined) {
  730. return;
  731. }
  732. if (data.world === undefined) {
  733. return;
  734. }
  735. importScene(data);
  736. } catch (err) {
  737. console.error(err);
  738. // probably wasn't valid data
  739. }
  740. });
  741. document.querySelector("#menu-export").addEventListener("click", e => {
  742. copyScene();
  743. });
  744. document.querySelector("#menu-save").addEventListener("click", e => {
  745. saveScene();
  746. });
  747. document.querySelector("#menu-load").addEventListener("click", e => {
  748. loadScene();
  749. });
  750. });
  751. function prepareEntities() {
  752. availableEntities["buildings"] = makeBuildings();
  753. availableEntities["landmarks"] = makeLandmarks();
  754. availableEntities["characters"] = makeCharacters();
  755. availableEntities["objects"] = makeObjects();
  756. availableEntities["naturals"] = makeNaturals();
  757. availableEntities["vehicles"] = makeVehicles();
  758. availableEntities["cities"] = makeCities();
  759. availableEntities["characters"].sort((x, y) => {
  760. return x.name < y.name ? -1 : 1
  761. });
  762. const holder = document.querySelector("#spawners");
  763. const categorySelect = document.createElement("select");
  764. categorySelect.id = "category-picker";
  765. holder.appendChild(categorySelect);
  766. Object.entries(availableEntities).forEach(([category, entityList]) => {
  767. const select = document.createElement("select");
  768. select.id = "create-entity-" + category;
  769. for (let i = 0; i < entityList.length; i++) {
  770. const entity = entityList[i];
  771. const option = document.createElement("option");
  772. option.value = i;
  773. option.innerText = entity.name;
  774. select.appendChild(option);
  775. availableEntitiesByName[entity.name] = entity;
  776. };
  777. const button = document.createElement("button");
  778. button.id = "create-entity-" + category + "-button";
  779. button.innerText = "Create";
  780. button.addEventListener("click", e => {
  781. const newEntity = entityList[select.value].constructor()
  782. displayEntity(newEntity, newEntity.defaultView, 0.5, 1);
  783. });
  784. const categoryOption = document.createElement("option");
  785. categoryOption.value = category
  786. categoryOption.innerText = category;
  787. if (category == "characters") {
  788. categoryOption.selected = true;
  789. select.classList.add("category-visible");
  790. button.classList.add("category-visible");
  791. }
  792. categorySelect.appendChild(categoryOption);
  793. holder.appendChild(select);
  794. holder.appendChild(button);
  795. });
  796. categorySelect.addEventListener("input", e => {
  797. const oldSelect = document.querySelector("select.category-visible");
  798. oldSelect.classList.remove("category-visible");
  799. const oldButton = document.querySelector("button.category-visible");
  800. oldButton.classList.remove("category-visible");
  801. const newSelect = document.querySelector("#create-entity-" + e.target.value);
  802. newSelect.classList.add("category-visible");
  803. const newButton = document.querySelector("#create-entity-" + e.target.value + "-button");
  804. newButton.classList.add("category-visible");
  805. });
  806. }
  807. window.addEventListener("resize", () => {
  808. entityX = document.querySelector("#entities").getBoundingClientRect().x;
  809. canvasWidth = document.querySelector("#display").clientWidth - 100;
  810. canvasHeight = document.querySelector("#display").clientHeight - 50;
  811. updateSizes();
  812. })
  813. document.addEventListener("mousemove", (e) => {
  814. if (clicked) {
  815. const position = snapRel(abs2rel({ x: e.clientX - dragOffsetX, y: e.clientY - dragOffsetY }));
  816. clicked.dataset.x = position.x;
  817. clicked.dataset.y = position.y;
  818. updateEntityElement(entities[clicked.dataset.key], clicked);
  819. if (hoveringInDeleteArea(e)) {
  820. document.querySelector("#menubar").classList.add("hover-delete");
  821. } else {
  822. document.querySelector("#menubar").classList.remove("hover-delete");
  823. }
  824. }
  825. });
  826. document.addEventListener("touchmove", (e) => {
  827. if (clicked) {
  828. e.preventDefault();
  829. let x = e.touches[0].clientX;
  830. let y = e.touches[0].clientY;
  831. const position = snapRel(abs2rel({ x: x - dragOffsetX, y: y - dragOffsetY }));
  832. clicked.dataset.x = position.x;
  833. clicked.dataset.y = position.y;
  834. updateEntityElement(entities[clicked.dataset.key], clicked);
  835. // what a hack
  836. // I should centralize this 'fake event' creation...
  837. if (hoveringInDeleteArea({ clientY: y })) {
  838. document.querySelector("#menubar").classList.add("hover-delete");
  839. } else {
  840. document.querySelector("#menubar").classList.remove("hover-delete");
  841. }
  842. }
  843. }, { passive: false });
  844. function checkFitWorld() {
  845. if (config.autoFit) {
  846. fitWorld();
  847. }
  848. }
  849. const fitModes = {
  850. "max": {
  851. start: 0,
  852. binop: math.max,
  853. final: (total, count) => total
  854. },
  855. "arithmetic mean": {
  856. start: 0,
  857. binop: math.add,
  858. final: (total, count) => total / count
  859. },
  860. "geometric mean": {
  861. start: 1,
  862. binop: math.multiply,
  863. final: (total, count) => math.pow(total, 1 / count)
  864. }
  865. }
  866. function fitWorld() {
  867. const fitMode = fitModes[config.autoFitMode]
  868. let max = fitMode.start
  869. let count = 0;
  870. Object.entries(entities).forEach(([key, entity]) => {
  871. const view = entity.view;
  872. max = fitMode.binop(max, entity.views[view].height.toNumber("meter"));
  873. count += 1;
  874. });
  875. max = fitMode.final(max, count)
  876. max = math.unit(max, "meter")
  877. setWorldHeight(config.height, math.multiply(max, 1.1));
  878. }
  879. function updateWorldHeight() {
  880. const unit = document.querySelector("#options-height-unit").value;
  881. const value = Math.max(0.000000001, document.querySelector("#options-height-value").value);
  882. const oldHeight = config.height;
  883. setWorldHeight(oldHeight, math.unit(value, unit));
  884. }
  885. function setWorldHeight(oldHeight, newHeight) {
  886. config.height = newHeight.to(document.querySelector("#options-height-unit").value)
  887. const unit = document.querySelector("#options-height-unit").value;
  888. document.querySelector("#options-height-value").value = config.height.toNumber(unit);
  889. Object.entries(entities).forEach(([key, entity]) => {
  890. const element = document.querySelector("#entity-" + key);
  891. let newPosition;
  892. if (!altHeld) {
  893. newPosition = adjustAbs({ x: element.dataset.x, y: element.dataset.y }, oldHeight, config.height);
  894. } else {
  895. newPosition = { x: element.dataset.x, y: element.dataset.y };
  896. }
  897. element.dataset.x = newPosition.x;
  898. element.dataset.y = newPosition.y;
  899. });
  900. updateSizes();
  901. }
  902. function loadScene() {
  903. try {
  904. const data = JSON.parse(localStorage.getItem("macrovision-save"));
  905. importScene(data);
  906. } catch (err) {
  907. alert("Something went wrong while loading (maybe you didn't have anything saved. Check the F12 console for the error.")
  908. console.error(err);
  909. }
  910. }
  911. function saveScene() {
  912. try {
  913. const string = JSON.stringify(exportScene());
  914. localStorage.setItem("macrovision-save", string);
  915. } catch (err) {
  916. alert("Something went wrong while saving (maybe I don't have localStorage permissions, or exporting failed). Check the F12 console for the error.")
  917. console.error(err);
  918. }
  919. }
  920. function exportScene() {
  921. const results = {};
  922. results.entities = [];
  923. Object.entries(entities).forEach(([key, entity]) => {
  924. const element = document.querySelector("#entity-" + key);
  925. results.entities.push({
  926. name: entity.identifier,
  927. scale: entity.scale,
  928. view: entity.view,
  929. x: element.dataset.x,
  930. y: element.dataset.y
  931. });
  932. });
  933. const unit = document.querySelector("#options-height-unit").value;
  934. results.world = {
  935. height: config.height.toNumber(unit),
  936. unit: unit
  937. }
  938. return results;
  939. }
  940. function copyScene() {
  941. const results = exportScene();
  942. navigator.clipboard.writeText(JSON.stringify(results))
  943. alert("Scene copied to clipboard. Paste text into the page to load the scene.");
  944. }
  945. // TODO - don't just search through every single entity
  946. // probably just have a way to do lookups directly
  947. function findEntity(name) {
  948. return availableEntitiesByName[name];
  949. }
  950. function importScene(data) {
  951. removeAllEntities();
  952. data.entities.forEach(entityInfo => {
  953. const entity = findEntity(entityInfo.name).constructor();
  954. entity.scale = entityInfo.scale
  955. displayEntity(entity, entityInfo.view, entityInfo.x, entityInfo.y);
  956. });
  957. config.height = math.unit(data.world.height, data.world.unit);
  958. document.querySelector("#options-height-unit").value = data.world.unit;
  959. updateSizes();
  960. }