Skip to content
View in the app

A better way to browse. Learn more.

Learn more

bhop-jump-rank/addons/amxmodx/scripting/olds_bhoprank.sma

olds_bhoprank.sma
597 lines · 19.2 KB · Pawn (AMX Mod X)
Raw
/*
 * Bhop Jump Rank (olds.ro workshop card LIB-0808)
 * Copyright (C) 2026 daemon (olds.ro)
 *
 * This program is free software: you can redistribute it and/or modify it under the terms
 * of the GNU General Public License as published by the Free Software Foundation, either
 * version 3 of the License, or (at your option) any later version.
 * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
 * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details: <https://www.gnu.org/licenses/>.
 *
 * Counts bunny hop jumps and ranks players by milestones. In FM_PlayerPreThink a change from
 * ground to air going up is a jump; it is a bunny hop when it comes within 0.1 s of the
 * landing before it. Once a run of olds_bhop_streak hops in a row is reached, the whole run
 * is counted and every further hop of it counts at once. Ranks start at the totals in
 * olds_bhop_levels; a new rank is announced in chat with the stock events/task_complete.wav.
 *
 * Totals are kept in the SQLx table olds_bhop by SteamID (threaded queries, MySQL or
 * SQLite). When the database cannot be reached the unsaved jumps go to the nVault
 * "olds_bhop" instead, and they are merged into the table as soon as it answers again
 * (at map start, every two minutes and when that player joins).
 */
#include <amxmodx>
#include <amxmisc>
#include <fakemeta>
#include <sqlx>
#include <nvault>

#define PLUGIN  "Bhop Jump Rank"
#define VERSION "1.0.0"
#define AUTHOR  "daemon (olds.ro)"

#define MAX_LEVELS  8
#define TASK_SAVE   8080
#define TASK_FLUSH  8081
#define HOP_WINDOW  0.1
#define LEVEL_SOUND "events/task_complete.wav"

new g_streak, g_keyMode
new g_cvarLevels, g_cvarNames
new g_driver[16], g_host[64], g_user[64], g_pass[64], g_db[64]

new g_levels[MAX_LEVELS], g_levelCount
new g_names[MAX_LEVELS + 1][32]

new g_key[MAX_PLAYERS + 1][64]
new g_jumps[MAX_PLAYERS + 1]     /* total shown to the player */
new g_synced[MAX_PLAYERS + 1]    /* part of the total already handed to the database or the vault */
new bool:g_loaded[MAX_PLAYERS + 1]
new g_run[MAX_PLAYERS + 1]       /* hops in the current run */
new bool:g_onGround[MAX_PLAYERS + 1]
new Float:g_landedAt[MAX_PLAYERS + 1]
new Float:g_lastHud[MAX_PLAYERS + 1]
new g_vault = INVALID_HANDLE
new bool:g_dbDown
new g_tableReady

/* ------------------------------------------------------------------ setup */

public plugin_precache()
{
    precache_sound(LEVEL_SOUND)
}

public plugin_init()
{
    register_plugin(PLUGIN, VERSION, AUTHOR)
    register_dictionary("olds_bhoprank.txt")
    bind_pcvar_num(create_cvar("olds_bhop_streak", "3", FCVAR_NONE, "Hops in a row before a run is counted", true, 1.0, true, 50.0), g_streak)
    g_cvarLevels = create_cvar("olds_bhop_levels", "100,500,2000", FCVAR_NONE, "Jump totals where the ranks start, ascending, comma separated")
    g_cvarNames = create_cvar("olds_bhop_names", "Walker,Hopper,Bunny,Rabbit King", FCVAR_NONE, "Rank names, one more than the levels, comma separated")
    hook_cvar_change(g_cvarLevels, "on_levels_change")
    hook_cvar_change(g_cvarNames, "on_levels_change")
    bind_pcvar_num(create_cvar("olds_bhop_key", "0", FCVAR_NONE, "Player key: 0 = SteamID, 1 = name", true, 0.0, true, 1.0), g_keyMode)
    bind_pcvar_string(create_cvar("olds_bhop_driver", "mysql", FCVAR_NONE, "SQLx driver: mysql or sqlite"), g_driver, charsmax(g_driver))
    bind_pcvar_string(create_cvar("olds_bhop_host", "127.0.0.1", FCVAR_PROTECTED, "Database host"), g_host, charsmax(g_host))
    bind_pcvar_string(create_cvar("olds_bhop_user", "", FCVAR_PROTECTED, "Database user"), g_user, charsmax(g_user))
    bind_pcvar_string(create_cvar("olds_bhop_pass", "", FCVAR_PROTECTED, "Database password"), g_pass, charsmax(g_pass))
    bind_pcvar_string(create_cvar("olds_bhop_db", "amxx", FCVAR_PROTECTED, "Database name (sqlite: the file in data/sqlite3)"), g_db, charsmax(g_db))
    AutoExecConfig(true, "olds_bhoprank")

    register_clcmd("say /rank", "cmd_rank")
    register_clcmd("say_team /rank", "cmd_rank")
    register_clcmd("say /top15", "cmd_top")
    register_clcmd("say_team /top15", "cmd_top")
    register_concmd("amx_bhop_status", "cmd_status", ADMIN_KICK, "- jumps, ranks and the database state")
    register_concmd("amx_bhop_save", "cmd_save", ADMIN_CFG, "- saves every player's jumps now")
    register_forward(FM_PlayerPreThink, "on_prethink")
    g_vault = nvault_open("olds_bhop")
    if (g_vault == INVALID_HANDLE)
        log_amx("Could not open the nVault olds_bhop: no fallback while the database is down")
}

