Skip to content
View in the app

A better way to browse. Learn more.

Learn more

soccer-ball-statistics/addons/amxmodx/scripting/olds_ballstats.sma

olds_ballstats.sma
623 lines · 19.9 KB · Pawn (AMX Mod X)
Raw
/*
 * Soccer Ball Statistics (olds.ro workshop card LIB-2055)
 *
 * SoccerJam: counts every player's ball touches, goals and assists, saves them
 * by SteamID in the SQLx table olds_ball_stats and shows them in game.
 *   say /ballstats    your goals, assists and touches
 *   say /balltop      the top 10 scorers (MOTD), by goals then assists
 *   amx_ballstats     every player's counts and the database state (ADMIN_KICK)
 *   amx_ballsave      saves everything now (ADMIN_CFG)
 *
 * Goal events: SoccerJam scores when its ball touches a goal net, so the
 * plugin watches the same touches (engine register_touch): the ball class
 * olds_bs_ball ("PwnBall") touching a player is a touch, touching
 * olds_bs_net ("soccerjam_goalnet") is a goal for the last player who touched
 * the ball. The assist goes to the player of the scorer's team who touched
 * the ball just before him (once per goal); a goal starts a new chain.
 *
 * Saving (threaded SQL_ThreadQuery, MySQL or SQLite): every olds_bs_saveint
 * seconds, when a player leaves and on demand, each player's new counts are
 * added to his row (INSERT IGNORE, then UPDATE ... + n). A failed query keeps
 * its counts in the nVault "olds_ballstats" and logs one warning until the
 * database answers again; the vault is merged at map start, every
 * olds_bs_saveint and when the player joins. At map end the unsaved counts go
 * to the vault first, so a map change loses nothing.
 *
 * Cvars: olds_bs_driver mysql, olds_bs_host, olds_bs_user, olds_bs_pass,
 * olds_bs_db amxx, olds_bs_saveint 60, olds_bs_key 0 (1 = by name),
 * olds_bs_ball PwnBall, olds_bs_net soccerjam_goalnet.
 *
 * Copyright (C) 2026 daemon (olds.ro)
 * SPDX-License-Identifier: GPL-3.0-or-later
 */
#include <amxmodx>
#include <amxmisc>
#include <engine>
#include <sqlx>
#include <nvault>

#define PLUGIN  "Soccer Ball Statistics"
#define VERSION "1.0.0"
#define AUTHOR  "olds.ro"

#pragma dynamic 16384

enum
{
    S_GOALS = 0,
    S_ASSISTS,
    S_TOUCHES,
    STATS
}

const TASK_SAVE = 20550
const Float:TOUCH_GAP = 0.5
const Float:GOAL_GAP = 3.0
const TOP = 10

new g_driver[16], g_host[64], g_user[64], g_pass[64], g_db[64]
new g_saveInt, g_keyMode
new g_ballClass[32], g_netClass[32]

new g_key[MAX_PLAYERS + 1][64]
new g_total[MAX_PLAYERS + 1][STATS]       // shown to the player
new g_synced[MAX_PLAYERS + 1][STATS]      // part already handed to the database or the vault
new bool:g_loaded[MAX_PLAYERS + 1]
new Float:g_lastTouch[MAX_PLAYERS + 1]

new g_last, g_prev                          // the ball's last two different touchers
new Float:g_nextGoal

new g_vault = INVALID_HANDLE
new bool:g_dbDown
new g_tableChecks

