map-editor.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321
  1. // Configuration de l'éditeur de carte
  2. class MapEditor {
  3. constructor() {
  4. this.canvas = document.getElementById('mapCanvas');
  5. this.container = document.querySelector('.map-canvas-container');
  6. this.zoomLevel = 1;
  7. this.panOffset = { x: 0, y: 0 };
  8. this.isDragging = false;
  9. this.lastMousePos = { x: 0, y: 0 };
  10. this.selectedTile = null;
  11. this.tileSize = 50; // Rayon de l'hexagone (du centre au sommet)
  12. this.init();
  13. }
  14. init() {
  15. if (!this.canvas) {
  16. console.error('MapEditor: Élément canvas non trouvé!');
  17. return;
  18. }
  19. if (!this.container) {
  20. console.error('MapEditor: Conteneur non trouvé!');
  21. return;
  22. }
  23. this.setupCanvas();
  24. this.renderMap();
  25. this.setupEventListeners();
  26. this.hideLoading();
  27. this.fitToScreen();
  28. }
  29. setupCanvas() {
  30. // La taille du canvas est définie dynamiquement dans renderMap() selon l'enveloppe.
  31. this.canvas.style.transformOrigin = '0 0';
  32. }
  33. // Conversion axial -> pixels pour hexagones pointus (pointy-top)
  34. axialToPixel(q, r) {
  35. const size = this.tileSize; // rayon (centre -> sommet)
  36. const x = size * Math.sqrt(3) * (q + r / 2);
  37. const y = size * 1.5 * r; // 3/2 * size
  38. return { x, y };
  39. }
  40. renderMap() {
  41. this.canvas.innerHTML = '';
  42. // Dimensions d'un hexagone (boîte englobante)
  43. const hexWidth = this.tileSize * Math.sqrt(3);
  44. const hexHeight = this.tileSize * 2;
  45. // Rayon de la carte hexagonale (en tuiles)
  46. // On utilise le plus grand hexagone qui tient dans (mapWidth, mapHeight)
  47. const radius = Math.floor((Math.min(mapWidth, mapHeight) - 1) / 2);
  48. if (radius < 0) return;
  49. // Première passe: calculer toutes les positions et les bornes pour dimensionner le canvas
  50. const positions = [];
  51. let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity;
  52. for (let q = -radius; q <= radius; q++) {
  53. const rMin = Math.max(-radius, -q - radius);
  54. const rMax = Math.min(radius, -q + radius);
  55. for (let r = rMin; r <= rMax; r++) {
  56. const { x, y } = this.axialToPixel(q, r);
  57. positions.push({ q, r, x, y });
  58. // consider hex bounding box (center ± half size) when computing extents
  59. const halfW = hexWidth / 2;
  60. const halfH = hexHeight / 2;
  61. if (x - halfW < minX) minX = x - halfW;
  62. if (y - halfH < minY) minY = y - halfH;
  63. if (x + halfW > maxX) maxX = x + halfW;
  64. if (y + halfH > maxY) maxY = y + halfH;
  65. }
  66. }
  67. // Padding pour éviter des coupures visuelles
  68. const padding = 20;
  69. // Dimensionner le canvas d'après l'enveloppe + la taille d'un hex
  70. const canvasWidth = (maxX - minX) + hexWidth + padding;
  71. const canvasHeight = (maxY - minY) + hexHeight + padding;
  72. this.canvas.style.width = canvasWidth + 'px';
  73. this.canvas.style.height = canvasHeight + 'px';
  74. // Seconde passe: rendre chaque hexagone avec un offset pour commencer à (padding/2, padding/2)
  75. const offsetX = -minX + padding / 2;
  76. const offsetY = -minY + padding / 2;
  77. for (const pos of positions) {
  78. // pass center coordinates adjusted by offset; renderHexagon will place box centered on these
  79. this.renderHexagon(pos.q, pos.r, pos.x + offsetX, pos.y + offsetY, hexWidth, hexHeight);
  80. }
  81. }
  82. renderHexagon(q, r, x, y, hexWidth, hexHeight) {
  83. const hex = document.createElement('div');
  84. hex.className = 'hexagon';
  85. hex.dataset.q = q;
  86. hex.dataset.r = r;
  87. // Expansion fine juste pour fondre l'anti-aliasing (évite interstice ET chevauchement)
  88. const expansion = Math.round(hexWidth * 0.004 * 1000) / 1000;
  89. const adjWidth = hexWidth + expansion;
  90. const adjHeight = hexHeight + expansion;
  91. const halfW = adjWidth / 2;
  92. const halfH = adjHeight / 2;
  93. hex.style.width = adjWidth + 'px';
  94. hex.style.height = adjHeight + 'px';
  95. hex.style.left = (Math.round((x - halfW) * 1000) / 1000) + 'px';
  96. hex.style.top = (Math.round((y - halfH) * 1000) / 1000) + 'px';
  97. hex.style.position = 'absolute';
  98. hex.style.cursor = 'pointer';
  99. hex.style.transition = 'background-color 0.2s';
  100. hex.style.backgroundColor = '#ffffff';
  101. hex.style.clipPath = 'polygon(50% 0%, 100% 25%, 100% 75%, 50% 100%, 0% 75%, 0% 25%)';
  102. hex.addEventListener('click', (e) => {
  103. e.stopPropagation();
  104. this.selectTile(q, r);
  105. });
  106. hex.addEventListener('mouseenter', () => {
  107. if (!this.selectedTile || this.selectedTile.q !== q || this.selectedTile.r !== r) {
  108. hex.style.backgroundColor = '#e3f2fd';
  109. }
  110. });
  111. hex.addEventListener('mouseleave', () => {
  112. if (!this.selectedTile || this.selectedTile.q !== q || this.selectedTile.r !== r) {
  113. hex.style.backgroundColor = '#ffffff';
  114. }
  115. });
  116. this.canvas.appendChild(hex);
  117. }
  118. selectTile(q, r) {
  119. // Désélectionner la tuile précédente
  120. if (this.selectedTile) {
  121. const prevHex = this.canvas.querySelector(`[data-q="${this.selectedTile.q}"][data-r="${this.selectedTile.r}"]`);
  122. if (prevHex) {
  123. prevHex.style.backgroundColor = '#ffffff';
  124. prevHex.style.borderColor = '#666';
  125. }
  126. }
  127. // Sélectionner la nouvelle tuile
  128. this.selectedTile = { q, r };
  129. const hex = this.canvas.querySelector(`[data-q="${q}"][data-r="${r}"]`);
  130. if (hex) {
  131. hex.style.backgroundColor = '#2196f3';
  132. hex.style.borderColor = '#1976d2';
  133. }
  134. // Afficher les informations de la tuile
  135. this.showTileInfo(q, r);
  136. }
  137. showTileInfo(q, r) {
  138. const tileInfo = document.getElementById('tileInfo');
  139. const tilePosition = document.getElementById('tilePosition');
  140. const tileType = document.getElementById('tileType');
  141. const tileProperties = document.getElementById('tileProperties');
  142. tilePosition.textContent = `Q: ${q}, R: ${r}`;
  143. tileType.textContent = 'Vide'; // Par défaut
  144. // TODO: Récupérer les vraies propriétés de la tuile depuis les données
  145. tileProperties.innerHTML = `
  146. <div class="row">
  147. <div class="col-md-6">
  148. <label class="form-label small">Type de terrain</label>
  149. <select class="form-select form-select-sm">
  150. <option>Vide</option>
  151. <option>Forêt</option>
  152. <option>Montagne</option>
  153. <option>Eau</option>
  154. <option>Ville</option>
  155. <option>Route</option>
  156. </select>
  157. </div>
  158. <div class="col-md-6">
  159. <label class="form-label small">Élévation</label>
  160. <input type="number" class="form-control form-control-sm" placeholder="0">
  161. </div>
  162. </div>
  163. <div class="mt-2">
  164. <label class="form-label small">Ressources</label>
  165. <div class="input-group input-group-sm">
  166. <input type="text" class="form-control" placeholder="Ajouter une ressource...">
  167. <button class="btn btn-outline-secondary" type="button">+</button>
  168. </div>
  169. </div>
  170. `;
  171. tileInfo.style.display = 'block';
  172. }
  173. setupEventListeners() {
  174. console.log('Configuration des event listeners de zoom');
  175. // Zoom
  176. document.getElementById('zoomIn').addEventListener('click', (e) => {
  177. e.preventDefault();
  178. console.log('Bouton zoom in cliqué');
  179. this.zoom(1.2);
  180. });
  181. document.getElementById('zoomOut').addEventListener('click', (e) => {
  182. e.preventDefault();
  183. console.log('Bouton zoom out cliqué');
  184. this.zoom(0.8);
  185. });
  186. document.getElementById('fitToScreen').addEventListener('click', (e) => {
  187. e.preventDefault();
  188. console.log('Bouton fit to screen cliqué');
  189. this.fitToScreen();
  190. });
  191. // Déplacement (pan)
  192. this.container.addEventListener('mousedown', (e) => {
  193. if (e.target === this.container) {
  194. this.isDragging = true;
  195. this.lastMousePos = { x: e.clientX, y: e.clientY };
  196. this.canvas.style.cursor = 'grabbing';
  197. }
  198. });
  199. document.addEventListener('mousemove', (e) => {
  200. if (this.isDragging) {
  201. const deltaX = e.clientX - this.lastMousePos.x;
  202. const deltaY = e.clientY - this.lastMousePos.y;
  203. this.panOffset.x += deltaX;
  204. this.panOffset.y += deltaY;
  205. this.updateTransform();
  206. this.lastMousePos = { x: e.clientX, y: e.clientY };
  207. }
  208. });
  209. document.addEventListener('mouseup', () => {
  210. this.isDragging = false;
  211. this.canvas.style.cursor = 'grab';
  212. });
  213. // Désélectionner en cliquant sur le fond
  214. this.container.addEventListener('click', () => {
  215. if (this.selectedTile) {
  216. this.selectTile(null, null);
  217. document.getElementById('tileInfo').style.display = 'none';
  218. }
  219. });
  220. }
  221. zoom(factor) {
  222. this.zoomLevel *= factor;
  223. this.zoomLevel = Math.max(0.1, Math.min(5, this.zoomLevel)); // Limiter le zoom entre 0.1x et 5x
  224. this.updateTransform();
  225. document.getElementById('zoomLevel').textContent = Math.round(this.zoomLevel * 100);
  226. }
  227. fitToScreen() {
  228. const containerRect = this.container.getBoundingClientRect();
  229. const canvasRect = this.canvas.getBoundingClientRect();
  230. const scaleX = containerRect.width / canvasRect.width;
  231. const scaleY = containerRect.height / canvasRect.height;
  232. const scale = Math.min(scaleX, scaleY) * 0.9; // Laisser un peu de marge
  233. this.zoomLevel = scale;
  234. this.panOffset = { x: 0, y: 0 };
  235. this.updateTransform();
  236. document.getElementById('zoomLevel').textContent = Math.round(this.zoomLevel * 100);
  237. }
  238. updateTransform() {
  239. // Arrondir la translation pour éviter les sous-pixels qui créent des micro-interstices
  240. const tx = Math.round(this.panOffset.x);
  241. const ty = Math.round(this.panOffset.y);
  242. this.canvas.style.transform = `translate(${tx}px, ${ty}px) scale(${this.zoomLevel})`;
  243. }
  244. hideLoading() {
  245. const loading = document.getElementById('mapLoading');
  246. if (loading) {
  247. // Retirer les classes Bootstrap qui forcent display: flex
  248. loading.classList.remove('d-flex');
  249. loading.style.display = 'none';
  250. }
  251. }
  252. }
  253. // Initialiser l'éditeur de carte
  254. (function () {
  255. function initMapEditor() {
  256. if (typeof mapData === 'undefined') {
  257. console.error('MapEditor: mapData non défini');
  258. return;
  259. }
  260. try {
  261. new MapEditor();
  262. } catch (error) {
  263. console.error('Erreur lors de la création de MapEditor:', error);
  264. }
  265. }
  266. // Attendre que le DOM soit complètement chargé
  267. if (document.readyState === 'loading') {
  268. document.addEventListener('DOMContentLoaded', initMapEditor);
  269. } else {
  270. initMapEditor();
  271. }
  272. })();