map-editor.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312
  1. (function(){
  2. var domReady = (window.MG && window.MG.domReady) || window.__MG_domReady || function(cb){ if (document.readyState==='loading') document.addEventListener('DOMContentLoaded', cb); else cb(); };
  3. domReady(function(){
  4. // On attend que la variable mapData soit définie dans la vue (home.php injecte mapData)
  5. if (typeof window.mapData === 'undefined' && typeof mapData !== 'undefined') {
  6. window.mapData = mapData;
  7. }
  8. // --- Début du code de MapEditor (copié depuis l'ancien fichier non-modulaire) ---
  9. class MapEditor {
  10. constructor() {
  11. this.canvas = document.getElementById('mapCanvas');
  12. this.container = document.querySelector('.map-canvas-container');
  13. this.zoomLevel = 1;
  14. this.panOffset = { x: 0, y: 0 };
  15. this.isDragging = false;
  16. this.lastMousePos = { x: 0, y: 0 };
  17. this.selectedTile = null;
  18. this.tileSize = 50; // Rayon de l'hexagone (du centre au sommet)
  19. this.init();
  20. }
  21. init() {
  22. if (!this.canvas) {
  23. console.error('MapEditor: Élément canvas non trouvé!');
  24. return;
  25. }
  26. if (!this.container) {
  27. console.error('MapEditor: Conteneur non trouvé!');
  28. return;
  29. }
  30. this.setupCanvas();
  31. this.renderMap();
  32. this.setupEventListeners();
  33. this.hideLoading();
  34. this.fitToScreen();
  35. }
  36. setupCanvas() {
  37. this.canvas.style.transformOrigin = '0 0';
  38. }
  39. axialToPixel(q, r) {
  40. if (window.MG && window.MG.geom && typeof window.MG.geom.axialToPixel === 'function') {
  41. return window.MG.geom.axialToPixel(this.tileSize, q, r);
  42. }
  43. // fallback local implementation
  44. const size = this.tileSize;
  45. const x = size * Math.sqrt(3) * (q + r / 2);
  46. const y = size * 1.5 * r;
  47. return { x, y };
  48. }
  49. renderMap() {
  50. this.canvas.innerHTML = '';
  51. const hexWidth = this.tileSize * Math.sqrt(3);
  52. const hexHeight = this.tileSize * 2;
  53. const mapWidth = (window.mapData && window.mapData.width) || 5;
  54. const mapHeight = (window.mapData && window.mapData.height) || 5;
  55. const radius = Math.floor((Math.min(mapWidth, mapHeight) - 1) / 2);
  56. if (radius < 0) return;
  57. const positions = [];
  58. let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity;
  59. for (let q = -radius; q <= radius; q++) {
  60. const rMin = Math.max(-radius, -q - radius);
  61. const rMax = Math.min(radius, -q + radius);
  62. for (let r = rMin; r <= rMax; r++) {
  63. const { x, y } = this.axialToPixel(q, r);
  64. positions.push({ q, r, x, y });
  65. const halfW = hexWidth / 2;
  66. const halfH = hexHeight / 2;
  67. if (x - halfW < minX) minX = x - halfW;
  68. if (y - halfH < minY) minY = y - halfH;
  69. if (x + halfW > maxX) maxX = x + halfW;
  70. if (y + halfH > maxY) maxY = y + halfH;
  71. }
  72. }
  73. const padding = 20;
  74. const canvasWidth = (maxX - minX) + hexWidth + padding;
  75. const canvasHeight = (maxY - minY) + hexHeight + padding;
  76. this.canvas.style.width = canvasWidth + 'px';
  77. this.canvas.style.height = canvasHeight + 'px';
  78. const offsetX = -minX + padding / 2;
  79. const offsetY = -minY + padding / 2;
  80. for (const pos of positions) {
  81. this.renderHexagon(pos.q, pos.r, pos.x + offsetX, pos.y + offsetY, hexWidth, hexHeight);
  82. }
  83. }
  84. renderHexagon(q, r, x, y, hexWidth, hexHeight) {
  85. const hex = document.createElement('div');
  86. hex.className = 'hexagon';
  87. hex.dataset.q = q;
  88. hex.dataset.r = r;
  89. const expansion = Math.round(hexWidth * 0.004 * 1000) / 1000;
  90. const adjWidth = hexWidth + expansion;
  91. const adjHeight = hexHeight + expansion;
  92. const halfW = adjWidth / 2;
  93. const halfH = adjHeight / 2;
  94. hex.style.width = adjWidth + 'px';
  95. hex.style.height = adjHeight + 'px';
  96. hex.style.left = (Math.round((x - halfW) * 1000) / 1000) + 'px';
  97. hex.style.top = (Math.round((y - halfH) * 1000) / 1000) + 'px';
  98. hex.style.position = 'absolute';
  99. hex.style.cursor = 'pointer';
  100. hex.style.transition = 'background-color 0.2s';
  101. hex.style.backgroundColor = '#ffffff';
  102. hex.style.clipPath = 'polygon(50% 0%, 100% 25%, 100% 75%, 50% 100%, 0% 75%, 0% 25%)';
  103. hex.addEventListener('click', (e) => {
  104. e.stopPropagation();
  105. this.selectTile(q, r);
  106. });
  107. hex.addEventListener('mouseenter', () => {
  108. if (!this.selectedTile || this.selectedTile.q !== q || this.selectedTile.r !== r) {
  109. hex.style.backgroundColor = '#e3f2fd';
  110. }
  111. });
  112. hex.addEventListener('mouseleave', () => {
  113. if (!this.selectedTile || this.selectedTile.q !== q || this.selectedTile.r !== r) {
  114. hex.style.backgroundColor = '#ffffff';
  115. }
  116. });
  117. this.canvas.appendChild(hex);
  118. }
  119. selectTile(q, r) {
  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. this.selectedTile = { q, r };
  128. const hex = this.canvas.querySelector(`[data-q="${q}"][data-r="${r}"]`);
  129. if (hex) {
  130. hex.style.backgroundColor = '#2196f3';
  131. hex.style.borderColor = '#1976d2';
  132. }
  133. // Émettre un événement DOM global pour signaler la sélection
  134. try {
  135. const ev = new CustomEvent('mg:tileSelected', { detail: { q, r } });
  136. window.dispatchEvent(ev);
  137. } catch (e) {
  138. // ignore
  139. }
  140. this.showTileInfo(q, r);
  141. }
  142. showTileInfo(q, r) {
  143. const tileInfo = document.getElementById('tileInfo');
  144. const tilePosition = document.getElementById('tilePosition');
  145. const tileType = document.getElementById('tileType');
  146. const tileProperties = document.getElementById('tileProperties');
  147. tilePosition.textContent = `Q: ${q}, R: ${r}`;
  148. // récupérer le type si défini dans mapData.tiles ou fallback
  149. let type = 'Vide';
  150. try {
  151. if (window.mapData && window.mapData.tiles) {
  152. const key = `${q},${r}`;
  153. const t = window.mapData.tiles[key] || (window.mapData.tiles[q] && window.mapData.tiles[q][r]);
  154. if (t && t.type) type = t.type;
  155. }
  156. } catch (e) {
  157. // ignore
  158. }
  159. tileType.textContent = type;
  160. // Montrer la sidebar des types de tuile
  161. const tileTypeTool = document.getElementById('tile-type-tool');
  162. if (tileTypeTool) tileTypeTool.style.display = 'block';
  163. // émettre événement tileInfo affiché
  164. try { window.dispatchEvent(new CustomEvent('mg:tileInfoShown', { detail: { q, r, type } })); } catch (e) {}
  165. tileProperties.innerHTML = `...`;
  166. tileInfo.style.display = 'block';
  167. }
  168. setupEventListeners() {
  169. document.getElementById('zoomIn').addEventListener('click', (e) => { e.preventDefault(); this.zoom(1.2); });
  170. document.getElementById('zoomOut').addEventListener('click', (e) => { e.preventDefault(); this.zoom(0.8); });
  171. document.getElementById('fitToScreen').addEventListener('click', (e) => { e.preventDefault(); this.fitToScreen(); });
  172. this.container.addEventListener('mousedown', (e) => {
  173. if (e.target === this.container) {
  174. this.isDragging = true;
  175. this.lastMousePos = { x: e.clientX, y: e.clientY };
  176. this.canvas.style.cursor = 'grabbing';
  177. }
  178. });
  179. document.addEventListener('mousemove', (e) => {
  180. if (this.isDragging) {
  181. const deltaX = e.clientX - this.lastMousePos.x;
  182. const deltaY = e.clientY - this.lastMousePos.y;
  183. this.panOffset.x += deltaX;
  184. this.panOffset.y += deltaY;
  185. this.updateTransform();
  186. this.lastMousePos = { x: e.clientX, y: e.clientY };
  187. }
  188. });
  189. document.addEventListener('mouseup', () => { this.isDragging = false; this.canvas.style.cursor = 'grab'; });
  190. this.container.addEventListener('click', () => {
  191. if (this.selectedTile) { this.selectTile(null, null); document.getElementById('tileInfo').style.display = 'none'; }
  192. });
  193. }
  194. zoom(factor) {
  195. if (window.MG && window.MG.geom && typeof window.MG.geom.computeZoom === 'function') {
  196. this.zoomLevel = window.MG.geom.computeZoom(this.zoomLevel, factor);
  197. } else {
  198. this.zoomLevel *= factor;
  199. this.zoomLevel = Math.max(0.1, Math.min(5, this.zoomLevel));
  200. }
  201. this.updateTransform();
  202. const el = document.getElementById('zoomLevel'); if (el) el.textContent = Math.round(this.zoomLevel * 100);
  203. }
  204. fitToScreen() { const containerRect = this.container.getBoundingClientRect(); const canvasRect = this.canvas.getBoundingClientRect(); const scaleX = containerRect.width / canvasRect.width; const scaleY = containerRect.height / canvasRect.height; const scale = Math.min(scaleX, scaleY) * 0.9; this.zoomLevel = scale; this.panOffset = { x: 0, y: 0 }; this.updateTransform(); document.getElementById('zoomLevel').textContent = Math.round(this.zoomLevel * 100); }
  205. updateTransform() { const tx = Math.round(this.panOffset.x); const ty = Math.round(this.panOffset.y); this.canvas.style.transform = `translate(${tx}px, ${ty}px) scale(${this.zoomLevel})`; }
  206. hideLoading() { const loading = document.getElementById('mapLoading'); if (loading) { loading.classList.remove('d-flex'); loading.style.display = 'none'; } }
  207. }
  208. // Initialiser l'éditeur
  209. (function() {
  210. function initMapEditor() {
  211. try { new MapEditor(); } catch (error) { console.error('Erreur lors de la création de MapEditor:', error); }
  212. }
  213. if (document.readyState === 'loading') {
  214. document.addEventListener('DOMContentLoaded', initMapEditor);
  215. } else {
  216. initMapEditor();
  217. }
  218. })();
  219. // --- Fin du code MapEditor ---
  220. });
  221. })();
  222. // Listeners pour la sidebar (gestion des types de tuile)
  223. (function(){
  224. function onTypeClick(e){
  225. const btn = e.currentTarget;
  226. const type = btn.dataset.type;
  227. // Mettre à jour l'affichage dans #tileType
  228. const tileTypeEl = document.getElementById('tileType');
  229. if (tileTypeEl) tileTypeEl.textContent = type;
  230. // Si une tuile est sélectionnée on met à jour window.mapData (structure minimale)
  231. try {
  232. const selected = (window.MG && window.MG.selectedTile) || null;
  233. // Certains setups n'exposent pas MG.selectedTile. On récupère depuis l'événement global si nécessaire
  234. let q=null,r=null;
  235. if (selected && typeof selected.q !== 'undefined') { q=selected.q; r=selected.r; }
  236. // fallback: chercher un élément hexagon sélectionné
  237. if (q===null) {
  238. const el = document.querySelector('.hexagon[style*="background-color: rgb(33, 150, 243)"]') || document.querySelector('.hexagon[style*="#2196f3"]');
  239. if (el) { q = parseInt(el.dataset.q,10); r = parseInt(el.dataset.r,10); }
  240. }
  241. if (q!==null && typeof q !== 'undefined'){
  242. window.mapData = window.mapData || {};
  243. window.mapData.tiles = window.mapData.tiles || {};
  244. const key = `${q},${r}`;
  245. window.mapData.tiles[key] = window.mapData.tiles[key] || {};
  246. window.mapData.tiles[key].type = type;
  247. // Dispatch event pour signaler changement de type
  248. try { window.dispatchEvent(new CustomEvent('mg:tileTypeChanged', { detail: { q, r, type } })); } catch(e){}
  249. }
  250. } catch (err){ console.error('Erreur lors du changement de type de tuile', err); }
  251. }
  252. document.addEventListener('DOMContentLoaded', function(){
  253. const opts = document.querySelectorAll('.tile-type-option');
  254. opts.forEach(o => o.addEventListener('click', onTypeClick));
  255. // Écouter la sélection de tuile pour stocker la sélection dans MG.selectedTile si possible
  256. window.addEventListener('mg:tileSelected', function(ev){
  257. try { window.MG = window.MG || {}; window.MG.selectedTile = ev.detail; } catch(e){}
  258. });
  259. });
  260. })();