Add automatic versioning and server configuration XML in preparation for services

This commit is contained in:
John Gross
2017-02-05 08:26:48 -08:00
parent fa63f3d811
commit d5159dc72a
33 changed files with 501 additions and 216 deletions

View File

@@ -3,7 +3,7 @@
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<targets>
<target name="logfile" layout="${longdate} [${level:uppercase=true}] ${logger}: ${message}" xsi:type="File" fileName="Torch.log" />
<target name="logfile" layout="${longdate} [${level:uppercase=true}] ${logger}: ${message}" xsi:type="File" fileName="Torch.log" deleteOldFileOnStartup="true"/>
<target name="console" layout="${longdate} [${level:uppercase=true}] ${logger}: ${message}" xsi:type="ColoredConsole" />
</targets>

View File

@@ -3,11 +3,15 @@ using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Sandbox;
using Sandbox.Game.Entities;
using Sandbox.Game.World;
using Torch.Commands;
using VRage.Game.Entity;
using VRage.Game.ModAPI;
namespace TestPlugin
{
[Category("admin", "tools")]
public class Commands : CommandModule
{
[Command("Ban", "Bans a player from the game")]

View File

@@ -26,7 +26,7 @@ namespace TestPlugin
}
/// <inheritdoc />
public override void Unload()
public override void Dispose()
{
//Torch.Log.Write($"Plugin unload {Name}");
}

View File

@@ -31,6 +31,9 @@
<CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet>
</PropertyGroup>
<ItemGroup>
<Reference Include="Sandbox.Game">
<HintPath>..\..\..\..\..\..\..\Program Files (x86)\Steam\steamapps\common\SpaceEngineers\Bin64\Sandbox.Game.dll</HintPath>
</Reference>
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.Xml.Linq" />
@@ -42,6 +45,11 @@
<Reference Include="VRage">
<HintPath>..\..\..\..\..\..\..\Program Files (x86)\Steam\steamapps\common\SpaceEngineers\Bin64\VRage.dll</HintPath>
</Reference>
<Reference Include="VRage.Game, Version=1.0.0.0, Culture=neutral, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\..\..\..\..\..\..\Program Files (x86)\Steam\steamapps\common\SpaceEngineers\Bin64\VRage.Game.dll</HintPath>
</Reference>
<Reference Include="VRage.Math, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" />
</ItemGroup>
<ItemGroup>
<Compile Include="Commands.cs" />

View File

@@ -9,6 +9,6 @@ namespace Torch.API
{
void UpdatePlugins();
void Init();
void UnloadPlugins();
void DisposePlugins();
}
}

View File

@@ -8,10 +8,13 @@ namespace Torch.API
{
public interface ITorchBase
{
event Action SessionLoading;
event Action SessionLoaded;
event Action SessionUnloading;
event Action SessionUnloaded;
IMultiplayer Multiplayer { get; }
IPluginManager Plugins { get; }
Version Version { get; }
Version TorchVersion { get; }
void Invoke(Action action);
void InvokeBlocking(Action action);
Task InvokeAsync(Action action);

View File

@@ -7,7 +7,7 @@ using System.Threading.Tasks;
namespace Torch.API
{
public interface ITorchPlugin
public interface ITorchPlugin : IDisposable
{
Guid Id { get; }
Version Version { get; }
@@ -23,10 +23,5 @@ namespace Torch.API
/// Called after each game tick. Not thread safe, use invocation methods in <see cref="ITorchBase"/>.
/// </summary>
void Update();
/// <summary>
/// Called when the game exits.
/// </summary>
void Unload();
}
}

View File

@@ -1,12 +1,17 @@
using System;
using System.Windows;
using NLog;
namespace Torch.Client
{
public static class Program
{
private static Logger _log = LogManager.GetLogger("Torch");
public static void Main(string[] args)
{
AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
var client = new TorchClient();
try
@@ -15,11 +20,18 @@ namespace Torch.Client
}
catch (Exception e)
{
MessageBox.Show($"Torch encountered an error trying to initialize the game.\n{e.Message}");
_log.Fatal("Torch encountered an error trying to initialize the game.");
_log.Fatal(e);
return;
}
client.Start();
}
private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
var ex = (Exception)e.ExceptionObject;
MessageBox.Show(ex.StackTrace, ex.Message);
}
}
}

View File

@@ -1,55 +1,16 @@
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;

