添加 CombatNodeComponent 及相关类
- CombatNodeComponent:节点组件,负责提取并开始关卡 - CombatScheduler:关卡调度器,负责关卡的生命周期调度 - MapEntity:地图实体,提供地图相关的数据 - Spawner:出生点,负责标记地图上的敌人出生点坐标 - House:基地,负责标记地图上的敌人目标点坐标
This commit is contained in:
@@ -0,0 +1,255 @@
|
||||
using System.Collections.Generic;
|
||||
using GameFramework.DataTable;
|
||||
using GeometryTD.DataTable;
|
||||
using GeometryTD.Definition;
|
||||
using UnityEngine;
|
||||
using UnityGameFramework.Runtime;
|
||||
|
||||
namespace GeometryTD.CustomComponent
|
||||
{
|
||||
/// <summary>
|
||||
/// 鎴樻枟鑺傜偣缁勪欢
|
||||
/// </summary>
|
||||
public class CombatNodeComponent : GameFrameworkComponent
|
||||
{
|
||||
// Level.Id => Level
|
||||
private readonly Dictionary<int, DRLevel> _levelsById = new();
|
||||
|
||||
// LevelId => LevelPhases
|
||||
private readonly Dictionary<int, List<DRLevelPhase>> _phasesByLevelId = new();
|
||||
|
||||
// LevelPhase.Id => LevelSpawnEntries
|
||||
private readonly Dictionary<int, List<DRLevelSpawnEntry>> _spawnEntriesByPhaseId = new();
|
||||
private readonly Dictionary<int, IReadOnlyList<DRLevelSpawnEntry>> _selectedSpawnEntriesByPhaseId = new();
|
||||
private readonly List<int> _levelIdBuffer = new();
|
||||
private readonly CombatScheduler _combatScheduler = new CombatScheduler();
|
||||
|
||||
private bool _runtimeInitialized;
|
||||
|
||||
public LevelThemeType CurrentThemeType { get; private set; }
|
||||
public DRLevel CurrentLevel { get; private set; }
|
||||
|
||||
public void OnInit(LevelThemeType themeType)
|
||||
{
|
||||
ShutdownBattleRuntime();
|
||||
|
||||
CurrentThemeType = themeType;
|
||||
CurrentLevel = null;
|
||||
_levelsById.Clear();
|
||||
_phasesByLevelId.Clear();
|
||||
_spawnEntriesByPhaseId.Clear();
|
||||
_selectedSpawnEntriesByPhaseId.Clear();
|
||||
_levelIdBuffer.Clear();
|
||||
|
||||
IDataTable<DRLevel> dtLevel = GameEntry.DataTable.GetDataTable<DRLevel>();
|
||||
IDataTable<DRLevelPhase> dtLevelPhase = GameEntry.DataTable.GetDataTable<DRLevelPhase>();
|
||||
IDataTable<DRLevelSpawnEntry> dtSpawnEntry = GameEntry.DataTable.GetDataTable<DRLevelSpawnEntry>();
|
||||
if (dtLevel == null || dtLevelPhase == null || dtSpawnEntry == null)
|
||||
{
|
||||
Log.Warning("CombatNodeComponent init failed. Missing data table(s).");
|
||||
return;
|
||||
}
|
||||
|
||||
DRLevel[] levels = dtLevel.GetAllDataRows();
|
||||
for (int i = 0; i < levels.Length; i++)
|
||||
{
|
||||
DRLevel level = levels[i];
|
||||
if (level.LevelThemeType != themeType)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
_levelsById[level.Id] = level;
|
||||
_phasesByLevelId[level.Id] = new List<DRLevelPhase>();
|
||||
_levelIdBuffer.Add(level.Id);
|
||||
}
|
||||
|
||||
DRLevelPhase[] levelPhases = dtLevelPhase.GetAllDataRows();
|
||||
for (int i = 0; i < levelPhases.Length; i++)
|
||||
{
|
||||
DRLevelPhase phase = levelPhases[i];
|
||||
int levelId = phase.Id / 1000;
|
||||
if (!_levelsById.ContainsKey(levelId))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!_phasesByLevelId.TryGetValue(levelId, out List<DRLevelPhase> phases))
|
||||
{
|
||||
phases = new List<DRLevelPhase>();
|
||||
_phasesByLevelId[levelId] = phases;
|
||||
}
|
||||
|
||||
phases.Add(phase);
|
||||
_spawnEntriesByPhaseId[phase.Id] = new List<DRLevelSpawnEntry>();
|
||||
}
|
||||
|
||||
DRLevelSpawnEntry[] spawnEntries = dtSpawnEntry.GetAllDataRows();
|
||||
for (int i = 0; i < spawnEntries.Length; i++)
|
||||
{
|
||||
DRLevelSpawnEntry spawnEntry = spawnEntries[i];
|
||||
int phaseId = spawnEntry.Id / 1000;
|
||||
int levelId = phaseId / 1000;
|
||||
if (!_levelsById.ContainsKey(levelId))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!_spawnEntriesByPhaseId.TryGetValue(phaseId, out List<DRLevelSpawnEntry> entries))
|
||||
{
|
||||
entries = new List<DRLevelSpawnEntry>();
|
||||
_spawnEntriesByPhaseId[phaseId] = entries;
|
||||
}
|
||||
|
||||
entries.Add(spawnEntry);
|
||||
}
|
||||
|
||||
foreach (List<DRLevelPhase> phaseList in _phasesByLevelId.Values)
|
||||
{
|
||||
phaseList.Sort((left, right) => left.Id.CompareTo(right.Id));
|
||||
}
|
||||
|
||||
foreach (List<DRLevelSpawnEntry> phaseSpawnEntries in _spawnEntriesByPhaseId.Values)
|
||||
{
|
||||
phaseSpawnEntries.Sort((left, right) =>
|
||||
{
|
||||
int timeCompare = left.StartTime.CompareTo(right.StartTime);
|
||||
if (timeCompare != 0)
|
||||
{
|
||||
return timeCompare;
|
||||
}
|
||||
|
||||
return left.Id.CompareTo(right.Id);
|
||||
});
|
||||
}
|
||||
|
||||
Log.Info(
|
||||
"CombatNodeComponent initialized. Theme={0}, Levels={1}, Phases={2}, Entries={3}.",
|
||||
themeType,
|
||||
_levelsById.Count,
|
||||
CountPhases(),
|
||||
CountEntries());
|
||||
|
||||
EnsureBattleRuntimeInitialized();
|
||||
}
|
||||
|
||||
public void StartCombat()
|
||||
{
|
||||
if (!EnsureBattleRuntimeInitialized())
|
||||
{
|
||||
Log.Warning("CombatNodeComponent start failed. Missing scheduler runtime.");
|
||||
return;
|
||||
}
|
||||
|
||||
if (!TrySelectRandomLevel(out DRLevel selectedLevel))
|
||||
{
|
||||
Log.Warning("CombatNodeComponent has no level cache. Call OnInit(levelThemeType) first.");
|
||||
return;
|
||||
}
|
||||
|
||||
if (!_phasesByLevelId.TryGetValue(selectedLevel.Id, out List<DRLevelPhase> phaseList) ||
|
||||
phaseList == null ||
|
||||
phaseList.Count <= 0)
|
||||
{
|
||||
Log.Warning("CombatNodeComponent start failed. Level '{0}' has no phase data.", selectedLevel.Id);
|
||||
return;
|
||||
}
|
||||
|
||||
_selectedSpawnEntriesByPhaseId.Clear();
|
||||
foreach (var phase in phaseList)
|
||||
{
|
||||
if (_spawnEntriesByPhaseId.TryGetValue(phase.Id, out List<DRLevelSpawnEntry> entries) &&
|
||||
entries != null)
|
||||
{
|
||||
_selectedSpawnEntriesByPhaseId[phase.Id] = entries;
|
||||
}
|
||||
else
|
||||
{
|
||||
_selectedSpawnEntriesByPhaseId[phase.Id] = new List<DRLevelSpawnEntry>();
|
||||
}
|
||||
}
|
||||
|
||||
CurrentLevel = selectedLevel;
|
||||
_combatScheduler.Start(selectedLevel, phaseList, _selectedSpawnEntriesByPhaseId);
|
||||
}
|
||||
|
||||
public void OnUpdate(float elapseSeconds, float realElapseSeconds)
|
||||
{
|
||||
if (!_runtimeInitialized)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
_combatScheduler.OnUpdate(elapseSeconds, realElapseSeconds);
|
||||
}
|
||||
|
||||
public void OnShutdown()
|
||||
{
|
||||
CurrentLevel = null;
|
||||
ShutdownBattleRuntime();
|
||||
}
|
||||
|
||||
private void OnDestroy()
|
||||
{
|
||||
OnShutdown();
|
||||
}
|
||||
|
||||
private bool EnsureBattleRuntimeInitialized()
|
||||
{
|
||||
if (_runtimeInitialized)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
_combatScheduler.OnInit();
|
||||
_runtimeInitialized = true;
|
||||
return true;
|
||||
}
|
||||
|
||||
private void ShutdownBattleRuntime()
|
||||
{
|
||||
if (!_runtimeInitialized)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
_combatScheduler.OnDestroy();
|
||||
_runtimeInitialized = false;
|
||||
}
|
||||
|
||||
private bool TrySelectRandomLevel(out DRLevel level)
|
||||
{
|
||||
level = null;
|
||||
if (_levelIdBuffer.Count <= 0)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
int selectedIndex = Random.Range(0, _levelIdBuffer.Count);
|
||||
int selectedLevelId = _levelIdBuffer[selectedIndex];
|
||||
return _levelsById.TryGetValue(selectedLevelId, out level);
|
||||
}
|
||||
|
||||
private int CountPhases()
|
||||
{
|
||||
int count = 0;
|
||||
foreach (List<DRLevelPhase> phases in _phasesByLevelId.Values)
|
||||
{
|
||||
count += phases.Count;
|
||||
}
|
||||
|
||||
return count;
|
||||
}
|
||||
|
||||
private int CountEntries()
|
||||
{
|
||||
int count = 0;
|
||||
foreach (List<DRLevelSpawnEntry> list in _spawnEntriesByPhaseId.Values)
|
||||
{
|
||||
count += list.Count;
|
||||
}
|
||||
|
||||
return count;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 5e646500b9304d438746f2351c71a0f4
|
||||
timeCreated: 1772103300
|
||||
@@ -0,0 +1,422 @@
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using GameFramework.Event;
|
||||
using GameFramework.Resource;
|
||||
using GeometryTD.CustomUtility;
|
||||
using GeometryTD.DataTable;
|
||||
using GeometryTD.Definition;
|
||||
using GeometryTD.Entity;
|
||||
using GeometryTD.Entity.EntityData;
|
||||
using UnityEngine;
|
||||
using UnityGameFramework.Runtime;
|
||||
|
||||
namespace GeometryTD.CustomComponent
|
||||
{
|
||||
public class CombatScheduler
|
||||
{
|
||||
private enum SchedulerState : byte
|
||||
{
|
||||
Idle = 0,
|
||||
WaitingForMap = 1,
|
||||
RunningPhase = 2,
|
||||
Completed = 3,
|
||||
Failed = 4
|
||||
}
|
||||
|
||||
private readonly List<DRLevelPhase> _phaseBuffer = new List<DRLevelPhase>();
|
||||
private readonly Dictionary<int, IReadOnlyList<DRLevelSpawnEntry>> _spawnEntriesByPhaseId =
|
||||
new Dictionary<int, IReadOnlyList<DRLevelSpawnEntry>>();
|
||||
|
||||
private readonly EnemyManager _enemyManager = new EnemyManager();
|
||||
|
||||
private EntityComponent _entity;
|
||||
private DRLevel _currentLevel;
|
||||
private DRLevelPhase _currentPhase;
|
||||
private int _currentPhaseIndex;
|
||||
private float _currentPhaseElapsed;
|
||||
private SchedulerState _state = SchedulerState.Idle;
|
||||
private int _loadingMapEntityId;
|
||||
private int _loadedMapEntityId;
|
||||
private bool _initialized;
|
||||
private bool _isEntityEventSubscribed;
|
||||
private MapEntity _currentMap;
|
||||
|
||||
public bool IsRunning => _state == SchedulerState.WaitingForMap || _state == SchedulerState.RunningPhase;
|
||||
public bool IsCompleted => _state == SchedulerState.Completed;
|
||||
public DRLevel CurrentLevel => _currentLevel;
|
||||
public DRLevelPhase CurrentPhase => _currentPhase;
|
||||
public MapEntity CurrentMap => _currentMap;
|
||||
|
||||
public void OnInit()
|
||||
{
|
||||
if (!_initialized)
|
||||
{
|
||||
_entity = GameEntry.Entity;
|
||||
EnsureEntityEventSubscribed();
|
||||
_enemyManager.OnInit(this);
|
||||
_initialized = true;
|
||||
}
|
||||
|
||||
ResetRuntime();
|
||||
}
|
||||
|
||||
public void Start(
|
||||
DRLevel level,
|
||||
IReadOnlyList<DRLevelPhase> phases,
|
||||
IReadOnlyDictionary<int, IReadOnlyList<DRLevelSpawnEntry>> spawnEntriesByPhaseId)
|
||||
{
|
||||
if (!_initialized || _entity == null)
|
||||
{
|
||||
_state = SchedulerState.Failed;
|
||||
Log.Warning("CombatScheduler start failed. Runtime is not initialized.");
|
||||
return;
|
||||
}
|
||||
|
||||
if (level == null || phases == null || phases.Count <= 0)
|
||||
{
|
||||
_state = SchedulerState.Failed;
|
||||
Log.Warning("CombatScheduler start failed. Invalid level or phase data.");
|
||||
return;
|
||||
}
|
||||
|
||||
_enemyManager.EndPhase();
|
||||
HideCurrentMapIfNeeded();
|
||||
ResetRuntime();
|
||||
|
||||
_currentLevel = level;
|
||||
foreach (var phase in phases)
|
||||
{
|
||||
_phaseBuffer.Add(phase);
|
||||
}
|
||||
|
||||
if (spawnEntriesByPhaseId != null)
|
||||
{
|
||||
foreach (var pair in spawnEntriesByPhaseId)
|
||||
{
|
||||
_spawnEntriesByPhaseId[pair.Key] = pair.Value;
|
||||
}
|
||||
}
|
||||
|
||||
if (_phaseBuffer.Count <= 0)
|
||||
{
|
||||
_state = SchedulerState.Failed;
|
||||
Log.Warning("CombatScheduler start failed. Level '{0}' has no phase data.", level.Id);
|
||||
return;
|
||||
}
|
||||
|
||||
if (!TryShowMap(level))
|
||||
{
|
||||
_state = SchedulerState.Failed;
|
||||
return;
|
||||
}
|
||||
|
||||
_currentPhase = null;
|
||||
_currentPhaseIndex = -1;
|
||||
_currentPhaseElapsed = 0f;
|
||||
_state = SchedulerState.WaitingForMap;
|
||||
|
||||
Log.Info("CombatScheduler started. Level={0}, PhaseCount={1}.", _currentLevel.Id, _phaseBuffer.Count);
|
||||
}
|
||||
|
||||
public void OnUpdate(float elapseSeconds, float realElapseSeconds)
|
||||
{
|
||||
switch (_state)
|
||||
{
|
||||
case SchedulerState.WaitingForMap:
|
||||
if (_currentMap == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
BeginNextPhase();
|
||||
return;
|
||||
case SchedulerState.RunningPhase:
|
||||
UpdateCurrentPhase(elapseSeconds, realElapseSeconds);
|
||||
return;
|
||||
default:
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
public void OnDestroy()
|
||||
{
|
||||
if (!_initialized)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
_enemyManager.OnDestroy();
|
||||
HideCurrentMapIfNeeded();
|
||||
ResetRuntime();
|
||||
UnsubscribeEntityEvents();
|
||||
_entity = null;
|
||||
_initialized = false;
|
||||
}
|
||||
|
||||
private bool TryShowMap(DRLevel level)
|
||||
{
|
||||
string mapAssetName = level.Id.ToString();
|
||||
string mapAssetPath = AssetUtility.GetLevelMapAsset(mapAssetName);
|
||||
if (GameEntry.Resource.HasAsset(mapAssetPath) == HasAssetResult.NotExist)
|
||||
{
|
||||
Log.Warning(
|
||||
"CombatScheduler start failed. Level '{0}' map asset not found: '{1}'.",
|
||||
level.Id,
|
||||
mapAssetPath);
|
||||
return false;
|
||||
}
|
||||
|
||||
_loadingMapEntityId = _entity.GenerateSerialId();
|
||||
_entity.ShowMap(new MapData(_loadingMapEntityId, level.Id, Vector3.zero), mapAssetName);
|
||||
|
||||
Log.Info(
|
||||
"CombatScheduler loading map. Level={0}, Asset='{1}', EntityId={2}.",
|
||||
level.Id,
|
||||
mapAssetPath,
|
||||
_loadingMapEntityId);
|
||||
return true;
|
||||
}
|
||||
|
||||
private void UpdateCurrentPhase(float elapseSeconds, float realElapseSeconds)
|
||||
{
|
||||
if (_currentPhase == null)
|
||||
{
|
||||
_state = SchedulerState.Failed;
|
||||
Log.Warning("CombatScheduler update failed. Current phase is null.");
|
||||
return;
|
||||
}
|
||||
|
||||
_currentPhaseElapsed += elapseSeconds;
|
||||
_enemyManager.OnUpdate(elapseSeconds, realElapseSeconds);
|
||||
|
||||
if (!ShouldEndCurrentPhase())
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
CompleteCurrentPhase();
|
||||
}
|
||||
|
||||
private bool ShouldEndCurrentPhase()
|
||||
{
|
||||
switch (_currentPhase.EndType)
|
||||
{
|
||||
case PhaseEndType.TimeElapsed:
|
||||
return _currentPhaseElapsed >= ResolveTimeElapsedThreshold(_currentPhase);
|
||||
case PhaseEndType.EnemiesCleared:
|
||||
case PhaseEndType.BossDead:
|
||||
return _enemyManager.IsPhaseSpawnCompleted && _enemyManager.AliveEnemyCount <= 0;
|
||||
case PhaseEndType.None:
|
||||
default:
|
||||
if (_currentPhase.DurationSeconds > 0 && _currentPhaseElapsed >= _currentPhase.DurationSeconds)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
return _enemyManager.IsPhaseSpawnCompleted && _enemyManager.AliveEnemyCount <= 0;
|
||||
}
|
||||
}
|
||||
|
||||
private float ResolveTimeElapsedThreshold(DRLevelPhase phase)
|
||||
{
|
||||
if (!string.IsNullOrWhiteSpace(phase.EndParam) &&
|
||||
float.TryParse(phase.EndParam, NumberStyles.Float, CultureInfo.InvariantCulture,
|
||||
out float parsedSeconds))
|
||||
{
|
||||
return parsedSeconds;
|
||||
}
|
||||
|
||||
if (phase.DurationSeconds > 0)
|
||||
{
|
||||
return phase.DurationSeconds;
|
||||
}
|
||||
|
||||
return 0f;
|
||||
}
|
||||
|
||||
private void CompleteCurrentPhase()
|
||||
{
|
||||
_enemyManager.EndPhase();
|
||||
Log.Info(
|
||||
"CombatScheduler phase completed. Level={0}, Phase={1}, Elapsed={2:F2}s.",
|
||||
_currentLevel != null ? _currentLevel.Id : 0,
|
||||
_currentPhase != null ? _currentPhase.Id : 0,
|
||||
_currentPhaseElapsed);
|
||||
|
||||
BeginNextPhase();
|
||||
}
|
||||
|
||||
private void BeginNextPhase()
|
||||
{
|
||||
_currentPhaseIndex++;
|
||||
if (_currentPhaseIndex >= _phaseBuffer.Count)
|
||||
{
|
||||
_state = SchedulerState.Completed;
|
||||
_currentPhase = null;
|
||||
Log.Info("CombatScheduler level completed. Level={0}.", _currentLevel != null ? _currentLevel.Id : 0);
|
||||
return;
|
||||
}
|
||||
|
||||
_currentPhase = _phaseBuffer[_currentPhaseIndex];
|
||||
_currentPhaseElapsed = 0f;
|
||||
|
||||
IReadOnlyList<DRLevelSpawnEntry> spawnEntries = null;
|
||||
_spawnEntriesByPhaseId.TryGetValue(_currentPhase.Id, out spawnEntries);
|
||||
_enemyManager.BeginPhase(_currentPhase, spawnEntries);
|
||||
_state = SchedulerState.RunningPhase;
|
||||
|
||||
Log.Info(
|
||||
"CombatScheduler phase started. Level={0}, Phase={1}, EndType={2}, Entries={3}.",
|
||||
_currentLevel != null ? _currentLevel.Id : 0,
|
||||
_currentPhase.Id,
|
||||
_currentPhase.EndType,
|
||||
spawnEntries != null ? spawnEntries.Count : 0);
|
||||
}
|
||||
|
||||
private void HideCurrentMapIfNeeded()
|
||||
{
|
||||
if (_entity == null)
|
||||
{
|
||||
_currentMap = null;
|
||||
_loadingMapEntityId = 0;
|
||||
_loadedMapEntityId = 0;
|
||||
return;
|
||||
}
|
||||
|
||||
if (_loadingMapEntityId != 0)
|
||||
{
|
||||
EntityBase loadingMap = _entity.GetGameEntity(_loadingMapEntityId);
|
||||
if (loadingMap != null)
|
||||
{
|
||||
_entity.HideEntity(loadingMap);
|
||||
}
|
||||
}
|
||||
|
||||
if (_loadedMapEntityId != 0)
|
||||
{
|
||||
EntityBase loadedMap = _entity.GetGameEntity(_loadedMapEntityId);
|
||||
if (loadedMap != null)
|
||||
{
|
||||
_entity.HideEntity(loadedMap);
|
||||
}
|
||||
}
|
||||
|
||||
_loadingMapEntityId = 0;
|
||||
_loadedMapEntityId = 0;
|
||||
_currentMap = null;
|
||||
}
|
||||
|
||||
private void EnsureEntityEventSubscribed()
|
||||
{
|
||||
if (_isEntityEventSubscribed)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
GameEntry.Event.Subscribe(ShowEntitySuccessEventArgs.EventId, OnShowEntitySuccess);
|
||||
GameEntry.Event.Subscribe(ShowEntityFailureEventArgs.EventId, OnShowEntityFailure);
|
||||
GameEntry.Event.Subscribe(HideEntityCompleteEventArgs.EventId, OnHideEntityComplete);
|
||||
_isEntityEventSubscribed = true;
|
||||
}
|
||||
|
||||
private void UnsubscribeEntityEvents()
|
||||
{
|
||||
if (!_isEntityEventSubscribed)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
GameEntry.Event.Unsubscribe(ShowEntitySuccessEventArgs.EventId, OnShowEntitySuccess);
|
||||
GameEntry.Event.Unsubscribe(ShowEntityFailureEventArgs.EventId, OnShowEntityFailure);
|
||||
GameEntry.Event.Unsubscribe(HideEntityCompleteEventArgs.EventId, OnHideEntityComplete);
|
||||
_isEntityEventSubscribed = false;
|
||||
}
|
||||
|
||||
private void ResetRuntime()
|
||||
{
|
||||
_phaseBuffer.Clear();
|
||||
_spawnEntriesByPhaseId.Clear();
|
||||
_currentLevel = null;
|
||||
_currentPhase = null;
|
||||
_currentPhaseIndex = -1;
|
||||
_currentPhaseElapsed = 0f;
|
||||
_state = SchedulerState.Idle;
|
||||
}
|
||||
|
||||
#region Event Handlers
|
||||
|
||||
private void OnShowEntitySuccess(object sender, GameEventArgs e)
|
||||
{
|
||||
if (!(e is ShowEntitySuccessEventArgs ne))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (ne.EntityLogicType != typeof(MapEntity) || ne.Entity.Id != _loadingMapEntityId)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
_loadedMapEntityId = _loadingMapEntityId;
|
||||
_loadingMapEntityId = 0;
|
||||
_currentMap = ne.Entity.Logic as MapEntity;
|
||||
if (_currentMap == null)
|
||||
{
|
||||
_state = SchedulerState.Failed;
|
||||
Log.Error("Loaded map entity logic is invalid. EntityId={0}.", ne.Entity.Id);
|
||||
return;
|
||||
}
|
||||
|
||||
Log.Info(
|
||||
"Map ready. LevelId={0}, PathCells={1}, FoundationCells={2}, Spawners={3}, House={4}.",
|
||||
_currentLevel != null ? _currentLevel.Id : 0,
|
||||
_currentMap.PathCells.Count,
|
||||
_currentMap.FoundationCells.Count,
|
||||
_currentMap.Spawners.Length,
|
||||
_currentMap.House != null ? _currentMap.House.name : "None");
|
||||
}
|
||||
|
||||
private void OnShowEntityFailure(object sender, GameEventArgs e)
|
||||
{
|
||||
if (!(e is ShowEntityFailureEventArgs ne))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (ne.EntityLogicType != typeof(MapEntity) || ne.EntityId != _loadingMapEntityId)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
_loadingMapEntityId = 0;
|
||||
_currentMap = null;
|
||||
_state = SchedulerState.Failed;
|
||||
Log.Error(
|
||||
"Map load failed. LevelId={0}, Asset='{1}', Error='{2}'.",
|
||||
_currentLevel != null ? _currentLevel.Id : 0,
|
||||
ne.EntityAssetName,
|
||||
ne.ErrorMessage);
|
||||
}
|
||||
|
||||
private void OnHideEntityComplete(object sender, GameEventArgs e)
|
||||
{
|
||||
if (!(e is HideEntityCompleteEventArgs ne))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (ne.EntityId == _loadedMapEntityId)
|
||||
{
|
||||
_loadedMapEntityId = 0;
|
||||
_currentMap = null;
|
||||
}
|
||||
|
||||
if (ne.EntityId == _loadingMapEntityId)
|
||||
{
|
||||
_loadingMapEntityId = 0;
|
||||
}
|
||||
}
|
||||
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 9f43fd8050fd4239b4407a4fedcf0b7a
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -0,0 +1,465 @@
|
||||
using System.Collections.Generic;
|
||||
using GameFramework.DataTable;
|
||||
using GameFramework.Event;
|
||||
using GeometryTD.DataTable;
|
||||
using GeometryTD.Definition;
|
||||
using GeometryTD.Entity;
|
||||
using GeometryTD.Entity.EntityData;
|
||||
using UnityEngine;
|
||||
using UnityGameFramework.Runtime;
|
||||
|
||||
namespace GeometryTD.CustomComponent
|
||||
{
|
||||
public class EnemyManager
|
||||
{
|
||||
private sealed class SpawnEntryRuntime
|
||||
{
|
||||
public DRLevelSpawnEntry Entry;
|
||||
public bool Completed;
|
||||
public float NextTriggerTime;
|
||||
public float EndTime;
|
||||
public int RemainingCount;
|
||||
}
|
||||
|
||||
private const int DefaultEnemyConfigId = 1;
|
||||
private const float MinStreamInterval = 0.05f;
|
||||
private const float MinBurstGap = 0.01f;
|
||||
|
||||
private readonly List<Spawner> _spawners = new List<Spawner>();
|
||||
private readonly Dictionary<int, Spawner> _spawnerByOrder = new Dictionary<int, Spawner>();
|
||||
private readonly List<Vector3> _pathBuffer = new List<Vector3>();
|
||||
private readonly List<SpawnEntryRuntime> _spawnRuntimes = new List<SpawnEntryRuntime>();
|
||||
|
||||
private CombatScheduler _combatScheduler;
|
||||
private EntityComponent _entity;
|
||||
private IDataTable<DREnemy> _drEnemy;
|
||||
|
||||
private int _spawnEnemyMaxCount = 5000;
|
||||
private int _currentEnemyCount;
|
||||
private int _nextSpawnerIndex;
|
||||
private int _currentMapEntityId;
|
||||
private bool _initialized;
|
||||
private bool _enemyConfigMissingLogged;
|
||||
|
||||
private float _phaseElapsed;
|
||||
private bool _isPhaseRunning;
|
||||
|
||||
public int AliveEnemyCount => _currentEnemyCount;
|
||||
public bool IsPhaseSpawnCompleted { get; private set; } = true;
|
||||
public bool IsPhaseRunning => _isPhaseRunning;
|
||||
|
||||
public void OnInit(CombatScheduler combatScheduler)
|
||||
{
|
||||
_combatScheduler = combatScheduler;
|
||||
if (_initialized)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
_entity = GameEntry.Entity;
|
||||
_drEnemy = GameEntry.DataTable.GetDataTable<DREnemy>();
|
||||
_currentEnemyCount = 0;
|
||||
_nextSpawnerIndex = 0;
|
||||
_currentMapEntityId = 0;
|
||||
_enemyConfigMissingLogged = false;
|
||||
_spawners.Clear();
|
||||
_spawnerByOrder.Clear();
|
||||
_pathBuffer.Clear();
|
||||
_spawnRuntimes.Clear();
|
||||
_phaseElapsed = 0f;
|
||||
_isPhaseRunning = false;
|
||||
IsPhaseSpawnCompleted = true;
|
||||
|
||||
GameEntry.Event.Subscribe(ShowEntitySuccessEventArgs.EventId, OnShowEntitySuccess);
|
||||
GameEntry.Event.Subscribe(ShowEntityFailureEventArgs.EventId, OnShowEntityFailure);
|
||||
GameEntry.Event.Subscribe(HideEntityCompleteEventArgs.EventId, OnHideEntityComplete);
|
||||
_initialized = true;
|
||||
}
|
||||
|
||||
public void BeginPhase(DRLevelPhase phase, IReadOnlyList<DRLevelSpawnEntry> spawnEntries)
|
||||
{
|
||||
if (!_initialized || _combatScheduler == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
_ = phase;
|
||||
EndPhase();
|
||||
|
||||
_phaseElapsed = 0f;
|
||||
_isPhaseRunning = true;
|
||||
IsPhaseSpawnCompleted = false;
|
||||
RefreshSpawnerCache(true);
|
||||
|
||||
if (spawnEntries != null)
|
||||
{
|
||||
for (int i = 0; i < spawnEntries.Count; i++)
|
||||
{
|
||||
SpawnEntryRuntime runtime = BuildSpawnRuntime(spawnEntries[i]);
|
||||
if (runtime != null)
|
||||
{
|
||||
_spawnRuntimes.Add(runtime);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
IsPhaseSpawnCompleted = _spawnRuntimes.Count <= 0;
|
||||
}
|
||||
|
||||
public void OnUpdate(float elapseSeconds, float realElapseSeconds)
|
||||
{
|
||||
if (!_initialized || _combatScheduler == null || !_isPhaseRunning)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
RefreshSpawnerCache(false);
|
||||
_phaseElapsed += elapseSeconds;
|
||||
UpdateSpawnRuntimes();
|
||||
}
|
||||
|
||||
public void EndPhase()
|
||||
{
|
||||
_isPhaseRunning = false;
|
||||
_phaseElapsed = 0f;
|
||||
_spawnRuntimes.Clear();
|
||||
IsPhaseSpawnCompleted = true;
|
||||
}
|
||||
|
||||
public void OnDestroy()
|
||||
{
|
||||
if (!_initialized)
|
||||
{
|
||||
_combatScheduler = null;
|
||||
return;
|
||||
}
|
||||
|
||||
EndPhase();
|
||||
GameEntry.Event.Unsubscribe(ShowEntitySuccessEventArgs.EventId, OnShowEntitySuccess);
|
||||
GameEntry.Event.Unsubscribe(ShowEntityFailureEventArgs.EventId, OnShowEntityFailure);
|
||||
GameEntry.Event.Unsubscribe(HideEntityCompleteEventArgs.EventId, OnHideEntityComplete);
|
||||
|
||||
_spawners.Clear();
|
||||
_spawnerByOrder.Clear();
|
||||
_pathBuffer.Clear();
|
||||
_currentMapEntityId = 0;
|
||||
_nextSpawnerIndex = 0;
|
||||
_combatScheduler = null;
|
||||
_initialized = false;
|
||||
}
|
||||
|
||||
private SpawnEntryRuntime BuildSpawnRuntime(DRLevelSpawnEntry entry)
|
||||
{
|
||||
if (entry == null || entry.EntryType == EntryType.None)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
SpawnEntryRuntime runtime = new SpawnEntryRuntime
|
||||
{
|
||||
Entry = entry,
|
||||
Completed = false,
|
||||
NextTriggerTime = Mathf.Max(0f, entry.StartTime),
|
||||
EndTime = Mathf.Max(0f, entry.StartTime),
|
||||
RemainingCount = Mathf.Max(0, entry.Count)
|
||||
};
|
||||
|
||||
switch (entry.EntryType)
|
||||
{
|
||||
case EntryType.Stream:
|
||||
{
|
||||
float duration = Mathf.Max(0f, entry.Duration);
|
||||
runtime.EndTime = duration > 0f ? runtime.NextTriggerTime + duration : runtime.NextTriggerTime;
|
||||
runtime.Completed = entry.Count <= 0;
|
||||
return runtime;
|
||||
}
|
||||
case EntryType.Burst:
|
||||
case EntryType.Boss:
|
||||
runtime.Completed = runtime.RemainingCount <= 0;
|
||||
return runtime;
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private void UpdateSpawnRuntimes()
|
||||
{
|
||||
bool allCompleted = true;
|
||||
for (int i = 0; i < _spawnRuntimes.Count; i++)
|
||||
{
|
||||
SpawnEntryRuntime runtime = _spawnRuntimes[i];
|
||||
if (runtime.Completed)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
switch (runtime.Entry.EntryType)
|
||||
{
|
||||
case EntryType.Stream:
|
||||
ProcessStreamRuntime(runtime);
|
||||
break;
|
||||
case EntryType.Burst:
|
||||
case EntryType.Boss:
|
||||
ProcessBurstRuntime(runtime);
|
||||
break;
|
||||
default:
|
||||
runtime.Completed = true;
|
||||
break;
|
||||
}
|
||||
|
||||
if (!runtime.Completed)
|
||||
{
|
||||
allCompleted = false;
|
||||
}
|
||||
}
|
||||
|
||||
IsPhaseSpawnCompleted = allCompleted;
|
||||
}
|
||||
|
||||
private void ProcessStreamRuntime(SpawnEntryRuntime runtime)
|
||||
{
|
||||
if (_phaseElapsed < runtime.NextTriggerTime)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
int countPerWave = Mathf.Max(0, runtime.Entry.Count);
|
||||
if (countPerWave <= 0)
|
||||
{
|
||||
runtime.Completed = true;
|
||||
return;
|
||||
}
|
||||
|
||||
float interval = runtime.Entry.Interval > 0f ? runtime.Entry.Interval : MinStreamInterval;
|
||||
while (_phaseElapsed >= runtime.NextTriggerTime && runtime.NextTriggerTime <= runtime.EndTime)
|
||||
{
|
||||
SpawnEnemies(runtime.Entry, countPerWave);
|
||||
runtime.NextTriggerTime += interval;
|
||||
}
|
||||
|
||||
if (runtime.NextTriggerTime > runtime.EndTime)
|
||||
{
|
||||
runtime.Completed = true;
|
||||
}
|
||||
}
|
||||
|
||||
private void ProcessBurstRuntime(SpawnEntryRuntime runtime)
|
||||
{
|
||||
if (_phaseElapsed < runtime.NextTriggerTime)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (runtime.RemainingCount <= 0)
|
||||
{
|
||||
runtime.Completed = true;
|
||||
return;
|
||||
}
|
||||
|
||||
float gap = runtime.Entry.Gap;
|
||||
if (gap <= 0f)
|
||||
{
|
||||
SpawnEnemies(runtime.Entry, runtime.RemainingCount);
|
||||
runtime.RemainingCount = 0;
|
||||
runtime.Completed = true;
|
||||
return;
|
||||
}
|
||||
|
||||
gap = Mathf.Max(gap, MinBurstGap);
|
||||
while (_phaseElapsed >= runtime.NextTriggerTime && runtime.RemainingCount > 0)
|
||||
{
|
||||
SpawnEnemies(runtime.Entry, 1);
|
||||
runtime.RemainingCount--;
|
||||
runtime.NextTriggerTime += gap;
|
||||
}
|
||||
|
||||
runtime.Completed = runtime.RemainingCount <= 0;
|
||||
}
|
||||
|
||||
private void SpawnEnemies(DRLevelSpawnEntry entry, int spawnCount)
|
||||
{
|
||||
if (spawnCount <= 0)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
Spawner spawner = ResolveSpawner(entry.SpawnPointId);
|
||||
if (spawner == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
MapEntity currentMap = _combatScheduler != null ? _combatScheduler.CurrentMap : null;
|
||||
if (currentMap == null ||
|
||||
!currentMap.TryFindPathWorldPoints(spawner, null, _pathBuffer) ||
|
||||
_pathBuffer.Count <= 0)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
DREnemy enemyConfig = GetEnemyConfig(entry.EnemyId);
|
||||
if (enemyConfig == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
for (int i = 0; i < spawnCount; i++)
|
||||
{
|
||||
if (_currentEnemyCount >= _spawnEnemyMaxCount)
|
||||
{
|
||||
break;
|
||||
}
|
||||
|
||||
int enemyEntityId = _entity.GenerateSerialId();
|
||||
EnemyData enemyData = new EnemyData(
|
||||
enemyEntityId,
|
||||
enemyConfig.EntityId,
|
||||
_pathBuffer[0],
|
||||
enemyConfig.BaseHp,
|
||||
enemyConfig.Speed,
|
||||
_pathBuffer);
|
||||
_entity.ShowEnemy(enemyData);
|
||||
}
|
||||
}
|
||||
|
||||
private DREnemy GetEnemyConfig(int enemyId)
|
||||
{
|
||||
if (_drEnemy == null)
|
||||
{
|
||||
_drEnemy = GameEntry.DataTable.GetDataTable<DREnemy>();
|
||||
if (_drEnemy == null)
|
||||
{
|
||||
if (!_enemyConfigMissingLogged)
|
||||
{
|
||||
Log.Warning("EnemyManagerComponent can not find DREnemy data table.");
|
||||
_enemyConfigMissingLogged = true;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
if (enemyId > 0)
|
||||
{
|
||||
DREnemy targetConfig = _drEnemy.GetDataRow(enemyId);
|
||||
if (targetConfig != null)
|
||||
{
|
||||
return targetConfig;
|
||||
}
|
||||
}
|
||||
|
||||
DREnemy defaultConfig = _drEnemy.GetDataRow(DefaultEnemyConfigId);
|
||||
if (defaultConfig != null)
|
||||
{
|
||||
return defaultConfig;
|
||||
}
|
||||
|
||||
DREnemy[] allConfigs = _drEnemy.GetAllDataRows();
|
||||
if (allConfigs.Length > 0)
|
||||
{
|
||||
return allConfigs[0];
|
||||
}
|
||||
|
||||
if (!_enemyConfigMissingLogged)
|
||||
{
|
||||
Log.Warning("EnemyManagerComponent found no enemy configs.");
|
||||
_enemyConfigMissingLogged = true;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
private Spawner ResolveSpawner(int spawnPointId)
|
||||
{
|
||||
if (spawnPointId > 0 && _spawnerByOrder.TryGetValue(spawnPointId, out Spawner mappedSpawner))
|
||||
{
|
||||
return mappedSpawner;
|
||||
}
|
||||
|
||||
if (_spawners.Count <= 0)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
Spawner fallbackSpawner = _spawners[_nextSpawnerIndex % _spawners.Count];
|
||||
_nextSpawnerIndex++;
|
||||
return fallbackSpawner;
|
||||
}
|
||||
|
||||
private void RefreshSpawnerCache(bool force)
|
||||
{
|
||||
MapEntity currentMap = _combatScheduler != null ? _combatScheduler.CurrentMap : null;
|
||||
if (currentMap == null)
|
||||
{
|
||||
_spawners.Clear();
|
||||
_spawnerByOrder.Clear();
|
||||
_currentMapEntityId = 0;
|
||||
_nextSpawnerIndex = 0;
|
||||
return;
|
||||
}
|
||||
|
||||
if (!force && _currentMapEntityId == currentMap.Id && _spawners.Count > 0)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
_spawners.Clear();
|
||||
_spawnerByOrder.Clear();
|
||||
_nextSpawnerIndex = 0;
|
||||
_currentMapEntityId = currentMap.Id;
|
||||
|
||||
Spawner[] mapSpawners = currentMap.Spawners;
|
||||
for (int i = 0; i < mapSpawners.Length; i++)
|
||||
{
|
||||
Spawner spawner = mapSpawners[i];
|
||||
if (spawner == null)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!currentMap.TryGetDefaultPathCells(spawner, out _))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
_spawners.Add(spawner);
|
||||
if (spawner.SpawnOrder > 0 && !_spawnerByOrder.ContainsKey(spawner.SpawnOrder))
|
||||
{
|
||||
_spawnerByOrder[spawner.SpawnOrder] = spawner;
|
||||
}
|
||||
}
|
||||
|
||||
_spawners.Sort((left, right) => left.SpawnOrder.CompareTo(right.SpawnOrder));
|
||||
}
|
||||
|
||||
private void OnShowEntitySuccess(object sender, GameEventArgs e)
|
||||
{
|
||||
if (e is ShowEntitySuccessEventArgs ne)
|
||||
{
|
||||
if (ne.EntityLogicType == typeof(EnemyEntity))
|
||||
{
|
||||
_currentEnemyCount++;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void OnShowEntityFailure(object sender, GameEventArgs e)
|
||||
{
|
||||
}
|
||||
|
||||
private void OnHideEntityComplete(object sender, GameEventArgs e)
|
||||
{
|
||||
if (!(e is HideEntityCompleteEventArgs ne))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (ne.EntityGroup.Name != "Enemy")
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
_currentEnemyCount = Mathf.Max(0, _currentEnemyCount - 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 8d840df1b53db744cb522b82426f2cd5
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
Reference in New Issue
Block a user