swiftlys2/docs/api/releases/features/ai/

Network Messages

SwiftlyS2's typed net-message API sends generated protobuf messages and intercepts them in both client-to-server and server-to-client directions, through APIISwiftlyCore.NetMessage (APIINetMessageService).

Net-message objects passed to callbacks are temporary wrappers. Read or copy values inside the callback and don't store those objects for later use.

Generated Message Interfaces

Every generated message (CUserMessageShake, CCLCMsg_Move, CMsgSosStartSoundEvent, ...) implements three interfaces:

Fields declared in the message's protobuf definition get typed properties directly on the generated type (msg.Duration, msg.SoundeventHash, ...). Declared repeated fields are typed as APIIProtobufRepeatedFieldValueType`1 - an IList<T> of scalar values - or APIIProtobufRepeatedFieldSubMessageType`1 for nested messages, which exposes Count, Get(index), Add() and Clear() on top of enumeration. Both derive from the APIIRepeatedField marker interface.

Sending Net Messages

APIINetMessageService.Send builds the message, runs your configure callback, and sends it via the configured recipient filter - use it for one-off sends:

Core.NetMessage.Send<CUserMessageShake>(msg =>
{
    msg.Duration = 1.0f;
    msg.Frequency = 2.0f;
    msg.Amplitude = 0.5f;
    msg.Command = 0;
 
    msg.Recipients.AddAllPlayers();
});