using System.Reflection;
using System.Runtime.InteropServices;
using System.Windows;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("PistonClient")]
[assembly: AssemblyTitle("Torch Client")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("PistonClient")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyProduct("Torch")]
[assembly: AssemblyCopyright("Copyright © Torch API 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
//In order to begin building localizable applications, set
//<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file
//inside a <PropertyGroup>. For example, if you are using US english
//in your source files, set the <UICulture> to en-US. Then uncomment
//the NeutralResourceLanguage attribute below. Update the "en-US" in
//the line below to match the UICulture setting in the project file.
//[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)]
[assembly: ThemeInfo(
ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located
//(used if a resource is not found in the page,
// or application resource dictionaries)
ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located
//(used if a resource is not found in the page,
// app, or any theme specific resource dictionaries)
)]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyVersion("1.0.35.456")]
[assembly: AssemblyFileVersion("1.0.35.456")]

View File

@@ -0,0 +1,28 @@
<#@ template debug="false" hostspecific="false" language="C#" #>
<#@ assembly name="System.Core" #>
<#@ import namespace="System.Linq" #>
<#@ import namespace="System.Text" #>
<#@ import namespace="System.Collections.Generic" #>
<#@ output extension=".cs" #>
using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("Torch Client")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Torch")]
[assembly: AssemblyCopyright("Copyright © Torch API 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
<# var dt = DateTime.Now;
int major = 1;
int minor = 0;
int build = dt.DayOfYear;
int rev = (int)dt.TimeOfDay.TotalMinutes / 2;
#>
[assembly: AssemblyVersion("<#= major #>.<#= minor #>.<#= build #>.<#= rev #>")]
[assembly: AssemblyFileVersion("<#= major #>.<#= minor #>.<#= build #>.<#= rev #>")]

View File

@@ -36,6 +36,9 @@
<CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet>
<Prefer32Bit>true</Prefer32Bit>
</PropertyGroup>
<PropertyGroup>
<ApplicationIcon>torchicon.ico</ApplicationIcon>
</PropertyGroup>
<ItemGroup>
<Reference Include="NLog, Version=4.0.0.0, Culture=neutral, PublicKeyToken=5120e14c03d0593c, processorArchitecture=MSIL">
<HintPath>..\packages\NLog.4.4.1\lib\net45\NLog.dll</HintPath>
@@ -100,14 +103,16 @@
<Reference Include="PresentationFramework" />
</ItemGroup>
<ItemGroup>
<Compile Include="Properties\AssemblyInfo.cs">
<DependentUpon>AssemblyInfo.tt</DependentUpon>
<AutoGen>True</AutoGen>
<DesignTime>True</DesignTime>
</Compile>
<Compile Include="TorchClient.cs" />
<Compile Include="TorchConsoleScreen.cs" />
<Compile Include="TorchMainMenuScreen.cs" />
<Compile Include="TorchSettingsScreen.cs" />
<Compile Include="Program.cs" />
<Compile Include="Properties\AssemblyInfo.cs">
<SubType>Code</SubType>
</Compile>
<Compile Include="Properties\Resources.Designer.cs">
<AutoGen>True</AutoGen>
<DesignTime>True</DesignTime>
@@ -141,6 +146,18 @@
<Private>True</Private>
</ProjectReference>
</ItemGroup>
<ItemGroup>
<Resource Include="torchicon.ico" />
</ItemGroup>
<ItemGroup>
<Content Include="Properties\AssemblyInfo.tt">
<Generator>TextTemplatingFileGenerator</Generator>
<LastGenOutput>AssemblyInfo.cs</LastGenOutput>
</Content>
</ItemGroup>
<ItemGroup>
<Service Include="{508349B6-6B84-4DF5-91F0-309BEEBAD82D}" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<PropertyGroup>
<PostBuildEvent>copy "$(SolutionDir)NLog.config" "$(TargetDir)"</PostBuildEvent>

View File

@@ -7,6 +7,7 @@ using System.Threading.Tasks;
using System.Windows;
using Sandbox;
using Sandbox.Engine.Platform;
using Sandbox.Engine.Utils;
using Sandbox.Game;
using SpaceEngineers.Game;
using Torch.API;
@@ -24,6 +25,7 @@ namespace Torch.Client
public override void Init()
{
Log.Info("Initializing Torch Client");
base.Init();
if (!File.Exists("steam_appid.txt"))
@@ -71,9 +73,8 @@ namespace Torch.Client
{
Persons = new List<MyCreditsPerson>
{
new MyCreditsPerson("JIMMACLE"),
new MyCreditsPerson("REXXAR"),
new MyCreditsPerson("PHOENIXTHESAGE")
new MyCreditsPerson("THE TORCH TEAM"),
new MyCreditsPerson("http://github.com/TorchSE"),
}
};
MyPerGameSettings.Credits.Departments.Insert(0, credits);

BIN
Torch.Client/torchicon.ico Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 17 KiB

View File

@@ -12,9 +12,14 @@ using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Threading;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using NLog;
using Sandbox.Game.World;
using Sandbox.ModAPI;
using Torch;
using Torch.API;
using VRage.Game.ModAPI;
namespace Torch.Server
{
@@ -34,19 +39,49 @@ namespace Torch.Server
return;
}
if (args.FirstOrDefault() == "-svcinstall")
string configName = args.Length > 0 ? args[0] : "TorchConfig.xml";
var configPath = Path.Combine(Directory.GetCurrentDirectory(), configName);
var options = new ServerConfig("Torch");
if (File.Exists(configName))
{
/* Working on installing the service properly instead of with sc.exe
_log.Info("Installing service");
var installer = new TorchServiceInstaller();
installer.Context = new InstallContext(Path.Combine(Directory.GetCurrentDirectory(), "svclog.log"), null);
installer.Context.Parameters.Add("name", "Torch DS");
installer.Install(new Hashtable
_log.Info($"Loading config {configPath}");
options = ServerConfig.LoadFrom(configPath);
}
else
{
{"name", "Torch DS"}
_log.Info($"Generating default config at {configPath}");
options.SaveTo(configPath);
}
});
_log.Info("Service Installed");*/
/*
if (!parser.ParseArguments(args, options))
{
_log.Error($"Parsing arguments failed: {string.Join(" ", args)}");
return;
}
if (!string.IsNullOrEmpty(options.Config) && File.Exists(options.Config))
{
options = ServerConfig.LoadFrom(options.Config);
parser.ParseArguments(args, options);
}*/
//RestartOnCrash autostart autosave=15
//gamepath ="C:\Program Files\Space Engineers DS" instance="Hydro Survival" instancepath="C:\ProgramData\SpaceEngineersDedicated\Hydro Survival"
/*
if (options.InstallService)
{
var serviceName = $"\"Torch - {options.InstanceName}\"";
// Working on installing the service properly instead of with sc.exe
_log.Info($"Installing service '{serviceName}");
var exePath = $"\"{Assembly.GetExecutingAssembly().Location}\"";
var createInfo = new ServiceCreateInfo
{
Name = options.InstanceName,
BinaryPath = exePath,
};
_log.Info("Service Installed");
var runArgs = string.Join(" ", args.Skip(1));
_log.Info($"Installing Torch as a service with arguments '{runArgs}'");
@@ -63,7 +98,7 @@ namespace Torch.Server
return;
}
if (args.FirstOrDefault() == "-svcuninstall")
if (options.UninstallService)
{
_log.Info("Uninstalling Torch service");
var startInfo = new ProcessStartInfo
@@ -77,9 +112,9 @@ namespace Torch.Server
Process.Start(startInfo).WaitForExit();
_log.Info("Torch service uninstalled");
return;
}
}*/
_server = new TorchServer();
_server = new TorchServer(options);
_server.Init();
_server.Start();
}

View File

@@ -1,55 +1,16 @@
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;

using System.Reflection;
using System.Runtime.InteropServices;
using System.Windows;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("TorchServer")]
[assembly: AssemblyTitle("Torch Server")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("TorchServer")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyProduct("Torch")]
[assembly: AssemblyCopyright("Copyright © Torch API 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
//In order to begin building localizable applications, set
//<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file
//inside a <PropertyGroup>. For example, if you are using US english
//in your source files, set the <UICulture> to en-US. Then uncomment
//the NeutralResourceLanguage attribute below. Update the "en-US" in
//the line below to match the UICulture setting in the project file.
//[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)]
[assembly: ThemeInfo(
ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located
//(used if a resource is not found in the page,
// or application resource dictionaries)
ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located
//(used if a resource is not found in the page,
// app, or any theme specific resource dictionaries)
)]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyVersion("1.0.35.456")]
[assembly: AssemblyFileVersion("1.0.35.456")]

View File

@@ -0,0 +1,28 @@
<#@ template debug="false" hostspecific="false" language="C#" #>
<#@ assembly name="System.Core" #>
<#@ import namespace="System.Linq" #>
<#@ import namespace="System.Text" #>
<#@ import namespace="System.Collections.Generic" #>
<#@ output extension=".cs" #>
using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("Torch Server")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Torch")]
[assembly: AssemblyCopyright("Copyright © Torch API 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
<# var dt = DateTime.Now;
int major = 1;
int minor = 0;
int build = dt.DayOfYear;
int rev = (int)dt.TimeOfDay.TotalMinutes / 2;
#>
[assembly: AssemblyVersion("<#= major #>.<#= minor #>.<#= build #>.<#= rev #>")]
[assembly: AssemblyFileVersion("<#= major #>.<#= minor #>.<#= build #>.<#= rev #>")]

View File

@@ -0,0 +1,70 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;
using NLog;
using VRage.Dedicated;
namespace Torch.Server
{
public class ServerConfig
{
private static Logger _log = LogManager.GetLogger("Config");
public string InstancePath { get; set; }
public string InstanceName { get; set; }
//public string SaveName { get; set; }
public int Autosave { get; set; }
public bool AutoRestart { get; set; }
public ServerConfig(string instanceName = "Torch", string instancePath = null, int autosaveInterval = 5, bool autoRestart = false)
{
InstanceName = instanceName;
InstancePath = instancePath ?? Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), "Torch", InstanceName);
Autosave = autosaveInterval;
AutoRestart = autoRestart;
}
public static ServerConfig LoadFrom(string path)
{
_log.Info($"Loading config from '{path}'");
try
{
var serializer = new XmlSerializer(typeof(ServerConfig));
ServerConfig config;
using (var f = File.OpenRead(path))
{
config = (ServerConfig)serializer.Deserialize(f);
}
return config;
}
catch (Exception e)
{
Console.WriteLine(e);
return null;
}
}
public bool SaveTo(string path)
{
_log.Info($"Saving config to '{path}'");
try
{
var serializer = new XmlSerializer(typeof(ServerConfig));
using (var f = File.OpenWrite(path))
{
serializer.Serialize(f, this);
}
return true;
}
catch (Exception e)
{
Console.WriteLine(e);
return false;
}
}
}
}

Binary file not shown.

Before

Width:  |  Height:  |  Size: 31 KiB

View File

@@ -40,7 +40,7 @@
<StartupObject>Torch.Server.Program</StartupObject>
</PropertyGroup>
<PropertyGroup>
<ApplicationIcon>SpaceEngineers.ico</ApplicationIcon>
<ApplicationIcon>torchicon.ico</ApplicationIcon>
</PropertyGroup>
<ItemGroup>
<Reference Include="HavokWrapper, Version=1.0.6051.28726, Culture=neutral, processorArchitecture=AMD64">
@@ -48,28 +48,38 @@
<HintPath>C:\Program Files (x86)\Steam\steamapps\common\SpaceEngineers\DedicatedServer64\HavokWrapper.dll</HintPath>
<Private>False</Private>
</Reference>
<Reference Include="Microsoft.CodeAnalysis, Version=1.2.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\..\..\..\..\..\..\Program Files (x86)\Steam\steamapps\common\SpaceEngineers\Bin64\Microsoft.CodeAnalysis.dll</HintPath>
</Reference>
<Reference Include="Microsoft.CodeAnalysis.CSharp, Version=1.2.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\..\..\..\..\..\..\Program Files (x86)\Steam\steamapps\common\SpaceEngineers\Bin64\Microsoft.CodeAnalysis.CSharp.dll</HintPath>
</Reference>
<Reference Include="NLog, Version=4.0.0.0, Culture=neutral, PublicKeyToken=5120e14c03d0593c, processorArchitecture=MSIL">
<HintPath>..\packages\NLog.4.4.1\lib\net45\NLog.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="Sandbox.Common, Version=1.0.0.0, Culture=neutral, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>C:\Program Files (x86)\Steam\steamapps\common\SpaceEngineers\DedicatedServer64\Sandbox.Common.dll</HintPath>
<Private>False</Private>
<Reference Include="Sandbox.Common">
<HintPath>..\..\..\..\..\..\..\steamcmd\steamapps\common\SpaceEngineersDedicatedServer\DedicatedServer64\Sandbox.Common.dll</HintPath>
</Reference>
<Reference Include="Sandbox.Game, Version=0.1.6101.33378, Culture=neutral, processorArchitecture=AMD64">
<SpecificVersion>False</SpecificVersion>
<HintPath>C:\Program Files (x86)\Steam\steamapps\common\SpaceEngineers\DedicatedServer64\Sandbox.Game.dll</HintPath>
<Private>False</Private>
<Reference Include="Sandbox.Game">
<HintPath>..\..\..\..\..\..\..\steamcmd\steamapps\common\SpaceEngineersDedicatedServer\DedicatedServer64\Sandbox.Game.dll</HintPath>
</Reference>
<Reference Include="SpaceEngineers.Game, Version=1.0.0.0, Culture=neutral, processorArchitecture=AMD64">
<Reference Include="Sandbox.Graphics, Version=0.1.6236.31422, Culture=neutral, processorArchitecture=AMD64">
<SpecificVersion>False</SpecificVersion>
<HintPath>C:\Program Files (x86)\Steam\steamapps\common\SpaceEngineers\Bin64\SpaceEngineers.Game.dll</HintPath>
<Private>False</Private>
<HintPath>..\..\..\..\..\..\..\steamcmd\steamapps\common\SpaceEngineersDedicatedServer\DedicatedServer64\Sandbox.Graphics.dll</HintPath>
</Reference>
<Reference Include="SpaceEngineersDedicated">
<HintPath>C:\Program Files (x86)\Steam\steamapps\common\SpaceEngineers\DedicatedServer64\SpaceEngineersDedicated.exe</HintPath>
<Private>False</Private>
<Reference Include="SpaceEngineers.Game">
<HintPath>..\..\..\..\..\..\..\steamcmd\steamapps\common\SpaceEngineersDedicatedServer\DedicatedServer64\SpaceEngineers.Game.dll</HintPath>
</Reference>
<Reference Include="SpaceEngineers.ObjectBuilders, Version=1.0.0.0, Culture=neutral, processorArchitecture=AMD64">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\..\..\..\..\..\..\steamcmd\steamapps\common\SpaceEngineersDedicatedServer\DedicatedServer64\SpaceEngineers.ObjectBuilders.dll</HintPath>
</Reference>
<Reference Include="SpaceEngineers.ObjectBuilders.XmlSerializers, Version=1.0.0.0, Culture=neutral, processorArchitecture=AMD64">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\..\..\..\..\..\..\steamcmd\steamapps\common\SpaceEngineersDedicatedServer\DedicatedServer64\SpaceEngineers.ObjectBuilders.XmlSerializers.dll</HintPath>
</Reference>
<Reference Include="SteamSDK, Version=0.0.0.0, Culture=neutral, processorArchitecture=AMD64">
<SpecificVersion>False</SpecificVersion>
@@ -91,36 +101,63 @@
<Reference Include="System.Xaml">
<RequiredTargetFramework>4.0</RequiredTargetFramework>
</Reference>
<Reference Include="VRage, Version=1.0.0.0, Culture=neutral, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>C:\Program Files (x86)\Steam\steamapps\common\SpaceEngineers\Bin64\VRage.dll</HintPath>
<Private>False</Private>
<Reference Include="VRage">
<HintPath>..\..\..\..\..\..\..\steamcmd\steamapps\common\SpaceEngineersDedicatedServer\DedicatedServer64\VRage.dll</HintPath>
</Reference>
<Reference Include="VRage.Dedicated, Version=1.0.0.0, Culture=neutral, processorArchitecture=AMD64">
<Reference Include="VRage.Audio, Version=1.0.0.0, Culture=neutral, processorArchitecture=AMD64">
<SpecificVersion>False</SpecificVersion>
<HintPath>C:\Program Files (x86)\Steam\steamapps\common\SpaceEngineers\DedicatedServer64\VRage.Dedicated.dll</HintPath>
<Private>False</Private>
<HintPath>..\..\..\..\..\..\..\steamcmd\steamapps\common\SpaceEngineersDedicatedServer\DedicatedServer64\VRage.Audio.dll</HintPath>
</Reference>
<Reference Include="VRage.Game, Version=1.0.0.0, Culture=neutral, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>C:\Program Files (x86)\Steam\steamapps\common\SpaceEngineers\DedicatedServer64\VRage.Game.dll</HintPath>
<Private>False</Private>
<Reference Include="VRage.Dedicated">
<HintPath>..\..\..\..\..\..\..\steamcmd\steamapps\common\SpaceEngineersDedicatedServer\DedicatedServer64\VRage.Dedicated.dll</HintPath>
</Reference>
<Reference Include="VRage.Input, Version=1.0.0.0, Culture=neutral, processorArchitecture=AMD64">
<SpecificVersion>False</SpecificVersion>
<HintPath>C:\Program Files (x86)\Steam\steamapps\common\SpaceEngineers\Bin64\VRage.Input.dll</HintPath>
<Private>False</Private>
<Reference Include="VRage.Game">
<HintPath>..\..\..\..\..\..\..\steamcmd\steamapps\common\SpaceEngineersDedicatedServer\DedicatedServer64\VRage.Game.dll</HintPath>
</Reference>
<Reference Include="VRage.Library, Version=1.0.0.0, Culture=neutral, processorArchitecture=MSIL">
<Reference Include="VRage.Game.XmlSerializers">
<HintPath>..\..\..\..\..\..\..\steamcmd\steamapps\common\SpaceEngineersDedicatedServer\DedicatedServer64\VRage.Game.XmlSerializers.dll</HintPath>
</Reference>
<Reference Include="VRage.Input">
<HintPath>..\..\..\..\..\..\..\steamcmd\steamapps\common\SpaceEngineersDedicatedServer\DedicatedServer64\VRage.Input.dll</HintPath>
</Reference>
<Reference Include="VRage.Library">
<HintPath>..\..\..\..\..\..\..\steamcmd\steamapps\common\SpaceEngineersDedicatedServer\DedicatedServer64\VRage.Library.dll</HintPath>
</Reference>
<Reference Include="VRage.Math, Version=1.0.0.0, Culture=neutral, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>C:\Program Files (x86)\Steam\steamapps\common\SpaceEngineers\Bin64\VRage.Library.dll</HintPath>
<Private>False</Private>
<HintPath>..\..\..\..\..\..\..\steamcmd\steamapps\common\SpaceEngineersDedicatedServer\DedicatedServer64\VRage.Math.dll</HintPath>
</Reference>
<Reference Include="VRage.Native, Version=0.0.0.0, Culture=neutral, processorArchitecture=AMD64">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\..\..\..\..\..\..\steamcmd\steamapps\common\SpaceEngineersDedicatedServer\DedicatedServer64\VRage.Native.dll</HintPath>
</Reference>
<Reference Include="VRage.OpenVRWrapper, Version=1.0.0.0, Culture=neutral, processorArchitecture=AMD64">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\..\..\..\..\..\..\steamcmd\steamapps\common\SpaceEngineersDedicatedServer\DedicatedServer64\VRage.OpenVRWrapper.dll</HintPath>
</Reference>
<Reference Include="VRage.Render, Version=1.0.0.0, Culture=neutral, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\..\..\..\..\..\..\steamcmd\steamapps\common\SpaceEngineersDedicatedServer\DedicatedServer64\VRage.Render.dll</HintPath>
</Reference>
<Reference Include="VRage.Render11, Version=1.0.0.0, Culture=neutral, processorArchitecture=AMD64">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\..\..\..\..\..\..\steamcmd\steamapps\common\SpaceEngineersDedicatedServer\DedicatedServer64\VRage.Render11.dll</HintPath>
</Reference>
<Reference Include="VRage.Scripting, Version=1.0.0.0, Culture=neutral, processorArchitecture=AMD64">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\..\..\..\..\..\..\steamcmd\steamapps\common\SpaceEngineersDedicatedServer\DedicatedServer64\VRage.Scripting.dll</HintPath>
</Reference>
<Reference Include="WindowsBase" />
<Reference Include="PresentationCore" />
<Reference Include="PresentationFramework" />
</ItemGroup>
<ItemGroup>
<Compile Include="Properties\AssemblyInfo.cs">
<AutoGen>True</AutoGen>
<DesignTime>True</DesignTime>
<DependentUpon>AssemblyInfo.tt</DependentUpon>
</Compile>
<Compile Include="ServerConfig.cs" />
<Compile Include="TorchService.cs">
<SubType>Component</SubType>
</Compile>
@@ -150,9 +187,6 @@
</Compile>
</ItemGroup>
<ItemGroup>
<Compile Include="Properties\AssemblyInfo.cs">
<SubType>Code</SubType>
</Compile>
<Compile Include="Properties\Resources.Designer.cs">
<AutoGen>True</AutoGen>
<DesignTime>True</DesignTime>
@@ -213,7 +247,16 @@
</Page>
</ItemGroup>
<ItemGroup>
<Resource Include="SpaceEngineers.ico" />
<Resource Include="torchicon.ico" />
</ItemGroup>
<ItemGroup>
<Service Include="{508349B6-6B84-4DF5-91F0-309BEEBAD82D}" />
</ItemGroup>
<ItemGroup>
<Content Include="Properties\AssemblyInfo.tt">
<Generator>TextTemplatingFileGenerator</Generator>
<LastGenOutput>AssemblyInfo.cs</LastGenOutput>
</Content>
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<PropertyGroup>

View File

@@ -8,9 +8,12 @@ using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using NLog;
using Torch;
using Sandbox;
using Sandbox.Engine.Analytics;
using Sandbox.Engine.Multiplayer;
using Sandbox.Engine.Utils;
using Sandbox.Game;
using Sandbox.Game.Gui;
using Sandbox.Game.World;
@@ -27,31 +30,24 @@ namespace Torch.Server
{
public Thread GameThread { get; private set; }
public bool IsRunning { get; private set; }
public bool IsService { get; }
public string InstancePath { get; private set; }
public string InstancePath { get; }
public string InstanceName { get; }
public event Action SessionLoading;
private readonly AutoResetEvent _stopHandle = new AutoResetEvent(false);
internal TorchServer(string instanceName = null)
internal TorchServer(ServerConfig options)
{
if (instanceName != null)
{
IsService = true;
InstanceName = instanceName;
}
MySession.OnLoading += OnSessionLoading;
InstanceName = options.InstanceName;
InstancePath = options.InstancePath;
}
public override void Init()
{
base.Init();
SpaceEngineersGame.SetupBasicGameInfo();
SpaceEngineersGame.SetupPerGameSettings();
Log.Info($"Server instance {InstanceName} at path {InstancePath}");
MyFakes.ENABLE_INFINARIO = false;
MyPerGameSettings.SendLogToKeen = false;
MyPerServerSettings.GameName = MyPerGameSettings.GameName;
MyPerServerSettings.GameNameSafe = MyPerGameSettings.GameNameSafe;
@@ -68,18 +64,7 @@ namespace Torch.Server
var gameVersion = MyPerGameSettings.BasicGameInfo.GameVersion;
MyFinalBuildConstants.APP_VERSION = gameVersion ?? 0;
InstancePath = InstanceName != null ? GetInstancePath(true, InstanceName) : GetInstancePath();
}
private void OnSessionLoading()
{
SessionLoading?.Invoke();
MySession.Static.OnReady += OnSessionReady;
}
private void OnSessionReady()
{
InvokeSessionLoaded();
//InstancePath = InstanceName != null ? GetInstancePath(true, InstanceName) : GetInstancePath();
}
/// <summary>
@@ -100,6 +85,7 @@ namespace Torch.Server
try { Reflection.InvokeStaticMethod(typeof(DedicatedServer), "RunMain", InstanceName, InstancePath, false, true); }
catch (Exception e)
{
Log.Error("Error running server.");
Log.Error(e);
throw;
}
@@ -134,26 +120,28 @@ namespace Torch.Server
VRage.FileSystem.MyFileSystem.Reset();
VRage.Input.MyGuiGameControlsHelpers.Reset();
VRage.Input.MyInput.UnloadData();
CleanupProfilers();
//CleanupProfilers();
Log.Info("Server stopped.");
_stopHandle.Set();
IsRunning = false;
}
/*
private string GetInstancePath(bool isService = false, string instanceName = "Torch")
{
if (isService)
return Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), MyPerServerSettings.GameDSName, instanceName);
return Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), MyPerServerSettings.GameDSName);
}
}*/
/*
private void CleanupProfilers()
{
typeof(MyRenderProfiler).GetField("m_threadProfiler", BindingFlags.Static | BindingFlags.NonPublic).SetValue(null, null);
typeof(MyRenderProfiler).GetField("m_gpuProfiler", BindingFlags.Static | BindingFlags.NonPublic).SetValue(null, null);
(typeof(MyRenderProfiler).GetField("m_threadProfilers", BindingFlags.Static | BindingFlags.NonPublic).GetValue(null) as List<MyProfiler>).Clear();
}
}*/
}
}

View File

@@ -1,5 +1,6 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
@@ -30,7 +31,15 @@ namespace Torch.Server
protected override void OnStart(string[] args)
{
base.OnStart(args);
_server = new TorchServer("Torch");
string configName = args.Length > 0 ? args[0] : "TorchConfig.xml";
var options = new ServerConfig("Torch");
if (File.Exists(configName))
options = ServerConfig.LoadFrom(configName);
else
options.SaveTo(configName);
_server = new TorchServer(options);
_server.Init();
_server.RunArgs = args;
Task.Run(() => _server.Start());

BIN
Torch.Server/torchicon.ico Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 17 KiB

View File

@@ -0,0 +1,79 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Torch.Collections
{
public class KeyTree<TKey, TValue>
{
private Dictionary<TKey, KeyTreeNode<TKey, TValue>> _nodes = new Dictionary<TKey, KeyTreeNode<TKey, TValue>>();
}
public class KeyTreeNode<TKey, TValue>
{
public TKey Key { get; }
public TValue Value { get; set; }
public KeyTreeNode<TKey, TValue> Parent { get; private set; }
private readonly Dictionary<TKey, KeyTreeNode<TKey, TValue>> _children = new Dictionary<TKey, KeyTreeNode<TKey, TValue>>();
public IEnumerable<KeyTreeNode<TKey, TValue>> Children => _children.Values;
public KeyTreeNode(TKey key, TValue value)
{
Key = key;
Value = value;
}
public KeyTreeNode<TKey, TValue> GetChild(TKey key)
{
if (_children.TryGetValue(key, out KeyTreeNode<TKey, TValue> value))
return value;
return null;
}
public bool AddChild(TKey key, TValue value)
{
if (_children.ContainsKey(key))
return false;
var node = new KeyTreeNode<TKey, TValue>(key, value) { Parent = this };
_children.Add(key, node);
return true;
}
public bool AddChild(KeyTreeNode<TKey, TValue> node)
{
if (node.Parent != null || _children.ContainsKey(node.Key))
return false;
node.Parent = this;
_children.Add(node.Key, node);
return true;
}
public bool RemoveChild(TKey key)
{
if (!_children.TryGetValue(key, out KeyTreeNode<TKey, TValue> value))
return false;
value.Parent = null;
_children.Remove(key);
return true;
}
public IEnumerable<KeyTreeNode<TKey, TValue>> Traverse()
{
foreach (var node in Children)
{
yield return node;
foreach (var child in node.Traverse())
{
yield return child;
}
}
}
}
}

View File

@@ -28,7 +28,7 @@ namespace Torch.Commands
public void Respond(string message, string sender = "Server", string font = MyFontEnum.Blue)
{
Torch.Multiplayer.SendMessage(message, Player.PlayerID, sender, font);
Torch.Multiplayer.SendMessage(message, Player.IdentityId, sender, font);
}
}
}

View File

@@ -9,13 +9,20 @@ namespace Torch.Commands
{
public class TorchCommands : CommandModule
{
#if DEBUG
[Command("fixit")]
public void Fixit()
{
Environment.Exit(0);
}
[Command("dbgcmd")]
public void Dbgcmd()
{
var commandManager = ((PluginManager)Context.Torch.Plugins).Commands;
Console.WriteLine(commandManager.Commands.GetTreeString());
}
#endif
[Command("help", "Displays help for a command")]
public void Help()
{
@@ -32,7 +39,6 @@ namespace Torch.Commands
if (command != null)
sb.AppendLine(command.HelpText);
if (children.Any())
sb.AppendLine($"Subcommands: {string.Join(", ", children)}");
Context.Respond(sb.ToString());
@@ -47,7 +53,7 @@ namespace Torch.Commands
[Command("ver", "Shows the running Torch version.")]
public void Version()
{
var ver = Context.Torch.Version;
var ver = Context.Torch.TorchVersion;
Context.Respond($"Torch version: {ver}");
}

View File

@@ -82,7 +82,7 @@ namespace Torch.Managers
/// <summary>
/// Send a message in chat.
/// </summary>
public void SendMessage(string message, long playerId, string author = "Server", string font = MyFontEnum.Blue)
public void SendMessage(string message, long playerId, string author = "Server", string font = MyFontEnum.Red)
{
var msg = new ScriptedChatMsg {Author = author, Font = font, Target = playerId, Text = message};
MyMultiplayerBase.SendScriptedChatMessage(ref msg);
@@ -164,7 +164,7 @@ namespace Torch.Managers
private HashSet<ulong> _waitingForGroup;
private HashSet<ulong> _waitingForFriends;
private Dictionary<ulong, ulong> _gameOwnerIds = new Dictionary<ulong, ulong>();
private IMultiplayer _multiplayerImplementation;
//private IMultiplayer _multiplayerImplementation;
/// <summary>
/// Removes Keen's hooks into some Steam events so we have full control over client authentication

View File

@@ -15,10 +15,18 @@ namespace Torch.Managers
public class NetworkManager
{
private NetworkManager()
{
try
{
if (ReflectionUnitTest())
InitNetworkIntercept();
}
catch (Exception ex)
{
_log.Error("Error initializing network intercept");
_log.Error(ex);
}
}
private static Logger _log = LogManager.GetLogger(nameof(NetworkManager));
private static NetworkManager _instance;

View File

@@ -72,10 +72,10 @@ namespace Torch.Managers
/// <summary>
/// Unloads all plugins.
/// </summary>
public void UnloadPlugins()
public void DisposePlugins()
{
foreach (var plugin in _plugins)
plugin.Unload();
plugin.Dispose();
_plugins.Clear();
}
@@ -114,11 +114,14 @@ namespace Torch.Managers
catch (Exception e)
{
_log.Error($"Error loading plugin '{type.FullName}'");
_log.Error(e);
throw;
}
}
}
}
_plugins.ForEach(p => p.Init(_torch));
}
public IEnumerator<ITorchPlugin> GetEnumerator()
@@ -168,7 +171,7 @@ namespace Torch.Managers
public void Dispose()
{
_manager.UnloadPlugins();
_manager.DisposePlugins();
}
}
}

