map-editor.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441
  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. // Guard: si pas de mapData ou pas d'élément canvas, ne pas initialiser l'éditeur
  9. if (typeof window.mapData === 'undefined' || !document.getElementById('mapCanvas')) {
  10. // Rien à faire sur cette page
  11. return;
  12. }
  13. // --- Début du code de MapEditor (copié depuis l'ancien fichier non-modulaire) ---
  14. class MapEditor {
  15. constructor() {
  16. this.canvas = document.getElementById('mapCanvas');
  17. this.container = document.querySelector('.map-canvas-container');
  18. this.zoomLevel = 1;
  19. this.panOffset = { x: 0, y: 0 };
  20. this.isDragging = false;
  21. this.lastMousePos = { x: 0, y: 0 };
  22. this.selectedTile = null;
  23. this.tileSize = 50; // Rayon de l'hexagone (du centre au sommet)
  24. this.init();
  25. }
  26. init() {
  27. if (!this.canvas) {
  28. console.error('MapEditor: Élément canvas non trouvé!');
  29. return;
  30. }
  31. if (!this.container) {
  32. console.error('MapEditor: Conteneur non trouvé!');
  33. return;
  34. }
  35. this.setupCanvas();
  36. this.renderMap();
  37. this.setupEventListeners();
  38. this.hideLoading();
  39. this.fitToScreen();
  40. }
  41. setupCanvas() {
  42. this.canvas.style.transformOrigin = '0 0';
  43. }
  44. axialToPixel(q, r) {
  45. if (window.MG && window.MG.geom && typeof window.MG.geom.axialToPixel === 'function') {
  46. return window.MG.geom.axialToPixel(this.tileSize, q, r);
  47. }
  48. // fallback local implementation
  49. const size = this.tileSize;
  50. const x = size * Math.sqrt(3) * (q + r / 2);
  51. const y = size * 1.5 * r;
  52. return { x, y };
  53. }
  54. renderMap() {
  55. this.canvas.innerHTML = '';
  56. const hexWidth = this.tileSize * Math.sqrt(3);
  57. const hexHeight = this.tileSize * 2;
  58. const mapWidth = (window.mapData && window.mapData.width) || 5;
  59. const mapHeight = (window.mapData && window.mapData.height) || 5;
  60. const radius = Math.floor((Math.min(mapWidth, mapHeight) - 1) / 2);
  61. if (radius < 0) return;
  62. const positions = [];
  63. let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity;
  64. for (let q = -radius; q <= radius; q++) {
  65. const rMin = Math.max(-radius, -q - radius);
  66. const rMax = Math.min(radius, -q + radius);
  67. for (let r = rMin; r <= rMax; r++) {
  68. const { x, y } = this.axialToPixel(q, r);
  69. positions.push({ q, r, x, y });
  70. const halfW = hexWidth / 2;
  71. const halfH = hexHeight / 2;
  72. if (x - halfW < minX) minX = x - halfW;
  73. if (y - halfH < minY) minY = y - halfH;
  74. if (x + halfW > maxX) maxX = x + halfW;
  75. if (y + halfH > maxY) maxY = y + halfH;
  76. }
  77. }
  78. const padding = 20;
  79. const canvasWidth = (maxX - minX) + hexWidth + padding;
  80. const canvasHeight = (maxY - minY) + hexHeight + padding;
  81. this.canvas.style.width = canvasWidth + 'px';
  82. this.canvas.style.height = canvasHeight + 'px';
  83. const offsetX = -minX + padding / 2;
  84. const offsetY = -minY + padding / 2;
  85. for (const pos of positions) {
  86. this.renderHexagon(pos.q, pos.r, pos.x + offsetX, pos.y + offsetY, hexWidth, hexHeight);
  87. }
  88. }
  89. renderHexagon(q, r, x, y, hexWidth, hexHeight) {
  90. const hex = document.createElement('div');
  91. hex.className = 'hexagon';
  92. hex.dataset.q = q;
  93. hex.dataset.r = r;
  94. const expansion = Math.round(hexWidth * 0.004 * 1000) / 1000;
  95. const adjWidth = hexWidth + expansion;
  96. const adjHeight = hexHeight + expansion;
  97. const halfW = adjWidth / 2;
  98. const halfH = adjHeight / 2;
  99. hex.style.width = adjWidth + 'px';
  100. hex.style.height = adjHeight + 'px';
  101. hex.style.left = (Math.round((x - halfW) * 1000) / 1000) + 'px';
  102. hex.style.top = (Math.round((y - halfH) * 1000) / 1000) + 'px';
  103. hex.style.position = 'absolute';
  104. hex.style.cursor = 'pointer';
  105. hex.style.transition = 'background-color 0.2s';
  106. hex.style.backgroundColor = '#ffffff';
  107. hex.style.clipPath = 'polygon(50% 0%, 100% 25%, 100% 75%, 50% 100%, 0% 75%, 0% 25%)';
  108. // Ajouter le SVG selon le type de tuile
  109. this.updateHexagonContent(hex, q, r);
  110. hex.addEventListener('click', (e) => {
  111. e.stopPropagation();
  112. this.selectTile(q, r);
  113. });
  114. hex.addEventListener('mouseenter', () => {
  115. if (!this.selectedTile || this.selectedTile.q !== q || this.selectedTile.r !== r) {
  116. hex.style.backgroundColor = '#e3f2fd';
  117. }
  118. });
  119. hex.addEventListener('mouseleave', () => {
  120. if (!this.selectedTile || this.selectedTile.q !== q || this.selectedTile.r !== r) {
  121. hex.style.backgroundColor = '#ffffff';
  122. }
  123. });
  124. this.canvas.appendChild(hex);
  125. }
  126. updateHexagonContent(hex, q, r) {
  127. // Vider le contenu existant
  128. hex.innerHTML = '';
  129. // Récupérer le type de tuile
  130. let type = null;
  131. try {
  132. if (window.mapData && window.mapData.tiles) {
  133. const key = `${q},${r}`;
  134. const tileData = window.mapData.tiles[key];
  135. if (tileData && tileData.type) {
  136. type = tileData.type;
  137. }
  138. }
  139. } catch (e) {
  140. // ignore
  141. }
  142. if (type && type !== 'empty') {
  143. // Récupérer le SVG depuis les options de la sidebar
  144. const radio = document.querySelector(`.tile-type-radio[value="${type}"]`);
  145. if (radio) {
  146. const label = radio.parentElement.querySelector('.form-check-label');
  147. if (label) {
  148. const svg = label.querySelector('svg');
  149. if (svg) {
  150. const svgClone = svg.cloneNode(true);
  151. // Ajuster la taille du SVG pour la tuile
  152. svgClone.setAttribute('width', '100%');
  153. svgClone.setAttribute('height', '100%');
  154. svgClone.style.position = 'absolute';
  155. svgClone.style.top = '0';
  156. svgClone.style.left = '0';
  157. svgClone.style.pointerEvents = 'none';
  158. hex.appendChild(svgClone);
  159. }
  160. }
  161. }
  162. }
  163. }
  164. selectTile(q, r) {
  165. if (this.selectedTile) {
  166. const prevHex = this.canvas.querySelector(`[data-q="${this.selectedTile.q}"][data-r="${this.selectedTile.r}"]`);
  167. if (prevHex) {
  168. prevHex.style.backgroundColor = '#ffffff';
  169. prevHex.style.borderColor = '#666';
  170. }
  171. }
  172. this.selectedTile = { q, r };
  173. const hex = this.canvas.querySelector(`[data-q="${q}"][data-r="${r}"]`);
  174. if (hex) {
  175. hex.style.backgroundColor = '#2196f3';
  176. hex.style.borderColor = '#1976d2';
  177. }
  178. // Émettre un événement DOM global pour signaler la sélection
  179. try {
  180. const ev = new CustomEvent('mg:tileSelected', { detail: { q, r } });
  181. window.dispatchEvent(ev);
  182. } catch (e) {
  183. // ignore
  184. }
  185. this.showTileInfo(q, r);
  186. }
  187. showTileInfo(q, r) {
  188. const tileInfo = document.getElementById('tileInfo');
  189. const tilePosition = document.getElementById('tilePosition');
  190. const tileType = document.getElementById('tileType');
  191. const tileProperties = document.getElementById('tileProperties');
  192. tilePosition.textContent = `Q: ${q}, R: ${r}`;
  193. // récupérer le type si défini dans mapData.tiles ou fallback
  194. let type = 'Vide';
  195. try {
  196. if (window.mapData && window.mapData.tiles) {
  197. const key = `${q},${r}`;
  198. const t = window.mapData.tiles[key] || (window.mapData.tiles[q] && window.mapData.tiles[q][r]);
  199. if (t && t.type) type = t.type;
  200. }
  201. } catch (e) {
  202. // ignore
  203. }
  204. tileType.textContent = type;
  205. // Montrer la sidebar des types de tuile
  206. const tileTypeTool = document.getElementById('tile-type-tool');
  207. if (tileTypeTool) tileTypeTool.style.display = 'block';
  208. // émettre événement tileInfo affiché
  209. try { window.dispatchEvent(new CustomEvent('mg:tileInfoShown', { detail: { q, r, type } })); } catch (e) {}
  210. tileProperties.innerHTML = `...`;
  211. tileInfo.style.display = 'block';
  212. }
  213. setupEventListeners() {
  214. document.getElementById('zoomIn').addEventListener('click', (e) => { e.preventDefault(); this.zoom(1.2); });
  215. document.getElementById('zoomOut').addEventListener('click', (e) => { e.preventDefault(); this.zoom(0.8); });
  216. document.getElementById('fitToScreen').addEventListener('click', (e) => { e.preventDefault(); this.fitToScreen(); });
  217. this.container.addEventListener('mousedown', (e) => {
  218. if (e.target === this.container) {
  219. this.isDragging = true;
  220. this.lastMousePos = { x: e.clientX, y: e.clientY };
  221. this.canvas.style.cursor = 'grabbing';
  222. }
  223. });
  224. document.addEventListener('mousemove', (e) => {
  225. if (this.isDragging) {
  226. const deltaX = e.clientX - this.lastMousePos.x;
  227. const deltaY = e.clientY - this.lastMousePos.y;
  228. this.panOffset.x += deltaX;
  229. this.panOffset.y += deltaY;
  230. this.updateTransform();
  231. this.lastMousePos = { x: e.clientX, y: e.clientY };
  232. }
  233. });
  234. document.addEventListener('mouseup', () => { this.isDragging = false; this.canvas.style.cursor = 'grab'; });
  235. this.container.addEventListener('click', () => {
  236. if (this.selectedTile) { this.selectTile(null, null); document.getElementById('tileInfo').style.display = 'none'; }
  237. });
  238. }
  239. zoom(factor) {
  240. if (window.MG && window.MG.geom && typeof window.MG.geom.computeZoom === 'function') {
  241. this.zoomLevel = window.MG.geom.computeZoom(this.zoomLevel, factor);
  242. } else {
  243. this.zoomLevel *= factor;
  244. this.zoomLevel = Math.max(0.1, Math.min(5, this.zoomLevel));
  245. }
  246. this.updateTransform();
  247. const el = document.getElementById('zoomLevel'); if (el) el.textContent = Math.round(this.zoomLevel * 100);
  248. }
  249. 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); }
  250. 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})`; }
  251. hideLoading() { const loading = document.getElementById('mapLoading'); if (loading) { loading.classList.remove('d-flex'); loading.style.display = 'none'; } }
  252. }
  253. // Initialiser l'éditeur
  254. (function() {
  255. function initMapEditor() {
  256. try { new MapEditor(); } catch (error) { console.error('Erreur lors de la création de MapEditor:', error); }
  257. }
  258. if (document.readyState === 'loading') {
  259. document.addEventListener('DOMContentLoaded', function(){ if (document.getElementById('mapCanvas')) initMapEditor(); });
  260. } else {
  261. if (document.getElementById('mapCanvas')) initMapEditor();
  262. }
  263. })();
  264. // --- Fin du code MapEditor ---
  265. });
  266. })();
  267. // Listeners pour la sidebar (gestion des types de tuile)
  268. (function(){
  269. function onTypeClick(e){
  270. const input = e.currentTarget;
  271. const type = input.value;
  272. // Mettre à jour l'affichage dans #tileType
  273. const tileTypeEl = document.getElementById('tileType');
  274. if (tileTypeEl) tileTypeEl.textContent = type;
  275. // Si une tuile est sélectionnée on met à jour window.mapData (structure minimale)
  276. try {
  277. const selected = (window.MG && window.MG.selectedTile) || null;
  278. // Certains setups n'exposent pas MG.selectedTile. On récupère depuis l'événement global si nécessaire
  279. let q=null,r=null;
  280. if (selected && typeof selected.q !== 'undefined') { q=selected.q; r=selected.r; }
  281. // fallback: chercher un élément hexagon sélectionné
  282. if (q===null) {
  283. const el = document.querySelector('.hexagon[style*="background-color: rgb(33, 150, 243)"]') || document.querySelector('.hexagon[style*="#2196f3"]');
  284. if (el) { q = parseInt(el.dataset.q,10); r = parseInt(el.dataset.r,10); }
  285. }
  286. if (q!==null && typeof q !== 'undefined'){
  287. window.mapData = window.mapData || {};
  288. window.mapData.tiles = window.mapData.tiles || {};
  289. const key = `${q},${r}`;
  290. window.mapData.tiles[key] = window.mapData.tiles[key] || {};
  291. window.mapData.tiles[key].type = type;
  292. // Mettre à jour visuellement la tuile
  293. const hex = document.querySelector(`.hexagon[data-q="${q}"][data-r="${r}"]`);
  294. if (hex) {
  295. updateHexagonContent(hex, q, r);
  296. }
  297. // Dispatch event pour signaler changement de type
  298. try { window.dispatchEvent(new CustomEvent('mg:tileTypeChanged', { detail: { q, r, type } })); } catch(e){}
  299. }
  300. } catch (err){ console.error('Erreur lors du changement de type de tuile', err); }
  301. }
  302. // Fonction pour mettre à jour le contenu d'un hexagone selon son type
  303. function updateHexagonContent(hex, q, r) {
  304. // Vider le contenu existant
  305. hex.innerHTML = '';
  306. // Récupérer le type de tuile
  307. let type = null;
  308. try {
  309. if (window.mapData && window.mapData.tiles) {
  310. const key = `${q},${r}`;
  311. const tileData = window.mapData.tiles[key];
  312. if (tileData && tileData.type) {
  313. type = tileData.type;
  314. }
  315. }
  316. } catch (e) {
  317. // ignore
  318. }
  319. if (type && type !== 'empty') {
  320. // Récupérer le SVG depuis les options de la sidebar
  321. const radio = document.querySelector(`.tile-type-radio[value="${type}"]`);
  322. if (radio) {
  323. const label = radio.parentElement.querySelector('.form-check-label');
  324. if (label) {
  325. const svg = label.querySelector('svg');
  326. if (svg) {
  327. const svgClone = svg.cloneNode(true);
  328. // Ajuster la taille du SVG pour la tuile
  329. svgClone.setAttribute('width', '100%');
  330. svgClone.setAttribute('height', '100%');
  331. svgClone.style.position = 'absolute';
  332. svgClone.style.top = '0';
  333. svgClone.style.left = '0';
  334. svgClone.style.pointerEvents = 'none';
  335. hex.appendChild(svgClone);
  336. }
  337. }
  338. }
  339. }
  340. }
  341. // Fonction pour mettre à jour les checkboxes selon le type de la tuile sélectionnée
  342. function updateTileTypeCheckboxes(type) {
  343. const radios = document.querySelectorAll('.tile-type-radio');
  344. radios.forEach(radio => {
  345. radio.checked = (radio.value === type);
  346. });
  347. }
  348. document.addEventListener('DOMContentLoaded', function(){
  349. const opts = document.querySelectorAll('.tile-type-radio');
  350. opts.forEach(o => o.addEventListener('change', onTypeClick));
  351. // Écouter la sélection de tuile pour mettre à jour les checkboxes
  352. window.addEventListener('mg:tileSelected', function(ev){
  353. try {
  354. window.MG = window.MG || {};
  355. window.MG.selectedTile = ev.detail;
  356. // Récupérer le type de la tuile sélectionnée et mettre à jour les checkboxes
  357. const { q, r } = ev.detail;
  358. const key = `${q},${r}`;
  359. const tileData = window.mapData && window.mapData.tiles && window.mapData.tiles[key];
  360. const type = tileData ? tileData.type : 'empty';
  361. updateTileTypeCheckboxes(type);
  362. } catch(e){}
  363. });
  364. // Écouter les changements de type de tuile pour mettre à jour les checkboxes
  365. window.addEventListener('mg:tileTypeChanged', function(ev){
  366. const { type, q, r } = ev.detail;
  367. updateTileTypeCheckboxes(type);
  368. // Mettre à jour visuellement la tuile
  369. const hex = document.querySelector(`.hexagon[data-q="${q}"][data-r="${r}"]`);
  370. if (hex) {
  371. updateHexagonContent(hex, q, r);
  372. }
  373. });
  374. });
  375. })();