Compare commits

...

2 Commits

Author SHA1 Message Date
CortexCore 1c00d8fb1c Merge branch 'main' of http://server.bitfall.icu:3000/root/BITKit 2024-12-25 11:35:39 +08:00
CortexCore b12511b825 1 2024-12-25 11:35:30 +08:00
8 changed files with 100 additions and 63 deletions

View File

@ -13,8 +13,12 @@ namespace BITKit
{ {
_logger = logger; _logger = logger;
_message = message; _message = message;
_logger.LogInformation($"开始计时:{message}");
_logger.LogInformation($"开始计时:{message}");
_stopwatch.Start();
} }
public void Dispose() public void Dispose()
{ {
_stopwatch.Stop(); _stopwatch.Stop();

View File

@ -21,7 +21,7 @@ namespace BITKit
} }
[CustomType(typeof(IValidHandle))] [CustomType(typeof(IValidHandle))]
public sealed class ValidHandle: IValidHandle public sealed class ValidHandle: IValidHandle,IDisposable
{ {
public class MyHandle:IDisposable public class MyHandle:IDisposable
{ {
@ -71,7 +71,7 @@ namespace BITKit
} }
public static implicit operator bool(ValidHandle validHandle) public static implicit operator bool(ValidHandle validHandle)
{ {
return validHandle.enableHandle; return !validHandle._isDisposed && validHandle.enableHandle;
} }
public bool Allow => this; public bool Allow => this;
@ -88,7 +88,7 @@ namespace BITKit
private bool tempEnable; private bool tempEnable;
private Action<bool> EventOnEnableChanged; private Action<bool> EventOnEnableChanged;
private readonly Queue<UniTaskCompletionSource> _completionSources = new(); private readonly Queue<UniTaskCompletionSource> _completionSources = new();
private bool _isDisposed;
public void AddElement(object obj) public void AddElement(object obj)
{ {
@ -224,6 +224,14 @@ namespace BITKit
disableObjs.Clear(); disableObjs.Clear();
Invoke(); Invoke();
} }
public void Dispose()
{
_isDisposed = true;
objs.Clear();
disableObjs.Clear();
EventOnEnableChanged = null;
}
} }
} }

View File

