Skip to content
View in the app

A better way to browse. Learn more.

Learn more

plugin-trap-notebook/scripting/olds_trapnote.sma

olds_trapnote.sma
468 lines · 13.6 KB · Pawn (AMX Mod X)
Raw
/*
 * Trap Notebook (olds.ro workshop card AMX-007)
 *
 * Gives each deathrun runner a personal history of the traps that ended their
 * runs on the current map. Say /trapnotes lists the caller's top three traps
 * and the deaths no configured trap explains ("unassigned").
 *
 * Needs: AMX Mod X 1.10 (nVault), ReGameDLL_CS + ReAPI.
 *
 * Runners are the CT team. Only their deaths are written down:
 *   - a death whose inflictor or attacker entity is a configured trap counts for that trap;
 *   - a death by another player is not a trap death and is not counted;
 *   - every other death (a fall, the world, a suicide, an unconfigured
 *     entity) counts as unassigned.
 * The inflictor is the one of the damage that killed the runner: it is noted
 * in a TakeDamage hook and trusted only when that damage came in the same
 * frame as the death. A death without damage (the console "kill", a team
 * change) therefore never inherits an earlier trap hit, and a death where the
 * victim is its own attacker is always a suicide. A trap is identified by the
 * entity's targetname, or by its brush model ("*12") for traps without one.
 *
 * Traps: configs/olds_trapnote/<map>.ini, one trap per line:
 *   "Trap name" id [id ...]       each id is a targetname or a brush model *N
 * A map without that file writes everything as unassigned.
 *
 * Storage: nVault "olds_trapnote", key "<steam id>|<map>", value
 * "u=<unassigned>;<trap>=<count>;..." by trap name. A runner's notebook is
 * loaded when they are authorised and saved on disconnect and map end; the
 * in-memory counts are then cleared, so the next player in that slot starts
 * empty. Players without a real Steam id (LAN ids, bots) are kept in memory only.
 * Entries untouched for 60 days are pruned when the plugin starts.
 *
 * Commands: say /trapnotes, say_team /trapnotes; olds_trapnote_status (ADMIN_CFG).
 * Cvar: olds_trapnote_bots (0/1, default 0) also stores bots' notebooks, keyed
 * by bot name; for testing only.
 *
 * Copyright (C) 2026 daemon (olds.ro)
 * SPDX-License-Identifier: GPL-3.0-or-later
 */
#include <amxmodx>
#include <amxmisc>
#include <nvault>
#include <reapi>

#define PLUGIN  "Trap Notebook"
#define VERSION "1.0.0"
#define AUTHOR  "olds.ro"

const MAX_TRAPS = 32
const TRAP_NAME_LEN = 32
const ID_LEN = 64
const KEY_LEN = 128
const VALUE_LEN = 1024
const TOP_COUNT = 3
const PRUNE_DAYS = 60
const Float:NOTES_COOLDOWN = 2.0

new const VAULT_NAME[] = "olds_trapnote"

// Traps of the current map.
new g_trapName[MAX_TRAPS][TRAP_NAME_LEN]
new g_trapCount
new Trie:g_trapById        // targetname or *N -> trap index

new g_map[32]
new g_vault = INVALID_HANDLE

// Per player.
new g_deaths[MAX_PLAYERS + 1][MAX_TRAPS]
new g_unassigned[MAX_PLAYERS + 1]
new g_key[MAX_PLAYERS + 1][KEY_LEN]   // empty = not stored
new Float:g_hurtTime[MAX_PLAYERS + 1] // game time of the latest damage taken
new g_hurtInflictor[MAX_PLAYERS + 1]  // and its inflictor
new Float:g_nextNotes[MAX_PLAYERS + 1]

new g_storeBots

