Init enter game

This commit is contained in:
Naruse
2025-06-14 11:15:32 +08:00
commit 6a03b39f07
568 changed files with 92872 additions and 0 deletions

21
KianaBH/KianaBH.csproj Normal file
View File

@@ -0,0 +1,21 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net9.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<CETCompat>false</CETCompat>
<RootNamespace>KianaBH.KianaBH</RootNamespace>
<AssemblyName>KianaBH</AssemblyName>
<ApplicationIcon>Source\Kiana.ico</ApplicationIcon>
<SatelliteResourceLanguages>false</SatelliteResourceLanguages>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\Common\Common.csproj" />
<ProjectReference Include="..\GameServer\GameServer.csproj" />
<ProjectReference Include="..\SdkServer\SdkServer.csproj" />
</ItemGroup>
</Project>

View File

@@ -0,0 +1,92 @@
using KianaBH.Data;
using KianaBH.Database;
using KianaBH.KianaBH.Tool;
using KianaBH.GameServer.Command;
using KianaBH.GameServer.Server;
using KianaBH.Internationalization;
using KianaBH.KcpSharp;
using KianaBH.Util;
using System.Globalization;
namespace KianaBH.KianaBH.Program;
public class KianaBH
{
public static readonly Logger Logger = new("KianaBH");
public static readonly DatabaseHelper DatabaseHelper = new();
public static readonly Listener Listener = new();
public static readonly CommandManager CommandManager = new();
public static async Task Main()
{
var time = DateTime.Now;
RegisterExitEvent();
IConsole.InitConsole();
LoaderManager.InitConfig();
await LoaderManager.InitSdkServer();
LoaderManager.InitPacket();
LoaderManager.InitDatabase();
if (!DatabaseHelper.LoadAllData)
{
var t = Task.Run(() =>
{
while (!DatabaseHelper.LoadAllData) // wait for all data to be loaded
Thread.Sleep(100);
});
await t.WaitAsync(new CancellationToken());
Logger.Info(I18NManager.Translate("Server.ServerInfo.LoadedItem", I18NManager.Translate("Word.Database")));
}
Logger.Warn(I18NManager.Translate("Server.ServerInfo.WaitForAllDone"));
await LoaderManager.InitResource();
ResourceManager.IsLoaded = true;
HandbookGenerator.GenerateAll();
LoaderManager.InitCommand();
var elapsed = DateTime.Now - time;
Logger.Info(I18NManager.Translate("Server.ServerInfo.ServerStarted",
Math.Round(elapsed.TotalSeconds, 2).ToString(CultureInfo.InvariantCulture)));
if (ConfigManager.Config.ServerOption.EnableMission)
Logger.Warn(I18NManager.Translate("Server.ServerInfo.MissionEnabled"));
}
# region Exit
private static void RegisterExitEvent()
{
AppDomain.CurrentDomain.ProcessExit += (_, _) =>
{
Logger.Info(I18NManager.Translate("Server.ServerInfo.Shutdown"));
ProcessExit();
};
AppDomain.CurrentDomain.UnhandledException += (obj, arg) =>
{
Logger.Error(I18NManager.Translate("Server.ServerInfo.UnhandledException", obj.GetType().Name),
(Exception)arg.ExceptionObject);
Logger.Info(I18NManager.Translate("Server.ServerInfo.Shutdown"));
ProcessExit();
Environment.Exit(1);
};
Console.CancelKeyPress += (_, eventArgs) =>
{
Logger.Info(I18NManager.Translate("Server.ServerInfo.CancelKeyPressed"));
eventArgs.Cancel = true;
Environment.Exit(0);
};
}
private static void ProcessExit()
{
KcpListener.Connections.Values.ToList().ForEach(x => x.Stop(true));
DatabaseHelper.SaveThread?.Interrupt();
DatabaseHelper.SaveDatabase();
}
# endregion
}

View File

