From 8261a458e29867fb6818a9368f45bd1f09ced00b Mon Sep 17 00:00:00 2001 From: CortexCore <2630229280@qq.com> Date: Mon, 24 Feb 2025 23:02:43 +0800 Subject: [PATCH] 1 --- Src/Core/Attributes/DataAttribute.cs | 0 .../Attributes/DataAttribute.cs.meta} | 2 +- Src/{ => Core}/BITKit.asmdef | 0 Src/{ => Core}/BITKit.asmdef.meta | 0 Src/Core/ECS/Built-In/IdComponent.cs | 10 +- Src/Core/ECS/Built-In/LocalPlayerComponent.cs | 10 + .../Built-In/LocalPlayerComponent.cs.meta} | 2 +- Src/Core/ECS/EntitiesService.cs | 171 +++++++-- Src/Core/ECS/EntityComponentSystem.cs | 1 - .../Scripts/Mono.meta => Core/Hotkey.meta} | 2 +- Src/Core/Hotkey/BITKit.Hotkey.asmdef | 14 + .../Hotkey/BITKit.Hotkey.asmdef.meta} | 2 +- Src/Core/Hotkey/IHotkeyCollection.cs | 47 +++ .../Hotkey/IHotkeyCollection.cs.meta} | 2 +- Src/Core/Item/Item.cs | 13 +- Src/Core/Mod/ModService.cs | 56 +-- Src/Core/Mod/ModService_IO.cs | 13 + Src/Core/Net/NetProvider.cs | 9 + Src/Core/Sharp/BITSharp.cs | 60 +++- Src/Core/StateMachine/AsyncStateMachine.cs | 23 +- Src/Core/StateMachine/IStateMachine.cs | 75 +++- Src/Core/UX/IUXPanel.cs | 3 + Src/Core/UX/IUXService.cs | 8 + Src/Core/WorldNode/IWorldNodeService.cs | 8 +- .../Scripts => Core}/WorldNode/UnityNode.cs | 7 +- .../WorldNode/UnityNode.cs.meta | 0 Src/Core/WorldNode/WorldInfoNodeService.cs | 19 +- Src/Core/WorldNode/WorldInfoNpcStartNode.cs | 17 + .../WorldNode/WorldInfoNpcStartNode.cs.meta} | 2 +- Src/Core/Wrapper/IWrapper.cs | 18 +- Src/{ => Core}/package.json | 0 Src/{ => Core}/package.json.meta | 0 Src/NetSupport/MathematicsSupport.cs | 4 +- Src/NetSupport/Net.BITKit.NetSupport.asmref | 3 + .../Net.BITKit.NetSupport.asmref.meta} | 5 +- .../UnityMathematicsYamlConverters.cs | 109 ++++++ .../UnityMathematicsYamlConverters.cs.meta | 11 + Src/Unity/BITKit.Unity.asmref | 3 + Src/Unity/BITKit.Unity.asmref.meta | 7 + .../Configs/Input/BITController.inputactions | 204 ++++++++++- Src/Unity/Scripts/Assets/BITFramework.cs | 5 +- .../Assets/ScriptableEntitiesService.cs | 65 ++++ .../Assets/ScriptableEntitiesService.cs.meta | 11 + Src/Unity/Scripts/Assets/YooAssetModHelper.cs | 155 +++++++- Src/Unity/Scripts/BITAppForUnity.cs | 8 + .../Scripts/InputSystem/InputActionGroup.cs | 33 ++ .../Scripts/InputSystem/UnityPlayerInput.cs | 50 +++ .../InputSystem/UnityPlayerInput.cs.meta | 11 + Src/Unity/Scripts/Mod/UnityModService.cs | 121 ------- .../Scripts/Mod/UnityModServiceTester.cs | 48 --- .../Scripts/Physics/BITKit.Physics.asmdef | 3 +- Src/Unity/Scripts/Physics/GeometryUtils.cs | 99 ++++++ .../Scripts/Physics/GeometryUtils.cs.meta | 11 + .../Physics/GetClosePointFromCollider.cs | 154 +++++--- .../GetClosePointFromColliderDebuger.cs | 34 ++ .../GetClosePointFromColliderDebuger.cs.meta | 11 + .../Physics/GetClosestPointFromMesh.cs | 53 +++ .../Physics/GetClosestPointFromMesh.cs.meta | 11 + .../DictionaryReferenceScriptableObject.cs | 2 +- .../Rig/TickOverrideTranformService.cs | 2 +- .../Scripts/Rig/TickOverrideTransform.cs | 2 +- Src/Unity/Scripts/Tick/IntervalTickService.cs | 2 +- Src/Unity/Scripts/UX/BITKit.UX.asmdef | 4 +- .../{StateMachine.meta => UX/Cell.meta} | 2 +- Src/Unity/Scripts/UX/Debuger/UXDebuger.cs | 3 +- .../UX/Input/BITKit.UX.OnScreen.asmdef | 3 +- Src/Unity/Scripts/UX/Input/OnScreenButton.cs | 115 ++++++ .../Scripts/UX/Input/OnScreenButton.cs.meta | 11 + Src/Unity/Scripts/UX/Input/OnScreenControl.cs | 330 ++++++++++++++++++ .../Scripts/UX/Input/OnScreenControl.cs.meta | 11 + Src/Unity/Scripts/UX/Input/OnScreenGamepad.cs | 92 +++++ .../Scripts/UX/Input/OnScreenGamepad.cs.meta | 11 + Src/Unity/Scripts/UX/Input/OnScreenStick.cs | 80 +++++ .../Scripts/UX/Input/OnScreenStick.cs.meta | 11 + Src/Unity/Scripts/UX/Input/UXInputAction.cs | 4 +- Src/Unity/Scripts/UX/Library/CellContainer.cs | 52 +++ .../Scripts/UX/Library/CellContainer.cs.meta | 11 + .../Scripts/UX/ModService/UXModService.cs | 15 +- .../{Selection.meta => UX/RadialMenu.meta} | 2 +- .../Scripts/UX/RadialMenu/UXRadialMenu.cs | 111 ++++++ .../UX/RadialMenu/UXRadialMenu.cs.meta | 11 + .../UX/Service/UI Toolkit/UIToolKitPanel.cs | 44 ++- .../Service/UI Toolkit/UIToolkitSubPanel.cs | 141 ++++++++ .../UI Toolkit/UIToolkitSubPanel.cs.meta | 11 + Src/Unity/Scripts/UX/Service/UXService.cs | 61 +++- Src/Unity/Scripts/UX/Settings/UXSettings.cs | 181 +++++----- Src/Unity/Scripts/UX/ToolTips/UXToolTips.cs | 13 +- .../Scripts/Utility/Editor/BITInspector.cs | 4 +- Src/Unity/Scripts/Utility/Extensions.cs | 57 ++- .../WorldNode/BITKit.WorldNode.Runtime.asmdef | 22 -- Src/Unity/Shader/ShaderGraph/Billboard.mat | 1 - Src/Unity/Socket.meta | 8 - Src/Unity/Socket/ISocketComponent.cs | 16 - Src/Unity/Socket/UnitySocketComponent.cs | 14 - Src/Unity/Socket/UnitySocketService.cs | 50 --- Src/Unity/Socket/UnitySocketService.cs.meta | 11 - Src/Unity/UX/Common/Common.uss | 119 +++++++ Src/Unity/UX/Common/Common_Mobile.asset | 8 - Src/Unity/UX/Common/Common_PC_Overlay.asset | 3 +- Src/Unity/UX/UXsettlement.uss | 10 - Src/Unity/UX/UXsettlement.uss.meta | 11 - Src/Unity/UX/ux_mod_Service.uxml | 87 +++-- Src/Unity/UX/ux_mod_service_template.uxml | 8 +- .../ScriptableObjectGroupEditor.cs | 20 +- 104 files changed, 2924 insertions(+), 686 deletions(-) create mode 100644 Src/Core/Attributes/DataAttribute.cs rename Src/{Unity/Socket/ISocketComponent.cs.meta => Core/Attributes/DataAttribute.cs.meta} (83%) rename Src/{ => Core}/BITKit.asmdef (100%) rename Src/{ => Core}/BITKit.asmdef.meta (100%) create mode 100644 Src/Core/ECS/Built-In/LocalPlayerComponent.cs rename Src/{Unity/Scripts/Mod/UnityModService.cs.meta => Core/ECS/Built-In/LocalPlayerComponent.cs.meta} (83%) rename Src/{Unity/Scripts/Mono.meta => Core/Hotkey.meta} (77%) create mode 100644 Src/Core/Hotkey/BITKit.Hotkey.asmdef rename Src/{Unity/Scripts/WorldNode/BITKit.WorldNode.Runtime.asmdef.meta => Core/Hotkey/BITKit.Hotkey.asmdef.meta} (76%) create mode 100644 Src/Core/Hotkey/IHotkeyCollection.cs rename Src/{Unity/Socket/UnitySocketComponent.cs.meta => Core/Hotkey/IHotkeyCollection.cs.meta} (83%) rename Src/{Unity/Scripts => Core}/WorldNode/UnityNode.cs (93%) rename Src/{Unity/Scripts => Core}/WorldNode/UnityNode.cs.meta (100%) create mode 100644 Src/Core/WorldNode/WorldInfoNpcStartNode.cs rename Src/{Unity/Scripts/Mod/UnityModServiceTester.cs.meta => Core/WorldNode/WorldInfoNpcStartNode.cs.meta} (83%) rename Src/{ => Core}/package.json (100%) rename Src/{ => Core}/package.json.meta (100%) create mode 100644 Src/NetSupport/Net.BITKit.NetSupport.asmref rename Src/{Unity/Scripts/WorldNode.meta => NetSupport/Net.BITKit.NetSupport.asmref.meta} (56%) create mode 100644 Src/NetSupport/UnityMathematicsYamlConverters.cs create mode 100644 Src/NetSupport/UnityMathematicsYamlConverters.cs.meta create mode 100644 Src/Unity/BITKit.Unity.asmref create mode 100644 Src/Unity/BITKit.Unity.asmref.meta create mode 100644 Src/Unity/Scripts/Assets/ScriptableEntitiesService.cs create mode 100644 Src/Unity/Scripts/Assets/ScriptableEntitiesService.cs.meta create mode 100644 Src/Unity/Scripts/InputSystem/UnityPlayerInput.cs create mode 100644 Src/Unity/Scripts/InputSystem/UnityPlayerInput.cs.meta delete mode 100644 Src/Unity/Scripts/Mod/UnityModService.cs delete mode 100644 Src/Unity/Scripts/Mod/UnityModServiceTester.cs create mode 100644 Src/Unity/Scripts/Physics/GeometryUtils.cs create mode 100644 Src/Unity/Scripts/Physics/GeometryUtils.cs.meta create mode 100644 Src/Unity/Scripts/Physics/GetClosePointFromColliderDebuger.cs create mode 100644 Src/Unity/Scripts/Physics/GetClosePointFromColliderDebuger.cs.meta create mode 100644 Src/Unity/Scripts/Physics/GetClosestPointFromMesh.cs create mode 100644 Src/Unity/Scripts/Physics/GetClosestPointFromMesh.cs.meta rename Src/Unity/Scripts/{StateMachine.meta => UX/Cell.meta} (77%) create mode 100644 Src/Unity/Scripts/UX/Input/OnScreenButton.cs create mode 100644 Src/Unity/Scripts/UX/Input/OnScreenButton.cs.meta create mode 100644 Src/Unity/Scripts/UX/Input/OnScreenControl.cs create mode 100644 Src/Unity/Scripts/UX/Input/OnScreenControl.cs.meta create mode 100644 Src/Unity/Scripts/UX/Input/OnScreenGamepad.cs create mode 100644 Src/Unity/Scripts/UX/Input/OnScreenGamepad.cs.meta create mode 100644 Src/Unity/Scripts/UX/Input/OnScreenStick.cs create mode 100644 Src/Unity/Scripts/UX/Input/OnScreenStick.cs.meta create mode 100644 Src/Unity/Scripts/UX/Library/CellContainer.cs create mode 100644 Src/Unity/Scripts/UX/Library/CellContainer.cs.meta rename Src/Unity/Scripts/{Selection.meta => UX/RadialMenu.meta} (77%) create mode 100644 Src/Unity/Scripts/UX/RadialMenu/UXRadialMenu.cs create mode 100644 Src/Unity/Scripts/UX/RadialMenu/UXRadialMenu.cs.meta create mode 100644 Src/Unity/Scripts/UX/Service/UI Toolkit/UIToolkitSubPanel.cs create mode 100644 Src/Unity/Scripts/UX/Service/UI Toolkit/UIToolkitSubPanel.cs.meta delete mode 100644 Src/Unity/Scripts/WorldNode/BITKit.WorldNode.Runtime.asmdef delete mode 100644 Src/Unity/Socket.meta delete mode 100644 Src/Unity/Socket/ISocketComponent.cs delete mode 100644 Src/Unity/Socket/UnitySocketComponent.cs delete mode 100644 Src/Unity/Socket/UnitySocketService.cs delete mode 100644 Src/Unity/Socket/UnitySocketService.cs.meta delete mode 100644 Src/Unity/UX/UXsettlement.uss delete mode 100644 Src/Unity/UX/UXsettlement.uss.meta diff --git a/Src/Core/Attributes/DataAttribute.cs b/Src/Core/Attributes/DataAttribute.cs new file mode 100644 index 0000000..e69de29 diff --git a/Src/Unity/Socket/ISocketComponent.cs.meta b/Src/Core/Attributes/DataAttribute.cs.meta similarity index 83% rename from Src/Unity/Socket/ISocketComponent.cs.meta rename to Src/Core/Attributes/DataAttribute.cs.meta index fb96fe3..7345a52 100644 --- a/Src/Unity/Socket/ISocketComponent.cs.meta +++ b/Src/Core/Attributes/DataAttribute.cs.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: 6d0be10870bf27f4b8b1c97ed8809308 +guid: 66cea81a8a712d348aded0734f12d2ef MonoImporter: externalObjects: {} serializedVersion: 2 diff --git a/Src/BITKit.asmdef b/Src/Core/BITKit.asmdef similarity index 100% rename from Src/BITKit.asmdef rename to Src/Core/BITKit.asmdef diff --git a/Src/BITKit.asmdef.meta b/Src/Core/BITKit.asmdef.meta similarity index 100% rename from Src/BITKit.asmdef.meta rename to Src/Core/BITKit.asmdef.meta diff --git a/Src/Core/ECS/Built-In/IdComponent.cs b/Src/Core/ECS/Built-In/IdComponent.cs index bb70db4..a302e87 100644 --- a/Src/Core/ECS/Built-In/IdComponent.cs +++ b/Src/Core/ECS/Built-In/IdComponent.cs @@ -2,13 +2,11 @@ using System.Dynamic; namespace BITKit.Entities { - public interface IdComponent + public class IdComponent { - ulong Id { get; set; } - } - public interface IdComponent_String - { - string DbId { get; } + public int Id { get; set; } + public string Name { get; set; } + public string Group { get; set; } } } diff --git a/Src/Core/ECS/Built-In/LocalPlayerComponent.cs b/Src/Core/ECS/Built-In/LocalPlayerComponent.cs new file mode 100644 index 0000000..a517db5 --- /dev/null +++ b/Src/Core/ECS/Built-In/LocalPlayerComponent.cs @@ -0,0 +1,10 @@ +using System.Collections; +using System.Collections.Generic; + +namespace BITKit.Entities +{ + public class LocalPlayerComponent + { + + } +} diff --git a/Src/Unity/Scripts/Mod/UnityModService.cs.meta b/Src/Core/ECS/Built-In/LocalPlayerComponent.cs.meta similarity index 83% rename from Src/Unity/Scripts/Mod/UnityModService.cs.meta rename to Src/Core/ECS/Built-In/LocalPlayerComponent.cs.meta index 5d61d2a..a11c63e 100644 --- a/Src/Unity/Scripts/Mod/UnityModService.cs.meta +++ b/Src/Core/ECS/Built-In/LocalPlayerComponent.cs.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: b030d336e53d2c646a7b382eb83897bf +guid: 46172bbdf3a15d4458646b3e80b6702c MonoImporter: externalObjects: {} serializedVersion: 2 diff --git a/Src/Core/ECS/EntitiesService.cs b/Src/Core/ECS/EntitiesService.cs index 9e36ce3..59f7ce5 100644 --- a/Src/Core/ECS/EntitiesService.cs +++ b/Src/Core/ECS/EntitiesService.cs @@ -5,28 +5,42 @@ using System.Linq; using System.Runtime.CompilerServices; using System.Security.AccessControl; using System.Threading; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; namespace BITKit.Entities { - public class EntitiesService:IEntitiesService + public class EntitiesService:IEntitiesService,IDisposable { - private readonly ConcurrentDictionary _entities = new(); - private readonly ConcurrentDictionary _queryCache = new(); - private readonly ConcurrentDictionary<(Type,Type), IEntity[]> _query2ComponentsCache = new(); - private readonly ConcurrentDictionary<(Type,Type,Type), IEntity[]> _query3ComponentsCache = new(); + private readonly ILogger _logger; + + private static int _count; + public EntitiesService() + { + _count++; + } + + public EntitiesService(ILogger logger) + { + _count++; + + _logger = logger; + } + + private static readonly ConcurrentDictionary Entities = new(); public event Action OnAdd; public event Action OnRemove; - public IEntity[] Entities => _entities.Values.ToArray(); + IEntity[] IEntitiesService.Entities => Entities.Values.ToArray(); public bool Register(IEntity entity) { - if (!_entities.TryAdd(entity.Id, entity)) return false; + if (!Entities.TryAdd(entity.Id, entity)) return false; OnAdd?.Invoke(entity); return true; } public bool UnRegister(IEntity entity) { - if (!_entities.TryRemove(entity.Id, out _)) return false; + if (!Entities.TryRemove(entity.Id, out _)) return false; OnRemove?.Invoke(entity); return true; } @@ -34,17 +48,17 @@ namespace BITKit.Entities private readonly CancellationTokenSource _cancellationTokenSource = new(); public IEntity Get(int id) { - return _entities[id]; + return Entities[id]; } public bool TryGetEntity(int id, out IEntity entity) { - return _entities.TryGetValue(id, out entity); + return Entities.TryGetValue(id, out entity); } public IEntity GetOrAdd(int id, Func factory) { - return _entities.GetOrAdd(id, factory); + return Entities.GetOrAdd(id, factory); } public IEntity[] Query() @@ -54,16 +68,36 @@ namespace BITKit.Entities public T[] QueryComponents() { - throw new NotImplementedException(); + var list = new List(); + foreach (var entity in Entities.Values) + { + if (entity.ServiceProvider.GetService() is { } t1) + { + list.Add(t1); + } + } + + return list.ToArray(); // return _queryCache.GetOrAdd(typeof(T), type => // { // return _entities.Values.Where(entity => entity.TryGetComponent(out T component)).ToArray(); // }).Cast().ToArray(); } + public (T, T1)[] QueryComponents() { - throw new NotImplementedException(); - // List<(T, T1)> list = new(); + var list = new List<(T, T1)>(); + foreach (var entity in Entities.Values) + { + if (entity.ServiceProvider.GetService() is { } t1 && + entity.ServiceProvider.GetService() is { } t2) + { + list.Add((t1, t2)); + } + } + + return list.ToArray(); + // List<(T, T1)> list = new(); // foreach (var entity in _entities.Values) // { // if (entity.TryGetComponent(out T t) && entity.TryGetComponent(out T1 t1)) @@ -73,7 +107,18 @@ namespace BITKit.Entities } public (T, T1, T2)[] QueryComponents() { - throw new NotImplementedException(); + var list = new List<(T, T1, T2)>(); + foreach (var entity in Entities.Values) + { + if (entity.ServiceProvider.GetService() is { } t1 && + entity.ServiceProvider.GetService() is { } t2 && + entity.ServiceProvider.GetService() is { } t3) + { + list.Add((t1, t2, t3)); + } + } + + return list.ToArray(); // List<(T, T1, T2)> list = new(); // foreach (var entity in _entities.Values) // { @@ -85,7 +130,19 @@ namespace BITKit.Entities public (T, T1, T2, T3)[] QueryComponents() { - throw new NotImplementedException(); + var list = new List<(T, T1, T2, T3)>(); + foreach (var entity in Entities.Values) + { + if (entity.ServiceProvider.GetService() is { } t1 && + entity.ServiceProvider.GetService() is { } t2 && + entity.ServiceProvider.GetService() is { } t3 && + entity.ServiceProvider.GetService() is { } t4) + { + list.Add((t1, t2, t3, t4)); + } + } + + return list.ToArray(); // List<(T, T1, T2, T3)> list = new(); // foreach (var entity in _entities.Values) // { @@ -97,7 +154,20 @@ namespace BITKit.Entities public (T, T1, T2, T3, T4)[] QueryComponents() { - throw new NotImplementedException(); + var list = new List<(T, T1, T2, T3, T4)>(); + foreach (var entity in Entities.Values) + { + if (entity.ServiceProvider.GetService() is { } t1 && + entity.ServiceProvider.GetService() is { } t2 && + entity.ServiceProvider.GetService() is { } t3 && + entity.ServiceProvider.GetService() is { } t4 && + entity.ServiceProvider.GetService() is { } t5) + { + list.Add((t1, t2, t3, t4, t5)); + } + } + + return list.ToArray(); // List<(T, T1, T2, T3, T4)> list = new(); // foreach (var entity in _entities.Values) // { @@ -109,7 +179,21 @@ namespace BITKit.Entities public (T, T1, T2, T3, T4, T5)[] QueryComponents() { - throw new NotImplementedException(); + var list = new List<(T, T1, T2, T3, T4, T5)>(); + foreach (var entity in Entities.Values) + { + if (entity.ServiceProvider.GetService() is { } t1 && + entity.ServiceProvider.GetService() is { } t2 && + entity.ServiceProvider.GetService() is { } t3 && + entity.ServiceProvider.GetService() is { } t4 && + entity.ServiceProvider.GetService() is { } t5 && + entity.ServiceProvider.GetService() is { } t6) + { + list.Add((t1, t2, t3, t4, t5, t6)); + } + } + + return list.ToArray(); // List<(T, T1, T2, T3, T4, T5)> list = new(); // foreach (var entity in _entities.Values) // { @@ -121,7 +205,22 @@ namespace BITKit.Entities public (T, T1, T2, T3, T4, T5, T6)[] QueryComponents() { - throw new NotImplementedException(); + var list = new List<(T, T1, T2, T3, T4, T5, T6)>(); + foreach (var entity in Entities.Values) + { + if (entity.ServiceProvider.GetService() is { } t1 && + entity.ServiceProvider.GetService() is { } t2 && + entity.ServiceProvider.GetService() is { } t3 && + entity.ServiceProvider.GetService() is { } t4 && + entity.ServiceProvider.GetService() is { } t5 && + entity.ServiceProvider.GetService() is { } t6 && + entity.ServiceProvider.GetService() is { } t7) + { + list.Add((t1, t2, t3, t4, t5, t6, t7)); + } + } + + return list.ToArray(); // List<(T, T1, T2, T3, T4, T5, T6)> list = new(); // foreach (var entity in _entities.Values) // { @@ -131,10 +230,38 @@ namespace BITKit.Entities // return list.ToArray(); } - public ValueTuple[] QueryComponents() where TRest : struct + public ValueTuple[] QueryComponents() + where TRest : struct { - throw new NotImplementedException(); - // throw new NotImplementedException(); + var list = new List>(); + foreach (var entity in Entities.Values) + { + if (entity.ServiceProvider.GetService() is { } t1 && + entity.ServiceProvider.GetService() is { } t2 && + entity.ServiceProvider.GetService() is { } t3 && + entity.ServiceProvider.GetService() is { } t4 && + entity.ServiceProvider.GetService() is { } t5 && + entity.ServiceProvider.GetService() is { } t6 && + entity.ServiceProvider.GetService() is { } t7 && + entity.ServiceProvider.GetService() is { } t8) + { + list.Add(new ValueTuple(t1, t2, t3, t4, t5, t6, t7, t8)); + } + } + return list.ToArray(); + } + + public void Dispose() + { + _count--; + if (_count <= 0) + { + Entities.Clear(); + } + + _logger.LogInformation($"已释放,还剩{_count}个实例"); + + _cancellationTokenSource?.Dispose(); } } } diff --git a/Src/Core/ECS/EntityComponentSystem.cs b/Src/Core/ECS/EntityComponentSystem.cs index eb6a43c..83bf419 100644 --- a/Src/Core/ECS/EntityComponentSystem.cs +++ b/Src/Core/ECS/EntityComponentSystem.cs @@ -24,7 +24,6 @@ namespace BITKit.Entities /// public interface IEntitiesService { - /// /// 当添加Entity时 /// diff --git a/Src/Unity/Scripts/Mono.meta b/Src/Core/Hotkey.meta similarity index 77% rename from Src/Unity/Scripts/Mono.meta rename to Src/Core/Hotkey.meta index 0bf59ec..86eaec9 100644 --- a/Src/Unity/Scripts/Mono.meta +++ b/Src/Core/Hotkey.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: 2e822c111559c204ba6fc483b283d193 +guid: ad41977c90d905e4fa0efdcfd3260ccc folderAsset: yes DefaultImporter: externalObjects: {} diff --git a/Src/Core/Hotkey/BITKit.Hotkey.asmdef b/Src/Core/Hotkey/BITKit.Hotkey.asmdef new file mode 100644 index 0000000..95a1523 --- /dev/null +++ b/Src/Core/Hotkey/BITKit.Hotkey.asmdef @@ -0,0 +1,14 @@ +{ + "name": "BITKit.Hotkey", + "rootNamespace": "", + "references": [], + "includePlatforms": [], + "excludePlatforms": [], + "allowUnsafeCode": false, + "overrideReferences": false, + "precompiledReferences": [], + "autoReferenced": true, + "defineConstraints": [], + "versionDefines": [], + "noEngineReferences": true +} \ No newline at end of file diff --git a/Src/Unity/Scripts/WorldNode/BITKit.WorldNode.Runtime.asmdef.meta b/Src/Core/Hotkey/BITKit.Hotkey.asmdef.meta similarity index 76% rename from Src/Unity/Scripts/WorldNode/BITKit.WorldNode.Runtime.asmdef.meta rename to Src/Core/Hotkey/BITKit.Hotkey.asmdef.meta index 3af7b66..b1fb63d 100644 --- a/Src/Unity/Scripts/WorldNode/BITKit.WorldNode.Runtime.asmdef.meta +++ b/Src/Core/Hotkey/BITKit.Hotkey.asmdef.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: 01cf845b40a364e4cbaee058936fa4a3 +guid: 3abaaefa7af558d44ba20cea1c43d602 AssemblyDefinitionImporter: externalObjects: {} userData: diff --git a/Src/Core/Hotkey/IHotkeyCollection.cs b/Src/Core/Hotkey/IHotkeyCollection.cs new file mode 100644 index 0000000..5f1f1b0 --- /dev/null +++ b/Src/Core/Hotkey/IHotkeyCollection.cs @@ -0,0 +1,47 @@ +using System; +using System.Collections; +using System.Collections.Generic; + +namespace BITKit.UX.Hotkey +{ + public interface IHotkeyProvider + { + string Name { get; } + string Description { get; } + object Data { get; } + bool Enabled { get; } + Action OnPerform { get; } + float HoldDuration => 0; + } + public struct HotkeyProvider : IHotkeyProvider + { + public string Name { get; set; } + public string Description { get; set; } + public object Data { get; set; } + public bool Enabled { get; set; } + public Action OnPerform { get; set; } + + public float HoldDuration { get; set; } + } + public interface IHotkeyCollection + { + IEnumerable Hotkeys { get; } + void Register(IHotkeyProvider hotkey); + void UnRegister(IHotkeyProvider hotkey); + } + + public class HotkeyCollection:IHotkeyCollection + { + private readonly HashSet _hotkeys = new(); + public IEnumerable Hotkeys => _hotkeys; + public void Register(IHotkeyProvider hotkey) + { + _hotkeys.Add(hotkey); + } + + public void UnRegister(IHotkeyProvider hotkey) + { + _hotkeys.Remove(hotkey); + } + } +} diff --git a/Src/Unity/Socket/UnitySocketComponent.cs.meta b/Src/Core/Hotkey/IHotkeyCollection.cs.meta similarity index 83% rename from Src/Unity/Socket/UnitySocketComponent.cs.meta rename to Src/Core/Hotkey/IHotkeyCollection.cs.meta index bb8c103..a362151 100644 --- a/Src/Unity/Socket/UnitySocketComponent.cs.meta +++ b/Src/Core/Hotkey/IHotkeyCollection.cs.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: 7ba6497a10fb8e14dab1acb39b2ec8aa +guid: 0ad36bc56dd5406418bf8ea67f4bc010 MonoImporter: externalObjects: {} serializedVersion: 2 diff --git a/Src/Core/Item/Item.cs b/Src/Core/Item/Item.cs index 97c2ba2..68fb998 100644 --- a/Src/Core/Item/Item.cs +++ b/Src/Core/Item/Item.cs @@ -53,7 +53,13 @@ namespace BITKit public interface IScriptableItemProperty { } - + /// + /// 控制器(分)类 + /// + public interface IScriptableControllerClass + { + + } /// /// 基础物品 /// @@ -88,6 +94,11 @@ namespace BITKit /// 属性 /// IReadOnlyDictionary Properties { get; } + + /// + /// 控制器类 + /// + IScriptableControllerClass ControllerClass { get; } /// /// 价值 diff --git a/Src/Core/Mod/ModService.cs b/Src/Core/Mod/ModService.cs index e700e1e..144bbba 100644 --- a/Src/Core/Mod/ModService.cs +++ b/Src/Core/Mod/ModService.cs @@ -14,6 +14,7 @@ using BITKit.IO; using BITKit.UX; using Cysharp.Threading.Tasks; using Microsoft.CSharp; +using Microsoft.Extensions.Logging; using Newtonsoft.Json; namespace BITKit.Mod @@ -133,17 +134,26 @@ namespace BITKit.Mod var list=new List(); var path = Path.Combine(Environment.CurrentDirectory, "Mods"); - var dir = new DirectoryInfo(path); - dir.Create(); - foreach (var x in dir.GetDirectories()) + + try { - var file = Path.Combine(x.FullName,ModPackage.DefaultFileName); - if(File.Exists(file) is false)continue; - var package = JsonConvert.DeserializeObject(await File.ReadAllTextAsync(file))!; - package.PackagePath = file; - package.WorkDirectory = x.FullName; - list.Add(package); + var dir = new DirectoryInfo(path); + dir.Create(); + foreach (var x in dir.GetDirectories()) + { + var file = Path.Combine(x.FullName,ModPackage.DefaultFileName); + if(File.Exists(file) is false)continue; + var package = JsonConvert.DeserializeObject(await File.ReadAllTextAsync(file))!; + package.PackagePath = file; + package.WorkDirectory = x.FullName; + list.Add(package); + } } + catch (Exception e) + { + BIT4Log.LogException(e); + } + return list.ToArray(); } @@ -200,19 +210,16 @@ namespace BITKit.Mod private static CancellationTokenSource _CancellationTokenSource; private static readonly ConcurrentDictionary _InstalledMods=new(); - public static async UniTask Initialize() + public static async UniTask Initialize(ILogger logger=null) { - BIT4Log.Log("Mod服务已启动"); + logger?.LogInformation("Mod服务已启动"); _CancellationTokenSource = new CancellationTokenSource(); try { - - - try { - var modPath = Path.Combine(Environment.CurrentDirectory, "Mods\\"); + var modPath = Path.Combine(Environment.CurrentDirectory, @"Mods\"); PathHelper.EnsureDirectoryCreated(modPath); var directoryInfo = new DirectoryInfo(modPath); foreach (var fileInfo in directoryInfo.GetFiles()) @@ -238,18 +245,16 @@ namespace BITKit.Mod } catch (Exception e) { - BIT4Log.Warning("自动加载Mod失败"); + logger?.LogWarning("自动加载Mod失败"); BIT4Log.LogException(e); } } catch (Exception e) { + logger?.LogWarning("Mod服务遇到了错误,已停止"); BIT4Log.LogException(e); - BIT4Log.Warning("Mod服务遇到了错误,已停止"); } - - } public static void Dispose() @@ -336,7 +341,7 @@ namespace BITKit.Mod } - var fileInfo = new FileInfo(path); + var fileInfo = new FileInfo(path); switch (fileInfo.Extension) { case ".dll": @@ -360,6 +365,10 @@ namespace BITKit.Mod } public static async UniTask Load(IMod mod) { + await IsBusy; + + using var _ = IsBusy.GetHandle(); + mod.OnInitialize(); OnModLoad?.Invoke(mod); BIT4Log.Log($"加载Mod:{mod.GetType().FullName}"); @@ -381,7 +390,7 @@ namespace BITKit.Mod BIT4Log.Log($"卸载Mod:{mod.GetType().FullName}"); } - public static async void Install(IMod mod) + public static async UniTask Install(IMod mod) { await IsBusy; @@ -404,11 +413,12 @@ namespace BITKit.Mod mod.OnInitialized(); OnModLoaded?.Invoke(mod); } - public static void UnInstall(IMod mod) + public static async UniTask UnInstall(IMod mod) { + await IsBusy; + using var _ = IsBusy.GetHandle(); - if(_InstalledMods.ContainsKey(mod.PackageName) is false) return; _InstalledMods.TryRemove(mod.PackageName); Mods = _InstalledMods.Values.ToArray(); diff --git a/Src/Core/Mod/ModService_IO.cs b/Src/Core/Mod/ModService_IO.cs index 7057577..c3b81cb 100644 --- a/Src/Core/Mod/ModService_IO.cs +++ b/Src/Core/Mod/ModService_IO.cs @@ -8,7 +8,20 @@ namespace BITKit.Mod public partial class ModService { public static Func> LoadAssetAsyncFactory; + public static Func>> LoadAssetsAsyncFactory; + public static async UniTask> LoadAssets(params string[] tags) + { + var list = new List(); + foreach (var func in LoadAssetsAsyncFactory.CastAsFunc()) + { + foreach (var obj in await func.Invoke(tags)) + { + list.Add((T)obj); + } + } + return list; + } public static async UniTask LoadAsset(string location) where T : class { if (LoadAssetAsyncFactory is null) diff --git a/Src/Core/Net/NetProvider.cs b/Src/Core/Net/NetProvider.cs index 6048ab6..53d664b 100644 --- a/Src/Core/Net/NetProvider.cs +++ b/Src/Core/Net/NetProvider.cs @@ -272,6 +272,14 @@ namespace BITKit using var ms = new MemoryStream(); using var writer = new BinaryWriter(ms); + foreach (var parameterInfo in methodInfo.GetParameters()) + { + if (parameterInfo.IsOut) + { + codeBuilder.AppendLine($"{parameterInfo.Name} = default;"); + } + } + codeBuilder.AppendLine(" using var ms = new MemoryStream();"); codeBuilder.AppendLine(" using var writer = new BinaryWriter(ms);"); codeBuilder.AppendLine(" writer.Write((byte)NetCommandType.Rpc);"); @@ -466,6 +474,7 @@ namespace BITKit { options= options.AddReferences(referencedAssembly); } + options = options.AddReferences(typeof(BITApp).Assembly); var assembly = BITSharp.Compile(code, options); diff --git a/Src/Core/Sharp/BITSharp.cs b/Src/Core/Sharp/BITSharp.cs index ff1df51..46cef9f 100644 --- a/Src/Core/Sharp/BITSharp.cs +++ b/Src/Core/Sharp/BITSharp.cs @@ -110,6 +110,11 @@ namespace BITKit { codeBuilder.AppendLine(GenerateMethod(method)); } + + foreach (var eventInfo in type.GetEvents()) + { + codeBuilder.AppendLine(GenerateEvent(eventInfo)); + } codeBuilder.AppendLine(AfterGenerate(type)); @@ -136,25 +141,32 @@ namespace BITKit public virtual string GenerateMethod(MethodInfo methodInfo) { var codeBuilder = new StringBuilder(); - HashSet propertyMethods = new(); + HashSet ignoreMethods = new(); + + foreach (var eventInfo in methodInfo.DeclaringType!.GetEvents()) + { + ignoreMethods.Add(eventInfo.AddMethod); + ignoreMethods.Add(eventInfo.RemoveMethod); + } foreach (var propertyInfo in methodInfo.DeclaringType!.GetProperties()) { if (propertyInfo.GetMethod is not null) { - propertyMethods.Add(propertyInfo.GetMethod); + ignoreMethods.Add(propertyInfo.GetMethod); } if (propertyInfo.SetMethod is not null) { - propertyMethods.Add(propertyInfo.SetMethod); + ignoreMethods.Add(propertyInfo.SetMethod); } } - if(propertyMethods.Contains(methodInfo))return string.Empty; + + if(ignoreMethods.Contains(methodInfo))return string.Empty; string methodName = methodInfo.Name; string parameters = string.Join(", ", methodInfo.GetParameters() - .Select(p => $"{CSharpName(p.ParameterType)} {p.Name}")); + .Select(p => $"{(p.IsOut?"out":string.Empty)} {CSharpName(p.IsOut?p.ParameterType.GetElementType():p.ParameterType)} {p.Name}")); var isAwaitable = methodInfo.ReturnType.GetMethod(nameof(Task.GetAwaiter)) != null; @@ -194,7 +206,17 @@ namespace BITKit public virtual string GenerateMethodContext(MethodInfo methodInfo) { - return methodInfo.ReturnType == typeof(void) ? string.Empty : $"return default;"; + var codeBuilder = new StringBuilder(); + foreach (var parameterInfo in methodInfo.GetParameters()) + { + if (parameterInfo.IsOut) + { + codeBuilder.AppendLine($"{parameterInfo.Name} = default;"); + } + } + + codeBuilder.AppendLine(methodInfo.ReturnType == typeof(void) ? string.Empty : $"return default;"); + return codeBuilder.ToString(); } public virtual string GenerateField(FieldInfo fieldInfo) @@ -209,7 +231,7 @@ namespace BITKit public virtual string GenerateEvent(EventInfo eventInfo) { - throw new NotImplementedException(); + return $"public event {CSharpName(eventInfo.EventHandlerType)} {eventInfo.Name};"; } } #if UNITY_5_3_OR_NEWER @@ -257,7 +279,6 @@ namespace BITKit { result.Add(fieldInfo.FieldType.Assembly); } - foreach (var propertyInfo in type.GetProperties()) { result.Add(propertyInfo.PropertyType.Assembly); @@ -269,6 +290,10 @@ namespace BITKit { result.Add(argument.Assembly); } + foreach (var parameterInfo in methodInfo.GetParameters()) + { + result.Add(parameterInfo.ParameterType.Assembly); + } } return result; } @@ -295,7 +320,24 @@ namespace BITKit using var ms = new MemoryStream(); var result = script.GetCompilation().Emit(ms); - if (!result.Success) throw new Exception(string.Join("\n",result.Diagnostics)); + if (!result.Success) + { + var report = new StringBuilder(); + report.AppendLine(code); + + foreach (var reference in script.GetCompilation().References) + { + report.AppendLine("Assembly referenced:" + reference.Display); + } + + foreach (var diagnostic in result.Diagnostics) + { + report.AppendLine(diagnostic.ToString()); + } + + + throw new Exception(report.ToString()); + } ms.Seek(0, SeekOrigin.Begin); var assembly = Assembly.Load(ms.ToArray()); // 加载程序集 diff --git a/Src/Core/StateMachine/AsyncStateMachine.cs b/Src/Core/StateMachine/AsyncStateMachine.cs index b581c0b..69c3bba 100644 --- a/Src/Core/StateMachine/AsyncStateMachine.cs +++ b/Src/Core/StateMachine/AsyncStateMachine.cs @@ -25,8 +25,8 @@ namespace BITKit.StateMachine public bool Enabled { get; set; } = true; public T CurrentState { get;private set; } public T NextOrCurrentState => _nextTargetState.IfNotAllow(CurrentState); - private T _nextState; public event Action OnStateChanging; + public event Func OnStateChangeAsync; public event Action OnStateChanged; public event Action OnStateRegistered; public IReadOnlyDictionary Dictionary => _dictionary; @@ -53,21 +53,18 @@ namespace BITKit.StateMachine { if (CurrentState is null) return; using var _ = IsBusy.GetHandle(); - await CurrentState.OnStateUpdateAsync(deltaTime); CurrentState.OnStateUpdate(deltaTime); + await CurrentState.OnStateUpdateAsync(deltaTime); } public async void DisposeState() { await IsBusy; - if(_cancellationTokenSource.IsCancellationRequested)return; + if (_cancellationTokenSource.IsCancellationRequested) return; if (CurrentState is null) return; using var _ = IsBusy.GetHandle(); - if (CurrentState is not null) - { - CurrentState.Enabled = false; - } + CurrentState.Enabled = false; await CurrentState.OnStateExitAsync(CurrentState, null); CurrentState.OnStateExit(CurrentState, null); CurrentState = null; @@ -108,10 +105,15 @@ namespace BITKit.StateMachine } _nextTargetState.SetValueThenAllow(nextState); await IsBusy; + + if(CurrentState==nextState)return; if(_cancellationTokenSource.IsCancellationRequested)return; using var _ = IsBusy.GetHandle(); + OnStateChanging?.Invoke(CurrentState,nextState); - if (_dictionary.TryAdd(nextState.Identifier, nextState)) + await OnStateChangeAsync.UniTaskFunc(CurrentState,nextState); + + if (nextState is not null && _dictionary.TryAdd(nextState.Identifier, nextState)) { await nextState.InitializeAsync(); if(_cancellationTokenSource.IsCancellationRequested)return; @@ -125,6 +127,11 @@ namespace BITKit.StateMachine CurrentState.OnStateExit(CurrentState,nextState); } + if (_nextTargetState.Allow && _nextTargetState.Value != nextState) + { + return; + } + var tempState = CurrentState; CurrentState = _nextTargetState.Value; _nextTargetState.Clear(); diff --git a/Src/Core/StateMachine/IStateMachine.cs b/Src/Core/StateMachine/IStateMachine.cs index d18a074..f91684d 100644 --- a/Src/Core/StateMachine/IStateMachine.cs +++ b/Src/Core/StateMachine/IStateMachine.cs @@ -1,4 +1,5 @@ using System; +using System.Collections.Concurrent; using System.Collections.Generic; using Cysharp.Threading.Tasks; @@ -44,11 +45,16 @@ namespace BITKit.StateMachine UniTask OnStateExitAsync(IState old, IState newState); } - public interface IStateMachine where T:IState + public interface IMicroStateMachine + { + T CurrentState { get; } + event Action OnStateChanged; + T TransitionState() where TState : T; + T TransitionState(T state); + } + public interface IStateMachine:IMicroStateMachine where T:IState { bool Enabled { get; set; } - T CurrentState { get; } - event Action OnStateChanged; event Action OnStateRegistered; event Action OnStateUnRegistered; @@ -56,13 +62,72 @@ namespace BITKit.StateMachine void Initialize(); void UpdateState(float deltaTime); void DisposeState(); - T TransitionState() 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 class MicroStateMachine : IMicroStateMachine + { + public T CurrentState { get; private set; } + public event Action OnStateChanged; + private readonly ConcurrentDictionary _stateDictionary=new(); + public T TransitionState() where TState : T + { + var state = _stateDictionary.GetOrAdd(typeof(TState), Activator.CreateInstance()); + return TransitionState(state); + } + + public T TransitionState(T state) + { + _stateDictionary.TryAdd(state.GetType(), state); + + if (Equals(state, CurrentState)) return default; + + var currentState = CurrentState; + CurrentState = state; + OnStateChanged?.Invoke(currentState, state); + return state; + } + } + public abstract class StateAsync:IStateAsync + { + public virtual bool Enabled { get; set; } + public virtual void Initialize() + { + } + + public virtual void OnStateEntry(IState old) + { + } + + public virtual void OnStateUpdate(float deltaTime) + { + } + + public virtual void OnStateExit(IState old, IState newState) + { + } + + public virtual int Identifier { get; set; } + public virtual UniTask InitializeAsync() + { + return UniTask.CompletedTask; + } + + public virtual UniTask OnStateEntryAsync(IState old) + { return UniTask.CompletedTask; + } + + public virtual UniTask OnStateUpdateAsync(float deltaTime) + { return UniTask.CompletedTask; + } + + public virtual UniTask OnStateExitAsync(IState old, IState newState) + { return UniTask.CompletedTask; + } + } public static class StateMachineUtils { public static void Register(this IStateMachine stateMachine, T newState) where T : IState diff --git a/Src/Core/UX/IUXPanel.cs b/Src/Core/UX/IUXPanel.cs index b642882..07eec72 100644 --- a/Src/Core/UX/IUXPanel.cs +++ b/Src/Core/UX/IUXPanel.cs @@ -30,6 +30,7 @@ namespace BITKit.UX /// 该面板是否启用玩家输入 /// bool AllowInput { get; } + object Root { get; } /// /// 事件回调,当面板被打开时触发 /// @@ -43,6 +44,8 @@ namespace BITKit.UX event Func OnExitAsync; event Action OnExitCompleted; + public event Action OnInitiated; + public event Func OnInitiatedAsync; void OnTick(float deltaTime); } } diff --git a/Src/Core/UX/IUXService.cs b/Src/Core/UX/IUXService.cs index b2c4724..eecdffa 100644 --- a/Src/Core/UX/IUXService.cs +++ b/Src/Core/UX/IUXService.cs @@ -1,5 +1,6 @@ using System; using Cysharp.Threading.Tasks; +using Unity.Mathematics; namespace BITKit.UX { @@ -52,6 +53,13 @@ namespace BITKit.UX /// 面板改变回调 /// public event Action OnPanelChanged; + /// + /// 获取可交互的元素 + /// + /// + /// + /// + public bool TryPick(float2 position, out object obj); } } diff --git a/Src/Core/WorldNode/IWorldNodeService.cs b/Src/Core/WorldNode/IWorldNodeService.cs index 7807301..6781446 100644 --- a/Src/Core/WorldNode/IWorldNodeService.cs +++ b/Src/Core/WorldNode/IWorldNodeService.cs @@ -10,7 +10,7 @@ namespace BITKit.WorldNode /// public interface IWorldNodeService { - public IReadOnlyDictionary WorldNodes { get; } + public IReadOnlyDictionary> WorldNodes { get; } public void RegisterNode(IWorldNode node); public event Action OnNodeRegistered; } @@ -21,12 +21,12 @@ namespace BITKit.WorldNode public class WorldNodeService : IWorldNodeService,IDisposable { public static event Action OnNodeRegistered; - IReadOnlyDictionary IWorldNodeService.WorldNodes => WorldNodes; - private static readonly ConcurrentDictionary WorldNodes = new(); + IReadOnlyDictionary> IWorldNodeService.WorldNodes => WorldNodes; + private static readonly ConcurrentDictionary> WorldNodes = new(); public void RegisterNode(IWorldNode node) { OnNodeRegistered?.Invoke(node); - WorldNodes.TryAdd(node.Id, node); + WorldNodes.GetOrCreate(node.Id).Add(node); } event Action IWorldNodeService.OnNodeRegistered { diff --git a/Src/Unity/Scripts/WorldNode/UnityNode.cs b/Src/Core/WorldNode/UnityNode.cs similarity index 93% rename from Src/Unity/Scripts/WorldNode/UnityNode.cs rename to Src/Core/WorldNode/UnityNode.cs index 71d2eaf..76a5c63 100644 --- a/Src/Unity/Scripts/WorldNode/UnityNode.cs +++ b/Src/Core/WorldNode/UnityNode.cs @@ -1,3 +1,4 @@ +#if UNITY_5_3_OR_NEWER using System; using System.Collections; using System.Collections.Generic; @@ -12,6 +13,8 @@ namespace BITKit.WorldNode [SerializeReference, SubclassSelector] private IWorldNode worldNode; public int Id { get; set; } + public IWorldNode WorldNode => worldNode; + public object WorldObject { get => gameObject; @@ -27,10 +30,10 @@ namespace BITKit.WorldNode Id = gameObject.GetInstanceID(); worldNode.Id = Id; worldNode.WorldObject = gameObject; - worldNodeService.RegisterNode(worldNode); worldNode.Initialize(); + worldNodeService.RegisterNode(worldNode); Destroy(this); } } } - +#endif diff --git a/Src/Unity/Scripts/WorldNode/UnityNode.cs.meta b/Src/Core/WorldNode/UnityNode.cs.meta similarity index 100% rename from Src/Unity/Scripts/WorldNode/UnityNode.cs.meta rename to Src/Core/WorldNode/UnityNode.cs.meta diff --git a/Src/Core/WorldNode/WorldInfoNodeService.cs b/Src/Core/WorldNode/WorldInfoNodeService.cs index 94d99e4..15c5582 100644 --- a/Src/Core/WorldNode/WorldInfoNodeService.cs +++ b/Src/Core/WorldNode/WorldInfoNodeService.cs @@ -20,17 +20,24 @@ namespace BITKit.WorldNode [SerializeReference,SubclassSelector] #endif private IReference description; +#if UNITY_5_3_OR_NEWER + public void Initialize() + { + Name = name?.Value; + Description = description?.Value; + } +#endif public int Id { get; set; } public object WorldObject { get; set; } - public string Name => name?.Value; - public string Description => description?.Value; + public string Name { get; set; } + public string Description { get; set; } } public sealed class WorldInfoNodeService : IDisposable { - public IReadOnlyDictionary WorldInfoNodes => _infoNodes; + public IReadOnlyDictionary WorldInfoNodes => InfoNodes; private readonly IWorldNodeService _worldNodeService; - private readonly ConcurrentDictionary _infoNodes = new(); + private static readonly ConcurrentDictionary InfoNodes = new(); public WorldInfoNodeService(IWorldNodeService worldNodeService) { @@ -42,12 +49,12 @@ namespace BITKit.WorldNode private void OnNodeRegistered(IWorldNode obj) { if (obj is not WorldInfoNode infoNode) return; - _infoNodes.TryAdd(obj.Id, infoNode); + InfoNodes.TryAdd(obj.Id, infoNode); } public void Dispose() { - _infoNodes.Clear(); + InfoNodes.Clear(); } } } diff --git a/Src/Core/WorldNode/WorldInfoNpcStartNode.cs b/Src/Core/WorldNode/WorldInfoNpcStartNode.cs new file mode 100644 index 0000000..fe1ba4f --- /dev/null +++ b/Src/Core/WorldNode/WorldInfoNpcStartNode.cs @@ -0,0 +1,17 @@ +using System; +using System.Collections; +using System.Collections.Generic; + +namespace BITKit.WorldNode +{ + [Serializable] + public struct WorldInfoNpcStartNode:IWorldNode + { + public string Address; + public int Id { get; set; } + public object WorldObject { get; set; } + public void Initialize() + { + } + } +} \ No newline at end of file diff --git a/Src/Unity/Scripts/Mod/UnityModServiceTester.cs.meta b/Src/Core/WorldNode/WorldInfoNpcStartNode.cs.meta similarity index 83% rename from Src/Unity/Scripts/Mod/UnityModServiceTester.cs.meta rename to Src/Core/WorldNode/WorldInfoNpcStartNode.cs.meta index f0589b8..9617805 100644 --- a/Src/Unity/Scripts/Mod/UnityModServiceTester.cs.meta +++ b/Src/Core/WorldNode/WorldInfoNpcStartNode.cs.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: c9d7136f598a780459b866ee63545a5f +guid: f2fba06a66e155a4580df30630f030fc MonoImporter: externalObjects: {} serializedVersion: 2 diff --git a/Src/Core/Wrapper/IWrapper.cs b/Src/Core/Wrapper/IWrapper.cs index abab98c..e782676 100644 --- a/Src/Core/Wrapper/IWrapper.cs +++ b/Src/Core/Wrapper/IWrapper.cs @@ -14,6 +14,22 @@ namespace BITKit } public class ValueWrapper : IWrapper { + public ValueWrapper() + { + var type = typeof(T); + if (type == typeof(string)) + { + _value = string.Empty.As(); + return; + } + if(type.IsAbstract || type.IsInterface)return; + // 检查类型是否具有公共无参数构造函数 + var constructor = type.GetConstructor(BindingFlags.Public | BindingFlags.Instance, null, Type.EmptyTypes, null); + if (constructor is not null) + { + _value = Activator.CreateInstance(); + } + } public Action OnValueChanged { get; set; } public T Value @@ -27,7 +43,7 @@ namespace BITKit } } - private T _value = typeof(T) == typeof(string) ? string.Empty.As() : Activator.CreateInstance(); + private T _value; public object Obj { get => Value; diff --git a/Src/package.json b/Src/Core/package.json similarity index 100% rename from Src/package.json rename to Src/Core/package.json diff --git a/Src/package.json.meta b/Src/Core/package.json.meta similarity index 100% rename from Src/package.json.meta rename to Src/Core/package.json.meta diff --git a/Src/NetSupport/MathematicsSupport.cs b/Src/NetSupport/MathematicsSupport.cs index b311f53..22dfd33 100644 --- a/Src/NetSupport/MathematicsSupport.cs +++ b/Src/NetSupport/MathematicsSupport.cs @@ -1,6 +1,8 @@ using System; using Newtonsoft.Json; using Unity.Mathematics; +using YamlDotNet.Core; +using YamlDotNet.Serialization; #if NET5_0_OR_GREATER namespace BITKit @@ -190,4 +192,4 @@ namespace BITKit } } } -#endif \ No newline at end of file +#endif diff --git a/Src/NetSupport/Net.BITKit.NetSupport.asmref b/Src/NetSupport/Net.BITKit.NetSupport.asmref new file mode 100644 index 0000000..eea02c3 --- /dev/null +++ b/Src/NetSupport/Net.BITKit.NetSupport.asmref @@ -0,0 +1,3 @@ +{ + "reference": "GUID:14fe60d984bf9f84eac55c6ea033a8f4" +} \ No newline at end of file diff --git a/Src/Unity/Scripts/WorldNode.meta b/Src/NetSupport/Net.BITKit.NetSupport.asmref.meta similarity index 56% rename from Src/Unity/Scripts/WorldNode.meta rename to Src/NetSupport/Net.BITKit.NetSupport.asmref.meta index 663a2bc..ff4100a 100644 --- a/Src/Unity/Scripts/WorldNode.meta +++ b/Src/NetSupport/Net.BITKit.NetSupport.asmref.meta @@ -1,7 +1,6 @@ fileFormatVersion: 2 -guid: 2da90b0890b24e644a1900960dc2fb9c -folderAsset: yes -DefaultImporter: +guid: 28ed10548f6aa6944ab6ac01ce4f9faf +AssemblyDefinitionReferenceImporter: externalObjects: {} userData: assetBundleName: diff --git a/Src/NetSupport/UnityMathematicsYamlConverters.cs b/Src/NetSupport/UnityMathematicsYamlConverters.cs new file mode 100644 index 0000000..908e1ef --- /dev/null +++ b/Src/NetSupport/UnityMathematicsYamlConverters.cs @@ -0,0 +1,109 @@ +using System; +using YamlDotNet.Core; +using YamlDotNet.Core.Events; +using YamlDotNet.Serialization; +using Unity.Mathematics; + +namespace BITKit +{ + public class UnityMathematicsYamlConverters : IYamlTypeConverter +{ + public bool Accepts(Type type) + { + return type == typeof(int2) || type == typeof(int3) || type == typeof(int4) || + type == typeof(float2) || type == typeof(float3) || type == typeof(float4) || + type == typeof(quaternion); + } + + public object ReadYaml(IParser parser, Type type, ObjectDeserializer rootDeserializer) + { + var scalar = parser.Consume(); + var parts = scalar.Value.Split(','); + + if (type == typeof(int2)) + { + if (parts.Length != 2) throw new YamlException(scalar.Start, scalar.End, "Expected 2 int values for int2."); + return new int2(int.Parse(parts[0]), int.Parse(parts[1])); + } + else if (type == typeof(int3)) + { + if (parts.Length != 3) throw new YamlException(scalar.Start, scalar.End, "Expected 3 int values for int3."); + return new int3(int.Parse(parts[0]), int.Parse(parts[1]), int.Parse(parts[2])); + } + else if (type == typeof(int4)) + { + if (parts.Length != 4) throw new YamlException(scalar.Start, scalar.End, "Expected 4 int values for int4."); + return new int4(int.Parse(parts[0]), int.Parse(parts[1]), int.Parse(parts[2]), int.Parse(parts[3])); + } + else if (type == typeof(float2)) + { + if (parts.Length != 2) throw new YamlException(scalar.Start, scalar.End, "Expected 2 float values for float2."); + return new float2(float.Parse(parts[0]), float.Parse(parts[1])); + } + else if (type == typeof(float3)) + { + if (parts.Length != 3) throw new YamlException(scalar.Start, scalar.End, "Expected 3 float values for float3."); + return new float3(float.Parse(parts[0]), float.Parse(parts[1]), float.Parse(parts[2])); + } + else if (type == typeof(float4)) + { + if (parts.Length != 4) throw new YamlException(scalar.Start, scalar.End, "Expected 4 float values for float4."); + return new float4(float.Parse(parts[0]), float.Parse(parts[1]), float.Parse(parts[2]), float.Parse(parts[3])); + } + else if (type == typeof(quaternion)) + { + if (parts.Length != 4) throw new YamlException(scalar.Start, scalar.End, "Expected 4 float values for quaternion."); + return new quaternion(float.Parse(parts[0]), float.Parse(parts[1]), float.Parse(parts[2]), float.Parse(parts[3])); + } + + throw new YamlException(scalar.Start, scalar.End, $"Unsupported type: {type}"); + } + + public void WriteYaml(IEmitter emitter, object value, Type type, ObjectSerializer serializer) + { + string scalarValue = ""; + + if (type == typeof(int2)) + { + var int2Value = (int2)value; + scalarValue = $"{int2Value.x},{int2Value.y}"; + } + else if (type == typeof(int3)) + { + var int3Value = (int3)value; + scalarValue = $"{int3Value.x},{int3Value.y},{int3Value.z}"; + } + else if (type == typeof(int4)) + { + var int4Value = (int4)value; + scalarValue = $"{int4Value.x},{int4Value.y},{int4Value.z},{int4Value.w}"; + } + else if (type == typeof(float2)) + { + var float2Value = (float2)value; + scalarValue = $"{float2Value.x},{float2Value.y}"; + } + else if (type == typeof(float3)) + { + var float3Value = (float3)value; + scalarValue = $"{float3Value.x},{float3Value.y},{float3Value.z}"; + } + else if (type == typeof(float4)) + { + var float4Value = (float4)value; + scalarValue = $"{float4Value.x},{float4Value.y},{float4Value.z},{float4Value.w}"; + } + else if (type == typeof(quaternion)) + { + var quaternionValue = (quaternion)value; + scalarValue = $"{quaternionValue.value.x},{quaternionValue.value.y},{quaternionValue.value.z},{quaternionValue.value.w}"; + } + else + { + throw new YamlException($"Unsupported type: {type}"); + } + + emitter.Emit(new Scalar(scalarValue)); + } +} +} diff --git a/Src/NetSupport/UnityMathematicsYamlConverters.cs.meta b/Src/NetSupport/UnityMathematicsYamlConverters.cs.meta new file mode 100644 index 0000000..01f2c99 --- /dev/null +++ b/Src/NetSupport/UnityMathematicsYamlConverters.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 16ca25bd5fef10847aec8081266207e1 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Src/Unity/BITKit.Unity.asmref b/Src/Unity/BITKit.Unity.asmref new file mode 100644 index 0000000..eea02c3 --- /dev/null +++ b/Src/Unity/BITKit.Unity.asmref @@ -0,0 +1,3 @@ +{ + "reference": "GUID:14fe60d984bf9f84eac55c6ea033a8f4" +} \ No newline at end of file diff --git a/Src/Unity/BITKit.Unity.asmref.meta b/Src/Unity/BITKit.Unity.asmref.meta new file mode 100644 index 0000000..3eaaf8d --- /dev/null +++ b/Src/Unity/BITKit.Unity.asmref.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: d31ceb431a775db4a8757a1208d82106 +AssemblyDefinitionReferenceImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Src/Unity/Configs/Input/BITController.inputactions b/Src/Unity/Configs/Input/BITController.inputactions index 8d81621..bc87ffd 100644 --- a/Src/Unity/Configs/Input/BITController.inputactions +++ b/Src/Unity/Configs/Input/BITController.inputactions @@ -36,7 +36,7 @@ "name": "Crouch", "type": "Button", "id": "eab8ff36-98a9-4a2d-8393-167d9347227b", - "expectedControlType": "Button", + "expectedControlType": "", "processors": "", "interactions": "Press,Tap", "initialStateCheck": false @@ -45,7 +45,7 @@ "name": "Crawl", "type": "Button", "id": "350ae177-bf96-40b1-aff0-e10865947df9", - "expectedControlType": "Button", + "expectedControlType": "", "processors": "", "interactions": "", "initialStateCheck": false @@ -54,7 +54,7 @@ "name": "HoldCrouch", "type": "Button", "id": "07dfe885-d709-4482-9686-57f671b1aed6", - "expectedControlType": "Button", + "expectedControlType": "", "processors": "", "interactions": "Press", "initialStateCheck": false @@ -63,7 +63,7 @@ "name": "Fire", "type": "Button", "id": "9db494c5-bec3-4b09-bd5f-66ba07a3a729", - "expectedControlType": "Button", + "expectedControlType": "", "processors": "", "interactions": "Press,Tap,Hold", "initialStateCheck": false @@ -81,7 +81,7 @@ "name": "Interactive", "type": "Button", "id": "9b32c7f1-0553-4735-b0f9-7726d59808ca", - "expectedControlType": "Button", + "expectedControlType": "", "processors": "", "interactions": "Press,Hold", "initialStateCheck": false @@ -90,7 +90,7 @@ "name": "Melee", "type": "Button", "id": "0afd994b-f97e-4198-8700-5f570d3b7b56", - "expectedControlType": "Button", + "expectedControlType": "", "processors": "", "interactions": "", "initialStateCheck": false @@ -99,7 +99,7 @@ "name": "Run", "type": "Button", "id": "95bba0fe-8e29-470a-a7ef-126b21ea4b5c", - "expectedControlType": "Button", + "expectedControlType": "", "processors": "", "interactions": "Press,MultiTap", "initialStateCheck": false @@ -108,7 +108,7 @@ "name": "Reload", "type": "Button", "id": "53f6beb0-aeec-43f0-aa36-f4d54f068d75", - "expectedControlType": "Button", + "expectedControlType": "", "processors": "", "interactions": "", "initialStateCheck": false @@ -234,7 +234,7 @@ "name": "ToggleCamera", "type": "Button", "id": "a207eefa-8338-4ae0-95a1-8f650a3db235", - "expectedControlType": "Button", + "expectedControlType": "", "processors": "", "interactions": "Press", "initialStateCheck": false @@ -272,6 +272,17 @@ "isComposite": false, "isPartOfComposite": false }, + { + "name": "", + "id": "bcc014bd-8bca-4b71-96b9-62fa63db2d17", + "path": "/delta", + "interactions": "", + "processors": "", + "groups": "", + "action": "View", + "isComposite": false, + "isPartOfComposite": false + }, { "name": "", "id": "3204e30b-6062-47f0-9af6-e72db104c7ec", @@ -283,6 +294,17 @@ "isComposite": false, "isPartOfComposite": false }, + { + "name": "", + "id": "88f9f36f-9b75-44a7-9176-b07a7daee4ab", + "path": "/buttonSouth", + "interactions": "", + "processors": "", + "groups": "", + "action": "Jump", + "isComposite": false, + "isPartOfComposite": false + }, { "name": "", "id": "c6f71c75-cb44-418b-9dc0-4202757d20ad", @@ -294,6 +316,17 @@ "isComposite": false, "isPartOfComposite": false }, + { + "name": "", + "id": "2560f543-52ea-48c4-a2f6-df8b9deef518", + "path": "/buttonEast", + "interactions": "", + "processors": "", + "groups": "", + "action": "Crouch", + "isComposite": false, + "isPartOfComposite": false + }, { "name": "", "id": "ad8529d0-2894-4cb2-aea4-f07f96251032", @@ -316,6 +349,17 @@ "isComposite": false, "isPartOfComposite": false }, + { + "name": "", + "id": "d158c65a-e04f-4a62-a576-d13796c3d903", + "path": "/rightTrigger", + "interactions": "", + "processors": "", + "groups": "", + "action": "Fire", + "isComposite": false, + "isPartOfComposite": false + }, { "name": "", "id": "05431a8a-4464-49e0-8a15-eec2a4351985", @@ -327,6 +371,17 @@ "isComposite": false, "isPartOfComposite": false }, + { + "name": "", + "id": "fce3a9d9-2f96-4a18-bc01-4f6a61f66e59", + "path": "/leftTrigger", + "interactions": "", + "processors": "", + "groups": "", + "action": "Aim", + "isComposite": false, + "isPartOfComposite": false + }, { "name": "", "id": "9a305ecb-00ee-46fb-be5b-f58125ac34eb", @@ -338,6 +393,17 @@ "isComposite": false, "isPartOfComposite": false }, + { + "name": "", + "id": "9a2d7939-d112-4796-a50f-7e723cb0ebb4", + "path": "/rightStickPress", + "interactions": "", + "processors": "", + "groups": "", + "action": "Melee", + "isComposite": false, + "isPartOfComposite": false + }, { "name": "2D Vector", "id": "f2793bde-975d-41cf-b721-4ea21c2cfe7d", @@ -415,6 +481,17 @@ "isComposite": false, "isPartOfComposite": false }, + { + "name": "", + "id": "7475328b-a74c-4c33-90ad-0a59351a3595", + "path": "/leftStickPress", + "interactions": "", + "processors": "", + "groups": "", + "action": "Run", + "isComposite": false, + "isPartOfComposite": false + }, { "name": "", "id": "b8ca7195-54e8-472e-9849-378ea8b1b2d4", @@ -536,6 +613,17 @@ "isComposite": false, "isPartOfComposite": false }, + { + "name": "", + "id": "fa054fa0-fc44-4096-a9df-ea3e6cae27f3", + "path": "/buttonWest", + "interactions": "", + "processors": "", + "groups": "", + "action": "Interactive", + "isComposite": false, + "isPartOfComposite": false + }, { "name": "", "id": "abfe62ef-1678-40c6-85e4-7644a3ffffc3", @@ -547,6 +635,17 @@ "isComposite": false, "isPartOfComposite": false }, + { + "name": "", + "id": "ccb765ab-4913-467a-9b10-c66f7b1b836c", + "path": "/buttonWest", + "interactions": "Hold", + "processors": "", + "groups": "", + "action": "Reload", + "isComposite": false, + "isPartOfComposite": false + }, { "name": "", "id": "c354e7ce-0648-4b49-b042-1f7dfc7657d9", @@ -591,6 +690,17 @@ "isComposite": false, "isPartOfComposite": false }, + { + "name": "", + "id": "438f83aa-f2a6-4d51-84a2-c6b334924fb0", + "path": "/select", + "interactions": "", + "processors": "", + "groups": "", + "action": "ToggleCamera", + "isComposite": false, + "isPartOfComposite": false + }, { "name": "", "id": "c7bf69ae-febf-4280-b153-d529229f82b5", @@ -686,7 +796,7 @@ "name": "Cancel", "type": "Button", "id": "60dfbf31-4ec8-4df1-be35-9f1eca07d7be", - "expectedControlType": "Button", + "expectedControlType": "", "processors": "", "interactions": "Press,Hold,Tap", "initialStateCheck": false @@ -713,7 +823,7 @@ "name": "Inventory", "type": "Button", "id": "80289a66-dc26-4d9e-967d-a561bb8794e3", - "expectedControlType": "Button", + "expectedControlType": "", "processors": "", "interactions": "Press,Hold", "initialStateCheck": false @@ -740,6 +850,17 @@ "isComposite": false, "isPartOfComposite": false }, + { + "name": "", + "id": "16cf3841-290b-4e38-9b3f-71d4a5428c70", + "path": "/leftStick", + "interactions": "", + "processors": "", + "groups": "", + "action": "Point", + "isComposite": false, + "isPartOfComposite": false + }, { "name": "", "id": "39028ab4-2f9f-43b2-99f6-6689cbc29e17", @@ -817,6 +938,50 @@ "isComposite": false, "isPartOfComposite": false }, + { + "name": "", + "id": "c65bdae3-6e08-4931-b364-738eb5248f5c", + "path": "/start", + "interactions": "", + "processors": "", + "groups": "", + "action": "Cancel", + "isComposite": false, + "isPartOfComposite": false + }, + { + "name": "", + "id": "e610040c-2163-48b0-892a-d17c525b4763", + "path": "/{Cancel}", + "interactions": "", + "processors": "", + "groups": "", + "action": "Cancel", + "isComposite": false, + "isPartOfComposite": false + }, + { + "name": "", + "id": "835f92ac-0a3f-495c-a09b-694b13942d96", + "path": "/{Cancel}", + "interactions": "", + "processors": "", + "groups": "", + "action": "Cancel", + "isComposite": false, + "isPartOfComposite": false + }, + { + "name": "", + "id": "a490bb73-90bd-4cd2-b702-cd89bc1987d4", + "path": "/{Cancel}", + "interactions": "", + "processors": "", + "groups": "", + "action": "Cancel", + "isComposite": false, + "isPartOfComposite": false + }, { "name": "", "id": "5f7a54af-6a1b-4e69-8a46-57a6772019cc", @@ -850,6 +1015,17 @@ "isComposite": false, "isPartOfComposite": false }, + { + "name": "", + "id": "6f51a8c8-9f11-40d5-a0b9-3a78dde74a22", + "path": "/dpad/up", + "interactions": "", + "processors": "", + "groups": "", + "action": "Inventory", + "isComposite": false, + "isPartOfComposite": false + }, { "name": "WASD", "id": "a40b1b7f-8cb3-4138-80a0-ec2771a2481a", @@ -981,7 +1157,7 @@ "name": "Vertical", "type": "Button", "id": "5703bb8a-1107-4f73-91fa-9bbc362d9528", - "expectedControlType": "Button", + "expectedControlType": "", "processors": "", "interactions": "", "initialStateCheck": false @@ -1093,7 +1269,7 @@ "name": "AscendAndDescend", "type": "Button", "id": "a78acdb6-b9dd-4d90-a89e-58fb62647380", - "expectedControlType": "Button", + "expectedControlType": "", "processors": "", "interactions": "", "initialStateCheck": false @@ -1309,7 +1485,7 @@ "name": "Vertical", "type": "Button", "id": "cc774816-362e-40d3-98c5-19411a7ae97a", - "expectedControlType": "Button", + "expectedControlType": "", "processors": "", "interactions": "", "initialStateCheck": false diff --git a/Src/Unity/Scripts/Assets/BITFramework.cs b/Src/Unity/Scripts/Assets/BITFramework.cs index 8510616..c475e63 100644 --- a/Src/Unity/Scripts/Assets/BITFramework.cs +++ b/Src/Unity/Scripts/Assets/BITFramework.cs @@ -6,7 +6,6 @@ using System.IO; using BITKit.IO; using BITKit.UX; using Cysharp.Threading.Tasks; -using UnityEditorInternal; using UnityEngine; using UnityEngine.Events; using UnityEngine.Rendering; @@ -26,9 +25,11 @@ namespace BITKit private static void Reload() { Stopwatch = new Stopwatch(); + #if UNITY_EDITOR + #else - SplashScreen.Stop(SplashScreen.StopBehavior.StopImmediate); + SplashScreen.Stop(SplashScreen.StopBehavior.StopImmediate); #endif } diff --git a/Src/Unity/Scripts/Assets/ScriptableEntitiesService.cs b/Src/Unity/Scripts/Assets/ScriptableEntitiesService.cs new file mode 100644 index 0000000..02c2118 --- /dev/null +++ b/Src/Unity/Scripts/Assets/ScriptableEntitiesService.cs @@ -0,0 +1,65 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using BITKit.Entities; +using BITKit.Mod; +using Cysharp.Threading.Tasks; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using UnityEngine; +using ILogger = Microsoft.Extensions.Logging.ILogger; + +namespace BITKit.IO +{ + public class ScriptableEntitiesService : IDisposable + { + private readonly IEntitiesService _entitiesService; + + public string Tags = "scriptable_object"; + + private readonly List _registeredEntities = new(); + + public ScriptableEntitiesService(IEntitiesService entitiesService) + { + _entitiesService = entitiesService; + } + + public async UniTask InitializeAsync(ILogger logger = null) + { + logger?.LogInformation("正在查找所有ScriptableObject..."); + var objs = await ModService.LoadAssets(Tags); + logger?.LogInformation($"找到{objs.Count}个资源,正在加载中..."); + for (var index = 0; index < objs.Count; index++) + { + var scriptableObject = objs[index]; + var entity = new Entity(); + + var idComponent = new IdComponent(); + + entity.ServiceCollection.AddSingleton(idComponent); + + var type = scriptableObject.GetType(); + + entity.ServiceCollection.AddSingleton(type, scriptableObject); + + _entitiesService.Register(entity); + + logger?.LogInformation($"已加载:{scriptableObject.name}:{type.Name},剩余:{index + 1}/{objs.Count}"); + _registeredEntities.Add(entity); + } + + logger?.LogInformation("加载完成"); + } + + public void Dispose() + { + foreach (var x in _registeredEntities) + { + _entitiesService.UnRegister(x); + } + + _registeredEntities.Clear(); + } + } + +} diff --git a/Src/Unity/Scripts/Assets/ScriptableEntitiesService.cs.meta b/Src/Unity/Scripts/Assets/ScriptableEntitiesService.cs.meta new file mode 100644 index 0000000..1416bfc --- /dev/null +++ b/Src/Unity/Scripts/Assets/ScriptableEntitiesService.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: e1ff18f234ca249459fb3df556f90b11 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Src/Unity/Scripts/Assets/YooAssetModHelper.cs b/Src/Unity/Scripts/Assets/YooAssetModHelper.cs index 10f8a7f..d9b9f21 100644 --- a/Src/Unity/Scripts/Assets/YooAssetModHelper.cs +++ b/Src/Unity/Scripts/Assets/YooAssetModHelper.cs @@ -1,30 +1,165 @@ using System; using System.Collections; +using System.Collections.Concurrent; using System.Collections.Generic; +using System.Drawing.Printing; +using System.IO; +using System.Linq; +using System.Text.RegularExpressions; using BITKit.Mod; using Cysharp.Threading.Tasks; +using Microsoft.Extensions.Logging; +using UnityEditor; using UnityEngine; using YooAsset; +using ILogger = Microsoft.Extensions.Logging.ILogger; using Object = UnityEngine.Object; namespace BITKit.IO { - public class YooAssetModHelper : MonoBehaviour + public class YooAssetModHelper { - private void OnEnable() + public static string Url = "http://server.bitfall.icu:21982/com.project.b/Mods"; + public static readonly ConcurrentDictionary> PackagesManifestDictionary = new(); + public static async UniTask LoadMods(ILogger logger=null) { - ModService.LoadAssetAsyncFactory += LoadAsset; + try + { + var modPath = Path.Combine(Environment.CurrentDirectory, "Mods"); + + if (Application.platform is RuntimePlatform.Android) + { + modPath = Path.Combine($"/storage/emulated/0/{Application.identifier}/Mods/"); + } + + + foreach (var directoryInfo in new DirectoryInfo(modPath).GetDirectories()) + { + var packageName = directoryInfo.Name; + + logger?.LogInformation($"开始加载:{packageName}"); + + var package = YooAssets.CreatePackage(packageName); + + + var initPars = new HostPlayModeParameters() + { + BuildinQueryServices = new GameQueryServices(), + RemoteServices = new RemoteServices($"{Url}/{directoryInfo.Name}",$"file://{directoryInfo.FullName}") + }; + + await package.InitializeAsync(initPars); + + var update = package.UpdatePackageVersionAsync(); + await update.ToUniTask(); + + var manifest = package.UpdatePackageManifestAsync(update.PackageVersion); + await manifest.ToUniTask(); + + var downloader = package.CreateResourceDownloader(10, 3); + + if (logger is not null) + { + downloader.OnDownloadProgressCallback = (totalDownloadCount, currentDownloadCount, + totalDownloadBytes, currentDownloadBytes) => + { + //下载进度 + var progress = (float)currentDownloadBytes / totalDownloadBytes; + logger.LogInformation($"已下载{(int)(progress*100)}%,资源数量{currentDownloadBytes}/{totalDownloadBytes}"); + }; + downloader.OnDownloadErrorCallback = (fileName, error) => + { + logger.LogError($"资源[{fileName}]下载错误::{error}"); + }; + } + + downloader.BeginDownload(); + + await downloader.ToUniTask(); + + var mod = new MyMod() + { + FolderPath = directoryInfo.FullName, + PackageName = packageName, + Name = packageName + }; + + await ModService.Install(mod); + await ModService.Load(mod); + + YooAssetUtils.RegisterResourcePackage(package); + + logger?.LogInformation($"已加载:{packageName},路径:{directoryInfo.FullName}"); + + } + return; + } + catch (Exception e) + { + if (logger is not null) + { + logger.LogCritical(e.Message,e); + } + else + { + BIT4Log.LogException(e); + } + } + logger?.LogInformation($"未找到Mod"); } - private void OnDisable() + + private static HashSet BuildPackageCache(string obj) { - ModService.LoadAssetAsyncFactory -= LoadAsset; + var package = YooAssets.GetPackage(obj); + var playMode = package.GetType().GetField("_playModeImpl", ReflectionHelper.Flags)!.GetValue(package); + var manifest = playMode.GetType().GetProperty("ActiveManifest", ReflectionHelper.Flags)!.GetValue(playMode); + var dictionary = manifest.GetType().GetField("AssetDic", ReflectionHelper.Flags)!.GetValue(manifest) as IDictionary; + + var hashset = new HashSet(); + + foreach (var key in dictionary.Keys) + { + hashset.Add(key?.ToString()); + } + + var assetPathMapping1=manifest.GetType().GetField("AssetPathMapping1", ReflectionHelper.Flags)!.GetValue(manifest) as IDictionary; + + foreach (var key in assetPathMapping1.Keys) + { + hashset.Add(key); + } + + return hashset; } - - private static async UniTask LoadAsset(string arg) + + public static async UniTask> LoadAssets( string[] arg) { - var handle = YooAssets.LoadAssetAsync(arg); - await handle; - return handle.AssetObject; + var list = new List(); + foreach (var resourcePackage in YooAssetUtils.RegisteredResourcePackages) + { + foreach (var assetInfo in resourcePackage.GetAssetInfos(arg)) + { + var asyncHandle = resourcePackage.LoadAssetAsync(assetInfo); + await asyncHandle; + list.Add(asyncHandle.AssetObject); + } + } + return list; + } + + public static async UniTask LoadAsset(string arg) + { + foreach (var resourcePackage in YooAssetUtils.RegisteredResourcePackages.Reverse()) + { + if(PackagesManifestDictionary.GetOrAdd(resourcePackage.PackageName,BuildPackageCache).Contains(arg) is false)continue; + + var assetInfo = resourcePackage.GetAssetInfo(arg); + if(string.IsNullOrEmpty(assetInfo.Error) is false)continue; + var handle = resourcePackage.LoadAssetAsync(arg); + await handle; + return handle.AssetObject; + } + return null; } } } diff --git a/Src/Unity/Scripts/BITAppForUnity.cs b/Src/Unity/Scripts/BITAppForUnity.cs index 877defd..bba49a7 100644 --- a/Src/Unity/Scripts/BITAppForUnity.cs +++ b/Src/Unity/Scripts/BITAppForUnity.cs @@ -203,6 +203,14 @@ namespace BITKit BITApp.Time.DeltaTime = Time.deltaTime; BITApp.Time.TimeAsDouble = Time.timeAsDouble; allowCursor = AllowCursor.Allow; + + if (Touchscreen.current is not null && Touchscreen.current.IsPressed()) + { + AllowCursor.AddElement(int.MaxValue); + }else if (Mouse.current is not null && Mouse.current.IsPressed()) + { + AllowCursor.RemoveElement(int.MaxValue); + } } public string GetName() diff --git a/Src/Unity/Scripts/InputSystem/InputActionGroup.cs b/Src/Unity/Scripts/InputSystem/InputActionGroup.cs index ea43ae6..d26bbb3 100644 --- a/Src/Unity/Scripts/InputSystem/InputActionGroup.cs +++ b/Src/Unity/Scripts/InputSystem/InputActionGroup.cs @@ -36,6 +36,19 @@ namespace BITKit action.RegisterCallback(callback); return this; } + + public InputActionGroup RegisterCallback(InputAction inputAction,Action callback) + { + EnsureConfiguration(); + + var action = actions.GetOrAdd(inputAction.name, _=>inputAction.Clone()); + + allowInput.Invoke(); + + action.RegisterCallback(callback); + + return this; + } public InputAction EnsureCreated(InputActionReference reference) { @@ -57,6 +70,20 @@ namespace BITKit return action; } + public InputAction EnsureCreated(InputAction inputAction) + { + EnsureConfiguration(); + var action = actions.GetOrAdd(inputAction.name, _ => + { + var newAction = inputAction.Clone(); + newAction.Rename(inputAction.name); + return newAction; + }); + + allowInput.Invoke(); + + return action; + } public void Inherit(InputActionGroup other) { @@ -80,6 +107,12 @@ namespace BITKit action.UnRegisterCallback(callback); } + public void UnRegisterCallback(InputAction inputAction, Action callback) + { + if(actions.TryGetValue(inputAction.name,out var action)) + action.UnRegisterCallback(callback); + } + private void EnsureConfiguration() { if (state is not InitializationState.Initialized) diff --git a/Src/Unity/Scripts/InputSystem/UnityPlayerInput.cs b/Src/Unity/Scripts/InputSystem/UnityPlayerInput.cs new file mode 100644 index 0000000..9146201 --- /dev/null +++ b/Src/Unity/Scripts/InputSystem/UnityPlayerInput.cs @@ -0,0 +1,50 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using BITKit; +using UnityEngine; + +namespace UnityEngine.InputSystem +{ + public class UnityPlayerInput : MonoBehaviour + { + private readonly InputActionGroup _inputActionGroup=new(); + + [SerializeField] private InputActionAsset inputActionAsset; + + private bool _isInitialized; + + private void Start() + { + foreach (var inputActionMap in inputActionAsset.actionMaps) + { + foreach (var inputAction in inputActionMap.actions) + { + _inputActionGroup.RegisterCallback(inputAction, x => + { + SendMessage($"On{inputAction.name}",x,SendMessageOptions.DontRequireReceiver); + }); + } + } + + if (_isInitialized is false) + { + _inputActionGroup.allowInput.AddElement(this); + } + + _isInitialized = true; + } + + private void OnEnable() + { + if (_isInitialized) + _inputActionGroup.allowInput.AddElement(this); + } + + private void OnDisable() + { + _inputActionGroup.allowInput.RemoveElement(this); + } + } + +} diff --git a/Src/Unity/Scripts/InputSystem/UnityPlayerInput.cs.meta b/Src/Unity/Scripts/InputSystem/UnityPlayerInput.cs.meta new file mode 100644 index 0000000..72bcd63 --- /dev/null +++ b/Src/Unity/Scripts/InputSystem/UnityPlayerInput.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 6b2748010e8669a44b12cd163ea95fa2 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Src/Unity/Scripts/Mod/UnityModService.cs b/Src/Unity/Scripts/Mod/UnityModService.cs deleted file mode 100644 index 4e23651..0000000 --- a/Src/Unity/Scripts/Mod/UnityModService.cs +++ /dev/null @@ -1,121 +0,0 @@ -using System; -using System.Collections; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using BITKit.UX; - -#if UNITY_EDITOR -using UnityEditor; -#endif - -using UnityEngine; - -namespace BITKit.Mod -{ - public class UnityModService : MonoBehaviour - { - [SerializeReference,SubclassSelector] private IReference[] referencedAssemblies; - private async void Start() - { - //DI.TryGet(out var waiting); - IUXWaiting waiting = null; - var handle = waiting?.Get(); - handle?.SetMessage("正在初始化Mod服务"); - - if (Application.isEditor is false) - { - BIT4Log.Log($"UnityPlayer所在位置:{Application.dataPath}"); - - BIT4Log.Log($"{nameof(System.Linq)}位于{typeof(Enumerable).Assembly.Location}"); - } - - - foreach (var x in referencedAssemblies) - { - var dllName = x.Value.Contains(".dll") ? x.Value : $"{x.Value}.dll"; - - if (SearchDll(dllName,out var dll) is false) - { - BIT4Log.Warning($"未找到:{dll}"); - continue; - } - - BITSharp.ReferencedAssemblies.Add(@$"""{dll}"""); - } - - try - { - ModService.Initialize(); - } - catch (Exception e) - { - BIT4Log.Warning("初始化失败"); - BIT4Log.LogException(e); - return; - } - - destroyCancellationToken.Register(ModService.Dispose); - - ModService.OnPackageLoad+=OnPackageLoad; - - - var packages = await ModService.SearchPackages(); - if (destroyCancellationToken.IsCancellationRequested) return; - foreach (var package in packages) - { - await ModService.LoadFromPackage(package.PackagePath); - if (destroyCancellationToken.IsCancellationRequested) return; - } - - - destroyCancellationToken.Register(() => - { - ModService.OnPackageLoad-=OnPackageLoad; - }); - - waiting?.Release(handle); - } - - private void OnPackageLoad(ModPackage obj) - { - var loadedDlls = referencedAssemblies.Cast(); - var reportBuilder = new System.Text.StringBuilder(); - - //对比已加载的dll和当前引用的dll - foreach (var x in obj.Dlls.Except(loadedDlls)) - { - if (SearchDll(x, out var dll) is false) - { - BIT4Log.Warning($"未找到:{dll}"); - continue; - } - - BITSharp.ReferencedAssemblies.Add(@$"""{dll}"""); - reportBuilder.AppendLine($"加载:{dll}"); - } - BIT4Log.Log(reportBuilder.ToString()); - } - private bool SearchDll(string dllName,out string dll,params string[] moreFolder) - { -#if UNITY_EDITOR - dll = System.IO.Path.Combine(Environment.CurrentDirectory, "Library", "ScriptAssemblies", dllName); - var folder = EditorApplication.applicationPath; - folder = Path.GetDirectoryName(folder); - if(File.Exists(dll) is false) - { - dll = Path.Combine(folder,"Data", "MonoBleedingEdge", "lib","mono","unityjit-win32",dllName); - } - if (File.Exists(dll) is false) - { - dll = Path.Combine(folder,"Data", "MonoBleedingEdge", "lib","mono","unityjit-win32","Facades",dllName); - } - -#else - dll = System.IO.Path.Combine(Environment.CurrentDirectory,$"{Application.productName}_Data", "Managed", dllName); -#endif - return File.Exists(dll); - } - } -} - diff --git a/Src/Unity/Scripts/Mod/UnityModServiceTester.cs b/Src/Unity/Scripts/Mod/UnityModServiceTester.cs deleted file mode 100644 index 78dfc90..0000000 --- a/Src/Unity/Scripts/Mod/UnityModServiceTester.cs +++ /dev/null @@ -1,48 +0,0 @@ -using System; -using System.Collections; -using System.Collections.Generic; -using Cysharp.Threading.Tasks; -using UnityEngine; - -namespace BITKit.Mod -{ - public class UnityModServiceTester : MonoBehaviour - { - [Serializable] - public class TestLogGameTickMod:MyMod - { - public override void OnInitialized() - { - base.OnInitialized(); - GameTickService.Add(OnTick); - } - private static void OnTick(float obj) - { - BIT4Log.Log($"On Test Mod Tick,delta:{obj}"); - } - public override void OnDispose() - { - GameTickService.Remove(OnTick); - } - } - - [SerializeReference, SubclassSelector] private IMod[] initialMods; - private void OnEnable() - { - foreach (var testMod in initialMods) - { - ModService.Install(testMod); - ModService.Load(testMod); - } - } - private void OnDisable() - { - foreach (var testMod in initialMods) - { - ModService.UnLoad(testMod); - ModService.UnInstall(testMod); - } - } - } - -} diff --git a/Src/Unity/Scripts/Physics/BITKit.Physics.asmdef b/Src/Unity/Scripts/Physics/BITKit.Physics.asmdef index e2e5ae1..036929d 100644 --- a/Src/Unity/Scripts/Physics/BITKit.Physics.asmdef +++ b/Src/Unity/Scripts/Physics/BITKit.Physics.asmdef @@ -2,7 +2,8 @@ "name": "BITKit.Physics", "rootNamespace": "", "references": [ - "GUID:14fe60d984bf9f84eac55c6ea033a8f4" + "GUID:14fe60d984bf9f84eac55c6ea033a8f4", + "GUID:6babdba9f8b742f40904649736008000" ], "includePlatforms": [], "excludePlatforms": [], diff --git a/Src/Unity/Scripts/Physics/GeometryUtils.cs b/Src/Unity/Scripts/Physics/GeometryUtils.cs new file mode 100644 index 0000000..f4d1449 --- /dev/null +++ b/Src/Unity/Scripts/Physics/GeometryUtils.cs @@ -0,0 +1,99 @@ +using System.Collections; +using System.Collections.Generic; +using UnityEngine; + +namespace BITKit.Physics +{ + public static class GeometryUtils + { + /// + /// 获取一个点到一条线段的最近点 + /// + /// + /// + /// + /// + public static Vector3 PointToLineSegmentDistance(Vector3 point, Vector3 lineStart, Vector3 lineEnd) + { + Vector3 lineDirection = lineEnd - lineStart; + Vector3 pointDirection = point - lineStart; + + float lineLength = lineDirection.magnitude; + lineDirection.Normalize(); + + float dotProduct = Vector3.Dot(pointDirection, lineDirection); + dotProduct = Mathf.Clamp(dotProduct, 0f, lineLength); + + Vector3 closestPoint = lineStart + lineDirection * dotProduct; + return closestPoint; + } + /// + /// 获取一个点到一个三角形内最短距离的点 + /// + /// 三角形顶点a + /// 三角形顶点b + /// 三角形顶点c + /// + /// + public static Vector3 GetPosInTriangle(Vector3 a, Vector3 b, Vector3 c, Vector3 pos) + { + Vector3 normal = Vector3.Cross(b - a, c - a).normalized; + Vector3 toPoint = pos - a; + float distance = Vector3.Dot(toPoint, normal); + + Vector3 targetPos = pos - distance * normal; + + if(PointInTriangle(targetPos, a, b, c)) + return targetPos; + else + { + Vector3 p1 = PointToLineSegmentDistance(pos, a, b); + Vector3 p2 = PointToLineSegmentDistance(pos, a, c); + Vector3 p3 = PointToLineSegmentDistance(pos, b, c); + + float d1 = Vector3.Distance(p1, pos); + float d2 = Vector3.Distance(p2, pos); + float d3 = Vector3.Distance(p3, pos); + + if (d1 <= d2 && d1 <= d3) + return p1; + else if (d2 <= d3 && d2 <= d1) + return p2; + else /*if(d3 <= d1 && d3 <= d2)*/ + return p3; + + //return default; + } + } + + /// + /// 判断一个点是否在三角形内 + /// + /// + /// + /// + /// + /// + public static bool PointInTriangle(Vector3 pos, Vector3 a, Vector3 b, Vector3 c) + { + var v0 = c - a; + var v1 = b - a; + var v2 = pos - a; + + var dot00 = Vector3.Dot(v0, v0); + var dot01 = Vector3.Dot(v0, v1); + var dot02 = Vector3.Dot(v0, v2); + var dot11 = Vector3.Dot(v1, v1); + var dot12 = Vector3.Dot(v1, v2); + + var invDenom = 1 / (dot00 * dot11 - dot01 * dot01); + var u = (dot11 * dot02 - dot01 * dot12) * invDenom; + var v = (dot00 * dot12 - dot01 * dot02) * invDenom; + + // 如果u和v都在[0,1]的范围内,那么点P在三角形ABC内 + return (u >= 0) && (v >= 0) && (u + v < 1); + } + } + +} + diff --git a/Src/Unity/Scripts/Physics/GeometryUtils.cs.meta b/Src/Unity/Scripts/Physics/GeometryUtils.cs.meta new file mode 100644 index 0000000..24d0947 --- /dev/null +++ b/Src/Unity/Scripts/Physics/GeometryUtils.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: ae14ae5985cea8e40946355bfdf7113b +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Src/Unity/Scripts/Physics/GetClosePointFromCollider.cs b/Src/Unity/Scripts/Physics/GetClosePointFromCollider.cs index b98097d..1812b49 100644 --- a/Src/Unity/Scripts/Physics/GetClosePointFromCollider.cs +++ b/Src/Unity/Scripts/Physics/GetClosePointFromCollider.cs @@ -1,7 +1,9 @@ using System.Collections; using System.Collections.Generic; +using System.Globalization; using System.Linq; using System.Text; +using DrawXXL; using UnityEngine; namespace BITKit.Physics @@ -9,7 +11,7 @@ namespace BITKit.Physics public class GetClosePointFromCollider : IClosePointProvider { public string Name="Default"; - public Transform Transform; + public readonly Transform Transform; public Vector3 Offset = default; public LayerMask LayerMask=LayerMask.NameToLayer("Default"); public float Distance=1.6f; @@ -26,68 +28,97 @@ namespace BITKit.Physics public bool TryGetValue(out Vector3 position, out Collider collider) { - Vector3 vector3 = default; StringBuilder reportBuilder = new(); reportBuilder.AppendLine($"检测任务:{Name}"); position = Transform.position + Transform.rotation * Offset; var detectedLength = UnityEngine.Physics.OverlapSphereNonAlloc(position, Distance, _mainCollider, LayerMask); reportBuilder.AppendLine($"检测到了{detectedLength}个碰撞体"); + + var validMeshColliders = new Queue<(Collider collider,Vector3 targetPosition)>(); + + var samplePoint = position; + samplePoint.y += Distance / 2; foreach (var collider1 in _mainCollider.Take(detectedLength).OrderBy(ByTop).Reverse()) - //for (var i = 0; i top) + if (Transform.position.y + MinHeight > closePoint.y) { - reportBuilder?.AppendLine("高度不足"); + DrawBasics.PointTag(closePoint,"not enough height"); continue; } - - var nextPos = position; - nextPos.y = collider1.bounds.center.y; - - { - var ray = new Ray(nextPos, Transform.forward); - if (collider1.Raycast(new Ray(nextPos, Transform.forward), out _, Distance) is false) - { - reportBuilder?.AppendLine("未检测到前方"); - Debug.DrawRay(ray.origin,ray.direction,Color.red,Distance); - continue; - } - } + - var height = Mathf.Abs(top - Transform.position.y); + var height = Mathf.Abs(closePoint.y - Transform.position.y); if (height > MaxHeight) { reportBuilder?.AppendLine($"高度差距过大:{height}"); continue; } + + - if (UnityEngine.Physics.Linecast(Transform.position, vector3, out var raycastHit2, LayerMask)) + if (UnityEngine.Physics.Linecast(Transform.position, closePoint, out var raycastHit2, LayerMask)) { if (raycastHit2.collider != collider1) { @@ -95,40 +126,61 @@ namespace BITKit.Physics continue; } } - var length = UnityEngine.Physics.OverlapSphereNonAlloc(vector3, 0.01f, _colliders, LayerMask); + + + + + var length = UnityEngine.Physics.OverlapSphereNonAlloc(closePoint+Vector3.up*0.2f, 0.1f, _colliders, LayerMask); switch (length) { - case 1: - if (_colliders[0] != collider1) - { - reportBuilder.AppendLine($"检测到了其他碰撞体{_colliders[0].name}"); - continue; - } - - break; - case > 1: + case > 0: reportBuilder.AppendLine("检测到了更多碰撞体"); for (var ii = 0; ii < length; ii++) { //Debug.DrawLine(vector3, _colliders[ii].ClosestPoint(vector3), Color.red, 8); reportBuilder.AppendLine($"\t{_colliders[ii].name}"); } - continue; } - - vector3.y = top; - position = vector3; - - collider = collider1; + + reportBuilder.AppendLine("成功"); + //BIT4Log.Log(reportBuilder.ToString()); - return true; + + Debug.DrawLine(Transform.position,closePoint,Color.green); + + validMeshColliders.Enqueue(new(collider1,closePoint)); + } + + var minDot = 64f; + + Collider resultCollider = default; + Vector3 resultPosition=default; + + while (validMeshColliders.TryDequeue(out var result)) + { + var dot =Mathf.Abs(Vector3.Cross(Transform.forward, result.targetPosition-Transform.position).y); + + DrawBasics.LineFrom(Transform.position,result.targetPosition-Transform.position,Color.red,text:dot.ToString(CultureInfo.InvariantCulture)); + + if(dot>minDot)continue; + + resultCollider = result.collider; + resultPosition = result.targetPosition; + + minDot = dot; + } + + if (minDot < 64) + { + collider = resultCollider; + position = resultPosition; + return true; } collider = null; - //BIT4Log.Log(reportBuilder.ToString()); return false; } private float ByTop(Collider arg) diff --git a/Src/Unity/Scripts/Physics/GetClosePointFromColliderDebuger.cs b/Src/Unity/Scripts/Physics/GetClosePointFromColliderDebuger.cs new file mode 100644 index 0000000..147f28c --- /dev/null +++ b/Src/Unity/Scripts/Physics/GetClosePointFromColliderDebuger.cs @@ -0,0 +1,34 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using UnityEngine; + +namespace BITKit.Physics +{ + [ExecuteAlways] + public class GetClosePointFromColliderDebugger : MonoBehaviour + { + private GetClosePointFromCollider _getClosePointFromCollider; + [SerializeField] private LayerMask layerMask; + private void OnEnable() + { + _getClosePointFromCollider = new GetClosePointFromCollider(transform); + + } + + private void Update() + { + _getClosePointFromCollider.LayerMask = layerMask; + if (_getClosePointFromCollider.TryGetValue(out Vector3 vector3, out var collider1)) + { + var offset = Vector3.up * -0.01f; + Debug.DrawLine(transform.position+offset,vector3+offset,Color.cyan); + } + } + + private void OnDrawGizmosSelected() + { + Gizmos.DrawWireSphere(transform.position,_getClosePointFromCollider.Distance); + } + } +} diff --git a/Src/Unity/Scripts/Physics/GetClosePointFromColliderDebuger.cs.meta b/Src/Unity/Scripts/Physics/GetClosePointFromColliderDebuger.cs.meta new file mode 100644 index 0000000..f7224fd --- /dev/null +++ b/Src/Unity/Scripts/Physics/GetClosePointFromColliderDebuger.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: e856e0f7ca7746740a416303f76dc89d +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Src/Unity/Scripts/Physics/GetClosestPointFromMesh.cs b/Src/Unity/Scripts/Physics/GetClosestPointFromMesh.cs new file mode 100644 index 0000000..76d5c70 --- /dev/null +++ b/Src/Unity/Scripts/Physics/GetClosestPointFromMesh.cs @@ -0,0 +1,53 @@ +using System.Collections; +using System.Collections.Generic; +using System.Linq; +using UnityEditor; +using UnityEngine; + +namespace BITKit.Physics +{ + public readonly struct GetClosestPointFromMesh:IClosePointProvider + { + private readonly Vector3 _position; + private readonly Mesh _mesh; + + public GetClosestPointFromMesh(Mesh mesh, Vector3 position) + { + _mesh = mesh; + _position = position; + } + + public bool TryGetValue(out Vector3 position, out Collider collider) + { + position = default; + collider = default; + + if (_mesh.isReadable is false) return false; + + + var vertices = _mesh.vertices; + + if (vertices.Length > 2048) return false; + + var minPos = new Vector3(64, 64, 64); + + for (var index = 0; index < _mesh.triangles.Length; index+=3) + { + var x = vertices[_mesh.triangles[index]]; + var y = vertices[_mesh.triangles[index + 1]]; + var z = vertices[_mesh.triangles[index + 2]]; + + var pos = GeometryUtils.GetPosInTriangle(x, y, z, _position); + + if (Vector3.Distance(pos, _position) < Vector3.Distance(minPos, _position)) + { + minPos = pos; + } + } + + position = minPos; + + return true; + } + } +} \ No newline at end of file diff --git a/Src/Unity/Scripts/Physics/GetClosestPointFromMesh.cs.meta b/Src/Unity/Scripts/Physics/GetClosestPointFromMesh.cs.meta new file mode 100644 index 0000000..265038a --- /dev/null +++ b/Src/Unity/Scripts/Physics/GetClosestPointFromMesh.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 979c184b4aaba6a439cbe74f0196267f +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Src/Unity/Scripts/Reference/DictionaryReferenceScriptableObject.cs b/Src/Unity/Scripts/Reference/DictionaryReferenceScriptableObject.cs index 61f76d3..8837b44 100644 --- a/Src/Unity/Scripts/Reference/DictionaryReferenceScriptableObject.cs +++ b/Src/Unity/Scripts/Reference/DictionaryReferenceScriptableObject.cs @@ -27,7 +27,7 @@ namespace BITKit AssetDatabase.LoadAssetAtPath( "Assets/Artists/Configs/reference_dictionary.asset"); #else - var task = YooAssets.LoadAssetAsync("reference_directory"); + var task = YooAssets.LoadAssetAsync("reference_dictionary"); task.WaitForAsyncComplete(); _singleton=task.AssetObject as DictionaryReferenceScriptableObject; #endif diff --git a/Src/Unity/Scripts/Rig/TickOverrideTranformService.cs b/Src/Unity/Scripts/Rig/TickOverrideTranformService.cs index d1337e5..a4ec2c8 100644 --- a/Src/Unity/Scripts/Rig/TickOverrideTranformService.cs +++ b/Src/Unity/Scripts/Rig/TickOverrideTranformService.cs @@ -11,7 +11,7 @@ using UnityEngine; using UnityEngine.Jobs; using UnityEngine.Pool; -namespace BITFALL.Rig{ +namespace BITKit.UX.Rig{ public class TickOverrideTranformService : MonoBehaviour { //[BurstCompile] diff --git a/Src/Unity/Scripts/Rig/TickOverrideTransform.cs b/Src/Unity/Scripts/Rig/TickOverrideTransform.cs index 1cf9ae5..271d3ef 100644 --- a/Src/Unity/Scripts/Rig/TickOverrideTransform.cs +++ b/Src/Unity/Scripts/Rig/TickOverrideTransform.cs @@ -3,7 +3,7 @@ using System.Collections; using System.Collections.Generic; using UnityEngine; -namespace BITFALL.Rig +namespace BITKit.UX.Rig { public class TickOverrideTransform : MonoBehaviour { diff --git a/Src/Unity/Scripts/Tick/IntervalTickService.cs b/Src/Unity/Scripts/Tick/IntervalTickService.cs index 9767263..894bcf6 100644 --- a/Src/Unity/Scripts/Tick/IntervalTickService.cs +++ b/Src/Unity/Scripts/Tick/IntervalTickService.cs @@ -14,7 +14,7 @@ namespace BITKit [Serializable] public class IntervalTick:ITicker { - [SerializeField] private float interval; + private float interval; public ulong TickCount=>IntervalTickService.GetTickCount(interval); public void Add(Action action) diff --git a/Src/Unity/Scripts/UX/BITKit.UX.asmdef b/Src/Unity/Scripts/UX/BITKit.UX.asmdef index cf1fce1..688963e 100644 --- a/Src/Unity/Scripts/UX/BITKit.UX.asmdef +++ b/Src/Unity/Scripts/UX/BITKit.UX.asmdef @@ -18,7 +18,9 @@ "GUID:517785bb4600a5140b47eac5fa49b8fc", "GUID:838d3286f0973344ab6e99d3951012f7", "GUID:a11ff146d38b27a44af87b4b4d9c4ecb", - "GUID:e4d11af1289097a4d9d8987f332a2ae8" + "GUID:e4d11af1289097a4d9d8987f332a2ae8", + "GUID:3abaaefa7af558d44ba20cea1c43d602", + "GUID:d8b63aba1907145bea998dd612889d6b" ], "includePlatforms": [], "excludePlatforms": [], diff --git a/Src/Unity/Scripts/StateMachine.meta b/Src/Unity/Scripts/UX/Cell.meta similarity index 77% rename from Src/Unity/Scripts/StateMachine.meta rename to Src/Unity/Scripts/UX/Cell.meta index 2c4ba03..a13c47f 100644 --- a/Src/Unity/Scripts/StateMachine.meta +++ b/Src/Unity/Scripts/UX/Cell.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: 9d540311d69835747a74085c9e0aba6c +guid: ea593ccd503f23741b162c0f5a00fb52 folderAsset: yes DefaultImporter: externalObjects: {} diff --git a/Src/Unity/Scripts/UX/Debuger/UXDebuger.cs b/Src/Unity/Scripts/UX/Debuger/UXDebuger.cs index fcfb2d3..10d9535 100644 --- a/Src/Unity/Scripts/UX/Debuger/UXDebuger.cs +++ b/Src/Unity/Scripts/UX/Debuger/UXDebuger.cs @@ -59,9 +59,10 @@ namespace BITKit.UX GUILayout.BeginVertical(); //颜色更改为黑色 GUI.color = textColor; - GUILayout.Label(_logBuilder.ToString(),style); + GUILayout.Label(string.Join("\n",_logBuilder.ToString().Split("\n").Reverse()),style); GUILayout.EndVertical(); GUILayout.EndArea(); } + } } \ No newline at end of file diff --git a/Src/Unity/Scripts/UX/Input/BITKit.UX.OnScreen.asmdef b/Src/Unity/Scripts/UX/Input/BITKit.UX.OnScreen.asmdef index 1470439..c961cbd 100644 --- a/Src/Unity/Scripts/UX/Input/BITKit.UX.OnScreen.asmdef +++ b/Src/Unity/Scripts/UX/Input/BITKit.UX.OnScreen.asmdef @@ -8,7 +8,8 @@ "GUID:14fe60d984bf9f84eac55c6ea033a8f4", "GUID:d525ad6bd40672747bde77962f1c401e", "GUID:49b49c76ee64f6b41bf28ef951cb0e50", - "GUID:517785bb4600a5140b47eac5fa49b8fc" + "GUID:517785bb4600a5140b47eac5fa49b8fc", + "GUID:d8b63aba1907145bea998dd612889d6b" ], "includePlatforms": [], "excludePlatforms": [], diff --git a/Src/Unity/Scripts/UX/Input/OnScreenButton.cs b/Src/Unity/Scripts/UX/Input/OnScreenButton.cs new file mode 100644 index 0000000..148bff4 --- /dev/null +++ b/Src/Unity/Scripts/UX/Input/OnScreenButton.cs @@ -0,0 +1,115 @@ +using System.Collections; +using System.Collections.Generic; +using UnityEngine; +using UnityEngine.UIElements; + +namespace BITKit.UX +{ + public class OnScreenButton : OnScreenControl + { + public new class UxmlTraits : VisualElement.UxmlTraits + { + private readonly UxmlFloatAttributeDescription m_PressedValueAttribute = new () + { + name = "PressedValue", + defaultValue = 1f, + }; + + private readonly UxmlBoolAttributeDescription m_ReleasePressAttribute = new() + { + name = "ReleasePress" + }; + + public override void Init(VisualElement ve, IUxmlAttributes bag, CreationContext cc) + { + base.Init(ve, bag, cc); + var table = (OnScreenButton)ve; + table.PressedValue = m_PressedValueAttribute.GetValueFromBag(bag, cc); + table.ReleasePress = m_ReleasePressAttribute.GetValueFromBag(bag, cc); + } + } + public new class UxmlFactory : UxmlFactory { } + public float PressedValue { get; set; }= 1f; + public bool ReleasePress { get; set; } + + private bool _isPressed; + private int _pointerId=-1; + private Label _label; + + private readonly ValidHandle _isTriggered = new(); + public OnScreenButton() + { + RegisterCallback(OnPointerUp); + RegisterCallback(OnPointerDown); + RegisterCallback(OnPointerMove); + this.AddManipulator(new Clickable(OnClick)); + _label = this.Create