public plugin_init()
{
    register_plugin(PLUGIN, VERSION, AUTHOR)
    register_dictionary("olds_ballstats.txt")
    bind_pcvar_string(create_cvar("olds_bs_driver", "mysql", FCVAR_NONE, "SQLx driver: mysql or sqlite"), g_driver,
        charsmax(g_driver))
    bind_pcvar_string(create_cvar("olds_bs_host", "127.0.0.1", FCVAR_PROTECTED, "Database host"), g_host, charsmax(g_host))
    bind_pcvar_string(create_cvar("olds_bs_user", "", FCVAR_PROTECTED, "Database user"), g_user, charsmax(g_user))
    bind_pcvar_string(create_cvar("olds_bs_pass", "", FCVAR_PROTECTED, "Database password"), g_pass, charsmax(g_pass))
    bind_pcvar_string(create_cvar("olds_bs_db", "amxx", FCVAR_PROTECTED, "Database name (sqlite: the file in data/sqlite3)"),
        g_db, charsmax(g_db))
    bind_pcvar_num(create_cvar("olds_bs_saveint", "60", FCVAR_NONE, "Seconds between saves", true, 10.0, true, 3600.0),
        g_saveInt)
    bind_pcvar_num(create_cvar("olds_bs_key", "0", FCVAR_NONE, "Player key: 0 = SteamID, 1 = name", true, 0.0, true, 1.0),
        g_keyMode)
    bind_pcvar_string(create_cvar("olds_bs_ball", "PwnBall", FCVAR_NONE, "Classname of the soccer ball"), g_ballClass,
        charsmax(g_ballClass))
    bind_pcvar_string(create_cvar("olds_bs_net", "soccerjam_goalnet", FCVAR_NONE, "Classname of the goal nets"), g_netClass,
        charsmax(g_netClass))
    AutoExecConfig(true, "olds_ballstats")

    register_clcmd("say /ballstats", "cmd_stats")
    register_clcmd("say_team /ballstats", "cmd_stats")
    register_clcmd("say /balltop", "cmd_top")
    register_clcmd("say_team /balltop", "cmd_top")
    register_concmd("amx_ballstats", "cmd_status", ADMIN_KICK, "- ball statistics and the database state")
    register_concmd("amx_ballsave", "cmd_save", ADMIN_CFG, "- saves every player's ball statistics now")
    g_vault = nvault_open("olds_ballstats")
    if (g_vault == INVALID_HANDLE)
        log_amx("Could not open the nVault olds_ballstats: no fallback while the database is down")
}

public plugin_cfg()
{
    // The classes come from the config, read by now.
    register_touch(g_ballClass, "player", "on_ball_touched_by")
    register_touch("player", g_ballClass, "on_player_touched_by")
    register_touch(g_ballClass, g_netClass, "on_ball_net")
    register_touch(g_netClass, g_ballClass, "on_net_ball")
    create_table()
    set_task(float(g_saveInt), "task_save", TASK_SAVE, _, _, "b")
}

public plugin_end()
{
    // Threaded queries may not finish now: unsaved counts go to the vault, merged next map.
    for (new id = 1; id <= MaxClients; id++)
    {
        if (!g_loaded[id] || !g_key[id][0])
            continue
        new delta[STATS], changed
        for (new s = 0; s < STATS; s++)
        {
            delta[s] = g_total[id][s] - g_synced[id][s]
            g_synced[id][s] = g_total[id][s]
            changed |= delta[s]
        }
        vault_put_totals(id)
        if (changed)
            vault_add_delta(g_key[id], delta)
    }
    if (g_vault != INVALID_HANDLE)
        nvault_close(g_vault)
}

/* ---------- the ball ---------- */

public on_ball_touched_by(ball, id)
{
    touched(id)
}

public on_player_touched_by(id, ball)
{
    touched(id)
}

touched(id)
{
    if (!(1 <= id <= MaxClients) || !is_user_alive(id))
        return
    new Float:now = get_gametime()
    // The ball rests on a player for several frames: one touch per contact.
    if (id == g_last && now - g_lastTouch[id] < TOUCH_GAP)
    {
        g_lastTouch[id] = now
        return
    }
    g_lastTouch[id] = now
    g_total[id][S_TOUCHES]++
    if (id != g_last)
    {
        g_prev = g_last
        g_last = id
    }
}

public on_ball_net(ball, net)
{
    goal()
}

public on_net_ball(net, ball)
{
    goal()
}

