Compare commits

..

22 Commits

Author SHA1 Message Date
ALEXTANG
fb26ea2297 Update AddressableManageComponent.cs 2023-08-04 01:42:26 +08:00
ALEXTANG
9ac150425f Update IntDictionaryConfig.cs 2023-08-04 01:42:00 +08:00
ALEXTANG
36d2c146b0 1、修复了MongoDB在2.18.0以后需要自定义注册ObjectSerializer的问题。 2、Addressable的AddAddressable接口增加isLock参数、用来决定是否需要添加携程锁。 3、修复了APackInfo因为网络多线程的原因导致线程安全的问题。
1、修复了MongoDB在2.18.0以后需要自定义注册ObjectSerializer的问题。
2、Addressable的AddAddressable接口增加isLock参数、用来决定是否需要添加携程锁。
3、修复了APackInfo因为网络多线程的原因导致线程安全的问题。
2023-08-04 01:41:31 +08:00
ALEXTANG
774b73bbbf 注释防裁剪脚本中相机权限的引用
注释防裁剪脚本中相机权限的引用
2023-08-01 16:57:43 +08:00
ALEXTANG
32366eb127 移除防裁剪脚本中相机权限的引用
移除防裁剪脚本中相机权限的引用
2023-08-01 16:54:49 +08:00
ALEXTANG
a843617e5f Update README.md 2023-08-01 10:44:15 +08:00
ALEXTANGXIAO
46b139f7cf 补充IOS运行快照到Books下
补充IOS运行快照到Books下
2023-08-01 00:06:07 +08:00
ALEXTANG
e6ff1dec3f Update BuglyAgent.cs 2023-07-31 20:36:44 +08:00
ALEXTANG
4429732010 Update ConfigLoader.cs 2023-07-31 15:01:11 +08:00
ALEXTANGXIAO
60a5caebae 1、Scene.Create接口增加了一个泛型方法接口。 2、SceneConfig增加了SceneTypeConfig和SceneSubType
1、Scene.Create接口增加了一个泛型方法接口。 2、SceneConfig增加了SceneTypeConfig和SceneSubType
2023-07-29 01:03:35 +08:00
ALEXTANGXIAO
f7c95d8216 服务器启动防呆提示需要转表
服务器启动防呆提示需要转表
2023-07-29 00:12:52 +08:00
ALEXTANGXIAO
98dcb80942 更新编辑器MenuItem导表与导出协议
更新编辑器MenuItem导表与导出协议
2023-07-29 00:03:54 +08:00
ALEXTANG
30192d52cf 调整网络demo场景路径
调整网络demo场景路径
2023-07-27 10:18:02 +08:00
ALEXTANGXIAO
b7b2262d53 合理化服务器命名,使开发者更容易理解。
Scene的routeId更名为locationId
2023-07-27 00:33:39 +08:00
ALEXTANG
d1c93f15d6 Application.OpenURL 调用bat的cmd运行时问题
Application.OpenURL 调用bat的cmd运行时问题
2023-07-26 15:39:20 +08:00
ALEXTANGXIAO
1ac1ff7d56 [+] Update HybridCLR v3.4.0
[+] Update HybridCLR v3.4.0
2023-07-26 00:07:47 +08:00
ALEXTANG
863788f303 Update UIWidget.cs 2023-07-25 23:37:02 +08:00
ALEXTANG
74790c7486 Update UIWindow.cs 2023-07-25 23:34:42 +08:00
ALEXTANG
1c223c8ad0 [+] DOTweenExtension
[+] DOTweenExtension
2023-07-25 17:08:57 +08:00
ALEXTANG
e75b3a4e66 [+] UniTask External YooAsset、Dotween、TextMeshPro 2023-07-25 16:28:09 +08:00
ALEXTANG
91b0995911 [+] UniTask External YooAsset、Dotween、TextMeshPro
[+] UniTask External YooAsset、Dotween、TextMeshPro
2023-07-25 16:22:13 +08:00
ALEXTANG
14c886ea8f [+] UniTask External YooAsset、Dotween、TextMeshPro
[+] UniTask External YooAsset、Dotween、TextMeshPro
2023-07-25 16:20:26 +08:00
148 changed files with 2232 additions and 1353 deletions

View File

@@ -1,5 +1,5 @@
fileFormatVersion: 2
guid: c930bcf75e933064db8511b88e39d216
guid: afddbfe87a53e9049bf031ee18842f87
folderAsset: yes
DefaultImporter:
externalObjects: {}

Binary file not shown.

View File

@@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: 8f3bcefaf67e76141a6d8edeb8354fea
TextScriptImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

Binary file not shown.

View File

@@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: 25113973d38eb5a48b064863830539a4
TextScriptImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

Binary file not shown.

View File

@@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: ef51ed54e72f97a4ab530b932680e08b
TextScriptImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

Binary file not shown.

View File

@@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: 090163c612f34ac4fb80004ac5f057b4
TextScriptImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -64,6 +64,14 @@ namespace TEngine.Core
LoadAssembly(assemblyName, assembly);
}
public static IEnumerable<int> ForEachAssemblyName()
{
foreach (var (key, _) in AssemblyList)
{
yield return key;
}
}
public static IEnumerable<Type> ForEach()
{
foreach (var (_, assemblyInfo) in AssemblyList)

View File

@@ -6,5 +6,7 @@ namespace TEngine.Core
public const uint ErrNotFoundRoute = 100000003; // 没有找到Route消息
public const uint ErrRouteTimeout = 100000004; // 发送Route消息超时
public const uint Error_NotFindEntity = 100000008; // 没有找到Entity
public const uint Error_CopyTimeout = 100000009; // CopyTimeout不能小于或等于0
public const uint Error_Transfer = 100000010;// 传送发生了错误
}
}

View File

@@ -79,6 +79,7 @@ public static class Define
public static readonly HashSet<string> ColTypeSet = new HashSet<string>()
{
"", "0", "bool", "byte", "short", "ushort", "int", "uint", "long", "ulong", "float", "string", "AttrConfig",
"IntDictionaryConfig", "StringDictionaryConfig",
"short[]", "int[]", "long[]", "float[]", "string[]"
};
/// <summary>

View File