@@ -0,0 +1,175 @@
using System.Reflection;
using KianaBH.Data;
using KianaBH.Database;
using KianaBH.KianaBH.Tool;
using KianaBH.GameServer.Command;
using KianaBH.GameServer.Server;
using KianaBH.GameServer.Server.Packet;
using KianaBH.Internationalization;
using KianaBH.KcpSharp;
using KianaBH.Proto;
using KianaBH.Util;
using KianaBH.Util.Security;
namespace KianaBH.KianaBH.Program;
public class LoaderManager : KianaBH
{
public static void InitConfig()
{
// Initialize log
var counter = 0;
FileInfo file;
while (true)
{
file = new FileInfo(ConfigManager.Config.Path.LogPath + $"/{DateTime.Now:yyyy-MM-dd}-{++counter}.log");
if (file is not { Exists: false, Directory: not null }) continue;
file.Directory.Create();
break;
}
Logger.SetLogFile(file);
// Init all directories
try
{
ConfigManager.InitDirectories();
}
catch (Exception e)
{
Logger.Error(I18NManager.Translate("Server.ServerInfo.FailedToLoadItem", I18NManager.Translate("Word.Config")), e);
Console.ReadLine();
return;
}
// Starting the server
Logger.Info(I18NManager.Translate("Server.ServerInfo.StartingServer"));
// Load the config
Logger.Info(I18NManager.Translate("Server.ServerInfo.LoadingItem", I18NManager.Translate("Word.Config")));
try
{
ConfigManager.LoadConfig();
}
catch (Exception e)
{
Logger.Error(
I18NManager.Translate("Server.ServerInfo.FailedToLoadItem", I18NManager.Translate("Word.Config")), e);
Console.ReadLine();
return;
}
// Load the language
Logger.Info(I18NManager.Translate("Server.ServerInfo.LoadingItem", I18NManager.Translate("Word.Language")));
try
{
I18NManager.LoadLanguage();
}
catch (Exception e)
{
Logger.Error(
I18NManager.Translate("Server.ServerInfo.FailedToLoadItem", I18NManager.Translate("Word.Language")), e);
Console.ReadLine();
return;
}
}
public static void InitDatabase()
{
// Initialize the database
try
{
_ = Task.Run(DatabaseHelper.Initialize); // do not wait
while (!DatabaseHelper.LoadAccount) Thread.Sleep(100);
Logger.Info(I18NManager.Translate("Server.ServerInfo.LoadedItem",
I18NManager.Translate("Word.DatabaseAccount")));
}
catch (Exception e)
{
Logger.Error(
I18NManager.Translate("Server.ServerInfo.FailedToLoadItem", I18NManager.Translate("Word.Database")), e);
Console.ReadLine();
return;
}
}
public static async Task InitSdkServer()
{
SdkServer.SdkServer.Main([]);
Logger.Info(I18NManager.Translate("Server.ServerInfo.ServerRunning", I18NManager.Translate("Word.Dispatch"),
ConfigManager.Config.HttpServer.GetDisplayAddress()));
KcpListener.BaseConnection = typeof(Connection);
KcpListener.StartListener();
await Task.CompletedTask;
}
public static void InitPacket()
{
// get opcode from CmdIds
var opcodes = typeof(CmdIds).GetFields().Where(x => x.FieldType == typeof(int)).ToList();
foreach (var opcode in opcodes)
{
var name = opcode.Name;
var value = (int)opcode.GetValue(null)!;
KcpConnection.LogMap.TryAdd(value, name);
}
HandlerManager.Init();
}
public static async Task InitResource()
{
// Init custom files
Logger.Info(I18NManager.Translate("Server.ServerInfo.GeneratingItem", I18NManager.Translate("Word.CustomData")));
try
{
await AssemblyGenerater.LoadCustomData(Assembly.GetExecutingAssembly());
}
catch (Exception e)
{
Logger.Error(
I18NManager.Translate("Server.ServerInfo.FailedToLoadItem", I18NManager.Translate("Word.CustomData")), e);
Console.ReadLine();
return;
}
// Load the game data
try
{
Logger.Info(I18NManager.Translate("Server.ServerInfo.LoadingItem", I18NManager.Translate("Word.GameData")));
ResourceManager.LoadGameData();
}
catch (Exception e)
{
Logger.Error(
I18NManager.Translate("Server.ServerInfo.FailedToLoadItem", I18NManager.Translate("Word.GameData")), e);
Console.ReadLine();
return;
}
}
public static void InitCommand()
{
// Register the command handlers
try
{
CommandManager.RegisterCommands();
}
catch (Exception e)
{
Logger.Error(
I18NManager.Translate("Server.ServerInfo.FailedToInitializeItem",
I18NManager.Translate("Word.Command")), e);
Console.ReadLine();
return;
}
IConsole.OnConsoleExcuteCommand += CommandExecutor.ConsoleExcuteCommand;
CommandExecutor.OnRunCommand += (sender, e) => { CommandManager.HandleCommand(e, sender); };
IConsole.ListenConsole();
}
}