goal()
{
    new Float:now = get_gametime()
    if (now < g_nextGoal)
        return
    g_nextGoal = now + GOAL_GAP
    new scorer = g_last, assist = g_prev
    g_last = 0
    g_prev = 0
    if (!(1 <= scorer <= MaxClients) || !is_user_connected(scorer))
        return
    g_total[scorer][S_GOALS]++
    new name[MAX_NAME_LENGTH]
    get_user_name(scorer, name, charsmax(name))
    if (1 <= assist <= MaxClients && assist != scorer && is_user_connected(assist)
        && get_user_team(assist) == get_user_team(scorer))
    {
        g_total[assist][S_ASSISTS]++
        new by[MAX_NAME_LENGTH]
        get_user_name(assist, by, charsmax(by))
        client_print_color(0, scorer, "^4[Ball]^1 %L", LANG_PLAYER, "BS_GOAL_ASSIST", name, g_total[scorer][S_GOALS], by)
    }
    else
        client_print_color(0, scorer, "^4[Ball]^1 %L", LANG_PLAYER, "BS_GOAL", name, g_total[scorer][S_GOALS])
}

/* ---------- players ---------- */

public client_putinserver(id)
{
    for (new s = 0; s < STATS; s++)
    {
        g_total[id][s] = 0
        g_synced[id][s] = 0
    }
    g_loaded[id] = false
    g_lastTouch[id] = 0.0
    if (g_keyMode == 1)
        get_user_name(id, g_key[id], charsmax(g_key[]))
    else
        get_user_authid(id, g_key[id], charsmax(g_key[]))
    load_player(id)
}

public client_disconnected(id)
{
    if (g_loaded[id])
        save_player(id)
    g_loaded[id] = false
    if (g_last == id)
        g_last = 0
    if (g_prev == id)
        g_prev = 0
}

/* ---------- vault ---------- */

vault_read(const prefix[], const key[], out[STATS])
{
    for (new s = 0; s < STATS; s++)
        out[s] = 0
    if (g_vault == INVALID_HANDLE)
        return
    new vkey[72], text[48], part[3][16]
    formatex(vkey, charsmax(vkey), "%s%s", prefix, key)
    if (!nvault_get(g_vault, vkey, text, charsmax(text)))
        return
    parse(text, part[0], charsmax(part[]), part[1], charsmax(part[]), part[2], charsmax(part[]))
    for (new s = 0; s < STATS; s++)
        out[s] = str_to_num(part[s])
}

vault_write(const prefix[], const key[], const values[STATS])
{
    if (g_vault == INVALID_HANDLE)
        return
    new vkey[72], text[48]
    formatex(vkey, charsmax(vkey), "%s%s", prefix, key)
    if (values[0] || values[1] || values[2])
    {
        formatex(text, charsmax(text), "%d %d %d", values[0], values[1], values[2])
        nvault_set(g_vault, vkey, text)
    }
    else
        nvault_remove(g_vault, vkey)
}

vault_put_totals(id)
{
    new values[STATS]
    for (new s = 0; s < STATS; s++)
        values[s] = g_total[id][s]
    vault_write("t:", g_key[id], values)
}

vault_add_delta(const key[], const delta[STATS])
{
    new values[STATS]
    vault_read("d:", key, values)
    for (new s = 0; s < STATS; s++)
        values[s] += delta[s]
    vault_write("d:", key, values)
    pending_add(key)
}

// Keys with counts waiting for the database: one vault entry "key1^nkey2^n...".
pending_add(const key[])
{
    if (g_vault == INVALID_HANDLE)
        return
    new list[1024], line[72]
    nvault_get(g_vault, "pending", list, charsmax(list))
    formatex(line, charsmax(line), "%s^n", key)
    if (containi(list, line) == -1 && strlen(list) + strlen(line) < charsmax(list))
    {
        add(list, charsmax(list), line)
        nvault_set(g_vault, "pending", list)
    }
}

pending_remove(const key[])
{
    if (g_vault == INVALID_HANDLE)
        return
    new list[1024], line[72]
    nvault_get(g_vault, "pending", list, charsmax(list))
    formatex(line, charsmax(line), "%s^n", key)
    replace(list, charsmax(list), line, "")
    if (list[0])
        nvault_set(g_vault, "pending", list)
    else
        nvault_remove(g_vault, "pending")
}