@@ -13,6 +13,7 @@ using Newtonsoft.Json;
// ReSharper disable SuspiciousTypeConversion.Global
// ReSharper disable InconsistentNaming
// ReSharper disable ConditionIsAlwaysTrueOrFalseAccordingToNullableAPIContract
namespace TEngine
{
@@ -194,14 +195,14 @@ namespace TEngine
public static T Create<T>(Scene scene, bool isRunEvent = true) where T : Entity, new()
{
var entity = Create<T>(scene.RouteId, isRunEvent);
var entity = Create<T>(scene.LocationId, isRunEvent);
entity.Scene = scene;
return entity;
}
public static T Create<T>(Scene scene, long id, bool isRunEvent = true) where T : Entity, new()
{
var entity = Create<T>(id, scene.RouteId, isRunEvent);
var entity = Create<T>(id, scene.LocationId, isRunEvent);
entity.Scene = scene;
return entity;
}
@@ -235,12 +236,12 @@ namespace TEngine
return entity;
}
private static T Create<T>(long id, uint routeId, bool isRunEvent = true) where T : Entity, new()
protected static T Create<T>(long id, uint locationId, bool isRunEvent = true) where T : Entity, new()
{
return Create<T>(id, IdFactory.NextEntityId(routeId), isRunEvent);
return Create<T>(id, IdFactory.NextEntityId(locationId), isRunEvent);
}
private static T Create<T>(long id, long runtimeId, bool isRunEvent = true) where T : Entity, new()
protected static T Create<T>(long id, long runtimeId, bool isRunEvent = true) where T : Entity, new()
{
var entity = Rent<T>(typeof(T));
entity.Id = id;
@@ -264,13 +265,6 @@ namespace TEngine
return entity;
}
protected static Scene CreateScene(long id, bool isRunEvent = true)
{
var entity = Create<Scene>(id, id, isRunEvent);
entity.Scene = entity;
return entity;
}
#endregion
#region Members
@@ -293,12 +287,12 @@ namespace TEngine
[BsonIgnore]
[JsonIgnore]
[IgnoreDataMember]
public Scene Scene { get; private set; }
public Scene Scene { get; protected set; }
[BsonIgnore]
[JsonIgnore]
[IgnoreDataMember]
public Entity Parent { get; private set; }
public Entity Parent { get; protected set; }
[BsonElement("t")]
[BsonIgnoreIfNull]
@@ -321,7 +315,7 @@ namespace TEngine
public T AddComponent<T>() where T : Entity, new()
{
var entity = Create<T>(Id, Scene.RouteId, false);
var entity = Create<T>(Id, Scene.LocationId, false);
AddComponent(entity);
EntitiesSystem.Instance.Awake(entity);
EntitiesSystem.Instance.StartUpdate(entity);
@@ -330,7 +324,7 @@ namespace TEngine
public T AddComponent<T>(long id) where T : Entity, new()
{
var entity = Create<T>(id, Scene.RouteId, false);
var entity = Create<T>(id, Scene.LocationId, false);
AddComponent(entity);
EntitiesSystem.Instance.Awake(entity);
EntitiesSystem.Instance.StartUpdate(entity);
@@ -409,10 +403,53 @@ namespace TEngine
#endregion
#if TENGINE_NET
#region ForEach
public IEnumerable<Entity> ForEachSingleCollection
{
get
{
foreach (var (_, treeEntity) in _tree)
{
if (treeEntity is not ISupportedSingleCollection)
{
continue;
}
yield return treeEntity;
}
}
}
public IEnumerable<Entity> ForEachTransfer
{
get
{
if (_tree != null)
{
foreach (var (_, treeEntity) in _tree)
{
if (treeEntity is ISupportedSingleCollection || treeEntity is ISupportedTransfer)
{
yield return treeEntity;
}
}
}
if (_multiDb != null)
{
foreach (var treeEntity in _multiDb)
{
if (treeEntity is not ISupportedTransfer)
{
continue;
}
yield return treeEntity;
}
}
}
}
#endregion
#endif
#region GetComponent
public DictionaryPool<Type, Entity> GetTree => _tree;
public T GetComponent<T>() where T : Entity, new()
{
return GetComponent(typeof(T)) as T;
@@ -538,7 +575,7 @@ namespace TEngine
{
Scene = scene;
#if TENGINE_NET
RuntimeId = IdFactory.NextEntityId(scene.RouteId);
RuntimeId = IdFactory.NextEntityId(scene.LocationId);
#else
RuntimeId = IdFactory.NextRunTimeId();
#endif

View File

@@ -0,0 +1,30 @@
// ReSharper disable ConditionIsAlwaysTrueOrFalseAccordingToNullableAPIContract
namespace TEngine
{
public readonly struct EntityReference<T> where T : Entity
{
private readonly T _entity;
private readonly long _runTimeId;
private EntityReference(T t)
{
_entity = t;
_runTimeId = t.RuntimeId;
}
public static implicit operator EntityReference<T>(T t)
{
return new EntityReference<T>(t);
}
public static implicit operator T(EntityReference<T> v)
{
if (v._entity == null)
{
return null;
}
return v._entity.RuntimeId != v._runTimeId ? null : v._entity;
}
}
}

View File

@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: c827c6f914b64f5d9eb0a1f29cc2c018
timeCreated: 1691083017

View File

@@ -0,0 +1,8 @@
#if TENGINE_NET
namespace TEngine;
/// <summary>
/// Entity支持传送。
/// </summary>
public interface ISupportedTransfer { }
#endif

View File

@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 06770f37cdfc480fb0c270ea93a10d26
timeCreated: 1691083054

View File

@@ -9,19 +9,19 @@ using TEngine.Core.DataBase;
#pragma warning disable CS8618
namespace TEngine
{
public sealed class Scene : Entity, INotSupportedPool
public class Scene : Entity, INotSupportedPool
{
public string Name { get; private set; }
public uint RouteId { get; private set; }
public uint LocationId { get; private set; }
#if TENGINE_UNITY
public Session Session { get; private set; }
public SceneConfigInfo SceneInfo { get; private set; }
#endif
#if TENGINE_NET
public int SceneType { get; private set; }
public int SceneSubType { get; private set; }
public World World { get; private set; }
public Server Server { get; private set; }
public uint SceneConfigId { get; private set; }
public SceneConfigInfo SceneInfo => ConfigTableManage.SceneConfig(SceneConfigId);
#endif
public static readonly List<Scene> Scenes = new List<Scene>();
@@ -33,11 +33,12 @@ namespace TEngine
}
Name = null;
RouteId = 0;
this.LocationId = 0;
#if TENGINE_NET
World = null;
Server = null;
SceneConfigId = 0;
SceneType = 0;
SceneSubType = 0;
#endif
#if TENGINE_UNITY
SceneInfo = null;
@@ -59,14 +60,27 @@ namespace TEngine
}
}
#if TENGINE_UNITY
public static Scene Create()
{
var sceneId = IdFactory.NextRunTimeId();
var scene = Create<Scene>(sceneId, sceneId);
scene.Scene = scene;
scene.Parent = scene;
Scenes.Add(scene);
return scene;
}
public static Scene Create(string name)
{
var runTimeId = IdFactory.NextRunTimeId();
var scene = CreateScene(runTimeId);
var sceneId = IdFactory.NextRunTimeId();
var scene = Create<Scene>(sceneId, sceneId);
scene.Scene = scene;
scene.Parent = scene;
scene.Name = name;
Scenes.Add(scene);
return scene;
}
public void CreateSession(string remoteAddress, NetworkProtocolType networkProtocolType, Action onConnectComplete, Action onConnectFail,Action onConnectDisconnect, int connectTimeout = 5000)
{
var address = NetworkHelper.ToIPEndPoint(remoteAddress);
@@ -77,96 +91,96 @@ namespace TEngine
}
#else
/// <summary>
/// 创建一个Scene
/// 创建一个Scene
/// </summary>
/// <param name="server"></param>
/// <param name="outerBindIp"></param>
/// <param name="sceneInfo"></param>
/// <param name="runEvent"></param>
/// <param name="onSetNetworkComplete"></param>
/// <param name="scene"></param>
/// <param name="sceneType"></param>
/// <param name="sceneSubType"></param>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
public static async FTask<Scene> Create(Server server, string outerBindIp, SceneConfigInfo sceneInfo, Action<Session> onSetNetworkComplete = null, bool runEvent = true)
public static async FTask<T> Create<T>(Scene scene, int sceneType, int sceneSubType) where T : Scene, new()
{
var scene = CreateScene(sceneInfo.EntityId);
sceneInfo.Scene = scene;
scene.Name = sceneInfo.Name;
scene.RouteId = sceneInfo.RouteId;
scene.Server = server;
scene.SceneConfigId = sceneInfo.Id;
var newScene = Create<T>(scene);
newScene.Scene = newScene;
newScene.Parent = scene;
newScene.SceneType = sceneType;
newScene.SceneSubType = sceneSubType;
newScene.Server = scene.Server;
newScene.LocationId = scene.Server.Id;
if (sceneInfo.WorldId != 0)
if (scene.World != null)
{
// 有可能不需要数据库、所以这里默认0的情况下就不创建数据库了
scene.World = World.Create(sceneInfo.WorldId);
newScene.World = scene.World;
}
if (!string.IsNullOrEmpty(sceneInfo.NetworkProtocol) && !string.IsNullOrEmpty(outerBindIp) && sceneInfo.OuterPort != 0)
if (sceneType > 0)
{
await EventSystem.Instance.PublishAsync(new OnCreateScene(newScene));
}
Scenes.Add(newScene);
return newScene;
}
/// <summary>
/// 创建一个Scene。
/// </summary>
/// <param name="server"></param>
/// <param name="sceneType"></param>
/// <param name="sceneSubType"></param>
/// <param name="sceneId"></param>
/// <param name="worldId"></param>
/// <param name="networkProtocol"></param>
/// <param name="outerBindIp"></param>
/// <param name="outerPort"></param>
/// <returns></returns>
public static async FTask<Scene> Create(Server server, int sceneType = 0, int sceneSubType = 0, long sceneId = 0, uint worldId = 0, string networkProtocol = null, string outerBindIp = null, int outerPort = 0)
{
if (sceneId == 0)
{
sceneId = new EntityIdStruct(server.Id, 0, 0);
}
var scene = Create<Scene>(sceneId, sceneId);
scene.Scene = scene;
scene.Parent = scene;
scene.SceneType = sceneType;
scene.SceneSubType = sceneSubType;
scene.Server = server;
scene.LocationId = server.Id;
if (worldId != 0)
{
// 有可能不需要数据库、所以这里默认0的情况下就不创建数据库了
scene.World = World.Create(worldId);
}
if (!string.IsNullOrEmpty(networkProtocol) && !string.IsNullOrEmpty(outerBindIp) && outerPort != 0)
{
// 设置Scene的网络、目前只支持KCP和TCP
var networkProtocolType = Enum.Parse<NetworkProtocolType>(sceneInfo.NetworkProtocol);
var networkProtocolType = Enum.Parse<NetworkProtocolType>(networkProtocol);
var serverNetworkComponent = scene.AddComponent<ServerNetworkComponent>();
var address = NetworkHelper.ToIPEndPoint($"{outerBindIp}:{sceneInfo.OuterPort}");
var address = NetworkHelper.ToIPEndPoint($"{outerBindIp}:{outerPort}");
serverNetworkComponent.Initialize(networkProtocolType, NetworkTarget.Outer, address);
}
if (runEvent && sceneInfo.SceneType != null)
if (sceneType > 0)
{
switch (sceneInfo.SceneType)
{
case "Addressable":
{
scene.AddComponent<AddressableManageComponent>();
break;
}
default:
{
// 没有SceneType目前只有代码创建的Scene才会这样、目前只有Server的Scene是这样
await EventSystem.Instance.PublishAsync(new OnCreateScene(sceneInfo, onSetNetworkComplete));
break;
}
}
await EventSystem.Instance.PublishAsync(new OnCreateScene(scene));
}
Scenes.Add(scene);
return scene;
}
/// <summary>
/// 一般用于创建临时Scene、如果不是必要不建议使用这个接口
/// </summary>
/// <param name="name"></param>
/// <param name="server"></param>
/// <param name="entityId"></param>
/// <param name="sceneConfigId"></param>
/// <param name="networkProtocol"></param>
/// <param name="outerBindIp"></param>
/// <param name="outerPort"></param>
/// <param name="runEvent"></param>
/// <param name="onSetNetworkComplete"></param>
/// <returns></returns>
public static async FTask<Scene> Create(string name, Server server, long entityId, uint sceneConfigId = 0, string networkProtocol = null, string outerBindIp = null, int outerPort = 0, Action<Session> onSetNetworkComplete = null, bool runEvent = true)
{
var sceneInfo = new SceneConfigInfo()
{
Name = name,
EntityId = entityId,
Id = sceneConfigId,
NetworkProtocol = networkProtocol,
OuterPort = outerPort,
WorldId = ((EntityIdStruct)entityId).WordId
};
return await Create(server, outerBindIp, sceneInfo, onSetNetworkComplete, runEvent);
}
public static List<SceneConfigInfo> GetSceneInfoByRouteId(uint routeId)
public static List<SceneConfigInfo> GetSceneInfoByServerConfigId(uint serverConfigId)
{
var list = new List<SceneConfigInfo>();
var allSceneConfig = ConfigTableManage.AllSceneConfig();
foreach (var sceneConfigInfo in allSceneConfig)
{
if (sceneConfigInfo.RouteId != routeId)
if (sceneConfigInfo.ServerConfigId != serverConfigId)
{
continue;
}

View File

@@ -5,13 +5,11 @@ namespace TEngine
{
public struct OnCreateScene
{
public readonly SceneConfigInfo SceneInfo;
public readonly Action<Session> OnSetNetworkComplete;
public readonly Scene Scene;
public OnCreateScene(SceneConfigInfo sceneInfo, Action<Session> onSetNetworkComplete)
public OnCreateScene(Scene scene)
{
SceneInfo = sceneInfo;
OnSetNetworkComplete = onSetNetworkComplete;
Scene = scene;
}
}
}

View File

@@ -0,0 +1,89 @@
#if TENGINE_NET
using System.Text;
using TEngine.Core;
using TEngine.Helper;
namespace TEngine.CustomExport;
public sealed class SceneTypeConfigToEnum : ACustomExport
{
public override void Run()
{
var fullPath = FileHelper.GetFullPath("../../../Config/Excel/Server/SceneConfig.xlsx");
using var excelPackage = ExcelHelper.LoadExcel(fullPath);
var sceneType = new Dictionary<string, string>();
var sceneSubType = new Dictionary<string, string>();
var sceneTypeConfig = excelPackage.Workbook.Worksheets["SceneTypeConfig"];
for (var row = 3; row <= sceneTypeConfig.Dimension.Rows; row++)
{
var sceneTypeId = sceneTypeConfig.GetCellValue(row, 1);
var sceneTypeStr = sceneTypeConfig.GetCellValue(row, 2);
if (string.IsNullOrEmpty(sceneTypeId) || string.IsNullOrEmpty(sceneTypeStr))
{
continue;
}
sceneType.Add(sceneTypeId, sceneTypeStr);
}
var sceneSubTypeConfig = excelPackage.Workbook.Worksheets["SceneSubTypeConfig"];
for (var row = 3; row <= sceneSubTypeConfig.Dimension.Rows; row++)
{
var sceneSubTypeId = sceneSubTypeConfig.GetCellValue(row, 1);
var sceneSubTypeStr = sceneSubTypeConfig.GetCellValue(row, 2);
if (string.IsNullOrEmpty(sceneSubTypeId) || string.IsNullOrEmpty(sceneSubTypeStr))
{
continue;
}
sceneSubType.Add(sceneSubTypeId, sceneSubTypeStr);
}
if (sceneType.Count > 0 || sceneSubType.Count > 0)
{
Write(CustomExportType.Server, sceneType, sceneSubType);
}
}
private void Write(CustomExportType customExportType, Dictionary<string, string> sceneTypes, Dictionary<string, string> sceneSubType)
{
var strBuilder = new StringBuilder();
var dicBuilder = new StringBuilder();
strBuilder.AppendLine("namespace TEngine\n{");
strBuilder.AppendLine("\t// 生成器自动生成,请不要手动编辑。");
strBuilder.AppendLine("\tpublic static class SceneType\n\t{");
dicBuilder.AppendLine("\n\t\tpublic static readonly Dictionary<string, int> SceneTypeDic = new Dictionary<string, int>()\n\t\t{");
foreach (var (sceneTypeId, sceneTypeStr) in sceneTypes)
{
dicBuilder.AppendLine($"\t\t\t{{ \"{sceneTypeStr}\", {sceneTypeId} }},");
strBuilder.AppendLine($"\t\tpublic const int {sceneTypeStr} = {sceneTypeId};");
}
dicBuilder.AppendLine("\t\t};");
strBuilder.Append(dicBuilder);
strBuilder.AppendLine("\t}\n");
strBuilder.AppendLine("\t// 生成器自动生成,请不要手动编辑。");
strBuilder.AppendLine("\tpublic static class SceneSubType\n\t{");
dicBuilder.Clear();
dicBuilder.AppendLine("\n\t\tpublic static readonly Dictionary<string, int> SceneSubTypeDic = new Dictionary<string, int>()\n\t\t{");
foreach (var (sceneSubTypeId, sceneSubTypeStr) in sceneSubType)
{
dicBuilder.AppendLine($"\t\t\t{{ \"{sceneSubTypeStr}\", {sceneSubTypeId} }},");
strBuilder.AppendLine($"\t\tpublic const int {sceneSubTypeStr} = {sceneSubTypeId};");
}
dicBuilder.AppendLine("\t\t};");
strBuilder.Append(dicBuilder);
strBuilder.AppendLine("\t}\n}");
Write("SceneType.cs", strBuilder.ToString(), customExportType);
}
}
#endif

View File

@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: d254c1aefb624046ab545bd8cebbe57c
timeCreated: 1690561569

View File

@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 2da9efac32374cb1a88c500e7ed43344
timeCreated: 1691084274

View File

@@ -0,0 +1,32 @@
using System.Collections.Generic;
using ProtoBuf;
namespace TEngine.Core
{
[ProtoContract]
public class IntDictionaryConfig
{
[ProtoMember(1, IsRequired = true)]
public Dictionary<int, int> Dic;
public int this[int key] => GetValue(key);
public bool TryGetValue(int key, out int value)
{
value = default;
if (!Dic.ContainsKey(key))
{
return false;
}
value = Dic[key];
return true;
}
private int GetValue(int key)
{
return Dic.TryGetValue(key, out var value) ? value : default;
}
}
}

View File

@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 34b41344fd6e462bae371207cdf8a5cd
timeCreated: 1691084286

View File

@@ -0,0 +1,32 @@
using System.Collections.Generic;
using ProtoBuf;
namespace TEngine.Core
{
[ProtoContract]
public sealed class StringDictionaryConfig
{
[ProtoMember(1, IsRequired = true)]
public Dictionary<int, string> Dic;
public string this[int key] => GetValue(key);
public bool TryGetValue(int key, out string value)
{
value = default;
if (!Dic.ContainsKey(key))
{
return false;
}
value = Dic[key];
return true;
}
private string GetValue(int key)
{
return Dic.TryGetValue(key, out var value) ? value : default;
}
}
}

View File

@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: a26ad73832de4b3e986ddb58426bcced
timeCreated: 1691084294

View File

@@ -4,17 +4,12 @@ using System.Reflection;
using System.Runtime.Loader;
using System.Text;
using System.Text.RegularExpressions;
using TEngine.CustomExport;
using TEngine.DataStructure;
using TEngine.Core;
using Newtonsoft.Json;
using OfficeOpenXml;
using TEngine.Helper;
using static System.String;
#pragma warning disable CS8625
#pragma warning disable CS8604
#pragma warning disable CS8602
#pragma warning disable CS8601
#pragma warning disable CS8600
#pragma warning disable CS8618
namespace TEngine.Core;
@@ -29,9 +24,13 @@ public sealed class ExcelExporter
private readonly ConcurrentDictionary<string, ExcelTable> _excelTables = new ConcurrentDictionary<string, ExcelTable>();
private readonly ConcurrentDictionary<string, ExcelWorksheet> _worksheets = new ConcurrentDictionary<string, ExcelWorksheet>();
public ExcelExporter(ExportType exportType)
static ExcelExporter()
{
ExcelPackage.LicenseContext = LicenseContext.NonCommercial;
}
public ExcelExporter(ExportType exportType)
{
var versionFilePath = Define.ExcelVersionFile;
switch (exportType)
@@ -87,6 +86,9 @@ public sealed class ExcelExporter
}
}
// 添加生成SceneType的自定义导出
task.Add(Task.Run(new SceneTypeConfigToEnum().Run));
Task.WaitAll(task.ToArray());
}
@@ -226,7 +228,7 @@ public sealed class ExcelExporter
{
// 列名字第一个字符是#不参与导出
var colName = GetCellValue(worksheet, 5, col);
var colName = worksheet.GetCellValue(5, col);
if (colName.StartsWith("#", StringComparison.Ordinal))
{
continue;
@@ -234,14 +236,14 @@ public sealed class ExcelExporter
// 数值列不参与导出
var numericalCol = GetCellValue(worksheet, 3, col);
var numericalCol = worksheet.GetCellValue(3, col);
if (numericalCol != "" && numericalCol != "0")
{
continue;
}
var serverType = GetCellValue(worksheet, 1, col);
var clientType = GetCellValue(worksheet, 2, col);
var serverType = worksheet.GetCellValue(1, col);
var clientType = worksheet.GetCellValue(2, col);
var isExportServer = !IsNullOrEmpty(serverType) && serverType != "0";
var isExportClient = !IsNullOrEmpty(clientType) && clientType != "0";
@@ -350,7 +352,7 @@ public sealed class ExcelExporter
foreach (var colIndex in cols)
{
var colName = GetCellValue(excelWorksheet, 5, colIndex);
var colName = excelWorksheet.GetCellValue(5, colIndex);
if (colNameSet.Contains(colName))
{
@@ -363,19 +365,19 @@ public sealed class ExcelExporter
if (isServer)
{
colType = GetCellValue(excelWorksheet, 1, colIndex);
colType = excelWorksheet.GetCellValue(1, colIndex);
if (IsNullOrEmpty(colType) || colType == "0")
{
colType = GetCellValue(excelWorksheet, 2, colIndex);
colType = excelWorksheet.GetCellValue(2, colIndex);
}
}
else
{
colType = GetCellValue(excelWorksheet, 2, colIndex);
colType = excelWorksheet.GetCellValue(2, colIndex);
}
var remarks = GetCellValue(excelWorksheet, 4, colIndex);
var remarks = excelWorksheet.GetCellValue(4, colIndex);
fileBuilder.Append($"\n\t\t[ProtoMember({++index}, IsRequired = true)]\n");
fileBuilder.Append(
@@ -436,12 +438,12 @@ public sealed class ExcelExporter
for (var row = 7; row <= rows; row++)
{
if (GetCellValue(excelWorksheet, row, 1).StartsWith("#", StringComparison.Ordinal))
if (excelWorksheet.GetCellValue(row, 1).StartsWith("#", StringComparison.Ordinal))
{
continue;
}
var id = GetCellValue(excelWorksheet, row, 3);
var id = excelWorksheet.GetCellValue(row, 3);
if (idCheck.Contains(id))
{
@@ -525,21 +527,21 @@ public sealed class ExcelExporter
{
string colType;
var colIndex = cols[i];
var colName = GetCellValue(excelWorksheet, 5, colIndex);
var value = GetCellValue(excelWorksheet, row, colIndex);
var colName = excelWorksheet.GetCellValue(5, colIndex);
var value = excelWorksheet.GetCellValue(row, colIndex);
if (isServer)
{
colType = GetCellValue(excelWorksheet, 1, colIndex);
colType = excelWorksheet.GetCellValue(1, colIndex);
if (IsNullOrEmpty(colType) || colType == "0")
{
colType = GetCellValue(excelWorksheet, 2, colIndex);
colType = excelWorksheet.GetCellValue(2, colIndex);
}
}
else
{
colType = GetCellValue(excelWorksheet, 2, colIndex);
colType = excelWorksheet.GetCellValue(2, colIndex);
}
try
@@ -574,7 +576,7 @@ public sealed class ExcelExporter
return worksheet;
}
worksheet = new ExcelPackage(name).Workbook.Worksheets[0];
worksheet = ExcelHelper.LoadExcel(name).Workbook.Worksheets[0];
if (isAddToDic)
{
@@ -585,26 +587,6 @@ public sealed class ExcelExporter
return worksheet;
}
private string GetCellValue(ExcelWorksheet sheet, int row, int column)
{
var cell = sheet.Cells[row, column];
try
{
if (cell.Value == null)
{
return "";
}
var s = cell.GetValue<string>();
return s.Trim();
}
catch (Exception e)
{
throw new Exception($"Rows {row} Columns {column} Content {cell.Text} {e}");
}
}
private void SetNewValue(PropertyInfo propertyInfo, AProto config, string type, string value)
{
if (IsNullOrWhiteSpace(value))
@@ -753,20 +735,34 @@ public sealed class ExcelExporter
return;
}
// case "AttrConfig":
// {
// if (value.Trim() == "" || value.Trim() == "{}")
// {
// propertyInfo.SetValue(config, null);
// return;
// }
//
// var attr = new AttrConfig {KV = JsonConvert.DeserializeObject<Dictionary<int, int>>(value)};
//
// propertyInfo.SetValue(config, attr);
//
// return;
// }
case "IntDictionaryConfig":
{
if (value.Trim() == "" || value.Trim() == "{}")
{
propertyInfo.SetValue(config, null);
return;
}
var attr = new IntDictionaryConfig {Dic = JsonConvert.DeserializeObject<Dictionary<int, int>>(value)};
propertyInfo.SetValue(config, attr);
return;
}
case "StringDictionaryConfig":
{
if (value.Trim() == "" || value.Trim() == "{}")
{
propertyInfo.SetValue(config, null);
return;
}
var attr = new StringDictionaryConfig {Dic = JsonConvert.DeserializeObject<Dictionary<int, string>>(value)};
propertyInfo.SetValue(config, attr);
return;
}
default:
throw new NotSupportedException($"不支持此类型: {type}");
}

View File

@@ -33,8 +33,6 @@ namespace TEngine.Core
{
var configFile = GetConfigPath(dataConfig);
var bytes = File.ReadAllBytes(configFile);
// var data = (AProto) ProtoBufHelper.FromBytes(typeof(T), bytes, 0, bytes.Length);
// var data = ProtoBufHelper.FromBytes<T>(bytes, 0, bytes.Length);
var data = (T)ProtoBufHelper.FromBytes(typeof(T), bytes, 0, bytes.Length);
data.AfterDeserialization();
ConfigDic[dataConfig] = data;

View File

@@ -25,8 +25,8 @@ public sealed class Exporter
LogInfo("请输入你想要做的操作:");
LogInfo("1:导出网络协议ProtoBuf");
LogInfo("2:增量导出Excel包含常量枚举");
LogInfo("3:全量导出Excel包含常量枚举");
LogInfo("2:增量导出服务器启动Excel包含常量枚举");
LogInfo("3:全量导出服务器启动Excel包含常量枚举");
var keyChar = Console.ReadKey().KeyChar;

View File

@@ -424,7 +424,9 @@ public sealed class ProtoBufExporter
"int32[]" => "int[] { }",
"int64[]" => "long[] { }",
"int32" => "int",
"uint32" => "uint",
"int64" => "long",
"uint64" => "ulong",
_ => type
};
}

View File

@@ -0,0 +1,34 @@
#if TENGINE_NET
using OfficeOpenXml;
namespace TEngine.Helper;
public static class ExcelHelper
{
public static ExcelPackage LoadExcel(string name)
{
return new ExcelPackage(name);
}
public static string GetCellValue(this ExcelWorksheet sheet, int row, int column)
{
ExcelRange cell = sheet.Cells[row, column];
try
{
if (cell.Value == null)
{
return "";
}
string s = cell.GetValue<string>();
return s.Trim();
}
catch (Exception e)
{
throw new Exception($"Rows {row} Columns {column} Content {cell.Text} {e}");
}
}
}
#endif

View File

@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 2ea3356f30cb40949949691a0e258a05
timeCreated: 1690561972

View File

@@ -5,6 +5,16 @@ namespace TEngine.Core
{
public static class FileHelper
{
/// <summary>
/// 获取文件全路径。
/// </summary>
/// <param name="relativePath"></param>
/// <returns></returns>
public static string GetFullPath(string relativePath)
{
return Path.GetFullPath(Path.Combine(Directory.GetCurrentDirectory(), relativePath));
}
/// <summary>
/// 拷贝文件到目标路径、如果目标目录不存在会自动创建目录
/// </summary>

View File

@@ -179,9 +179,8 @@ public sealed class MongoHelper : Singleton<MongoHelper>
public void SerializeTo<T>(T t, MemoryStream stream)
{
var bytes = t.ToBson();
stream.Write(bytes, 0, bytes.Length);
using var writer = new BsonBinaryWriter(stream, BsonBinaryWriterSettings.Defaults);
BsonSerializer.Serialize(writer, typeof(T), t);
}
public T Clone<T>(T t)

View File

@@ -14,26 +14,26 @@ namespace TEngine.Core
public uint Time{ get; private set; }
public uint Sequence{ get; private set; }
public uint RouteId { get; private set; }
public uint LocationId { get; private set; }
public ushort AppId => (ushort)(RouteId >> 10 & RouteIdStruct.MaskAppId);
public ushort WordId=> (ushort)(RouteId & RouteIdStruct.MaskWordId);
public ushort AppId => (ushort)(this.LocationId >> 10 & RouteIdStruct.MaskAppId);
public ushort WordId=> (ushort)(this.LocationId & RouteIdStruct.MaskWordId);
public const int MaskRouteId = 0x3FFFF;
public const int MaskSequence = 0xFFFF;
public EntityIdStruct(uint routeId, uint time, uint sequence)
public EntityIdStruct(uint locationId, uint time, uint sequence)
{
Time = time;
Sequence = sequence;
RouteId = routeId;
LocationId = locationId;
}
public static implicit operator long(EntityIdStruct entityIdStruct)
{
ulong result = 0;
result |= entityIdStruct.Sequence;
result |= (ulong)entityIdStruct.RouteId << 16;
result |= (ulong)entityIdStruct.LocationId << 16;
result |= (ulong)entityIdStruct.Time << 34;
return (long)result;
}
@@ -46,7 +46,7 @@ namespace TEngine.Core
Sequence = (uint) (result & MaskSequence)
};
result >>= 16;
idStruct.RouteId = (uint) (result & 0x3FFFF);
idStruct.LocationId = (uint) (result & 0x3FFFF);
result >>= 18;
idStruct.Time = (uint) result;
return idStruct;

View File

@@ -32,7 +32,7 @@ namespace TEngine.Core
return new RuntimeIdStruct(_lastRunTimeIdTime, _lastRunTimeIdSequence);
}
public static long NextEntityId(uint routeId)
public static long NextEntityId(uint locationId)
{
var time = (uint)((TimeHelper.Now - Epoch2023) / 1000);
@@ -47,7 +47,7 @@ namespace TEngine.Core
_lastEntityIdSequence = 0;
}
return new EntityIdStruct(routeId, _lastEntityIdTime, _lastEntityIdSequence);
return new EntityIdStruct(locationId, _lastEntityIdTime, _lastEntityIdSequence);
}
public static uint GetRouteId(long entityId)

View File

@@ -51,7 +51,7 @@ public class SessionIdleCheckerComponent: Entity
return;
}
Log.Warning($"session timeout id:{Id}");
Log.Warning($"session timeout id:{Id} timeNow:{timeNow} _session.LastReceiveTime:{_session.LastReceiveTime} _timeOut:{_timeOut}");
_session.Dispose();
}
}

View File

@@ -2,16 +2,16 @@ namespace TEngine
{
public class SceneConfigInfo
{
public Scene Scene;
public long EntityId;
public uint Id;
public string SceneType;
public string Name;
public string NetworkProtocol;
public uint RouteId;
public long EntityId;
public int SceneType;
public int SceneSubType;
public string SceneTypeStr;
public string SceneSubTypeStr;
public uint ServerConfigId;
public uint WorldId;
public int OuterPort;
public string NetworkProtocol;
}
}

View File

@@ -103,13 +103,13 @@ namespace TEngine
private static readonly Dictionary<uint, Server> Servers = new Dictionary<uint, Server>();
public static async FTask Create(uint routeId)
public static async FTask Create(uint serverConfigId)
{
var serverConfigInfo = ConfigTableManage.ServerConfig(routeId);
var serverConfigInfo = ConfigTableManage.ServerConfig(serverConfigId);
if (serverConfigInfo == null)
{
Log.Error($"not found server by Id:{routeId}");
Log.Error($"not found server by Id:{serverConfigId}");
return;
}
@@ -121,14 +121,14 @@ namespace TEngine
return;
}
var sceneInfos = Scene.GetSceneInfoByRouteId(routeId);
await Create(routeId, machineConfigInfo.InnerBindIP, serverConfigInfo.InnerPort, machineConfigInfo.OuterBindIP, sceneInfos);
// Log.Info($"ServerId:{routeId} is start complete");
var sceneInfos = Scene.GetSceneInfoByServerConfigId(serverConfigId);
await Create(serverConfigId, machineConfigInfo.InnerBindIP, serverConfigInfo.InnerPort, machineConfigInfo.OuterBindIP, sceneInfos);
// Log.Info($"ServerId:{serverConfigId} is start complete");
}
public static async FTask<Server> Create(uint routeId, string innerBindIp, int innerPort, string outerBindIp, List<SceneConfigInfo> sceneInfos)
public static async FTask<Server> Create(uint serverConfigId, string innerBindIp, int innerPort, string outerBindIp, List<SceneConfigInfo> sceneInfos)
{
if (Servers.TryGetValue(routeId, out var server))
if (Servers.TryGetValue(serverConfigId, out var server))
{
return server;
}
@@ -137,10 +137,10 @@ namespace TEngine
server = new Server
{
Id = routeId
Id = serverConfigId
};
server.Scene = await Scene.Create($"ServerScene{routeId}", server, new EntityIdStruct(routeId, 0, 0));
server.Scene = await Scene.Create(server);
// 创建网络、Server下的网络只能是内部网络、外部网络是在Scene中定义
@@ -155,16 +155,17 @@ namespace TEngine
foreach (var sceneConfig in sceneInfos)
{
await Scene.Create(server, outerBindIp, sceneConfig);
await Scene.Create(server, sceneConfig.SceneType, sceneConfig.SceneSubType, sceneConfig.EntityId,
sceneConfig.WorldId, sceneConfig.NetworkProtocol, outerBindIp, sceneConfig.OuterPort);
}
Servers.Add(routeId, server);
Servers.Add(serverConfigId, server);
return server;
}
public static Server Get(uint routeId)
public static Server Get(uint serverConfigId)
{
return Servers.TryGetValue(routeId, out var server) ? server : null;
return Servers.TryGetValue(serverConfigId, out var server) ? server : null;
}
#endregion

View File

@@ -12,22 +12,21 @@ namespace TEngine.Core.Network
foreach (var sceneConfigInfo in sceneConfigInfos)
{
if (sceneConfigInfo.SceneType == "Addressable")
if (sceneConfigInfo.SceneTypeStr == "Addressable")
{
AddressableScenes.Add(sceneConfigInfo);
}
}
}
public static async FTask AddAddressable(Scene scene, long addressableId, long routeId)
public static async FTask AddAddressable(Scene scene, long addressableId, long routeId, bool isLock = true)
{
var addressableScene = AddressableScenes[(int)addressableId % AddressableScenes.Count];
var response = await MessageHelper.CallInnerRoute(scene, addressableScene.EntityId,
new I_AddressableAdd_Request
{
AddressableId = addressableId, RouteId = routeId
AddressableId = addressableId, RouteId = routeId, IsLock = isLock
});
if (response.ErrorCode != 0)
{
Log.Error($"AddAddressable error is {response.ErrorCode}");

View File

@@ -1,3 +1,4 @@
using System;
using System.Collections.Generic;
namespace TEngine.Core.Network
@@ -8,13 +9,28 @@ namespace TEngine.Core.Network
private readonly Dictionary<long, WaitCoroutineLock> _locks = new();
private readonly CoroutineLockQueueType _addressableLock = new CoroutineLockQueueType("AddressableLock");
public async FTask Add(long addressableId, long routeId)
public async FTask Add(long addressableId, long routeId, bool isLock)
{
using (await _addressableLock.Lock(addressableId))
WaitCoroutineLock waitCoroutineLock = null;
try
{
if (isLock)
{
waitCoroutineLock = await _addressableLock.Lock(addressableId);
}
_addressable[addressableId] = routeId;
Log.Debug($"AddressableManageComponent Add addressableId:{addressableId} routeId:{routeId}");
}
catch (Exception e)
{
Log.Error(e);
}
finally
{
waitCoroutineLock?.Dispose();
}
}
public async FTask<long> Get(long addressableId)
@@ -31,6 +47,7 @@ namespace TEngine.Core.Network
using (await _addressableLock.Lock(addressableId))
{
_addressable.Remove(addressableId);
Log.Debug($"Addressable Remove addressableId: {addressableId} _addressable:{_addressable.Count}");
}
}

View File

@@ -19,7 +19,7 @@ namespace TEngine.Core.Network
base.Dispose();
}
public FTask Register()
public FTask Register(bool isLock = true)
{
if (Parent == null)
{
@@ -36,7 +36,7 @@ namespace TEngine.Core.Network
#if TENGINE_DEVELOP
Log.Debug($"AddressableMessageComponent Register addressableId:{AddressableId} RouteId:{Parent.RuntimeId}");
#endif
return AddressableHelper.AddAddressable(Scene, AddressableId, Parent.RuntimeId);
return AddressableHelper.AddAddressable(Scene, AddressableId, Parent.RuntimeId, isLock);
}
public FTask Lock()

View File

@@ -5,7 +5,7 @@ public sealed class I_AddressableAddHandler : RouteRPC<Scene, I_AddressableAdd_R
{
protected override async FTask Run(Scene scene, I_AddressableAdd_Request request, I_AddressableAdd_Response response, Action reply)
{
await scene.GetComponent<AddressableManageComponent>().Add(request.AddressableId, request.RouteId);
await scene.GetComponent<AddressableManageComponent>().Add(request.AddressableId, request.RouteId, request.IsLock);
}
}
#endif

View File

@@ -41,7 +41,7 @@ namespace TEngine.Core.Network
scene = entity.Scene;
}
Log.Error($"SceneWorld:{session.Scene.World.Id} SceneRouteId:{scene.RouteId} SceneType:{scene.SceneInfo.SceneType} EntityId {tEntity.Id} : Error {e}");
Log.Error($"SceneWorld:{session.Scene.World.Id} ServerConfigId:{scene.Server?.Id} SceneType:{scene.SceneType} EntityId {tEntity.Id} : Error {e}");
}
}
@@ -100,7 +100,7 @@ namespace TEngine.Core.Network
scene = entity.Scene;
}
Log.Error($"SceneWorld:{session.Scene.World.Id} SceneRouteId:{scene.RouteId} SceneType:{scene.SceneInfo.SceneType} EntityId {tEntity.Id} : Error {e}");
Log.Error($"SceneWorld:{session.Scene.World?.Id} ServerConfigId:{scene.Server?.Id} SceneType:{scene.SceneType} EntityId {tEntity.Id} : Error {e}");
response.ErrorCode = CoreErrorCode.ErrRpcFail;
}
finally
@@ -144,7 +144,7 @@ namespace TEngine.Core.Network
scene = entity.Scene;
}
Log.Error($"SceneWorld:{session.Scene.World?.Id} SceneRouteId:{scene.RouteId} SceneType:{scene.SceneInfo.SceneType} EntityId {tEntity.Id} : Error {e}");
Log.Error($"SceneWorld:{session.Scene.World.Id} ServerConfigId:{scene.Server?.Id} SceneType:{scene.SceneType} EntityId {tEntity.Id} : Error {e}");
}
finally
{
@@ -207,7 +207,7 @@ namespace TEngine.Core.Network
scene = entity.Scene;
}
Log.Error($"SceneWorld:{session.Scene.World.Id} SceneRouteId:{scene.RouteId} SceneType:{scene.SceneInfo.SceneType} EntityId {tEntity.Id} : Error {e}");
Log.Error($"SceneWorld:{session.Scene.World?.Id} ServerConfigId:{scene.Server?.Id} SceneType:{scene.SceneType} EntityId {tEntity.Id} : Error {e}");
response.ErrorCode = CoreErrorCode.ErrRpcFail;
}
finally