View File

@@ -0,0 +1,18 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
https://go.microsoft.com/fwlink/?LinkID=208121.
-->
<Project>
<PropertyGroup>
<Configuration>Debug</Configuration>
<Platform>Any CPU</Platform>
<PublishDir>bin\KianaBH-Win64-Debug</PublishDir>
<PublishProtocol>FileSystem</PublishProtocol>
<_TargetId>Folder</_TargetId>
<TargetFramework>net9.0</TargetFramework>
<RuntimeIdentifier>win-x64</RuntimeIdentifier>
<SelfContained>false</SelfContained>
<PublishSingleFile>false</PublishSingleFile>
<PublishReadyToRun>false</PublishReadyToRun>
</PropertyGroup>
</Project>

View File

@@ -0,0 +1,19 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
https://go.microsoft.com/fwlink/?LinkID=208121.
-->
<Project>
<PropertyGroup>
<Configuration>Release</Configuration>
<Platform>Any CPU</Platform>
<PublishDir>bin\KianaBH-MultiFile\</PublishDir>
<PublishProtocol>FileSystem</PublishProtocol>
<_TargetId>Folder</_TargetId>
<TargetFramework>net9.0</TargetFramework>
<RuntimeIdentifier>win-x64</RuntimeIdentifier>
<SelfContained>true</SelfContained>
<PublishSingleFile>false</PublishSingleFile>
<PublishReadyToRun>true</PublishReadyToRun>
<PublishTrimmed>false</PublishTrimmed>
</PropertyGroup>
</Project>

View File

@@ -0,0 +1,19 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
https://go.microsoft.com/fwlink/?LinkID=208121.
-->
<Project>
<PropertyGroup>
<Configuration>Release</Configuration>
<Platform>Any CPU</Platform>
<PublishDir>bin\KianaBH-OneFile\</PublishDir>
<PublishProtocol>FileSystem</PublishProtocol>
<_TargetId>Folder</_TargetId>
<TargetFramework>net9.0</TargetFramework>
<RuntimeIdentifier>win-x64</RuntimeIdentifier>
<SelfContained>true</SelfContained>
<PublishSingleFile>true</PublishSingleFile>
<PublishReadyToRun>true</PublishReadyToRun>
<PublishTrimmed>false</PublishTrimmed>
</PropertyGroup>
</Project>

BIN
KianaBH/Source/Kiana.ico Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 422 KiB

View File

@@ -0,0 +1,38 @@
using KianaBH.Util;
using System.Reflection;
namespace KianaBH.KianaBH.Tool;
public class AssemblyGenerater
{
private static readonly string SourceSpace = "KianaBH.KianaBH.Source.";
public static async ValueTask LoadCustomData(Assembly assembly)
{
string[] embededRes = assembly.GetManifestResourceNames();
foreach (var res in embededRes)
{
var stream = assembly.GetManifestResourceStream(res);
if (stream != null && res.Contains(ConfigManager.Config.Path.DataPath.Split("/").Last()))
await WriteOutputFiles(stream, res);
}
}
private async static ValueTask WriteOutputFiles(Stream stream, string resSpace)
{
if (stream == null) return;
string relativePath = resSpace.Replace(SourceSpace, "");
int lastDotIndex = relativePath.LastIndexOf('.');
string outputPath = string.Concat(
ConfigManager.Config.Path.ConfigPath, "/",
relativePath[..lastDotIndex].Replace('.', '/'),
relativePath.AsSpan(lastDotIndex));
if (File.Exists(outputPath)) return; // Check if file exist
using var fileStream = new FileStream(outputPath, FileMode.Create, FileAccess.Write);
stream.Position = 0;
await stream.CopyToAsync(fileStream);
}
}