public plugin_cfg()
{
    parse_levels()
    create_table()
    set_task(60.0, "save_all_task", TASK_SAVE, _, _, "b")
    set_task(120.0, "flush_task", TASK_FLUSH, _, _, "b")
}

public plugin_end()
{
    /* Map end: threaded queries may not finish now, so the unsaved jumps go to the vault and
       are merged at the next map start. */
    for (new id = 1; id <= MaxClients; id++)
    {
        if (!g_loaded[id] || !g_key[id][0])
            continue
        new delta = g_jumps[id] - g_synced[id]
        vault_set("t:", g_key[id], g_jumps[id])
        if (delta > 0)
        {
            vault_set("d:", g_key[id], vault_get("d:", g_key[id]) + delta)
            pending_add(g_key[id])
            g_synced[id] = g_jumps[id]
        }
    }
    if (g_vault != INVALID_HANDLE)
        nvault_close(g_vault)
}

/* ------------------------------------------------------------------ ranks */

public on_levels_change(pcvar, const oldValue[], const newValue[])
{
    RequestFrame("parse_levels_frame")
}

public parse_levels_frame()
{
    parse_levels()
}

parse_levels()
{
    new text[160], rest[160], part[16], last = 0
    get_pcvar_string(g_cvarLevels, text, charsmax(text))
    g_levelCount = 0
    while (text[0] && g_levelCount < MAX_LEVELS)
    {
        strtok2(text, part, charsmax(part), rest, charsmax(rest), ',', TRIM_FULL)
        copy(text, charsmax(text), rest)
        new value = str_to_num(part)
        if (!is_str_num(part) || value <= last)
        {
            log_amx("olds_bhop_levels: ^"%s^" is not a number above %d, the rest is ignored", part, last)
            break
        }
        g_levels[g_levelCount++] = value
        last = value
    }
    get_pcvar_string(g_cvarNames, text, charsmax(text))
    for (new i = 0; i <= g_levelCount; i++)
    {
        if (text[0])
        {
            strtok2(text, g_names[i], charsmax(g_names[]), rest, charsmax(rest), ',', TRIM_FULL)
            copy(text, charsmax(text), rest)
        }
        else
            formatex(g_names[i], charsmax(g_names[]), "Rank %d", i + 1)
    }
}

rank_of(jumps)
{
    new r
    while (r < g_levelCount && jumps >= g_levels[r])
        r++
    return r
}

/* ------------------------------------------------------------------ counting */

public on_prethink(id)
{
    if (!is_user_alive(id))
        return FMRES_IGNORED
    new bool:ground = (pev(id, pev_flags) & FL_ONGROUND) != 0
    new Float:now = get_gametime()
    if (ground && !g_onGround[id])
        g_landedAt[id] = now
    else if (!ground && g_onGround[id])
    {
        new Float:vel[3]
        pev(id, pev_velocity, vel)
        if (vel[2] > 100.0 && pev(id, pev_waterlevel) < 2 && pev(id, pev_movetype) == MOVETYPE_WALK)
            took_off(id, now - g_landedAt[id] <= HOP_WINDOW)
    }
    g_onGround[id] = ground
    return FMRES_IGNORED
}

