This commit is contained in:
CortexCore
2024-11-13 17:47:45 +08:00
parent c4af12acd7
commit 416e3322db
208 changed files with 2591757 additions and 1497 deletions

View File

@@ -0,0 +1,176 @@
using System;
using System.Collections.Generic;
using System.Threading;
using Cysharp.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Random = UnityEngine.Random;
namespace BITKit.StateMachine
{
/// <summary>
/// 动态异步状态机
/// </summary>
/// <typeparam name="T">异步状态</typeparam>
public class AsyncStateMachine<T>:IStateMachine<T> ,IDisposable where T : class, IStateAsync
{
private readonly IServiceProvider _serviceProvider;
public AsyncStateMachine(IServiceProvider serviceProvider)
{
_serviceProvider = serviceProvider;
}
public AsyncStateMachine()
{
_serviceProvider = new ServiceCollection().BuildServiceProvider();
}
public bool Enabled { get; set; } = true;
public T CurrentState { get;private set; }
public T NextOrCurrentState => _nextTargetState.IfNotAllow(CurrentState);
private T _nextState;
public event Action<T, T> OnStateChanging;
public event Action<T, T> OnStateChanged;
public event Action<T> OnStateRegistered;
public IReadOnlyDictionary<int, T> Dictionary => _dictionary;
public event Action<T> OnStateUnRegistered;
public IDictionary<Type, T> StateDictionary { get; } = new Dictionary<Type, T>();
public readonly ValidHandle IsBusy=new();
private readonly CancellationTokenSource _cancellationTokenSource=new();
private readonly Dictionary<int, T> _dictionary = new();
private readonly Optional<T> _nextTargetState = new();
public async void Initialize()
{
await IsBusy;
if(_cancellationTokenSource.IsCancellationRequested)return;
using var _ = IsBusy.GetHandle();
foreach (var (_,value) in StateDictionary)
{
await value.InitializeAsync();
value.Initialize();
}
}
public async void UpdateState(float deltaTime)
{
if (CurrentState is null) return;
using var _ = IsBusy.GetHandle();
await CurrentState.OnStateUpdateAsync(deltaTime);
CurrentState.OnStateUpdate(deltaTime);
}
public async void DisposeState()
{
await IsBusy;
if(_cancellationTokenSource.IsCancellationRequested)return;
if (CurrentState is null) return;
using var _ = IsBusy.GetHandle();
await CurrentState.OnStateExitAsync(CurrentState, null);
if(_cancellationTokenSource.IsCancellationRequested)return;
CurrentState.OnStateExit(CurrentState, null);
CurrentState = null;
}
public T TransitionState<TState>() where TState : T
{
T nextState;
foreach (var (type, value) in Dictionary)
{
if ((typeof(TState) == value.GetType()) is false) continue;
nextState = value;
TransitionState(nextState);
return nextState;
}
nextState = _serviceProvider.GetRequiredService<TState>();
return TransitionState(nextState);;
}
public async UniTask TransitionStateAsync(T nextState)
{
if (nextState is not null)
{
if (nextState.Identifier == 0)
{
nextState.Identifier = nextState.GetHashCode();
}
}
if (Equals(nextState, CurrentState)) return;
if(_nextTargetState.Allow && Equals(_nextTargetState.Value,nextState))return;
if (_nextTargetState.Allow)
{
_nextTargetState.Value = nextState;
return;
}
_nextTargetState.SetValueThenAllow(nextState);
await IsBusy;
if(_cancellationTokenSource.IsCancellationRequested)return;
using var _ = IsBusy.GetHandle();
OnStateChanging?.Invoke(CurrentState,nextState);
if (_dictionary.TryAdd(nextState.Identifier, nextState))
{
await nextState.InitializeAsync();
if(_cancellationTokenSource.IsCancellationRequested)return;
nextState.Initialize();
}
if (CurrentState is not null)
{
CurrentState.Enabled = false;
await CurrentState.OnStateExitAsync(CurrentState, nextState);
if(_cancellationTokenSource.IsCancellationRequested)return;
CurrentState.OnStateExit(CurrentState,nextState);
}
var tempState = CurrentState;
CurrentState = _nextTargetState.Value;
_nextTargetState.Clear();
nextState.Enabled = true;
await nextState.OnStateEntryAsync(tempState);
if(_cancellationTokenSource.IsCancellationRequested)return;
nextState.OnStateEntry(tempState);
OnStateChanged?.Invoke(tempState,nextState);
}
public T TransitionState(T nextState)
{
TransitionStateAsync(nextState).Forget();
return nextState;
}
public async void UnRegister(T newState)
{
if (newState is null) return;
if (Dictionary.ContainsKey(newState.Identifier) is false) return;
_dictionary.Remove(newState.Identifier);
if (Equals(CurrentState, newState))
{
await CurrentState.OnStateExitAsync(CurrentState, null);
CurrentState.OnStateExit(CurrentState, null);
if (CurrentState is IAsyncDisposable asyncDisposable)
{
await asyncDisposable.DisposeAsync();
}
if (CurrentState is IDisposable disposable)
{
disposable.Dispose();
}
CurrentState = null;
}
OnStateUnRegistered?.Invoke(newState);
}
public void Dispose()
{
if(_isDisposed)return;
_cancellationTokenSource.Cancel();
_cancellationTokenSource.Dispose();
_isDisposed = true;
}
private bool _isDisposed;
}
}