View File

@@ -78,7 +78,7 @@ namespace TEngine.Core.Network
{
if (DisposePackInfo)
{
packInfo.Dispose();
NetworkThread.Instance.SynchronizationContext.Post(packInfo.Dispose);
}
}
}

View File

@@ -35,7 +35,7 @@ public static class MessageHelper
}
EntityIdStruct entityIdStruct = entityId;
var session = scene.Server.GetSession(entityIdStruct.RouteId);
var session = scene.Server.GetSession(entityIdStruct.LocationId);
session.Send(message, 0, entityId);
}
@@ -48,7 +48,7 @@ public static class MessageHelper
}
EntityIdStruct entityIdStruct = entityId;
var session = scene.Server.GetSession(entityIdStruct.RouteId);
var session = scene.Server.GetSession(entityIdStruct.LocationId);
session.Send(message, 0, routeTypeOpCode, entityId);
}
@@ -81,7 +81,7 @@ public static class MessageHelper
EntityIdStruct entityIdStruct = entityId;
var rpcId = ++_rpcId;
var session = scene.Server.GetSession(entityIdStruct.RouteId);
var session = scene.Server.GetSession(entityIdStruct.LocationId);
var requestCallback = FTask<IResponse>.Create(false);
RequestCallback.Add(rpcId, MessageSender.Create(rpcId, requestType, requestCallback));
session.Send(request, rpcId, routeTypeOpCode, entityId);
@@ -98,7 +98,7 @@ public static class MessageHelper
EntityIdStruct entityIdStruct = entityId;
var rpcId = ++_rpcId;
var session = scene.Server.GetSession(entityIdStruct.RouteId);
var session = scene.Server.GetSession(entityIdStruct.LocationId);
var requestCallback = FTask<IResponse>.Create(false);
RequestCallback.Add(rpcId, MessageSender.Create(rpcId, request, requestCallback));
session.Send(request, rpcId, entityId);

