This commit is contained in:
CortexCore 2024-11-08 17:28:07 +08:00
parent 1650126d55
commit faf72b05e9
14 changed files with 196 additions and 379 deletions

View File

@ -7,6 +7,7 @@ using Microsoft.SqlServer.Server;
namespace BITKit
{
/// <summary>
/// 支持二进制化的的物品容器,适用于网络化物品容器
/// 支持属性
@ -74,7 +75,7 @@ namespace BITKit
public class RuntimeItemContainer : IRuntimeItemContainer
{
private readonly ConcurrentDictionary<int, IRuntimeItem> _items = new();
public readonly ConcurrentDictionary<int, IRuntimeItem> Items = new();
public void Read(BinaryReader r)
{
throw new NotImplementedException();
@ -86,7 +87,7 @@ namespace BITKit
}
public int Id { get; set; }
public IRuntimeItem[] GetItems()=>_items.Values.ToArray();
public IRuntimeItem[] GetItems()=>Items.Values.ToArray();
public bool Add(IRuntimeItem item)
{
@ -98,17 +99,17 @@ namespace BITKit
}
}
_items.Set(item.Id,item);
Items.Set(item.Id, item);
OnAdd?.Invoke(item);
//BIT4Log.Log<RuntimeItemContainer>($"添加了了:{item.Id}");
return true;
}
public bool Remove(int id)
{
if (_items.TryGetValue(id, out var item) is false) return false;
if (Items.TryGetValue(id, out var item) is false) return false;
foreach (var func in RemoveFactory.CastAsFunc())
{
@ -117,7 +118,7 @@ namespace BITKit
return false;
}
}
_items.TryRemove(item.Id);
Items.TryRemove(item.Id);
OnRemove?.Invoke(item);
//BIT4Log.Log<RuntimeItemContainer>($"移除了:{id}");
return true;
@ -125,8 +126,7 @@ namespace BITKit
public bool Drop(int id)
{
if (_items.TryGetValue(id, out var item) is false) return false;
if (Items.TryGetValue(id, out var item) is false) return false;
foreach (var func in DropFactory.CastAsFunc())
{
if (func.Invoke(item) is false)
@ -134,7 +134,7 @@ namespace BITKit
return false;
}
}
_items.TryRemove(item.Id);
Items.TryRemove(item.Id);
OnDrop?.Invoke(item);
//BIT4Log.Log<RuntimeItemContainer>($"丢下了:{id}");
return true;

13
Src/Core/Item/ItemEx.cs Normal file
View File

@ -0,0 +1,13 @@
using System.Collections;
using System.Collections.Generic;
namespace BITKit
{
/// <summary>
/// 玩家向背包添加物品,但是被其他逻辑处理
/// </summary>
public sealed class PlayerInventoryAddItemOverridden : InGameException
{
}
}

View File

@ -1,5 +1,5 @@
fileFormatVersion: 2
guid: 2abc8d2959200da4294a6177cc85c5ca
guid: ebeadaca27f99904a87e52f3f63042f9
MonoImporter:
externalObjects: {}
serializedVersion: 2

View File

