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

Native Functions and Hooks

This is low-level, unsafe territory. A wrong calling convention, a mismatched delegate signature, or a bad register edit in a mid-hook can crash the game server. Test on a disposable server first.

Native interop splits across three services: Core.GameData (APIIGameDataService) resolves named signatures/offsets/patches shipped with your plugin, Core.Memory (APIIMemoryService) turns raw addresses into callable, hookable functions (or raw memory to mid-hook directly), and Core.GameHooks (APIIGameHooks) wraps the common engine callbacks in typed categories.

Resolving Addresses

From Your Plugin's GameData

Each plugin ships its own resources/gamedata/*.jsonc with signatures, offsets and patches per platform, keyed by name - signatures in signatures.jsonc, offsets in offsets.jsonc and byte patches in patches.jsonc. Look them up with TryGetSignature/TryGetOffset:

if (!Core.GameData.TryGetSignature("CBaseEntity::DispatchSpawn", out nint dispatchSpawnAddress))
{
    Core.Logger.LogWarning("Signature not found");
    return;
}
 
if (!Core.GameData.TryGetOffset("CCSPlayer_ItemServices::GiveNamedItem", out nint giveNamedItemOffset))
{
    return;
}

The full APIIGameDataService surface:

MemberReturnsDefined in
HasSignature(string signatureName)boolsignatures.jsonc
GetSignature(string signatureName)nintsignatures.jsonc
TryGetSignature(string signatureName, out nint)boolsignatures.jsonc
HasOffset(string offsetName)booloffsets.jsonc
GetOffset(string offsetName)intoffsets.jsonc
TryGetOffset(string offsetName, out nint)booloffsets.jsonc
HasPatch(string patchName)boolpatches.jsonc
ApplyPatch(string patchName)voidpatches.jsonc
RevertPatch(string patchName)voidpatches.jsonc

GetOffset hands the offset back as an int, TryGetOffset as an nint.

From a Raw Pattern or VTable Name

Core.Memory can also scan a library directly, skipping gamedata entirely:

nint? patternAddress = Core.Memory.GetAddressBySignature(Library.Server, "55 8B EC 83 EC 08 8B 45 08 5D C3");
nint? vtableAddress = Core.Memory.GetVTableAddress(Library.Server, "CCSPlayer_ItemServices");
nint? interfaceAddress = Core.Memory.GetInterfaceByName("VEngineServer");

APILibrary exposes the module names used by these lookups:

MemberModule
Library.Engineengine2
Library.Tier0tier0
Library.Serverserver
Library.NetworkSystemnetworksystem

Other Memory Helpers

The same service resolves cross-references, inspects object pointers, converts raw addresses and allocates memory:

nint resolved = Core.Memory.ResolveXrefAddress(xrefAddress);
 
string? vtableName = Core.Memory.GetObjectPtrVtableName(entityAddress);
bool hasVTable = Core.Memory.ObjectPtrHasVtable(entityAddress);
bool isBaseEntity = Core.Memory.ObjectPtrHasBaseClass(entityAddress, "CBaseEntity");
 
CBaseEntity entity = Core.Memory.ToSchemaClass<CBaseEntity>(entityAddress);
IServerSideClient client = Core.Memory.ToServerSideClient(clientAddress);
 
nint block = Core.Memory.Alloc(64);
block = Core.Memory.Resize(block, 128);
Core.Memory.Free(block);
MemberReturns
ResolveXrefAddress(nint xrefAddress)nint, the address the xref points at
GetObjectPtrVtableName(nint address)string?, null when not found
ObjectPtrHasVtable(nint address)bool
ObjectPtrHasBaseClass(nint address, string baseClassName)bool
ToSchemaClass<T>(nint address)T, where T : class, ISchemaClass<T>
ToServerSideClient(nint address)APIIServerSideClient
Alloc(ulong size)nint, the address of the allocated block
Resize(nint pointer, ulong newSize)nint, the address of the resized block
Free(nint pointer)void

Declaring a Delegate

Wrapping a native function needs a delegate matching its exact signature and calling convention:

[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate nint DispatchSpawnDelegate(nint pEntity, nint pKeyValues);

Wrapping and Calling It

Wrap by address or by vtable + index; the resulting APIIUnmanagedFunction`1 exposes Address (nint) and two delegate-typed members: Call (goes through any installed hooks) and CallOriginal (skips the hook chain).

IUnmanagedFunction<DispatchSpawnDelegate> func =
    Core.Memory.GetUnmanagedFunctionByAddress<DispatchSpawnDelegate>(dispatchSpawnAddress);
// or: Core.Memory.GetUnmanagedFunctionByVTable<DispatchSpawnDelegate>(vtableAddress.Value, 15);
nint address = func.Address;
nint result = func.Call(pEntity, pKeyValues);
nint resultUnhooked = func.CallOriginal(pEntity, pKeyValues);

Hooking It

AddHook takes a builder that receives "the next function in the chain" and must return your replacement delegate. Skipping next() skips the original call entirely. It returns the hook's Guid, which RemoveHook takes.

Guid hookId = func.AddHook(next =>
{
    return (pEntity, pKeyValues) =>
    {
        // pre logic
        nint result = next()(pEntity, pKeyValues);
        // post logic
        return result;
    };
});
 
// later
func.RemoveHook(hookId);

Hooks are cleaned up automatically on unload, but removing them yourself once done is still good practice.

Mid-Function Hooks

When hooking function entry/exit isn't precise enough, Core.Memory.GetUnmanagedMemoryByAddress wraps an arbitrary address in an APIIUnmanagedMemory so you can hook mid-function, with read/write access to the CPU registers at that point:

IUnmanagedMemory mem = Core.Memory.GetUnmanagedMemoryByAddress(dispatchSpawnAddress);
 
Guid midHookId = mem.AddHook((ref MidHookContext ctx) =>
{
    Console.WriteLine($"RIP=0x{ctx.RIP:X}, RAX=0x{ctx.RAX:X}");
    ctx.RAX = 0x1337; // example register edit
});
 
// later
mem.RemoveHook(midHookId);

AddHook here takes a APIMidHookDelegate (void (ref MidHookContext)) and returns a Guid, and the wrapper exposes Address. See APIMidHookContext for the full register list - every general-purpose register (RAX, RBX, RCX, RDX, RSI, RDI, RBP, RSP, R8-R15, RIP, RFLAGS, plus the internal TRAMPOLINE_RSP) and XMM0-XMM15 as APIXmm structs (fixed buffers U8, U16, U32, U64, F32, F64). MidHookContext.ToString() dumps every register in one go.

Hook Modes and Results

APIHookMode picks when a hook runs, APIHookResult tells the framework what to do with the call afterwards:

ValueNumberWhen it runs
HookMode.Pre0Before the game processes the call.
HookMode.Post1After the game processed the call.
ValueNumberEffect
HookResult.Continue0Following hooks and the original function run.
HookResult.Stop1Following hooks and the original function are cancelled.
HookResult.Handled2Following hooks are cancelled, the original function still runs.
HookResult.CancelOriginal3Following hooks run, the original function is cancelled.

Stop and Handled have no effect in post hooks - the original function has already run by the time they are set.

Delegate-based hooks such as Core.GameEvent and the client command/chat and net message hooks return the result from the handler. Game hooks below take it on the context with SetHookResult(HookResult) instead, and hooks whose native function returns a value expose that separately: SetReturn(...) in a Pre context, and a settable Return on the matching Post context.

Higher-Level Alternative: Game Hooks

Core.GameHooks (APIIGameHooks) wraps the vtable-hook plumbing above into typed categories with separate Pre/Post delegates - no manual delegate/signature bookkeeping. Example, hooking entity damage via APIITakeDamageEntityHook:

private void OnTakeDamagePre(ref TakeDamageEntityPreContext ctx)
{
    var entity = ctx.Params.Entity;
    ref var info = ref ctx.Params.Info;
 
    // ctx.SetHookResult(HookResult.Stop); // to block the damage
}
 
// Register in Load():
Core.GameHooks.Entities.TakeDamage.Pre += OnTakeDamagePre;

The same handler can be registered by attribute instead. APIGameHookHandler takes the mode in its constructor, sits on a method whose signature matches the hook's delegate, and allows one attribute per method (AllowMultiple = false); the methods are discovered on registered instances - see Using Attributes:

[GameHookHandler(HookMode.Pre)]
private void OnTakeDamagePre(ref TakeDamageEntityPreContext ctx)
{
    // ctx.SetHookResult(HookResult.Stop); // to block the damage
}

Categories

CategoryAccess pathHooks
ControllerCore.GameHooks.ControllerProcessUsercmds, SimulateUserCommands
EntitiesCore.GameHooks.EntitiesTakeDamage, StartTouch, Touch, EndTouch, AcceptInput, FireOutput
ItemsCore.GameHooks.ItemsCanAcquire, GetItemInLoadout
MovementCore.GameHooks.MovementRunCommand, SetupMove, ProcessMovement, CheckFalling, CategorizePosition, TryPlayerMove, WalkMove, Friction, AirAccelerate, AirMove, OnJumpModern, OnJumpLegacy, CheckJumpButtonModern, CheckJumpButtonLegacy, LadderMove, CanUnduck, Duck, CheckVelocity, WaterMove, CheckWater, MoveInit, FullWalkMove, CheckParameters, PlayerMove, GroundAccelerate
PawnCore.GameHooks.PawnPostThink, CanMove
WeaponsCore.GameHooks.WeaponsDrop, CanUse
DatamapsCore.GameHooks.DatamapsDatamap (think/touch/use) function hooks, grouped by owning schema class

Items.GetItemInLoadout is the one exception that needs a server setting: subscribing its Pre/Post throws unless FollowCS2ServerGuidelines is disabled in core.jsonc.

Hook Params

Every hook has a Pre and a Post context, both carrying a Params field with the arguments of the call:

HookParams members
Controller.ProcessUsercmdsPlayer (IPlayer), Usercmds (List<IUserCmd>), Paused (bool), Margin (float)
Controller.SimulateUserCommandsPlayer (IPlayer)
Entities.TakeDamageEntity (CBaseEntity), Info (ref CTakeDamageInfo), DamageResult (CTakeDamageResult*, may be null)
Entities.StartTouch / Touch / EndTouchEntity and OtherEntity (both CBaseEntity)
Entities.AcceptInputIdentity (CEntityIdentity), EntityInstance (CEntityInstance), DesignerName (string), InputName (string), Activator and Caller (both CEntityInstance?), VariantValue (ref CVariant<CVariantDefaultAllocator>), OutputId (int)
Entities.FireOutputEntityIO (ref CEntityIOOutput), DesignerName (string), OutputName (string), Activator and Caller (both CEntityInstance?), VariantValue (ref CVariant<CVariantDefaultAllocator>), Delay (float)
Items.CanAcquirePlayer (IPlayer), EconItemView (CEconItemView), WeaponVData (CCSWeaponBaseVData?), AcquireMethod (APIAcquireMethod)
Items.GetItemInLoadoutPlayer (IPlayer), Team (Team), Slot (loadout_slot_t)
Pawn.PostThink / CanMovePlayer (IPlayer)
Weapons.DropPlayer (IPlayer), Weapon (CBasePlayerWeapon?), SwappingWeapon (bool)
Weapons.CanUsePlayer (IPlayer), Weapon (CCSWeaponBase)
Movement.RunCommandPlayer (IPlayer), UserCmd (APIIUserCmd)
Movement.SetupMovePlayer (IPlayer), UserCmd (APIIUserCmd), MoveData (APIIMoveData)
every other Movement hookPlayer (IPlayer), MoveData (APIIMoveData)

Some hooks carry extra settable params: Movement.AirAccelerate adds WishDirection (Vector), WishSpeed (float) and Acceleration (float), Movement.GroundAccelerate adds WishDirection, FrameTime (float, read-only), WishSpeed and Acceleration, Movement.TryPlayerMove adds FirstDest (Vector), FirstTrace (APITraceResult, read-only) and IsSurfing (bool), Movement.CategorizePosition a StayOnGround (bool), and Movement.FullWalkMove a Ground (bool).

IMoveData and IUserCmd wrap native pointers - IMoveData.From(address) and IUserCmd.From(address) build one from an address, and Address/TypedAddress are exposed back.

Return Values

Hooks whose original function returns a value expose it on the context:

HookReturn typeSet it in PreRead/overwrite it in Post
Core.GameHooks.Items.CanAcquireAcquireResultctx.SetReturn(...)ctx.Return
Core.GameHooks.Items.GetItemInLoadoutCEconItemView?ctx.SetReturn(...)ctx.Return
Core.GameHooks.Weapons.CanUseboolctx.SetReturn(...)ctx.Return
Core.GameHooks.Pawn.CanMoveboolctx.SetReturn(...)ctx.Return
Core.GameHooks.Movement.CanUnduckboolctx.SetReturn(...)ctx.Return
Core.GameHooks.Movement.LadderMoveboolctx.SetReturn(...)ctx.Return
Core.GameHooks.Movement.MoveInitboolctx.SetReturn(...)ctx.Return
Core.GameHooks.Movement.PlayerMoveboolctx.SetReturn(...)ctx.Return
Core.GameHooks.Movement.CheckWaterboolctx.SetReturn(...)ctx.Return

Items.GetItemInLoadout behaves a little differently: the Pre SetReturn(item) is only used when the hook result is Stop or CancelOriginal, and the Post Return object is only valid during the callback - keep the item's address instead if you need it later.

Every other hook has no return value - use SetHookResult(HookResult.CancelOriginal) when you need to stop the original call.