public plugin_init()
{
    register_plugin(PLUGIN, VERSION, AUTHOR)
    register_dictionary("olds_trapnote.txt")

    bind_pcvar_num(create_cvar("olds_trapnote_bots", "0", FCVAR_NONE,
        "Also store bots' notebooks, keyed by bot name (testing only).", true, 0.0, true, 1.0), g_storeBots)

    register_clcmd("say /trapnotes", "cmd_notes")
    register_clcmd("say_team /trapnotes", "cmd_notes")
    register_concmd("olds_trapnote_status", "cmd_status", ADMIN_CFG, "- every runner's notebook on this map")

    RegisterHookChain(RG_CBasePlayer_TakeDamage, "on_take_damage_pre", false)
    RegisterHookChain(RG_CBasePlayer_Killed, "on_killed_pre", false)
    RegisterHookChain(RG_CBasePlayer_Spawn, "on_spawn_post", true)

    get_mapname(g_map, charsmax(g_map))
    g_trapById = TrieCreate()

    g_vault = nvault_open(VAULT_NAME)
    if (g_vault == INVALID_HANDLE)
        log_amx("Could not open nVault %s: notebooks are kept for this map only.", VAULT_NAME)
    else
        nvault_prune(g_vault, 0, get_systime() - PRUNE_DAYS * 86400)
}

public plugin_cfg()
{
    load_traps()
}

public plugin_end()
{
    for (new id = 1; id <= MaxClients; id++)
    {
        if (is_user_connected(id))
            save_notebook(id)
    }
    if (g_vault != INVALID_HANDLE)
    {
        nvault_close(g_vault)
        g_vault = INVALID_HANDLE
    }
    TrieDestroy(g_trapById)
}

/* ---------- traps ---------- */

load_traps()
{
    new path[PLATFORM_MAX_PATH]
    get_configsdir(path, charsmax(path))
    format(path, charsmax(path), "%s/olds_trapnote/%s.ini", path, g_map)

    new file = fopen(path, "rt")
    if (!file)
    {
        log_amx("No traps for %s (%s): every runner death is unassigned.", g_map, path)
        return
    }

    new line[512], name[TRAP_NAME_LEN], rest[512], left[512], id[ID_LEN], lineNumber
    while (fgets(file, line, charsmax(line)))
    {
        lineNumber++
        trim(line)
        if (!line[0] || line[0] == ';' || line[0] == '#' || (line[0] == '/' && line[1] == '/'))
            continue

        if (g_trapCount == MAX_TRAPS)
        {
            log_amx("%s: only the first %d traps are used.", path, MAX_TRAPS)
            break
        }

        argbreak(line, name, charsmax(name), rest, charsmax(rest))
        if (!name[0] || !rest[0])
        {
            log_amx("%s line %d: expected ^"Trap name^" followed by one or more targetnames.", path, lineNumber)
            continue
        }
        if (contain(name, ";") != -1 || contain(name, "=") != -1 || equali(name, "u"))
        {
            log_amx("%s line %d: a trap name cannot contain ; or = and cannot be ^"u^".", path, lineNumber)
            continue
        }
        if (find_trap(name) != -1)
        {
            log_amx("%s line %d: trap ^"%s^" is already defined.", path, lineNumber, name)
            continue
        }

        new trap = g_trapCount, ids
        while (rest[0])
        {
            copy(left, charsmax(left), rest)
            argbreak(left, id, charsmax(id), rest, charsmax(rest))
            if (!id[0])
                continue
            if (TrieKeyExists(g_trapById, id))
            {
                log_amx("%s line %d: ^"%s^" already belongs to another trap.", path, lineNumber, id)
                continue
            }
            TrieSetCell(g_trapById, id, trap)
            ids++
        }
        if (!ids)
        {
            log_amx("%s line %d: trap ^"%s^" has no usable targetname.", path, lineNumber, name)
            continue
        }

        copy(g_trapName[trap], charsmax(g_trapName[]), name)
        g_trapCount++
    }
    fclose(file)

    log_amx("%d trap(s) loaded for %s.", g_trapCount, g_map)
}

find_trap(const name[])
{
    for (new trap = 0; trap < g_trapCount; trap++)
    {
        if (equali(g_trapName[trap], name))
            return trap
    }
    return -1
}

