Add resource package support

This commit is contained in:
sardelka9515
2022-08-23 12:21:17 +08:00
parent 6d7fe58719
commit 8ff08e0804
9 changed files with 102 additions and 48 deletions

View File

@ -129,7 +129,6 @@ namespace RageCoop.Client
PlayerPosition=P.ReadPosition(); PlayerPosition=P.ReadPosition();
FPS=Game.FPS; FPS=Game.FPS;
// World.DrawMarker(MarkerType.DebugSphere, PedExtensions.RaycastEverything(default), default, default, new Vector3(0.2f, 0.2f, 0.2f), Color.AliceBlue); // World.DrawMarker(MarkerType.DebugSphere, PedExtensions.RaycastEverything(default), default, default, new Vector3(0.2f, 0.2f, 0.2f), Color.AliceBlue);
if (Game.IsLoading) if (Game.IsLoading)
{ {
return; return;
@ -317,7 +316,7 @@ namespace RageCoop.Client
EntityPool.Cleanup(); EntityPool.Cleanup();
PlayerList.Cleanup(); PlayerList.Cleanup();
LocalPlayerID=default; LocalPlayerID=default;
WorldThread.Traffic(true); WorldThread.Traffic(!Settings.DisableTraffic);
} }
private static void DoQueuedActions() private static void DoQueuedActions()
{ {

View File

@ -75,6 +75,7 @@ namespace RageCoop.Client
} }
Main.QueueAction(() => Main.QueueAction(() =>
{ {
WorldThread.Traffic(!Main.Settings.DisableTraffic);
CoopMenu.ConnectedMenuSetting(); CoopMenu.ConnectedMenuSetting();
Main.MainChat.Init(); Main.MainChat.Init();
if (Main.Settings.Voice && !Voice.WasInitialized()) if (Main.Settings.Voice && !Voice.WasInitialized())

View File

@ -16,7 +16,7 @@ using System.Resources;
// Version informationr( // Version informationr(
[assembly: AssemblyVersion("1.5.2.114")] [assembly: AssemblyVersion("1.5.2.117")]
[assembly: AssemblyFileVersion("1.5.2.114")] [assembly: AssemblyFileVersion("1.5.2.117")]
[assembly: NeutralResourcesLanguageAttribute( "en-US" )] [assembly: NeutralResourcesLanguageAttribute( "en-US" )]

View File

@ -106,13 +106,6 @@ namespace RageCoop.Client.Scripting
} }
LoadedResources.Clear(); LoadedResources.Clear();
} }
private List<string> ToIgnore = new List<string>
{
"RageCoop.Client.dll",
"RageCoop.Core.dll",
"RageCoop.Server.dll",
"ScriptHookVDotNet3.dll"
};
private List<ClientResource> LoadedResources = new List<ClientResource>(); private List<ClientResource> LoadedResources = new List<ClientResource>();
private string BaseScriptType; private string BaseScriptType;
public Logger Logger { get; set; } public Logger Logger { get; set; }

View File