took_off(id, bool:hop)
{
    if (!hop)
    {
        /* A jump from standing starts a new run. */
        g_run[id] = 1
        return
    }
    g_run[id]++
    new add = 0
    if (g_run[id] == g_streak)
        add = g_streak
    else if (g_run[id] > g_streak)
        add = 1
    if (!add)
        return
    new before = rank_of(g_jumps[id])
    g_jumps[id] += add
    new after = rank_of(g_jumps[id])
    if (after > before)
        level_up(id, after)
    new Float:now = get_gametime()
    if (now - g_lastHud[id] > 0.2 && !is_user_bot(id))
    {
        g_lastHud[id] = now
        set_hudmessage(80, 200, 255, -1.0, 0.85, 0, 0.0, 1.0, 0.0, 0.2, -1)
        show_hudmessage(id, "%L", id, "BHR_HUD", g_jumps[id], g_names[after], g_run[id])
    }
}

level_up(id, rank)
{
    new name[MAX_NAME_LENGTH]
    get_user_name(id, name, charsmax(name))
    client_print(0, print_chat, "%L", LANG_PLAYER, "BHR_LEVEL_UP", name, g_names[rank], g_jumps[id])
    client_cmd(id, "spk ^"%s^"", LEVEL_SOUND)
    log_amx("%s reached rank %s with %d jumps", name, g_names[rank], g_jumps[id])
    save_player(id)
}

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

make_key(id)
{
    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[]))
}

public client_putinserver(id)
{
    g_jumps[id] = 0
    g_synced[id] = 0
    g_run[id] = 0
    g_loaded[id] = false
    g_onGround[id] = false
    make_key(id)
    load_player(id)
}

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

vault_get(const prefix[], const key[])
{
    if (g_vault == INVALID_HANDLE)
        return 0
    new vkey[72]
    formatex(vkey, charsmax(vkey), "%s%s", prefix, key)
    return nvault_get(g_vault, vkey)
}

vault_set(const prefix[], const key[], value)
{
    if (g_vault == INVALID_HANDLE)
        return
    new vkey[72], text[16]
    formatex(vkey, charsmax(vkey), "%s%s", prefix, key)
    if (value)
    {
        num_to_str(value, text, charsmax(text))
        nvault_set(g_vault, vkey, text)
    }
    else
        nvault_remove(g_vault, vkey)
}

/* The keys with jumps waiting for the database, as 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")
}

create_table()
{
    new Handle:tuple = make_tuple()
    SQL_ThreadQuery(tuple, "on_table", "CREATE TABLE IF NOT EXISTS olds_bhop (steamid VARCHAR(64) NOT NULL PRIMARY KEY, name VARCHAR(64) NOT NULL DEFAULT '', jumps 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
    }
    g_dbDown = false
    g_tableReady++
    flush_pending()
}

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

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 jumps FROM olds_bhop 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
    if (failState != TQUERY_SUCCESS)
    {
        set_down(error)
        /* The last total this server knew, from the vault. */
        base = vault_get("t:", g_key[id])
    }
    else
    {
        g_dbDown = false
        if (SQL_NumResults(query))
            base = SQL_ReadResult(query, 0)
        /* Jumps left in the vault from a database outage are still to be merged. */
        base += vault_get("d:", g_key[id])
        if (vault_get("d:", g_key[id]))
            push_pending(g_key[id])
    }
    /* Jumps made while the answer was on its way stay on top. */
    new during = g_jumps[id]
    g_jumps[id] = base + during
    g_synced[id] = base
    g_loaded[id] = true
}

/* Hands the unsaved part of the total to the database (or, if it is down, to the vault). */
save_player(id)
{
    new delta = g_jumps[id] - g_synced[id]
    vault_set("t:", g_key[id], g_jumps[id])
    if (delta <= 0 || !g_key[id][0])
        return
    g_synced[id] = g_jumps[id]
    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
       the database is back. */
    send_delta(g_key[id], name, delta)
}