@ -18,6 +18,7 @@ namespace BITKit
{ {
public class BITFramework : MonoBehaviour public class BITFramework : MonoBehaviour
{ {
public static BITFramework Singleton { get; private set; }
private static System.Diagnostics.Stopwatch Stopwatch; private static System.Diagnostics.Stopwatch Stopwatch;
[RuntimeInitializeOnLoadMethod] [RuntimeInitializeOnLoadMethod]
@ -29,17 +30,6 @@ namespace BITKit
SplashScreen.Stop(SplashScreen.StopBehavior.StopImmediate); SplashScreen.Stop(SplashScreen.StopBehavior.StopImmediate);
#endif #endif
} }
// [SerializeField] private AssetReference serviceReference;
// private async void Start()
// {
// if(InitializationState is not InitializationState.None)return;
// InitializationState = InitializationState.Initializing;
// var asyncOperationHandle = serviceReference.LoadAssetAsync<GameObject>();
// await UniTask.WaitUntil(() => asyncOperationHandle.IsDone);
// DontDestroyOnLoad(Instantiate(asyncOperationHandle.Result));
// Stopwatch.Stop();
// BIT4Log.Log<BITFramework>($"BITFramework加载完成,耗时:{Stopwatch.ElapsedMilliseconds}ms");
// }
[SerializeReference, SubclassSelector] private IReference addressableName; [SerializeReference, SubclassSelector] private IReference addressableName;
[SerializeReference, SubclassSelector] private IReference packageName = new Reference("DefaultPackage"); [SerializeReference, SubclassSelector] private IReference packageName = new Reference("DefaultPackage");
@ -69,6 +59,7 @@ namespace BITKit
private Action<string> _setProgressLabel; private Action<string> _setProgressLabel;
private async void Start() private async void Start()
{ {
Singleton = this;
try try
{ {
#if UNITY_EDITOR #if UNITY_EDITOR
@ -151,10 +142,18 @@ namespace BITKit
} }
} }
#endif #endif
if (isOffline) #if UNITY_5_3_OR_NEWER
if (IsEditorSimulateMode is false && isOffline)
{ {
initParameters = new OfflinePlayModeParameters(); initParameters = new OfflinePlayModeParameters();
} }
#else
if (isOffline)
{
initParameters = new OfflinePlayModeParameters();
}
#endif
InitializationOperation initOperation = null; InitializationOperation initOperation = null;
try try
@ -312,30 +311,7 @@ namespace BITKit
YooAssetUtils.RegisterPackage(packageName.Value); YooAssetUtils.RegisterPackage(packageName.Value);
YooAssetUtils.RegisterResourcePackage(package); YooAssetUtils.RegisterResourcePackage(package);
if (loadEntryScene.Allow) await AfterInit(package);
{
_progressLabel.text="正在加载场景...";
try
{
await package.LoadSceneAsync(loadEntryScene.Value);
_progressLabel.text="场景加载完成...";
}
catch (Exception e)
{
Debug.LogException(e);
await UniTask.NextFrame();
_progressLabel.text = e.Message;
}
}
else
{
_progressLabel.text="未找到默认场景,正在加载场景[1]";
SceneManager.LoadScene(1);
}
if (document)
Destroy(document);
} }
catch (Exception e) catch (Exception e)
{ {
@ -343,9 +319,35 @@ namespace BITKit
_progressBar.value =0; _progressBar.value =0;
_progressLabel.text = e.Message; _progressLabel.text = e.Message;
} }
} }
private async UniTask AfterInit(ResourcePackage package)
{
if (loadEntryScene.Allow)
{
_progressLabel.text="正在加载场景...";
try
{
await package.LoadSceneAsync(loadEntryScene.Value);
_progressLabel.text="场景加载完成...";
}
catch (Exception e)
{
Debug.LogException(e);
await UniTask.NextFrame();
_progressLabel.text = e.Message;
}
}
else
{
_progressLabel.text="未找到默认场景,正在加载场景[1]";
SceneManager.LoadScene(1);
}
if (document)
Destroy(document);
}
private void OnDestroy() private void OnDestroy()
{ {
#if UNITY_EDITOR #if UNITY_EDITOR

View File

@ -7,8 +7,9 @@ using ILogger = Microsoft.Extensions.Logging.ILogger;
namespace BITKit namespace BITKit
{ {
public sealed class UnityLogger:ILogger public abstract class UnityLogger:ILogger
{ {
[HideInCallstack]
public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter) public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter)
{ {
switch (logLevel) switch (logLevel)
@ -37,15 +38,37 @@ namespace BITKit
return null; return null;
} }
} }
public sealed class UnityLoggerProvider:ILoggerProvider public sealed class UnityLogger<T>:ILogger<T>
{ {
public void Dispose() public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter)
{ {
switch (logLevel)
{
case LogLevel.Critical:
case LogLevel.Error:
if (exception is not null)
{
Debug.LogException(exception);
}
else
{
Debug.LogError($"{typeof(T).Name}:{state.ToString()}");
}
break;
default:
Debug.Log($"{typeof(T).Name}:{state.ToString()}");
break;
}
} }
public ILogger CreateLogger(string categoryName) public bool IsEnabled(LogLevel logLevel)
{ {
return new UnityLogger(); return true;
}
public IDisposable BeginScope<TState>(TState state) where TState : notnull
{
return null;
} }
} }
} }

View File

