Files
RAGECOOP-V/Client/Scripts/Scripting/API.cs

440 lines
15 KiB
C#
Raw Normal View History

#undef DEBUG
2022-10-23 19:02:39 +08:00
using Lidgren.Network;
using Newtonsoft.Json;
using RageCoop.Client.Menus;
using RageCoop.Core;
using RageCoop.Core.Scripting;
2023-02-12 22:06:57 +08:00
using System;
using System.Collections.Generic;
using System.Net;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Threading;
[assembly: InternalsVisibleTo("CodeGen")] // For generating api bridge
namespace RageCoop.Client.Scripting
{
2022-07-01 13:54:18 +08:00
/// <summary>
/// </summary>
2022-06-22 14:18:20 +08:00
public class CustomEventReceivedArgs : EventArgs
{
2022-07-01 13:54:18 +08:00
/// <summary>
2022-10-23 19:02:39 +08:00
/// The event hash
2022-07-01 13:54:18 +08:00
/// </summary>
2022-06-22 14:18:20 +08:00
public int Hash { get; set; }
2022-10-23 19:02:39 +08:00
2022-07-01 13:54:18 +08:00
/// <summary>
2022-10-23 19:02:39 +08:00
/// Supported types: byte, short, ushort, int, uint, long, ulong, float, bool, string, Vector3, Quaternion
2022-07-01 13:54:18 +08:00
/// </summary>
public object[] Args { get; set; }
2022-06-22 14:18:20 +08:00
}
2022-10-23 19:02:39 +08:00
/// <summary>
2022-10-23 19:02:39 +08:00
/// Provides vital functionality to interact with RAGECOOP
/// </summary>
2023-02-12 22:06:57 +08:00
internal static unsafe partial class API
{
#region INTERNAL
2022-10-23 19:02:39 +08:00
internal static Dictionary<int, List<Action<CustomEventReceivedArgs>>> CustomEventHandlers =
new Dictionary<int, List<Action<CustomEventReceivedArgs>>>();
#endregion
2022-10-23 19:02:39 +08:00
/// <summary>
2022-10-23 19:02:39 +08:00
/// Client configuration, this will conflict with server-side config.
/// </summary>
public static class Config
{
/// <summary>
2022-10-23 19:02:39 +08:00
/// Get or set local player's username, set won't be effective if already connected to a server.
/// </summary>
public static string Username
{
get => Main.Settings.Username;
set
{
2022-10-23 19:02:39 +08:00
if (Networking.IsOnServer || string.IsNullOrEmpty(value)) return;
Main.Settings.Username = value;
}
}
2022-10-23 19:02:39 +08:00
/// <summary>
2022-10-23 19:02:39 +08:00
/// Enable automatic respawn for this player.
/// </summary>
public static bool EnableAutoRespawn { get; set; } = true;
/// <summary>
2022-10-23 19:02:39 +08:00
/// Get or set player's blip color
/// </summary>
public static BlipColor BlipColor { get; set; } = BlipColor.White;
/// <summary>
2022-10-23 19:02:39 +08:00
/// Get or set player's blip sprite
/// </summary>
public static BlipSprite BlipSprite { get; set; } = BlipSprite.Standard;
/// <summary>
2022-10-23 19:02:39 +08:00
/// Get or set scale of player's blip
/// </summary>
public static float BlipScale { get; set; } = 1;
2023-02-12 22:06:57 +08:00
public static bool ShowPlayerNameTag
{
get => Main.Settings.ShowPlayerNameTag;
set
{
if (value == ShowPlayerNameTag) return;
Main.Settings.ShowPlayerNameTag = value;
Util.SaveSettings();
}
}
}
2022-10-23 19:02:39 +08:00
2022-10-08 23:49:48 +08:00
/// <summary>
2022-10-23 19:02:39 +08:00
/// Base events for RageCoop
/// </summary>
public static class Events
{
/// <summary>
2022-10-23 19:02:39 +08:00
/// The local player is dead
/// </summary>
public static event EmptyEvent OnPlayerDied;
/// <summary>
2022-10-23 19:02:39 +08:00
/// A local vehicle is spawned
/// </summary>
public static event EventHandler<SyncedVehicle> OnVehicleSpawned;
/// <summary>
2022-10-23 19:02:39 +08:00
/// A local vehicle is deleted
/// </summary>
public static event EventHandler<SyncedVehicle> OnVehicleDeleted;
/// <summary>
2022-10-23 19:02:39 +08:00
/// A local ped is spawned
/// </summary>
public static event EventHandler<SyncedPed> OnPedSpawned;
/// <summary>
2022-10-23 19:02:39 +08:00
/// A local ped is deleted
/// </summary>
public static event EventHandler<SyncedPed> OnPedDeleted;
2022-10-23 19:02:39 +08:00
#region DELEGATES
/// <summary>
/// </summary>
2022-10-23 19:02:39 +08:00
public delegate void EmptyEvent();
/// <summary>
/// </summary>
2022-10-23 19:02:39 +08:00
/// <param name="hash"></param>
/// <param name="args"></param>
public delegate void CustomEvent(int hash, List<object> args);
#endregion
#region INVOKE
2022-10-23 19:02:39 +08:00
internal static void InvokeVehicleSpawned(SyncedVehicle v)
{
OnVehicleSpawned?.Invoke(null, v);
}
2022-10-23 19:02:39 +08:00
internal static void InvokeVehicleDeleted(SyncedVehicle v)
{
OnVehicleDeleted?.Invoke(null, v);
}
internal static void InvokePedSpawned(SyncedPed p)
{
OnPedSpawned?.Invoke(null, p);
}
internal static void InvokePedDeleted(SyncedPed p)
{
OnPedDeleted?.Invoke(null, p);
}
internal static void InvokePlayerDied()
{
OnPlayerDied?.Invoke();
}
2022-11-16 17:40:07 +08:00
internal static void InvokeCustomEventReceived(Packets.CustomEvent p)
2022-06-21 18:13:30 +08:00
{
2022-10-23 19:02:39 +08:00
var args = new CustomEventReceivedArgs { Hash = p.Hash, Args = p.Args };
2022-10-10 16:45:58 +08:00
2023-02-13 17:51:18 +08:00
// Log.Debug($"CustomEvent:\n"+args.Args.DumpWithType());
2022-07-20 17:50:01 +08:00
2022-10-23 19:02:39 +08:00
if (CustomEventHandlers.TryGetValue(p.Hash, out var handlers))
handlers.ForEach(x => { x.Invoke(args); });
2022-06-21 18:13:30 +08:00
}
2022-10-23 19:02:39 +08:00
#endregion
}
2022-06-21 18:13:30 +08:00
2022-07-11 11:30:00 +08:00
#region PROPERTIES
/// <summary>
2022-10-23 19:02:39 +08:00
/// Get the local player's ID
/// </summary>
2022-07-11 11:30:00 +08:00
/// <returns>PlayerID</returns>
public static int LocalPlayerID => Main.LocalPlayerID;
2022-07-11 11:30:00 +08:00
2022-07-31 20:47:04 +08:00
/// <summary>
2022-10-23 19:02:39 +08:00
/// Check if player is connected to a server
2022-07-31 20:47:04 +08:00
/// </summary>
public static bool IsOnServer => Networking.IsOnServer;
2022-07-31 20:47:04 +08:00
/// <summary>
2022-10-23 19:02:39 +08:00
/// Get an <see cref="System.Net.IPEndPoint" /> that the player is currently connected to, or null if not connected to
/// the server
2022-07-31 20:47:04 +08:00
/// </summary>
2022-10-23 19:02:39 +08:00
public static IPEndPoint ServerEndPoint =>
Networking.IsOnServer ? Networking.ServerConnection?.RemoteEndPoint : null;
2022-07-31 20:47:04 +08:00
/// <summary>
2022-10-23 19:02:39 +08:00
/// Check if a RAGECOOP menu is visible
/// </summary>
2022-10-23 19:02:39 +08:00
public static bool IsMenuVisible => CoopMenu.MenuPool.AreAnyVisible;
2022-07-11 11:30:00 +08:00
/// <summary>
2022-10-23 19:02:39 +08:00
/// Check if the RAGECOOP chat is visible
/// </summary>
public static bool IsChatFocused => Main.MainChat.Focused;
/// <summary>
2022-10-23 19:02:39 +08:00
/// Check if the RAGECOOP list of players is visible
/// </summary>
public static bool IsPlayerListVisible => Util.GetTickCount64() - PlayerList.Pressed < 5000;
/// <summary>
2022-10-23 19:02:39 +08:00
/// Get the version of RAGECOOP
/// </summary>
public static Version CurrentVersion => Main.Version;
2022-07-11 11:30:00 +08:00
2022-08-27 14:17:10 +08:00
/// <summary>
2022-10-23 19:02:39 +08:00
/// Get all players indexed by their ID
2022-08-27 14:17:10 +08:00
/// </summary>
2023-02-12 22:06:57 +08:00
public static Dictionary<int, Player> Players => new(PlayerList.Players);
2022-08-27 14:17:10 +08:00
2022-07-11 11:30:00 +08:00
#endregion
2022-07-11 11:30:00 +08:00
#region FUNCTIONS
2022-10-23 19:02:39 +08:00
/// <summary>
/// Queue an action to be executed on next tick.
/// </summary>
/// <param name="a"></param>
public static void QueueAction(Action a)
{
WorldThread.QueueAction(a);
}
public static void QueueActionAndWait(Action a, int timeout = 15000)
{
var done = new AutoResetEvent(false);
Exception e = null;
QueueAction(() =>
{
try
{
a();
done.Set();
}
catch (Exception ex)
{
e = ex;
}
});
if (e != null)
throw e;
if (!done.WaitOne(timeout)) throw new TimeoutException();
}
/// <summary>
/// Queue an action to be executed on next tick, allowing you to call scripting API from another thread.
/// </summary>
/// <param name="a">
/// An <see cref="Func{T, TResult}" /> to be executed with a return value indicating whether it can be
/// removed after execution.
/// </param>
public static void QueueAction(Func<bool> a)
{
WorldThread.QueueAction(a);
}
2022-06-21 18:13:30 +08:00
/// <summary>
2022-10-23 19:02:39 +08:00
/// Send an event and data to the server.
2022-06-21 18:13:30 +08:00
/// </summary>
/// <param name="eventHash">An unique identifier of the event</param>
2022-10-23 19:02:39 +08:00
/// <param name="args">
/// The objects conataing your data, see <see cref="CustomEventReceivedArgs" /> for a list of supported
/// types
/// </param>
public static void SendCustomEvent(CustomEventHash eventHash, params object[] args)
2023-02-12 22:06:57 +08:00
=> SendCustomEvent(CustomEventFlags.None, eventHash, args);
2022-10-23 19:02:39 +08:00
/// <summary>
2022-10-23 19:02:39 +08:00
/// Send an event and data to the server
/// </summary>
/// <param name="flags"></param>
/// <param name="eventHash">An unique identifier of the event</param>
2022-10-23 19:02:39 +08:00
/// <param name="args">
/// The objects conataing your data, see <see cref="CustomEventReceivedArgs" /> for a list of supported
/// types
/// </param>
public static void SendCustomEvent(CustomEventFlags flags, CustomEventHash eventHash, params object[] args)
{
Networking.Peer.SendTo(new Packets.CustomEvent(flags)
{
Args = args,
Hash = eventHash
2022-10-23 19:02:39 +08:00
}, Networking.ServerConnection, ConnectionChannel.Event, NetDeliveryMethod.ReliableOrdered);
}
2022-06-22 14:18:20 +08:00
/// <summary>
2022-10-23 19:02:39 +08:00
/// Register an handler to the specifed event hash, one event can have multiple handlers. This will be invoked from
/// backgound thread, use <see cref="QueueAction(Action)" /> in the handler to dispatch code to script thread.
/// </summary>
2022-10-23 19:02:39 +08:00
/// <param name="hash">
2023-02-12 22:06:57 +08:00
/// An unique identifier of the event
2022-10-23 19:02:39 +08:00
/// </param>
/// <param name="handler">An handler to be invoked when the event is received from the server. </param>
public static void RegisterCustomEventHandler(CustomEventHash hash, Action<CustomEventReceivedArgs> handler)
{
lock (CustomEventHandlers)
{
2022-10-23 19:02:39 +08:00
if (!CustomEventHandlers.TryGetValue(hash, out var handlers))
CustomEventHandlers.Add(hash, handlers = new List<Action<CustomEventReceivedArgs>>());
handlers.Add(handler);
}
}
2022-07-20 17:50:01 +08:00
2022-07-19 17:15:53 +08:00
/// <summary>
/// </summary>
/// <returns></returns>
public static void RequestSharedFile(string name, Action<string> callback)
2022-07-19 17:15:53 +08:00
{
EventHandler<string> handler = (s, e) =>
{
2022-10-23 19:02:39 +08:00
if (e.EndsWith(name)) callback(e);
2022-07-19 17:15:53 +08:00
};
2022-09-06 21:46:35 +08:00
DownloadManager.DownloadCompleted += handler;
2022-10-23 19:02:39 +08:00
Networking.GetResponse<Packets.FileTransferResponse>(new Packets.FileTransferRequest
{
Name = name
},
2022-10-23 19:02:39 +08:00
p =>
2022-10-10 16:45:58 +08:00
{
2022-10-23 19:02:39 +08:00
if (p.Response != FileResponse.Loaded)
{
DownloadManager.DownloadCompleted -= handler;
throw new ArgumentException("Requested file was not found on the server: " + name);
}
});
}
2023-02-12 22:06:57 +08:00
/// <summary>
/// Connect to a server
/// </summary>
/// <param name="address">Address of the server, e.g. 127.0.0.1:4499</param>
/// <exception cref="InvalidOperationException">When a connection is active or being established</exception>
[Remoting]
public static void Connect(string address)
{
if (Networking.IsOnServer || Networking.IsConnecting)
throw new InvalidOperationException("Cannot connect to server when another connection is active");
Networking.ToggleConnection(address);
}
/// <summary>
/// Disconnect from current server or cancel the connection attempt.
/// </summary>
[Remoting]
public static void Disconnect()
{
if (Networking.IsOnServer || Networking.IsConnecting) Networking.ToggleConnection(null);
}
/// <summary>
/// List all servers from master server address
/// </summary>
/// <returns></returns>
[Remoting]
public static List<ServerInfo> ListServers()
{
return JsonDeserialize<List<ServerInfo>>(
HttpHelper.DownloadString(Main.Settings.MasterServer));
}
/// <summary>
/// Send a local chat message to this player
/// </summary>
/// <param name="from">Name of the sender</param>
/// <param name="message">The player's message</param>
[Remoting]
public static void LocalChatMessage(string from, string message)
{
Main.MainChat.AddMessage(from, message);
}
/// <summary>
/// Send a chat message or command to server/other players
/// </summary>
/// <param name="message"></param>
[Remoting]
public static void SendChatMessage(string message)
{
if (!IsOnServer)
throw new InvalidOperationException("Not on server");
Networking.SendChatMessage(message);
}
[Remoting]
public static ClientResource GetResource(string name)
{
2023-02-13 17:51:18 +08:00
if (MainRes.LoadedResources.TryGetValue(name, out var resource))
2023-02-12 22:06:57 +08:00
return resource;
return null;
}
[Remoting(GenBridge = false)]
public static object GetProperty(string name)
=> typeof(API).GetProperty(name, BindingFlags.Static | BindingFlags.Public)?.GetValue(null);
[Remoting(GenBridge = false)]
public static void SetProperty(string name, string jsonVal)
{
var prop = typeof(API).GetProperty(name, BindingFlags.Static | BindingFlags.Public); ;
if (prop == null)
throw new KeyNotFoundException($"Property {name} was not found");
prop.SetValue(null, JsonDeserialize(jsonVal, prop.PropertyType));
}
[Remoting]
public static object GetConfig(string name)
=> typeof(Config).GetProperty(name, BindingFlags.Static | BindingFlags.Public)?.GetValue(null);
[Remoting]
public static void SetConfig(string name, string jsonVal)
{
var prop = typeof(Config).GetProperty(name, BindingFlags.Static | BindingFlags.Public);
if (prop == null)
throw new KeyNotFoundException($"Property {name} was not found");
prop.SetValue(null, JsonDeserialize(jsonVal, prop.PropertyType));
}
2022-10-23 19:02:39 +08:00
#endregion
2023-02-12 22:06:57 +08:00
}
2022-10-23 19:02:39 +08:00
}