using UnityEngine; using System.Collections.Generic; public class MapMaker2 : MonoBehaviour { [Header("Map Settings")] public int initialMapSize = 150; public int expansionSize = 50; public float playerDistanceThreshold = 20f; [Header("Simple Mode")] [Tooltip("Use simple static map generation (no exploration/expansion)")] public bool useSimpleMode = true; [Header("Exploration Settings")] [Tooltip("Use exploration system instead of expansion")] public bool useExplorationSystem = true; public void SetMapData(MapData newMapData) { mapData = newMapData; // Update the visualization if (mapVisualizer != null) { mapVisualizer.VisualizeMap(mapData); } else { Debug.LogWarning("⚠️ MapVisualizer is null, cannot update visualization"); } } public MapData GetMapData() { return mapData; } [Header("Exploration Settings")] public int explorationMapSize = 300; public int explorationInitialVisible = 80; [Header("Expansion Settings")] [Tooltip("Cooldown time between map expansions in seconds")] public float expansionCooldown = 5f; [Tooltip("Chance for terrain to continue from existing edge (0-1)")] [Range(0f, 1f)] public float terrainContinuityChance = 0.7f; [Header("Generation Settings")] public int seed = 12345; [Header("Visualization")] public MapVisualizer mapVisualizer; [Header("Debug")] public bool debugMode = false; private MapData mapData; private TerrainGenerator terrainGenerator; private FeatureGenerator featureGenerator; private ExpansionManager expansionManager; private ExplorationManager explorationManager; private Transform player; private float lastExpansionTime = 0f; void Start() { InitializeMap(); if (useSimpleMode) { GenerateCompleteMapWithTeamMarker(); } else if (useExplorationSystem) { InitializeExplorationSystem(); } else { GenerateInitialMap(); } } void Update() { // In simple mode, no expansion or exploration updates needed if (useSimpleMode) { // Only handle finding the player reference if missing if (player == null) { GameObject teamMarker = GameObject.Find("TeamMarker"); if (teamMarker != null) { player = teamMarker.transform; } } return; } // Only handle finding the player reference, not continuous exploration checks if (player == null) { // Debug log every few seconds to show player reference status if (Time.time % 3f < Time.deltaTime) { Debug.LogWarning($"🚫 MapMaker2 Update: Player reference is null! useExplorationSystem: {useExplorationSystem}"); // Try to find TeamMarker if not found GameObject teamMarker = GameObject.Find("TeamMarker"); if (teamMarker != null) { player = teamMarker.transform; } } } else if (!useExplorationSystem) { // Only run expansion checks for the old system CheckForExpansion(); } // Exploration system is now event-driven, no Update checks needed! } private void InitializeMap() { Random.InitState(seed); mapData = new MapData(initialMapSize, initialMapSize); terrainGenerator = new TerrainGenerator(); featureGenerator = new FeatureGenerator(); expansionManager = new ExpansionManager(this); explorationManager = new ExplorationManager(this); // Find player object - try multiple approaches GameObject playerObj = GameObject.FindGameObjectWithTag("Player"); // If no "Player" tag found, try finding by name patterns if (playerObj == null) { // Try common player names string[] playerNames = { "TeamMarker", "Player", "PlayerCharacter", "Team", "MainCharacter" }; foreach (string name in playerNames) { playerObj = GameObject.Find(name); if (playerObj != null) { Debug.LogWarning($"Found player object by name '{name}' but it doesn't have 'Player' tag. Consider adding the tag."); break; } } } if (playerObj != null) { player = playerObj.transform; } else { Debug.LogWarning("No player object found! Trying to find any object that might be the player..."); } // Initialize visualizer if not set if (mapVisualizer == null) mapVisualizer = GetComponent(); } private void GenerateInitialMap() { // Generate base terrain terrainGenerator.GenerateTerrain(mapData); // Generate features featureGenerator.GenerateFeatures(mapData); // Visualize the map VisualizeMap(); } /// /// Generate complete map with team marker placement - Simple Mode /// private void GenerateCompleteMapWithTeamMarker() { // Generate the full beautiful map using original generators terrainGenerator.GenerateTerrain(mapData); featureGenerator.GenerateFeatures(mapData); // Find a good settlement for team marker placement Vector2Int? settlementPos = FindBestSettlementForTeamMarker(); if (!settlementPos.HasValue) { // Fallback to center if no settlements found Vector2Int centerPos = new Vector2Int(mapData.Width / 2, mapData.Height / 2); // PlaceTeamMarkerAt(centerPos); Debug.LogWarning($"⚠️ No settlements found, placed team marker at center: {centerPos}"); } // Visualize the map VisualizeMap(); } /// /// Find the best settlement position for team marker placement /// private Vector2Int? FindBestSettlementForTeamMarker() { List settlements = new List(); // Find all towns and villages for (int x = 0; x < mapData.Width; x++) { for (int y = 0; y < mapData.Height; y++) { MapTile tile = mapData.GetTile(x, y); if (tile != null && (tile.featureType == FeatureType.Town || tile.featureType == FeatureType.Village)) { settlements.Add(new Vector2Int(x, y)); } } } if (settlements.Count == 0) return null; // Prefer towns over villages, and those closer to center Vector2 center = new Vector2(mapData.Width / 2f, mapData.Height / 2f); Vector2Int bestSettlement = settlements[0]; float bestScore = float.MinValue; foreach (Vector2Int settlement in settlements) { MapTile tile = mapData.GetTile(settlement.x, settlement.y); float score = 0; // Prefer towns (higher score) if (tile.featureType == FeatureType.Town) score += 100; else score += 50; // Village // Prefer locations closer to center (but not exactly center) float distanceToCenter = Vector2.Distance(settlement, center); score += Mathf.Max(0, 50 - distanceToCenter); // Closer to center = higher score if (score > bestScore) { bestScore = score; bestSettlement = settlement; } } return bestSettlement; } /// /// Place team marker at specified map coordinates /// private void PlaceTeamMarkerAt(Vector2Int mapPos) { // Remove existing team marker GameObject existingMarker = GameObject.Find("TeamMarker"); if (existingMarker != null) { DestroyImmediate(existingMarker); } // Create new team marker GameObject teamMarker = new GameObject("TeamMarkerMapMaker2"); // Position it correctly in world space teamMarker.transform.position = new Vector3(mapPos.x, 0.5f, mapPos.y); // Add visual representation GameObject visualMarker = GameObject.CreatePrimitive(PrimitiveType.Sphere); visualMarker.transform.SetParent(teamMarker.transform); visualMarker.transform.localPosition = Vector3.zero; visualMarker.transform.localScale = Vector3.one * 0.8f; // Make it green and distinctive Renderer renderer = visualMarker.GetComponent(); if (renderer != null) { renderer.material.color = Color.green; } // Add a tag for easy finding teamMarker.tag = "Player"; // Update player reference player = teamMarker.transform; } private void CheckForExpansion() { // Check if mapVisualizer is available and has valid tileSize if (mapVisualizer == null) { Debug.LogWarning("MapVisualizer is null! Cannot check for expansion."); return; } float tileSize = mapVisualizer.tileSize; if (tileSize <= 0) { Debug.LogWarning($"Invalid tile size: {tileSize}. Using default value of 1."); tileSize = 1f; } // Debug player position Vector2 playerPos = new Vector2(player.position.x / tileSize, player.position.z / tileSize); // Debug log every few seconds if (Time.time % 2f < Time.deltaTime) // Log every 2 seconds { } // Check cooldown to prevent rapid expansions if (Time.time - lastExpansionTime < expansionCooldown) return; if (expansionManager.ShouldExpand(playerPos, mapData)) { ExpandMap(playerPos); } } private void ExpandMap(Vector2 playerPos) { lastExpansionTime = Time.time; expansionManager.ExpandMap(mapData, playerPos, expansionSize); VisualizeMap(); // Update visualization } private void VisualizeMap() { if (mapVisualizer != null) { mapVisualizer.VisualizeMap(mapData); } } public TerrainGenerator GetTerrainGenerator() => terrainGenerator; public FeatureGenerator GetFeatureGenerator() => featureGenerator; public ExplorationManager GetExplorationManager() => explorationManager; // Public method to manually set player reference if automatic detection fails public void SetPlayer(Transform playerTransform) { player = playerTransform; } /// /// Enable Simple Mode - Beautiful map generation without exploration/expansion /// [ContextMenu("🎮 Enable Simple Mode (Beautiful Map + Team Marker)")] public void EnableSimpleMode() { useSimpleMode = true; useExplorationSystem = false; // Clear existing map visualization if (mapVisualizer != null) mapVisualizer.ClearAllTiles(); // Regenerate with simple mode mapData = new MapData(initialMapSize, initialMapSize); GenerateCompleteMapWithTeamMarker(); } // For debugging - regenerate map [ContextMenu("Regenerate Map")] public void RegenerateMap() { if (mapVisualizer != null) mapVisualizer.ClearAllTiles(); // Preserve current map size instead of resetting to initial size int currentWidth = mapData != null ? mapData.Width : initialMapSize; int currentHeight = mapData != null ? mapData.Height : initialMapSize; Random.InitState(seed); mapData = new MapData(currentWidth, currentHeight); terrainGenerator = new TerrainGenerator(); featureGenerator = new FeatureGenerator(); GenerateInitialMap(); } // For debugging - reset to original size [ContextMenu("Reset to Original Size")] public void ResetToOriginalSize() { if (mapVisualizer != null) mapVisualizer.ClearAllTiles(); InitializeMap(); GenerateInitialMap(); } // For debugging - force map expansion [ContextMenu("Force Map Expansion")] public void ForceExpansion() { Vector2 playerPos; if (player != null) { float tileSize = mapVisualizer != null && mapVisualizer.tileSize > 0 ? mapVisualizer.tileSize : 1f; playerPos = new Vector2(player.position.x / tileSize, player.position.z / tileSize); } else { // If no player, expand from center-right edge to test the system playerPos = new Vector2(mapData.Width - 10, mapData.Height / 2); Debug.LogWarning("No player found, using test position for forced expansion"); } lastExpansionTime = 0f; // Reset cooldown ExpandMap(playerPos); } // For debugging - manually set TeamMarker as player [ContextMenu("Set TeamMarker as Player")] public void SetTeamMarkerAsPlayer() { GameObject teamMarker = GameObject.Find("TeamMarker"); if (teamMarker != null) { SetPlayer(teamMarker.transform); } else { Debug.LogError("TeamMarker object not found!"); } } // === Exploration System Methods === private void InitializeExplorationSystem() { if (explorationManager == null) { Debug.LogError("❌ ExplorationManager is null! Cannot initialize exploration system."); return; } explorationManager.fullMapWidth = explorationMapSize; explorationManager.fullMapHeight = explorationMapSize; explorationManager.initialVisibleSize = explorationInitialVisible; explorationManager.InitializeExploration(); } private void ExploreNewAreas(Vector2 playerPos) { lastExpansionTime = Time.time; explorationManager.ExploreNewAreas(playerPos, mapData); VisualizeMap(); // Update visualization } // === Public Methods for Event-Driven Exploration === /// /// Check for exploration when team position changes (event-driven) /// public void OnTeamPositionChanged(Vector2Int newPosition) { if (!useExplorationSystem || explorationManager == null) return; // Optimization: Only check if team moved a significant distance or cooldown passed if (Time.time - lastExpansionTime < expansionCooldown) return; // Convert tile position to world position for exploration system Vector2 worldPos = new Vector2(newPosition.x, newPosition.y); if (explorationManager.ShouldExplore(worldPos, mapData)) { ExploreNewAreas(worldPos); } } // === Methods needed by ExplorationManager === public void GenerateCompleteMap(MapData targetMapData) { // Generate base terrain terrainGenerator.GenerateTerrain(targetMapData); // Generate features featureGenerator.GenerateFeatures(targetMapData); } [ContextMenu("Enable Exploration System")] public void EnableExplorationSystem() { useExplorationSystem = true; } [ContextMenu("Test Exploration Now")] public void TestExplorationNow() { if (!useExplorationSystem) { Debug.LogWarning("⚠️ Exploration system is not enabled! Enable it first."); return; } // Debug player detection if (player == null) { // Try to find player again GameObject playerObj = GameObject.FindGameObjectWithTag("Player"); if (playerObj == null) { playerObj = GameObject.Find("TeamMarker"); } if (playerObj != null) { player = playerObj.transform; } else { Debug.LogError("❌ Cannot find player object! Make sure TeamMarker has 'Player' tag or is named 'TeamMarker'"); return; } } if (explorationManager == null) { Debug.LogError("❌ ExplorationManager is null! This should be created in InitializeMap()"); return; } float tileSize = mapVisualizer != null && mapVisualizer.tileSize > 0 ? mapVisualizer.tileSize : 1f; Vector2 playerPos = new Vector2(player.position.x / tileSize, player.position.z / tileSize); // Force exploration regardless of cooldown lastExpansionTime = 0f; ExploreNewAreas(playerPos); } [ContextMenu("DEBUG: Show Full 300x300 Map")] public void ShowFullMap() { if (!useExplorationSystem || explorationManager == null) { Debug.LogError("❌ Exploration system not enabled or null!"); return; } explorationManager.ShowFullMap(); } [ContextMenu("DEBUG: Show Exploration State")] public void DebugExplorationState() { if (!useExplorationSystem || explorationManager == null) { Debug.LogError("❌ Exploration system not enabled or null!"); return; } if (player == null) { GameObject teamMarker = GameObject.Find("TeamMarker"); if (teamMarker != null) player = teamMarker.transform; } if (player == null) { Debug.LogError("❌ No player/team marker found!"); return; } float tileSize = mapVisualizer != null && mapVisualizer.tileSize > 0 ? mapVisualizer.tileSize : 1f; Vector2 playerPos = new Vector2(player.position.x / tileSize, player.position.z / tileSize); explorationManager.DebugExplorationState(playerPos, mapData); } [ContextMenu("Disable Exploration System")] public void DisableExplorationSystem() { useExplorationSystem = false; } [ContextMenu("PERF: Toggle Performance Mode")] public void TogglePerformanceMode() { if (explorationManager != null) { explorationManager.TogglePerformanceMode(); } else { Debug.LogError("❌ Exploration manager not available!"); } } [ContextMenu("PERF: Test 500x500 Map")] public void TestLargeMap500() { if (explorationManager != null) { explorationManager.SetMapSize(500, 500); } else { Debug.LogError("❌ Exploration manager not available!"); } } [ContextMenu("PERF: Test 1000x1000 Map")] public void TestMassiveMap1000() { if (explorationManager != null) { explorationManager.SetMapSize(1000, 1000); } else { Debug.LogError("❌ Exploration manager not available!"); } } [ContextMenu("PERF: Reset to 300x300")] public void ResetToStandardSize() { if (explorationManager != null) { explorationManager.SetMapSize(300, 300); } else { Debug.LogError("❌ Exploration manager not available!"); } } [ContextMenu("FIX: Synchronize Team Marker Position")] public void SynchronizeTeamMarkerPosition() { if (explorationManager != null) { explorationManager.SynchronizeTeamMarkerPosition(); } else { Debug.LogError("❌ Exploration manager not available!"); } } [ContextMenu("TEST: Debug Full Map Coordinate Fix")] public void TestFullMapCoordinateFix() { if (!useExplorationSystem || explorationManager == null) { Debug.LogError("❌ Exploration system not enabled or null!"); return; } GameObject teamMarker = GameObject.Find("TeamMarker"); if (teamMarker == null) { Debug.LogError("❌ Team marker not found!"); return; } Vector3 worldPos = teamMarker.transform.position; Vector2Int worldTilePos = new Vector2Int( Mathf.RoundToInt(worldPos.x), Mathf.RoundToInt(worldPos.y) ); // Show full map and check if position is preserved explorationManager.ShowFullMap(); // Check position after full map is shown Vector3 newWorldPos = teamMarker.transform.position; Vector2Int newWorldTilePos = new Vector2Int( Mathf.RoundToInt(newWorldPos.x), Mathf.RoundToInt(newWorldPos.y) ); if (worldTilePos != newWorldTilePos) { Debug.LogError($"❌ COORDINATE FIX FAILED: Position changed from {worldTilePos} to {newWorldTilePos}"); } else { } } [ContextMenu("FIX: Reset Team Marker to Map Center")] public void ResetTeamMarkerToCenter() { if (!useExplorationSystem || explorationManager == null) { Debug.LogError("❌ Exploration system not enabled or null!"); return; } explorationManager.ResetTeamMarkerToMapCenter(); } [ContextMenu("FIX: Clear Saved Team Position")] public void ClearSavedTeamPosition() { // Clear saved position from PlayerPrefs string keyX = $"TeamPosition_{seed}_X"; string keyY = $"TeamPosition_{seed}_Y"; if (PlayerPrefs.HasKey(keyX)) PlayerPrefs.DeleteKey(keyX); if (PlayerPrefs.HasKey(keyY)) PlayerPrefs.DeleteKey(keyY); PlayerPrefs.Save(); } [ContextMenu("DEBUG: Show Coordinate State")] public void DebugCoordinateState() { if (explorationManager != null) { explorationManager.DebugCoordinateState(); } else { Debug.LogError("❌ Exploration manager not available!"); } } [ContextMenu("FIX: Force Coordinate Sync")] public void ForceCoordinateSync() { if (explorationManager != null) { explorationManager.ForceCoordinateSync(); } else { Debug.LogError("❌ Exploration manager not available!"); } } [ContextMenu("TEST: Simple Coordinate Conversion")] public void TestSimpleCoordinateConversion() { if (!useExplorationSystem || explorationManager == null) { Debug.LogError("❌ Exploration system not enabled or null!"); return; } explorationManager.TestSimpleCoordinateConversion(); } [ContextMenu("TEST: Positioning After Fix")] public void TestPositioningAfterFix() { if (!useExplorationSystem || explorationManager == null) { Debug.LogError("❌ Exploration system not enabled or null!"); return; } explorationManager.TestPositioningAfterFix(); } [ContextMenu("TEST: Full Map Tile Coverage")] public void TestFullMapTileCoverage() { if (!useExplorationSystem || explorationManager == null) { Debug.LogError("❌ Exploration system not enabled or null!"); return; } explorationManager.TestFullMapTileCoverage(); } [ContextMenu("TEST: Visual Tile Rendering")] public void TestVisualTileRendering() { if (!useExplorationSystem || explorationManager == null) { Debug.LogError("❌ Exploration system not enabled or null!"); return; } explorationManager.TestVisualTileRendering(); } [ContextMenu("TEST: Detailed Coordinate Conversion")] public void TestDetailedCoordinateConversion() { if (!useExplorationSystem || explorationManager == null) { Debug.LogError("❌ Exploration system not enabled or null!"); return; } explorationManager.TestCoordinateConversion(); } /// /// Public method to synchronize team position - can be called by travel system /// public void SyncTeamPosition() { if (useExplorationSystem && explorationManager != null) { explorationManager.SynchronizeTeamMarkerPosition(); } } // Expose map size properties for ExplorationManager public int mapWidth { get => mapData?.Width ?? initialMapSize; set { /* Can be used by exploration system */ } } public int mapHeight { get => mapData?.Height ?? initialMapSize; set { /* Can be used by exploration system */ } } }