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

1217 lignes
36 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 getSortedEntities() {
  451. return Object.keys(entities).sort((a, b) => {
  452. const entA = entities[a];
  453. const entB = entities[b];
  454. const viewA = entA.view;
  455. const viewB = entB.view;
  456. const heightA = entA.views[viewA].height.to("meter").value;
  457. const heightB = entB.views[viewB].height.to("meter").value;
  458. return heightA - heightB;
  459. });
  460. }
  461. function clearViewOptions() {
  462. const holder = document.querySelector("#options-view");
  463. holder.innerHTML = "";
  464. }
  465. // this is a crime against humanity, and also stolen from
  466. // stack overflow
  467. // https://stackoverflow.com/questions/38487569/click-through-png-image-only-if-clicked-coordinate-is-transparent
  468. const testCanvas = document.createElement("canvas");
  469. testCanvas.id = "test-canvas";
  470. const testCtx = testCanvas.getContext("2d");
  471. function testClick(event) {
  472. // oh my god I can't believe I'm doing this
  473. const target = event.target;
  474. if (navigator.userAgent.indexOf("Firefox") != -1) {
  475. clickDown(target.parentElement, event.clientX, event.clientY);
  476. return;
  477. }
  478. // Get click coordinates
  479. let w = target.width;
  480. let h = target.height;
  481. let ratioW = 1, ratioH = 1;
  482. // Limit the size of the canvas so that very large images don't cause problems)
  483. if (w > 1000) {
  484. ratioW = w / 1000;
  485. w /= ratioW;
  486. h /= ratioW;
  487. }
  488. if (h > 1000) {
  489. ratioH = h / 1000;
  490. w /= ratioH;
  491. h /= ratioH;
  492. }
  493. const ratio = ratioW * ratioH;
  494. var x = event.clientX - target.getBoundingClientRect().x,
  495. y = event.clientY - target.getBoundingClientRect().y,
  496. alpha;
  497. testCtx.canvas.width = w;
  498. testCtx.canvas.height = h;
  499. // Draw image to canvas
  500. // and read Alpha channel value
  501. testCtx.drawImage(target, 0, 0, w, h);
  502. alpha = testCtx.getImageData(Math.floor(x / ratio), Math.floor(y / ratio), 1, 1).data[3]; // [0]R [1]G [2]B [3]A
  503. // If pixel is transparent,
  504. // retrieve the element underneath and trigger it's click event
  505. if (alpha === 0) {
  506. const oldDisplay = target.style.display;
  507. target.style.display = "none";
  508. const newTarget = document.elementFromPoint(event.clientX, event.clientY);
  509. newTarget.dispatchEvent(new MouseEvent(event.type, {
  510. "clientX": event.clientX,
  511. "clientY": event.clientY
  512. }));
  513. target.style.display = oldDisplay;
  514. } else {
  515. clickDown(target.parentElement, event.clientX, event.clientY);
  516. }
  517. }
  518. function arrangeEntities(order) {
  519. let x = 0.1;
  520. order.forEach(key => {
  521. document.querySelector("#entity-" + key).dataset.x = x;
  522. x += 0.8 / (order.length - 1);
  523. });
  524. updateSizes();
  525. }
  526. function removeAllEntities() {
  527. Object.keys(entities).forEach(key => {
  528. removeEntity(document.querySelector("#entity-" + key));
  529. });
  530. }
  531. function removeEntity(element) {
  532. if (selected == element) {
  533. deselect();
  534. }
  535. delete entities[element.dataset.key];
  536. const bottomName = document.querySelector("#bottom-name-" + element.dataset.key);
  537. bottomName.parentElement.removeChild(bottomName);
  538. element.parentElement.removeChild(element);
  539. }
  540. function displayEntity(entity, view, x, y) {
  541. const box = document.createElement("div");
  542. box.classList.add("entity-box");
  543. const img = document.createElement("img");
  544. img.classList.add("entity-image");
  545. img.addEventListener("dragstart", e => {
  546. e.preventDefault();
  547. });
  548. const nameTag = document.createElement("div");
  549. nameTag.classList.add("entity-name");
  550. nameTag.innerText = entity.name;
  551. box.appendChild(img);
  552. box.appendChild(nameTag);
  553. const image = entity.views[view].image;
  554. img.src = image.source;
  555. if (image.bottom !== undefined) {
  556. img.style.setProperty("--offset", ((-1 + image.bottom) * 100) + "%")
  557. } else {
  558. img.style.setProperty("--offset", ((-1) * 100) + "%")
  559. }
  560. box.dataset.x = x;
  561. box.dataset.y = y;
  562. img.addEventListener("mousedown", e => { testClick(e); e.stopPropagation() });
  563. img.addEventListener("touchstart", e => {
  564. const fakeEvent = {
  565. target: e.target,
  566. clientX: e.touches[0].clientX,
  567. clientY: e.touches[0].clientY
  568. };
  569. testClick(fakeEvent);
  570. });
  571. box.id = "entity-" + entityIndex;
  572. box.dataset.key = entityIndex;
  573. entity.view = view;
  574. entities[entityIndex] = entity;
  575. entity.index = entityIndex;
  576. const world = document.querySelector("#entities");
  577. world.appendChild(box);
  578. const bottomName = document.createElement("div");
  579. bottomName.classList.add("bottom-name");
  580. bottomName.id = "bottom-name-" + entityIndex;
  581. bottomName.innerText = entity.name;
  582. bottomName.addEventListener("click", () => select(box));
  583. world.appendChild(bottomName);
  584. entityIndex += 1;
  585. updateEntityElement(entity, box);
  586. if (config.autoFit) {
  587. fitWorld();
  588. }
  589. select(box);
  590. }
  591. document.addEventListener("DOMContentLoaded", () => {
  592. prepareEntities();
  593. const sceneChoices = document.querySelector("#scene-choices");
  594. Object.entries(scenes).forEach(([id, scene]) => {
  595. const option = document.createElement("option");
  596. option.innerText = id;
  597. option.value = id;
  598. sceneChoices.appendChild(option);
  599. });
  600. document.querySelector("#load-scene").addEventListener("click", e => {
  601. const chosen = sceneChoices.value;
  602. removeAllEntities();
  603. scenes[chosen]();
  604. });
  605. entityX = document.querySelector("#entities").getBoundingClientRect().x;
  606. canvasWidth = document.querySelector("#display").clientWidth - 100;
  607. canvasHeight = document.querySelector("#display").clientHeight - 50;
  608. document.querySelector("#open-help").addEventListener("click", e => {
  609. document.querySelector("#help").classList.add("visible");
  610. });
  611. document.querySelector("#close-help").addEventListener("click", e => {
  612. document.querySelector("#help").classList.remove("visible");
  613. });
  614. const unitSelector = document.querySelector("#options-height-unit");
  615. unitChoices.length.forEach(lengthOption => {
  616. const option = document.createElement("option");
  617. option.innerText = lengthOption;
  618. option.value = lengthOption;
  619. if (lengthOption === "meters") {
  620. option.selected = true;
  621. }
  622. unitSelector.appendChild(option);
  623. });
  624. scenes["Demo"]();
  625. fitWorld();
  626. document.querySelector("#world").addEventListener("wheel", e => {
  627. if (shiftHeld) {
  628. const dir = e.deltaY > 0 ? 0.9 : 1.1;
  629. if (selected) {
  630. const entity = entities[selected.dataset.key];
  631. entity.views[entity.view].height = math.multiply(entity.views[entity.view].height, dir);
  632. updateEntityOptions(entity, entity.view);
  633. updateViewOptions(entity, entity.view);
  634. updateSizes();
  635. }
  636. } else {
  637. const dir = e.deltaY < 0 ? 0.9 : 1.1;
  638. setWorldHeight(config.height, math.multiply(config.height, dir));
  639. updateWorldOptions();
  640. }
  641. checkFitWorld();
  642. })
  643. document.querySelector("body").appendChild(testCtx.canvas);
  644. updateSizes();
  645. document.querySelector("#options-height-value").addEventListener("input", e => {
  646. updateWorldHeight();
  647. })
  648. unitSelector.addEventListener("input", e => {
  649. checkFitWorld();
  650. updateWorldHeight();
  651. })
  652. world.addEventListener("mousedown", e => deselect());
  653. document.querySelector("#display").addEventListener("mousedown", deselect);
  654. document.addEventListener("mouseup", e => clickUp(e));
  655. document.addEventListener("touchend", e => {
  656. const fakeEvent = {
  657. target: e.target,
  658. clientX: e.changedTouches[0].clientX,
  659. clientY: e.changedTouches[0].clientY
  660. };
  661. clickUp(fakeEvent);
  662. });
  663. document.querySelector("#entity-view").addEventListener("input", e => {
  664. entities[selected.dataset.key].view = e.target.value;
  665. const image = entities[selected.dataset.key].views[e.target.value].image;
  666. selected.querySelector(".entity-image").src = image.source;
  667. if (image.bottom !== undefined) {
  668. selected.querySelector(".entity-image").style.setProperty("--offset", ((-1 + image.bottom) * 100) + "%")
  669. } else {
  670. selected.querySelector(".entity-image").style.setProperty("--offset", ((-1) * 100) + "%")
  671. }
  672. updateSizes();
  673. updateEntityOptions(entities[selected.dataset.key], e.target.value);
  674. updateViewOptions(entities[selected.dataset.key], e.target.value);
  675. });
  676. clearViewList();
  677. document.querySelector("#menu-clear").addEventListener("click", e => {
  678. removeAllEntities();
  679. });
  680. document.querySelector("#menu-order-height").addEventListener("click", e => {
  681. const order = Object.keys(entities).sort((a, b) => {
  682. const entA = entities[a];
  683. const entB = entities[b];
  684. const viewA = entA.view;
  685. const viewB = entB.view;
  686. const heightA = entA.views[viewA].height.to("meter").value;
  687. const heightB = entB.views[viewB].height.to("meter").value;
  688. return heightA - heightB;
  689. });
  690. arrangeEntities(order);
  691. });
  692. document.querySelector("#options-world-fit").addEventListener("click", fitWorld);
  693. document.querySelector("#options-world-autofit").addEventListener("input", e => {
  694. config.autoFit = e.target.checked;
  695. if (config.autoFit) {
  696. fitWorld();
  697. }
  698. });
  699. document.querySelector("#options-world-autofit-mode").addEventListener("input", e => {
  700. config.autoFitMode = e.target.value;
  701. if (config.autoFit) {
  702. fitWorld();
  703. }
  704. })
  705. document.addEventListener("keydown", e => {
  706. if (e.key == "Delete") {
  707. if (selected) {
  708. removeEntity(selected);
  709. selected = null;
  710. }
  711. }
  712. })
  713. document.addEventListener("keydown", e => {
  714. if (e.key == "Shift") {
  715. shiftHeld = true;
  716. e.preventDefault();
  717. } else if (e.key == "Alt") {
  718. altHeld = true;
  719. e.preventDefault();
  720. }
  721. });
  722. document.addEventListener("keyup", e => {
  723. if (e.key == "Shift") {
  724. shiftHeld = false;
  725. e.preventDefault();
  726. } else if (e.key == "Alt") {
  727. altHeld = false;
  728. e.preventDefault();
  729. }
  730. });
  731. document.addEventListener("paste", e => {
  732. try {
  733. const data = JSON.parse(e.clipboardData.getData("text"));
  734. if (data.entities === undefined) {
  735. return;
  736. }
  737. if (data.world === undefined) {
  738. return;
  739. }
  740. importScene(data);
  741. } catch (err) {
  742. console.error(err);
  743. // probably wasn't valid data
  744. }
  745. });
  746. document.querySelector("#menu-export").addEventListener("click", e => {
  747. copyScene();
  748. });
  749. document.querySelector("#menu-save").addEventListener("click", e => {
  750. saveScene();
  751. });
  752. document.querySelector("#menu-load").addEventListener("click", e => {
  753. loadScene();
  754. });
  755. });
  756. function prepareEntities() {
  757. availableEntities["buildings"] = makeBuildings();
  758. availableEntities["landmarks"] = makeLandmarks();
  759. availableEntities["characters"] = makeCharacters();
  760. availableEntities["objects"] = makeObjects();
  761. availableEntities["naturals"] = makeNaturals();
  762. availableEntities["vehicles"] = makeVehicles();
  763. availableEntities["cities"] = makeCities();
  764. availableEntities["characters"].sort((x, y) => {
  765. return x.name < y.name ? -1 : 1
  766. });
  767. const holder = document.querySelector("#spawners");
  768. const categorySelect = document.createElement("select");
  769. categorySelect.id = "category-picker";
  770. holder.appendChild(categorySelect);
  771. Object.entries(availableEntities).forEach(([category, entityList]) => {
  772. const select = document.createElement("select");
  773. select.id = "create-entity-" + category;
  774. for (let i = 0; i < entityList.length; i++) {
  775. const entity = entityList[i];
  776. const option = document.createElement("option");
  777. option.value = i;
  778. option.innerText = entity.name;
  779. select.appendChild(option);
  780. availableEntitiesByName[entity.name] = entity;
  781. };
  782. const button = document.createElement("button");
  783. button.id = "create-entity-" + category + "-button";
  784. button.innerText = "Create";
  785. button.addEventListener("click", e => {
  786. const newEntity = entityList[select.value].constructor()
  787. displayEntity(newEntity, newEntity.defaultView, 0.5, 1);
  788. });
  789. const categoryOption = document.createElement("option");
  790. categoryOption.value = category
  791. categoryOption.innerText = category;
  792. if (category == "characters") {
  793. categoryOption.selected = true;
  794. select.classList.add("category-visible");
  795. button.classList.add("category-visible");
  796. }
  797. categorySelect.appendChild(categoryOption);
  798. holder.appendChild(select);
  799. holder.appendChild(button);
  800. });
  801. categorySelect.addEventListener("input", e => {
  802. const oldSelect = document.querySelector("select.category-visible");
  803. oldSelect.classList.remove("category-visible");
  804. const oldButton = document.querySelector("button.category-visible");
  805. oldButton.classList.remove("category-visible");
  806. const newSelect = document.querySelector("#create-entity-" + e.target.value);
  807. newSelect.classList.add("category-visible");
  808. const newButton = document.querySelector("#create-entity-" + e.target.value + "-button");
  809. newButton.classList.add("category-visible");
  810. });
  811. }
  812. window.addEventListener("resize", () => {
  813. entityX = document.querySelector("#entities").getBoundingClientRect().x;
  814. canvasWidth = document.querySelector("#display").clientWidth - 100;
  815. canvasHeight = document.querySelector("#display").clientHeight - 50;
  816. updateSizes();
  817. })
  818. document.addEventListener("mousemove", (e) => {
  819. if (clicked) {
  820. const position = snapRel(abs2rel({ x: e.clientX - dragOffsetX, y: e.clientY - dragOffsetY }));
  821. clicked.dataset.x = position.x;
  822. clicked.dataset.y = position.y;
  823. updateEntityElement(entities[clicked.dataset.key], clicked);
  824. if (hoveringInDeleteArea(e)) {
  825. document.querySelector("#menubar").classList.add("hover-delete");
  826. } else {
  827. document.querySelector("#menubar").classList.remove("hover-delete");
  828. }
  829. }
  830. });
  831. document.addEventListener("touchmove", (e) => {
  832. if (clicked) {
  833. e.preventDefault();
  834. let x = e.touches[0].clientX;
  835. let y = e.touches[0].clientY;
  836. const position = snapRel(abs2rel({ x: x - dragOffsetX, y: y - dragOffsetY }));
  837. clicked.dataset.x = position.x;
  838. clicked.dataset.y = position.y;
  839. updateEntityElement(entities[clicked.dataset.key], clicked);
  840. // what a hack
  841. // I should centralize this 'fake event' creation...
  842. if (hoveringInDeleteArea({ clientY: y })) {
  843. document.querySelector("#menubar").classList.add("hover-delete");
  844. } else {
  845. document.querySelector("#menubar").classList.remove("hover-delete");
  846. }
  847. }
  848. }, { passive: false });
  849. function checkFitWorld() {
  850. if (config.autoFit) {
  851. fitWorld();
  852. }
  853. }
  854. const fitModes = {
  855. "max": {
  856. start: 0,
  857. binop: math.max,
  858. final: (total, count) => total
  859. },
  860. "arithmetic mean": {
  861. start: 0,
  862. binop: math.add,
  863. final: (total, count) => total / count
  864. },
  865. "geometric mean": {
  866. start: 1,
  867. binop: math.multiply,
  868. final: (total, count) => math.pow(total, 1 / count)
  869. }
  870. }
  871. function fitWorld() {
  872. const fitMode = fitModes[config.autoFitMode]
  873. let max = fitMode.start
  874. let count = 0;
  875. Object.entries(entities).forEach(([key, entity]) => {
  876. const view = entity.view;
  877. max = fitMode.binop(max, entity.views[view].height.toNumber("meter"));
  878. count += 1;
  879. });
  880. max = fitMode.final(max, count)
  881. max = math.unit(max, "meter")
  882. setWorldHeight(config.height, math.multiply(max, 1.1));
  883. }
  884. function updateWorldHeight() {
  885. const unit = document.querySelector("#options-height-unit").value;
  886. const value = Math.max(0.000000001, document.querySelector("#options-height-value").value);
  887. const oldHeight = config.height;
  888. setWorldHeight(oldHeight, math.unit(value, unit));
  889. }
  890. function setWorldHeight(oldHeight, newHeight) {
  891. config.height = newHeight.to(document.querySelector("#options-height-unit").value)
  892. const unit = document.querySelector("#options-height-unit").value;
  893. document.querySelector("#options-height-value").value = config.height.toNumber(unit);
  894. Object.entries(entities).forEach(([key, entity]) => {
  895. const element = document.querySelector("#entity-" + key);
  896. let newPosition;
  897. if (!altHeld) {
  898. newPosition = adjustAbs({ x: element.dataset.x, y: element.dataset.y }, oldHeight, config.height);
  899. } else {
  900. newPosition = { x: element.dataset.x, y: element.dataset.y };
  901. }
  902. element.dataset.x = newPosition.x;
  903. element.dataset.y = newPosition.y;
  904. });
  905. updateSizes();
  906. }
  907. function loadScene() {
  908. try {
  909. const data = JSON.parse(localStorage.getItem("macrovision-save"));
  910. importScene(data);
  911. } catch (err) {
  912. alert("Something went wrong while loading (maybe you didn't have anything saved. Check the F12 console for the error.")
  913. console.error(err);
  914. }
  915. }
  916. function saveScene() {
  917. try {
  918. const string = JSON.stringify(exportScene());
  919. localStorage.setItem("macrovision-save", string);
  920. } catch (err) {
  921. alert("Something went wrong while saving (maybe I don't have localStorage permissions, or exporting failed). Check the F12 console for the error.")
  922. console.error(err);
  923. }
  924. }
  925. function exportScene() {
  926. const results = {};
  927. results.entities = [];
  928. Object.entries(entities).forEach(([key, entity]) => {
  929. const element = document.querySelector("#entity-" + key);
  930. results.entities.push({
  931. name: entity.identifier,
  932. scale: entity.scale,
  933. view: entity.view,
  934. x: element.dataset.x,
  935. y: element.dataset.y
  936. });
  937. });
  938. const unit = document.querySelector("#options-height-unit").value;
  939. results.world = {
  940. height: config.height.toNumber(unit),
  941. unit: unit
  942. }
  943. return results;
  944. }
  945. function copyScene() {
  946. const results = exportScene();
  947. navigator.clipboard.writeText(JSON.stringify(results))
  948. alert("Scene copied to clipboard. Paste text into the page to load the scene.");
  949. }
  950. // TODO - don't just search through every single entity
  951. // probably just have a way to do lookups directly
  952. function findEntity(name) {
  953. return availableEntitiesByName[name];
  954. }
  955. function importScene(data) {
  956. removeAllEntities();
  957. data.entities.forEach(entityInfo => {
  958. const entity = findEntity(entityInfo.name).constructor();
  959. entity.scale = entityInfo.scale
  960. displayEntity(entity, entityInfo.view, entityInfo.x, entityInfo.y);
  961. });
  962. config.height = math.unit(data.world.height, data.world.unit);
  963. document.querySelector("#options-height-unit").value = data.world.unit;
  964. updateSizes();
  965. }