| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441 |
- (function(){
- var domReady = (window.MG && window.MG.domReady) || window.__MG_domReady || function(cb){ if (document.readyState==='loading') document.addEventListener('DOMContentLoaded', cb); else cb(); };
- domReady(function(){
- // On attend que la variable mapData soit définie dans la vue (home.php injecte mapData)
- if (typeof window.mapData === 'undefined' && typeof mapData !== 'undefined') {
- window.mapData = mapData;
- }
- // Guard: si pas de mapData ou pas d'élément canvas, ne pas initialiser l'éditeur
- if (typeof window.mapData === 'undefined' || !document.getElementById('mapCanvas')) {
- // Rien à faire sur cette page
- return;
- }
- // --- Début du code de MapEditor (copié depuis l'ancien fichier non-modulaire) ---
- class MapEditor {
- constructor() {
- this.canvas = document.getElementById('mapCanvas');
- this.container = document.querySelector('.map-canvas-container');
- this.zoomLevel = 1;
- this.panOffset = { x: 0, y: 0 };
- this.isDragging = false;
- this.lastMousePos = { x: 0, y: 0 };
- this.selectedTile = null;
- this.tileSize = 50; // Rayon de l'hexagone (du centre au sommet)
- this.init();
- }
- init() {
- if (!this.canvas) {
- console.error('MapEditor: Élément canvas non trouvé!');
- return;
- }
- if (!this.container) {
- console.error('MapEditor: Conteneur non trouvé!');
- return;
- }
- this.setupCanvas();
- this.renderMap();
- this.setupEventListeners();
- this.hideLoading();
- this.fitToScreen();
- }
- setupCanvas() {
- this.canvas.style.transformOrigin = '0 0';
- }
- axialToPixel(q, r) {
- if (window.MG && window.MG.geom && typeof window.MG.geom.axialToPixel === 'function') {
- return window.MG.geom.axialToPixel(this.tileSize, q, r);
- }
- // fallback local implementation
- const size = this.tileSize;
- const x = size * Math.sqrt(3) * (q + r / 2);
- const y = size * 1.5 * r;
- return { x, y };
- }
- renderMap() {
- this.canvas.innerHTML = '';
- const hexWidth = this.tileSize * Math.sqrt(3);
- const hexHeight = this.tileSize * 2;
- const mapWidth = (window.mapData && window.mapData.width) || 5;
- const mapHeight = (window.mapData && window.mapData.height) || 5;
- const radius = Math.floor((Math.min(mapWidth, mapHeight) - 1) / 2);
- if (radius < 0) return;
- const positions = [];
- let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity;
- for (let q = -radius; q <= radius; q++) {
- const rMin = Math.max(-radius, -q - radius);
- const rMax = Math.min(radius, -q + radius);
- for (let r = rMin; r <= rMax; r++) {
- const { x, y } = this.axialToPixel(q, r);
- positions.push({ q, r, x, y });
- const halfW = hexWidth / 2;
- const halfH = hexHeight / 2;
- if (x - halfW < minX) minX = x - halfW;
- if (y - halfH < minY) minY = y - halfH;
- if (x + halfW > maxX) maxX = x + halfW;
- if (y + halfH > maxY) maxY = y + halfH;
- }
- }
- const padding = 20;
- const canvasWidth = (maxX - minX) + hexWidth + padding;
- const canvasHeight = (maxY - minY) + hexHeight + padding;
- this.canvas.style.width = canvasWidth + 'px';
- this.canvas.style.height = canvasHeight + 'px';
- const offsetX = -minX + padding / 2;
- const offsetY = -minY + padding / 2;
- for (const pos of positions) {
- this.renderHexagon(pos.q, pos.r, pos.x + offsetX, pos.y + offsetY, hexWidth, hexHeight);
- }
- }
- renderHexagon(q, r, x, y, hexWidth, hexHeight) {
- const hex = document.createElement('div');
- hex.className = 'hexagon';
- hex.dataset.q = q;
- hex.dataset.r = r;
- const expansion = Math.round(hexWidth * 0.004 * 1000) / 1000;
- const adjWidth = hexWidth + expansion;
- const adjHeight = hexHeight + expansion;
- const halfW = adjWidth / 2;
- const halfH = adjHeight / 2;
- hex.style.width = adjWidth + 'px';
- hex.style.height = adjHeight + 'px';
- hex.style.left = (Math.round((x - halfW) * 1000) / 1000) + 'px';
- hex.style.top = (Math.round((y - halfH) * 1000) / 1000) + 'px';
- hex.style.position = 'absolute';
- hex.style.cursor = 'pointer';
- hex.style.transition = 'background-color 0.2s';
- hex.style.backgroundColor = '#ffffff';
- hex.style.clipPath = 'polygon(50% 0%, 100% 25%, 100% 75%, 50% 100%, 0% 75%, 0% 25%)';
- // Ajouter le SVG selon le type de tuile
- this.updateHexagonContent(hex, q, r);
- hex.addEventListener('click', (e) => {
- e.stopPropagation();
- this.selectTile(q, r);
- });
- hex.addEventListener('mouseenter', () => {
- if (!this.selectedTile || this.selectedTile.q !== q || this.selectedTile.r !== r) {
- hex.style.backgroundColor = '#e3f2fd';
- }
- });
- hex.addEventListener('mouseleave', () => {
- if (!this.selectedTile || this.selectedTile.q !== q || this.selectedTile.r !== r) {
- hex.style.backgroundColor = '#ffffff';
- }
- });
- this.canvas.appendChild(hex);
- }
- updateHexagonContent(hex, q, r) {
- // Vider le contenu existant
- hex.innerHTML = '';
- // Récupérer le type de tuile
- let type = null;
- try {
- if (window.mapData && window.mapData.tiles) {
- const key = `${q},${r}`;
- const tileData = window.mapData.tiles[key];
- if (tileData && tileData.type) {
- type = tileData.type;
- }
- }
- } catch (e) {
- // ignore
- }
- if (type && type !== 'empty') {
- // Récupérer le SVG depuis les options de la sidebar
- const radio = document.querySelector(`.tile-type-radio[value="${type}"]`);
- if (radio) {
- const label = radio.parentElement.querySelector('.form-check-label');
- if (label) {
- const svg = label.querySelector('svg');
- if (svg) {
- const svgClone = svg.cloneNode(true);
- // Ajuster la taille du SVG pour la tuile
- svgClone.setAttribute('width', '100%');
- svgClone.setAttribute('height', '100%');
- svgClone.style.position = 'absolute';
- svgClone.style.top = '0';
- svgClone.style.left = '0';
- svgClone.style.pointerEvents = 'none';
- hex.appendChild(svgClone);
- }
- }
- }
- }
- }
- selectTile(q, r) {
- if (this.selectedTile) {
- const prevHex = this.canvas.querySelector(`[data-q="${this.selectedTile.q}"][data-r="${this.selectedTile.r}"]`);
- if (prevHex) {
- prevHex.style.backgroundColor = '#ffffff';
- prevHex.style.borderColor = '#666';
- }
- }
- this.selectedTile = { q, r };
- const hex = this.canvas.querySelector(`[data-q="${q}"][data-r="${r}"]`);
- if (hex) {
- hex.style.backgroundColor = '#2196f3';
- hex.style.borderColor = '#1976d2';
- }
- // Émettre un événement DOM global pour signaler la sélection
- try {
- const ev = new CustomEvent('mg:tileSelected', { detail: { q, r } });
- window.dispatchEvent(ev);
- } catch (e) {
- // ignore
- }
- this.showTileInfo(q, r);
- }
- showTileInfo(q, r) {
- const tileInfo = document.getElementById('tileInfo');
- const tilePosition = document.getElementById('tilePosition');
- const tileType = document.getElementById('tileType');
- const tileProperties = document.getElementById('tileProperties');
- tilePosition.textContent = `Q: ${q}, R: ${r}`;
- // récupérer le type si défini dans mapData.tiles ou fallback
- let type = 'Vide';
- try {
- if (window.mapData && window.mapData.tiles) {
- const key = `${q},${r}`;
- const t = window.mapData.tiles[key] || (window.mapData.tiles[q] && window.mapData.tiles[q][r]);
- if (t && t.type) type = t.type;
- }
- } catch (e) {
- // ignore
- }
- tileType.textContent = type;
- // Montrer la sidebar des types de tuile
- const tileTypeTool = document.getElementById('tile-type-tool');
- if (tileTypeTool) tileTypeTool.style.display = 'block';
- // émettre événement tileInfo affiché
- try { window.dispatchEvent(new CustomEvent('mg:tileInfoShown', { detail: { q, r, type } })); } catch (e) {}
- tileProperties.innerHTML = `...`;
- tileInfo.style.display = 'block';
- }
- setupEventListeners() {
- document.getElementById('zoomIn').addEventListener('click', (e) => { e.preventDefault(); this.zoom(1.2); });
- document.getElementById('zoomOut').addEventListener('click', (e) => { e.preventDefault(); this.zoom(0.8); });
- document.getElementById('fitToScreen').addEventListener('click', (e) => { e.preventDefault(); this.fitToScreen(); });
- this.container.addEventListener('mousedown', (e) => {
- if (e.target === this.container) {
- this.isDragging = true;
- this.lastMousePos = { x: e.clientX, y: e.clientY };
- this.canvas.style.cursor = 'grabbing';
- }
- });
- document.addEventListener('mousemove', (e) => {
- if (this.isDragging) {
- const deltaX = e.clientX - this.lastMousePos.x;
- const deltaY = e.clientY - this.lastMousePos.y;
- this.panOffset.x += deltaX;
- this.panOffset.y += deltaY;
- this.updateTransform();
- this.lastMousePos = { x: e.clientX, y: e.clientY };
- }
- });
- document.addEventListener('mouseup', () => { this.isDragging = false; this.canvas.style.cursor = 'grab'; });
- this.container.addEventListener('click', () => {
- if (this.selectedTile) { this.selectTile(null, null); document.getElementById('tileInfo').style.display = 'none'; }
- });
- }
- zoom(factor) {
- if (window.MG && window.MG.geom && typeof window.MG.geom.computeZoom === 'function') {
- this.zoomLevel = window.MG.geom.computeZoom(this.zoomLevel, factor);
- } else {
- this.zoomLevel *= factor;
- this.zoomLevel = Math.max(0.1, Math.min(5, this.zoomLevel));
- }
- this.updateTransform();
- const el = document.getElementById('zoomLevel'); if (el) el.textContent = Math.round(this.zoomLevel * 100);
- }
- 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); }
- 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})`; }
- hideLoading() { const loading = document.getElementById('mapLoading'); if (loading) { loading.classList.remove('d-flex'); loading.style.display = 'none'; } }
- }
- // Initialiser l'éditeur
- (function() {
- function initMapEditor() {
- try { new MapEditor(); } catch (error) { console.error('Erreur lors de la création de MapEditor:', error); }
- }
- if (document.readyState === 'loading') {
- document.addEventListener('DOMContentLoaded', function(){ if (document.getElementById('mapCanvas')) initMapEditor(); });
- } else {
- if (document.getElementById('mapCanvas')) initMapEditor();
- }
- })();
- // --- Fin du code MapEditor ---
- });
- })();
- // Listeners pour la sidebar (gestion des types de tuile)
- (function(){
- function onTypeClick(e){
- const input = e.currentTarget;
- const type = input.value;
- // Mettre à jour l'affichage dans #tileType
- const tileTypeEl = document.getElementById('tileType');
- if (tileTypeEl) tileTypeEl.textContent = type;
- // Si une tuile est sélectionnée on met à jour window.mapData (structure minimale)
- try {
- const selected = (window.MG && window.MG.selectedTile) || null;
- // Certains setups n'exposent pas MG.selectedTile. On récupère depuis l'événement global si nécessaire
- let q=null,r=null;
- if (selected && typeof selected.q !== 'undefined') { q=selected.q; r=selected.r; }
- // fallback: chercher un élément hexagon sélectionné
- if (q===null) {
- const el = document.querySelector('.hexagon[style*="background-color: rgb(33, 150, 243)"]') || document.querySelector('.hexagon[style*="#2196f3"]');
- if (el) { q = parseInt(el.dataset.q,10); r = parseInt(el.dataset.r,10); }
- }
- if (q!==null && typeof q !== 'undefined'){
- window.mapData = window.mapData || {};
- window.mapData.tiles = window.mapData.tiles || {};
- const key = `${q},${r}`;
- window.mapData.tiles[key] = window.mapData.tiles[key] || {};
- window.mapData.tiles[key].type = type;
- // Mettre à jour visuellement la tuile
- const hex = document.querySelector(`.hexagon[data-q="${q}"][data-r="${r}"]`);
- if (hex) {
- updateHexagonContent(hex, q, r);
- }
- // Dispatch event pour signaler changement de type
- try { window.dispatchEvent(new CustomEvent('mg:tileTypeChanged', { detail: { q, r, type } })); } catch(e){}
- }
- } catch (err){ console.error('Erreur lors du changement de type de tuile', err); }
- }
- // Fonction pour mettre à jour le contenu d'un hexagone selon son type
- function updateHexagonContent(hex, q, r) {
- // Vider le contenu existant
- hex.innerHTML = '';
- // Récupérer le type de tuile
- let type = null;
- try {
- if (window.mapData && window.mapData.tiles) {
- const key = `${q},${r}`;
- const tileData = window.mapData.tiles[key];
- if (tileData && tileData.type) {
- type = tileData.type;
- }
- }
- } catch (e) {
- // ignore
- }
- if (type && type !== 'empty') {
- // Récupérer le SVG depuis les options de la sidebar
- const radio = document.querySelector(`.tile-type-radio[value="${type}"]`);
- if (radio) {
- const label = radio.parentElement.querySelector('.form-check-label');
- if (label) {
- const svg = label.querySelector('svg');
- if (svg) {
- const svgClone = svg.cloneNode(true);
- // Ajuster la taille du SVG pour la tuile
- svgClone.setAttribute('width', '100%');
- svgClone.setAttribute('height', '100%');
- svgClone.style.position = 'absolute';
- svgClone.style.top = '0';
- svgClone.style.left = '0';
- svgClone.style.pointerEvents = 'none';
- hex.appendChild(svgClone);
- }
- }
- }
- }
- }
- // Fonction pour mettre à jour les checkboxes selon le type de la tuile sélectionnée
- function updateTileTypeCheckboxes(type) {
- const radios = document.querySelectorAll('.tile-type-radio');
- radios.forEach(radio => {
- radio.checked = (radio.value === type);
- });
- }
- document.addEventListener('DOMContentLoaded', function(){
- const opts = document.querySelectorAll('.tile-type-radio');
- opts.forEach(o => o.addEventListener('change', onTypeClick));
- // Écouter la sélection de tuile pour mettre à jour les checkboxes
- window.addEventListener('mg:tileSelected', function(ev){
- try {
- window.MG = window.MG || {};
- window.MG.selectedTile = ev.detail;
- // Récupérer le type de la tuile sélectionnée et mettre à jour les checkboxes
- const { q, r } = ev.detail;
- const key = `${q},${r}`;
- const tileData = window.mapData && window.mapData.tiles && window.mapData.tiles[key];
- const type = tileData ? tileData.type : 'empty';
- updateTileTypeCheckboxes(type);
- } catch(e){}
- });
- // Écouter les changements de type de tuile pour mettre à jour les checkboxes
- window.addEventListener('mg:tileTypeChanged', function(ev){
- const { type, q, r } = ev.detail;
- updateTileTypeCheckboxes(type);
- // Mettre à jour visuellement la tuile
- const hex = document.querySelector(`.hexagon[data-q="${q}"][data-r="${r}"]`);
- if (hex) {
- updateHexagonContent(hex, q, r);
- }
- });
- });
- })();
|