View File

@@ -0,0 +1,95 @@
using KianaBH.Data;
using KianaBH.GameServer.Command;
using KianaBH.Internationalization;
using KianaBH.Util;
using Newtonsoft.Json;
using System.Text;
namespace KianaBH.KianaBH.Tool;
public static class HandbookGenerator
{
public static void GenerateAll()
{
var directory = new DirectoryInfo(ConfigManager.Config.Path.ResourcePath + "/TextMap");
var handbook = new DirectoryInfo(ConfigManager.Config.Path.HandbookPath);
if (!handbook.Exists) handbook.Create();
if (!directory.Exists) return;
foreach (var langFile in directory.GetFiles())
{
if (langFile.Extension != ".json") continue;
var lang = langFile.Name.Replace("TextMap", "").Replace(".json", "");
// Check if handbook needs to regenerate
var handbookPath = $"{ConfigManager.Config.Path.HandbookPath}/Handbook{lang}.txt";
if (File.Exists(handbookPath))
{
var handbookInfo = new FileInfo(handbookPath);
if (handbookInfo.LastWriteTime >= langFile.LastWriteTime)
continue; // Skip if handbook is newer than language file
}
Generate(lang);
}
Logger.GetByClassName()
.Info(I18NManager.Translate("Server.ServerInfo.GeneratedItem", I18NManager.Translate("Word.Handbook")));
}
public static void Generate(string lang)
{
var textMapPath = ConfigManager.Config.Path.ResourcePath + "/TextMap/TextMap" + lang + ".json";
var fallbackTextMapPath = ConfigManager.Config.Path.ResourcePath + "/TextMap/TextMap" +
ConfigManager.Config.ServerOption.FallbackLanguage + ".json";
if (!File.Exists(textMapPath))
{
Logger.GetByClassName().Error(I18NManager.Translate("Server.ServerInfo.FailedToReadItem", textMapPath,
I18NManager.Translate("Word.NotFound")));
return;
}
if (!File.Exists(fallbackTextMapPath))
{
Logger.GetByClassName().Error(I18NManager.Translate("Server.ServerInfo.FailedToReadItem", textMapPath,
I18NManager.Translate("Word.NotFound")));
return;
}
var textMap = JsonConvert.DeserializeObject<Dictionary<long, string>>(File.ReadAllText(textMapPath));
var fallbackTextMap =
JsonConvert.DeserializeObject<Dictionary<long, string>>(File.ReadAllText(fallbackTextMapPath));
if (textMap == null || fallbackTextMap == null)
{
Logger.GetByClassName().Error(I18NManager.Translate("Server.ServerInfo.FailedToReadItem", textMapPath,
I18NManager.Translate("Word.Error")));
return;
}
var builder = new StringBuilder();
builder.AppendLine("#Handbook generated in " + DateTime.Now.ToString("yyyy/MM/dd HH:mm"));
builder.AppendLine();
builder.AppendLine("#Command");
builder.AppendLine();
GenerateCmd(builder, lang);
builder.AppendLine();
WriteToFile(lang, builder.ToString());
}
public static void GenerateCmd(StringBuilder builder, string lang)
{
foreach (var cmd in CommandManager.CommandInfo)
{
builder.Append("\t" + cmd.Key);
var desc = I18NManager.TranslateAsCertainLang(lang, cmd.Value.Description).Replace("\n", "\n\t\t");
builder.AppendLine(": " + desc);
}
}
public static void WriteToFile(string lang, string content)
{
File.WriteAllText($"{ConfigManager.Config.Path.HandbookPath}/Handbook{lang}.txt", content);
}
}