/* ---------- database ---------- */

Handle:make_tuple()
{
    SQL_SetAffinity(g_driver)
    return SQL_MakeDbTuple(g_host, g_user, g_pass, g_db, 3)
}

bool:is_sqlite()
{
    return equali(g_driver, "sqlite")
}

set_down(const error[])
{
    if (!g_dbDown)
        log_amx("Database unavailable (%s): ball statistics are kept in the nVault until it answers", error)
    g_dbDown = true
}

create_table()
{
    new Handle:tuple = make_tuple()
    SQL_ThreadQuery(tuple, "on_table", "CREATE TABLE IF NOT EXISTS olds_ball_stats (steamid VARCHAR(64) NOT NULL PRIMARY KEY, name VARCHAR(64) NOT NULL DEFAULT '', goals INTEGER NOT NULL DEFAULT 0, assists INTEGER NOT NULL DEFAULT 0, touches INTEGER NOT NULL DEFAULT 0)")
    SQL_FreeHandle(tuple)
}

public on_table(failState, Handle:query, error[], errnum, data[], size, Float:queueTime)
{
    if (failState != TQUERY_SUCCESS)
    {
        set_down(error)
        return
    }
    if (g_dbDown)
        log_amx("Database answers again: merging the nVault")
    g_dbDown = false
    g_tableChecks++
    flush_pending()
}

load_player(id)
{
    if (!g_key[id][0])
        return
    new quoted[140], query[256], data[2]
    SQL_QuoteString(Empty_Handle, quoted, charsmax(quoted), g_key[id])
    formatex(query, charsmax(query), "SELECT goals, assists, touches FROM olds_ball_stats WHERE steamid = '%s'", quoted)
    data[0] = id
    data[1] = get_user_userid(id)
    new Handle:tuple = make_tuple()
    SQL_ThreadQuery(tuple, "on_load", query, data, sizeof(data))
    SQL_FreeHandle(tuple)
}

public on_load(failState, Handle:query, error[], errnum, data[], size, Float:queueTime)
{
    new id = data[0]
    if (!is_user_connected(id) || get_user_userid(id) != data[1])
        return
    new base[STATS], waiting[STATS]
    if (failState != TQUERY_SUCCESS)
    {
        set_down(error)
        // The last totals this server knew.
        vault_read("t:", g_key[id], base)
    }
    else
    {
        g_dbDown = false
        if (SQL_NumResults(query))
        {
            for (new s = 0; s < STATS; s++)
                base[s] = SQL_ReadResult(query, s)
        }
        // Counts left in the vault from an outage are still to be merged.
        vault_read("d:", g_key[id], waiting)
        for (new s = 0; s < STATS; s++)
            base[s] += waiting[s]
        if (waiting[0] || waiting[1] || waiting[2])
            push_pending(g_key[id])
    }
    // Counts made while the answer was on its way stay on top.
    for (new s = 0; s < STATS; s++)
    {
        g_total[id][s] += base[s]
        g_synced[id][s] = base[s]
    }
    g_loaded[id] = true
}

save_player(id)
{
    if (!g_key[id][0])
        return
    vault_put_totals(id)
    new delta[STATS], changed
    for (new s = 0; s < STATS; s++)
    {
        delta[s] = g_total[id][s] - g_synced[id][s]
        g_synced[id][s] = g_total[id][s]
        changed |= delta[s]
    }
    if (!changed)
        return
    new name[MAX_NAME_LENGTH]
    get_user_name(id, name, charsmax(name))
    // Sent even while the database is down: a failure lands in the vault, a success shows it is back.
    send_delta(g_key[id], name, delta)
}