View File

@@ -0,0 +1,85 @@
using System;
using System.Collections.Generic;
using Cysharp.Threading.Tasks;
namespace BITKit.StateMachine
{
public struct EmptyState:IState
{
public bool Enabled { get; set; }
public void Initialize()
{
}
public void OnStateEntry(IState old)
{
}
public void OnStateUpdate(float deltaTime)
{
}
public void OnStateExit(IState old, IState newState)
{
}
}
public interface IState
{
bool Enabled { get; set; }
void Initialize();
void OnStateEntry(IState old);
void OnStateUpdate(float deltaTime);
void OnStateExit(IState old, IState newState);
}
public interface IStateAsync:IState
{
/// <summary>
/// 识别符,用于识别多个相同状态但不同用途的状态机
/// </summary>
int Identifier { get; set; }
UniTask InitializeAsync();
UniTask OnStateEntryAsync(IState old);
UniTask OnStateUpdateAsync(float deltaTime);
UniTask OnStateExitAsync(IState old, IState newState);
}
public interface IStateMachine<T> where T:IState
{
bool Enabled { get; set; }
T CurrentState { get; }
event Action<T,T> OnStateChanged;
event Action<T> OnStateRegistered;
event Action<T> OnStateUnRegistered;
IDictionary<Type, T> StateDictionary { get; }
void Initialize();
void UpdateState(float deltaTime);
void DisposeState();
T TransitionState<TState>() where TState : T;
T TransitionState(T state);
void Register(T newState) => throw new NotImplementedException("未实现的接口");
void UnRegister(T newState) => throw new NotImplementedException("未实现的接口");
void InvokeOnStateRegistered(T state){}
void InvokeOnStateUnRegistered(T state){}
}
public static class StateMachineUtils
{
public static void Register<T>(this IStateMachine<T> stateMachine, T newState) where T : IState
{
if (stateMachine.StateDictionary.ContainsKey(newState.GetType()))
{
throw new ArgumentException($"State {newState.GetType().Name} already registered");
}
stateMachine.StateDictionary.Add(newState.GetType(), newState);
newState.Initialize();
stateMachine.InvokeOnStateRegistered(newState);
}
public static void UnRegister<T>(this IStateMachine<T> stateMachine, T newState) where T : IState
{
if (!stateMachine.StateDictionary.ContainsKey(newState.GetType())) return;
stateMachine.StateDictionary.Remove(newState.GetType());
stateMachine.InvokeOnStateUnRegistered(newState);
}
}
}