@ -1,8 +1,7 @@
using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Cysharp.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
@ -16,111 +15,113 @@ namespace BITKit.StateMachine
{
private enum AsyncState
{
None,
Initializing,
InEntering,
InExiting,
InUpdating,
}
private readonly IServiceCollection _serviceCollection;
public AsyncStateMachine(IServiceCollection serviceCollection)
private readonly IServiceProvider _serviceProvider;
public AsyncStateMachine(IServiceProvider serviceProvider)
{
_serviceCollection = serviceCollection;
_serviceProvider = serviceProvider;
}
public AsyncStateMachine()
{
_serviceProvider = new ServiceCollection().BuildServiceProvider();
}
public bool Enabled { get; set; }
public T CurrentState { get; set; }
private T _nextState;
public event Action<T, T> OnStateChanging;
public event Action<T, T> OnStateChanging;
public event Action<T, T> OnStateChanged;
public event Action<T> OnStateRegistered;
public event Action<T> OnStateUnRegistered;
public IDictionary<Type, T> StateDictionary { get; } = new Dictionary<Type, T>();
private AsyncState _currentState;
private Task _currentTask;
private readonly CancellationTokenSource _cancellationTokenSource=new();
public async void Initialize()
private readonly ValidHandle _isBusy=new();
private readonly ConcurrentQueue<(UniTask task,AsyncState state,T value)> _taskQueue=new();
public void Initialize()
{
if (_currentState is not AsyncState.None)
foreach (var (_,value) in StateDictionary)
{
throw new InvalidOperationException("状态机可能已初始化");
_taskQueue.Enqueue(new (value.InitializeAsync(),AsyncState.Initializing,value));
}
_currentState = AsyncState.Initializing;
foreach (var (type,value) in StateDictionary)
{
await value.InitializeAsync();
}
foreach (var (type,value) in StateDictionary)
{
value.Initialize();
}
_currentState = AsyncState.None;
}
public void UpdateState(float deltaTime)
public async void UpdateState(float deltaTime)
{
if(_cancellationTokenSource.IsCancellationRequested)return;
switch (_currentState)
if(Enabled is false)return;
CurrentState?.OnStateUpdate(deltaTime);
if(_isBusy)return;
using var _ = _isBusy.GetHandle();
if (!_taskQueue.TryDequeue(out var task)) return;
await task.task;
if(_cancellationTokenSource.IsCancellationRequested|| Enabled is false)return;
switch (task.state)
{
case AsyncState.None:
if (_nextState is not null)
{
_currentState = AsyncState.InEntering;
_currentTask = CurrentState.OnStateEntryAsync(CurrentState).AsTask();
OnStateChanging?.Invoke(CurrentState,_nextState);
return;
}
_currentState = AsyncState.InUpdating;
if (CurrentState is not null)
{
_currentTask = CurrentState.OnStateUpdateAsync(deltaTime).AsTask();
}
break;
case AsyncState.InExiting:
if (_currentTask.IsCompleted)
{
_currentState =_nextState is not null ? AsyncState.InEntering : AsyncState.None;
CurrentState.OnStateExit(CurrentState,_nextState);
if (_nextState is not null)
{
_currentTask = _nextState.OnStateEntryAsync(_nextState).AsTask();
}
}
case AsyncState.Initializing:
task.value.Initialize();
OnStateRegistered?.Invoke(task.value);
break;
case AsyncState.InEntering:
if (_currentTask.IsCompleted)
{
_currentState = AsyncState.None;
_nextState.OnStateEntry(CurrentState);
OnStateChanged?.Invoke(CurrentState,_nextState);
CurrentState = _nextState;
_nextState = default;
}
_nextState.OnStateEntry(_nextState);
OnStateChanged?.Invoke(CurrentState,_nextState);
CurrentState = _nextState;
break;
case AsyncState.InUpdating:
if (_currentTask.IsCompleted)
{
_currentTask = null;
_currentState = AsyncState.None;
}
case AsyncState.InExiting:
CurrentState?.OnStateExit(CurrentState,_nextState);
break;
}
if(Enabled is false)return;
if (CurrentState is not null)
{
await CurrentState.OnStateUpdateAsync(deltaTime);
}
}
public void DisposeState()
{
_taskQueue.Clear();
if (CurrentState is not null)
{
_taskQueue.Enqueue(new(CurrentState.OnStateExitAsync(CurrentState,null),AsyncState.InExiting,CurrentState));
}
}
public void TransitionState<State>() where State : T
public T TransitionState<TState>() where TState : T
{
throw new InvalidOperationException("动态异步状态机不支持,请使用TransitionAsync");
T nextState;
foreach (var (type, value) in StateDictionary)
{
if (!type.IsAssignableFrom(typeof(TState))) continue;
nextState = value;
TransitionState(nextState);
return nextState;
}
nextState = _serviceProvider.GetRequiredService<TState>();
_taskQueue.Enqueue(new(nextState.InitializeAsync(),AsyncState.Initializing,nextState));
TransitionState(nextState);
return nextState;
}
public void TransitionState(T state)
public T TransitionState(T nextState)
{
if(Equals(CurrentState,nextState))return nextState;
OnStateChanging?.Invoke(CurrentState,nextState);
if (CurrentState is not null)
{
_taskQueue.Enqueue(new(CurrentState.OnStateExitAsync(CurrentState,nextState),AsyncState.InExiting,CurrentState));
}
if (nextState is not null)
{
_taskQueue.Enqueue(new(nextState.OnStateEntryAsync(nextState),AsyncState.InEntering,nextState));
}
return nextState;
}
public void Dispose()

View File

@ -56,8 +56,8 @@ namespace BITKit.StateMachine
void Initialize();
void UpdateState(float deltaTime);
void DisposeState();
void TransitionState<State>() where State : T;
void TransitionState(T state);
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){}