View File

@@ -63,6 +63,8 @@ namespace TEngine
public long AddressableId { get; set; }
[ProtoMember(2)]
public long RouteId { get; set; }
[ProtoMember(3)]
public bool IsLock { get; set; }
}
[ProtoContract]
public partial class I_AddressableAdd_Response : AProto, IRouteResponse

View File

@@ -46,7 +46,7 @@ namespace TEngine.Core.Network
}
finally
{
packInfo.Dispose();
NetworkThread.Instance.SynchronizationContext.Post(packInfo.Dispose);
}
await FTask.CompletedTask;

View File

@@ -103,7 +103,7 @@ namespace TEngine.Core.Network
}
finally
{
packInfo.Dispose();
NetworkThread.Instance.SynchronizationContext.Post(packInfo.Dispose);
}
}

View File

@@ -120,7 +120,7 @@ namespace TEngine.Core.Network
}
finally
{
packInfo.Dispose();
NetworkThread.Instance.SynchronizationContext.Post(packInfo.Dispose);
}
throw new NotSupportedException($"Received unsupported message protocolCode:{packInfo.ProtocolCode} messageType:{messageType}");

View File

@@ -1,6 +1,8 @@
#if TENGINE_NET
using System.Buffers;
using TEngine.DataStructure;
using MongoDB.Bson.Serialization;
using MongoDB.Bson.Serialization.Serializers;
// ReSharper disable ConditionIsAlwaysTrueOrFalseAccordingToNullableAPIContract
namespace TEngine.Core.Network;
@@ -199,8 +201,17 @@ public sealed class InnerPacketParser : APacketParser
{
if (message is IBsonMessage)
{
try
{
MongoHelper.Instance.SerializeTo(message, memoryStream);
}
catch (Exception e)
{
Log.Fatal(e);
throw;
}
}
else
{
ProtoBufHelper.ToStream(message, memoryStream);

View File

@@ -92,7 +92,7 @@ public class SingleCollection : Singleton<SingleCollection>
using var collections = ListPool<Entity>.Create();
foreach (var (_, treeEntity) in entity.GetTree)
foreach (var treeEntity in entity.ForEachSingleCollection)
{
if (treeEntity is not ISupportedSingleCollection)
{

View File

@@ -36,46 +36,41 @@ public static class TEngineSettingsHelper
private static void LoadProtoConfig(IConfigurationRoot root)
{
// ProtoBuf文件所在的位置文件夹位置
Define.ProtoBufDirectory = root["Export:ProtoBufDirectory:Value"].GetFullPath();
Define.ProtoBufDirectory = FileHelper.GetFullPath(root["Export:ProtoBufDirectory:Value"]);
// ProtoBuf生成到服务端的文件夹位置
Define.ProtoBufServerDirectory = root["Export:ProtoBufServerDirectory:Value"].GetFullPath();
Define.ProtoBufServerDirectory = FileHelper.GetFullPath(root["Export:ProtoBufServerDirectory:Value"]);
// ProtoBuf生成到客户端的文件夹位置
Define.ProtoBufClientDirectory = root["Export:ProtoBufClientDirectory:Value"].GetFullPath();
Define.ProtoBufClientDirectory = FileHelper.GetFullPath(root["Export:ProtoBufClientDirectory:Value"]);
// ProtoBuf生成代码模板的位置
Define.ProtoBufTemplatePath = root["Export:ProtoBufTemplatePath:Value"].GetFullPath();
Define.ProtoBufTemplatePath = FileHelper.GetFullPath(root["Export:ProtoBufTemplatePath:Value"]);
}
private static void LoadExcelConfig(IConfigurationRoot root)
{
// Excel配置文件根目录
Define.ExcelProgramPath = root["Export:ExcelProgramPath:Value"].GetFullPath();
Define.ExcelProgramPath = FileHelper.GetFullPath(root["Export:ExcelProgramPath:Value"]);
// Excel版本文件的位置
Define.ExcelVersionFile = root["Export:ExcelVersionFile:Value"].GetFullPath();
Define.ExcelVersionFile = FileHelper.GetFullPath(root["Export:ExcelVersionFile:Value"]);
// Excel生成服务器代码的文件夹位置
Define.ExcelServerFileDirectory = root["Export:ExcelServerFileDirectory:Value"].GetFullPath();
Define.ExcelServerFileDirectory = FileHelper.GetFullPath(root["Export:ExcelServerFileDirectory:Value"]);
// Excel生成客户端代码文件夹位置
Define.ExcelClientFileDirectory = root["Export:ExcelClientFileDirectory:Value"].GetFullPath();
Define.ExcelClientFileDirectory = FileHelper.GetFullPath(root["Export:ExcelClientFileDirectory:Value"]);
// Excel生成服务器二进制数据文件夹位置
Define.ExcelServerBinaryDirectory = root["Export:ExcelServerBinaryDirectory:Value"].GetFullPath();
Define.ExcelServerBinaryDirectory = FileHelper.GetFullPath(root["Export:ExcelServerBinaryDirectory:Value"]);
// Excel生成客户端二进制数据文件夹位置
Define.ExcelClientBinaryDirectory = root["Export:ExcelClientBinaryDirectory:Value"].GetFullPath();
Define.ExcelClientBinaryDirectory = FileHelper.GetFullPath(root["Export:ExcelClientBinaryDirectory:Value"]);
// Excel生成服务器Json数据文件夹位置
Define.ExcelServerJsonDirectory = root["Export:ExcelServerJsonDirectory:Value"].GetFullPath();
Define.ExcelServerJsonDirectory = FileHelper.GetFullPath(root["Export:ExcelServerJsonDirectory:Value"]);
// Excel生成客户端Json数据文件夹位置
Define.ExcelClientJsonDirectory = root["Export:ExcelClientJsonDirectory:Value"].GetFullPath();
Define.ExcelClientJsonDirectory = FileHelper.GetFullPath(root["Export:ExcelClientJsonDirectory:Value"]);
// Excel生成代码模板的位置
Define.ExcelTemplatePath = root["Export:ExcelTemplatePath:Value"].GetFullPath();
Define.ExcelTemplatePath = FileHelper.GetFullPath(root["Export:ExcelTemplatePath:Value"]);
// 服务器自定义导出代码文件夹位置
Define.ServerCustomExportDirectory = root["Export:ServerCustomExportDirectory:Value"].GetFullPath();
Define.ServerCustomExportDirectory = FileHelper.GetFullPath(root["Export:ServerCustomExportDirectory:Value"]);
// 客户端自定义导出代码
Define.ClientCustomExportDirectory = root["Export:ClientCustomExportDirectory:Value"].GetFullPath();
Define.ClientCustomExportDirectory = FileHelper.GetFullPath(root["Export:ClientCustomExportDirectory:Value"]);
// 自定义导出代码存放的程序集
Define.CustomExportAssembly = root["Export:CustomExportAssembly:Value"].GetFullPath();
}
private static string GetFullPath(this string relativePath)
{
return Path.GetFullPath(Path.Combine(Directory.GetCurrentDirectory(), relativePath));
Define.CustomExportAssembly = FileHelper.GetFullPath(root["Export:CustomExportAssembly:Value"]);
}
}
#endif

View File

@@ -35,7 +35,7 @@ public partial class GameApp:Singleton<GameApp>
/// </summary>
private void StartGameLogic()
{
GameModule.UI.ShowUIAsync<NetWorkDemoUI>();
}
/// <summary>

View File

@@ -51,7 +51,7 @@ public class ConfigLoader:Singleton<ConfigLoader>
#if UNITY_EDITOR
var ret = File.ReadAllText($"{Application.dataPath}/../GenerateDatas/json/{file}.json", System.Text.Encoding.UTF8);
#else
var textAssets = GameModule.Resource.LoadAsset<TextAsset>($"{SettingsUtils.FrameworkGlobalSettings.ConfigFolderName}{file}.json");
var textAssets = GameModule.Resource.LoadAsset<TextAsset>(file);
var ret = textAssets.text;
#endif
return JSON.Parse(ret);
@@ -68,7 +68,7 @@ public class ConfigLoader:Singleton<ConfigLoader>
#if UNITY_EDITOR
ret = File.ReadAllBytes($"{Application.dataPath}/../GenerateDatas/bytes/{file}.bytes");
#else
var textAssets = GameModule.Resource.LoadAsset<TextAsset>($"{SettingsUtils.FrameworkGlobalSettings.ConfigFolderName}{file}.bytes");
var textAssets = GameModule.Resource.LoadAsset<TextAsset>(file);
ret = textAssets.bytes;
#endif
return new ByteBuf(ret);

View File

@@ -7,46 +7,29 @@
//------------------------------------------------------------------------------
using Bright.Serialization;
using System.Collections.Generic;
using SimpleJSON;
namespace GameConfig.Battle
{
public sealed partial class BuffAttrConfig : Bright.Config.BeanBase
{
public BuffAttrConfig(JSONNode _json)
public BuffAttrConfig(ByteBuf _buf)
{
{ if(!_json["BuffID"].IsNumber) { throw new SerializationException(); } BuffID = _json["BuffID"]; }
{ if(!_json["name"].IsString) { throw new SerializationException(); } Name = _json["name"]; }
{ if(!_json["StackNum"].IsNumber) { throw new SerializationException(); } StackNum = _json["StackNum"]; }
{ if(!_json["DurTime"].IsNumber) { throw new SerializationException(); } DurTime = _json["DurTime"]; }
{ if(!_json["ResultType"].IsNumber) { throw new SerializationException(); } ResultType = (Battle.BuffResultType)_json["ResultType"].AsInt; }
{ if(!_json["RemoveWhenDie"].IsNumber) { throw new SerializationException(); } RemoveWhenDie = _json["RemoveWhenDie"]; }
{ if(!_json["DotDamageData"].IsObject) { throw new SerializationException(); } DotDamageData = Battle.SkillAttrDamageData.DeserializeSkillAttrDamageData(_json["DotDamageData"]); }
{ if(!_json["DotTickConfig"].IsObject) { throw new SerializationException(); } DotTickConfig = Battle.BuffDotTickConfig.DeserializeBuffDotTickConfig(_json["DotTickConfig"]); }
{ var __json0 = _json["AttrData"]; if(!__json0.IsArray) { throw new SerializationException(); } AttrData = new System.Collections.Generic.List<Battle.ResAttrImpactData>(__json0.Count); foreach(JSONNode __e0 in __json0.Children) { Battle.ResAttrImpactData __v0; { if(!__e0.IsObject) { throw new SerializationException(); } __v0 = Battle.ResAttrImpactData.DeserializeResAttrImpactData(__e0); } AttrData.Add(__v0); } }
BuffID = _buf.ReadInt();
Name = _buf.ReadString();
StackNum = _buf.ReadInt();
DurTime = _buf.ReadFloat();
ResultType = (Battle.BuffResultType)_buf.ReadInt();
RemoveWhenDie = _buf.ReadInt();
DotDamageData = Battle.SkillAttrDamageData.DeserializeSkillAttrDamageData(_buf);
DotTickConfig = Battle.BuffDotTickConfig.DeserializeBuffDotTickConfig(_buf);
{int n0 = System.Math.Min(_buf.ReadSize(), _buf.Size);AttrData = new System.Collections.Generic.List<Battle.ResAttrImpactData>(n0);for(var i0 = 0 ; i0 < n0 ; i0++) { Battle.ResAttrImpactData _e0; _e0 = Battle.ResAttrImpactData.DeserializeResAttrImpactData(_buf); AttrData.Add(_e0);}}
PostInit();
}
public BuffAttrConfig(int BuffID, string name, int StackNum, float DurTime, Battle.BuffResultType ResultType, int RemoveWhenDie, Battle.SkillAttrDamageData DotDamageData, Battle.BuffDotTickConfig DotTickConfig, System.Collections.Generic.List<Battle.ResAttrImpactData> AttrData )
public static BuffAttrConfig DeserializeBuffAttrConfig(ByteBuf _buf)
{
this.BuffID = BuffID;
this.Name = name;
this.StackNum = StackNum;
this.DurTime = DurTime;
this.ResultType = ResultType;
this.RemoveWhenDie = RemoveWhenDie;
this.DotDamageData = DotDamageData;
this.DotTickConfig = DotTickConfig;
this.AttrData = AttrData;
PostInit();
}
public static BuffAttrConfig DeserializeBuffAttrConfig(JSONNode _json)
{
return new Battle.BuffAttrConfig(_json);
return new Battle.BuffAttrConfig(_buf);
}
/// <summary>
@@ -113,4 +96,5 @@ public sealed partial class BuffAttrConfig : Bright.Config.BeanBase
partial void PostInit();
partial void PostResolve();
}
}

View File

@@ -7,44 +7,28 @@
//------------------------------------------------------------------------------
using Bright.Serialization;
using System.Collections.Generic;
using SimpleJSON;
namespace GameConfig.Battle
{
public sealed partial class BuffConfig : Bright.Config.BeanBase
{
public BuffConfig(JSONNode _json)
public BuffConfig(ByteBuf _buf)
{
{ if(!_json["BuffID"].IsNumber) { throw new SerializationException(); } BuffID = _json["BuffID"]; }
{ if(!_json["name"].IsString) { throw new SerializationException(); } Name = _json["name"]; }
{ if(!_json["prefId"].IsNumber) { throw new SerializationException(); } PrefId = _json["prefId"]; }
{ if(!_json["desc"].IsString) { throw new SerializationException(); } Desc = _json["desc"]; }
{ if(!_json["icon"].IsString) { throw new SerializationException(); } Icon = _json["icon"]; }
{ if(!_json["TimeType"].IsNumber) { throw new SerializationException(); } TimeType = (Battle.BuffTimeType)_json["TimeType"].AsInt; }
{ if(!_json["ReplaceType"].IsNumber) { throw new SerializationException(); } ReplaceType = (Battle.BuffReplaceType)_json["ReplaceType"].AsInt; }
{ if(!_json["State"].IsObject) { throw new SerializationException(); } State = Battle.BuffTriggleState.DeserializeBuffTriggleState(_json["State"]); }
BuffID = _buf.ReadInt();
Name = _buf.ReadString();
PrefId = _buf.ReadInt();
Desc = _buf.ReadString();
Icon = _buf.ReadString();
TimeType = (Battle.BuffTimeType)_buf.ReadInt();
ReplaceType = (Battle.BuffReplaceType)_buf.ReadInt();
State = Battle.BuffTriggleState.DeserializeBuffTriggleState(_buf);
PostInit();
}
public BuffConfig(int BuffID, string name, int prefId, string desc, string icon, Battle.BuffTimeType TimeType, Battle.BuffReplaceType ReplaceType, Battle.BuffTriggleState State )
public static BuffConfig DeserializeBuffConfig(ByteBuf _buf)
{
this.BuffID = BuffID;
this.Name = name;
this.PrefId = prefId;
this.Desc = desc;
this.Icon = icon;
this.TimeType = TimeType;
this.ReplaceType = ReplaceType;
this.State = State;
PostInit();
}
public static BuffConfig DeserializeBuffConfig(JSONNode _json)
{
return new Battle.BuffConfig(_json);
return new Battle.BuffConfig(_buf);
}
/// <summary>
@@ -108,4 +92,5 @@ public sealed partial class BuffConfig : Bright.Config.BeanBase
partial void PostInit();
partial void PostResolve();
}
}

View File

@@ -7,32 +7,22 @@
//------------------------------------------------------------------------------
using Bright.Serialization;
using System.Collections.Generic;
using SimpleJSON;
namespace GameConfig.Battle
{
public sealed partial class BuffDotTickConfig : Bright.Config.BeanBase
{
public BuffDotTickConfig(JSONNode _json)
public BuffDotTickConfig(ByteBuf _buf)
{
{ if(!_json["TickTime"].IsNumber) { throw new SerializationException(); } TickTime = _json["TickTime"]; }
{ if(!_json["TickWhenAdd"].IsNumber) { throw new SerializationException(); } TickWhenAdd = _json["TickWhenAdd"]; }
TickTime = _buf.ReadFloat();
TickWhenAdd = _buf.ReadInt();
PostInit();
}
public BuffDotTickConfig(float TickTime, int TickWhenAdd )
public static BuffDotTickConfig DeserializeBuffDotTickConfig(ByteBuf _buf)
{
this.TickTime = TickTime;
this.TickWhenAdd = TickWhenAdd;
PostInit();
}
public static BuffDotTickConfig DeserializeBuffDotTickConfig(JSONNode _json)
{
return new Battle.BuffDotTickConfig(_json);
return new Battle.BuffDotTickConfig(_buf);
}
public float TickTime { get; private set; }
@@ -61,4 +51,5 @@ public sealed partial class BuffDotTickConfig : Bright.Config.BeanBase
partial void PostInit();
partial void PostResolve();
}
}

View File

@@ -7,32 +7,22 @@
//------------------------------------------------------------------------------
using Bright.Serialization;
using System.Collections.Generic;
using SimpleJSON;
namespace GameConfig.Battle
{
public sealed partial class BuffTriggleState : Bright.Config.BeanBase
{
public BuffTriggleState(JSONNode _json)
public BuffTriggleState(ByteBuf _buf)
{
{ if(!_json["StateID"].IsNumber) { throw new SerializationException(); } StateID = (Battle.BuffStateID)_json["StateID"].AsInt; }
{ if(!_json["StateParam"].IsNumber) { throw new SerializationException(); } StateParam = _json["StateParam"]; }
StateID = (Battle.BuffStateID)_buf.ReadInt();
StateParam = _buf.ReadFloat();
PostInit();
}
public BuffTriggleState(Battle.BuffStateID StateID, float StateParam )
public static BuffTriggleState DeserializeBuffTriggleState(ByteBuf _buf)
{
this.StateID = StateID;
this.StateParam = StateParam;
PostInit();
}
public static BuffTriggleState DeserializeBuffTriggleState(JSONNode _json)
{
return new Battle.BuffTriggleState(_json);
return new Battle.BuffTriggleState(_buf);
}
public Battle.BuffStateID StateID { get; private set; }
@@ -61,4 +51,5 @@ public sealed partial class BuffTriggleState : Bright.Config.BeanBase
partial void PostInit();
partial void PostResolve();
}
}

View File

@@ -7,34 +7,23 @@
//------------------------------------------------------------------------------
using Bright.Serialization;
using System.Collections.Generic;
using SimpleJSON;
namespace GameConfig.Battle
{
public sealed partial class ResAttrImpactData : Bright.Config.BeanBase
{
public ResAttrImpactData(JSONNode _json)
public ResAttrImpactData(ByteBuf _buf)
{
{ if(!_json["DataType"].IsNumber) { throw new SerializationException(); } DataType = (Battle.ActorAttrDataType)_json["DataType"].AsInt; }
{ if(!_json["AddType"].IsNumber) { throw new SerializationException(); } AddType = (Battle.ActorAttrAddType)_json["AddType"].AsInt; }
{ if(!_json["Value"].IsNumber) { throw new SerializationException(); } Value = _json["Value"]; }
DataType = (Battle.ActorAttrDataType)_buf.ReadInt();
AddType = (Battle.ActorAttrAddType)_buf.ReadInt();
Value = _buf.ReadFloat();
PostInit();
}
public ResAttrImpactData(Battle.ActorAttrDataType DataType, Battle.ActorAttrAddType AddType, float Value )
public static ResAttrImpactData DeserializeResAttrImpactData(ByteBuf _buf)
{
this.DataType = DataType;
this.AddType = AddType;
this.Value = Value;
PostInit();
}
public static ResAttrImpactData DeserializeResAttrImpactData(JSONNode _json)
{
return new Battle.ResAttrImpactData(_json);
return new Battle.ResAttrImpactData(_buf);
}
public Battle.ActorAttrDataType DataType { get; private set; }
@@ -65,4 +54,5 @@ public sealed partial class ResAttrImpactData : Bright.Config.BeanBase
partial void PostInit();
partial void PostResolve();
}
}

View File

@@ -7,40 +7,26 @@
//------------------------------------------------------------------------------
using Bright.Serialization;
using System.Collections.Generic;
using SimpleJSON;
namespace GameConfig.Battle
{
public sealed partial class SkillAttrDamageData : Bright.Config.BeanBase
{
public SkillAttrDamageData(JSONNode _json)
public SkillAttrDamageData(ByteBuf _buf)
{
{ if(!_json["MagicType"].IsNumber) { throw new SerializationException(); } MagicType = (Battle.SkillMagicType)_json["MagicType"].AsInt; }
{ if(!_json["AttrType"].IsNumber) { throw new SerializationException(); } AttrType = (Battle.SkillAttrDamageType)_json["AttrType"].AsInt; }
{ if(!_json["Param1"].IsNumber) { throw new SerializationException(); } Param1 = _json["Param1"]; }
{ if(!_json["Param2"].IsNumber) { throw new SerializationException(); } Param2 = _json["Param2"]; }
{ if(!_json["Param3"].IsNumber) { throw new SerializationException(); } Param3 = _json["Param3"]; }
{ if(!_json["MaxLimit"].IsNumber) { throw new SerializationException(); } MaxLimit = _json["MaxLimit"]; }
MagicType = (Battle.SkillMagicType)_buf.ReadInt();
AttrType = (Battle.SkillAttrDamageType)_buf.ReadInt();
Param1 = _buf.ReadFloat();
Param2 = _buf.ReadFloat();
Param3 = _buf.ReadFloat();
MaxLimit = _buf.ReadFloat();
PostInit();
}
public SkillAttrDamageData(Battle.SkillMagicType MagicType, Battle.SkillAttrDamageType AttrType, float Param1, float Param2, float Param3, float MaxLimit )
public static SkillAttrDamageData DeserializeSkillAttrDamageData(ByteBuf _buf)
{
this.MagicType = MagicType;
this.AttrType = AttrType;
this.Param1 = Param1;
this.Param2 = Param2;
this.Param3 = Param3;
this.MaxLimit = MaxLimit;
PostInit();
}
public static SkillAttrDamageData DeserializeSkillAttrDamageData(JSONNode _json)
{
return new Battle.SkillAttrDamageData(_json);
return new Battle.SkillAttrDamageData(_buf);
}
public Battle.SkillMagicType MagicType { get; private set; }
@@ -77,4 +63,5 @@ public sealed partial class SkillAttrDamageData : Bright.Config.BeanBase
partial void PostInit();
partial void PostResolve();
}
}

View File

@@ -7,50 +7,31 @@
//------------------------------------------------------------------------------
using Bright.Serialization;
using System.Collections.Generic;
using SimpleJSON;
namespace GameConfig.Battle
{
public sealed partial class SkillBaseConfig : Bright.Config.BeanBase
{
public SkillBaseConfig(JSONNode _json)
public SkillBaseConfig(ByteBuf _buf)
{
{ if(!_json["id"].IsNumber) { throw new SerializationException(); } Id = _json["id"]; }
{ if(!_json["name"].IsString) { throw new SerializationException(); } Name = _json["name"]; }
{ if(!_json["SkillDispID"].IsNumber) { throw new SerializationException(); } SkillDispID = _json["SkillDispID"]; }
{ if(!_json["SkillType"].IsNumber) { throw new SerializationException(); } SkillType = _json["SkillType"]; }
{ if(!_json["desc"].IsString) { throw new SerializationException(); } Desc = _json["desc"]; }
{ if(!_json["CostMP"].IsNumber) { throw new SerializationException(); } CostMP = _json["CostMP"]; }
{ if(!_json["GCDID"].IsNumber) { throw new SerializationException(); } GCDID = _json["GCDID"]; }
{ if(!_json["SkillCD"].IsNumber) { throw new SerializationException(); } SkillCD = _json["SkillCD"]; }
{ if(!_json["IsRepeatTrigger"].IsBoolean) { throw new SerializationException(); } IsRepeatTrigger = _json["IsRepeatTrigger"]; }
{ var __json0 = _json["BuffID"]; if(!__json0.IsArray) { throw new SerializationException(); } BuffID = new System.Collections.Generic.List<int>(__json0.Count); foreach(JSONNode __e0 in __json0.Children) { int __v0; { if(!__e0.IsNumber) { throw new SerializationException(); } __v0 = __e0; } BuffID.Add(__v0); } }
{ var __json0 = _json["AttrDamageData"]; if(!__json0.IsArray) { throw new SerializationException(); } AttrDamageData = new System.Collections.Generic.List<Battle.SkillAttrDamageData>(__json0.Count); foreach(JSONNode __e0 in __json0.Children) { Battle.SkillAttrDamageData __v0; { if(!__e0.IsObject) { throw new SerializationException(); } __v0 = Battle.SkillAttrDamageData.DeserializeSkillAttrDamageData(__e0); } AttrDamageData.Add(__v0); } }
Id = _buf.ReadInt();
Name = _buf.ReadString();
SkillDispID = _buf.ReadInt();
SkillType = _buf.ReadInt();
Desc = _buf.ReadString();
CostMP = _buf.ReadInt();
GCDID = _buf.ReadInt();
SkillCD = _buf.ReadFloat();
IsRepeatTrigger = _buf.ReadBool();
{int n0 = System.Math.Min(_buf.ReadSize(), _buf.Size);BuffID = new System.Collections.Generic.List<int>(n0);for(var i0 = 0 ; i0 < n0 ; i0++) { int _e0; _e0 = _buf.ReadInt(); BuffID.Add(_e0);}}
{int n0 = System.Math.Min(_buf.ReadSize(), _buf.Size);AttrDamageData = new System.Collections.Generic.List<Battle.SkillAttrDamageData>(n0);for(var i0 = 0 ; i0 < n0 ; i0++) { Battle.SkillAttrDamageData _e0; _e0 = Battle.SkillAttrDamageData.DeserializeSkillAttrDamageData(_buf); AttrDamageData.Add(_e0);}}
PostInit();
}
public SkillBaseConfig(int id, string name, int SkillDispID, int SkillType, string desc, int CostMP, int GCDID, float SkillCD, bool IsRepeatTrigger, System.Collections.Generic.List<int> BuffID, System.Collections.Generic.List<Battle.SkillAttrDamageData> AttrDamageData )
public static SkillBaseConfig DeserializeSkillBaseConfig(ByteBuf _buf)
{
this.Id = id;
this.Name = name;
this.SkillDispID = SkillDispID;
this.SkillType = SkillType;
this.Desc = desc;
this.CostMP = CostMP;
this.GCDID = GCDID;
this.SkillCD = SkillCD;
this.IsRepeatTrigger = IsRepeatTrigger;
this.BuffID = BuffID;
this.AttrDamageData = AttrDamageData;
PostInit();
}
public static SkillBaseConfig DeserializeSkillBaseConfig(JSONNode _json)
{
return new Battle.SkillBaseConfig(_json);
return new Battle.SkillBaseConfig(_buf);
}
/// <summary>
@@ -129,4 +110,5 @@ public sealed partial class SkillBaseConfig : Bright.Config.BeanBase
partial void PostInit();
partial void PostResolve();
}
}

View File

@@ -7,26 +7,25 @@
//------------------------------------------------------------------------------
using Bright.Serialization;
using System.Collections.Generic;
using SimpleJSON;
namespace GameConfig.Battle
{
public sealed partial class TbBuff
public partial class TbBuff
{
private readonly Dictionary<int, Battle.BuffConfig> _dataMap;
private readonly List<Battle.BuffConfig> _dataList;
public TbBuff(JSONNode _json)
public TbBuff(ByteBuf _buf)
{
_dataMap = new Dictionary<int, Battle.BuffConfig>();
_dataList = new List<Battle.BuffConfig>();
foreach(JSONNode _row in _json.Children)
for(int n = _buf.ReadSize() ; n > 0 ; --n)
{
var _v = Battle.BuffConfig.DeserializeBuffConfig(_row);
Battle.BuffConfig _v;
_v = Battle.BuffConfig.DeserializeBuffConfig(_buf);
_dataList.Add(_v);
_dataMap.Add(_v.BuffID, _v);
}
@@ -57,7 +56,6 @@ public sealed partial class TbBuff
}
}
partial void PostInit();
partial void PostResolve();
}

View File

@@ -7,26 +7,25 @@
//------------------------------------------------------------------------------
using Bright.Serialization;
using System.Collections.Generic;
using SimpleJSON;
namespace GameConfig.Battle
{
public sealed partial class TbBuffAttr
public partial class TbBuffAttr
{
private readonly Dictionary<int, Battle.BuffAttrConfig> _dataMap;
private readonly List<Battle.BuffAttrConfig> _dataList;
public TbBuffAttr(JSONNode _json)
public TbBuffAttr(ByteBuf _buf)
{
_dataMap = new Dictionary<int, Battle.BuffAttrConfig>();
_dataList = new List<Battle.BuffAttrConfig>();
foreach(JSONNode _row in _json.Children)
for(int n = _buf.ReadSize() ; n > 0 ; --n)
{
var _v = Battle.BuffAttrConfig.DeserializeBuffAttrConfig(_row);
Battle.BuffAttrConfig _v;
_v = Battle.BuffAttrConfig.DeserializeBuffAttrConfig(_buf);
_dataList.Add(_v);
_dataMap.Add(_v.BuffID, _v);
}
@@ -57,7 +56,6 @@ public sealed partial class TbBuffAttr
}
}
partial void PostInit();
partial void PostResolve();
}

View File

@@ -7,26 +7,25 @@
//------------------------------------------------------------------------------
using Bright.Serialization;
using System.Collections.Generic;
using SimpleJSON;
namespace GameConfig.Battle
{
public sealed partial class TbSkill
public partial class TbSkill
{
private readonly Dictionary<int, Battle.SkillBaseConfig> _dataMap;
private readonly List<Battle.SkillBaseConfig> _dataList;
public TbSkill(JSONNode _json)
public TbSkill(ByteBuf _buf)
{
_dataMap = new Dictionary<int, Battle.SkillBaseConfig>();
_dataList = new List<Battle.SkillBaseConfig>();
foreach(JSONNode _row in _json.Children)
for(int n = _buf.ReadSize() ; n > 0 ; --n)
{
var _v = Battle.SkillBaseConfig.DeserializeSkillBaseConfig(_row);
Battle.SkillBaseConfig _v;
_v = Battle.SkillBaseConfig.DeserializeSkillBaseConfig(_buf);
_dataList.Add(_v);
_dataMap.Add(_v.Id, _v);
}
@@ -57,7 +56,6 @@ public sealed partial class TbSkill
}
}
partial void PostInit();
partial void PostResolve();
}

View File

@@ -6,20 +6,19 @@
// </auto-generated>
//------------------------------------------------------------------------------
using Bright.Serialization;
using SimpleJSON;
namespace GameConfig
{
public sealed partial class Tables
public partial class Tables
{
public item.TbItem TbItem {get; }
public Battle.TbSkill TbSkill {get; }
public Battle.TbBuff TbBuff {get; }
public Battle.TbBuffAttr TbBuffAttr {get; }
public Tables(System.Func<string, JSONNode> loader)
public Tables(System.Func<string, ByteBuf> loader)
{
var tables = new System.Collections.Generic.Dictionary<string, object>();
TbItem = new item.TbItem(loader("item_tbitem"));
@@ -30,8 +29,8 @@ public sealed partial class Tables
tables.Add("Battle.TbBuff", TbBuff);
TbBuffAttr = new Battle.TbBuffAttr(loader("battle_tbbuffattr"));
tables.Add("Battle.TbBuffAttr", TbBuffAttr);
PostInit();
PostInit();
TbItem.Resolve(tables);
TbSkill.Resolve(tables);
TbBuff.Resolve(tables);

View File

@@ -7,50 +7,31 @@
//------------------------------------------------------------------------------
using Bright.Serialization;
using System.Collections.Generic;
using SimpleJSON;
namespace GameConfig.item
{
public sealed partial class Item : Bright.Config.BeanBase
{
public Item(JSONNode _json)
public Item(ByteBuf _buf)
{
{ if(!_json["id"].IsNumber) { throw new SerializationException(); } Id = _json["id"]; }
{ if(!_json["name"].IsString) { throw new SerializationException(); } Name = _json["name"]; }
{ if(!_json["desc"].IsString) { throw new SerializationException(); } Desc = _json["desc"]; }
{ if(!_json["price"].IsNumber) { throw new SerializationException(); } Price = _json["price"]; }
{ if(!_json["upgrade_to_item_id"].IsNumber) { throw new SerializationException(); } UpgradeToItemId = _json["upgrade_to_item_id"]; }
{ var _j = _json["expire_time"]; if (_j.Tag != JSONNodeType.None && _j.Tag != JSONNodeType.NullValue) { { if(!_j.IsNumber) { throw new SerializationException(); } ExpireTime = _j; } } else { ExpireTime = null; } }
{ if(!_json["batch_useable"].IsBoolean) { throw new SerializationException(); } BatchUseable = _json["batch_useable"]; }
{ if(!_json["quality"].IsNumber) { throw new SerializationException(); } Quality = (item.EQuality)_json["quality"].AsInt; }
{ if(!_json["exchange_stream"].IsObject) { throw new SerializationException(); } ExchangeStream = item.ItemExchange.DeserializeItemExchange(_json["exchange_stream"]); }
{ var __json0 = _json["exchange_list"]; if(!__json0.IsArray) { throw new SerializationException(); } ExchangeList = new System.Collections.Generic.List<item.ItemExchange>(__json0.Count); foreach(JSONNode __e0 in __json0.Children) { item.ItemExchange __v0; { if(!__e0.IsObject) { throw new SerializationException(); } __v0 = item.ItemExchange.DeserializeItemExchange(__e0); } ExchangeList.Add(__v0); } }
{ if(!_json["exchange_column"].IsObject) { throw new SerializationException(); } ExchangeColumn = item.ItemExchange.DeserializeItemExchange(_json["exchange_column"]); }
Id = _buf.ReadInt();
Name = _buf.ReadString();
Desc = _buf.ReadString();
Price = _buf.ReadInt();
UpgradeToItemId = _buf.ReadInt();
if(_buf.ReadBool()){ ExpireTime = _buf.ReadInt(); } else { ExpireTime = null; }
BatchUseable = _buf.ReadBool();
Quality = (item.EQuality)_buf.ReadInt();
ExchangeStream = item.ItemExchange.DeserializeItemExchange(_buf);
{int n0 = System.Math.Min(_buf.ReadSize(), _buf.Size);ExchangeList = new System.Collections.Generic.List<item.ItemExchange>(n0);for(var i0 = 0 ; i0 < n0 ; i0++) { item.ItemExchange _e0; _e0 = item.ItemExchange.DeserializeItemExchange(_buf); ExchangeList.Add(_e0);}}
ExchangeColumn = item.ItemExchange.DeserializeItemExchange(_buf);
PostInit();
}
public Item(int id, string name, string desc, int price, int upgrade_to_item_id, int? expire_time, bool batch_useable, item.EQuality quality, item.ItemExchange exchange_stream, System.Collections.Generic.List<item.ItemExchange> exchange_list, item.ItemExchange exchange_column )
public static Item DeserializeItem(ByteBuf _buf)
{
this.Id = id;
this.Name = name;
this.Desc = desc;
this.Price = price;
this.UpgradeToItemId = upgrade_to_item_id;
this.ExpireTime = expire_time;
this.BatchUseable = batch_useable;
this.Quality = quality;
this.ExchangeStream = exchange_stream;
this.ExchangeList = exchange_list;
this.ExchangeColumn = exchange_column;
PostInit();
}
public static Item DeserializeItem(JSONNode _json)
{
return new item.Item(_json);
return new item.Item(_buf);
}
/// <summary>
@@ -135,4 +116,5 @@ public sealed partial class Item : Bright.Config.BeanBase
partial void PostInit();
partial void PostResolve();
}
}

View File

@@ -7,32 +7,22 @@
//------------------------------------------------------------------------------
using Bright.Serialization;
using System.Collections.Generic;
using SimpleJSON;
namespace GameConfig.item
{
public sealed partial class ItemExchange : Bright.Config.BeanBase
{
public ItemExchange(JSONNode _json)
public ItemExchange(ByteBuf _buf)
{
{ if(!_json["id"].IsNumber) { throw new SerializationException(); } Id = _json["id"]; }
{ if(!_json["num"].IsNumber) { throw new SerializationException(); } Num = _json["num"]; }
Id = _buf.ReadInt();
Num = _buf.ReadInt();
PostInit();
}
public ItemExchange(int id, int num )
public static ItemExchange DeserializeItemExchange(ByteBuf _buf)
{
this.Id = id;
this.Num = num;
PostInit();
}
public static ItemExchange DeserializeItemExchange(JSONNode _json)
{
return new item.ItemExchange(_json);
return new item.ItemExchange(_buf);
}
/// <summary>
@@ -67,4 +57,5 @@ public sealed partial class ItemExchange : Bright.Config.BeanBase
partial void PostInit();
partial void PostResolve();
}
}

View File

@@ -7,26 +7,25 @@
//------------------------------------------------------------------------------
using Bright.Serialization;
using System.Collections.Generic;
using SimpleJSON;
namespace GameConfig.item
{
public sealed partial class TbItem
public partial class TbItem
{
private readonly Dictionary<int, item.Item> _dataMap;
private readonly List<item.Item> _dataList;
public TbItem(JSONNode _json)
public TbItem(ByteBuf _buf)
{
_dataMap = new Dictionary<int, item.Item>();
_dataList = new List<item.Item>();
foreach(JSONNode _row in _json.Children)
for(int n = _buf.ReadSize() ; n > 0 ; --n)
{
var _v = item.Item.DeserializeItem(_row);
item.Item _v;
_v = item.Item.DeserializeItem(_buf);
_dataList.Add(_v);
_dataMap.Add(_v.Id, _v);
}
@@ -57,7 +56,6 @@ public sealed partial class TbItem
}
}
partial void PostInit();
partial void PostResolve();
}

View File

@@ -30,10 +30,14 @@ public class DisStripCode : MonoBehaviour
RegisterType<Animator>();
RegisterType<Animation>();
#if UNITY_IOS || PLATFORM_IOS
/*
// IOSCamera ios下相机权限的问题用这种方法就可以解决了 问题防裁剪。
foreach (var _ in WebCamTexture.devices)
{
}
*/
#endif
}
private void RegisterType<T>()

View File

@@ -0,0 +1,39 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using UnityEngine;
#if UNITY_EDITOR
using UnityEditor;
#endif
namespace TEngine.Editor
{
public static class GenTools
{
public const string GenNetFirstTips = "ProtoGenTools.GenNetFirstTips";
[MenuItem("TEngine/导出网络Proto|Gen Proto", false, 100)]
public static void ExportProto()
{
var firstTips = EditorPrefs.GetBool(GenNetFirstTips, false);
if (!firstTips && EditorUtility.DisplayDialog("提示", "导出网络Proto依赖于DotNet下Server解决方案首次打开请编译", "不再提示", "继续"))
{
EditorPrefs.SetBool(GenNetFirstTips, true);
return;
}
Application.OpenURL(System.IO.Path.Combine(Application.dataPath,"../DotNet/start_export.bat"));
Debug.Log("proto2cs succeed!");
}
[MenuItem("TEngine/导出Config|Export Config", false, 100)]
public static void ExportConfig()
{
Application.OpenURL(System.IO.Path.Combine(Application.dataPath,"../Luban/gen_code_bin_to_project.bat"));
Debug.Log("proto2cs succeed!");
}
}
}

View File

@@ -1,291 +0,0 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using UnityEngine;
#if UNITY_EDITOR
using UnityEditor;
#endif
namespace TEngine.Editor
{
public static class ProtoGenTools
{
#if UNITY_EDITOR
[MenuItem("TEngine/生成Proto|Gen Proto", false, 10)]
#endif
public static void Export()
{
InnerProto2CS.Proto2CS();
Debug.Log("proto2cs succeed!");
}
}
public static class InnerProto2CS
{
private static string ProtoPath = UnityEngine.Application.dataPath + "/..\\Luban\\Proto\\pb_schemas\\";
private static string OutPutPath =
UnityEngine.Application.dataPath + "/..\\Luban\\Proto\\Gen\\";
private static readonly char[] splitChars = { ' ', '\t' };
public static void Proto2CS()
{
Proto2CS("GameProto", "ProtoBase.proto", OutPutPath,10001,false);
}
public static void Proto2CS(string nameSpace, string protoName, string outputPath, int startOpcode,bool useMemoryPool = false)
{
if (!Directory.Exists(outputPath))
{
Directory.CreateDirectory(outputPath);
}
string proto = Path.Combine(ProtoPath, protoName);
string csPath = Path.Combine(outputPath, Path.GetFileNameWithoutExtension(proto) + ".cs");
string s = File.ReadAllText(proto);
StringBuilder sb = new StringBuilder();
sb.Append("//------------------------------------------------------------------------------\n");
sb.Append("// <auto-generated>\n");
sb.Append("// This code was generated by a tool.\n");
sb.Append("// Changes to this file may cause incorrect behavior and will be lost if\n");
sb.Append("// the code is regenerated.\n");
sb.Append("// </auto-generated>\n");
sb.Append("//------------------------------------------------------------------------------\n");
sb.Append("\n");
sb.Append("using System;\n");
sb.Append("using ProtoBuf;\n");
sb.Append("using TEngine;\n");
sb.Append("using System.Collections.Generic;\n");
sb.Append("\n");
sb.Append($"namespace {nameSpace}\n");
sb.Append("{\n");
bool isMsgStart = false;
bool isEnumStart = false;
foreach (string line in s.Split('\n'))
{
string newline = line.Trim();
if (newline == "")
{
continue;
}
if (newline.StartsWith("//ResponseType"))
{
string responseType = line.Split(' ')[1].TrimEnd('\r', '\n');
sb.AppendLine($"\t[ResponseType(nameof({responseType}))]");
continue;
}
if (newline.StartsWith("//"))
{
sb.Append($"\t{newline}\n");
continue;
}
if (newline.StartsWith("message"))
{
string parentClass = "";
isMsgStart = true;
string msgName = newline.Split(splitChars, StringSplitOptions.RemoveEmptyEntries)[1];
string[] ss = newline.Split(new[] { "//" }, StringSplitOptions.RemoveEmptyEntries);
if (ss.Length == 2)
{
parentClass = ss[1].Trim();
}
sb.Append($"\t[Serializable,global::ProtoBuf.ProtoContract(Name = @\"{msgName}\")]\n");
if (useMemoryPool)
{
sb.Append($"\tpublic partial class {msgName}: IMemory");
}
else
{
sb.Append($"\tpublic partial class {msgName}");
}
if (parentClass != "")
{
sb.Append($", {parentClass}\n");
}
else
{
sb.Append("\n");
}
continue;
}
if (isMsgStart)
{
if (newline == "{")
{
sb.Append("\t{\n");
continue;
}
if (newline == "}")
{
isMsgStart = false;
sb.Append("\t}\n\n");
continue;
}
if (newline.Trim().StartsWith("//"))
{
sb.AppendLine(newline);
continue;
}
if (newline.Trim() != "" && newline != "}")
{
if (newline.StartsWith("repeated"))
{
Repeated(sb, nameSpace, newline);
}
else
{
Members(sb, newline, true);
}
}
}
if (newline.StartsWith("enum"))
{
isEnumStart = true;
string enumName = newline.Split(splitChars, StringSplitOptions.RemoveEmptyEntries)[1];
sb.Append($"\t[global::ProtoBuf.ProtoContract()]\n");
sb.Append($"\tpublic enum {enumName}");
sb.Append("\n");
continue;
}
if (isEnumStart)
{
if (newline == "{")
{
sb.Append("\t{\n");
continue;
}
if (newline == "}")
{
isEnumStart = false;
sb.Append("\t}\n\n");
continue;
}
if (newline.Trim().StartsWith("//"))
{
sb.AppendLine(newline);
continue;
}
int index = newline.IndexOf(";");
newline = newline.Remove(index);
sb.Append($"\t\t{newline},\n\n");
}
}
sb.Append("}\n");
using (FileStream txt = new FileStream(csPath, FileMode.Create, FileAccess.ReadWrite))
{
using (StreamWriter sw = new StreamWriter(txt))
{
Debug.Log(sb.ToString());
sw.Write(sb.ToString());
}
}
}
private static void Repeated(StringBuilder sb, string ns, string newline)
{
try
{
int index = newline.IndexOf(";");
newline = newline.Remove(index);
string[] ss = newline.Split(splitChars, StringSplitOptions.RemoveEmptyEntries);
string type = ss[1];
type = ConvertType(type);
string name = ss[2];
int n = int.Parse(ss[4]);
sb.Append($"\t\t[global::ProtoBuf.ProtoMember({n})]\n");
sb.Append($"\t\tpublic List<{type}> {name} = new List<{type}>();\n\n");
}
catch (Exception e)
{
Console.WriteLine($"{newline}\n {e}");
}
}
private static string ConvertType(string type)
{
string typeCs = "";
switch (type)
{
case "int16":
typeCs = "short";
break;
case "int32":
typeCs = "int";
break;
case "bytes":
typeCs = "byte[]";
break;
case "uint32":
typeCs = "uint";
break;
case "long":
typeCs = "long";
break;
case "int64":
typeCs = "long";
break;
case "uint64":
typeCs = "ulong";
break;
case "uint16":
typeCs = "ushort";
break;
default:
typeCs = type;
break;
}
return typeCs;
}
private static void Members(StringBuilder sb, string newline, bool isRequired)
{
try
{
int index = newline.IndexOf(";");
newline = newline.Remove(index);
string[] ss = newline.Split(splitChars, StringSplitOptions.RemoveEmptyEntries);
string type = ss[0];
string name = ss[1];
int n = int.Parse(ss[3]);
string typeCs = ConvertType(type);
sb.Append($"\t\t[global::ProtoBuf.ProtoMember({n})]\n");
if (string.Equals(type,"string"))
{
sb.Append($"\t\t[global::System.ComponentModel.DefaultValue(\"\")]\n");
}
sb.Append($"\t\tpublic {typeCs} {name} {{ get; set; }}\n\n");
}
catch (Exception e)
{
Console.WriteLine($"{newline}\n {e}");
}
}
}
}

View File

@@ -1,448 +0,0 @@
using System;
using UnityEditor;
using UnityEngine;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Xml;
using TEngine;
using TEngine.Editor;
using Debug = UnityEngine.Debug;
class GenNetScriptWindow : EditorWindow
{
private static GenNetScriptWindow _window = null;
//绑定通知协议
private StringBuilder _strBindNotify;
//枚举对应协议号
private readonly Dictionary<string, int> _dicName2ID = new Dictionary<string, int>();
//xxx.xml下的协议枚举list
private readonly Dictionary<string, List<string>> _dicPath2Name = new Dictionary<string, List<string>>();
//协议号有没有被勾选
private readonly Dictionary<int, bool> _dicID2Select = new Dictionary<int, bool>();
//记录回包协议号
private readonly Dictionary<int, int> _dicID2ID = new Dictionary<int, int>();
private Vector2 _scrollPos;
private Vector2 _fileListScrollPos;
private string _path = @"G:\github\TEngine\Luban\Proto\pb_schemas\";
private readonly List<string> _filePathList = new List<string>();
private string _curSelectFile = string.Empty;
private string _filterFileName = string.Empty;
private string _filterProName = string.Empty;
[MenuItem("TEngine/协议生成工具|Protobuf Tools")]
static void OpenGenNetScriptWindow()
{
if (!_window)
{
_window = ScriptableObject.CreateInstance<GenNetScriptWindow>();
_window.maxSize = new Vector2(1000, 800);
_window.minSize = _window.maxSize / 2;
_window.LoadLastPath();
}
_window.ShowUtility();
}
void OnGUI()
{
EditorGUILayout.PrefixLabel("protoPath");
_path = EditorGUILayout.TextField(_path);
var r = EditorGUILayout.BeginHorizontal("Button");
if (GUI.Button(r, GUIContent.none))
{
ReadPath();
}
GUILayout.Label("Search");
EditorGUILayout.EndHorizontal();
//加个文件筛选
//EditorGUILayout.BeginHorizontal();
GUILayout.Label("filter file:");
_filterFileName = GUILayout.TextField(_filterFileName);
//EditorGUILayout.EndHorizontal();
//显示文件名部分
if (_filePathList.Count > 0)
{
_fileListScrollPos = EditorGUILayout.BeginScrollView(_fileListScrollPos, GUILayout.Width(r.width), GUILayout.Height(200));
for (int i = 0; i < _filePathList.Count; ++i)
{
var fileName = Path.GetFileNameWithoutExtension(_filePathList[i]);
if (!string.IsNullOrEmpty(_filterFileName) && fileName.IndexOf(_filterFileName, StringComparison.Ordinal) == -1)
{
continue;
}
if (GUILayout.Button(fileName))
{
_curSelectFile = _filePathList[i];
LoadSelectFile();
}
}
EditorGUILayout.EndScrollView();
}
GUILayout.Label("-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------");
if (!string.IsNullOrEmpty(_curSelectFile))
{
//加个协议筛选
GUILayout.Label("filter proto:");
_filterProName = GUILayout.TextField(_filterProName);
_scrollPos = EditorGUILayout.BeginScrollView(_scrollPos, GUILayout.Width(r.width), GUILayout.Height(200));
var fileName2 = Path.GetFileNameWithoutExtension(_curSelectFile);
List<string> list;
if (_dicPath2Name.TryGetValue(fileName2, out list))
{
EditorGUI.indentLevel++;
for (int i = 0; i < list.Count; ++i)
{
var cmdName = list[i];
//筛选一下,忽略大小写
if (!string.IsNullOrEmpty(_filterProName) && cmdName.ToLower().IndexOf(_filterProName.ToLower()) == -1)
continue;
var cmdID = _dicName2ID[cmdName];
EditorGUILayout.BeginHorizontal(GUIStyle.none);
//协议名
EditorGUILayout.LabelField(cmdName);
//toggle
if (!_dicID2Select.ContainsKey(cmdID))
_dicID2Select[cmdID] = false;
_dicID2Select[cmdID] = EditorGUILayout.Toggle(cmdID.ToString(),_dicID2Select[cmdID]);
//回包协议号
if (!_dicID2ID.ContainsKey(cmdID))
{
if (cmdName.EndsWith("REQ"))
_dicID2ID[cmdID] = cmdID + 1;
else
_dicID2ID[cmdID] = 0;
}
_dicID2ID[cmdID] = EditorGUILayout.IntField(_dicID2ID[cmdID]);
EditorGUILayout.EndHorizontal();
}
EditorGUI.indentLevel--;
}
EditorGUILayout.EndScrollView();
}
if (!string.IsNullOrEmpty(_curSelectFile))
{
if (GUILayout.Button("GenSelect"))
{
OnClickGenBtn(false);
}
if (GUILayout.Button("GenAll"))
{
OnClickGenBtn(true);
}
}
if (GUILayout.Button("导出Proto To Csharp|Export Proto To Csharp"))
{
ExportProto();
}
}
#region
private void LoadLastPath()
{
if (PlayerPrefs.HasKey("GenNetScriptWindow.Path"))
{
_path = PlayerPrefs.GetString("GenNetScriptWindow.Path");
}
ReadPath();
}
private void ReadPath()
{
PlayerPrefs.SetString("GenNetScriptWindow.Path", _path);
_filePathList.Clear();
_curSelectFile = String.Empty;
JustLoadFileList(_filePathList, _path);
}
private void JustLoadFileList(List<string> exportList, string folderPath, bool deep = false)
{
if (!LoadFoldChildFileList(exportList, folderPath, deep))
{
EditorUtility.DisplayDialog("folder not exist", "folder not exist:"+_path, "ok");
}
}
private void LoadSelectFile()
{
_dicID2Select.Clear();
_dicID2ID.Clear();
_dicName2ID.Clear();
var xmlFilePath = _curSelectFile;
var fileName = Path.GetFileNameWithoutExtension(xmlFilePath);
var protocolNameList = new List<string>();
//读xml
if (fileName.StartsWith("proto_cs"))
{
Debug.Log("load xml.name:" + fileName);
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(xmlFilePath);
GenProtocolNameList(xmlDoc.ChildNodes, protocolNameList);
_dicPath2Name[fileName] = protocolNameList;
Debug.Log(fileName + " success.");
}
}
private bool LoadFoldChildFileList(List<string> exportList, string folderPath, bool deep = false)
{
if (!Directory.Exists(folderPath))
{
Log.Error("folder not exist: {0}", folderPath);
return false;
}
string[] subFile = Directory.GetFiles(folderPath);
foreach (string fileName in subFile)
{
//有些筛选条件,直接写死这里了。方便
var name = Path.GetFileNameWithoutExtension(fileName);
if (name.StartsWith("proto_cs"))
exportList.Add(fileName);
}
if (deep)
{
string[] subFolders = Directory.GetDirectories(folderPath);
foreach (string folderName in subFolders)
{
LoadFoldChildFileList(exportList, folderName);
}
}
return true;
}
//把macro里的协议号和协议枚举名对应起来
private void GenProtocolNameList(XmlNodeList nodeList, List<string> nameList)
{
foreach (XmlNode node in nodeList)
{
if (node.Attributes == null)
continue;
if (node.Name == "macro")
{
var name = node.Attributes.GetNamedItem("name").Value;
if (name.StartsWith("CS_CMD") || name.StartsWith("CS_NOTIFY"))
{
var id = Convert.ToInt32(node.Attributes.GetNamedItem("value").Value);
_dicName2ID[name] = id;
if (nameList != null)
nameList.Add(name);
}
}
GenProtocolNameList(node.ChildNodes, nameList);
}
}
#endregion
#region
private void OnClickGenBtn(bool genAll)
{
_strBindNotify = new StringBuilder();
bool needRegCmdHandle = false;
StringBuilder sb = new StringBuilder();
List<int> listGenId = new List<int>();
var iter = _dicID2Select.GetEnumerator();
while (iter.MoveNext())
{
if (iter.Current.Value || genAll)
{
int resId = iter.Current.Key;
int resID;
if (_dicID2ID.TryGetValue(resId, out resID))
{
if (resID != 0)
{
var oneStr = GenOneReq(resId, resID);
sb.Append(oneStr);
sb.Append("\n\n");
listGenId.Add(resId);
listGenId.Add(resID);
}
else if (!listGenId.Contains(resId))
{
needRegCmdHandle = true;
var oneStr = GenOneReq(0, resId);
sb.Append(oneStr);
sb.Append("\n\n");
listGenId.Add(resId);
}
}
}
}
if (needRegCmdHandle)
{
sb.Append("public void RegCmdHandle()\n");
sb.Append("{\n");
sb.Append(_strBindNotify);
sb.Append("}\n");
}
TextEditor te = new TextEditor();
te.text = sb.ToString();
te.SelectAll();
te.Copy();
}
private static readonly Dictionary<string, string> TempParamDic = new Dictionary<string, string>();
private static string _reqClassName = string.Empty;
private static string _resClassName = string.Empty;
private static string _reqEnumName = string.Empty;
private static string _resEnumName = string.Empty;
private static string _reqDesc = string.Empty;
private static bool _resResult;
private string GenOneReq(int reqId, int resId)
{
TempParamDic.Clear();
_reqClassName = string.Empty;
_resClassName = string.Empty;
_reqEnumName = string.Empty;
_resEnumName = string.Empty;
_resResult = false;
var xmlFilePath = _curSelectFile;
var fileName = Path.GetFileNameWithoutExtension(xmlFilePath);
//读xml
if (fileName.StartsWith("proto_cs"))
{
Debug.Log("load xml.name:" + fileName);
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(xmlFilePath);
_GenOneReq(xmlDoc.ChildNodes, reqId,resId);
Debug.Log(fileName + " success.");
var sb = new StringBuilder();
sb.Append("#region ");
sb.Append(_reqDesc);
sb.Append(string.Format("\n//{0}\n", _reqDesc));
if (reqId != 0)
{
sb.Append("public void ");
sb.Append(_reqClassName.Substring(2));
sb.Append("(");
foreach (var item in TempParamDic)
{
sb.Append(string.Format("{0} {1}, ", item.Value, item.Key));
}
sb.Remove(sb.Length - 2, 2);//把多余的逗号和空格删了
sb.Append(")\n{\n");
sb.Append(string.Format("\tCSPkg reqPkg = ProtoUtil.BuildCSMsg(netMacros.{0});\n", _reqEnumName));
sb.Append(string.Format("\t{0} reqData = reqPkg.Body.{1};\n", _reqClassName, _reqClassName.Substring(2)));
foreach (var item in TempParamDic)
{
sb.Append(string.Format("\treqData.{0} = {0};\n", item.Key));
}
sb.Append("\n");
sb.Append(string.Format("\tGameClient.Instance.SendCSMsg(reqPkg, netMacros.{0}, {1});\n", _resEnumName,
_resClassName.Substring(2)));
sb.Append("}\n\n");
}
else
{
_strBindNotify.Append(string.Format("\t\tGameClient.Instance.RegCmdHandle(netMacros.{0}, {1});\n", _resEnumName, _resClassName.Substring(2)));
}
//回包
sb.Append(string.Format("private void {0}(CSMsgResult result, CSPkg msg)\n", _resClassName.Substring(2)));
sb.Append("{\n");
sb.Append(string.Format("\tif (DodUtil.CheckHaveError(result, msg, typeof({0})))\n", _resClassName));
sb.Append("\t\treturn;\n\n");
sb.Append(string.Format("\t{0} resData = msg.Body.{1};\n", _resClassName, _resClassName.Substring(2)));
if (_resResult)
{
sb.Append("\tif (resData.Result.Ret != 0)\n");
sb.Append("\t{\n");
sb.Append("\t\tUISys.Mgr.ShowTipMsg(resData.Result);\n");
sb.Append("\t\treturn;\n");
sb.Append("\t}\n");
}
sb.Append("\t//todo\n");
sb.Append("}\n#endregion");
return sb.ToString();
}
return null;
}
private void _GenOneReq(XmlNodeList nodeList, int reqId,int resId)
{
foreach (XmlNode node in nodeList)
{
if (node.Attributes == null)
continue;
if (node.Name.Equals("macro"))
{
var name = node.Attributes.GetNamedItem("name").Value;
if (name.StartsWith("CS_CMD") || name.StartsWith("CS_NOTIFY"))
{
var id = Convert.ToInt32(node.Attributes.GetNamedItem("value").Value);
if (id == reqId)
_reqEnumName = name;
if (id == resId)
_resEnumName = name;
}
}
if (node.Name.Equals("struct"))
{
if (node.Attributes.GetNamedItem("id") == null)
continue;
var enumName = node.Attributes.GetNamedItem("id").Value;
if (enumName.Equals(_reqEnumName))
{
var name = node.Attributes.GetNamedItem("name").Value;
_reqClassName = name;
if (node.Attributes.GetNamedItem("name") != null)
{
_reqDesc = node.Attributes.GetNamedItem("desc").Value;
}
foreach (XmlNode childNode in node.ChildNodes)
{
if (childNode != null && childNode.Name.Equals("entry"))
{
var paramName = childNode.Attributes.GetNamedItem("name").Value;
var paramType = childNode.Attributes.GetNamedItem("type").Value;
TempParamDic.Add(paramName, paramType);
}
}
}
if (enumName.Equals(_resEnumName))
{
var className = node.Attributes.GetNamedItem("name").Value;
_resClassName = className;
}
}
_GenOneReq(node.ChildNodes, reqId, resId);
}
}
#endregion
#region ToCsharp
private void ExportProto()
{
ProtoGenTools.Export();
}
#endregion
}

View File

@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 6670b23e26f70d24aa0016b4a7d1d8f3
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

Some files were not shown because too many files have changed in this diff Show More