/* The configured trap an entity belongs to, or -1. */
trap_of(entity)
{
    if (entity <= MaxClients || is_nullent(entity))
        return -1

    new id[ID_LEN], trap
    get_entvar(entity, var_targetname, id, charsmax(id))
    if (id[0] && TrieGetCell(g_trapById, id, trap))
        return trap

    get_entvar(entity, var_model, id, charsmax(id))
    if (id[0] == '*' && TrieGetCell(g_trapById, id, trap))
        return trap

    return -1
}

/* ---------- deaths ---------- */

public on_take_damage_pre(victim, inflictor, attacker, Float:damage, damageBits)
{
    // Killed runs inside TakeDamage, so this pre hook is the one that sees the damage first.
    if (1 <= victim <= MaxClients)
    {
        g_hurtTime[victim] = get_gametime()
        g_hurtInflictor[victim] = inflictor
    }
    return HC_CONTINUE
}

public on_spawn_post(id)
{
    if (1 <= id <= MaxClients)
        forget_damage(id)
    return HC_CONTINUE
}

forget_damage(id)
{
    g_hurtTime[id] = -1.0
    g_hurtInflictor[id] = 0
}

public on_killed_pre(victim, attacker, gib)
{
    if (!(1 <= victim <= MaxClients) || !is_user_connected(victim))
        return HC_CONTINUE
    if (TeamName:get_member(victim, m_iTeam) != TEAM_CT)
        return HC_CONTINUE

    // Killed by another player: not a trap death.
    if (1 <= attacker <= MaxClients && attacker != victim)
        return HC_CONTINUE

    // A suicide (console "kill") is never a trap death, whatever hurt the runner before.
    if (attacker == victim)
    {
        g_unassigned[victim]++
        forget_damage(victim)
        return HC_CONTINUE
    }

    // Only damage dealt in this frame can have caused this death.
    new inflictor = g_hurtTime[victim] == get_gametime() ? g_hurtInflictor[victim] : 0
    forget_damage(victim)

    new trap = trap_of(inflictor)
    if (trap == -1 && attacker != inflictor)
        trap = trap_of(attacker)

    if (trap == -1)
        g_unassigned[victim]++
    else
        g_deaths[victim][trap]++
    return HC_CONTINUE
}

/* ---------- storage ---------- */

public client_authorized(id, const authid[])
{
    if (is_user_hltv(id))
        return

    new key[KEY_LEN]
    if (is_user_bot(id))
    {
        if (!g_storeBots)
            return
        new name[32]
        get_user_name(id, name, charsmax(name))
        formatex(key, charsmax(key), "BOT:%s|%s", name, g_map)
    }
    else
    {
        if (!equal(authid, "STEAM_", 6) || equal(authid, "STEAM_ID_LAN") || equal(authid, "STEAM_ID_PENDING"))
            return
        formatex(key, charsmax(key), "%s|%s", authid, g_map)
    }

    copy(g_key[id], charsmax(g_key[]), key)
    load_notebook(id)
}

public client_disconnected(id)
{
    save_notebook(id)
    clear_player(id)
    forget_damage(id)
}

clear_player(id)
{
    arrayset(g_deaths[id], 0, sizeof g_deaths[])
    g_unassigned[id] = 0
    g_key[id][0] = EOS
    g_nextNotes[id] = 0.0
}

/* Adds the stored counts to anything already counted this connection. */
load_notebook(id)
{
    if (g_vault == INVALID_HANDLE || !g_key[id][0])
        return

    new value[VALUE_LEN], stamp
    if (!nvault_lookup(g_vault, g_key[id], value, charsmax(value), stamp))
        return

    new pair[TRAP_NAME_LEN + 16], name[TRAP_NAME_LEN], number[12], left[VALUE_LEN]
    while (value[0])
    {
        copy(left, charsmax(left), value)
        strtok2(left, pair, charsmax(pair), value, charsmax(value), ';', TRIM_FULL)
        if (!pair[0])
            continue
        strtok2(pair, name, charsmax(name), number, charsmax(number), '=', TRIM_FULL)

        new count = str_to_num(number)
        if (count <= 0)
            continue
        if (equal(name, "u"))
        {
            g_unassigned[id] += count
            continue
        }
        // Traps renamed or removed from the config are dropped.
        new trap = find_trap(name)
        if (trap != -1)
            g_deaths[id][trap] += count
    }
}