// data: key (0-63), name (65-96), the three deltas (97-99), the step (100: 0 insert, 1 update)
send_delta(const key[], const name[], const delta[STATS])
{
    new data[102], quoted[140], qname[80], query[384]
    copy(data, 63, key)
    copy(data[65], 31, name)
    for (new s = 0; s < STATS; s++)
        data[97 + s] = delta[s]
    data[100] = 0
    SQL_QuoteString(Empty_Handle, quoted, charsmax(quoted), key)
    SQL_QuoteString(Empty_Handle, qname, charsmax(qname), name)
    if (is_sqlite())
        formatex(query, charsmax(query), "INSERT OR IGNORE INTO olds_ball_stats (steamid, name) VALUES ('%s', '%s')", quoted, qname)
    else
        formatex(query, charsmax(query), "INSERT IGNORE INTO olds_ball_stats (steamid, name) VALUES ('%s', '%s')", quoted, qname)
    new Handle:tuple = make_tuple()
    SQL_ThreadQuery(tuple, "on_delta", query, data, sizeof(data))
    SQL_FreeHandle(tuple)
}

public on_delta(failState, Handle:query, error[], errnum, data[], size, Float:queueTime)
{
    new key[64], name[32], delta[STATS]
    copy(key, charsmax(key), data)
    copy(name, charsmax(name), data[65])
    for (new s = 0; s < STATS; s++)
        delta[s] = data[97 + s]
    if (failState != TQUERY_SUCCESS)
    {
        set_down(error)
        // Not lost: kept in the vault and merged later.
        vault_add_delta(key, delta)
        return
    }
    g_dbDown = false
    if (data[100] != 0)
        return
    new quoted[140], qname[80], query2[384], setName[120]
    SQL_QuoteString(Empty_Handle, quoted, charsmax(quoted), key)
    if (name[0])
    {
        SQL_QuoteString(Empty_Handle, qname, charsmax(qname), name)
        formatex(setName, charsmax(setName), ", name = '%s'", qname)
    }
    formatex(query2, charsmax(query2),
        "UPDATE olds_ball_stats SET goals = goals + %d, assists = assists + %d, touches = touches + %d%s WHERE steamid = '%s'",
        delta[S_GOALS], delta[S_ASSISTS], delta[S_TOUCHES], setName, quoted)
    data[100] = 1
    new Handle:tuple = make_tuple()
    SQL_ThreadQuery(tuple, "on_delta", query2, data, size)
    SQL_FreeHandle(tuple)
}

push_pending(const key[])
{
    new delta[STATS], none[STATS]
    vault_read("d:", key, delta)
    vault_write("d:", key, none)
    pending_remove(key)
    if (delta[0] || delta[1] || delta[2])
    {
        send_delta(key, "", delta)
        log_amx("Merging %d goal(s), %d assist(s), %d touch(es) of %s from the nVault", delta[0], delta[1], delta[2], key)
    }
}

flush_pending()
{
    if (g_vault == INVALID_HANDLE)
        return
    new list[1024], rest[1024], key[72]
    nvault_get(g_vault, "pending", list, charsmax(list))
    while (list[0])
    {
        strtok2(list, key, charsmax(key), rest, charsmax(rest), '^n', TRIM_FULL)
        copy(list, charsmax(list), rest)
        if (key[0])
            push_pending(key)
    }
}

public task_save()
{
    save_all()
    // The table check answers whether the database is back; its answer merges the vault.
    create_table()
}

save_all()
{
    for (new id = 1; id <= MaxClients; id++)
        if (g_loaded[id])
            save_player(id)
}

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

public cmd_stats(id)
{
    client_print_color(id, print_team_default, "^4[Ball]^1 %L", id, "BS_STATS", g_total[id][S_GOALS],
        g_total[id][S_ASSISTS], g_total[id][S_TOUCHES])
    return PLUGIN_HANDLED
}

public cmd_top(id)
{
    // Unsaved counts first, so the list is current.
    save_all()
    new data[2]
    data[0] = id
    if (id)
        data[1] = get_user_userid(id)
    new query[160]
    formatex(query, charsmax(query), "SELECT name, steamid, goals, assists, touches FROM olds_ball_stats ORDER BY goals DESC, assists DESC LIMIT %d", TOP)
    new Handle:tuple = make_tuple()
    SQL_ThreadQuery(tuple, "on_top", query, data, sizeof(data))
    SQL_FreeHandle(tuple)
    return PLUGIN_HANDLED
}