Use APIINetMessageService.Create instead to build the same message shape repeatedly, tweak recipients directly through APIINetMessage`1.Recipients (a APICRecipientFilter), and send with Send()/SendToPlayer/SendToAllPlayers:

using var msg = Core.NetMessage.Create<CUserMessageShake>();
 
msg.Duration = 1.0f;
msg.Frequency = 2.0f;
msg.Amplitude = 0.5f;
msg.Command = 0;
 
msg.Recipients.RemoveAllPlayers();
msg.Recipients.AddRecipient(0);
msg.Recipients.AddRecipient(1);
 
msg.Send(); // or msg.SendToPlayer(0) / msg.SendToAllPlayers()

Create<T> returns T, so a message you keep around can be reconfigured and sent again - change its fields or recipient filter and call Send() once more.

Recipient Filters

Recipients is a APICRecipientFilter - a 64-bit player mask that Send and Create configure in place:

msg.Recipients.AddAllPlayers();       // target every player
msg.Recipients.RemoveAllPlayers();    // empty the filter
msg.Recipients.AddRecipient(slot);    // add a single slot
msg.Recipients.RemoveRecipient(slot); // remove a single slot
 
int count = msg.Recipients.GetRecipientCount();
foreach (int slot in msg.Recipients.GetRecipients())
{
    // every slot currently in the filter
}

AddRecipient/RemoveRecipient take player slots 0-63 and throw IndexOutOfRangeException outside that range. The filter also exposes RecipientsMask (ulong, the raw mask) and ToMask(), the buffer type BufferType (APINetChannelBufType_t: BUF_DEFAULT, BUF_UNRELIABLE, BUF_RELIABLE, BUF_VOICE, defaulting to BUF_RELIABLE for a newly constructed filter), and the InitMessage, DisabledPrediction and PredictedSlot fields. The static FromMask(ulong), FromPlayers(...) and FromSingle(int) factories build a standalone filter for APIs that take one by value.

Recipients is returned by reference, so next to changing the filter in place you can assign a whole one - useful when you already built a filter elsewhere:

msg.Recipients = CRecipientFilter.FromSingle(0);

See Sound Events for another user of the same struct.

Hooking Net Messages

Three hook pipelines: client messages (APIINetMessageService.HookClientMessage, client-to-server), server messages (APIINetMessageService.HookServerMessage, server-to-client), and internal server messages (APIINetMessageService.HookServerMessageInternal, server-to-client with a target playerId - only a small subset of server-to-client messages use this pipeline). Each can be registered programmatically or via an attribute discovered on any registered class (your BasePlugin is registered by default - see Using Attributes).

The handlers are the delegates declared on APIINetMessageService: APIINetMessageService.ClientNetMessageHandler and APIINetMessageService.ServerNetMessageInternalHandler take (T msg, int playerId), APIINetMessageService.ServerNetMessageHandler takes (T msg), and all three return APIHookResult. T is constrained to APIITypedProtobuf`1, APIINetMessage`1 and IDisposable - every generated message satisfies that. The matching attributes (APIClientNetMessageHandler, APIServerNetMessageHandler, APIServerNetMessageInternalHandler) are parameterless, target methods and allow one per method (AllowMultiple = false), so the method parameter picks the message type.

Client Hooks

private Guid _clientMoveHook;
 
public override void Load(bool hotReload)
{
    _clientMoveHook = Core.NetMessage.HookClientMessage<CCLCMsg_Move>(OnClientMove);
}
 
public override void Unload()
{
    if (_clientMoveHook != Guid.Empty)
        Core.NetMessage.Unhook(_clientMoveHook);
}
 
private HookResult OnClientMove(CCLCMsg_Move msg, int playerId)
{
    Console.WriteLine($"player={playerId}, lastCmd={msg.LastCommandNumber}");
    return HookResult.Continue;
}

Server and Internal Server Hooks

Same shape, different attribute and delegate signature - APIServerNetMessageHandler has no playerId, APIServerNetMessageInternalHandler does:

[ServerNetMessageHandler]
public HookResult OnServerSound(CMsgSosStartSoundEvent msg)
{
    Console.WriteLine($"sound hash={msg.SoundeventHash}");
    return HookResult.Continue;
}
 
[ServerNetMessageInternalHandler]
public HookResult OnServerSoundInternal(CMsgSosStartSoundEvent msg, int playerId)
{
    Console.WriteLine($"player={playerId}, sound hash={msg.SoundeventHash}");
    return HookResult.Continue;
}

Register the programmatic equivalents with APIINetMessageService.HookServerMessage/APIINetMessageService.HookServerMessageInternal, same Load/Unload/Guid pattern as the client hook above:

private Guid _serverSoundHook;
 
public override void Load(bool hotReload)
{
    _serverSoundHook = Core.NetMessage.HookServerMessage<CMsgSosStartSoundEvent>(OnServerSound);
    // or Core.NetMessage.HookServerMessageInternal<CMsgSosStartSoundEvent>(OnServerSoundInternal);
}

HookResult Behavior

Net-message hooks return HookResult.Continue (allow) or HookResult.Stop (block) - in client hooks that blocks delivery to the server, in server/internal hooks it blocks delivery to clients.

Unhooking

Unhook by Guid via APIINetMessageService.Unhook, or clear all hooks for a specific net-message type:

Core.NetMessage.Unhook(hookGuid);
 
Core.NetMessage.UnhookClientMessage<CCLCMsg_Move>();
Core.NetMessage.UnhookServerMessage<CMsgSosStartSoundEvent>();
Core.NetMessage.UnhookServerMessageInternal<CMsgSosStartSoundEvent>();

See APIINetMessageService.UnhookClientMessage, APIINetMessageService.UnhookServerMessage and APIINetMessageService.UnhookServerMessageInternal - one pipeline each, with the same generic constraints as their hooking counterparts.

Working with the Raw Payload Accessor

Generated message interfaces expose typed properties, plus Accessor (APIIProtobufAccessor) for field-based access when needed:

private HookResult OnServerSound(CMsgSosStartSoundEvent msg)
{
    uint hash = msg.Accessor.HasField("soundevent_hash")
        ? msg.Accessor.GetUInt32("soundevent_hash")
        : msg.SoundeventHash;
 
    Console.WriteLine($"sound hash={hash}");
    return HookResult.Continue;
}

Every field type follows the same naming pattern: Set<Type>(fieldName, value) writes, Get<Type>(fieldName) reads, Add<Type>(fieldName, value) appends to a repeated field, and SetRepeated<Type>(fieldName, index, value) / GetRepeated<Type>(fieldName, index) address an element by index:

Field type<Type> suffix
boolBool
intInt32
uintUInt32
longInt64
ulongUInt64
floatFloat
doubleDouble
stringString
byte[]Bytes
Vector2DVector2D
VectorVector
ColorColor
QAngleQAngle

With msg being the message you are reading from or writing to, and the strings being protobuf field names:

msg.Accessor.SetFloat("amplitude", 0.5f);
msg.Accessor.SetString("soundevent_name", "Weapon_AK47.Single");
 
float amplitude = msg.Accessor.GetFloat("amplitude");
Vector position = msg.Accessor.GetVector("origin");
 
// repeated fields, addressed by name and index
int size = msg.Accessor.GetRepeatedFieldSize("sounds");
string first = msg.Accessor.GetRepeatedString("sounds", 0);
msg.Accessor.ClearRepeatedField("sounds");

Use the accessor to write a field that has no generated property, e.g. in a hook before the message goes out, or to reset a message before reusing it:

msg.Accessor.SetUInt32("soundevent_hash", 1234u);
 
msg.Accessor.Clear(); // reset every field on the message

The remaining members cover nested messages and untyped values:

  • GetNestedMessage(fieldName), GetRepeatedNestedMessage(fieldName, index) and AddNestedMessage(fieldName) return a native pointer (nint) to a nested message - wrap it in a typed message again with APIHelper.AsProtobuf, Helper.AsProtobuf<T>(nint ptr, bool manuallyAllocated), where manuallyAllocated tells the wrapper whether it owns the pointer (true for a message you allocated yourself, false for one borrowed from the game).
  • HasField(fieldName) checks for presence, GetRepeatedFieldSize(fieldName) counts the elements of a repeated field, ClearRepeatedField(fieldName) empties one repeated field and Clear() resets the whole message.
  • Generic Set<T>/Get<T>, Add<T> and SetRepeated<T>/GetRepeated<T> overloads are available alongside the typed helpers.

As a native wrapper, the accessor is also an APIINativeHandle - IsValid and Address are available on it.