@ -418,6 +418,12 @@ namespace RageCoop.Core
return memoryStream.ToArray(); return memoryStream.ToArray();
} }
} }
public static MemoryStream ToMemStream(this Stream stream)
{
var memoryStream = new MemoryStream();
stream.CopyTo(memoryStream);
return memoryStream;
}
public static byte[] Join(this List<byte[]> arrays,int lengthPerArray=-1) public static byte[] Join(this List<byte[]> arrays,int lengthPerArray=-1)
{ {
if (arrays.Count==1) { return arrays[0]; } if (arrays.Count==1) { return arrays[0]; }

View File

@ -303,10 +303,12 @@ namespace RageCoop.Server
} }
internal void SendFile(Stream stream, string name, Client client,int id=default, Action<float> updateCallback = null) internal void SendFile(Stream stream, string name, Client client,int id=default, Action<float> updateCallback = null)
{ {
id = id ==default? NewFileID(): id ;
stream.Seek(0, SeekOrigin.Begin); stream.Seek(0, SeekOrigin.Begin);
// Logger.Debug("1");
id = id ==default? NewFileID(): id ;
// Logger.Debug("2");
var total = stream.Length; var total = stream.Length;
// Logger.Debug("3");
if (GetResponse<Packets.FileTransferResponse>(client, new Packets.FileTransferRequest() if (GetResponse<Packets.FileTransferResponse>(client, new Packets.FileTransferRequest()
{ {
FileLength= total, FileLength= total,

View File

@ -15,7 +15,7 @@ using System.Resources;
[assembly: AssemblyCulture("")] [assembly: AssemblyCulture("")]
// Version information // Version information
[assembly: AssemblyVersion("1.5.2.84")] [assembly: AssemblyVersion("1.5.2.98")]
[assembly: AssemblyFileVersion("1.5.2.84")] [assembly: AssemblyFileVersion("1.5.2.98")]
[assembly: NeutralResourcesLanguageAttribute( "en-US" )] [assembly: NeutralResourcesLanguageAttribute( "en-US" )]

View File

@ -22,9 +22,42 @@ namespace RageCoop.Server.Scripting
Server = server; Server = server;
Logger=server.Logger; Logger=server.Logger;
} }
private List<string> ClientResourceZips=new List<string>(); private Dictionary<string,Func<Stream>> ClientResources=new();
private Dictionary<string,Func<Stream>> ResourceStreams=new();
private List<MemoryStream> MemStreams = new();
public void LoadAll() public void LoadAll()
{ {
// Packages
{
var path = Path.Combine("Resources", "Packages");
Directory.CreateDirectory(path);
foreach (var pkg in Directory.GetFiles(path,"*.respkg",SearchOption.AllDirectories))
{
Logger?.Debug($"Adding resourece from package \"{Path.GetFileNameWithoutExtension(pkg)}\"");
var pkgZip = new ZipFile(pkg);
foreach (ZipEntry e in pkgZip)
{
if (!e.IsFile) { continue; }
if (e.Name.StartsWith("Client") && e.Name.EndsWith(".res"))
{
var stream = pkgZip.GetInputStream(e).ToMemStream();
MemStreams.Add(stream);
ClientResources.Add(Path.GetFileNameWithoutExtension(e.Name), () => stream);
Logger?.Debug("Resource added: "+ Path.GetFileNameWithoutExtension(e.Name));
}
else if (e.Name.StartsWith("Server") && e.Name.EndsWith(".res"))
{
var stream = pkgZip.GetInputStream(e).ToMemStream();
MemStreams.Add(stream);
ResourceStreams.Add(Path.GetFileNameWithoutExtension(e.Name), () => stream);
Logger?.Debug("Resource added: " + Path.GetFileNameWithoutExtension(e.Name));
}
}
pkgZip.Close();
}
}
// Client // Client
{ {
var path = Path.Combine("Resources", "Client"); var path = Path.Combine("Resources", "Client");
@ -45,22 +78,21 @@ namespace RageCoop.Server.Scripting
var zipPath = Path.Combine(tmpDir, Path.GetFileName(resourceFolder))+".res"; var zipPath = Path.Combine(tmpDir, Path.GetFileName(resourceFolder))+".res";
try try
{ {
using (ZipFile zip = ZipFile.Create(zipPath)) using ZipFile zip = ZipFile.Create(zipPath);
{ zip.BeginUpdate();
zip.BeginUpdate(); foreach (var dir in Directory.GetDirectories(resourceFolder, "*", SearchOption.AllDirectories))
foreach (var dir in Directory.GetDirectories(resourceFolder, "*", SearchOption.AllDirectories)) {
{ zip.AddDirectory(dir[(resourceFolder.Length + 1)..]);
zip.AddDirectory(dir[(resourceFolder.Length + 1)..]); }
} foreach (var file in Directory.GetFiles(resourceFolder, "*", SearchOption.AllDirectories))
foreach (var file in Directory.GetFiles(resourceFolder, "*", SearchOption.AllDirectories)) {
{ if (Path.GetFileName(file).CanBeIgnored()) { continue; }
zip.Add(file, file[(resourceFolder.Length + 1)..]); zip.Add(file, file[(resourceFolder.Length + 1)..]);
} }
zip.CommitUpdate(); zip.CommitUpdate();
zip.Close(); zip.Close();
ClientResourceZips.Add(zipPath); ClientResources.Add(Path.GetFileNameWithoutExtension(zipPath), () => File.OpenRead(zipPath));
} }
}
catch (Exception ex) catch (Exception ex)
{ {
Logger?.Error($"Failed to pack client resource:{resourceFolder}"); Logger?.Error($"Failed to pack client resource:{resourceFolder}");
@ -71,7 +103,10 @@ namespace RageCoop.Server.Scripting
var packed = Directory.GetFiles(path, "*.res", SearchOption.TopDirectoryOnly); var packed = Directory.GetFiles(path, "*.res", SearchOption.TopDirectoryOnly);
if (packed.Length>0) if (packed.Length>0)
{ {
ClientResourceZips.AddRange(packed); foreach(var file in packed)
{
ClientResources.Add(Path.GetFileNameWithoutExtension(file),()=>File.OpenRead(file));
}
} }
} }
@ -101,26 +136,34 @@ namespace RageCoop.Server.Scripting
Logger?.Error(ex); Logger?.Error(ex);
} }
} }
foreach (var resource in Directory.GetFiles(path, "*.res", SearchOption.TopDirectoryOnly)) foreach (var res in Directory.GetFiles(path, "*.res", SearchOption.TopDirectoryOnly))
{ {
try if (!ResourceStreams.TryAdd(Path.GetFileNameWithoutExtension(res),()=>File.OpenRead(res)))
{
Logger?.Warning($"Resource \"{res}\" cannot be loaded, ignoring...");
continue;
}
}
foreach(var res in ResourceStreams)
{
try
{ {
var name = Path.GetFileNameWithoutExtension(resource); var name = res.Key;
if (LoadedResources.ContainsKey(name)) if (LoadedResources.ContainsKey(name))
{ {
Logger?.Warning($"Resource \"{name}\" has already been loaded, ignoring..."); Logger?.Warning($"Resource \"{name}\" has already been loaded, ignoring...");
continue; continue;
} }
Logger?.Info($"Loading resource: "+name); Logger?.Info($"Loading resource: "+name);
var r = ServerResource.LoadFromZip(resource, Path.Combine("Resources", "Temp", "Server"), dataFolder, Logger); var r = ServerResource.LoadFrom(res.Value(),name, Path.Combine("Resources", "Temp", "Server"), dataFolder, Logger);
LoadedResources.Add(r.Name, r); LoadedResources.Add(r.Name, r);
} }
catch(Exception ex) catch(Exception ex)
{ {
Logger?.Error($"Failed to load resource: {Path.GetFileNameWithoutExtension(resource)}"); Logger?.Error($"Failed to load resource: {res.Key}");
Logger?.Error(ex); Logger?.Error(ex);
} }
} }
// Start scripts // Start scripts
lock (LoadedResources) lock (LoadedResources)
@ -172,21 +215,31 @@ namespace RageCoop.Server.Scripting
} }
LoadedResources.Clear(); LoadedResources.Clear();
} }
foreach(var s in MemStreams)
{
try
{
s.Close();
s.Dispose();
}
catch(Exception ex)
{
Logger?.Error("[Resources.CloseMemStream]",ex);
}
}
} }
public void SendTo(Client client) public void SendTo(Client client)
{ {
Task.Run(() => Task.Run(() =>
{ {
if (ClientResourceZips.Count!=0) if (ClientResources.Count!=0)
{ {
Logger?.Info($"Sending resources to client:{client.Username}"); Logger?.Info($"Sending resources to client:{client.Username}");
foreach (var rs in ClientResourceZips) foreach (var rs in ClientResources)
{ {
using (var fs = File.OpenRead(rs)) Logger?.Debug(rs.Key);
{ Server.SendFile(rs.Value(),rs.Key+".res", client);
Server.SendFile(rs, Path.GetFileName(rs), client);
}
} }
Logger?.Info($"Resources sent to:{client.Username}"); Logger?.Info($"Resources sent to:{client.Username}");

View File

@ -81,10 +81,10 @@ namespace RageCoop.Server.Scripting
} }
return r; return r;
} }
internal static ServerResource LoadFromZip(string zipPath, string tmpDir, string dataFolder, Logger logger = null) internal static ServerResource LoadFrom(Stream input,string name, string tmpDir, string dataFolder, Logger logger = null)
{ {
tmpDir=Path.Combine(tmpDir, Path.GetFileNameWithoutExtension(zipPath)); tmpDir=Path.Combine(tmpDir, name);
new FastZip().ExtractZip(zipPath, tmpDir, null); new FastZip().ExtractZip(input, tmpDir, FastZip.Overwrite.Always,null,null,null,true,true);
return LoadFrom(tmpDir, dataFolder, logger, true); return LoadFrom(tmpDir, dataFolder, logger, true);
} }
/// <summary> /// <summary>