View File

@@ -48,7 +48,7 @@ namespace Torch
return true;
}
catch (AmbiguousMatchException aex)
catch (AmbiguousMatchException)
{
return true;
}
@@ -95,7 +95,7 @@ namespace Torch
if (prop == null)
prop = type.GetProperty(propertyName, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static | BindingFlags.FlattenHierarchy);
if (prop == null)
prop = type.BaseType.GetProperty(propertyName, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static | BindingFlags.FlattenHierarchy);
prop = type.BaseType?.GetProperty(propertyName, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static | BindingFlags.FlattenHierarchy);
if (prop == null)
{
Log.Error("Failed to find property '{0}' in type '{1}'", propertyName, type.FullName);

View File

@@ -145,6 +145,7 @@
<Reference Include="WindowsBase" />
</ItemGroup>
<ItemGroup>
<Compile Include="Collections\KeyTree.cs" />
<Compile Include="Commands\CategoryAttribute.cs" />
<Compile Include="Commands\Command.cs" />
<Compile Include="Commands\CommandAttribute.cs" />

View File

@@ -9,10 +9,14 @@ using System.Threading;
using System.Threading.Tasks;
using NLog;
using Sandbox;
using Sandbox.Game;
using Sandbox.Game.World;
using Sandbox.ModAPI;
using SpaceEngineers.Game;
using Torch.API;
using Torch.Managers;
using VRage.Scripting;
using VRage.Utils;
namespace Torch
{
@@ -24,20 +28,19 @@ namespace Torch
/// </summary>
[Obsolete]
public static ITorchBase Instance { get; private set; }
protected static Logger Log = LogManager.GetLogger("Torch");
public Version Version { get; protected set; }
protected static Logger Log { get; } = LogManager.GetLogger("Torch");
public Version TorchVersion { get; protected set; }
public Version GameVersion { get; private set; }
public string[] RunArgs { get; set; }
public IPluginManager Plugins { get; protected set; }
public IMultiplayer Multiplayer { get; protected set; }
public event Action SessionLoading;
public event Action SessionLoaded;
public event Action SessionUnloading;
public event Action SessionUnloaded;
private bool _init;
protected void InvokeSessionLoaded()
{
SessionLoaded?.Invoke();
}
protected TorchBase()
{
if (Instance != null)
@@ -45,7 +48,7 @@ namespace Torch
Instance = this;
Version = Assembly.GetExecutingAssembly().GetName().Version;
TorchVersion = Assembly.GetExecutingAssembly().GetName().Version;
RunArgs = new string[0];
Plugins = new PluginManager(this);
Multiplayer = new MultiplayerManager(this);
@@ -120,12 +123,34 @@ namespace Torch
AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
SpaceEngineersGame.SetupBasicGameInfo();
SpaceEngineersGame.SetupPerGameSettings();
TorchVersion = Assembly.GetEntryAssembly().GetName().Version;
GameVersion = new Version(new MyVersion(MyPerGameSettings.BasicGameInfo.GameVersion.Value).FormattedText.ToString().Replace("_", "."));
var verInfo = $"Torch {TorchVersion}, SE {GameVersion}";
Console.Title = verInfo;
#if DEBUG
Log.Info("DEBUG");
#else
Log.Info("RELEASE");
#endif
Log.Info(verInfo);
Log.Info($"Executing assembly: {Assembly.GetEntryAssembly().FullName}");
Log.Info($"Executing directory: {AppDomain.CurrentDomain.BaseDirectory}");
MySession.OnLoading += () => SessionLoading?.Invoke();
MySession.AfterLoading += () => SessionLoaded?.Invoke();
MySession.OnUnloading += () => SessionUnloading?.Invoke();
MySession.OnUnloaded += () => SessionUnloaded?.Invoke();
_init = true;
}
private void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
Log.Fatal((Exception)e.ExceptionObject);
Console.ReadLine();
Environment.Exit(-1);
}
public abstract void Start();

View File

@@ -18,7 +18,7 @@ namespace Torch
public Version Version { get; }
public string Name { get; }
public ITorchBase Torch { get; private set; }
private static Logger _log = LogManager.GetCurrentClassLogger();
private static readonly Logger _log = LogManager.GetLogger(nameof(TorchPluginBase));
protected TorchPluginBase()
{
@@ -44,7 +44,7 @@ namespace Torch
Torch = torch;
}
public abstract void Update();
public abstract void Unload();
public virtual void Update() { }
public abstract void Dispose();
}
}

BIN
torchicon.ico Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 17 KiB