View File

@ -1,5 +1,6 @@
using System;
using System.Collections.Generic;
using Cysharp.Threading.Tasks;
namespace BITKit
{
@ -22,6 +23,23 @@ namespace BITKit
[CustomType(typeof(IValidHandle))]
public sealed class ValidHandle: IValidHandle
{
public class MyHandle:IDisposable
{
private readonly ValidHandle _validHandle;
public MyHandle(ValidHandle validHandle)
{
_validHandle = validHandle;
_validHandle.AddElement(this);
}
public void Dispose()
{
_validHandle.RemoveElement(this);
}
}
public MyHandle GetHandle() => new MyHandle(this);
public override string ToString()
{
return $"Allow:{enableHandle}\nElements:{string.Join("\n",objs)}\nDisableElements:{string.Join("\n",disableObjs)}";
@ -51,6 +69,7 @@ namespace BITKit
public readonly List<object> disableObjs = new List<object>();
private bool tempEnable;
private Action<bool> EventOnEnableChanged;
private readonly List<UniTaskCompletionSource> _completionSources = new();
public void AddElement(object obj)
@ -73,7 +92,14 @@ namespace BITKit
{
enableHandle = tempEnable;
if (EventOnEnableChanged is not null)
{
EventOnEnableChanged.Invoke(enableHandle);
}
if (tempEnable) return;
foreach (var cs in _completionSources)
{
cs.TrySetResult();
}
}
}
public void RemoveElement(object obj)
@ -164,7 +190,16 @@ namespace BITKit
EventOnEnableChanged -= action;
}
}
public UniTask.Awaiter GetAwaiter()
{
if (Allow is false)
{
return UniTask.CompletedTask.GetAwaiter();
}
var cs = new UniTaskCompletionSource();
_completionSources.Add(cs);
return cs.Task.GetAwaiter();
}
public void Clear()
{
objs.Clear();

View File

@ -1,74 +0,0 @@
using System;
using System.Collections;
using System.Collections.Generic;
using BITKit.StateMachine;
using UnityEngine;
namespace BITKit
{
public abstract class StateBasedMonoBehaviour<T> : MonoBehaviour, IStateMachine<T> where T : IState
{
[SerializeField] private MonoStateMachine<T> stateMachine;
protected Transform Transform => _transform ? _transform : _transform = transform;
private Transform _transform;
public bool Enabled
{
get => stateMachine.Enabled;
set => stateMachine.Enabled = value;
}
public T CurrentState
{
get => stateMachine.CurrentState;
set => stateMachine.CurrentState = value;
}
public event Action<T, T> OnStateChanged
{
add => stateMachine.OnStateChanged += value;
remove => stateMachine.OnStateChanged -= value;
}
public event Action<T> OnStateRegistered;
public event Action<T> OnStateUnRegistered;
public IDictionary<Type, T> StateDictionary => stateMachine.StateDictionary;
public virtual void Initialize()
{
stateMachine.Initialize();
}
public virtual void UpdateState(float deltaTime)
{
stateMachine.UpdateState(deltaTime);
}
public virtual void DisposeState()
{
stateMachine.DisposeState();
}
public virtual void TransitionState<State>() where State : T
{
stateMachine.TransitionState<State>();
}
public virtual void TransitionState(T state)
{
stateMachine.TransitionState(state);
}
public virtual void Register(T newState) => StateMachineUtils.Register(this,newState);
public virtual void UnRegister(T newState)=>StateMachineUtils.UnRegister(this,newState);
void IStateMachine<T>.InvokeOnStateRegistered(T state)
{
OnStateRegistered?.Invoke(state);
}
void IStateMachine<T>.InvokeOnStateUnRegistered(T state)
{
OnStateUnRegistered?.Invoke(state);
}
}
}

View File

@ -1,11 +0,0 @@
fileFormatVersion: 2
guid: 9c3c4b253dc3f5144abdd6fa34699cdd
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -2,11 +2,21 @@ using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using BITKit.Mod;
using Cysharp.Threading.Tasks;
using UnityEngine;
using UnityEngine.UIElements;
namespace BITKit
{
public static class ModServiceDictionaryReferenceExtensions
{
public static UniTask<T> LoadAssets<T>(int id) where T :class
{
var path = DictionaryReferenceScriptableObject.Dictionary[id];
return ModService.LoadAsset<T>(path);
}
}
public sealed class DictionaryReferenceConfigAttribute : System.Attribute
{
public readonly int index;

View File

@ -18,7 +18,9 @@
"overrideReferences": false,
"precompiledReferences": [],
"autoReferenced": true,
"defineConstraints": [],
"defineConstraints": [
"deprecated"
],
"versionDefines": [],
"noEngineReferences": false
}

View File

@ -1,29 +0,0 @@
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
using UnityEngine.UIElements;
namespace BITKit.Sensors
{
public class SensorEditorWindow : EditorWindow
{
private Toggle _toggle;
[MenuItem("Tools/Sensor/EditorWindow")]
public static void ShowWindow()
{
GetWindow<SensorEditorWindow>("SensorEditorWindow");
}
private void CreateGUI()
{
_toggle = rootVisualElement.Create<Toggle>("Enable Sensor");
_toggle.label = "Enable Sensor";
_toggle.value = SensorGlobalSettings.Enabled;
}
private void Update()
{
SensorGlobalSettings.Enabled = _toggle.value;
}
}
}

View File

@ -1,11 +0,0 @@
fileFormatVersion: 2
guid: b0ad25384d3d5d74a95d99ceed99ec8d
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -1,130 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
#if UNITY_EDITOR
using UnityEditor;
using UnityEditor.UIElements;
#endif
using UnityEngine;
using UnityEngine.UIElements;
namespace BITKit.StateMachine
{
[Serializable]
public class MonoStateMachine<TState> : IStateMachine<TState> where TState : IState
{
public bool Enabled
{
get => _enabled;
set
{
_enabled = value;
if (CurrentState is null) return;
if (value)
{
CurrentState.OnStateExit(null,null);
}
else
{
CurrentState.OnStateEntry(null);
}
}
}
public TState CurrentState { get; set; }
public event Action<TState, TState> OnStateChanged;
public event Action<TState> OnStateRegistered;
public event Action<TState> OnStateUnRegistered;
[SerializeReference, SubclassSelector] public List<TState> states = new();
[SerializeField,ReadOnly] private string _currentStateName;
[SerializeField] private bool debug;
[SerializeField] private bool transitionOnNextFrame;
public IDictionary<Type, TState> StateDictionary { get; } = new Dictionary<Type, TState>();
private bool _enabled = true;
private readonly DoubleBuffer<TState> _nextState = new();
protected bool cancelUpdateStateThisFrame;
public void Initialize()
{
foreach (var state in states)
{
//state.TransitionState = InternalTransitionState;
state.Initialize();
StateDictionary.Add(state.GetType(), state);
}
// if (states.Count > 0)
// {
// TransitionState(states[0]);
// }
}
public void UpdateState(float deltaTime)
{
if(transitionOnNextFrame && _nextState.TryGetRelease(out var nextState))
TransitionStateInternal(nextState);
if (Enabled)
{
if (cancelUpdateStateThisFrame is false)
{
CurrentState?.OnStateUpdate(deltaTime);
}
cancelUpdateStateThisFrame = false;
}
}
public void DisposeState()
{
}
public void TransitionState<State>() where State : TState
{
var nextState = StateDictionary.GetOrCreate(typeof(State));
TransitionState(nextState);
}
public void TransitionState(TState newState)
{
if(transitionOnNextFrame)
_nextState.Release(newState);
else
{
TransitionStateInternal(newState);
cancelUpdateStateThisFrame = true;
}
}
private void TransitionStateInternal(TState newState)
{
if (Equals(newState,CurrentState)) return;
var oldState = CurrentState;
if (oldState is not null)
{
oldState.OnStateExit(oldState, newState);
oldState.Enabled = false;
}
_currentStateName = newState is not null ? newState.GetType().Name : "null";
if (debug)
{
BIT4Log.Log<MonoStateMachine<TState>>($"TransitionState from {_currentStateName} to {_currentStateName}");
}
CurrentState = newState;
if (newState is not null)
{
newState.Enabled = true;
newState.OnStateEntry(oldState);
}
OnStateChanged?.Invoke(oldState, newState);
}
public virtual void Register(TState newState)=>StateMachineUtils.Register(this,newState);
public virtual void UnRegister(TState newState)=>StateMachineUtils.UnRegister(this,newState);
public void InvokeOnStateRegistered(TState state)
{
OnStateRegistered?.Invoke(state);
}
public void InvokeOnStateUnRegistered(TState state)
{
OnStateUnRegistered?.Invoke(state);
}
}
}

View File

@ -28,10 +28,55 @@ namespace BITKit.UX
protected abstract string DocumentPath { get; }
public VisualElement RootVisualElement { get; set; }
protected VisualTreeAsset VisualTreeAsset { get; private set; }
private readonly ValidHandle _isBusy = new();
protected UIToolKitPanel(IUXService uxService)
{
UXService = uxService;
uxService.Register(this);
InitializeAsync().Forget();
}
private async UniTask InitializeAsync()
{
await _isBusy;
using var b = _isBusy.GetHandle();
if (RootVisualElement is null)
{
VisualTreeAsset = await ModService.LoadAsset<VisualTreeAsset>(DocumentPath);
RootVisualElement = UXService.Root.As<VisualElement>().Create(VisualTreeAsset);
RootVisualElement.pickingMode = PickingMode.Ignore;
RootVisualElement.style.position = Position.Absolute;
RootVisualElement.style.left = 0;
RootVisualElement.style.right = 0;
RootVisualElement.style.top = 0;
RootVisualElement.style.bottom = 0;
var invisible = RootVisualElement.Create<VisualElement>();
invisible.name = "invisible_return_generate";
invisible.style.position = Position.Absolute;
invisible.pickingMode = PickingMode.Ignore;
invisible.style.left = 0;
invisible.style.right = 0;
invisible.style.top = 0;
invisible.style.bottom = 0;
invisible.SendToBack();
if (CloseWhenClickOutside)
{
invisible.RegisterCallback<MouseDownEvent>(x => { OnReturn(); });
invisible.pickingMode = PickingMode.Position;
}
if (IsWindow)
{
invisible.style.backgroundColor = new Color(0, 0, 0, 0.9f);
}
UXUtils.Inject(this);
RootVisualElement.SetActive(false);
}
}
protected virtual Optional<float> EntryDuration { get; }= new();
@ -62,42 +107,8 @@ namespace BITKit.UX
OnEntry?.Invoke();
}
async UniTask IEntryElement.EntryAsync()
{
if (RootVisualElement is null)
{
VisualTreeAsset = await ModService.LoadAsset<VisualTreeAsset>(DocumentPath);
RootVisualElement = UXService.Root.As<VisualElement>().Create(VisualTreeAsset);
RootVisualElement.pickingMode = PickingMode.Ignore;
RootVisualElement.style.position = Position.Absolute;
RootVisualElement.style.left = 0;
RootVisualElement.style.right = 0;
RootVisualElement.style.top = 0;
RootVisualElement.style.bottom = 0;
var invisible = RootVisualElement.Create<VisualElement>();
invisible.name = "invisible_return_generate";
invisible.style.position = Position.Absolute;
invisible.pickingMode = PickingMode.Ignore;
invisible.style.left = 0;
invisible.style.right = 0;
invisible.style.top = 0;
invisible.style.bottom = 0;
invisible.SendToBack();
if (CloseWhenClickOutside)
{
invisible.RegisterCallback<MouseDownEvent>(x => { OnReturn(); });
invisible.pickingMode = PickingMode.Position;
}
if (IsWindow)
{
invisible.style.backgroundColor = new Color(0, 0, 0, 0.9f);
}
UXUtils.Inject(this);
}
{
await InitializeAsync();
RootVisualElement.SetActive(true);
RootVisualElement.AddToClassList(USSEntry);