public on_top(failState, Handle:query, error[], errnum, data[], size, Float:queueTime)
{
    new id = data[0]
    if (id && (!is_user_connected(id) || get_user_userid(id) != data[1]))
        return
    if (failState != TQUERY_SUCCESS)
    {
        set_down(error)
        if (id)
            client_print_color(id, print_team_default, "^4[Ball]^1 %L", id, "BS_TOP_DOWN")
        else
            server_print("[Ball] top %d: the database is down", TOP)
        return
    }
    g_dbDown = false
    new motd[1536], len, name[64], key[64], n
    len = formatex(motd, charsmax(motd), "<html><body style=^"background:#111;color:#ddd;font-family:Verdana^"><h3>Top %d scorers</h3><table><tr><th></th><th>Player</th><th>Goals</th><th>Assists</th><th>Touches</th></tr>", TOP)
    while (SQL_MoreResults(query))
    {
        n++
        SQL_ReadResult(query, 0, name, charsmax(name))
        SQL_ReadResult(query, 1, key, charsmax(key))
        new goals = SQL_ReadResult(query, 2), assists = SQL_ReadResult(query, 3), touches = SQL_ReadResult(query, 4)
        if (!name[0])
            copy(name, charsmax(name), key)
        replace_all(name, charsmax(name), "&", "&amp;")
        replace_all(name, charsmax(name), "<", "&lt;")
        replace_all(name, charsmax(name), ">", "&gt;")
        len += formatex(motd[len], charsmax(motd) - len, "<tr><td>%d.</td><td>%s</td><td>%d</td><td>%d</td><td>%d</td></tr>", n,
            name, goals, assists, touches)
        if (!id)
            server_print("[Ball] top %d: %s, %d goal(s), %d assist(s), %d touch(es)", n, name, goals, assists, touches)
        SQL_NextRow(query)
    }
    if (!n)
        len += formatex(motd[len], charsmax(motd) - len, "<tr><td colspan=5>No goals yet.</td></tr>")
    formatex(motd[len], charsmax(motd) - len, "</table></body></html>")
    if (id)
        show_motd(id, motd, "Ball top")
    else if (!n)
        server_print("[Ball] top %d: no goals yet", TOP)
}

public cmd_save(id, level, cid)
{
    if (!cmd_access(id, level, cid, 1))
        return PLUGIN_HANDLED
    task_save()
    console_print(id, "[Ball] saving every player's ball statistics")
    return PLUGIN_HANDLED
}

public cmd_status(id, level, cid)
{
    if (!cmd_access(id, level, cid, 1))
        return PLUGIN_HANDLED
    new pending[1024]
    if (g_vault != INVALID_HANDLE)
        nvault_get(g_vault, "pending", pending, charsmax(pending))
    replace_all(pending, charsmax(pending), "^n", " ")
    console_print(id, "[Ball] driver %s, database down %d, table checks %d, ball %s, net %s, pending in vault: %s", g_driver,
        g_dbDown, g_tableChecks, g_ballClass, g_netClass, pending)
    new name[MAX_NAME_LENGTH], waiting[STATS]
    for (new p = 1; p <= MaxClients; p++)
    {
        if (!is_user_connected(p))
            continue
        get_user_name(p, name, charsmax(name))
        vault_read("d:", g_key[p], waiting)
        console_print(id, "[Ball]   %s (%s): goals %d, assists %d, touches %d; saved %d/%d/%d; in vault %d/%d/%d; loaded %d",
            name, g_key[p], g_total[p][S_GOALS], g_total[p][S_ASSISTS], g_total[p][S_TOUCHES], g_synced[p][S_GOALS],
            g_synced[p][S_ASSISTS], g_synced[p][S_TOUCHES], waiting[0], waiting[1], waiting[2], g_loaded[p])
    }
    if (!id)
        cmd_top(0)
    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.