/* data: key, then the delta in the last cell (step 0 = insert the row, 1 = add the jumps) */
send_delta(const key[], const name[], delta)
{
    new data[100], quoted[140], qname[80], query[384]
    copy(data, 64, key)
    copy(data[65], 31, name)
    data[97] = delta
    data[98] = 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_bhop (steamid, name, jumps) VALUES ('%s', '%s', 0)", quoted, qname)
    else
        formatex(query, charsmax(query), "INSERT IGNORE INTO olds_bhop (steamid, name, jumps) VALUES ('%s', '%s', 0)", 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[65], name[32]
    copy(key, charsmax(key), data)
    copy(name, charsmax(name), data[65])
    new delta = data[97]
    if (failState != TQUERY_SUCCESS)
    {
        set_down(error)
        /* Not lost: kept in the vault and merged later. */
        vault_set("d:", key, vault_get("d:", key) + delta)
        pending_add(key)
        return
    }
    g_dbDown = false
    if (data[98] == 0)
    {
        new quoted[140], query2[256]
        SQL_QuoteString(Empty_Handle, quoted, charsmax(quoted), key)
        formatex(query2, charsmax(query2), "UPDATE olds_bhop SET jumps = jumps + %d WHERE steamid = '%s'", delta, quoted)
        data[98] = 1
        new Handle:tuple = make_tuple()
        SQL_ThreadQuery(tuple, "on_delta", query2, data, size)
        SQL_FreeHandle(tuple)
    }
}

/* Moves the jumps kept in the vault for one key into the database. */
push_pending(const key[])
{
    new delta = vault_get("d:", key)
    vault_set("d:", key, 0)
    pending_remove(key)
    if (delta > 0)
    {
        send_delta(key, "", delta)
        log_amx("Merging %d jumps of %s from the nVault into the database", delta, 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)
        /* An online player's total already holds these jumps: only the table gets them. */
        if (key[0])
            push_pending(key)
    }
}

/* The table is checked (and made) first; its answer merges the vault. */
public flush_task()
{
    create_table()
}

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

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

public cmd_rank(id)
{
    new r = rank_of(g_jumps[id])
    if (r < g_levelCount)
        client_print(id, print_chat, "%L", id, "BHR_RANK_NEXT", g_names[r], g_jumps[id], g_levels[r] - g_jumps[id], g_names[r + 1])
    else
        client_print(id, print_chat, "%L", id, "BHR_RANK_TOP", g_names[r], g_jumps[id])
    return PLUGIN_HANDLED
}

public cmd_top(id)
{
    /* Unsaved jumps first, so the list is current. */
    save_all_task()
    new data[2]
    data[0] = id
    data[1] = 0
    if (id)
        data[1] = get_user_userid(id)
    new Handle:tuple = make_tuple()
    SQL_ThreadQuery(tuple, "on_top", "SELECT name, steamid, jumps FROM olds_bhop ORDER BY jumps DESC LIMIT 15", 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(id, print_chat, "%L", id, "BHR_TOP_DOWN")
        else
            server_print("[Bhop] top 15: the database is down")
        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>Bhop top 15</h3><table>")
    while (SQL_MoreResults(query))
    {
        n++
        SQL_ReadResult(query, 0, name, charsmax(name))
        SQL_ReadResult(query, 1, key, charsmax(key))
        new jumps = SQL_ReadResult(query, 2)
        if (!name[0])
            copy(name, charsmax(name), key)
        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>%s</td></tr>", n, name, jumps, g_names[rank_of(jumps)])
        if (!id)
            server_print("[Bhop] top %d: %s, %d jumps, %s", n, name, jumps, g_names[rank_of(jumps)])
        SQL_NextRow(query)
    }
    formatex(motd[len], charsmax(motd) - len, "</table></body></html>")
    if (id)
        show_motd(id, motd, "Bhop top 15")
}

public cmd_save(id, level, cid)
{
    if (!cmd_access(id, level, cid, 1))
        return PLUGIN_HANDLED
    save_all_task()
    create_table()
    console_print(id, "[Bhop] saving every player's jumps")
    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, "[Bhop] driver %s, database down %d, table checks %d, streak %d, levels %d, pending in vault: %s", g_driver, g_dbDown,
        g_tableReady, g_streak, g_levelCount, pending)
    new name[MAX_NAME_LENGTH]
    for (new p = 1; p <= MaxClients; p++)
    {
        if (!is_user_connected(p))
            continue
        get_user_name(p, name, charsmax(name))
        console_print(id, "[Bhop]   %s (%s): jumps %d, saved %d, in vault %d, rank %s, run %d, loaded %d", name, g_key[p], g_jumps[p],
            g_synced[p], vault_get("d:", g_key[p]), g_names[rank_of(g_jumps[p])], g_run[p], 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.