@ -159,7 +159,7 @@ namespace BITKit.UX
Dispose(); Dispose();
BITAppForUnity.AllowCursor.RemoveElement(this); BITAppForUnity.AllowCursor.RemoveElement(this);
} }
public void Show(string content, string title = "Alert", Action confirmAction = null, Action<bool> onChoose = null) public async void Show(string content, string title = "Alert", Action confirmAction = null, Action<bool> onChoose = null)
{ {
PrintAlertMessage(new AlertMessage() PrintAlertMessage(new AlertMessage()
{ {

View File

@ -12,19 +12,18 @@ namespace BITKit.UX
protected readonly CancellationTokenSource CancellationToken; protected readonly CancellationTokenSource CancellationToken;
protected readonly IUXService UXService; protected readonly IUXService UXService;
protected VisualElement RootVisualElement { get; set; } protected VisualElement RootVisualElement { get; set; }
private bool _initialized; protected bool IsInitialized { get; private set; }
protected UIToolkitOverlay(IUXService uxService, CancellationTokenSource cancellationToken) protected UIToolkitOverlay(IUXService uxService, CancellationTokenSource cancellationToken)
{ {
UXService = uxService; UXService = uxService;
CancellationToken = cancellationToken; CancellationToken = cancellationToken;
CancellationToken.Token.Register(Dispose); CancellationToken.Token.Register(Dispose);
} }
protected abstract string DocumentPath { get; } protected abstract string DocumentPath { get; }
// ReSharper disable once MemberCanBeProtected.Global // ReSharper disable once MemberCanBeProtected.Global
public virtual async UniTask InitializeAsync() public virtual async UniTask InitializeAsync()
{ {
if(_initialized)return; if(IsInitialized)return;
var asset =await ModService.LoadAsset<VisualTreeAsset>(DocumentPath); var asset =await ModService.LoadAsset<VisualTreeAsset>(DocumentPath);
var root= RootVisualElement = UXService.Root.As<VisualElement>().Create(asset); var root= RootVisualElement = UXService.Root.As<VisualElement>().Create(asset);
@ -40,12 +39,12 @@ namespace BITKit.UX
root.style.right = 0; root.style.right = 0;
UXUtils.Inject(this); UXUtils.Inject(this);
_initialized = true; IsInitialized = true;
} }
public virtual void Dispose() public virtual void Dispose()
{ {
if(RootVisualElement is null)return; if(RootVisualElement is null)return;
_initialized = false; IsInitialized = false;
RootVisualElement.RemoveFromHierarchy(); RootVisualElement.RemoveFromHierarchy();
RootVisualElement = null; RootVisualElement = null;
} }

View File

@ -1,6 +1,7 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Text; using System.Text;
using System.Threading;
using BITKit.Mod; using BITKit.Mod;
using Cysharp.Threading.Tasks; using Cysharp.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection;
@ -17,10 +18,12 @@ namespace BITKit.UX
{ {
private readonly IAfterTicker _ticker; private readonly IAfterTicker _ticker;
private readonly IServiceProvider _serviceProvider; private readonly IServiceProvider _serviceProvider;
public UXService(IAfterTicker ticker, IServiceProvider serviceProvider) private readonly CancellationTokenSource _cancellationTokenSource;
public UXService(IAfterTicker ticker, IServiceProvider serviceProvider, CancellationTokenSource cancellationTokenSource)
{ {
_ticker = ticker; _ticker = ticker;
_serviceProvider = serviceProvider; _serviceProvider = serviceProvider;
_cancellationTokenSource = cancellationTokenSource;
_entryGroup.OnEntry += OnEntry; _entryGroup.OnEntry += OnEntry;
_ticker.Add(OnTick); _ticker.Add(OnTick);
} }
@ -74,6 +77,12 @@ namespace BITKit.UX
var gameObject = new GameObject("UXService"); var gameObject = new GameObject("UXService");
Object.DontDestroyOnLoad(gameObject); Object.DontDestroyOnLoad(gameObject);
_cancellationTokenSource.Token.Register(() =>
{
Object.Destroy(gameObject);
});
var document = gameObject.AddComponent<UIDocument>(); var document = gameObject.AddComponent<UIDocument>();
try try
{ {

View File

@ -83,17 +83,9 @@ namespace BITKit
{ {
handle.Dispose(); handle.Dispose();
} }
private async void OnTick(float deltaTime) private void OnTick(float deltaTime)
{ {
switch (_initializationState) if(_initializationState is not InitializationState.Initialized)return;
{
case InitializationState.None:
_initializationState = InitializationState.Initializing;
await InitializeAsync();
break;
case InitializationState.Initializing:
return;
}
while (_initializedHandles.TryDequeue(out var handle)) while (_initializedHandles.TryDequeue(out var handle))
{ {
var container = _container.Create(_handleTemplate); var container = _container.Create(_handleTemplate);