save_notebook(id)
{
    if (g_vault == INVALID_HANDLE || !g_key[id][0])
        return

    new value[VALUE_LEN], length
    length = formatex(value, charsmax(value), "u=%d", g_unassigned[id])
    for (new trap = 0; trap < g_trapCount && length < charsmax(value); trap++)
    {
        if (g_deaths[id][trap])
            length += formatex(value[length], charsmax(value) - length, ";%s=%d", g_trapName[trap], g_deaths[id][trap])
    }

    if (g_unassigned[id] || length > 3)
        nvault_set(g_vault, g_key[id], value)
}

/* ---------- commands ---------- */

public cmd_notes(id)
{
    if (!is_user_connected(id))
        return PLUGIN_HANDLED

    new Float:now = get_gametime()
    if (now < g_nextNotes[id])
        return PLUGIN_HANDLED
    g_nextNotes[id] = now + NOTES_COOLDOWN

    if (TeamName:get_member(id, m_iTeam) != TEAM_CT)
    {
        client_print_color(id, print_team_default, "^4[Trap Notebook]^1 %L", id, "TRAPNOTE_RUNNERS_ONLY")
        return PLUGIN_HANDLED
    }

    new text[192]
    format_notes(id, id, text, charsmax(text))
    client_print_color(id, print_team_default, "^4[Trap Notebook]^1 %s", text)
    console_print(id, "[Trap Notebook] %s", text)
    return PLUGIN_HANDLED
}

/* lang is a player index or LANG_SERVER. */
format_notes(lang, id, text[], len)
{
    new top[TOP_COUNT], shown
    top_traps(id, top, shown)

    if (!shown)
        formatex(text, len, "%L", lang, "TRAPNOTE_NONE", g_map)
    else
    {
        new length = formatex(text, len, "%L", lang, "TRAPNOTE_TOP", g_map)
        for (new i = 0; i < shown; i++)
        {
            if (i)
                length += copy(text[length], len - length, ",")
            length += formatex(text[length], len - length, " %s %d", g_trapName[top[i]], g_deaths[id][top[i]])
        }
    }

    new length = strlen(text)
    formatex(text[length], len - length, " | %L %d", lang, "TRAPNOTE_UNASSIGNED", g_unassigned[id])
}

/* Up to TOP_COUNT traps with the most deaths; ties keep config order. */
top_traps(id, top[TOP_COUNT], &shown)
{
    shown = 0
    new bool:used[MAX_TRAPS]
    for (new slot = 0; slot < TOP_COUNT; slot++)
    {
        new best = -1
        for (new trap = 0; trap < g_trapCount; trap++)
        {
            if (used[trap] || !g_deaths[id][trap])
                continue
            if (best == -1 || g_deaths[id][trap] > g_deaths[id][best])
                best = trap
        }
        if (best == -1)
            break
        used[best] = true
        top[shown++] = best
    }
}

public cmd_status(id, level, cid)
{
    if (!cmd_access(id, level, cid, 1))
        return PLUGIN_HANDLED

    console_print(id, "[Trap Notebook] %d trap(s) on %s, vault %s", g_trapCount, g_map,
        g_vault == INVALID_HANDLE ? "closed" : "open")

    new players[MAX_PLAYERS], count, name[32], text[192]
    get_players(players, count, "h")
    for (new i = 0; i < count; i++)
    {
        new player = players[i]
        get_user_name(player, name, charsmax(name))
        format_notes(id ? id : LANG_SERVER, player, text, charsmax(text))
        console_print(id, "[Trap Notebook] %s (%s): %s", name, g_key[player][0] ? "stored" : "memory", text)
    }
    return PLUGIN_HANDLED
}

Search

Search

Configure browser push notifications

Chrome (Android)
  1. Tap the lock icon next to the address bar.
  2. Tap Permissions → Notifications.
  3. Adjust your preference.
Chrome (Desktop)
  1. Click the padlock icon in the address bar.
  2. Select Site settings.
  3. Find Notifications and adjust your preference.