From 170746cbecdf646a0d8bdd63363d658c34924464 Mon Sep 17 00:00:00 2001 From: et-nik Date: Sun, 17 Jan 2021 17:26:18 +0300 Subject: [PATCH 01/19] Implement team spawn points --- src/game/server/gamerules.cpp | 2 +- src/game/server/player.cpp | 40 ++++++++++++++++++++++------------- 2 files changed, 26 insertions(+), 16 deletions(-) diff --git a/src/game/server/gamerules.cpp b/src/game/server/gamerules.cpp index 63c8dc47..7cf7bca9 100644 --- a/src/game/server/gamerules.cpp +++ b/src/game/server/gamerules.cpp @@ -26,7 +26,7 @@ #include "skill.h" #include "game.h" -extern edict_t *EntSelectSpawnPoint(CBaseEntity *pPlayer); +extern edict_t *EntSelectSpawnPoint(CBasePlayer *pPlayer); DLL_GLOBAL CGameRules *g_pGameRules = NULL; extern DLL_GLOBAL BOOL g_fGameOver; diff --git a/src/game/server/player.cpp b/src/game/server/player.cpp index 57f3328a..7eff2315 100644 --- a/src/game/server/player.cpp +++ b/src/game/server/player.cpp @@ -48,7 +48,7 @@ BOOL gInitHUD = TRUE; extern void CopyToBodyQue(entvars_t *pev); extern Vector VecBModelOrigin(entvars_t *pevBModel); -extern edict_t *EntSelectSpawnPoint(CBaseEntity *pPlayer); +extern edict_t *EntSelectSpawnPoint(CBasePlayer *pPlayer); // the world node graph extern CGraph WorldGraph; @@ -2809,7 +2809,7 @@ Returns the entity to spawn at USES AND SETS GLOBAL g_pLastSpawn ============ */ -edict_t *EntSelectSpawnPoint(CBaseEntity *pPlayer) +edict_t *EntSelectSpawnPoint(CBasePlayer *pPlayer) { CBaseEntity *pSpot; edict_t *player; @@ -2832,31 +2832,41 @@ edict_t *EntSelectSpawnPoint(CBaseEntity *pPlayer) // Randomize the start spot for (int i = RANDOM_LONG(1, 5); i > 0; i--) pSpot = UTIL_FindEntityByClassname(pSpot, "info_player_deathmatch"); + if (FNullEnt(pSpot)) // skip over the null point pSpot = UTIL_FindEntityByClassname(pSpot, "info_player_deathmatch"); - CBaseEntity *pFirstSpot = pSpot; + if (g_pGameRules->IsTeamplay()) { + // try to find team spawn + CBaseEntity *pFirstSpot = pSpot; - do - { - if (pSpot) - { - // check if pSpot is valid - if (IsSpawnPointValid(pPlayer, pSpot)) - { - if (pSpot->pev->origin == Vector(0, 0, 0)) - { + do { + if (pSpot) { + if (g_pGameRules->GetTeamIndex(pPlayer->TeamID()) != pSpot->pev->team) { pSpot = UTIL_FindEntityByClassname(pSpot, "info_player_deathmatch"); continue; } - // if so, go to pSpot + if (IsSpawnPointValid(pPlayer, pSpot) && pSpot->pev->origin != Vector(0, 0, 0)) { + goto ReturnSpot; + } + } + + pSpot = UTIL_FindEntityByClassname(pSpot, "info_player_deathmatch"); + } while (pSpot != pFirstSpot); + } + + CBaseEntity *pFirstSpot = pSpot; + + do { + if (pSpot) { + if (IsSpawnPointValid(pPlayer, pSpot) && pSpot->pev->origin != Vector(0, 0, 0)) { goto ReturnSpot; } } - // increment pSpot + pSpot = UTIL_FindEntityByClassname(pSpot, "info_player_deathmatch"); - } while (pSpot != pFirstSpot); // loop if we're not back to the start + } while (pSpot != pFirstSpot); // we haven't found a place to spawn yet, so kill any guy at the first spawn point and spawn there if (!FNullEnt(pSpot)) From 5012039a957f5c00856e5a32b45e445c58a12b9e Mon Sep 17 00:00:00 2001 From: et-nik Date: Sun, 17 Jan 2021 23:00:43 +0300 Subject: [PATCH 02/19] Fix codestyle --- src/game/server/player.cpp | 24 ++++++++++++++++-------- 1 file changed, 16 insertions(+), 8 deletions(-) diff --git a/src/game/server/player.cpp b/src/game/server/player.cpp index 7eff2315..9f587c93 100644 --- a/src/game/server/player.cpp +++ b/src/game/server/player.cpp @@ -2836,18 +2836,23 @@ edict_t *EntSelectSpawnPoint(CBasePlayer *pPlayer) if (FNullEnt(pSpot)) // skip over the null point pSpot = UTIL_FindEntityByClassname(pSpot, "info_player_deathmatch"); - if (g_pGameRules->IsTeamplay()) { + if (g_pGameRules->IsTeamplay()) + { // try to find team spawn CBaseEntity *pFirstSpot = pSpot; - do { - if (pSpot) { - if (g_pGameRules->GetTeamIndex(pPlayer->TeamID()) != pSpot->pev->team) { + do + { + if (pSpot) + { + if (g_pGameRules->GetTeamIndex(pPlayer->TeamID()) != pSpot->pev->team) + { pSpot = UTIL_FindEntityByClassname(pSpot, "info_player_deathmatch"); continue; } - if (IsSpawnPointValid(pPlayer, pSpot) && pSpot->pev->origin != Vector(0, 0, 0)) { + if (IsSpawnPointValid(pPlayer, pSpot) && pSpot->pev->origin != Vector(0, 0, 0)) + { goto ReturnSpot; } } @@ -2858,9 +2863,12 @@ edict_t *EntSelectSpawnPoint(CBasePlayer *pPlayer) CBaseEntity *pFirstSpot = pSpot; - do { - if (pSpot) { - if (IsSpawnPointValid(pPlayer, pSpot) && pSpot->pev->origin != Vector(0, 0, 0)) { + do + { + if (pSpot) + { + if (IsSpawnPointValid(pPlayer, pSpot) && pSpot->pev->origin != Vector(0, 0, 0)) + { goto ReturnSpot; } } From d626045efe3a22946afea6832b81d802c0f6bebb Mon Sep 17 00:00:00 2001 From: tmp64 Date: Mon, 18 Jan 2021 10:20:00 +0700 Subject: [PATCH 03/19] Server: Add a cvar to toggle team spawns --- src/game/server/player.cpp | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/game/server/player.cpp b/src/game/server/player.cpp index 9f587c93..5e4b0871 100644 --- a/src/game/server/player.cpp +++ b/src/game/server/player.cpp @@ -53,6 +53,8 @@ extern edict_t *EntSelectSpawnPoint(CBasePlayer *pPlayer); // the world node graph extern CGraph WorldGraph; +ConVar mp_use_team_spawns("mp_use_team_spawns", "0", FCVAR_SERVER, "When teamplay is enabled, players will be spawned on team spawns if the map has them"); + #define TRAIN_ACTIVE 0x80 #define TRAIN_NEW 0xc0 #define TRAIN_OFF 0x00 @@ -2836,7 +2838,7 @@ edict_t *EntSelectSpawnPoint(CBasePlayer *pPlayer) if (FNullEnt(pSpot)) // skip over the null point pSpot = UTIL_FindEntityByClassname(pSpot, "info_player_deathmatch"); - if (g_pGameRules->IsTeamplay()) + if (g_pGameRules->IsTeamplay() && mp_use_team_spawns.GetBool()) { // try to find team spawn CBaseEntity *pFirstSpot = pSpot; From cdac9ad996626b1ead7ff322cd9497ac5535be4a Mon Sep 17 00:00:00 2001 From: tmp64 Date: Tue, 19 Jan 2021 23:03:25 +0700 Subject: [PATCH 04/19] Server: Rename mp_use_team_spawns -> mp_teamspawn --- src/game/server/player.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/game/server/player.cpp b/src/game/server/player.cpp index 5e4b0871..d90b8762 100644 --- a/src/game/server/player.cpp +++ b/src/game/server/player.cpp @@ -53,7 +53,7 @@ extern edict_t *EntSelectSpawnPoint(CBasePlayer *pPlayer); // the world node graph extern CGraph WorldGraph; -ConVar mp_use_team_spawns("mp_use_team_spawns", "0", FCVAR_SERVER, "When teamplay is enabled, players will be spawned on team spawns if the map has them"); +ConVar mp_teamspawn("mp_teamspawn", "0", FCVAR_SERVER, "When teamplay is enabled, players will be spawned on team spawns if the map has them"); #define TRAIN_ACTIVE 0x80 #define TRAIN_NEW 0xc0 @@ -2838,7 +2838,7 @@ edict_t *EntSelectSpawnPoint(CBasePlayer *pPlayer) if (FNullEnt(pSpot)) // skip over the null point pSpot = UTIL_FindEntityByClassname(pSpot, "info_player_deathmatch"); - if (g_pGameRules->IsTeamplay() && mp_use_team_spawns.GetBool()) + if (g_pGameRules->IsTeamplay() && mp_teamspawn.GetBool()) { // try to find team spawn CBaseEntity *pFirstSpot = pSpot; From 984164ccb24edde82211e3ebc127e6e32622815d Mon Sep 17 00:00:00 2001 From: et-nik Date: Tue, 19 Jan 2021 19:28:52 +0300 Subject: [PATCH 05/19] Fix ci artifacts. Add platform type to archive name --- scripts/BuildRelease.py | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/scripts/BuildRelease.py b/scripts/BuildRelease.py index 228e51e3..64cdd346 100755 --- a/scripts/BuildRelease.py +++ b/scripts/BuildRelease.py @@ -282,8 +282,13 @@ def parse_arguments(self): self.release_version = "{}+{}".format(self.release_version, args.v_meta) # Set output directory - self.out_dir_name = 'BugfixedHL-{}-{}-{}-{}'.format(self.release_version.replace('+', '-'), - self.build_target_name, self.git_hash, self.date_code) + self.out_dir_name = 'BugfixedHL-{}-{}-{}-{}-{}'.format( + self.release_version.replace('+', '-'), + self.build_target_name, + get_platform_type(), + self.git_hash, + self.date_code + ) out_dir = args.out_dir if out_dir: From a76c6b24275a2bc19a0aaeb29b9aaa935ead4bb0 Mon Sep 17 00:00:00 2001 From: et-nik Date: Sun, 24 Jan 2021 19:01:51 +0300 Subject: [PATCH 06/19] Add export for some methods and functions --- src/game/server/player.h | 6 +++--- src/game/server/weapons.h | 6 +++--- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/src/game/server/player.h b/src/game/server/player.h index b52d3539..4726434d 100644 --- a/src/game/server/player.h +++ b/src/game/server/player.h @@ -243,7 +243,7 @@ class CBasePlayer : public CBaseMonster void DeathSound(void); int Classify(void); - void SetAnimation(PLAYER_ANIM playerAnim); + void EXPORT SetAnimation(PLAYER_ANIM playerAnim); void SetWeaponAnimType(const char *szExtention); char m_szAnimExtention[32]; @@ -275,7 +275,7 @@ class CBasePlayer : public CBaseMonster void SelectItem(const char *pstr); void ItemPreFrame(void); void ItemPostFrame(void); - void GiveNamedItem(const char *szName); + void EXPORT GiveNamedItem(const char *szName); void EnableControl(BOOL fControl); int GiveAmmo(int iAmount, char *szName, int iMax); @@ -293,7 +293,7 @@ class CBasePlayer : public CBaseMonster BOOL FBecomeProne(void); void BarnacleVictimBitten(entvars_t *pevBarnacle); void BarnacleVictimReleased(void); - static int GetAmmoIndex(const char *psz); + static int EXPORT GetAmmoIndex(const char *psz); int AmmoInventory(int iAmmoIndex); int Illumination(void); diff --git a/src/game/server/weapons.h b/src/game/server/weapons.h index 03ec1905..302fcfa7 100644 --- a/src/game/server/weapons.h +++ b/src/game/server/weapons.h @@ -383,9 +383,9 @@ extern DLL_GLOBAL short g_sModelIndexBubbles; // holds the index for the bubbles extern DLL_GLOBAL short g_sModelIndexBloodDrop; // holds the sprite index for blood drops extern DLL_GLOBAL short g_sModelIndexBloodSpray; // holds the sprite index for blood spray (bigger) -extern void ClearMultiDamage(void); -extern void ApplyMultiDamage(entvars_t *pevInflictor, entvars_t *pevAttacker); -extern void AddMultiDamage(entvars_t *pevInflictor, CBaseEntity *pEntity, float flDamage, int bitsDamageType); +extern void EXPORT ClearMultiDamage(void); +extern void EXPORT ApplyMultiDamage(entvars_t *pevInflictor, entvars_t *pevAttacker); +extern void EXPORT AddMultiDamage(entvars_t *pevInflictor, CBaseEntity *pEntity, float flDamage, int bitsDamageType); extern void DecalGunshot(TraceResult *pTrace, int iBulletType); extern void SpawnBlood(Vector vecSpot, int bloodColor, float flDamage); From da65de3c199c10198a828c581f6ebafa563d70b5 Mon Sep 17 00:00:00 2001 From: et-nik Date: Sun, 24 Jan 2021 19:27:08 +0300 Subject: [PATCH 07/19] Add export for UTIL_PrecacheOtherWeapon --- src/game/server/weapons.h | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/game/server/weapons.h b/src/game/server/weapons.h index 302fcfa7..f76cbf98 100644 --- a/src/game/server/weapons.h +++ b/src/game/server/weapons.h @@ -387,6 +387,8 @@ extern void EXPORT ClearMultiDamage(void); extern void EXPORT ApplyMultiDamage(entvars_t *pevInflictor, entvars_t *pevAttacker); extern void EXPORT AddMultiDamage(entvars_t *pevInflictor, CBaseEntity *pEntity, float flDamage, int bitsDamageType); +extern void EXPORT UTIL_PrecacheOtherWeapon(const char *szClassname); + extern void DecalGunshot(TraceResult *pTrace, int iBulletType); extern void SpawnBlood(Vector vecSpot, int bloodColor, float flDamage); extern int DamageDecal(CBaseEntity *pEntity, int bitsDamageType); From 3eea5476e06895b008b0a39b77df029b7f5ebfad Mon Sep 17 00:00:00 2001 From: et-nik Date: Sat, 14 Dec 2024 01:11:06 +0100 Subject: [PATCH 08/19] update source_sdk --- source_sdk | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/source_sdk b/source_sdk index b3d55819..4ee45b6c 160000 --- a/source_sdk +++ b/source_sdk @@ -1 +1 @@ -Subproject commit b3d558195e8ecd5948c2b5e4d210a199e6881834 +Subproject commit 4ee45b6cf749322e5e6734c2a3f16f6ac9726b54 From d94e7efb85730ed54677b07b225c150f40e0c02a Mon Sep 17 00:00:00 2001 From: et-nik Date: Mon, 12 Oct 2026 11:37:34 +0200 Subject: [PATCH 09/19] custom scoreboard --- docs/scoreboard-protocol.md | 1013 ++++++++++++++++ gamedir/CMakeLists.txt | 1 + .../amxmodx/scripting/include/bugfixedapi.inc | 147 +++ gamedir/ui/resource/ClientSchemeBase.res | 84 ++ gamedir/ui/resource/ScorePanel_gungame.res | 105 ++ .../language/bugfixedhl_english.utf8.txt | 44 + .../language/bugfixedhl_russian.utf8.txt | 44 + gamedir/ui/scripts/HudLayoutBase.res | 35 + src/bugfixedapi_amxx/bhl_api.cpp | 7 +- src/bugfixedapi_amxx/bhl_api.h | 8 + src/bugfixedapi_amxx/bugfixedapi_amxx.cpp | 252 +++- src/bugfixedapi_amxx/moduleconfig.h | 6 +- src/game/client/CMakeLists.txt | 6 + src/game/client/hud.cpp | 74 ++ src/game/client/hud.h | 12 + src/game/client/hud/gungame_hud.cpp | 540 +++++++++ src/game/client/hud/gungame_hud.h | 95 ++ src/game/client/hud/jumpspeed.cpp | 3 +- src/game/client/hud/scores.cpp | 42 +- src/game/client/hud/speedometer.cpp | 3 +- src/game/client/hud/statusbar.cpp | 6 + src/game/client/hud/timer.cpp | 10 +- src/game/client/hud_renderer.cpp | 13 +- src/game/client/hud_renderer.h | 5 +- src/game/client/scoreboard_data.cpp | 1060 +++++++++++++++++ src/game/client/scoreboard_data.h | 187 +++ src/game/client/vgui/score_panel.cpp | 799 ++++++++++++- src/game/client/vgui/score_panel.h | 153 +++ src/game/client/vgui/score_panel_cells.cpp | 426 +++++++ src/game/client/vgui/score_panel_cells.h | 121 ++ src/game/server/CBugfixedServer.cpp | 245 +++- src/game/server/CBugfixedServer.h | 49 + src/game/server/CMakeLists.txt | 2 + src/game/server/CScoreboardExt.cpp | 871 ++++++++++++++ src/game/server/CScoreboardExt.h | 153 +++ src/game/server/client.cpp | 7 + src/game/server/multiplay_gamerules.cpp | 2 + src/game/server/player.cpp | 3 + src/game/shared/CMakeLists.txt | 2 + src/game/shared/ClientSupportsFlags.h | 8 + src/game/shared/IBugfixedServer.h | 20 +- src/game/shared/IScoreboardExt.h | 73 ++ src/game/shared/ScoreboardProtocol.h | 90 ++ 43 files changed, 6760 insertions(+), 66 deletions(-) create mode 100644 docs/scoreboard-protocol.md create mode 100644 gamedir/ui/resource/ScorePanel_gungame.res create mode 100644 src/game/client/hud/gungame_hud.cpp create mode 100644 src/game/client/hud/gungame_hud.h create mode 100644 src/game/client/scoreboard_data.cpp create mode 100644 src/game/client/scoreboard_data.h create mode 100644 src/game/client/vgui/score_panel_cells.cpp create mode 100644 src/game/client/vgui/score_panel_cells.h create mode 100644 src/game/server/CScoreboardExt.cpp create mode 100644 src/game/server/CScoreboardExt.h create mode 100644 src/game/shared/IScoreboardExt.h create mode 100644 src/game/shared/ScoreboardProtocol.h diff --git a/docs/scoreboard-protocol.md b/docs/scoreboard-protocol.md new file mode 100644 index 00000000..7199db21 --- /dev/null +++ b/docs/scoreboard-protocol.md @@ -0,0 +1,1013 @@ +# Scoreboard extension protocol + +Protocol version 1. Implemented in the BugfixedHL client and server, in `bugfixedapi_amxx` and in the +GunGame plugin. + +This document describes how a BugfixedHL server sends a custom scoreboard layout and extra values +for players, teams and the whole game to BugfixedHL clients, and how the GunGame scoreboard and +HUD widget use that data. The first consumer is the GunGame plugin. + +## 1. Goals + +- A server plugin can add columns to the scoreboard, hide some standard columns, move the others + and fill cells for players, teams and the whole game. +- HUD widgets read the same data. The first one is the GunGame HUD (8.4). +- Full backward compatibility in both directions: + - old clients (older BugfixedHL, Valve, AG, OpenAG) on a new server see the standard scoreboard + and HUD and never receive the new message; + - new clients on an old server (older BugfixedHL, AG, Valve) see the standard scoreboard and HUD. +- The protocol can grow without breaking clients that only know version 1. + +Out of scope: demo playback, HLTV, AG and Valve server DLLs. + +The data model is the Source engine `player_resource` idea, but it is not a networked entity. +`entity_state_t` has a fixed set of numeric fields and no strings, an entity reaches a client only +when it has a model and is in the client's PVS, and it can't be addressed to one client. +User messages carry strings, are reliable and can be sent to a single client. + +## 2. Overview + +``` +plugin (AMXX) ── natives ──▶ bugfixedapi_amxx ── IBugfixedServer ──▶ hl.so: scoreboard state + │ + "BhlScore" user message, MSG_ONE, + only to clients with ScoreboardV1 + ▼ + client.dll: scoreboard store ──▶ ScorePanel, hud_scores, + GunGame HUD widget +``` + +| Term | Meaning | +|--------|----------------------------------------------------------------| +| Schema | `Config` plus the list of columns | +| Target | Owner of a value: the whole game, a player or a team | +| Cell | One value, addressed by target and column | +| List | A named array of values that belongs to the whole game | +| Preset | Client-side look and behaviour bound to a name, e.g. `gungame` | +| Caps | Bitmask of client features, reported by the client in `_bhl` | + +## 3. Client capabilities + +### 3.1 Format + +The client reports its features in the cvar and userinfo key `_bhl`. The value is a bitmask +written as lowercase hex without a prefix, at most 8 digits: `1`, `3`, `1f`. + +The server parses it with `strtoul(value, &end, 16)`. An empty value, trailing characters or more +than 8 digits mean `0`. Unknown bits are ignored. + +| Bit | Mask | Name | Meaning | +|------|-------|----------------|----------------------------------------------------------| +| 0 | `0x1` | `ScoreboardV1` | Understands `BhlScore` protocol version 1 | +| 1 | `0x2` | `GunGameHudV1` | Draws the GunGame HUD widget; the plugin drops its texts | +| 2–31 | — | reserved | Clients send 0, servers ignore | + +`GunGameHudV1` is only set together with `ScoreboardV1`, because the widget reads the store. + +Bits are never reused or redefined. An incompatible protocol change gets a new bit +(`ScoreboardV2`), and the server sends the new format only to clients that have that bit. + +`_bhl` doesn't replace `aghl_supports`. The MOTD flags stay where they are. + +### 3.2 Client side + +- `ConVar _bhl` has only `FCVAR_USERINFO`. + - No `FCVAR_ARCHIVE` or `FCVAR_BHL_ARCHIVE`: the value is computed, it must not be saved to configs. + - No `FCVAR_PRIVILEGED`: the engine answers a cvar query for such cvars with `CVAR is privileged`, + which would break the server fallback from 3.3. +- The cvar is registered with the caps of the build as its default value, so the key is in + userinfo from the first connect. +- One owner function, `CHud::UpdateCapsUserinfo()`, computes the caps from the build + features and client settings and writes `_bhl`. It runs: + - on the first frame after configs have been executed (`m_NextFrameQueue`); + - when a related client setting changes; + - on every `VidInit`. + + A value typed by the user is overwritten by the next call. +- One frame after a write the client compares `gEngfuncs.LocalPlayerInfo_ValueForKey("_bhl")` with + the expected value: + - on mismatch it runs `setinfo _bhl `; + - if the key is still wrong on the next check, it prints one console message (most likely the + userinfo is full). The server can still detect the client with the cvar query from 3.3. +- Client settings: + - `hud_scoreboard_custom 0` clears `ScoreboardV1` and `GunGameHudV1`. The server stops sending + data, the client shows the standard scoreboard. Setting it back to 1 brings a full sync. + - `hud_gungame 0` clears `GunGameHudV1`. The plugin shows its own HUD texts again. + +### 3.3 Server side + +For every client the server keeps `caps` and the source they came from: + +| Source | Set when | +|------------|---------------------------------------------------------------| +| `Unknown` | On connect, before anything is known | +| `Userinfo` | `_bhl` is present in userinfo | +| `Query` | The cvar query answered; errors give `caps = 0` | +| `None` | No key, and a query is impossible: bot, HLTV, p47, LAN client | + +1. `ClientConnect` and `ClientUserInfoChanged` read `_bhl` from userinfo. If the key is present, + it is parsed and the source becomes `Userinfo`. Userinfo always wins: a query answer that + arrives later doesn't overwrite it. If the key disappears from userinfo, the source goes back + to `Unknown`. +2. In `InitHUD`, if the source is `Unknown` and either a schema is active or `sv_bhl_query_vars` + is 1, the server calls `QueryClientCvarValue2(_bhl)` with a new `REQUESTID_CAPS`. It applies the + same p47 and LAN checks as the existing `aghl_*` queries. If a schema becomes active later on the + map, clients that are still `Unknown` are queried at that moment. +3. An answer that doesn't parse (`Bad CVAR request`, `CVAR is privileged`, empty) means `0`. +4. Every change of `caps` fires the plugin forward `bhl_client_caps_changed(id)`. + - `ScoreboardV1` appeared after `InitHUD`: the client gets a full sync (5.3). + - `ScoreboardV1` disappeared: the server stops sending to that client and doesn't send `Reset`. + +Each layer covers a different case: + +| Layer | Covers | +|-------------|---------------------------------------------------------------------| +| Cvar mirror | The normal case: no extra traffic, known before `InitHUD` | +| `setinfo` | The cvar was not mirrored into userinfo for any reason | +| Cvar query | Userinfo is full (256 bytes), so neither path above can add the key | + +The server command `bhl_caps` prints slot, name, caps and source for every connected client. + +## 4. Message `BhlScore` + +### 4.1 Transport + +- The server registers `REG_USER_MSG("BhlScore", -1)`: variable size, payload up to 192 bytes. +- The message is sent only with `MSG_ONE` (reliable) and only to clients that have + `ScoreboardV1` and passed `InitHUD`. It is never sent with `MSG_ALL`, `MSG_BROADCAST` or + `MSG_ONE_UNRELIABLE`, and never to bots or HLTV proxies. + - Old clients never receive it, so it doesn't matter how their engine handles unknown messages. + - An old server never registers it, so the client hook never fires. +- One message carries one operation. The first byte is the opcode, the rest is its payload. + The client ignores messages with unknown opcodes, which lets new opcodes be added safely. +- `Reset`, `Config` and `Column` are read field by field, and trailing bytes after the known fields + are ignored. Later versions may append fields to them. `Values` and `List` have no room for + trailing fields and are extended through new value types. + +### 4.2 Data types + +All integers are little-endian, as written by `WRITE_*` and read by `READ_*`. + +| Type | Bytes | Write / read | Range | +|----------|-------|--------------------------------|-----------------------| +| `byte` | 1 | `WRITE_BYTE` / `READ_BYTE` | 0 … 255 | +| `char` | 1 | `WRITE_CHAR` / `READ_CHAR` | −128 … 127 | +| `short` | 2 | `WRITE_SHORT` / `READ_SHORT` | −32768 … 32767 | +| `word` | 2 | `WRITE_SHORT` / `READ_WORD` | 0 … 65535 | +| `long` | 4 | `WRITE_LONG` / `READ_LONG` | −2³¹ … 2³¹−1 | +| `string` | n + 1 | `WRITE_STRING` / `READ_STRING` | UTF-8, NUL-terminated | + +Strings: + +- A string starting with `#` is a localization token resolved by VGUI2 on the client. If the token + is missing, the client shows the string without the leading `#`. +- Plugins can only use tokens shipped with the client in `ui/resource/language/bugfixedhl_*.txt`. + The client adds generic tokens for common columns, see section 10. +- Color codes (`^1` … `^9`) are not interpreted in version 1. The client strips them. +- The server truncates strings to the limits from 4.6. The client truncates them again + if they are still too long. + +### 4.3 Opcodes + +| Op | Name | Payload | +|--------|----------|---------------------------------------------| +| `0x00` | `Reset` | Protocol version | +| `0x01` | `Config` | Hidden standard columns, preset, title, tag | +| `0x02` | `Column` | One column definition | +| `0x03` | `Values` | Cells for one or more targets | +| `0x04` | `List` | Items of one list | +| other | reserved | Ignored by the client | + +#### `Reset` (`0x00`) + +| Field | Type | Notes | +|-----------|--------|-----------------------| +| `version` | `byte` | Protocol version, `1` | + +The client drops the schema, all cells and all lists and returns to the standard scoreboard. +`version` is informational: the client reads the fields it knows. A version 1 client accepts any +`version ≥ 1` and ignores a `Reset` with `version 0`. + +#### `Config` (`0x01`) + +| Field | Type | Notes | +|----------|----------|------------------------------------------------------| +| `flags` | `word` | See below | +| `preset` | `string` | Up to 15 bytes; `""` means the generic look | +| `title` | `string` | Up to 63 bytes; replaces the server name if not `""` | +| `tag` | `string` | Up to 15 bytes; a badge next to the title: `FFA` | + +| Bit | Name | Meaning | +|------|---------------|-------------------------| +| 0 | `HideFrags` | Hide the Frags column | +| 1 | `HideDeaths` | Hide the Deaths column | +| 2 | `HideEff` | Hide the Eff column | +| 3 | `HideSteamID` | Hide the SteamID column | +| 4–15 | reserved | Sent as 0, ignored | + +The server can't hide Avatar, Name and Ping. Avatars follow the player's +`hud_scoreboard_showavatars`. + +The first `Config` after a `Reset` (or after `VidInit`) turns the custom scoreboard on. +A repeated `Config` replaces the previous one. + +`preset` selects client-side look and behaviour, see 6.7. An unknown preset falls back to the +generic look. + +#### `Column` (`0x02`) + +| Field | Type | Notes | +|-----------|----------|----------------------------------------------------------------------------------| +| `id` | `byte` | 0–15 | +| `display` | `byte` | How cells are drawn, see below | +| `flags` | `word` | See below | +| `width` | `byte` | Proportional units as in `ScorePanel.res`; `0` is the default | +| `sort` | `byte` | `0`: not a sort key; bits 0–6: priority, 1 first; bit 7: ascending | +| `key` | `string` | Up to 15 bytes of `[a-z0-9_]`, unique: `level`, `weapon` | +| `title` | `string` | Up to 31 bytes, text or `#token`; `""` for a built-in column keeps its own title | + +A `Column` with an existing `id` replaces that column's definition; its cells are kept. +Columns are shown in ascending `id` order. The server assigns ids, plugins address columns +by `key`. Presets and HUD widgets use `key` to find data by meaning without depending on ids. + +Display kinds: + +| Value | Name | Draws | +|-------|-----------|----------------------------------------------------------------------------------| +| 0 | `Text` | Any cell as text | +| 1 | `Icon` | `Icon` cells as sprite and text; other cells as text | +| 2 | `Meter` | `Progress` cells as dots or a bar with a `cur/max` counter (6.6); others as text | +| 3 | `Builtin` | A standard column, chosen by `key`; cells are ignored | +| 4 | `Steps` | `Progress` cells as `cur/max` with a strip of `max` steps below (6.6) | +| other | — | Same as `Text` | + +Default widths for `width = 0`: `Text` 60, `Icon` 100, `Meter` 90, `Steps` 60. A `Builtin` column +keeps the width of its standard column. + +Built-in columns: + +| `key` | Column | Notes | +|-----------|---------|---------------------------------------------------------| +| `rank` | `#` | Place, computed by the client (6.4); always drawn first | +| `frags` | Frags | | +| `deaths` | Deaths | | +| `eff` | Eff | Also follows `hud_scoreboard_showeff` | +| `steamid` | SteamID | Also follows `hud_scoreboard_showsteamid` | +| `ping` | Ping | | +| other | — | The column is ignored | + +A `Builtin` column moves a standard column to its own position. Standard columns that the schema +doesn't mention keep their default places. `Hide*` flags win over a `Builtin` column. + +Column flags: + +| Bits | Name | Meaning | +|------|-----------|-------------------------------------------------------------| +| 0 | `Hidden` | Data only: not drawn, still used for sorting and by widgets | +| 1–2 | `Align` | 0 left, 1 center, 2 right; 3 is treated as left | +| 3 | `Primary` | The main score: `hud_scores` shows it instead of frags | +| 4–15 | reserved | Sent as 0, ignored | + +A `Hidden` column can carry values for the whole game only, for example the GunGame phase. + +#### `Values` (`0x03`) + +The payload is a sequence of groups that runs to the end of the message: + +``` +Values := op:byte(0x03) Group+ +Group := target:byte count:byte Cell{count} +Cell := column:byte Value +Value := type:byte len:byte payload:byte{len} +``` + +Targets: + +| Value | Target | +|---------------|------------------------------------------------------| +| `0x00` | The whole game | +| `0x01`–`0x40` | Player 1–64 | +| `0x81`–`0xC0` | Team 1–64, numbered like `teamnumber` in `ScoreInfo` | +| other | Reserved: the client skips the group | + +Cell fields: + +- `column` is the column id. `0xFF` together with type `None` clears all cells of the target. +- `type` is the value type, see below. +- `len` is the payload length. The client always moves on by `len` bytes, so it can skip + types it doesn't know. + +Value types: + +| Value | Name | `len` | Payload | +|-------|------------|---------|--------------------------------------------------------| +| 0 | `None` | 0 | Nothing: clears the cell | +| 1 | `Int` | 1, 2, 4 | Signed integer, `len` bytes | +| 2 | `Text` | 1–32 | `string` | +| 3 | `Icon` | 2–64 | `string sprite`, `string text` | +| 4 | `Progress` | 2 or 4 | `cur`, `max`: two `byte` for `len` 2, two `word` for 4 | +| other | — | any | Unknown type: the cell is cleared | + +- A known type with a wrong `len` or a broken payload clears the cell. +- If the message ends in the middle of a group or a cell, the client keeps the cells it has + already applied and drops the rest. +- Cells of columns that don't exist yet are stored and shown when the column arrives. +- `Icon.sprite` is a sprite name from `hud.txt`, the same names the kill feed uses (`d_9mmAR`). + If the client doesn't have the sprite, it draws only `text`. +- `Progress` with `max = 0` is drawn as `cur`. + +Sort keys: `Int` uses the value, `Progress` uses `cur`, `Text` and `Icon` compare text +case-insensitively. Empty cells go after filled ones. + +#### `List` (`0x04`) + +A list is a named array of values that belongs to the whole game, for example the weapons of all +GunGame levels. + +``` +List := op:byte(0x04) id:byte total:byte start:byte key:string Value* +``` + +| Field | Type | Notes | +|---------|----------|----------------------------------------------------------| +| `id` | `byte` | 0–7, assigned by the server | +| `total` | `byte` | Number of items, 0–64; the client resizes the list to it | +| `start` | `byte` | Index of the first item in this message | +| `key` | `string` | Up to 15 bytes of `[a-z0-9_]`, unique: `levels` | +| items | `Value*` | Items `start`, `start + 1`, … up to the end of message | + +- A long list is split into several messages with different `start`. +- Items at `total` or beyond are dropped. An item of an unknown type is stored as empty. +- `total = 0` removes the list. +- Items added by a resize are always sent, as `None` if they were not set. + +### 4.4 Example: one GunGame row + +Player 5 is on level 12 of 24 with the MP5 and has 1 of 3 kills. Column ids: `level` 1, +`weapon` 2, `progress` 3. + +``` +03 op Values +05 03 target: player 5, 3 cells +01 04 02 0c 18 level: Progress, len 2, cur 12, max 24 +02 03 0c 64 5f 39 6d 6d 41 52 00 weapon: Icon, len 12, sprite "d_9mmAR" + 4d 50 35 00 text "MP5" +03 04 02 01 03 progress: Progress, len 2, cur 1, max 3 +``` + +The group takes 27 bytes. With the `kills` and hidden `score` cells (8–10 more bytes) a player +takes 35–37 bytes, so one message holds 5 players and a full sync of 32 players needs 7 `Values` +messages. + +### 4.5 Sizes for GunGame + +| Message | Bytes | +|----------------------------|-----------| +| `Reset` | 2 | +| `Config` | ~25 | +| `Column` × 9 | ~15–30 | +| `List` `levels`, 24 levels | 2 × ≤ 192 | +| `Values`, 32 players | 7 × ≤ 192 | +| Level-up of one player | ~33 | +| Kill without level-up | ~18 | +| Warmup second | ~8 | + +### 4.6 Limits + +| What | Limit | +|------------------------|---------------| +| Message payload | 192 bytes | +| Columns | 16 (ids 0–15) | +| Lists | 8 (ids 0–7) | +| List items | 64 | +| Column and list `key` | 15 bytes | +| Column title | 31 bytes | +| Preset name | 15 bytes | +| Config title | 63 bytes | +| Config tag | 15 bytes | +| `Text` value | 31 bytes | +| `Icon` sprite and text | 31 bytes each | +| Dots | `max ≤ 10` | + +String limits are in bytes, without the terminating NUL. + +## 5. Server behaviour + +### 5.1 State + +One object in `hl.so`, `CScoreboardExt`, holds the config, the columns, the lists and +the cells of the whole game, every player and every team. For each client it also keeps `caps`, +their source, a `ready` flag (set after `InitHUD`), pending `Reset` and header flags and sets of +dirty cells and list items. + +### 5.2 Sending + +Plugins only change the state and mark the changed cells and list items dirty for every ready +client. In `StartFrame` the server walks the ready clients that have `ScoreboardV1` and sends: + +1. `Reset`, if one is pending; +2. `Config` and every `Column`, if the header is pending; +3. the dirty list items packed into `List` messages; +4. the dirty cells packed into `Values` messages. + +A client gets at most about 512 bytes per frame. When its budget is used up, nothing more is sent +to it for about 0.1 s. A client with nothing pending gets small updates every frame. Several +changes of one cell in one frame produce one value. + +### 5.3 Full sync + +A full sync is `Reset`, the header, every list item and every non-empty cell marked dirty for +that client. It starts: + +- about 0.5 s after `InitHUD` of a client with `ScoreboardV1` (without a schema only `Reset` is + sent); +- when `ScoreboardV1` appears after `InitHUD`; +- for every ready client, when a plugin turns a schema on in the middle of a map (a client that + is still in its 0.5 s wait after `InitHUD` keeps it). + +`InitHUD` already sends `ScoreInfo` and `TeamInfo` for every player and the MOTD. The engine +moves a client's reliable buffer (about 4 KB on HLDS) out only after the previous reliable message +is acknowledged, so the sync is paced by time, not by frames, to avoid `Reliable channel +overflowed`: it starts after the `InitHUD` burst and drains at about 5 KB/s. With 32 players a +GunGame sync takes about 0.6 s. + +### 5.4 Events + +| Event | Server | +|----------------------|----------------------------------------------------------------| +| Map change | State is cleared; the plugin sets the schema again | +| Plugin resets schema | `Reset` to every ready client; the schema is off | +| Player disconnects | Slot cells are cleared; `0xFF`/`None` for the slot to everyone | +| Player changes team | Nothing: placement comes from `TeamInfo` and `ScoreInfo` | +| Client loses the cap | Nothing more is sent to that client | + +## 6. Client behaviour: scoreboard + +### 6.1 Store + +The store, `CScoreboardData`, is cleared on `VidInit` and on `Reset`. A player's cells +are cleared when the slot becomes empty, even if the server didn't say so. + +### 6.2 Activation + +The custom scoreboard is shown when a `Config` arrived after the last `Reset` or `VidInit` and +`hud_scoreboard_custom` allows it. Otherwise the standard scoreboard is shown; incoming data is +still stored. + +### 6.3 Layout + +- Column order: `rank`, Avatar, Name, then SteamID, Eff, Frags and Deaths at their default places + unless the schema moves them, then custom and `Builtin` columns by `id`, then Ping unless moved. + Hidden standard columns and `Hidden` custom columns are left out. +- Name takes all free width. If the other columns need more, Name shrinks down to 100 units + (`column_name_min`), then down to 80 units; columns that still don't fit are dropped from the + end. +- A preset may bring its own layout file `ScorePanel_.res`. Without it, `ScorePanel.res` + is used. +- While a `Steps` column is visible, rows are taller so the strip fits under the text. +- Team section headers show team cells as text in the same columns (`ModifyColumn`; the list + control can't draw images in headers): `Icon` as its name, `Progress` as `cur/max`. Team frags + and deaths follow the `Hide*` flags. + +### 6.4 Sorting and places + +- Players inside a section and the teams are sorted by the sort keys in priority order. Ties fall + back to the standard order (frags descending, deaths ascending), then to the index. Teams are + sorted by team cells; a team without cells keeps the standard order. +- The place in the `rank` column depends only on the first sort key: equal values share a place + (`1, 1, 3`). Further keys only order the rows. Without sort keys the place follows row order. +- With team sections the place is shown in the team header and counted among teams; player rows + leave `rank` empty. Without teams the place is shown in player rows. + +### 6.5 `hud_scores` + +With an active schema and a `Primary` column, `hud_scores` shows that column as text instead of +frags and sorts the same way as the scoreboard. Without a `Primary` column it doesn't change. + +### 6.6 Drawing + +- `Icon`: the sprite from `hud.txt`, scaled to the row height with its aspect ratio kept and drawn + additively like the kill feed, tinted with the row text color. The text follows to the right. +- `Meter`, the same element as in the GunGame HUD (8.4.3): + - `max ≤ 10`: `cur` filled dots and `max − cur` empty ones, drawn from a procedural circle texture; + - `max > 10`: a rounded bar of the same length as 10 dots, filled to `cur / max`; + - the `cur/max` counter stands to the right. In the scoreboard it is always shown, in the HUD + only next to the bar. +- `Steps`: `cur/max` as text; below it a strip of `max` segments. Segments before `cur` are + filled, segment `cur` is highlighted, the rest are dimmed, the last one is marked. +- `Progress` in a `Text` column: `cur/max`. + +### 6.7 Presets + +| Preset | Behaviour | +|-----------|--------------------------------------------------| +| `""` | Generic: only what the schema describes | +| `gungame` | The GunGame scoreboard and HUD widget, section 8 | + +### 6.8 Debug commands + +- `hud_scoreboard_test [preset]` fills the store with fake data for the current players without + a server. +- `hud_scoreboard_dump` prints the store to the console. + +## 7. Client behaviour: standard scoreboard + +Without an active schema the scoreboard is the same as now. The place column appears only when a +schema adds the built-in `rank` column. The own-row highlight and the ping highlight from section 8 +exist only in the `gungame` preset. + +## 8. GunGame preset + +The preset follows two mockups made for 1920×1080: "TAB" for the scoreboard and "Main" for the +game screen. Interface strings are localized (section 10); the mockups use Russian. + +### 8.1 Data + +The plugin fills these keys: + +| Key | Kind | Target | Type | Meaning | +|--------------|---------|----------------|------------|-------------------------------------------------| +| `rank` | builtin | — | — | Place, computed by the client | +| `level` | column | player, team | `Progress` | Current level, 1-based / number of levels | +| `weapon` | column | player, team | `Icon` | Weapon of the current level | +| `progress` | column | player, team | `Progress` | Kills on the current level / kills it needs | +| `kills` | column | player, team | `Int` | Kills in the match | +| `deaths` | builtin | — | — | Standard deaths, moved after `kills` | +| `score` | column | player, team | `Int` | Progress P, hidden, first sort key | +| `phase` | column | the whole game | `Int` | 0 game, 1 warmup, 2 start countdown, 3 finished | +| `phase_left` | column | the whole game | `Int` | Seconds left in the warmup or the countdown | +| `levels` | list | the whole game | `Icon` | Weapon of every level, in order | + +- P is the sum of kills needed on all passed levels plus kills on the current level. The plugin + computes it, because kills per level differ (1–7 in the shipped configs) and teamplay multiplies + them by `gg_teamplay_multigoal`. Ordering by P gives the same order as the plugin's + `Sort_RankPos` (level, then kills). +- `kills` counts kills of other players. Suicides and team kills don't count. The counter is reset + together with the scores after the warmup. +- A player is on the last level when `level.cur = level.max`. +- Weapon names come from the client table (10.3) for standard HL sprites. `Icon.text` from the + server is used only for other sprites. + +### 8.2 Places + +The scoreboard and the HUD use the same rules. + +- Participants are players that are not spectators. Bots count. +- Places follow P: equal P share a place (`1, 1, 3`). +- In teamplay places are counted among teams that have participants. Team names come from + `TeamNames`, team P from the team `score` cell. +- Overtake: the neighbour is the nearest participant with a strictly greater P; + N = P(neighbour) − P(player) + 1, at least 1. +- Lead: D = P(player) − P(next participant). + +### 8.3 Scoreboard (TAB) + +#### 8.3.1 Placement + +- Layout file `ScorePanel_gungame.res`. +- Centered horizontally, about 70% of the screen width, but not narrower than the columns plus + the Name minimum; on 4:3 screens it is wider. The top edge is about 10% of the screen height down. +- One row per player; the table grows down. When rows don't fit, the existing compact spacing + is used, then scrolling. +- No server name, timer or hint line. + +#### 8.3.2 Header + +Left: + +- the title and the tag badge from `Config`: `GUNGAME` and `FFA`; +- below them, one line with the map and the player count: `crossfire · 12 / 16 игроков` + (connected / max players). There are no icon files yet, so the line has no icons. + +Right, the banner `ЛИДЕР НА ПОСЛЕДНЕМ УРОВНЕ`: + +- shown while the player or team on the first place is on the last level; +- an accent bar instead of the crown icon, the banner title and the line + `Kr1sTaL · Crowbar · 1 убийство до победы`: + the leader's name, the weapon and `progress.max − progress.cur` kills left; +- in teamplay the line names the team; +- if several leaders share the first place, the first row in sort order is shown. + +#### 8.3.3 Columns + +`#` · Avatar · `ИГРОК` · `УРОВЕНЬ` · `ОРУЖИЕ` · `ПРОГРЕСС` · `УБИЙСТВА` · `СМЕРТИ` · `ПИНГ` + +- Headers are drawn in uppercase. +- The player column takes all free width; the others have fixed widths. +- Numbers in the last three columns are aligned right. +- Avatars follow `hud_scoreboard_showavatars`. SteamID and Eff are hidden. + +| Column | Shows | +|------------|-----------------------------------------------------------------------------------------| +| `#` | Place. The first three places are marked, the first stronger than the others. | +| `ИГРОК` | Name without color codes, cut with `…`. The own row has the `ТЫ` badge after the name. | +| `УРОВЕНЬ` | `9/14` with the strip of all levels below (`Steps`); the last level is marked. | +| `ОРУЖИЕ` | Weapon icon and name. On the last level the `ФИНАЛ` badge follows the name. | +| `ПРОГРЕСС` | Dots (filled for done, empty for left) and `1/2` (`Meter`). Dots = kills on this level. | +| `УБИЙСТВА` | `kills` | +| `СМЕРТИ` | Standard deaths | +| `ПИНГ` | Ping without loss (`hud_scoreboard_showloss` is ignored); 100 and above is highlighted | + +#### 8.3.4 Highlighted rows + +- Own row: the whole row is highlighted, the name is emphasized, `ТЫ` follows it. +- A player on the last level: the row is highlighted, the level number and the weapon icon are + emphasized, `ФИНАЛ` follows the weapon. If this player is the leader, the first-place mark + shows the final too. + +#### 8.3.5 Teamplay + +- Sections per team, as in the current BugfixedHL scoreboard; sections are ordered by team P. +- A team header shows the team place, level, weapon, progress, kills and deaths. +- Players inside a team are sorted by `kills` (the second sort key). +- Spectators stay in their own section at the bottom. + +### 8.4 HUD widget + +Health, armor, ammo, the kill feed and the crosshair stay the classic HL elements. The widget adds +two elements: the place block at the top center and the level bar at the bottom center. + +#### 8.4.1 Visibility + +- The widget is on when the `gungame` preset is active and both `hud_scoreboard_custom` and + `hud_gungame` are 1. +- It follows the usual HUD rules: hidden with `hud_draw 0` and during intermission. It is also + hidden while the scoreboard is open, because the GunGame table starts near the top. +- A spectator in first-person mode sees the data of the observed player. In other spectator + modes the widget is hidden. +- With `phase = 3` (finished) the widget is hidden; the plugin's winner message and final table + are shown as before. +- While the widget is on, `CHudTimer` draws nothing, including the next map line and server + timers. This includes the finished phase. `customtimer` still rings when it expires. +- While the level bar is on (also while the open scoreboard hides it), the speedometer and + `hud_jumpspeed` in their bottom mode and the status bar move above it. + +#### 8.4.2 Place block + +Three lines at the top center: + +1. Place: `МЕСТО 4 / 8`. +2. Overtake or lead (8.2): + + | Situation | Text | + |-------------------------------|---------------------------------| + | Not first | `До обгона Freeman: 3 убийства` | + | First, ahead of second | `Отрыв: 2 убийства` | + | First, tied with the next one | `Вровень` | + | No opponents | `Ожидание соперников` | + +3. Kills on the current level (8.4.3), with a visible gap above it. + +- Tied leaders both see `МЕСТО 1 / 8` and `Вровень`. +- A long name is cut to 20 characters plus `…`. Characters are counted in UTF-8 code points after + color codes are stripped. +- `убийство` follows the plural rules of the client language (10.2). + +Warmup: + +| `phase` | Line 1 | Lines 2 and 3, level bar | +|---------|--------------------------------|--------------------------| +| 1 | `РАЗМИНКА 0:15` (`phase_left`) | Hidden | +| 2 | `СТАРТ ЧЕРЕЗ 3` (`phase_left`) | Hidden | + +The plugin updates `phase_left` every second, as its warmup timer already does. + +#### 8.4.3 Kills on the current level + +- Up to 10 kills needed: one dot per kill, filled for done, empty for left. +- More than 10: a rounded bar, as if the dots merged. The filled part shows the share of done + kills, the `16 / 25` counter stands to the right. +- The bar has the same length as a row of 10 dots and is centered too, so the block doesn't jump + when the form changes. The form is chosen per level. + +#### 8.4.4 Level bar + +- One cell per item of `levels`, left to right in level order, each with the weapon icon. +- Passed levels are filled, the current one is highlighted, the rest are dimmed. No captions. +- The bar stands on the line of the health and ammo numbers. +- If the cells don't fit, they shrink down to a minimum size. If they still don't fit, the bar + shows a window around the current level and marks the hidden ends with `‹` and `›`. + +#### 8.4.5 Look + +- One color for everything, `hud_color` (default `255 160 0`, `#FFA000`), icons included. +- Text uses VGUI2 scheme fonts (new entries in `ClientScheme`), so Cyrillic and scaling work and + the fonts can be changed in `.res` files. +- Positions and sizes live in `HudLayoutBase.res` and can be overridden in `HudLayout.res`. + +## 9. Plugin API + +### 9.1 Server interface + +`IBugfixedServer` gets minor version 2. `SetPlayerScore` is documented as added in 1.1, but +`IBUGFIXEDSERVER_MINOR` is still 0, so this change sets it to 2. New methods are appended: + +- `GetClientCaps(int idx)` returns the caps of a client; +- `GetScoreboard()` returns `bhl::IScoreboardExt *`, a separate interface whose methods take + column and list keys, never ids. New methods are appended to it the same way. + +`bugfixedapi_amxx` checks the interface version per feature instead of refusing the whole API. +On a server older than 1.2 the existing natives keep working, `bhl_sb_available()` returns false, +`bhl_get_client_caps()` returns 0 and the other `bhl_sb_*` natives log one error and do nothing. + +### 9.2 Natives + +```pawn +enum BhlClientCaps +{ + BHL_CAPS_NONE = 0, + BHL_CAPS_SCOREBOARD_V1 = (1 << 0), + BHL_CAPS_GUNGAME_HUD_V1 = (1 << 1) +}; + +enum BhlSbDisplay +{ + BHL_SB_TEXT = 0, + BHL_SB_ICON = 1, + BHL_SB_METER = 2, + BHL_SB_BUILTIN = 3, + BHL_SB_STEPS = 4 +}; + +enum BhlSbHide +{ + BHL_SB_HIDE_NONE = 0, + BHL_SB_HIDE_FRAGS = (1 << 0), + BHL_SB_HIDE_DEATHS = (1 << 1), + BHL_SB_HIDE_EFF = (1 << 2), + BHL_SB_HIDE_STEAMID = (1 << 3) +}; + +enum BhlSbColumnFlags +{ + BHL_SB_COL_NONE = 0, + BHL_SB_COL_HIDDEN = (1 << 0), + BHL_SB_COL_CENTER = (1 << 1), + BHL_SB_COL_RIGHT = (2 << 1), + BHL_SB_COL_PRIMARY = (1 << 3) +}; + +const BHL_SB_SORT_ASC = 0x80; + +const BhlSbTarget:BHL_SB_GLOBAL = BhlSbTarget:0; +const BhlSbTarget:BHL_SB_INVALID = BhlSbTarget:-1; + +stock BhlSbTarget:bhl_sb_player(idx) +{ + return BhlSbTarget:idx; +} + +native BhlSbTarget:bhl_sb_team(const teamName[]); + +native BhlClientCaps:bhl_get_client_caps(idx); +forward bhl_client_caps_changed(idx); + +native bool:bhl_sb_available(); +native bhl_sb_reset(); +native bhl_sb_config(BhlSbHide:hide, const preset[] = "", const title[] = "", const tag[] = ""); +native bool:bhl_sb_add_column(const key[], const title[], BhlSbDisplay:display = BHL_SB_TEXT, + width = 0, sort = 0, BhlSbColumnFlags:flags = BHL_SB_COL_NONE); + +native bhl_sb_set_int(BhlSbTarget:target, const key[], value); +native bhl_sb_set_text(BhlSbTarget:target, const key[], const text[]); +native bhl_sb_set_icon(BhlSbTarget:target, const key[], const sprite[], const text[]); +native bhl_sb_set_progress(BhlSbTarget:target, const key[], cur, max); +native bhl_sb_clear(BhlSbTarget:target, const key[] = ""); + +native bool:bhl_sb_list_resize(const key[], count); +native bhl_sb_list_set_int(const key[], index, value); +native bhl_sb_list_set_text(const key[], index, const text[]); +native bhl_sb_list_set_icon(const key[], index, const sprite[], const text[]); +``` + +- Teams are addressed by name, the same name `get_user_team()` returns. `bhl_sb_team()` returns + an opaque handle that stays valid until the map changes, or `BHL_SB_INVALID` for an unknown team. +- Values for players that are not connected are ignored. +- `sort` is a priority starting at 1; add `BHL_SB_SORT_ASC` for ascending order. +- A `BHL_SB_BUILTIN` column takes one of the keys from 4.3: `rank`, `frags`, `deaths`, `eff`, + `steamid`, `ping`. +- `bhl_sb_list_resize()` creates the list on first use. Setting an item out of range is ignored. +- Setting a cell or an item to the value it already has sends nothing. + +### 9.3 GunGame + +The plugin keeps working without the module: `set_module_filter` and `set_native_filter` in +`plugin_natives` let it load, and every call is guarded by a flag. The `level * 100` frags hack +stays for old clients. A new per-player counter keeps the kills in the match for the `kills` +column. + +```pawn +Scoreboard_Setup() +{ + if (!g_bhlApi || !bhl_sb_available()) + return + + new bool:isTeamPlay = get_pcvar_num(cvar[CVAR_TEAMPLAY]) == 1 + + bhl_sb_reset() + bhl_sb_config(BHL_SB_HIDE_FRAGS | BHL_SB_HIDE_EFF | BHL_SB_HIDE_STEAMID, "gungame", "GUNGAME", + isTeamPlay ? "TEAM" : "FFA") + bhl_sb_add_column("rank", "", BHL_SB_BUILTIN) + bhl_sb_add_column("level", "#BHL_SB_Level", BHL_SB_STEPS, 60, 0, BHL_SB_COL_PRIMARY) + bhl_sb_add_column("weapon", "#BHL_SB_Weapon", BHL_SB_ICON, 120) + bhl_sb_add_column("progress", "#BHL_SB_Progress", BHL_SB_METER, 90) + bhl_sb_add_column("kills", "#BHL_SB_Kills", BHL_SB_TEXT, 60, 2, BHL_SB_COL_RIGHT) + bhl_sb_add_column("deaths", "", BHL_SB_BUILTIN, 0, 0, BHL_SB_COL_RIGHT) + bhl_sb_add_column("score", "", BHL_SB_TEXT, 0, 1, BHL_SB_COL_HIDDEN) + bhl_sb_add_column("phase", "", BHL_SB_TEXT, 0, 0, BHL_SB_COL_HIDDEN) + bhl_sb_add_column("phase_left", "", BHL_SB_TEXT, 0, 0, BHL_SB_COL_HIDDEN) + + bhl_sb_list_resize("levels", g_levelsCount) + + for (new i; i < g_levelsCount; i++) + bhl_sb_list_set_icon("levels", i, g_levelIcon[i], g_levelWeaponName[i]) +} + +Scoreboard_UpdatePlayer(id) +{ + if (!g_bhlApi) + return + + new level = playersData[id][PLAYER_CURRENTLEVEL] + new BhlSbTarget:target = bhl_sb_player(id) + + bhl_sb_set_progress(target, "level", level + 1, g_levelsCount) + bhl_sb_set_icon(target, "weapon", g_levelIcon[level], g_levelWeaponName[level]) + bhl_sb_set_progress(target, "progress", playersData[id][PLAYER_KILLS], playersData[id][PLAYER_NEEDKILLS]) + bhl_sb_set_int(target, "kills", playersData[id][PLAYER_TOTALKILLS]) + bhl_sb_set_int(target, "score", Player_GetScore(id)) +} +``` + +Names of plugin variables and helpers in the example are illustrative. + +| Plugin function | Scoreboard call | +|--------------------------|-------------------------------------------------------| +| `Enable_GunGame` | `Scoreboard_Setup()` | +| `Disable_GunGame` | `bhl_sb_reset()` | +| `Equip_PlayerWithWeapon` | `Scoreboard_UpdatePlayer(id)` | +| `On_PlayerKilled` | `Scoreboard_UpdatePlayer(killer)` | +| `Update_TeamData` | Teammates and `bhl_sb_team(teamName)` cells | +| `WarmUp_Timer` | `phase` 1 or 2 and `phase_left`; `phase` 0 at the end | +| `resetPlayersScore` | `kills` 0 for everyone | +| `endgame` | Final values for everyone, `phase` 3 | +| Auto-save restore | `Scoreboard_UpdatePlayer(id)` | + +For clients with `GunGameHudV1` the plugin skips: + +- the text informer (`Show_HudInformer`); +- `StatusIcon`; +- the warmup messages from `WarmUp_Timer`, which then go to every other player one by one + instead of `show_hudmessage(0, …)`. + +The winner message, the final table and chat notifications stay for everyone. + +## 10. Localization + +### 10.1 Tokens + +The client adds tokens to `bugfixedhl_*.txt`: + +| Token | English | Russian | +|----------------------|--------------------------|---------------------------| +| `BHL_SB_Level` | Level | Уровень | +| `BHL_SB_Weapon` | Weapon | Оружие | +| `BHL_SB_Progress` | Progress | Прогресс | +| `BHL_SB_Kills` | Kills | Убийства | +| `BHL_GG_ColPlayer` | Player | Игрок | +| `BHL_GG_You` | YOU | ТЫ | +| `BHL_GG_Final` | FINAL | ФИНАЛ | +| `BHL_GG_LeaderFinal` | LEADER ON THE LAST LEVEL | ЛИДЕР НА ПОСЛЕДНЕМ УРОВНЕ | +| `BHL_GG_LeaderLine` | %s1 · %s2 · %s3 to win | %s1 · %s2 · %s3 до победы | +| `BHL_GG_PlayersOne` | %s1 / %s2 player | %s1 / %s2 игрок | +| `BHL_GG_PlayersFew` | %s1 / %s2 players | %s1 / %s2 игрока | +| `BHL_GG_PlayersMany` | %s1 / %s2 players | %s1 / %s2 игроков | +| `BHL_GG_Place` | PLACE %s1 / %s2 | МЕСТО %s1 / %s2 | +| `BHL_GG_Overtake` | To pass %s1: %s2 | До обгона %s1: %s2 | +| `BHL_GG_Lead` | Lead: %s1 | Отрыв: %s1 | +| `BHL_GG_Tied` | Tied | Вровень | +| `BHL_GG_Waiting` | Waiting for opponents | Ожидание соперников | +| `BHL_GG_Warmup` | WARMUP %s1 | РАЗМИНКА %s1 | +| `BHL_GG_StartIn` | START IN %s1 | СТАРТ ЧЕРЕЗ %s1 | +| `BHL_GG_KillsOne` | %s1 kill | %s1 убийство | +| `BHL_GG_KillsFew` | %s1 kills | %s1 убийства | +| `BHL_GG_KillsMany` | %s1 kills | %s1 убийств | + +`Players*` takes the plural form from the second number. + +### 10.2 Plural forms + +The client picks the `One`, `Few` or `Many` token by the rule of its language: + +| Language | One | Few | Many | +|----------|-----------------------------|-------------------------------------|-------| +| Russian | n % 10 = 1 and n % 100 ≠ 11 | n % 10 in 2–4 and n % 100 not 12–14 | Other | +| English | n = 1 | — | Other | + +A language without its own rule uses the English one. + +### 10.3 Weapon names + +Names of standard HL weapons are the same in every language, as in the mockup. They are tokens +`BHL_Weapon_` with English text in every language file. + +| Sprite | Name | Source | +|----------------|----------|----------| +| `d_crowbar` | Crowbar | mockup | +| `d_9mmhandgun` | Glock | proposal | +| `d_357` | .357 | mockup | +| `d_9mmAR` | MP5 | mockup | +| `d_shotgun` | Shotgun | proposal | +| `d_crossbow` | Crossbow | proposal | +| `d_bolt` | Crossbow | proposal | +| `d_rpg_rocket` | RPG | proposal | +| `d_gauss` | Gauss | mockup | +| `d_egon` | Egon | proposal | +| `d_hornet` | Hornet | mockup | +| `d_grenade` | Grenade | mockup | +| `d_satchel` | Satchel | mockup | +| `d_tripmine` | Tripmine | proposal | +| `d_snark` | Snark | proposal | + +## 11. Compatibility + +Client and server: + +| Client \ Server | Old / AG / Valve | New, no schema | New, schema active | +|-------------------------------------|------------------|----------------|--------------------| +| Old (BugfixedHL, Valve, AG, OpenAG) | as now | as now | as now | +| New | standard | standard | custom | +| New, `hud_scoreboard_custom 0` | standard | standard | standard | +| New, `_bhl` not in userinfo | standard | standard | custom via query ¹ | + +¹ If the client passes the p47 and LAN checks. + +GunGame on a server with the new plugin: + +| Client | Scoreboard | HUD | +|--------------------------------|------------|-------------------------------------------------| +| Old | standard | Plugin informer, `StatusIcon`, warmup texts | +| New, `hud_gungame 1` | GunGame | Widget; plugin texts off except winner and chat | +| New, `hud_gungame 0` | GunGame | Plugin informer, `StatusIcon`, warmup texts | +| New, `hud_scoreboard_custom 0` | standard | Plugin informer, `StatusIcon`, warmup texts | + +Module and server DLL: + +| `bugfixedapi_amxx` \ `hl.so` | API 1.0 / 1.1 | API 1.2 | +|------------------------------|---------------------------------|------------| +| Old module | as now | as now | +| New module | old natives work, no `bhl_sb_*` | everything | +| No module | GunGame works as now | same | + +## 12. Test plan + +Capabilities: + +- From a second client, the first client's userinfo has no `_bhl` (keys with `_` are not forwarded). +- Fill the userinfo with `setinfo` keys: `_bhl` doesn't fit, `bhl_caps` shows source `Query`, the + custom scoreboard still works. +- `setinfo` during a game reaches `ClientUserInfoChanged`; `hud_scoreboard_custom 0/1` and + `hud_gungame 0/1` switch the scoreboard and the plugin texts both ways. +- Writing the same `_bhl` value again doesn't cause `ClientUserInfoChanged` spam. + +Protocol and server: + +- Every cell of the compatibility tables in section 11. +- Map change, reconnect, joining mid-game, GunGame on and off, teamplay. +- 32 players with bots: the full sync never triggers `Reliable channel overflowed`. +- The full sync arrives after the client's `VidInit` and nothing is lost. +- Malformed messages from a debug server command: the client doesn't crash. + +GunGame scoreboard: + +- 640×480, 1280×720 and 1920×1080: the table fits; on 4:3 it is wider than 70%. +- 12 and 32 players: the table grows down, then compact spacing, then scrolling. +- 9, 14 and 24 levels in the level strip; dots with 1–10 kills and the bar with more. +- Ties: shared places, the banner with several leaders on the last level. +- Teamplay with 2 and 4 teams: team headers, players by kills, spectators at the bottom. +- Avatars on and off; own row, last-level rows, ping 100 and above. +- A weapon with a non-standard sprite shows the name from the config. + +GunGame HUD: + +- 640×480, 1280×720 and 1920×1080 with 9, 12 and 24 levels: cells shrink, then the window with + `‹ ›` appears. +- Warmup → countdown → game → win: the block changes, the plugin texts are not duplicated, the + widget hides after the win. +- Ties, a single player on the server, teamplay with 2 and 4 teams. +- Spectator in first-person and free modes. +- Kills per level ≤ 10 and > 10 (teamplay): dots and bar have the same length, the block doesn't jump. +- Plural forms for 1, 2, 5, 11, 12, 21, 22, 25. +- The speedometer and `hud_jumpspeed` in bottom mode don't overlap the level bar; the status bar + with names doesn't overlap it either. + +## 13. Open questions + +1. Are the opt-out settings needed, and are `hud_scoreboard_custom` and `hud_gungame` good names? +2. Icon tint in the scoreboard: the row text color or the HUD color? +3. Color codes in `Text` values: strip them in version 1, or draw them like in player names? +4. Exact sizes and colors from the mockups: dots, bar, level cells and their minimum, row height, + column widths, highlight colors, top-3 marks. +5. Icons for the map, the player count and the crown: files from the designer. +6. In teamplay, should player rows repeat the team level, weapon and progress, or leave them empty? +7. Weapon names marked as proposals in 10.3. diff --git a/gamedir/CMakeLists.txt b/gamedir/CMakeLists.txt index c72e5ebb..b4eb9313 100644 --- a/gamedir/CMakeLists.txt +++ b/gamedir/CMakeLists.txt @@ -79,6 +79,7 @@ set( CLIENT_FILES ui/resource/MOTD.res ui/resource/open_source_software.txt ui/resource/ScorePanel.res + ui/resource/ScorePanel_gungame.res ui/resource/SpectatorInfoPanel.res ui/resource/TeamMenu.res diff --git a/gamedir/addons/amxmodx/scripting/include/bugfixedapi.inc b/gamedir/addons/amxmodx/scripting/include/bugfixedapi.inc index e4f067b1..ef638af4 100644 --- a/gamedir/addons/amxmodx/scripting/include/bugfixedapi.inc +++ b/gamedir/addons/amxmodx/scripting/include/bugfixedapi.inc @@ -135,3 +135,150 @@ native bhl_show_motd_from_file(E_MotdType:type, idx, const file[]); * @param deaths Number of deaths */ native bhl_set_player_score(idx, frags, deaths); + +//------------------------------------ +// Client capabilities and the scoreboard extension +// See docs/scoreboard-protocol.md in the BugfixedHL repository +//------------------------------------ + +enum BhlClientCaps +{ + BHL_CAPS_NONE = 0, + BHL_CAPS_SCOREBOARD_V1 = (1 << 0), + BHL_CAPS_GUNGAME_HUD_V1 = (1 << 1) +}; + +enum BhlSbDisplay +{ + BHL_SB_TEXT = 0, + BHL_SB_ICON = 1, + BHL_SB_METER = 2, + BHL_SB_BUILTIN = 3, + BHL_SB_STEPS = 4 +}; + +enum BhlSbHide +{ + BHL_SB_HIDE_NONE = 0, + BHL_SB_HIDE_FRAGS = (1 << 0), + BHL_SB_HIDE_DEATHS = (1 << 1), + BHL_SB_HIDE_EFF = (1 << 2), + BHL_SB_HIDE_STEAMID = (1 << 3) +}; + +enum BhlSbColumnFlags +{ + BHL_SB_COL_NONE = 0, + BHL_SB_COL_HIDDEN = (1 << 0), + BHL_SB_COL_CENTER = (1 << 1), + BHL_SB_COL_RIGHT = (2 << 1), + BHL_SB_COL_PRIMARY = (1 << 3) +}; + +enum BhlSbTarget +{ + BHL_SB_INVALID = -1, + BHL_SB_GLOBAL = 0 +}; + +/** + * Add to the sort priority of bhl_sb_add_column for ascending order. + */ +#define BHL_SB_SORT_ASC 0x80 + +/** + * Returns the scoreboard target of a player. + * @param idx Player's index + */ +stock BhlSbTarget:bhl_sb_player(idx) +{ + return BhlSbTarget:idx; +} + +/** + * Returns the scoreboard target of a team. + * The target stays valid until the map changes. + * @param teamName Team name, the same that get_user_team() returns + * @return Team target or BHL_SB_INVALID + */ +native BhlSbTarget:bhl_sb_team(const teamName[]); + +/** + * Returns features the client reports to the server. + * Use bitwise AND to check: + * if (bhl_get_client_caps(idx) & BHL_CAPS_GUNGAME_HUD_V1) { ... } + * @param idx Player's index + * @return BhlClientCaps bitfield, BHL_CAPS_NONE on servers without the feature + */ +native BhlClientCaps:bhl_get_client_caps(idx); + +/** + * Called when the value returned by bhl_get_client_caps() changes for a player in game. + * @param idx Player's index + */ +forward bhl_client_caps_changed(idx); + +/** + * Returns whether the server supports the scoreboard extension. + * All other bhl_sb_* natives do nothing when it returns false. + */ +native bool:bhl_sb_available(); + +/** + * Removes the schema, all values and lists. Clients return to the standard scoreboard. + */ +native bhl_sb_reset(); + +/** + * Turns the custom scoreboard on. + * @param hide Standard columns to hide + * @param preset Client preset name, "" for the generic look + * @param title Replaces the server name if not empty + * @param tag Badge next to the title, for example "FFA" + */ +native bhl_sb_config(BhlSbHide:hide, const preset[] = "", const title[] = "", const tag[] = ""); + +/** + * Adds a column, or replaces the column with the same key. Columns are shown in the order they are added. + * @param key Up to 15 characters of [a-z0-9_]. For BHL_SB_BUILTIN one of: + * rank, frags, deaths, eff, steamid, ping + * @param title Text or #token shipped with the client, "" for the default title of a built-in column + * @param display How the values are drawn + * @param width Width in proportional units, 0 for the default + * @param sort 0 or sort priority starting at 1, plus BHL_SB_SORT_ASC for ascending order + * @param flags Column flags + * @return true on success + */ +native bool:bhl_sb_add_column(const key[], const title[], BhlSbDisplay:display = BHL_SB_TEXT, + width = 0, sort = 0, BhlSbColumnFlags:flags = BHL_SB_COL_NONE); + +/** + * Sets a value of a column for a target. + * Values for players that are not connected are ignored. + * Setting the value a cell already has sends nothing. + * @param target BHL_SB_GLOBAL, bhl_sb_player(idx) or bhl_sb_team(name) + * @param key Column key + */ +native bhl_sb_set_int(BhlSbTarget:target, const key[], value); +native bhl_sb_set_text(BhlSbTarget:target, const key[], const text[]); +native bhl_sb_set_icon(BhlSbTarget:target, const key[], const sprite[], const text[]); +native bhl_sb_set_progress(BhlSbTarget:target, const key[], cur, max); + +/** + * Clears a value of a target, or every value of the target if key is empty. + */ +native bhl_sb_clear(BhlSbTarget:target, const key[] = ""); + +/** + * Creates a list on first use and sets its size (up to 64 items). + * @param key Up to 15 characters of [a-z0-9_] + * @return true on success + */ +native bool:bhl_sb_list_resize(const key[], count); + +/** + * Sets an item of a list. Items out of range are ignored. + */ +native bhl_sb_list_set_int(const key[], index, value); +native bhl_sb_list_set_text(const key[], index, const text[]); +native bhl_sb_list_set_icon(const key[], index, const sprite[], const text[]); diff --git a/gamedir/ui/resource/ClientSchemeBase.res b/gamedir/ui/resource/ClientSchemeBase.res index dba66c7e..6a70c83e 100644 --- a/gamedir/ui/resource/ClientSchemeBase.res +++ b/gamedir/ui/resource/ClientSchemeBase.res @@ -596,6 +596,90 @@ Scheme "custom" "1" } } + + // GunGame HUD and scoreboard + "GunGameHudLarge" // place line of the HUD widget + { + "1" + { + "name" "Verdana" + "tall" "16" + "weight" "800" + "yres" "480 599" + } + "2" + { + "name" "Verdana" + "tall" "18" + "weight" "800" + "yres" "600 767" + } + "3" + { + "name" "Verdana" + "tall" "20" + "weight" "800" + "yres" "768 1023" + "antialias" "1" + } + "4" + { + "name" "Verdana" + "tall" "28" + "weight" "800" + "yres" "1024 1199" + "antialias" "1" + } + "5" + { + "name" "Verdana" + "tall" "34" + "weight" "800" + "yres" "1200 6000" + "antialias" "1" + } + } + "GunGameHudText" // other lines of the HUD widget + { + "1" + { + "name" "Verdana" + "tall" "12" + "weight" "600" + "yres" "480 599" + } + "2" + { + "name" "Verdana" + "tall" "13" + "weight" "600" + "yres" "600 767" + } + "3" + { + "name" "Verdana" + "tall" "14" + "weight" "600" + "yres" "768 1023" + "antialias" "1" + } + "4" + { + "name" "Verdana" + "tall" "20" + "weight" "600" + "yres" "1024 1199" + "antialias" "1" + } + "5" + { + "name" "Verdana" + "tall" "24" + "weight" "600" + "yres" "1200 6000" + "antialias" "1" + } + } } // diff --git a/gamedir/ui/resource/ScorePanel_gungame.res b/gamedir/ui/resource/ScorePanel_gungame.res new file mode 100644 index 00000000..6e893b0c --- /dev/null +++ b/gamedir/ui/resource/ScorePanel_gungame.res @@ -0,0 +1,105 @@ +/////////////////////////////////////////////////////////// +// Scoreboard layout of the "gungame" preset +// +// Loaded instead of ScorePanel.res while a server with the GunGame +// plugin sends the custom scoreboard. Keys that are not set here +// come from ScorePanel.res. +// +// Set here only keys that ScorePanel.res also has, or "gg_" keys: +// any other key would keep its GunGame value after switching back. +/////////////////////////////////////////////////////////// +#base "ScorePanel.res" + +"ui/resource/ScorePanel_gungame.res" +{ + "ScorePanel" + { + // Position and size are set in code: see gg_wide_percent and gg_top_percent + "xpos" "c-300" + "wide" "600" + + // Column widths. The player column takes the free width. + "column_avatar" "20" + "column_deaths" "50" + "column_ping" "50" + + // Minimum distance between the bottom edge of the score panel and the bottom edge of the screen + "vertical_margin" "20" + + // Width in percent of the screen width. The panel is wider if the columns need it. + "gg_wide_percent" "70" + + // Distance from the top edge of the screen in percent of the screen height + "gg_top_percent" "10" + + // Ping from this value is highlighted + "gg_ping_high" "100" + "gg_ping_high_color" "255 80 80 255" + + // Rows of this player and of players on the last level + "gg_own_row_bgcolor" "255 160 0 56" + "gg_final_row_bgcolor" "255 64 32 40" + + // Own name, level and weapon on the last level + "gg_emphasis_color" "255 176 0 255" + + // Marks of the first three places. Use opaque colors. + "gg_place_first_color" "255 160 0 255" + "gg_place_first_textcolor" "0 0 0 255" + "gg_place_top_color" "112 72 16 255" + "gg_place_final_color" "255 64 32 255" // First place on the last level + + // Banner "Leader on the last level" + "gg_banner_bgcolor" "255 64 32 48" + "gg_banner_accent_color" "255 160 0 255" + "gg_banner_padding" "3" + "gg_banner_accent_wide" "2" + } + "ServerName" + { + "xpos" "8" + "ypos" "4" + "wide" "320" + "tall" "18" + "font" "GunGameHudLarge" + } + "MapName" + { + "xpos" "8" + "ypos" "23" + "wide" "320" + "tall" "12" + } + "PlayerCount" + { + "visible" "0" + } + "LeaderTitle" + { + "fieldName" "LeaderTitle" + "xpos" "0" + "ypos" "5" + "wide" "100" + "tall" "12" + "visible" "0" + "textAlignment" "east" + "font" "GunGameHudText" + "fgcolor_override" "255 160 0 255" + } + "LeaderLine" + { + "fieldName" "LeaderLine" + "xpos" "0" + "ypos" "18" + "wide" "100" + "tall" "12" + "visible" "0" + "textAlignment" "east" + "font" "Default" + } + "PlayerList" + { + "xpos" "8" + "ypos" "40" + } +} diff --git a/gamedir/ui/resource/language/bugfixedhl_english.utf8.txt b/gamedir/ui/resource/language/bugfixedhl_english.utf8.txt index 2484a8b1..09faedcb 100644 --- a/gamedir/ui/resource/language/bugfixedhl_english.utf8.txt +++ b/gamedir/ui/resource/language/bugfixedhl_english.utf8.txt @@ -24,6 +24,50 @@ "BHL_Scores_MenuCopySteamID" "Copy SteamID" "BHL_Scores_MenuCopySteamID64" "Copy SteamID64" +// Scoreboard extension +"BHL_PluralRule" "en" // Plural rule: "en" or "ru" +"BHL_SB_Level" "Level" +"BHL_SB_Weapon" "Weapon" +"BHL_SB_Progress" "Progress" +"BHL_SB_Kills" "Kills" + +// GunGame +"BHL_GG_ColPlayer" "Player" +"BHL_GG_You" "YOU" +"BHL_GG_Final" "FINAL" +"BHL_GG_LeaderFinal" "LEADER ON THE LAST LEVEL" +"BHL_GG_LeaderLine" "%s1 · %s2 · %s3 to win" +"BHL_GG_PlayersOne" "%s1 / %s2 player" +"BHL_GG_PlayersFew" "%s1 / %s2 players" +"BHL_GG_PlayersMany" "%s1 / %s2 players" +"BHL_GG_Place" "PLACE %s1 / %s2" +"BHL_GG_Overtake" "To pass %s1: %s2" +"BHL_GG_Lead" "Lead: %s1" +"BHL_GG_Tied" "Tied" +"BHL_GG_Waiting" "Waiting for opponents" +"BHL_GG_Warmup" "WARMUP %s1" +"BHL_GG_StartIn" "START IN %s1" +"BHL_GG_KillsOne" "%s1 kill" +"BHL_GG_KillsFew" "%s1 kills" +"BHL_GG_KillsMany" "%s1 kills" + +// Weapon names (the same in every language) +"BHL_Weapon_crowbar" "Crowbar" +"BHL_Weapon_9mmhandgun" "Glock" +"BHL_Weapon_357" ".357" +"BHL_Weapon_9mmAR" "MP5" +"BHL_Weapon_shotgun" "Shotgun" +"BHL_Weapon_crossbow" "Crossbow" +"BHL_Weapon_bolt" "Crossbow" +"BHL_Weapon_rpg_rocket" "RPG" +"BHL_Weapon_gauss" "Gauss" +"BHL_Weapon_egon" "Egon" +"BHL_Weapon_hornet" "Hornet" +"BHL_Weapon_grenade" "Grenade" +"BHL_Weapon_satchel" "Satchel" +"BHL_Weapon_tripmine" "Tripmine" +"BHL_Weapon_snark" "Snark" + "BHL_Update_Notif_Title" "Update notification" "BHL_Update_Notif_Text" "A new update has been released." "BHL_Update_Notif_OldVer" "Your version: " diff --git a/gamedir/ui/resource/language/bugfixedhl_russian.utf8.txt b/gamedir/ui/resource/language/bugfixedhl_russian.utf8.txt index 8b8ddd24..7bcb6617 100644 --- a/gamedir/ui/resource/language/bugfixedhl_russian.utf8.txt +++ b/gamedir/ui/resource/language/bugfixedhl_russian.utf8.txt @@ -24,6 +24,50 @@ "BHL_Scores_MenuCopySteamID" "Скопировать SteamID" "BHL_Scores_MenuCopySteamID64" "Скопировать SteamID64" +// Scoreboard extension +"BHL_PluralRule" "ru" // Plural rule: "en" or "ru" +"BHL_SB_Level" "Уровень" +"BHL_SB_Weapon" "Оружие" +"BHL_SB_Progress" "Прогресс" +"BHL_SB_Kills" "Убийства" + +// GunGame +"BHL_GG_ColPlayer" "Игрок" +"BHL_GG_You" "ТЫ" +"BHL_GG_Final" "ФИНАЛ" +"BHL_GG_LeaderFinal" "ЛИДЕР НА ПОСЛЕДНЕМ УРОВНЕ" +"BHL_GG_LeaderLine" "%s1 · %s2 · %s3 до победы" +"BHL_GG_PlayersOne" "%s1 / %s2 игрок" +"BHL_GG_PlayersFew" "%s1 / %s2 игрока" +"BHL_GG_PlayersMany" "%s1 / %s2 игроков" +"BHL_GG_Place" "МЕСТО %s1 / %s2" +"BHL_GG_Overtake" "До обгона %s1: %s2" +"BHL_GG_Lead" "Отрыв: %s1" +"BHL_GG_Tied" "Вровень" +"BHL_GG_Waiting" "Ожидание соперников" +"BHL_GG_Warmup" "РАЗМИНКА %s1" +"BHL_GG_StartIn" "СТАРТ ЧЕРЕЗ %s1" +"BHL_GG_KillsOne" "%s1 убийство" +"BHL_GG_KillsFew" "%s1 убийства" +"BHL_GG_KillsMany" "%s1 убийств" + +// Weapon names (the same in every language) +"BHL_Weapon_crowbar" "Crowbar" +"BHL_Weapon_9mmhandgun" "Glock" +"BHL_Weapon_357" ".357" +"BHL_Weapon_9mmAR" "MP5" +"BHL_Weapon_shotgun" "Shotgun" +"BHL_Weapon_crossbow" "Crossbow" +"BHL_Weapon_bolt" "Crossbow" +"BHL_Weapon_rpg_rocket" "RPG" +"BHL_Weapon_gauss" "Gauss" +"BHL_Weapon_egon" "Egon" +"BHL_Weapon_hornet" "Hornet" +"BHL_Weapon_grenade" "Grenade" +"BHL_Weapon_satchel" "Satchel" +"BHL_Weapon_tripmine" "Tripmine" +"BHL_Weapon_snark" "Snark" + "BHL_Update_Notif_Title" "Уведомление об обновлении" "BHL_Update_Notif_Text" "Вышло новое обновление." "BHL_Update_Notif_OldVer" "Ваша версия: " diff --git a/gamedir/ui/scripts/HudLayoutBase.res b/gamedir/ui/scripts/HudLayoutBase.res index 2bcb5cd7..df780aa5 100644 --- a/gamedir/ui/scripts/HudLayoutBase.res +++ b/gamedir/ui/scripts/HudLayoutBase.res @@ -106,4 +106,39 @@ "default_name_color_kill" "OffWhite" "default_name_color_death" "OffWhite" } + + HudGunGamePanel + { + "fieldName" "HudGunGamePanel" + "visible" "1" + "enabled" "1" + "xpos" "0" + "ypos" "0" + "wide" "f0" + "tall" "f0" + + // Place block at the top center + "place_ypos" "12" // Top of the place line + "line_gap" "2" // Distance between the place line and the overtake line + "meter_gap" "6" // Distance above the kills meter + "dot_size" "7" // Diameter of a kill dot, height of the kill bar + "dot_gap" "3" // Distance between kill dots + "counter_gap" "6" // Distance between the kill bar and its counter + "large_font" "GunGameHudLarge" + "text_font" "GunGameHudText" + + // Level bar at the bottom center, on the line of the health and ammo numbers + "cell_wide" "30" // Width of a level cell + "cell_min_wide" "14" // Cells shrink down to this width, then the bar shows a window around the current level + "cell_tall" "15" // Height of a level cell + "cell_gap" "3" // Distance between level cells + "icon_padding" "2" // Padding of the weapon icon inside a cell + "bar_max_wide" "300" // Maximal width of the level bar + + // Alpha of the HUD color (hud_color) + "alpha_passed" "112" // Passed level cells + "alpha_current" "48" // Current level cell, drawn with a frame + "alpha_future" "24" // Next level cells + "alpha_dim" "80" // Icons of the next levels, the empty part of the kill bar + } } diff --git a/src/bugfixedapi_amxx/bhl_api.cpp b/src/bugfixedapi_amxx/bhl_api.cpp index 95dbb95d..74e67dbc 100644 --- a/src/bugfixedapi_amxx/bhl_api.cpp +++ b/src/bugfixedapi_amxx/bhl_api.cpp @@ -23,6 +23,11 @@ bool bhl::IsServerApiReady() return (g_pServerApi != nullptr); } +bool bhl::IsScoreboardApiReady() +{ + return g_pServerApi != nullptr && g_iServerMinor >= SCOREBOARD_API_MINOR; +} + bhl::E_ApiInitResult bhl::InitServerApi() { assert(!IsServerApiReady()); @@ -50,7 +55,7 @@ bhl::E_ApiInitResult bhl::InitServerApi() // Check version pIface->GetInterfaceVersion(g_iServerMajor, g_iServerMinor); - if (!(g_iServerMajor == IBUGFIXEDSERVER_MAJOR && g_iServerMinor >= IBUGFIXEDSERVER_MINOR)) + if (g_iServerMajor != IBUGFIXEDSERVER_MAJOR) return E_ApiInitResult::VersionMismatch; g_pServerApi = pIface; diff --git a/src/bugfixedapi_amxx/bhl_api.h b/src/bugfixedapi_amxx/bhl_api.h index 7a84acd9..4a8072a0 100644 --- a/src/bugfixedapi_amxx/bhl_api.h +++ b/src/bugfixedapi_amxx/bhl_api.h @@ -16,6 +16,9 @@ enum class E_ApiInitResult VersionMismatch // GetInterfaceVersion returned incompatible version }; +//! Server API minor version that added GetClientCaps and GetScoreboard +constexpr int SCOREBOARD_API_MINOR = 2; + /** * @returns pointer to server API or nullptr */ @@ -26,6 +29,11 @@ bhl::IBugfixedServer *serverapi(); */ bool IsServerApiReady(); +/** + * Return true if API is available and has GetClientCaps and GetScoreboard. + */ +bool IsScoreboardApiReady(); + /** * Initializes server API. * Uses functions from interface.h to get API pointer and check the version. diff --git a/src/bugfixedapi_amxx/bugfixedapi_amxx.cpp b/src/bugfixedapi_amxx/bugfixedapi_amxx.cpp index e1944cf2..33ca97af 100644 --- a/src/bugfixedapi_amxx/bugfixedapi_amxx.cpp +++ b/src/bugfixedapi_amxx/bugfixedapi_amxx.cpp @@ -176,6 +176,202 @@ static cell AMX_NATIVE_CALL bhl_set_player_score(AMX *amx, cell *params) return 1; } +static int g_iClientCapsChangedFwd = -1; +static bhl::E_ClientCaps g_ClientCaps[32 + 1]; +static bool g_bScoreboardErrorLogged = false; + +static bool CheckScoreboardApi(const char *native) +{ + if (bhl::IsScoreboardApiReady()) + return true; + + if (bhl::IsServerApiReady() && !g_bScoreboardErrorLogged) + { + int major = 0, minor = 0; + bhl::GetServerApiVersion(major, minor); + MF_Log("%s: server API %d.%d doesn't support the scoreboard extension (requires %d.%d). bhl_sb_* natives will not function.", native, major, minor, IBUGFIXEDSERVER_MAJOR, bhl::SCOREBOARD_API_MINOR); + g_bScoreboardErrorLogged = true; + } + + return false; +} + +// native BhlSbTarget:bhl_sb_team(const teamName[]) +static cell AMX_NATIVE_CALL bhl_sb_team(AMX *amx, cell *params) +{ + if (!CheckScoreboardApi(__func__)) + return -1; + + int length; + const char *teamName = MF_GetAmxString(amx, params[1], 0, &length); + return (cell)bhl::serverapi()->GetScoreboard()->GetTeamTarget(teamName); +} + +// native BhlClientCaps:bhl_get_client_caps(idx) +static cell AMX_NATIVE_CALL bhl_get_client_caps(AMX *amx, cell *params) +{ + if (!bhl::IsScoreboardApiReady()) + return 0; + int idx = params[1]; + if (idx < 1 || idx > gpGlobals->maxClients) + return 0; + return (cell)bhl::serverapi()->GetClientCaps(idx); +} + +// native bool:bhl_sb_available() +static cell AMX_NATIVE_CALL bhl_sb_available(AMX *amx, cell *params) +{ + return bhl::IsScoreboardApiReady(); +} + +// native bhl_sb_reset() +static cell AMX_NATIVE_CALL bhl_sb_reset(AMX *amx, cell *params) +{ + if (!CheckScoreboardApi(__func__)) + return 0; + bhl::serverapi()->GetScoreboard()->Reset(); + return 1; +} + +// native bhl_sb_config(BhlSbHide:hide, const preset[] = "", const title[] = "", const tag[] = "") +static cell AMX_NATIVE_CALL bhl_sb_config(AMX *amx, cell *params) +{ + if (!CheckScoreboardApi(__func__)) + return 0; + + int length; + const char *preset = MF_GetAmxString(amx, params[2], 0, &length); + const char *title = MF_GetAmxString(amx, params[3], 1, &length); + const char *tag = MF_GetAmxString(amx, params[4], 2, &length); + bhl::serverapi()->GetScoreboard()->SetConfig(static_cast(params[1]), preset, title, tag); + return 1; +} + +// native bool:bhl_sb_add_column(const key[], const title[], BhlSbDisplay:display = BHL_SB_TEXT, width = 0, sort = 0, BhlSbColumnFlags:flags = BHL_SB_COL_NONE) +static cell AMX_NATIVE_CALL bhl_sb_add_column(AMX *amx, cell *params) +{ + if (!CheckScoreboardApi(__func__)) + return 0; + + int length; + const char *key = MF_GetAmxString(amx, params[1], 0, &length); + const char *title = MF_GetAmxString(amx, params[2], 1, &length); + return (cell)bhl::serverapi()->GetScoreboard()->AddColumn(key, title, params[3], params[4], params[5], static_cast(params[6])); +} + +// native bhl_sb_set_int(BhlSbTarget:target, const key[], value) +static cell AMX_NATIVE_CALL bhl_sb_set_int(AMX *amx, cell *params) +{ + if (!CheckScoreboardApi(__func__)) + return 0; + + int length; + const char *key = MF_GetAmxString(amx, params[2], 0, &length); + bhl::serverapi()->GetScoreboard()->SetInt(params[1], key, params[3]); + return 1; +} + +// native bhl_sb_set_text(BhlSbTarget:target, const key[], const text[]) +static cell AMX_NATIVE_CALL bhl_sb_set_text(AMX *amx, cell *params) +{ + if (!CheckScoreboardApi(__func__)) + return 0; + + int length; + const char *key = MF_GetAmxString(amx, params[2], 0, &length); + const char *text = MF_GetAmxString(amx, params[3], 1, &length); + bhl::serverapi()->GetScoreboard()->SetText(params[1], key, text); + return 1; +} + +// native bhl_sb_set_icon(BhlSbTarget:target, const key[], const sprite[], const text[]) +static cell AMX_NATIVE_CALL bhl_sb_set_icon(AMX *amx, cell *params) +{ + if (!CheckScoreboardApi(__func__)) + return 0; + + int length; + const char *key = MF_GetAmxString(amx, params[2], 0, &length); + const char *sprite = MF_GetAmxString(amx, params[3], 1, &length); + const char *text = MF_GetAmxString(amx, params[4], 2, &length); + bhl::serverapi()->GetScoreboard()->SetIcon(params[1], key, sprite, text); + return 1; +} + +// native bhl_sb_set_progress(BhlSbTarget:target, const key[], cur, max) +static cell AMX_NATIVE_CALL bhl_sb_set_progress(AMX *amx, cell *params) +{ + if (!CheckScoreboardApi(__func__)) + return 0; + + int length; + const char *key = MF_GetAmxString(amx, params[2], 0, &length); + bhl::serverapi()->GetScoreboard()->SetProgress(params[1], key, params[3], params[4]); + return 1; +} + +// native bhl_sb_clear(BhlSbTarget:target, const key[] = "") +static cell AMX_NATIVE_CALL bhl_sb_clear(AMX *amx, cell *params) +{ + if (!CheckScoreboardApi(__func__)) + return 0; + + int length; + const char *key = MF_GetAmxString(amx, params[2], 0, &length); + bhl::serverapi()->GetScoreboard()->Clear(params[1], key); + return 1; +} + +// native bool:bhl_sb_list_resize(const key[], count) +static cell AMX_NATIVE_CALL bhl_sb_list_resize(AMX *amx, cell *params) +{ + if (!CheckScoreboardApi(__func__)) + return 0; + + int length; + const char *key = MF_GetAmxString(amx, params[1], 0, &length); + return (cell)bhl::serverapi()->GetScoreboard()->ListResize(key, params[2]); +} + +// native bhl_sb_list_set_int(const key[], index, value) +static cell AMX_NATIVE_CALL bhl_sb_list_set_int(AMX *amx, cell *params) +{ + if (!CheckScoreboardApi(__func__)) + return 0; + + int length; + const char *key = MF_GetAmxString(amx, params[1], 0, &length); + bhl::serverapi()->GetScoreboard()->ListSetInt(key, params[2], params[3]); + return 1; +} + +// native bhl_sb_list_set_text(const key[], index, const text[]) +static cell AMX_NATIVE_CALL bhl_sb_list_set_text(AMX *amx, cell *params) +{ + if (!CheckScoreboardApi(__func__)) + return 0; + + int length; + const char *key = MF_GetAmxString(amx, params[1], 0, &length); + const char *text = MF_GetAmxString(amx, params[3], 1, &length); + bhl::serverapi()->GetScoreboard()->ListSetText(key, params[2], text); + return 1; +} + +// native bhl_sb_list_set_icon(const key[], index, const sprite[], const text[]) +static cell AMX_NATIVE_CALL bhl_sb_list_set_icon(AMX *amx, cell *params) +{ + if (!CheckScoreboardApi(__func__)) + return 0; + + int length; + const char *key = MF_GetAmxString(amx, params[1], 0, &length); + const char *sprite = MF_GetAmxString(amx, params[3], 1, &length); + const char *text = MF_GetAmxString(amx, params[4], 2, &length); + bhl::serverapi()->GetScoreboard()->ListSetIcon(key, params[2], sprite, text); + return 1; +} + AMX_NATIVE_INFO bugfixedapi_Exports[] = { { "bhl_is_api_ready", bhl_is_api_ready }, { "bhl_get_server_version", bhl_get_server_version }, @@ -190,6 +386,21 @@ AMX_NATIVE_INFO bugfixedapi_Exports[] = { { "bhl_show_motd_from_string", bhl_show_motd_from_string }, { "bhl_show_motd_from_file", bhl_show_motd_from_file }, { "bhl_set_player_score", bhl_set_player_score }, + { "bhl_sb_team", bhl_sb_team }, + { "bhl_get_client_caps", bhl_get_client_caps }, + { "bhl_sb_available", bhl_sb_available }, + { "bhl_sb_reset", bhl_sb_reset }, + { "bhl_sb_config", bhl_sb_config }, + { "bhl_sb_add_column", bhl_sb_add_column }, + { "bhl_sb_set_int", bhl_sb_set_int }, + { "bhl_sb_set_text", bhl_sb_set_text }, + { "bhl_sb_set_icon", bhl_sb_set_icon }, + { "bhl_sb_set_progress", bhl_sb_set_progress }, + { "bhl_sb_clear", bhl_sb_clear }, + { "bhl_sb_list_resize", bhl_sb_list_resize }, + { "bhl_sb_list_set_int", bhl_sb_list_set_int }, + { "bhl_sb_list_set_text", bhl_sb_list_set_text }, + { "bhl_sb_list_set_icon", bhl_sb_list_set_icon }, { nullptr, nullptr } }; @@ -224,7 +435,7 @@ void OnAmxxAttach() bhl::GetServerApiVersion(major, minor); LOG_ERROR(PLID, "Interface version mismatch."); LOG_ERROR(PLID, "\tGot: %d.%d", major, minor); - LOG_ERROR(PLID, "\tRequired: %d.%d", IBUGFIXEDSERVER_MAJOR, IBUGFIXEDSERVER_MINOR); + LOG_ERROR(PLID, "\tRequired: %d.x", IBUGFIXEDSERVER_MAJOR); } // Print final message @@ -238,9 +449,48 @@ void OnAmxxAttach() LOG_MESSAGE(PLID, "Got IBugfixedServer from server library."); LOG_MESSAGE(PLID, "BugfixedAPI AMXX module loaded successfully."); + + if (!bhl::IsScoreboardApiReady()) + { + int major = 0, minor = 0; + bhl::GetServerApiVersion(major, minor); + LOG_MESSAGE(PLID, "Server API %d.%d doesn't support the scoreboard extension (requires %d.%d). bhl_sb_* natives will not function.", major, minor, IBUGFIXEDSERVER_MAJOR, bhl::SCOREBOARD_API_MINOR); + } } void OnAmxxDetach() { bhl::ShutdownServerApi(); } + +void OnPluginsLoaded() +{ + g_iClientCapsChangedFwd = MF_RegisterForward("bhl_client_caps_changed", ET_IGNORE, FP_CELL, FP_DONE); + g_bScoreboardErrorLogged = false; +} + +void OnPluginsUnloading() +{ + g_iClientCapsChangedFwd = -1; +} + +void StartFrame() +{ + if (bhl::IsScoreboardApiReady()) + { + int maxClients = std::min(gpGlobals->maxClients, (int)ARRAYSIZE(g_ClientCaps) - 1); + for (int i = 1; i <= maxClients; i++) + { + bhl::E_ClientCaps caps = bhl::serverapi()->GetClientCaps(i); + if (caps == g_ClientCaps[i]) + continue; + + g_ClientCaps[i] = caps; + + if (g_iClientCapsChangedFwd != -1 && MF_IsPlayerIngame(i)) + MF_ExecuteForward(g_iClientCapsChangedFwd, static_cast(i)); + } + } + + RETURN_META(MRES_IGNORED); +} diff --git a/src/bugfixedapi_amxx/moduleconfig.h b/src/bugfixedapi_amxx/moduleconfig.h index bb6dcb12..4e979cda 100644 --- a/src/bugfixedapi_amxx/moduleconfig.h +++ b/src/bugfixedapi_amxx/moduleconfig.h @@ -84,10 +84,10 @@ /** All plugins loaded * Do forward functions init here (MF_RegisterForward) */ -//#define FN_AMXX_PLUGINSLOADED OnPluginsLoaded +#define FN_AMXX_PLUGINSLOADED OnPluginsLoaded /** All plugins are about to be unloaded */ -//#define FN_AMXX_PLUGINSUNLOADING OnPluginsUnloading +#define FN_AMXX_PLUGINSUNLOADING OnPluginsUnloading /** All plugins are now unloaded */ //#define FN_AMXX_PLUGINSUNLOADED OnPluginsUnloaded @@ -136,7 +136,7 @@ // #define FN_ServerDeactivate ServerDeactivate /* pfnServerDeactivate() (wd) Server is leaving the map (shutdown or changelevel); SDK2 */ // #define FN_PlayerPreThink PlayerPreThink /* pfnPlayerPreThink() */ // #define FN_PlayerPostThink PlayerPostThink /* pfnPlayerPostThink() */ -// #define FN_StartFrame StartFrame /* pfnStartFrame() */ +#define FN_StartFrame StartFrame /* pfnStartFrame() */ // #define FN_ParmsNewLevel ParmsNewLevel /* pfnParmsNewLevel() */ // #define FN_ParmsChangeLevel ParmsChangeLevel /* pfnParmsChangeLevel() */ // #define FN_GetGameDescription GetGameDescription /* pfnGetGameDescription() Returns string describing current .dll. E.g. "TeamFotrress 2" "Half-Life" */ diff --git a/src/game/client/CMakeLists.txt b/src/game/client/CMakeLists.txt index 91038f1e..bfa400e6 100644 --- a/src/game/client/CMakeLists.txt +++ b/src/game/client/CMakeLists.txt @@ -101,6 +101,8 @@ set( SOURCE_FILES hud/flashlight.h hud/geiger.cpp hud/geiger.h + hud/gungame_hud.cpp + hud/gungame_hud.h hud/health.cpp hud/health.h hud/jumpspeed.cpp @@ -143,6 +145,8 @@ set( SOURCE_FILES vgui/crosshair_image.h vgui/score_panel.cpp vgui/score_panel.h + vgui/score_panel_cells.cpp + vgui/score_panel_cells.h vgui/spectator_panel.cpp vgui/spectator_panel.h vgui/team_menu.cpp @@ -222,6 +226,8 @@ set( SOURCE_FILES rainbow.h results.cpp results.h + scoreboard_data.cpp + scoreboard_data.h sdl_rt.cpp sdl_rt.h studio_util.cpp diff --git a/src/game/client/hud.cpp b/src/game/client/hud.cpp index 7aef31ea..d6b7de0e 100644 --- a/src/game/client/hud.cpp +++ b/src/game/client/hud.cpp @@ -47,6 +47,7 @@ #include "sdl_rt.h" #include "fog.h" #include "engine_builds.h" +#include "scoreboard_data.h" #if USE_UPDATER #include "updater/update_checker.h" @@ -78,6 +79,7 @@ #include "hud/jumpspeed.h" #include "hud/timer.h" #include "hud/strafeguide.h" +#include "hud/gungame_hud.h" // Adrenaline Gamer HUD Elements #include "hud/ag/ag_countdown.h" @@ -143,6 +145,7 @@ ConVar showtriggers("showtriggers", "0", 0, "Shows trigger brushes"); ConVar aghl_version("aghl_version", APP_VERSION, 0, "BugfixedHL version"); ConVar aghl_supports("aghl_supports", "0", 0, "Bitfield of features supported by this client"); +ConVar bhl_caps_userinfo("_bhl", "3", FCVAR_USERINFO, "Bitfield of BugfixedHL client capabilities, set automatically"); ConVar cl_enable_html_motd("cl_enable_html_motd", "1", FCVAR_BHL_ARCHIVE, "Enables/disables support for HTML MOTDs"); ConVar zoom_sensitivity_ratio("zoom_sensitivity_ratio", "1.2", FCVAR_ARCHIVE | FCVAR_BHL_ARCHIVE); @@ -376,6 +379,7 @@ void CHud::Init(void) RegisterHudElem(); RegisterHudElem(); RegisterHudElem(); + RegisterHudElem(); if (CHudRenderer::Get().IsAvailable()) { @@ -409,6 +413,7 @@ void CHud::Init(void) bhlcfg::Init(); CResults::Get().Init(); + CScoreboardData::Get().Init(); #if USE_UPDATER CHttpClient::Get(); @@ -442,6 +447,7 @@ void CHud::VidInit(void) } CSvcMessages::Get().VidInit(); + CScoreboardData::Get().VidInit(); // ---------- // Load Sprites @@ -541,6 +547,21 @@ void CHud::VidInit(void) for (CHudElem *i : m_HudList) i->VidInit(); + + UpdateCapsUserinfo(); +} + +static int GetClientCaps() +{ + bhl::E_ClientCaps caps = bhl::E_ClientCaps::None; + + if (CScoreboardData::IsCustomEnabled()) + SetEnumFlag(caps, bhl::E_ClientCaps::ScoreboardV1); + + if (CScoreboardData::IsGunGameHudEnabled()) + SetEnumFlag(caps, bhl::E_ClientCaps::GunGameHudV1); + + return static_cast(caps); } void CHud::Frame(double time) @@ -554,6 +575,7 @@ void CHud::Frame(double time) CHudVoiceStatus::Get()->RunFrame(time); CResults::Get().Frame(); + CScoreboardData::Get().Frame(); #if USE_UPDATER CHttpClient::Get().RunFrame(); @@ -568,6 +590,12 @@ void CHud::Frame(double time) UpdateSupportsCvar(); } + if (GetClientCaps() != m_iCaps || strcmp(bhl_caps_userinfo.GetString(), m_szCaps)) + UpdateCapsUserinfo(); + + if (m_iCapsCheckFrame != 0 && m_iFrameCount >= m_iCapsCheckFrame) + CheckCapsUserinfo(); + while (m_NextFrameQueue.size()) { auto &i = m_NextFrameQueue.front(); @@ -872,6 +900,52 @@ void CHud::UpdateSupportsCvar() gEngfuncs.pfnClientCmd(buf); } +void CHud::UpdateCapsUserinfo() +{ + int caps = GetClientCaps(); + + if (caps != m_iCaps) + { + m_iCaps = caps; + snprintf(m_szCaps, sizeof(m_szCaps), "%x", static_cast(caps)); + m_iCapsCheckFrame = 0; + m_bCapsCheckFailed = false; + } + + if (strcmp(bhl_caps_userinfo.GetString(), m_szCaps)) + bhl_caps_userinfo.SetValue(m_szCaps); + + if (!m_bCapsCheckFailed && m_iCapsCheckFrame == 0) + { + m_bCapsSetinfoSent = false; + m_iCapsCheckFrame = m_iFrameCount + 1; + } +} + +void CHud::CheckCapsUserinfo() +{ + m_iCapsCheckFrame = 0; + + if (!strcmp(gEngfuncs.LocalPlayerInfo_ValueForKey(bhl_caps_userinfo.GetName()), m_szCaps)) + return; + + if (!m_bCapsSetinfoSent) + { + char buf[64]; + snprintf(buf, sizeof(buf), "setinfo %s %s\n", bhl_caps_userinfo.GetName(), m_szCaps); + gEngfuncs.pfnClientCmd(buf); + m_bCapsSetinfoSent = true; + + // The command runs from the command buffer, give it a full frame + m_iCapsCheckFrame = m_iFrameCount + 2; + } + else + { + ConPrintf(ConColor::Red, "Failed to put %s into userinfo, it may be full. The server will query the cvar instead.\n", bhl_caps_userinfo.GetName()); + m_bCapsCheckFailed = true; + } +} + EHudScale CHud::DetectMaxHudScale() { const HudScaleInfo *pMaxScaleInfo = nullptr; diff --git a/src/game/client/hud.h b/src/game/client/hud.h index 48493ed0..0eef6d4d 100644 --- a/src/game/client/hud.h +++ b/src/game/client/hud.h @@ -313,9 +313,21 @@ class CHud bool m_bIsHTMLEnabled = false; int m_iFrameCount = 0; + int m_iCaps = -1; //!< Client caps written to _bhl, -1 before the first update + char m_szCaps[16] = {}; //!< m_iCaps as written to _bhl + int m_iCapsCheckFrame = 0; //!< Frame of the next check of _bhl in userinfo, 0 if none is pending + bool m_bCapsSetinfoSent = false; + bool m_bCapsCheckFailed = false; //!< _bhl can't be put into userinfo, don't retry until the caps change + void UpdateHudColors(); void UpdateSupportsCvar(); + //! Computes the client caps and writes them to _bhl (docs/scoreboard-protocol.md, 3.2) + void UpdateCapsUserinfo(); + + //! Compares _bhl in userinfo with the caps, retries once with setinfo + void CheckCapsUserinfo(); + //! Detects the maximum supported HUD scale. EHudScale DetectMaxHudScale(); diff --git a/src/game/client/hud/gungame_hud.cpp b/src/game/client/hud/gungame_hud.cpp new file mode 100644 index 00000000..816e1817 --- /dev/null +++ b/src/game/client/hud/gungame_hud.cpp @@ -0,0 +1,540 @@ +#include +#include +#include +#include +#include +#include +#include "hud.h" +#include "cl_util.h" +#include "pm_shared.h" +#include "hud/gungame_hud.h" +#include "vgui/client_viewport.h" +#include "vgui/score_panel_cells.h" +#include "hud_renderer.h" + +static constexpr int PHASE_WARMUP = 1; +static constexpr int PHASE_COUNTDOWN = 2; +static constexpr int PHASE_FINISHED = 3; + +//! Names longer than this (in code points) are cut +static constexpr int MAX_NAME_CHARS = 20; + +//! Right edge of the classic armor counter in widths of a digit: offset 10, suit icon 2, number 3 +static constexpr int ARMOR_RIGHT_DIGITS = 15; + +static constexpr int CIRCLE_TEXTURE_SIZE = 64; + +static constexpr wchar_t MARKER_LEFT[] = L"\u2039"; +static constexpr wchar_t MARKER_RIGHT[] = L"\u203A"; + +DEFINE_HUD_ELEM(CHudGunGamePanel); + +//! Removes color codes and cuts the name to MAX_NAME_CHARS code points +static void GetShortName(const char *name, wchar_t *buf, int bufSizeBytes) +{ + char clean[128]; + RemoveColorCodes(name, clean, sizeof(clean)); + + int chars = 0; + + for (char *c = clean; *c; c++) + { + if ((static_cast(*c) & 0xC0) != 0x80 && chars++ == MAX_NAME_CHARS) + { + Q_strncpy(c, "\xE2\x80\xA6", sizeof(clean) - (c - clean)); + break; + } + } + + Q_UTF8ToWString(clean, buf, bufSizeBytes, STRINGCONVERT_REPLACE); +} + +static int GetGlobalInt(const char *key) +{ + const CScoreboardData &data = CScoreboardData::Get(); + int value = 0; + + if (!data.GetGlobalValue(data.FindColumn(key)).GetNumber(value)) + return 0; + + return value; +} + +//! Creates a white anti-aliased disc or ring texture from columns [x0; x1) of the circle +static int CreateCircleTexture(bool ring, int x0, int x1) +{ + constexpr float radius = CIRCLE_TEXTURE_SIZE / 2.0f; + constexpr float ringWidth = CIRCLE_TEXTURE_SIZE / 6.0f; + int wide = x1 - x0; + std::vector rgba(wide * CIRCLE_TEXTURE_SIZE * 4, 255); + + for (int y = 0; y < CIRCLE_TEXTURE_SIZE; y++) + { + for (int x = x0; x < x1; x++) + { + float dist = std::hypot(x + 0.5f - radius, y + 0.5f - radius); + float alpha = clamp(radius - dist, 0.0f, 1.0f); + + if (ring) + alpha *= clamp(dist - (radius - ringWidth), 0.0f, 1.0f); + + rgba[(y * wide + x - x0) * 4 + 3] = static_cast(alpha * 255); + } + } + + int id = vgui2::surface()->CreateNewTextureID(true); + vgui2::surface()->DrawSetTextureRGBA(id, rgba.data(), wide, CIRCLE_TEXTURE_SIZE, true, false); + return id; +} + +static void DrawTexture(int id, int x, int y, int wide, int tall, Color color) +{ + vgui2::surface()->DrawSetTexture(id); + vgui2::surface()->DrawSetColor(color); + vgui2::surface()->DrawTexturedRect(x, y, x + wide, y + tall); +} + +CHudGunGamePanel::CHudGunGamePanel() + : vgui2::Panel(NULL, "HudGunGamePanel") +{ + SetParent(g_pViewport); + SetPaintBackgroundEnabled(true); + SetMouseInputEnabled(false); + SetKeyBoardInputEnabled(false); + SetVisible(false); +} + +bool CHudGunGamePanel::IsWidgetEnabled() +{ + return CScoreboardData::Get().IsGunGame() && CScoreboardData::IsGunGameHudEnabled(); +} + +int CHudGunGamePanel::GetLevelBarTop() +{ + CHudGunGamePanel *panel = Get(); + + if (!panel || panel->m_iLevelCount == 0) + return -1; + + int x, y; + panel->GetPos(x, y); + return y + panel->m_iBarY; +} + +int CHudGunGamePanel::GetLevelBarOffset() +{ + int barTop = GetLevelBarTop(); + + if (barTop == -1) + return 0; + + CHudGunGamePanel *panel = Get(); + int lineBottom = ScreenHeight - gHUD.m_iFontHeight / 2; + return max(0, lineBottom - barTop + panel->m_iCellGap); +} + +void CHudGunGamePanel::Init() +{ + m_iFlags |= HUD_ACTIVE; +} + +void CHudGunGamePanel::VidInit() +{ + m_iSpriteSerial = -1; +} + +void CHudGunGamePanel::Think() +{ + bool visible = UpdateState() && !g_pViewport->IsScoreBoardVisible(); + + if (IsVisible() != visible) + SetVisible(visible); + + // VGUI calls Think only while the panel is visible + if (visible) + m_iFlags &= ~HUD_ACTIVE; + else + m_iFlags |= HUD_ACTIVE; +} + +bool CHudGunGamePanel::UpdateState() +{ + m_iLevelCount = 0; + + if (!IsWidgetEnabled() || hud_draw.GetFloat() <= 0 || gHUD.m_iIntermission || (gHUD.m_iHideHUDDisplay & HIDEHUD_ALL)) + return false; + + CPlayerInfo *pi = nullptr; + + if (g_iUser1 == OBS_NONE) + pi = GetThisPlayerInfo(); + else if (g_iUser1 == OBS_IN_EYE) + pi = GetPlayerInfoSafe(g_iUser2); + + if (!pi || !pi->IsConnected() || pi->IsSpectator()) + return false; + + int phase = GetGlobalInt("phase"); + + if (phase == PHASE_FINISHED) + return false; + + const CScoreboardData &data = CScoreboardData::Get(); + int sortCol = data.GetFirstSortColumn(); + int team = pi->GetTeamNumber(); + + m_iTarget = pi->GetIndex(); + m_iTeam = (sortCol != -1 && team > 0 && !data.GetTeamValue(team, sortCol).IsEmpty()) ? team : 0; + m_wszTitle[0] = 0; + m_wszInfo[0] = 0; + m_iMeterMax = 0; + m_iInfoY = m_iPlaceY + vgui2::surface()->GetFontTall(m_LargeFont) + m_iLineGap; + m_iMeterY = m_iInfoY + vgui2::surface()->GetFontTall(m_TextFont) + m_iMeterGap; + + if (phase == PHASE_WARMUP || phase == PHASE_COUNTDOWN) + { + int left = max(GetGlobalInt("phase_left"), 0); + wchar_t time[16]; + + if (phase == PHASE_WARMUP) + { + V_snwprintf(time, std::size(time), L"%d:%02d", left / 60, left % 60); + ConstructScoreText(m_wszTitle, sizeof(m_wszTitle), "BHL_GG_Warmup", 1, time); + } + else + { + V_snwprintf(time, std::size(time), L"%d", left); + ConstructScoreText(m_wszTitle, sizeof(m_wszTitle), "BHL_GG_StartIn", 1, time); + } + + return true; + } + + UpdatePlace(); + + const CScoreboardData::Value &progress = GetCell("progress"); + + if (progress.type == bhl::sb::E_ValueType::Progress && progress.iMax > 0) + { + m_iMeterMax = progress.iMax; + m_iMeterCur = clamp(progress.iValue, 0, progress.iMax); + } + + UpdateLevelBar(); + return true; +} + +void CHudGunGamePanel::UpdatePlace() +{ + const CScoreboardData &data = CScoreboardData::Get(); + int sortCol = data.GetFirstSortColumn(); + + if (sortCol == -1) + return; + + bool teamplay = m_iTeam != 0; + int total = 0; + int place = teamplay ? data.GetTeamPlace(m_iTeam, &total) : data.GetPlayerPlace(m_iTarget, &total); + int value = 0; + const CScoreboardData::Value &ownValue = teamplay ? data.GetTeamValue(m_iTeam, sortCol) : data.GetPlayerValue(m_iTarget, sortCol); + + if (place == 0 || !ownValue.GetNumber(value)) + return; + + wchar_t placeText[16], totalText[16]; + V_snwprintf(placeText, std::size(placeText), L"%d", place); + V_snwprintf(totalText, std::size(totalText), L"%d", total); + ConstructScoreText(m_wszTitle, sizeof(m_wszTitle), "BHL_GG_Place", 2, placeText, totalText); + + // Nearest rival ahead and the gap to the best rival behind (docs/scoreboard-protocol.md, 8.2) + int sign = data.GetColumn(sortCol).IsSortAscending() ? -1 : 1; + int rivals = 0; + int ahead = 0; + int aheadGap = 0; + int behindGap = INT_MAX; + + auto fnCheckRival = [&](int id, const CScoreboardData::Value &rivalValue) { + int rival = 0; + + if (!rivalValue.GetNumber(rival)) + return; + + int gap = (rival - value) * sign; + rivals++; + + if (gap <= 0) + { + behindGap = min(behindGap, -gap); + return; + } + + bool isNearer = ahead == 0 || gap < aheadGap; + + if (!isNearer && gap == aheadGap) + isNearer = (teamplay ? data.CompareTeams(id, ahead) : data.ComparePlayers(id, ahead)) > 0; + + if (isNearer) + { + ahead = id; + aheadGap = gap; + } + }; + + if (teamplay) + { + bool hasPlayers[MAX_TEAMS + 1] = {}; + + for (int i = 1; i <= MAX_PLAYERS; i++) + { + CPlayerInfo *pi = GetPlayerInfoSafe(i); + + if (pi && !pi->IsSpectator()) + hasPlayers[pi->GetTeamNumber()] = true; + } + + for (int i = 1; i <= MAX_TEAMS; i++) + { + if (i != m_iTeam && hasPlayers[i]) + fnCheckRival(i, data.GetTeamValue(i, sortCol)); + } + } + else + { + for (int i = 1; i <= MAX_PLAYERS; i++) + { + CPlayerInfo *pi = GetPlayerInfoSafe(i); + + if (pi && i != m_iTarget && !pi->IsSpectator()) + fnCheckRival(i, data.GetPlayerValue(i, sortCol)); + } + } + + wchar_t kills[64]; + + if (rivals == 0) + { + ConstructScoreText(m_wszInfo, sizeof(m_wszInfo), "BHL_GG_Waiting", 0, nullptr); + } + else if (ahead != 0) + { + wchar_t name[64]; + GetShortName(teamplay ? GetTeamInfo(ahead)->GetDisplayName() : GetPlayerInfo(ahead)->GetDisplayName(), name, sizeof(name)); + FormatScoreKills(kills, sizeof(kills), max(aheadGap + 1, 1)); + ConstructScoreText(m_wszInfo, sizeof(m_wszInfo), "BHL_GG_Overtake", 2, name, kills); + } + else if (behindGap == 0) + { + ConstructScoreText(m_wszInfo, sizeof(m_wszInfo), "BHL_GG_Tied", 0, nullptr); + } + else + { + FormatScoreKills(kills, sizeof(kills), behindGap); + ConstructScoreText(m_wszInfo, sizeof(m_wszInfo), "BHL_GG_Lead", 1, kills); + } +} + +void CHudGunGamePanel::UpdateLevelBar() +{ + const CScoreboardData &data = CScoreboardData::Get(); + const CScoreboardData::Value &level = GetCell("level"); + const CScoreboardData::List *list = data.FindList("levels"); + int count = (list && list->iCount > 0) ? list->iCount : level.iMax; + + if (level.type != bhl::sb::E_ValueType::Progress || count <= 0) + return; + + if (m_iSpriteSerial != data.GetSerial()) + { + m_iSpriteSerial = data.GetSerial(); + + for (int i = 0; i < bhl::sb::MAX_LIST_ITEMS; i++) + { + bool hasIcon = list && i < list->iCount && list->items[i].type == bhl::sb::E_ValueType::Icon && list->items[i].szSprite[0]; + m_iSprites[i] = hasIcon ? gHUD.GetSpriteIndex(list->items[i].szSprite) : -1; + } + } + + m_iLevelCount = count; + m_iLevel = clamp(level.iValue - 1, 0, count - 1); + + // The bar stands between the armor and the ammo numbers. If it doesn't fit there, it moves above them. + int digitWide = gHUD.GetSpriteRect(gHUD.m_HUD_number_0).GetWidth(); + int freeWide = GetWide() - 2 * (ARMOR_RIGHT_DIGITS * digitWide + m_iCellGap); + int minWide = count * m_iCellMinWide + (count - 1) * m_iCellGap; + bool lifted = minWide > freeWide && freeWide < m_iBarMaxWide; + int maxWide = lifted ? m_iBarMaxWide : min(m_iBarMaxWide, freeWide); + + m_iBarCellWide = clamp((maxWide - (count - 1) * m_iCellGap) / count, m_iCellMinWide, m_iCellWide); + m_iBarFirst = 0; + m_iBarShown = count; + + if (minWide > maxWide) + { + int markerWide = vgui2::surface()->GetCharacterWidth(m_TextFont, MARKER_LEFT[0]) + m_iCellGap; + m_iBarShown = clamp((maxWide - 2 * markerWide + m_iCellGap) / max(m_iCellMinWide + m_iCellGap, 1), 1, count); + m_iBarFirst = clamp(m_iLevel - m_iBarShown / 2, 0, count - m_iBarShown); + } + + int lineTop = GetTall() - gHUD.m_iFontHeight - gHUD.m_iFontHeight / 2; + m_iBarX = (GetWide() - GetLevelBarWide()) / 2; + m_iBarY = lifted ? lineTop - m_iCellGap - m_iCellTall : lineTop + (gHUD.m_iFontHeight - m_iCellTall) / 2; +} + +const CScoreboardData::Value &CHudGunGamePanel::GetCell(const char *key) +{ + const CScoreboardData &data = CScoreboardData::Get(); + int col = data.FindColumn(key); + const CScoreboardData::Value &value = data.GetPlayerValue(m_iTarget, col); + + if (value.IsEmpty() && m_iTeam != 0) + return data.GetTeamValue(m_iTeam, col); + + return value; +} + +Color CHudGunGamePanel::GetColor(int alpha) +{ + Color color = gHUD.GetHudColor(HudPart::Common, 0); + return Color(color.r(), color.g(), color.b(), static_cast(clamp(alpha, 0, 255) * gHUD.GetHudTransparency())); +} + +int CHudGunGamePanel::GetMeterBarWide() +{ + return bhl::sb::MAX_DOTS * m_iDotSize + (bhl::sb::MAX_DOTS - 1) * m_iDotGap; +} + +int CHudGunGamePanel::GetLevelBarWide() +{ + return m_iBarShown * m_iBarCellWide + (m_iBarShown - 1) * m_iCellGap; +} + +void CHudGunGamePanel::DrawRoundedBar(int x, int y, int wide, Color color) +{ + int radius = m_iDotSize / 2; + wide = max(wide, 2 * radius); + + DrawTexture(m_iCapTextures[0], x, y, radius, m_iDotSize, color); + vgui2::surface()->DrawSetColor(color); + vgui2::surface()->DrawFilledRect(x + radius, y, x + wide - radius, y + m_iDotSize); + DrawTexture(m_iCapTextures[1], x + wide - radius, y, radius, m_iDotSize, color); +} + +void CHudGunGamePanel::DrawCenteredText(vgui2::HFont font, int y, const wchar_t *text, Color color) +{ + if (!text[0]) + return; + + int wide, tall; + vgui2::surface()->GetTextSize(font, text, wide, tall); + DrawCellText(font, (GetWide() - wide) / 2, y, color, text); +} + +void CHudGunGamePanel::PaintBackground() +{ + // HACK ALERT: Text is drawn in Paint(), see CHudDeathNoticePanel::Paint() + if (m_iDotTexture == -1) + { + m_iDotTexture = CreateCircleTexture(false, 0, CIRCLE_TEXTURE_SIZE); + m_iRingTexture = CreateCircleTexture(true, 0, CIRCLE_TEXTURE_SIZE); + m_iCapTextures[0] = CreateCircleTexture(false, 0, CIRCLE_TEXTURE_SIZE / 2); + m_iCapTextures[1] = CreateCircleTexture(false, CIRCLE_TEXTURE_SIZE / 2, CIRCLE_TEXTURE_SIZE); + } + + if (m_iMeterMax > bhl::sb::MAX_DOTS) + { + int wide = GetMeterBarWide(); + int x = (GetWide() - wide) / 2; + DrawRoundedBar(x, m_iMeterY, wide, GetColor(m_iAlphaDim)); + + if (m_iMeterCur > 0) + DrawRoundedBar(x, m_iMeterY, wide * m_iMeterCur / m_iMeterMax, GetColor(255)); + } + else if (m_iMeterMax > 0) + { + int x = (GetWide() - (m_iMeterMax * m_iDotSize + (m_iMeterMax - 1) * m_iDotGap)) / 2; + + for (int i = 0; i < m_iMeterMax; i++) + { + DrawTexture(i < m_iMeterCur ? m_iDotTexture : m_iRingTexture, x, m_iMeterY, m_iDotSize, m_iDotSize, GetColor(255)); + x += m_iDotSize + m_iDotGap; + } + } + + for (int i = 0; i < m_iBarShown && m_iLevelCount > 0; i++) + { + int level = m_iBarFirst + i; + int x = m_iBarX + i * (m_iBarCellWide + m_iCellGap); + int alpha = level < m_iLevel ? m_iAlphaPassed : (level == m_iLevel ? m_iAlphaCurrent : m_iAlphaFuture); + + vgui2::surface()->DrawSetColor(GetColor(alpha)); + vgui2::surface()->DrawFilledRect(x, m_iBarY, x + m_iBarCellWide, m_iBarY + m_iCellTall); + + if (level == m_iLevel) + { + vgui2::surface()->DrawSetColor(GetColor(255)); + vgui2::surface()->DrawOutlinedRect(x, m_iBarY, x + m_iBarCellWide, m_iBarY + m_iCellTall); + } + } + + if (m_iLevelCount == 0 || !CHudRenderer::Get().IsAvailable()) + return; + + for (int i = 0; i < m_iBarShown; i++) + { + int level = m_iBarFirst + i; + int sprite = level < bhl::sb::MAX_LIST_ITEMS ? m_iSprites[level] : -1; + + if (sprite == -1) + continue; + + const wrect_t &rc = gHUD.GetSpriteRect(sprite); + + if (rc.GetWidth() <= 0 || rc.GetHeight() <= 0) + continue; + + float scale = std::min(float(m_iBarCellWide - 2 * m_iIconPadding) / rc.GetWidth(), float(m_iCellTall - 2 * m_iIconPadding) / rc.GetHeight()); + int wide = static_cast(rc.GetWidth() * scale); + int tall = static_cast(rc.GetHeight() * scale); + + if (wide <= 0 || tall <= 0) + continue; + + int x = m_iBarX + i * (m_iBarCellWide + m_iCellGap) + (m_iBarCellWide - wide) / 2; + int y = m_iBarY + (m_iCellTall - tall) / 2; + Color color = GetColor(level > m_iLevel ? m_iAlphaDim : 255); + + CHudRenderer::SpriteSet(gHUD.GetSprite(sprite), color.r() * color.a() / 255, color.g() * color.a() / 255, color.b() * color.a() / 255); + CHudRenderer::SpriteDrawAdditiveScaled(0, x, y, wide, tall, &rc); + } +} + +void CHudGunGamePanel::Paint() +{ + Color color = GetColor(255); + + DrawCenteredText(m_LargeFont, m_iPlaceY, m_wszTitle, color); + DrawCenteredText(m_TextFont, m_iInfoY, m_wszInfo, color); + + int fontTall = vgui2::surface()->GetFontTall(m_TextFont); + + if (m_iMeterMax > bhl::sb::MAX_DOTS) + { + wchar_t counter[32]; + V_snwprintf(counter, std::size(counter), L"%d / %d", m_iMeterCur, m_iMeterMax); + DrawCellText(m_TextFont, (GetWide() + GetMeterBarWide()) / 2 + m_iCounterGap, m_iMeterY + (m_iDotSize - fontTall) / 2, color, counter); + } + + if (m_iLevelCount == 0) + return; + + int y = m_iBarY + (m_iCellTall - fontTall) / 2; + + if (m_iBarFirst > 0) + { + int markerWide = vgui2::surface()->GetCharacterWidth(m_TextFont, MARKER_LEFT[0]); + DrawCellText(m_TextFont, m_iBarX - m_iCellGap - markerWide, y, color, MARKER_LEFT); + } + + if (m_iBarFirst + m_iBarShown < m_iLevelCount) + DrawCellText(m_TextFont, m_iBarX + GetLevelBarWide() + m_iCellGap, y, color, MARKER_RIGHT); +} diff --git a/src/game/client/hud/gungame_hud.h b/src/game/client/hud/gungame_hud.h new file mode 100644 index 00000000..2609055a --- /dev/null +++ b/src/game/client/hud/gungame_hud.h @@ -0,0 +1,95 @@ +#ifndef HUD_GUNGAME_HUD_H +#define HUD_GUNGAME_HUD_H +#include +#include "hud/base.h" +#include "scoreboard_data.h" + +/** + * GunGame HUD widget: the place block at the top center and the level bar at the bottom center. + * Shows data of the scoreboard extension store (docs/scoreboard-protocol.md, 8.4). + */ +class CHudGunGamePanel : public CHudElemBase, public vgui2::Panel +{ +public: + DECLARE_CLASS_SIMPLE(CHudGunGamePanel, vgui2::Panel); + + CHudGunGamePanel(); + + //! True when the gungame preset is active and the widget is enabled in the settings + static bool IsWidgetEnabled(); + + //! Screen Y of the top edge of the level bar or -1 if there is no level bar + static int GetLevelBarTop(); + + //! How far the speedometer and jumpspeed at the bottom must move up to stay above the level bar + static int GetLevelBarOffset(); + + void Init() override; + void VidInit() override; + void Think() override; + void PaintBackground() override; + void Paint() override; + +private: + CPanelAnimationVarAliasType(int, m_iPlaceY, "place_ypos", "12", "proportional_int"); + CPanelAnimationVarAliasType(int, m_iLineGap, "line_gap", "2", "proportional_int"); + CPanelAnimationVarAliasType(int, m_iMeterGap, "meter_gap", "6", "proportional_int"); + CPanelAnimationVarAliasType(int, m_iDotSize, "dot_size", "7", "proportional_int"); + CPanelAnimationVarAliasType(int, m_iDotGap, "dot_gap", "3", "proportional_int"); + CPanelAnimationVarAliasType(int, m_iCounterGap, "counter_gap", "6", "proportional_int"); + CPanelAnimationVarAliasType(int, m_iCellWide, "cell_wide", "30", "proportional_int"); + CPanelAnimationVarAliasType(int, m_iCellMinWide, "cell_min_wide", "14", "proportional_int"); + CPanelAnimationVarAliasType(int, m_iCellTall, "cell_tall", "15", "proportional_int"); + CPanelAnimationVarAliasType(int, m_iCellGap, "cell_gap", "3", "proportional_int"); + CPanelAnimationVarAliasType(int, m_iIconPadding, "icon_padding", "2", "proportional_int"); + CPanelAnimationVarAliasType(int, m_iBarMaxWide, "bar_max_wide", "300", "proportional_int"); + + CPanelAnimationVar(int, m_iAlphaPassed, "alpha_passed", "112"); + CPanelAnimationVar(int, m_iAlphaCurrent, "alpha_current", "48"); + CPanelAnimationVar(int, m_iAlphaFuture, "alpha_future", "24"); + CPanelAnimationVar(int, m_iAlphaDim, "alpha_dim", "80"); + + CPanelAnimationVar(vgui2::HFont, m_LargeFont, "large_font", "GunGameHudLarge"); + CPanelAnimationVar(vgui2::HFont, m_TextFont, "text_font", "GunGameHudText"); + + int m_iTarget = 0; //!< Player whose data is shown + int m_iTeam = 0; //!< Team of the target if places are counted among teams, otherwise 0 + + wchar_t m_wszTitle[64] = {}; + wchar_t m_wszInfo[128] = {}; + int m_iInfoY = 0; + + int m_iMeterCur = 0; + int m_iMeterMax = 0; //!< 0 if the kills meter is hidden + int m_iMeterY = 0; + + int m_iLevelCount = 0; //!< 0 if the level bar is hidden + int m_iLevel = 0; //!< Current level, 0-based + int m_iBarFirst = 0; //!< First shown level + int m_iBarShown = 0; //!< Number of shown levels + int m_iBarX = 0; + int m_iBarY = 0; + int m_iBarCellWide = 0; + + int m_iSpriteSerial = -1; + int m_iSprites[bhl::sb::MAX_LIST_ITEMS] = {}; + + int m_iDotTexture = -1; + int m_iRingTexture = -1; + int m_iCapTextures[2] = { -1, -1 }; + + bool UpdateState(); + void UpdatePlace(); + void UpdateLevelBar(); + + //! Cell of the target or, if it is empty, of the target's team + const CScoreboardData::Value &GetCell(const char *key); + + Color GetColor(int alpha); + int GetMeterBarWide(); + int GetLevelBarWide(); + void DrawRoundedBar(int x, int y, int wide, Color color); + void DrawCenteredText(vgui2::HFont font, int y, const wchar_t *text, Color color); +}; + +#endif diff --git a/src/game/client/hud/jumpspeed.cpp b/src/game/client/hud/jumpspeed.cpp index 635762d5..1544cfd1 100644 --- a/src/game/client/hud/jumpspeed.cpp +++ b/src/game/client/hud/jumpspeed.cpp @@ -3,6 +3,7 @@ #include "cl_util.h" #include "parsemsg.h" #include "jumpspeed.h" +#include "hud/gungame_hud.h" extern ConVar hud_speedometer; extern ConVar hud_speedometer_below_cross; @@ -51,7 +52,7 @@ void CHudJumpspeed::Draw(float flTime) int y; if (!hud_jumpspeed_below_cross.GetBool()) { - y = ScreenHeight - gHUD.m_iFontHeight - gHUD.m_iFontHeight / 2; + y = ScreenHeight - gHUD.m_iFontHeight - gHUD.m_iFontHeight / 2 - CHudGunGamePanel::GetLevelBarOffset(); } else { diff --git a/src/game/client/hud/scores.cpp b/src/game/client/hud/scores.cpp index 9004cecf..da99aafc 100644 --- a/src/game/client/hud/scores.cpp +++ b/src/game/client/hud/scores.cpp @@ -25,6 +25,7 @@ #include "scores.h" #include "vgui/client_viewport.h" #include "hud/ag/ag_global.h" +#include "scoreboard_data.h" ConVar hud_scores("hud_scores", "0", FCVAR_BHL_ARCHIVE, "Maximum number of lines for HUD scoreboard, 0 to disable"); ConVar hud_scores_pos("hud_scores_pos", "30 50", FCVAR_BHL_ARCHIVE, "Position of HUD scoreboard, 'x y' in pixels"); @@ -32,6 +33,16 @@ ConVar hud_scores_alpha("hud_scores_alpha", "20", FCVAR_BHL_ARCHIVE, "Alpha of H DEFINE_HUD_ELEM(CHudScores); +//! Formats a line with the value of the Primary column of the scoreboard extension instead of frags +static void FormatPrimaryLine(char *buf, int bufSize, const CScoreboardData::Value &value, const char *name) +{ + wchar_t wszValue[64]; + char szValue[128]; + value.ToString(wszValue, sizeof(wszValue)); + Q_WStringToUTF8(wszValue, szValue, sizeof(szValue), STRINGCONVERT_REPLACE); + snprintf(buf, bufSize, "%-5s %s", szValue, name); +} + void CHudScores::Init() { m_iFlags |= HUD_ACTIVE; @@ -89,6 +100,9 @@ void CHudScores::Update() int iMaxLines = hud_scores.GetInt(); m_iLines = 0; + const CScoreboardData &sbData = CScoreboardData::Get(); + int iPrimaryCol = sbData.IsActive() ? sbData.FindPrimaryColumn() : -1; + if (gHUD.m_Teamplay) { std::fill(m_TeamData.begin(), m_TeamData.end(), TeamData()); @@ -131,6 +145,14 @@ void CHudScores::Update() // Sort teams based on the score std::sort(m_SortedTeamIDs.begin(), m_SortedTeamIDs.begin() + iTeamCount, [&](int ilhs, int irhs) { + if (iPrimaryCol != -1) + { + int cmp = sbData.CompareTeams(ilhs, irhs); + + if (cmp != 0) + return cmp < 0; + } + const TeamData &lhs = m_TeamData[ilhs]; const TeamData &rhs = m_TeamData[irhs]; @@ -157,7 +179,11 @@ void CHudScores::Update() TeamData &team = m_TeamData[teamIdx]; HudScoresData &data = m_ScoresData[m_iLines]; - snprintf(buf, sizeof(buf), "%-5i %s", team.iFrags, GetTeamInfo(teamIdx)->GetDisplayName()); + if (iPrimaryCol != -1) + FormatPrimaryLine(buf, sizeof(buf), sbData.GetTeamValue(teamIdx, iPrimaryCol), GetTeamInfo(teamIdx)->GetDisplayName()); + else + snprintf(buf, sizeof(buf), "%-5i %s", team.iFrags, GetTeamInfo(teamIdx)->GetDisplayName()); + Q_UTF8ToWString(buf, data.wszScore, sizeof(data.wszScore), STRINGCONVERT_REPLACE); data.color = g_pViewport->GetTeamColor(teamIdx); m_iLines++; @@ -180,6 +206,14 @@ void CHudScores::Update() // Sort players std::sort(m_SortedPlayerIDs.begin(), m_SortedPlayerIDs.begin() + iPlayerCount, [&](int ilhs, int irhs) { + if (iPrimaryCol != -1) + { + int cmp = sbData.ComparePlayers(ilhs, irhs); + + if (cmp != 0) + return cmp < 0; + } + CPlayerInfo *lhs = GetPlayerInfo(ilhs); CPlayerInfo *rhs = GetPlayerInfo(irhs); @@ -206,7 +240,11 @@ void CHudScores::Update() CPlayerInfo *pi = GetPlayerInfo(idx); HudScoresData &data = m_ScoresData[m_iLines]; - snprintf(buf, sizeof(buf), "%-5i %s", pi->GetFrags(), pi->GetDisplayName()); + if (iPrimaryCol != -1) + FormatPrimaryLine(buf, sizeof(buf), sbData.GetPlayerValue(idx, iPrimaryCol), pi->GetDisplayName()); + else + snprintf(buf, sizeof(buf), "%-5i %s", pi->GetFrags(), pi->GetDisplayName()); + Q_UTF8ToWString(buf, data.wszScore, sizeof(data.wszScore), STRINGCONVERT_REPLACE); data.color = gHUD.GetClientColor(idx, NoTeamColor::Orange); m_iLines++; diff --git a/src/game/client/hud/speedometer.cpp b/src/game/client/hud/speedometer.cpp index 842e2eef..436064ed 100644 --- a/src/game/client/hud/speedometer.cpp +++ b/src/game/client/hud/speedometer.cpp @@ -3,6 +3,7 @@ #include "cl_util.h" #include "parsemsg.h" #include "speedometer.h" +#include "hud/gungame_hud.h" extern ConVar hud_jumpspeed; extern ConVar hud_jumpspeed_below_cross; @@ -59,7 +60,7 @@ void CHudSpeedometer::Draw(float time) if (hud_jumpspeed.GetBool() && !hud_jumpspeed_below_cross.GetBool()) yoffset = gHUD.m_iFontHeight; - y = ScreenHeight - gHUD.m_iFontHeight - gHUD.m_iFontHeight / 2 - yoffset; + y = ScreenHeight - gHUD.m_iFontHeight - gHUD.m_iFontHeight / 2 - yoffset - CHudGunGamePanel::GetLevelBarOffset(); } if (hud_draw.GetFloat() > 0) diff --git a/src/game/client/hud/statusbar.cpp b/src/game/client/hud/statusbar.cpp index 64cdfedd..9de20536 100644 --- a/src/game/client/hud/statusbar.cpp +++ b/src/game/client/hud/statusbar.cpp @@ -28,6 +28,7 @@ #include "statusbar.h" #include "text_message.h" #include "vgui/client_viewport.h" +#include "hud/gungame_hud.h" #ifdef _TFC #define STATUSBAR_ID_LINE 2 @@ -193,6 +194,7 @@ void CHudStatusBar::Draw(float fTime) // Allow to change status bar position when using custom HUD to avoid overlapping int Y_START = hud_custom.GetBool() ? g_pViewport->GetStatusBarYPos() : ScreenHeight - 52; + int levelBarTop = CHudGunGamePanel::GetLevelBarTop(); // Draw the status bar lines for (int i = 0; i < MAX_STATUSBAR_LINES; i++) @@ -203,6 +205,10 @@ void CHudStatusBar::Draw(float fTime) int x = 8; int y = Y_START - (4 + TextHeight * i); // draw along bottom of screen + // Keep the lines above the GunGame level bar + if (levelBarTop != -1) + y = min(y, levelBarTop - TextHeight * (i + 1)); + // let user set status ID bar centering if ((i == STATUSBAR_ID_LINE) && hud_centerid.GetBool()) { diff --git a/src/game/client/hud/timer.cpp b/src/game/client/hud/timer.cpp index e38ff4e9..2fe2c15c 100644 --- a/src/game/client/hud/timer.cpp +++ b/src/game/client/hud/timer.cpp @@ -19,6 +19,7 @@ #include "net.h" #include "demo.h" #include "demo_api.h" +#include "hud/gungame_hud.h" #define NET_API gEngfuncs.pNetAPI @@ -556,6 +557,8 @@ void CHudTimer::Draw(float fTime) if (gHUD.m_iHideHUDDisplay & HIDEHUD_ALL) return; + bool hidden = CHudGunGamePanel::IsWidgetEnabled(); + // We will take time from demo stream if playingback float currentTime; if (gEngfuncs.pDemoAPI->IsPlayingback()) @@ -578,7 +581,7 @@ void CHudTimer::Draw(float fTime) // Draw timer float timeleft = m_flSynced ? (int)(m_flEndTime - currentTime) + 1 : (int)(m_flEndTime - m_flEffectiveTime); - int hud_timer = (int)m_pCvarHudTimer->value; + int hud_timer = hidden ? 0 : (int)m_pCvarHudTimer->value; int ypos = ScreenHeight * TIMER_Y; switch (hud_timer) { @@ -603,7 +606,7 @@ void CHudTimer::Draw(float fTime) } // Draw next map - int hud_nextmap = (int)m_pCvarHudNextmap->value; + int hud_nextmap = hidden ? 0 : (int)m_pCvarHudNextmap->value; if (m_szNextmap[0] && timeleft < 60 && timeleft >= 0 && m_flEndTime > 0 && (hud_nextmap == 2 || (hud_nextmap == 1 && timeleft >= 37))) { snprintf(text, sizeof(text), "Nextmap is %s", m_szNextmap); @@ -627,6 +630,9 @@ void CHudTimer::Draw(float fTime) } else if (m_flCustomTimerEnd[i] > currentTime) { + if (hidden) + continue; + timeleft = (int)(m_flCustomTimerEnd[i] - currentTime) + 1; sprintf(text, "Timer %d", (int)timeleft); // Output to screen diff --git a/src/game/client/hud_renderer.cpp b/src/game/client/hud_renderer.cpp index cd104601..7289ce8e 100644 --- a/src/game/client/hud_renderer.cpp +++ b/src/game/client/hud_renderer.cpp @@ -52,7 +52,12 @@ void CHudRenderer::SpriteDrawAdditive(int frame, int x, int y, const wrect_t *pr s_Instance.DrawSprite(frame, x, y, -1, -1, prc, SpriteDrawMode::Additive); } -void CHudRenderer::DrawSprite(int frame, float x, float y, float width, float height, const wrect_t *prc, SpriteDrawMode mode) +void CHudRenderer::SpriteDrawAdditiveScaled(int frame, int x, int y, int width, int height, const wrect_t *prc) +{ + s_Instance.DrawSprite(frame, x, y, -1, -1, prc, SpriteDrawMode::Additive, width, height); +} + +void CHudRenderer::DrawSprite(int frame, float x, float y, float width, float height, const wrect_t *prc, SpriteDrawMode mode, float outWidth, float outHeight) { if (m_hPic <= 0) { @@ -98,6 +103,12 @@ void CHudRenderer::DrawSprite(int frame, float x, float y, float width, float he s[1] = t[1] = 1.0f; } + if (outWidth > 0 && outHeight > 0) + { + width = outWidth; + height = outHeight; + } + const model_t *spriteModel = gEngfuncs.GetSpritePointer(m_hPic); if (!spriteModel) diff --git a/src/game/client/hud_renderer.h b/src/game/client/hud_renderer.h index 8031768c..d1811376 100644 --- a/src/game/client/hud_renderer.h +++ b/src/game/client/hud_renderer.h @@ -14,6 +14,9 @@ class CHudRenderer static void SpriteDraw(int frame, int x, int y, const wrect_t *prc); static void SpriteDrawAdditive(int frame, int x, int y, const wrect_t *prc); + //! Draws the sprite rectangle stretched to width x height + static void SpriteDrawAdditiveScaled(int frame, int x, int y, int width, int height, const wrect_t *prc); + private: enum class SpriteDrawMode { @@ -24,7 +27,7 @@ class CHudRenderer HSPRITE m_hPic = 0; uint8_t m_SpriteColor[4]; - void DrawSprite(int frame, float x, float y, float width, float height, const wrect_t *prc, SpriteDrawMode mode); + void DrawSprite(int frame, float x, float y, float width, float height, const wrect_t *prc, SpriteDrawMode mode, float outWidth = -1, float outHeight = -1); }; #endif diff --git a/src/game/client/scoreboard_data.cpp b/src/game/client/scoreboard_data.cpp new file mode 100644 index 00000000..2032be7c --- /dev/null +++ b/src/game/client/scoreboard_data.cpp @@ -0,0 +1,1060 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include "hud.h" +#include "cl_util.h" +#include "scoreboard_data.h" + +using namespace bhl::sb; + +static_assert(TARGET_PLAYER_LAST - TARGET_PLAYER_FIRST + 1 <= MAX_PLAYERS, "player targets must fit m_PlayerValues"); +static_assert(TARGET_TEAM_LAST - TARGET_TEAM_BASE <= MAX_TEAMS, "team targets must fit m_TeamValues"); + +ConVar hud_scoreboard_custom("hud_scoreboard_custom", "1", FCVAR_ARCHIVE, "Show the custom scoreboard when the server provides one"); +ConVar hud_gungame("hud_gungame", "1", FCVAR_BHL_ARCHIVE, "Show the GunGame HUD (requires hud_scoreboard_custom 1)"); + +CON_COMMAND(hud_scoreboard_dump, "Prints the custom scoreboard data to the console") +{ + CScoreboardData::Get().DumpCommand(); +} + +CON_COMMAND(hud_scoreboard_test, "Fills the custom scoreboard with test data: hud_scoreboard_test [preset|off] [phase] [phase_left]") +{ + CScoreboardData::Get().TestCommand(); +} + +namespace +{ + +//! Reads the payload of a BhlScore message and tracks the remaining size +class CMsgReader +{ +public: + CMsgReader(const void *pBuf, int iSize) + : m_pBuf(static_cast(pBuf)) + , m_iSize(iSize) + { + } + + int GetRemaining() const + { + return m_iSize - m_iPos; + } + + bool ReadByte(int &out) + { + if (GetRemaining() < 1) + return false; + + out = m_pBuf[m_iPos]; + m_iPos++; + return true; + } + + bool ReadChar(int &out) + { + if (!ReadByte(out)) + return false; + + out = static_cast(out); + return true; + } + + bool ReadWord(int &out) + { + if (GetRemaining() < 2) + return false; + + out = m_pBuf[m_iPos] | (m_pBuf[m_iPos + 1] << 8); + m_iPos += 2; + return true; + } + + bool ReadShort(int &out) + { + if (!ReadWord(out)) + return false; + + out = static_cast(out); + return true; + } + + bool ReadLong(int &out) + { + if (GetRemaining() < 4) + return false; + + unsigned int value = 0; + + for (int i = 3; i >= 0; i--) + value = (value << 8) | m_pBuf[m_iPos + i]; + + out = static_cast(value); + m_iPos += 4; + return true; + } + + //! Reads a NUL-terminated string, truncates it to the buffer and strips color codes. + //! Returns false if the payload ends before the terminator. + bool ReadString(char *buf, int bufSize) + { + int len = 0; + bool bTruncated = false; + bool bTerminated = false; + + while (GetRemaining() > 0) + { + char c = static_cast(m_pBuf[m_iPos]); + m_iPos++; + + if (c == '\0') + { + bTerminated = true; + break; + } + + if (len < bufSize - 1) + buf[len++] = c; + else + bTruncated = true; + } + + buf[len] = '\0'; + + if (bTruncated) + Q_UnicodeRepair(buf, STRINGCONVERT_SKIP); + + RemoveColorCodesInPlace(buf); + return bTerminated; + } + + template + bool ReadString(char (&buf)[N]) + { + return ReadString(buf, N); + } + + //! Returns a reader of the next len bytes and skips them. len must not exceed GetRemaining(). + CMsgReader ReadBlock(int len) + { + CMsgReader block(m_pBuf + m_iPos, len); + m_iPos += len; + return block; + } + +private: + const unsigned char *m_pBuf = nullptr; + int m_iSize = 0; + int m_iPos = 0; +}; + +const CScoreboardData::Value s_EmptyValue = CScoreboardData::Value(); +const CScoreboardData::Column s_EmptyColumn = CScoreboardData::Column(); + +/** + * Reads "type len payload". + * A value of an unknown type, with a wrong len or a broken payload is returned empty. + * @param type Receives the type byte + * @return false if the message ends inside the value + */ +bool ReadValue(CMsgReader &reader, CScoreboardData::Value &value, int &type) +{ + int len = 0; + value = CScoreboardData::Value(); + + if (!reader.ReadByte(type) || !reader.ReadByte(len) || len > reader.GetRemaining()) + return false; + + CMsgReader payload = reader.ReadBlock(len); + bool bValid = false; + + switch (static_cast(type)) + { + case E_ValueType::Int: + if (len == 1) + bValid = payload.ReadChar(value.iValue); + else if (len == 2) + bValid = payload.ReadShort(value.iValue); + else if (len == 4) + bValid = payload.ReadLong(value.iValue); + break; + case E_ValueType::Text: + bValid = len <= MAX_TEXT_LEN + 1 && payload.ReadString(value.szText); + break; + case E_ValueType::Icon: + bValid = len <= 2 * (MAX_TEXT_LEN + 1) && payload.ReadString(value.szSprite) && payload.ReadString(value.szText); + break; + case E_ValueType::Progress: + if (len == 2) + bValid = payload.ReadByte(value.iValue) && payload.ReadByte(value.iMax); + else if (len == 4) + bValid = payload.ReadWord(value.iValue) && payload.ReadWord(value.iMax); + break; + default: + break; + } + + if (bValid) + value.type = static_cast(type); + else + value = CScoreboardData::Value(); + + return true; +} + +void ClearValues(CScoreboardData::Value *values) +{ + for (int i = 0; i < MAX_COLUMNS; i++) + values[i] = CScoreboardData::Value(); +} + +//! Returns < 0 if a goes before b. Empty values go after filled ones in both directions. +int CompareValues(const CScoreboardData::Value &a, const CScoreboardData::Value &b, bool bAscending) +{ + if (a.IsEmpty() || b.IsEmpty()) + return static_cast(a.IsEmpty()) - static_cast(b.IsEmpty()); + + int numA = 0; + int numB = 0; + bool bIsNumA = a.GetNumber(numA); + bool bIsNumB = b.GetNumber(numB); + int result = 0; + + if (bIsNumA != bIsNumB) + return bIsNumA ? -1 : 1; + + if (bIsNumA) + { + result = (numA > numB) - (numA < numB); + } + else + { + result = Q_stricmp(a.szText, b.szText); + + if (result == 0) + result = Q_stricmp(a.szSprite, b.szSprite); + } + + return bAscending ? result : -result; +} + +bool IsParticipant(int client) +{ + CPlayerInfo *pi = GetPlayerInfo(client); + return pi->IsConnected() && !pi->IsSpectator(); +} + +void ValueToDebugString(const CScoreboardData::Value &value, char *buf, int bufSize) +{ + switch (value.type) + { + case E_ValueType::Int: + snprintf(buf, bufSize, "%d", value.iValue); + break; + case E_ValueType::Text: + snprintf(buf, bufSize, "\"%s\"", value.szText); + break; + case E_ValueType::Icon: + snprintf(buf, bufSize, "%s \"%s\"", value.szSprite, value.szText); + break; + case E_ValueType::Progress: + snprintf(buf, bufSize, "%d/%d", value.iValue, value.iMax); + break; + default: + snprintf(buf, bufSize, "-"); + break; + } +} + +CScoreboardData::Value MakeInt(int n) +{ + CScoreboardData::Value value; + value.type = E_ValueType::Int; + value.iValue = n; + return value; +} + +CScoreboardData::Value MakeProgress(int cur, int max) +{ + CScoreboardData::Value value; + value.type = E_ValueType::Progress; + value.iValue = cur; + value.iMax = max; + return value; +} + +CScoreboardData::Value MakeIcon(const char *sprite, const char *text) +{ + CScoreboardData::Value value; + value.type = E_ValueType::Icon; + V_strcpy_safe(value.szSprite, sprite); + V_strcpy_safe(value.szText, text); + return value; +} + +CScoreboardData s_ScoreboardData; + +} + +//----------------------------------------------------- +// Value, Column +//----------------------------------------------------- +bool CScoreboardData::Value::IsEmpty() const +{ + return type == E_ValueType::None; +} + +bool CScoreboardData::Value::GetNumber(int &out) const +{ + if (type != E_ValueType::Int && type != E_ValueType::Progress) + return false; + + out = iValue; + return true; +} + +void CScoreboardData::Value::ToString(wchar_t *buf, int bufSizeBytes) const +{ + int bufLen = bufSizeBytes / static_cast(sizeof(wchar_t)); + + if (bufLen <= 0) + return; + + switch (type) + { + case E_ValueType::Int: + V_snwprintf(buf, bufLen, L"%d", iValue); + break; + case E_ValueType::Text: + LocalizeString(szText, buf, bufSizeBytes); + break; + case E_ValueType::Icon: + GetIconName(*this, buf, bufSizeBytes); + break; + case E_ValueType::Progress: + if (iMax == 0) + V_snwprintf(buf, bufLen, L"%d", iValue); + else + V_snwprintf(buf, bufLen, L"%d/%d", iValue, iMax); + break; + default: + buf[0] = L'\0'; + break; + } +} + +int CScoreboardData::Column::GetAlign() const +{ + int align = (static_cast(flags) >> 1) & 3; + return align == 3 ? 0 : align; +} + +//----------------------------------------------------- +// CScoreboardData +//----------------------------------------------------- +CScoreboardData &CScoreboardData::Get() +{ + return s_ScoreboardData; +} + +CScoreboardData::CScoreboardData() = default; + +void CScoreboardData::Init() +{ + ::HookMessage(MSG_NAME, [](const char *pszName, int iSize, void *pbuf) { + return CScoreboardData::Get().MsgFunc_BhlScore(pszName, iSize, pbuf); + }); +} + +void CScoreboardData::VidInit() +{ + Clear(); + std::fill(std::begin(m_bPlayerConnected), std::end(m_bPlayerConnected), false); +} + +void CScoreboardData::Frame() +{ + for (int i = 1; i <= MAX_PLAYERS; i++) + { + bool bIsConnected = GetPlayerInfo(i)->IsConnected(); + + if (m_bPlayerConnected[i] && !bIsConnected) + { + ClearValues(m_PlayerValues[i]); + m_iSerial++; + } + + m_bPlayerConnected[i] = bIsConnected; + } +} + +bool CScoreboardData::IsCustomEnabled() +{ + return hud_scoreboard_custom.GetBool(); +} + +bool CScoreboardData::IsGunGameHudEnabled() +{ + return IsCustomEnabled() && hud_gungame.GetBool(); +} + +bool CScoreboardData::IsActive() const +{ + return m_bConfigReceived && IsCustomEnabled(); +} + +bool CScoreboardData::IsGunGame() const +{ + return IsActive() && !Q_stricmp(m_szPreset, "gungame"); +} + +bool CScoreboardData::IsStdColumnHidden(E_ConfigFlags flag) const +{ + return IsActive() && IsEnumFlagSet(m_ConfigFlags, flag); +} + +const CScoreboardData::Column &CScoreboardData::GetColumn(int id) const +{ + if (id < 0 || id >= MAX_COLUMNS) + return s_EmptyColumn; + + return m_Columns[id]; +} + +int CScoreboardData::FindColumn(const char *key) const +{ + for (int i = 0; i < MAX_COLUMNS; i++) + { + if (m_Columns[i].bValid && !strcmp(m_Columns[i].szKey, key)) + return i; + } + + return -1; +} + +int CScoreboardData::FindPrimaryColumn() const +{ + for (int i = 0; i < MAX_COLUMNS; i++) + { + if (m_Columns[i].bValid && m_Columns[i].IsPrimary()) + return i; + } + + return -1; +} + +int CScoreboardData::GetFirstSortColumn() const +{ + return m_iSortColumnCount > 0 ? m_SortColumns[0] : -1; +} + +const CScoreboardData::Value &CScoreboardData::GetGlobalValue(int col) const +{ + if (col < 0 || col >= MAX_COLUMNS) + return s_EmptyValue; + + return m_GlobalValues[col]; +} + +const CScoreboardData::Value &CScoreboardData::GetPlayerValue(int client, int col) const +{ + if (client < 1 || client > MAX_PLAYERS || col < 0 || col >= MAX_COLUMNS || !GetPlayerInfo(client)->IsConnected()) + return s_EmptyValue; + + return m_PlayerValues[client][col]; +} + +const CScoreboardData::Value &CScoreboardData::GetTeamValue(int team, int col) const +{ + if (team < 1 || team > MAX_TEAMS || col < 0 || col >= MAX_COLUMNS) + return s_EmptyValue; + + return m_TeamValues[team][col]; +} + +const CScoreboardData::List *CScoreboardData::FindList(const char *key) const +{ + for (const List &list : m_Lists) + { + if (list.bValid && !strcmp(list.szKey, key)) + return &list; + } + + return nullptr; +} + +int CScoreboardData::ComparePlayers(int a, int b) const +{ + for (int i = 0; i < m_iSortColumnCount; i++) + { + int col = m_SortColumns[i]; + int result = CompareValues(GetPlayerValue(a, col), GetPlayerValue(b, col), m_Columns[col].IsSortAscending()); + + if (result != 0) + return result; + } + + return 0; +} + +int CScoreboardData::CompareTeams(int a, int b) const +{ + for (int i = 0; i < m_iSortColumnCount; i++) + { + int col = m_SortColumns[i]; + int result = CompareValues(GetTeamValue(a, col), GetTeamValue(b, col), m_Columns[col].IsSortAscending()); + + if (result != 0) + return result; + } + + return 0; +} + +int CScoreboardData::GetPlayerPlace(int client, int *pTotal) const +{ + int col = GetFirstSortColumn(); + const Value &value = GetPlayerValue(client, col); + bool bAscending = GetColumn(col).IsSortAscending(); + int total = 0; + int ahead = 0; + + for (int i = 1; i <= MAX_PLAYERS; i++) + { + if (!IsParticipant(i)) + continue; + + total++; + + if (CompareValues(GetPlayerValue(i, col), value, bAscending) < 0) + ahead++; + } + + if (pTotal) + *pTotal = total; + + if (value.IsEmpty() || !IsParticipant(client)) + return 0; + + return ahead + 1; +} + +int CScoreboardData::GetTeamPlace(int team, int *pTotal) const +{ + bool bHasParticipants[MAX_TEAMS + 1] = {}; + + for (int i = 1; i <= MAX_PLAYERS; i++) + { + if (!IsParticipant(i)) + continue; + + int playerTeam = GetPlayerInfo(i)->GetTeamNumber(); + + if (playerTeam >= 1 && playerTeam <= MAX_TEAMS) + bHasParticipants[playerTeam] = true; + } + + int col = GetFirstSortColumn(); + const Value &value = GetTeamValue(team, col); + bool bAscending = GetColumn(col).IsSortAscending(); + int total = 0; + int ahead = 0; + + for (int i = 1; i <= MAX_TEAMS; i++) + { + if (!bHasParticipants[i]) + continue; + + total++; + + if (CompareValues(GetTeamValue(i, col), value, bAscending) < 0) + ahead++; + } + + if (pTotal) + *pTotal = total; + + if (value.IsEmpty() || !bHasParticipants[team]) + return 0; + + return ahead + 1; +} + +const char *CScoreboardData::GetPluralSuffix(int n) +{ + const wchar_t *rule = g_pVGuiLocalize->Find("BHL_PluralRule"); + n = abs(n); + + if (rule && !wcscmp(rule, L"ru")) + { + if (n % 10 == 1 && n % 100 != 11) + return "One"; + + if (n % 10 >= 2 && n % 10 <= 4 && (n % 100 < 12 || n % 100 > 14)) + return "Few"; + + return "Many"; + } + + return n == 1 ? "One" : "Many"; +} + +void CScoreboardData::LocalizeString(const char *str, wchar_t *buf, int bufSizeBytes) +{ + if (str[0] == '#' && str[1]) + { + const wchar_t *localized = g_pVGuiLocalize->Find(str); + + if (localized) + { + V_wcsncpy(buf, localized, bufSizeBytes); + return; + } + + str++; + } + + Q_UTF8ToWString(str, buf, bufSizeBytes, STRINGCONVERT_REPLACE); +} + +void CScoreboardData::GetIconName(const Value &value, wchar_t *buf, int bufSizeBytes) +{ + if (!strncmp(value.szSprite, "d_", 2)) + { + char token[64]; + snprintf(token, sizeof(token), "BHL_Weapon_%s", value.szSprite + 2); + const wchar_t *name = g_pVGuiLocalize->Find(token); + + if (name) + { + V_wcsncpy(buf, name, bufSizeBytes); + return; + } + } + + LocalizeString(value.szText, buf, bufSizeBytes); +} + +void CScoreboardData::DumpCommand() +{ + ConPrintf("Scoreboard: active %d, config %d, hud_scoreboard_custom %d, hud_gungame %d, serial %d\n", + IsActive(), m_bConfigReceived, IsCustomEnabled(), IsGunGameHudEnabled(), m_iSerial); + ConPrintf("Config: flags 0x%x, preset \"%s\", title \"%s\", tag \"%s\"\n", + static_cast(m_ConfigFlags), m_szPreset, m_szTitle, m_szTag); + + ConPrintf("Columns:\n"); + + for (int i = 0; i < MAX_COLUMNS; i++) + { + const Column &column = m_Columns[i]; + + if (column.bValid) + { + ConPrintf(" %2d: key \"%s\", title \"%s\", display %d, flags 0x%x, width %d, sort 0x%02x\n", + i, column.szKey, column.szTitle, static_cast(column.display), static_cast(column.flags), column.iWidth, column.iSort); + } + } + + auto fnPrintCells = [this](const char *target, const Value *values) { + bool bHasHeader = false; + + for (int i = 0; i < MAX_COLUMNS; i++) + { + if (values[i].IsEmpty()) + continue; + + if (!bHasHeader) + { + ConPrintf("%s:\n", target); + bHasHeader = true; + } + + char buf[128]; + ValueToDebugString(values[i], buf, sizeof(buf)); + ConPrintf(" %2d %-15s %s\n", i, m_Columns[i].szKey, buf); + } + }; + + fnPrintCells("Whole game", m_GlobalValues); + + for (int i = 1; i <= MAX_PLAYERS; i++) + { + CPlayerInfo *pi = GetPlayerInfo(i); + char target[128]; + snprintf(target, sizeof(target), "Player %d \"%s\"", i, pi->IsConnected() ? pi->GetDisplayName(true) : "(disconnected)"); + fnPrintCells(target, m_PlayerValues[i]); + } + + for (int i = 1; i <= MAX_TEAMS; i++) + { + char target[128]; + snprintf(target, sizeof(target), "Team %d \"%s\"", i, GetTeamInfo(i)->GetDisplayName()); + fnPrintCells(target, m_TeamValues[i]); + } + + ConPrintf("Lists:\n"); + + for (int i = 0; i < MAX_LISTS; i++) + { + const List &list = m_Lists[i]; + + if (!list.bValid) + continue; + + ConPrintf(" %d: key \"%s\", %d items\n", i, list.szKey, list.iCount); + + for (int j = 0; j < list.iCount; j++) + { + char buf[128]; + ValueToDebugString(list.items[j], buf, sizeof(buf)); + ConPrintf(" %2d: %s\n", j, buf); + } + } +} + +void CScoreboardData::TestCommand() +{ + const char *preset = gEngfuncs.Cmd_Argc() >= 2 ? gEngfuncs.Cmd_Argv(1) : "gungame"; + + Clear(); + + if (!strcmp(preset, "off")) + { + ConPrintf("Scoreboard test data removed.\n"); + return; + } + + enum + { + COL_RANK = 0, + COL_LEVEL, + COL_WEAPON, + COL_PROGRESS, + COL_KILLS, + COL_DEATHS, + COL_SCORE, + COL_PHASE, + COL_PHASE_LEFT, + }; + + struct TestColumn + { + const char *pszKey; + const char *pszTitle; + E_Display display; + int iWidth; + int iSort; + E_ColumnFlags flags; + }; + + static const TestColumn s_Columns[] = { + { "rank", "", E_Display::Builtin, 0, 0, E_ColumnFlags::None }, + { "level", "#BHL_SB_Level", E_Display::Steps, 60, 0, E_ColumnFlags::Primary }, + { "weapon", "#BHL_SB_Weapon", E_Display::Icon, 120, 0, E_ColumnFlags::None }, + { "progress", "#BHL_SB_Progress", E_Display::Meter, 90, 0, E_ColumnFlags::None }, + { "kills", "#BHL_SB_Kills", E_Display::Text, 60, 2, E_ColumnFlags::AlignRight }, + { "deaths", "", E_Display::Builtin, 0, 0, E_ColumnFlags::AlignRight }, + { "score", "", E_Display::Text, 0, 1, E_ColumnFlags::Hidden }, + { "phase", "", E_Display::Text, 0, 0, E_ColumnFlags::Hidden }, + { "phase_left", "", E_Display::Text, 0, 0, E_ColumnFlags::Hidden }, + }; + + struct TestLevel + { + const char *pszSprite; + const char *pszName; + int iKills; + }; + + static const TestLevel s_Levels[] = { + { "d_9mmhandgun", "Glock", 2 }, + { "d_357", "Python", 2 }, + { "d_9mmAR", "MP5", 3 }, + { "d_shotgun", "Shotgun", 2 }, + { "d_crossbow", "Crossbow", 2 }, + { "d_rpg_rocket", "RPG", 2 }, + { "d_gauss", "Gauss", 2 }, + { "d_egon", "Egon", 12 }, + { "d_hornet", "Hornet", 2 }, + { "d_snark", "Snark", 2 }, + { "d_tripmine", "Tripmine", 1 }, + { "d_satchel", "Satchel", 1 }, + { "d_grenade", "Grenade", 1 }, + { "d_crowbar", "Crowbar", 1 }, + }; + + constexpr int LEVEL_COUNT = static_cast(std::size(s_Levels)); + + m_bConfigReceived = true; + m_ConfigFlags = static_cast(static_cast(E_ConfigFlags::HideFrags) | static_cast(E_ConfigFlags::HideEff) | static_cast(E_ConfigFlags::HideSteamID)); + V_strcpy_safe(m_szPreset, preset); + V_strcpy_safe(m_szTitle, "GUNGAME"); + V_strcpy_safe(m_szTag, gHUD.m_Teamplay ? "TEAM" : "FFA"); + + for (int i = 0; i < static_cast(std::size(s_Columns)); i++) + { + Column &column = m_Columns[i]; + column.bValid = true; + column.display = s_Columns[i].display; + column.flags = s_Columns[i].flags; + column.iWidth = s_Columns[i].iWidth; + column.iSort = s_Columns[i].iSort; + V_strcpy_safe(column.szKey, s_Columns[i].pszKey); + V_strcpy_safe(column.szTitle, s_Columns[i].pszTitle); + } + + UpdateSortColumns(); + + List &levels = m_Lists[0]; + levels.bValid = true; + levels.iCount = LEVEL_COUNT; + V_strcpy_safe(levels.szKey, "levels"); + + for (int i = 0; i < LEVEL_COUNT; i++) + levels.items[i] = MakeIcon(s_Levels[i].pszSprite, s_Levels[i].pszName); + + m_GlobalValues[COL_PHASE] = MakeInt(gEngfuncs.Cmd_Argc() >= 3 ? atoi(gEngfuncs.Cmd_Argv(2)) : 0); + m_GlobalValues[COL_PHASE_LEFT] = MakeInt(gEngfuncs.Cmd_Argc() >= 4 ? atoi(gEngfuncs.Cmd_Argv(3)) : 0); + + int playerCount = 0; + + for (int i = 1; i <= MAX_PLAYERS; i++) + { + CPlayerInfo *pi = GetPlayerInfoSafe(i); + + if (!pi) + continue; + + // The first player is on the last level, the third and the fourth are tied + int seed = playerCount == 3 ? 2 : playerCount; + int level = LEVEL_COUNT - 1 - (seed * 3) % LEVEL_COUNT; + int kills = seed % s_Levels[level].iKills; + int score = kills; + + for (int j = 0; j < level; j++) + score += s_Levels[j].iKills; + + Value *values = m_PlayerValues[i]; + values[COL_LEVEL] = MakeProgress(level + 1, LEVEL_COUNT); + values[COL_WEAPON] = levels.items[level]; + values[COL_PROGRESS] = MakeProgress(kills, s_Levels[level].iKills); + values[COL_KILLS] = MakeInt(score + seed % 3); + values[COL_SCORE] = MakeInt(score); + + int team = pi->GetTeamNumber(); + + if (team >= 1 && team <= MAX_TEAMS && CompareValues(values[COL_SCORE], m_TeamValues[team][COL_SCORE], false) < 0) + std::copy(values, values + MAX_COLUMNS, m_TeamValues[team]); + + playerCount++; + } + + m_iSerial++; + ConPrintf("Scoreboard test data: %d players, preset \"%s\".\n", playerCount, m_szPreset); +} + +void CScoreboardData::Clear() +{ + m_bConfigReceived = false; + m_ConfigFlags = E_ConfigFlags::None; + m_szPreset[0] = '\0'; + m_szTitle[0] = '\0'; + m_szTag[0] = '\0'; + + for (Column &column : m_Columns) + column = Column(); + + ClearValues(m_GlobalValues); + + for (Value *values : m_PlayerValues) + ClearValues(values); + + for (Value *values : m_TeamValues) + ClearValues(values); + + for (List &list : m_Lists) + list = List(); + + m_iSortColumnCount = 0; + m_iSerial++; + m_iSchemaSerial++; +} + +void CScoreboardData::UpdateSortColumns() +{ + m_iSortColumnCount = 0; + + for (int i = 0; i < MAX_COLUMNS; i++) + { + const Column &column = m_Columns[i]; + + if (column.bValid && column.display != E_Display::Builtin && column.GetSortPriority() > 0) + m_SortColumns[m_iSortColumnCount++] = i; + } + + std::stable_sort(m_SortColumns, m_SortColumns + m_iSortColumnCount, [this](int a, int b) { + return m_Columns[a].GetSortPriority() < m_Columns[b].GetSortPriority(); + }); +} + +CScoreboardData::Value *CScoreboardData::GetTargetValues(int target) +{ + if (target == TARGET_GLOBAL) + return m_GlobalValues; + + if (target >= TARGET_PLAYER_FIRST && target <= TARGET_PLAYER_LAST) + return m_PlayerValues[target]; + + if (target >= TARGET_TEAM_FIRST && target <= TARGET_TEAM_LAST) + return m_TeamValues[target - TARGET_TEAM_BASE]; + + return nullptr; +} + +int CScoreboardData::MsgFunc_BhlScore(const char *pszName, int iSize, void *pbuf) +{ + CMsgReader reader(pbuf, iSize); + int op = 0; + + if (!reader.ReadByte(op)) + return 1; + + switch (static_cast(op)) + { + case E_Op::Reset: + { + int version = 0; + + if (reader.ReadByte(version) && version >= 1) + Clear(); + + break; + } + case E_Op::Config: + { + int flags = 0; + char preset[sizeof(m_szPreset)]; + char title[sizeof(m_szTitle)]; + char tag[sizeof(m_szTag)]; + + if (!reader.ReadWord(flags) || !reader.ReadString(preset) || !reader.ReadString(title) || !reader.ReadString(tag)) + break; + + m_bConfigReceived = true; + m_ConfigFlags = static_cast(flags); + V_strcpy_safe(m_szPreset, preset); + V_strcpy_safe(m_szTitle, title); + V_strcpy_safe(m_szTag, tag); + m_iSerial++; + m_iSchemaSerial++; + break; + } + case E_Op::Column: + { + int id = 0; + int display = 0; + int flags = 0; + int width = 0; + int sort = 0; + Column column; + + if (!reader.ReadByte(id) || !reader.ReadByte(display) || !reader.ReadWord(flags) || !reader.ReadByte(width) || !reader.ReadByte(sort) + || !reader.ReadString(column.szKey) || !reader.ReadString(column.szTitle)) + break; + + if (id >= MAX_COLUMNS) + break; + + column.bValid = true; + column.display = display <= static_cast(E_Display::Steps) ? static_cast(display) : E_Display::Text; + column.flags = static_cast(flags); + column.iWidth = width; + column.iSort = sort; + m_Columns[id] = column; + UpdateSortColumns(); + m_iSerial++; + m_iSchemaSerial++; + break; + } + case E_Op::Values: + { + int target = 0; + int count = 0; + + while (reader.ReadByte(target) && reader.ReadByte(count)) + { + Value *values = GetTargetValues(target); + + for (int i = 0; i < count; i++) + { + int col = 0; + int type = 0; + Value value; + + if (!reader.ReadByte(col) || !ReadValue(reader, value, type)) + return 1; + + if (!values) + continue; + + if (col == ALL_COLUMNS && type == static_cast(E_ValueType::None)) + { + ClearValues(values); + m_iSerial++; + } + else if (col < MAX_COLUMNS) + { + values[col] = value; + m_iSerial++; + } + } + } + + break; + } + case E_Op::List: + { + int id = 0; + int total = 0; + int start = 0; + char key[MAX_KEY_LEN + 1]; + + if (!reader.ReadByte(id) || !reader.ReadByte(total) || !reader.ReadByte(start) || !reader.ReadString(key) || id >= MAX_LISTS) + break; + + List &list = m_Lists[id]; + total = min(total, MAX_LIST_ITEMS); + + for (int i = total; i < list.iCount; i++) + list.items[i] = Value(); + + list.bValid = total > 0; + list.iCount = total; + V_strcpy_safe(list.szKey, total > 0 ? key : ""); + m_iSerial++; + + for (int i = start; reader.GetRemaining() > 0; i++) + { + int type = 0; + Value value; + + if (!ReadValue(reader, value, type)) + break; + + if (i < total) + list.items[i] = value; + } + + break; + } + default: + break; + } + + return 1; +} diff --git a/src/game/client/scoreboard_data.h b/src/game/client/scoreboard_data.h new file mode 100644 index 00000000..313780e6 --- /dev/null +++ b/src/game/client/scoreboard_data.h @@ -0,0 +1,187 @@ +#ifndef SCOREBOARD_DATA_H +#define SCOREBOARD_DATA_H +#include +#include "cdll_dll.h" + +/** + * Client store of the scoreboard extension (docs/scoreboard-protocol.md). + * Receives "BhlScore" messages. Read by the scoreboard, hud_scores and the GunGame HUD. + */ +class CScoreboardData +{ +public: + struct Value + { + bhl::sb::E_ValueType type = bhl::sb::E_ValueType::None; + int iValue = 0; //!< Int value or Progress cur + int iMax = 0; //!< Progress max + char szText[bhl::sb::MAX_TEXT_LEN + 1] = {}; //!< Text value or Icon text + char szSprite[bhl::sb::MAX_TEXT_LEN + 1] = {}; //!< Icon sprite name from hud.txt + + bool IsEmpty() const; + + //! Sort key: Int value or Progress cur. Returns false for other types. + bool GetNumber(int &out) const; + + //! Text form: "5", text, icon name (see GetIconName), "cur/max". Empty for None. + void ToString(wchar_t *buf, int bufSizeBytes) const; + }; + + struct Column + { + bool bValid = false; + bhl::sb::E_Display display = bhl::sb::E_Display::Text; + bhl::sb::E_ColumnFlags flags = bhl::sb::E_ColumnFlags::None; + int iWidth = 0; //!< Proportional units, 0 for the default + int iSort = 0; //!< Raw sort byte + char szKey[bhl::sb::MAX_KEY_LEN + 1] = {}; + char szTitle[bhl::sb::MAX_COLUMN_TITLE_LEN + 1] = {}; + + int GetSortPriority() const { return iSort & bhl::sb::SORT_PRIORITY_MASK; } + bool IsSortAscending() const { return (iSort & bhl::sb::SORT_ASC) != 0; } + bool IsHidden() const { return IsEnumFlagSet(flags, bhl::sb::E_ColumnFlags::Hidden); } + bool IsPrimary() const { return IsEnumFlagSet(flags, bhl::sb::E_ColumnFlags::Primary); } + + //! Returns 0 (left), 1 (center) or 2 (right) + int GetAlign() const; + }; + + struct List + { + bool bValid = false; + char szKey[bhl::sb::MAX_KEY_LEN + 1] = {}; + int iCount = 0; + Value items[bhl::sb::MAX_LIST_ITEMS]; + }; + + static CScoreboardData &Get(); + + CScoreboardData(); + CScoreboardData(const CScoreboardData &) = delete; + CScoreboardData &operator=(const CScoreboardData &) = delete; + + //! Hooks BhlScore. Called from CHud::Init. + void Init(); + + //! Clears everything. Called from CHud::VidInit. + void VidInit(); + + //! Clears cells of disconnected players. Called from CHud::Frame. + void Frame(); + + //! True when hud_scoreboard_custom allows the custom scoreboard (setting only, ignores the server) + static bool IsCustomEnabled(); + + //! True when hud_gungame allows the GunGame HUD (also requires IsCustomEnabled) + static bool IsGunGameHudEnabled(); + + //! True when the server sent a config after the last reset and IsCustomEnabled() + bool IsActive() const; + + //! True when IsActive() and the config uses the "gungame" preset + bool IsGunGame() const; + + bool IsStdColumnHidden(bhl::sb::E_ConfigFlags flag) const; + const char *GetPreset() const { return m_szPreset; } + const char *GetTitle() const { return m_szTitle; } + const char *GetTag() const { return m_szTag; } + + //! Incremented on every change of the store + int GetSerial() const { return m_iSerial; } + + //! Incremented on every change of the config or columns + int GetSchemaSerial() const { return m_iSchemaSerial; } + + //! @param id Column id [0; MAX_COLUMNS) + const Column &GetColumn(int id) const; + + //! Returns column id or -1 + int FindColumn(const char *key) const; + + //! Returns id of the Primary column or -1 + int FindPrimaryColumn() const; + + //! Returns id of the column with the lowest non-zero sort priority or -1 + int GetFirstSortColumn() const; + + //! Values of absent or disconnected targets are empty + const Value &GetGlobalValue(int col) const; + const Value &GetPlayerValue(int client, int col) const; + const Value &GetTeamValue(int team, int col) const; + + //! Returns nullptr if there is no such list + const List *FindList(const char *key) const; + + /** + * Compares players by the sort keys of the schema. + * @return < 0 if a goes before b, > 0 if after, 0 if the keys are equal + */ + int ComparePlayers(int a, int b) const; + int CompareTeams(int a, int b) const; + + /** + * Place by the first sort key among participants: connected players that are not spectators. + * Equal values share a place (1, 1, 3). + * @param pTotal Receives the number of participants + * @return Place starting at 1, or 0 if the player has no value or there is no sort key + */ + int GetPlayerPlace(int client, int *pTotal = nullptr) const; + + /** + * Place by the first sort key among teams that have participants. + */ + int GetTeamPlace(int team, int *pTotal = nullptr) const; + + /** + * Returns "One", "Few" or "Many": the plural form of n for the client language + * (token BHL_PluralRule in bugfixedhl_*.txt). + */ + static const char *GetPluralSuffix(int n); + + /** + * Converts a UTF-8 string of the protocol to wide. + * "#token" is localized, a missing token is shown without '#'. + */ + static void LocalizeString(const char *str, wchar_t *buf, int bufSizeBytes); + + /** + * Display name of an Icon value: BHL_Weapon_ for standard HL sprites, + * the text of the value otherwise. + */ + static void GetIconName(const Value &value, wchar_t *buf, int bufSizeBytes); + + //! hud_scoreboard_dump: prints the store to the console + void DumpCommand(); + + //! hud_scoreboard_test [preset|off] [phase] [phase_left]: fills the store with a fake GunGame schema + void TestCommand(); + +private: + bool m_bConfigReceived = false; + bhl::sb::E_ConfigFlags m_ConfigFlags = bhl::sb::E_ConfigFlags::None; + char m_szPreset[bhl::sb::MAX_PRESET_LEN + 1] = {}; + char m_szTitle[bhl::sb::MAX_TITLE_LEN + 1] = {}; + char m_szTag[bhl::sb::MAX_TAG_LEN + 1] = {}; + int m_iSerial = 0; + int m_iSchemaSerial = 0; + + Column m_Columns[bhl::sb::MAX_COLUMNS]; + Value m_GlobalValues[bhl::sb::MAX_COLUMNS]; + Value m_PlayerValues[MAX_PLAYERS + 1][bhl::sb::MAX_COLUMNS]; + Value m_TeamValues[MAX_TEAMS + 1][bhl::sb::MAX_COLUMNS]; + List m_Lists[bhl::sb::MAX_LISTS]; + + int m_SortColumns[bhl::sb::MAX_COLUMNS] = {}; //!< Ids of the sort key columns in priority order + int m_iSortColumnCount = 0; + bool m_bPlayerConnected[MAX_PLAYERS + 1] = {}; //!< Connection state seen by the last Frame + + void Clear(); + void UpdateSortColumns(); + + //! Returns MAX_COLUMNS values of the protocol target or nullptr + Value *GetTargetValues(int target); + + int MsgFunc_BhlScore(const char *pszName, int iSize, void *pbuf); +}; + +#endif diff --git a/src/game/client/vgui/score_panel.cpp b/src/game/client/vgui/score_panel.cpp index 27818042..9b329a5c 100644 --- a/src/game/client/vgui/score_panel.cpp +++ b/src/game/client/vgui/score_panel.cpp @@ -1,11 +1,14 @@ #include #include +#include #include #include +#include #include #include #include #include +#include #include #include #include @@ -14,6 +17,7 @@ #include "cl_voice_status.h" #include "client_vgui.h" #include "client_steam_context.h" +#include "scoreboard_data.h" #include "hud/chat.h" #include "hud/text_message.h" #include "vgui/client_viewport.h" @@ -145,6 +149,10 @@ CScorePanel::CScorePanel() m_pServerNameLabel = new vgui2::Label(this, "ServerName", "A Half-Life Server"); m_pMapNameLabel = new vgui2::Label(this, "MapName", "Map: crossfire"); m_pPlayerCountLabel = new vgui2::Label(this, "PlayerCount", "2/32"); + m_pLeaderTitleLabel = new vgui2::Label(this, "LeaderTitle", ""); + m_pLeaderLineLabel = new vgui2::Label(this, "LeaderLine", ""); + m_pLeaderTitleLabel->SetVisible(false); + m_pLeaderLineLabel->SetVisible(false); // Player list m_pPlayerList = new vgui2::SectionedListPanel(this, "PlayerList"); @@ -172,15 +180,28 @@ CScorePanel::CScorePanel() CreatePlayerMenu(); - LoadControlSettings(VGUI2_ROOT_DIR "resource/ScorePanel.res"); + Q_strncpy(m_szLayoutFile, VGUI2_ROOT_DIR "resource/ScorePanel.res", sizeof(m_szLayoutFile)); + LoadControlSettings(m_szLayoutFile); SetVisible(false); } void CScorePanel::UpdateServerName() { wchar_t wbuf[MAX_SERVERNAME_LENGTH]; - g_pVGuiLocalize->ConvertANSIToUnicode(g_pViewport->GetServerName(), wbuf, sizeof(wbuf)); + CScoreboardData &data = CScoreboardData::Get(); + + // The title of the custom scoreboard replaces the server name + if (m_bCustom && (data.GetTitle()[0] || m_bGunGame)) + CScoreboardData::LocalizeString(data.GetTitle(), wbuf, sizeof(wbuf)); + else + g_pVGuiLocalize->ConvertANSIToUnicode(g_pViewport->GetServerName(), wbuf, sizeof(wbuf)); + m_pServerNameLabel->SetText(wbuf); + + if (m_bCustom) + CScoreboardData::LocalizeString(data.GetTag(), m_wszTag, sizeof(m_wszTag)); + else + m_wszTag[0] = L'\0'; } void CScorePanel::EnableMousePointer(bool bEnable) @@ -238,6 +259,21 @@ void CScorePanel::ApplySchemeSettings(vgui2::IScheme *pScheme) void CScorePanel::OnThink() { + CScoreboardData &data = CScoreboardData::Get(); + + if (data.IsActive() != m_bCustom || (m_bCustom && (data.GetSerial() != m_iStoreSerial || m_bSectionsDirty))) + { + m_iStoreSerial = data.GetSerial(); + + // Sections and columns can't be changed in place, so the schema or the order of teams rebuilds them + if (data.IsActive() != m_bCustom || data.GetSchemaSerial() != m_iSchemaSerial) + FullUpdate(); + else if (m_bSectionsDirty || !std::is_sorted(m_SortedTeamIDs.begin(), m_SortedTeamIDs.begin() + m_iSortedTeamCount, [this](int ilhs, int irhs) { return IsTeamBefore(ilhs, irhs); })) + RefreshItems(); + else + UpdateAllClients(); + } + if (m_iKillerIndex != 0 && m_PlayerData[m_iKillerIndex].nItemID != -1) { // Update bg color @@ -286,6 +322,42 @@ void CScorePanel::OnCommand(const char *command) } } +void CScorePanel::PaintBackground() +{ + BaseClass::PaintBackground(); + + if (m_bGunGame && m_pLeaderTitleLabel->IsVisible()) + { + // Leader banner: a box around both lines with an accent at the left edge + int x, y, wide, tall, lineX, lineY, lineWide, lineTall; + m_pLeaderTitleLabel->GetBounds(x, y, wide, tall); + m_pLeaderLineLabel->GetBounds(lineX, lineY, lineWide, lineTall); + + int x0 = std::min(x, lineX) - m_iGGBannerPadding; + int y0 = y - m_iGGBannerPadding; + int x1 = std::max(x + wide, lineX + lineWide) + m_iGGBannerPadding; + int y1 = lineY + lineTall + m_iGGBannerPadding; + + vgui2::surface()->DrawSetColor(m_GGBannerBgColor); + vgui2::surface()->DrawFilledRect(x0, y0, x1, y1); + vgui2::surface()->DrawSetColor(m_GGBannerAccentColor); + vgui2::surface()->DrawFilledRect(x0, y0, x0 + m_iGGBannerAccentWide, y1); + } +} + +void CScorePanel::Paint() +{ + BaseClass::Paint(); + + if (m_bCustom && m_wszTag[0] && m_pServerNameLabel->IsVisible()) + { + int x, y, wide, tall, textWide, textTall; + m_pServerNameLabel->GetBounds(x, y, wide, tall); + m_pServerNameLabel->GetContentSize(textWide, textTall); + DrawScoreBadge(m_CellStyle, x + std::min(textWide, wide) + m_CellStyle.iSpacing, y + tall / 2, m_wszTag); + } +} + const char *CScorePanel::GetName() { return VIEWPORT_PANEL_SCORE; @@ -348,6 +420,25 @@ void CScorePanel::OnItemContextMenu(int itemID) void CScorePanel::FullUpdate() { + CScoreboardData &data = CScoreboardData::Get(); + bool bWasGunGame = m_bGunGame; + m_bCustom = data.IsActive(); + m_bGunGame = m_bCustom && data.IsGunGame(); + m_iStoreSerial = data.GetSerial(); + m_iSchemaSerial = data.GetSchemaSerial(); + + // The GunGame preset sets the bounds in code, only a reload restores them + if (bWasGunGame != m_bGunGame) + m_szLayoutFile[0] = '\0'; + + UpdateLayoutFile(); + + if (!m_bGunGame) + { + m_pLeaderTitleLabel->SetVisible(false); + m_pLeaderLineLabel->SetVisible(false); + } + UpdateServerName(); UpdateMapName(); RefreshItems(); @@ -367,9 +458,11 @@ void CScorePanel::RefreshItems() std::fill(m_TeamData.begin(), m_TeamData.end(), TeamData()); std::fill(m_PlayerData.begin(), m_PlayerData.end(), PlayerData()); std::fill(m_IsTeamSectionCreated.begin(), m_IsTeamSectionCreated.end(), false); + m_bSectionsDirty = false; m_pPlayerList->RemoveAll(); m_pPlayerList->RemoveAllSections(); + BuildCustomColumns(); RestoreSize(); // Assign player teams, calculate team scores @@ -414,25 +507,10 @@ void CScorePanel::RefreshItems() } // Sort teams based on the score - std::sort(m_SortedTeamIDs.begin(), m_SortedTeamIDs.begin() + iTeamCount, [&](int ilhs, int irhs) { - const TeamData &lhs = m_TeamData[ilhs]; - const TeamData &rhs = m_TeamData[irhs]; - - // Compare kills - if (lhs.iFrags > rhs.iFrags) - return true; - else if (lhs.iFrags < rhs.iFrags) - return false; - - // Compare deaths if kills are equal - if (lhs.iDeaths < rhs.iDeaths) - return true; - else if (lhs.iDeaths > rhs.iDeaths) - return false; - - // Compare idx if everything is equal - return ilhs > irhs; + std::sort(m_SortedTeamIDs.begin(), m_SortedTeamIDs.begin() + iTeamCount, [this](int ilhs, int irhs) { + return IsTeamBefore(ilhs, irhs); }); + m_iSortedTeamCount = iTeamCount; // Create header before any other sections CreateSection(HEADER_SECTION_ID); @@ -465,7 +543,7 @@ void CScorePanel::CreateSection(int nTeamID) char buf[128]; TeamData &td = m_TeamData[nTeamID]; - m_pPlayerList->AddSection(nTeamID, "", StaticPlayerSortFuncByFrags); + m_pPlayerList->AddSection(nTeamID, "", m_bCustom ? StaticPlayerSortFuncCustom : StaticPlayerSortFuncByFrags); m_pPlayerList->SetSectionFgColor(nTeamID, g_pViewport->GetTeamColor(nTeamID)); if (nTeamID == HEADER_SECTION_ID) @@ -474,6 +552,18 @@ void CScorePanel::CreateSection(int nTeamID) m_pPlayerList->SetSectionDividerColor(nTeamID, Color(0, 0, 0, 0)); } + if (m_bCustom) + { + // Team sections get their texts from UpdateScoresAndCounts + for (const CustomColumn &col : m_CustomColumns) + { + m_pPlayerList->AddColumnToSection(nTeamID, col.szName, nTeamID == HEADER_SECTION_ID ? col.wszTitle : L"", + col.iFlags, col.iWidth); + } + + return; + } + // Avatar m_pPlayerList->AddColumnToSection(nTeamID, "avatar", "", vgui2::SectionedListPanel::COLUMN_IMAGE | vgui2::SectionedListPanel::COLUMN_CENTER, @@ -583,6 +673,9 @@ void CScorePanel::UpdateClientInfo(int client) pd.nTeamID = pi->GetTeamNumber(); } + if (m_bCustom && !m_IsTeamSectionCreated[pd.nTeamID]) + m_bSectionsDirty = true; + // Create section for player's team if need to CreateSection(pd.nTeamID); @@ -638,6 +731,9 @@ void CScorePanel::UpdateClientInfo(int client) { playerKv->SetInt("ping", pi->GetPing()); } + + if (m_bCustom) + UpdateCustomCells(pi, playerKv); } if (pd.nItemID == -1) @@ -768,6 +864,9 @@ void CScorePanel::UpdateScoresAndCounts() snprintf(buf, sizeof(buf), "%d", td.iDeaths); g_pVGuiLocalize->ConvertANSIToUnicode(buf, wbuf, sizeof(wbuf)); m_pPlayerList->ModifyColumn(nTeamID, "deaths", wbuf); + + if (m_bCustom) + UpdateCustomTeamHeader(nTeamID); }; // Update team score and player count @@ -795,6 +894,9 @@ void CScorePanel::UpdateScoresAndCounts() // Update total player count snprintf(buf, sizeof(buf), "%d/%d", iPlayerCount, gEngfuncs.GetMaxClients()); m_pPlayerCountLabel->SetText(buf); + + if (m_bGunGame) + UpdateGunGameHeader(iPlayerCount); } int CScorePanel::GetNameColumnWidth() @@ -822,7 +924,7 @@ Color CScorePanel::GetPlayerBgColor(CPlayerInfo *pi) { if (pi->IsThisPlayer()) { - return m_ThisPlayerBgColor; + return m_bGunGame ? m_GGOwnRowColor : m_ThisPlayerBgColor; } else if (m_iKillerIndex == pi->GetIndex()) { @@ -844,6 +946,10 @@ Color CScorePanel::GetPlayerBgColor(CPlayerInfo *pi) return color; } } + else if (m_bGunGame && IsOnLastLevel(pi->GetIndex())) + { + return m_GGFinalRowColor; + } return Color(0, 0, 0, 0); } @@ -1068,15 +1174,17 @@ int CScorePanel::GetLineSpacingForHeight(int h) int CScorePanel::GetLineSpacingForNormal() { if (hud_scoreboard_spacing_normal.GetInt() > 0) - return hud_scoreboard_spacing_normal.GetInt(); + return hud_scoreboard_spacing_normal.GetInt() + m_iLineSpacingExtra; + if (m_iLineSpacingExtra > 0) + return m_iDefaultLineSpacing + m_iLineSpacingExtra; return 0; } int CScorePanel::GetLineSpacingForCompact() { if (hud_scoreboard_spacing_compact.GetInt() > 0) - return hud_scoreboard_spacing_compact.GetInt(); - return GetLineSpacingForHeight(ScreenHeight); + return hud_scoreboard_spacing_compact.GetInt() + m_iLineSpacingExtra; + return GetLineSpacingForHeight(ScreenHeight) + m_iLineSpacingExtra; } void CScorePanel::RestoreSize() @@ -1090,6 +1198,7 @@ void CScorePanel::RestoreSize() void CScorePanel::Resize() { SizeMode mode = GetSizeMode(); + int top = m_bGunGame ? ScreenHeight * m_iGGTopPercent / 100 : m_iVerticalMargin; // Returns true if scrollbar was enabled auto fnUpdateSize = [&](int &height) { @@ -1105,10 +1214,10 @@ void CScorePanel::Resize() listHeight = max(m_iMinHeight, tall); height += listHeight; - if (ScreenHeight - height < m_iVerticalMargin * 2) + if (ScreenHeight - height < top + m_iVerticalMargin) { // It didn't fit - height = ScreenHeight - m_iVerticalMargin * 2; + height = ScreenHeight - top - m_iVerticalMargin; listHeight = height - addHeight; m_pPlayerList->SetVerticalScrollbar(true); bIsOverflowed = true; @@ -1144,9 +1253,9 @@ void CScorePanel::Resize() GetSize(wide, tall); SetSize(wide, height); - // Move to center + // Move to center. The GunGame preset grows down from the top edge. GetPos(x, y); - y = (ScreenHeight - height) / 2; + y = m_bGunGame ? top : (ScreenHeight - height) / 2; SetPos(x, y); } @@ -1175,3 +1284,635 @@ bool CScorePanel::StaticPlayerSortFuncByFrags(vgui2::SectionedListPanel *list, i // the same, so compare itemID's (as a sentinel value to get deterministic sorts) return itemID1 < itemID2; } + +bool CScorePanel::IsTeamBefore(int ilhs, int irhs) +{ + if (m_bCustom) + { + int cmp = CScoreboardData::Get().CompareTeams(ilhs, irhs); + + if (cmp != 0) + return cmp < 0; + } + + const TeamData &lhs = m_TeamData[ilhs]; + const TeamData &rhs = m_TeamData[irhs]; + + // Compare kills + if (lhs.iFrags > rhs.iFrags) + return true; + else if (lhs.iFrags < rhs.iFrags) + return false; + + // Compare deaths if kills are equal + if (lhs.iDeaths < rhs.iDeaths) + return true; + else if (lhs.iDeaths > rhs.iDeaths) + return false; + + // Compare idx if everything is equal + return ilhs > irhs; +} + +void CScorePanel::UpdateLayoutFile() +{ + char path[64]; + char preset[bhl::sb::MAX_PRESET_LEN + 1]; + Q_strncpy(path, VGUI2_ROOT_DIR "resource/ScorePanel.res", sizeof(path)); + Q_strncpy(preset, CScoreboardData::Get().GetPreset(), sizeof(preset)); + Q_strlower(preset); + + // The preset comes from the server, so only [a-z0-9_] may get into the file name + bool bValidPreset = m_bCustom && preset[0]; + + for (const char *c = preset; *c && bValidPreset; c++) + bValidPreset = (*c >= 'a' && *c <= 'z') || (*c >= '0' && *c <= '9') || *c == '_'; + + if (bValidPreset) + { + char presetPath[64]; + snprintf(presetPath, sizeof(presetPath), VGUI2_ROOT_DIR "resource/ScorePanel_%s.res", preset); + + if (g_pFullFileSystem->FileExists(presetPath)) + Q_strncpy(path, presetPath, sizeof(path)); + } + + if (!Q_strcmp(path, m_szLayoutFile)) + return; + + Q_strncpy(m_szLayoutFile, path, sizeof(m_szLayoutFile)); + LoadControlSettings(m_szLayoutFile); +} + +void CScorePanel::BuildCustomColumns() +{ + m_CustomColumns.clear(); + m_iLineSpacingExtra = 0; + m_iLevelColumn = -1; + m_iWeaponColumn = -1; + m_iProgressColumn = -1; + + if (!m_bCustom) + return; + + CScoreboardData &data = CScoreboardData::Get(); + + m_CellStyle.hFont = m_CellFont; + m_CellStyle.hBadgeFont = m_BadgeFont; + m_CellStyle.filledColor = m_CellFilledColor; + m_CellStyle.emptyColor = m_CellEmptyColor; + m_CellStyle.currentColor = m_CellCurrentColor; + m_CellStyle.lastColor = m_CellLastColor; + m_CellStyle.badgeBgColor = m_BadgeBgColor; + m_CellStyle.badgeFgColor = m_BadgeFgColor; + m_CellStyle.iDotSize = m_iCellDotSize; + m_CellStyle.iDotGap = m_iCellDotGap; + m_CellStyle.iStripTall = m_iCellStripTall; + m_CellStyle.iStripGap = m_iCellStripGap; + m_CellStyle.iSpacing = m_iCellSpacing; + + if (m_bGunGame) + { + m_iLevelColumn = data.FindColumn("level"); + m_iWeaponColumn = data.FindColumn("weapon"); + m_iProgressColumn = data.FindColumn("progress"); + } + + // Column names indexed by ColumnType, the same as the keys of Builtin columns + static const char *const s_StdColumnNames[] = { "rank", "avatar", "name", "steamid", "eff", "frags", "deaths", "ping" }; + int nSlotCount = 0; + + auto fnGetBuiltinType = [](const char *key) { + for (ColumnType type : { ColumnType::Rank, ColumnType::SteamID, ColumnType::Eff, ColumnType::Frags, ColumnType::Deaths, ColumnType::Ping }) + { + if (!Q_strcmp(key, s_StdColumnNames[(int)type])) + return type; + } + + return ColumnType::Custom; + }; + + // bCell: the column is drawn by CScoreCellImage + auto fnAddColumn = [&](ColumnType type, int nColumnID, const char *title, int width, int align, bool bCell) { + CustomColumn col; + col.type = type; + col.nColumnID = nColumnID; + col.nSlot = bCell ? nSlotCount++ : -1; + col.iAlign = align; + col.iWidth = width; + + if (type == ColumnType::Avatar) + col.iFlags = vgui2::SectionedListPanel::COLUMN_IMAGE | vgui2::SectionedListPanel::COLUMN_CENTER; + else if (bCell) + col.iFlags = vgui2::SectionedListPanel::COLUMN_IMAGE; + else if (type == ColumnType::Name && gHUD.GetColorCodeAction() == ColorCodeAction::Handle) + col.iFlags = vgui2::SectionedListPanel::COLUMN_BRIGHT | vgui2::SectionedListPanel::COLUMN_COLORED; + else + col.iFlags = vgui2::SectionedListPanel::COLUMN_BRIGHT; + + if (type != ColumnType::Avatar && align == 1) + col.iFlags |= vgui2::SectionedListPanel::COLUMN_CENTER; + else if (type != ColumnType::Avatar && align == 2) + col.iFlags |= vgui2::SectionedListPanel::COLUMN_RIGHT; + + if (type == ColumnType::Custom) + snprintf(col.szName, sizeof(col.szName), "c%d_%s", nColumnID, data.GetColumn(nColumnID).szKey); + else + Q_strncpy(col.szName, s_StdColumnNames[(int)type], sizeof(col.szName)); + + CScoreboardData::LocalizeString(title, col.wszTitle, sizeof(col.wszTitle)); + + if (m_bGunGame) + ScoreTextToUpper(col.wszTitle); + + m_CustomColumns.push_back(col); + }; + + // pColumn: the Builtin column that moves the standard one + auto fnAddStdColumn = [&](ColumnType type, const CScoreboardData::Column *pColumn) { + const char *title = ""; + int width = 0; + bool bVisible = true; + + switch (type) + { + case ColumnType::Rank: + title = "#"; + width = m_iColumnWidthRank; + break; + case ColumnType::Avatar: + width = m_iColumnWidthAvatar; + break; + case ColumnType::Name: + title = m_bGunGame ? "#BHL_GG_ColPlayer" : "#PlayerName"; + break; + case ColumnType::SteamID: + title = "#BHL_Scores_ColSteamID"; + width = m_iColumnWidthSteamID; + bVisible = hud_scoreboard_showsteamid.GetBool() && !data.IsStdColumnHidden(bhl::sb::E_ConfigFlags::HideSteamID); + break; + case ColumnType::Eff: + title = "#BHL_Scores_ColEff"; + width = m_iColumnWidthEff; + bVisible = hud_scoreboard_showeff.GetBool() && !data.IsStdColumnHidden(bhl::sb::E_ConfigFlags::HideEff); + break; + case ColumnType::Frags: + title = "#PlayerScore"; + width = m_iColumnWidthFrags; + bVisible = !data.IsStdColumnHidden(bhl::sb::E_ConfigFlags::HideFrags); + break; + case ColumnType::Deaths: + title = "#PlayerDeath"; + width = m_iColumnWidthDeaths; + bVisible = !data.IsStdColumnHidden(bhl::sb::E_ConfigFlags::HideDeaths); + break; + case ColumnType::Ping: + title = (hud_scoreboard_showloss.GetBool() && !m_bGunGame) ? "#BHL_Scores_ColPingLoss" : "#BHL_Scores_ColPing"; + width = m_iColumnWidthPing; + break; + case ColumnType::Custom: + break; + } + + if (!bVisible) + return; + + int align = 0; + + if (pColumn) + { + align = pColumn->GetAlign(); + + if (pColumn->szTitle[0]) + title = pColumn->szTitle; + } + else if (m_bGunGame && type == ColumnType::Ping) + { + align = 2; + } + + bool bCell = type == ColumnType::Rank || (m_bGunGame && (type == ColumnType::Name || type == ColumnType::Ping)); + fnAddColumn(type, -1, title, width, align, bCell); + }; + + // Standard columns moved by Builtin columns + std::array builtins = {}; + + for (int i = 0; i < bhl::sb::MAX_COLUMNS; i++) + { + const CScoreboardData::Column &col = data.GetColumn(i); + + if (col.bValid && !col.IsHidden() && col.display == bhl::sb::E_Display::Builtin) + { + ColumnType type = fnGetBuiltinType(col.szKey); + + if (type != ColumnType::Custom && !builtins[(int)type]) + builtins[(int)type] = &col; + } + } + + if (builtins[(int)ColumnType::Rank]) + fnAddStdColumn(ColumnType::Rank, builtins[(int)ColumnType::Rank]); + + fnAddStdColumn(ColumnType::Avatar, nullptr); + fnAddStdColumn(ColumnType::Name, nullptr); + + for (ColumnType type : { ColumnType::SteamID, ColumnType::Eff, ColumnType::Frags, ColumnType::Deaths }) + { + if (!builtins[(int)type]) + fnAddStdColumn(type, nullptr); + } + + for (int i = 0; i < bhl::sb::MAX_COLUMNS; i++) + { + const CScoreboardData::Column &col = data.GetColumn(i); + + if (!col.bValid || col.IsHidden()) + continue; + + if (col.display == bhl::sb::E_Display::Builtin) + { + ColumnType type = fnGetBuiltinType(col.szKey); + + if (type != ColumnType::Custom && type != ColumnType::Rank && builtins[(int)type] == &col) + fnAddStdColumn(type, &col); + + continue; + } + + int width = col.iWidth; + bool bCell = false; + + switch (col.display) + { + case bhl::sb::E_Display::Icon: + width = width ? width : 100; + bCell = true; + break; + case bhl::sb::E_Display::Meter: + width = width ? width : 90; + bCell = true; + break; + case bhl::sb::E_Display::Steps: + width = width ? width : 60; + bCell = true; + break; + default: + width = width ? width : 60; + break; + } + + fnAddColumn(ColumnType::Custom, i, col.szTitle, vgui2::scheme()->GetProportionalScaledValue(width), col.GetAlign(), bCell); + } + + if (!builtins[(int)ColumnType::Ping]) + fnAddStdColumn(ColumnType::Ping, nullptr); + + // Name takes the free width and shrinks to its minimum, then columns are dropped from the end + int listX, listY; + m_pPlayerList->GetPos(listX, listY); + int reservedWide = LIST_ROW_PADDING + m_pPlayerList->GetScrollBar()->GetWide(); + int otherWide = 0; + + for (const CustomColumn &col : m_CustomColumns) + otherWide += col.iWidth; + + if (m_bGunGame) + { + int x, y; + int wide = std::max(ScreenWidth * m_iGGWidePercent / 100, otherWide + m_iColumnWidthNameMin + reservedWide + 2 * listX); + wide = std::min(wide, ScreenWidth); + GetPos(x, y); + SetBounds((ScreenWidth - wide) / 2, y, wide, GetTall()); + m_pPlayerList->SetWide(wide - 2 * listX); + } + + int freeWide = m_pPlayerList->GetWide() - reservedWide; + + // On narrow screens Name gives up to a fifth of its minimum before a column is dropped + int nameMin = std::max(std::min(freeWide - otherWide, m_iColumnWidthNameMin), m_iColumnWidthNameMin * 4 / 5); + + while (otherWide + nameMin > freeWide && m_CustomColumns.back().type != ColumnType::Name) + { + otherWide -= m_CustomColumns.back().iWidth; + m_CustomColumns.pop_back(); + } + + for (CustomColumn &col : m_CustomColumns) + { + if (col.type == ColumnType::Name) + col.iWidth = std::max(freeWide - otherWide, nameMin); + else if (col.type == ColumnType::Custom && data.GetColumn(col.nColumnID).display == bhl::sb::E_Display::Steps) + m_iLineSpacingExtra = m_iCellStripTall + m_iCellStripGap; + } + + m_pPlayerList->SetLineSpacingOverride(0); + m_iDefaultLineSpacing = m_pPlayerList->GetLineSpacing(); +} + +CScoreCellImage *CScorePanel::GetCellImage(int index) +{ + if (!m_pImageList->IsValidIndex(index) || !m_pImageList->GetImage(index)) + m_pImageList->SetImageAtIndex(index, new CScoreCellImage(m_CellStyle)); + + return static_cast(m_pImageList->GetImage(index)); +} + +void CScorePanel::UpdateCustomCells(CPlayerInfo *pi, KeyValues *kv) +{ + CScoreboardData &data = CScoreboardData::Get(); + int client = pi->GetIndex(); + int lineSpacing = m_pPlayerList->GetLineSpacing(); + bool bLastLevel = IsOnLastLevel(client); + Color color = gHUD.GetClientColor(client, NoTeamColor::White); + wchar_t wbuf[128]; + char buf[128]; + + for (const CustomColumn &col : m_CustomColumns) + { + if (col.nSlot == -1) + { + if (col.type == ColumnType::Custom) + { + data.GetPlayerValue(client, col.nColumnID).ToString(wbuf, sizeof(wbuf)); + Q_WStringToUTF8(wbuf, buf, sizeof(buf)); + kv->SetString(col.szName, buf); + } + + continue; + } + + // Image columns read the index of the image from the row + int index = CELL_IMAGE_BASE + col.nSlot * MAX_PLAYERS + client - 1; + CScoreCellImage *pCell = GetCellImage(index); + pCell->SetSize(col.iWidth - COLUMN_DATA_GAP, lineSpacing); + pCell->SetAlign(col.iAlign); + pCell->SetColor(color); + + switch (col.type) + { + case ColumnType::Rank: + { + // With team sections the place is shown in team headers + int place = m_PlayerData[client].nTeamID == HEADER_SECTION_ID ? GetPlayerRank(client) : 0; + Color markColor(0, 0, 0, 0); + + if (m_bGunGame && place == 1) + { + markColor = bLastLevel ? m_GGPlaceFinalColor : m_GGPlaceFirstColor; + pCell->SetColor(m_GGPlaceFirstTextColor); + } + else if (m_bGunGame && place >= 2 && place <= 3) + { + markColor = m_GGPlaceTopColor; + } + + pCell->SetPlace(place, markColor); + break; + } + case ColumnType::Name: + { + RemoveColorCodes(kv->GetString(col.szName), buf, sizeof(buf)); + Q_UTF8ToWString(buf, wbuf, sizeof(wbuf), STRINGCONVERT_REPLACE); + pCell->SetText(wbuf); + + if (pi->IsThisPlayer()) + { + pCell->SetColor(m_GGEmphasisColor); + pCell->SetBadge(g_pVGuiLocalize->Find("#BHL_GG_You")); + } + + break; + } + case ColumnType::Ping: + { + V_snwprintf(wbuf, ARRAYSIZE(wbuf), L"%d", pi->GetPing()); + pCell->SetText(wbuf); + + if (pi->GetPing() >= m_iGGPingHigh) + pCell->SetColor(m_GGPingHighColor); + + break; + } + case ColumnType::Custom: + { + pCell->SetValue(data.GetColumn(col.nColumnID).display, data.GetPlayerValue(client, col.nColumnID)); + + if (bLastLevel && (col.nColumnID == m_iLevelColumn || col.nColumnID == m_iWeaponColumn)) + pCell->SetColor(m_GGEmphasisColor); + + if (bLastLevel && col.nColumnID == m_iWeaponColumn) + pCell->SetBadge(g_pVGuiLocalize->Find("#BHL_GG_Final")); + + break; + } + default: + break; + } + + kv->SetInt(col.szName, index); + } +} + +void CScorePanel::UpdateCustomTeamHeader(int nTeamID) +{ + CScoreboardData &data = CScoreboardData::Get(); + bool bIsTeam = nTeamID >= 1 && nTeamID <= MAX_TEAMS; + wchar_t wbuf[128]; + + for (const CustomColumn &col : m_CustomColumns) + { + if (col.type != ColumnType::Rank && col.type != ColumnType::Custom) + continue; + + wbuf[0] = L'\0'; + + if (bIsTeam && col.type == ColumnType::Rank) + { + int place = GetTeamRank(nTeamID); + + if (place > 0) + V_snwprintf(wbuf, ARRAYSIZE(wbuf), L"%d", place); + } + else if (bIsTeam) + { + data.GetTeamValue(nTeamID, col.nColumnID).ToString(wbuf, sizeof(wbuf)); + } + + m_pPlayerList->ModifyColumn(nTeamID, col.szName, wbuf); + } +} + +void CScorePanel::UpdateGunGameHeader(int iPlayerCount) +{ + CScoreboardData &data = CScoreboardData::Get(); + wchar_t wbuf[256]; + wchar_t wbuf2[128]; + wchar_t wnum1[16]; + wchar_t wnum2[16]; + char buf[64]; + + int maxPlayers = gEngfuncs.GetMaxClients(); + V_snwprintf(wnum1, ARRAYSIZE(wnum1), L"%d", iPlayerCount); + V_snwprintf(wnum2, ARRAYSIZE(wnum2), L"%d", maxPlayers); + snprintf(buf, sizeof(buf), "BHL_GG_Players%s", CScoreboardData::GetPluralSuffix(maxPlayers)); + ConstructScoreText(wbuf2, sizeof(wbuf2), buf, 2, wnum1, wnum2); + + wchar_t wmap[64]; + V_FileBase(gEngfuncs.pfnGetLevelName(), buf, sizeof(buf)); + g_pVGuiLocalize->ConvertANSIToUnicode(buf, wmap, sizeof(wmap)); + V_snwprintf(wbuf, ARRAYSIZE(wbuf), L"%ls \u00B7 %ls", wmap, wbuf2); + m_pMapNameLabel->SetText(wbuf); + + // Leader: the first team in teamplay, the first participant otherwise + int leader = 0; + + for (int i = 1; i <= MAX_TEAMS; i++) + { + if (m_TeamData[i].iPlayerCount > 0 && (leader == 0 || IsTeamBefore(i, leader))) + leader = i; + } + + bool bIsTeam = leader != 0; + + for (int i = 1; i <= MAX_PLAYERS && !bIsTeam; i++) + { + CPlayerInfo *pi = GetPlayerInfo(i); + + if (pi->IsConnected() && !pi->IsSpectator() && (leader == 0 || IsPlayerBefore(i, leader))) + leader = i; + } + + auto fnGetValue = [&](int col) -> const CScoreboardData::Value & { + return bIsTeam ? data.GetTeamValue(leader, col) : data.GetPlayerValue(leader, col); + }; + + bool bShowBanner = leader != 0 && m_iLevelColumn != -1 && IsLastLevel(fnGetValue(m_iLevelColumn)); + m_pLeaderTitleLabel->SetVisible(bShowBanner); + m_pLeaderLineLabel->SetVisible(bShowBanner); + + if (!bShowBanner) + return; + + wchar_t wname[128]; + wchar_t wweapon[64] = L""; + wchar_t wkills[64]; + int killsLeft = 0; + + if (bIsTeam) + CScoreboardData::LocalizeString(GetTeamInfo(leader)->GetDisplayName(), wname, sizeof(wname)); + else + Q_UTF8ToWString(GetPlayerInfo(leader)->GetDisplayName(true), wname, sizeof(wname), STRINGCONVERT_REPLACE); + + if (m_iWeaponColumn != -1) + CScoreboardData::GetIconName(fnGetValue(m_iWeaponColumn), wweapon, sizeof(wweapon)); + + if (m_iProgressColumn != -1) + { + const CScoreboardData::Value &progress = fnGetValue(m_iProgressColumn); + + if (progress.type == bhl::sb::E_ValueType::Progress) + killsLeft = std::max(progress.iMax - progress.iValue, 0); + } + + FormatScoreKills(wkills, sizeof(wkills), killsLeft); + ConstructScoreText(wbuf, sizeof(wbuf), "BHL_GG_LeaderLine", 3, wname, wweapon, wkills); + + m_pLeaderTitleLabel->SetText("#BHL_GG_LeaderFinal"); + m_pLeaderLineLabel->SetText(wbuf); + + // Align the right edge of the banner with the player list + int listX, listY, x, y, titleWide, lineWide, tall; + m_pPlayerList->GetPos(listX, listY); + m_pLeaderTitleLabel->GetContentSize(titleWide, tall); + m_pLeaderLineLabel->GetContentSize(lineWide, tall); + int wide = std::max(titleWide, lineWide); + int bannerX = GetWide() - listX - m_iGGBannerPadding - wide; + + m_pLeaderTitleLabel->GetPos(x, y); + m_pLeaderTitleLabel->SetBounds(bannerX, y, wide, m_pLeaderTitleLabel->GetTall()); + m_pLeaderLineLabel->GetPos(x, y); + m_pLeaderLineLabel->SetBounds(bannerX, y, wide, m_pLeaderLineLabel->GetTall()); +} + +int CScorePanel::GetPlayerRank(int client) +{ + CScoreboardData &data = CScoreboardData::Get(); + + if (data.GetFirstSortColumn() != -1) + return data.GetPlayerPlace(client); + + // Without sort keys the place follows row order + if (GetPlayerInfo(client)->IsSpectator()) + return 0; + + int place = 1; + + for (int i = 1; i <= MAX_PLAYERS; i++) + { + CPlayerInfo *pi = GetPlayerInfo(i); + + if (i != client && pi->IsConnected() && !pi->IsSpectator() && IsPlayerBefore(i, client)) + place++; + } + + return place; +} + +int CScorePanel::GetTeamRank(int nTeamID) +{ + CScoreboardData &data = CScoreboardData::Get(); + + if (data.GetFirstSortColumn() != -1) + return data.GetTeamPlace(nTeamID); + + for (int i = 0; i < m_iSortedTeamCount; i++) + { + if (m_SortedTeamIDs[i] == nTeamID) + return i + 1; + } + + return 0; +} + +bool CScorePanel::IsOnLastLevel(int client) +{ + return m_iLevelColumn != -1 && IsLastLevel(CScoreboardData::Get().GetPlayerValue(client, m_iLevelColumn)); +} + +bool CScorePanel::IsLastLevel(const CScoreboardData::Value &level) +{ + return level.type == bhl::sb::E_ValueType::Progress && level.iMax > 0 && level.iValue >= level.iMax; +} + +bool CScorePanel::IsPlayerBefore(int client1, int client2) +{ + int cmp = CScoreboardData::Get().ComparePlayers(client1, client2); + + if (cmp != 0) + return cmp < 0; + + // Standard order + CPlayerInfo *pi1 = GetPlayerInfo(client1); + CPlayerInfo *pi2 = GetPlayerInfo(client2); + + if (pi1->IsConnected() && pi2->IsConnected()) + { + if (pi1->GetFrags() != pi2->GetFrags()) + return pi1->GetFrags() > pi2->GetFrags(); + + if (pi1->GetDeaths() != pi2->GetDeaths()) + return pi1->GetDeaths() < pi2->GetDeaths(); + } + + return client1 < client2; +} + +bool CScorePanel::StaticPlayerSortFuncCustom(vgui2::SectionedListPanel *list, int itemID1, int itemID2) +{ + KeyValues *it1 = list->GetItemData(itemID1); + KeyValues *it2 = list->GetItemData(itemID2); + Assert(it1 && it2); + + return IsPlayerBefore(it1->GetInt("client"), it2->GetInt("client")); +} diff --git a/src/game/client/vgui/score_panel.h b/src/game/client/vgui/score_panel.h index 17e57e5a..245b5be5 100644 --- a/src/game/client/vgui/score_panel.h +++ b/src/game/client/vgui/score_panel.h @@ -3,12 +3,14 @@ #include #include +#include #include #include #include #include #include "IViewportPanel.h" #include "viewport_panel_names.h" +#include "vgui/score_panel_cells.h" namespace vgui2 { @@ -52,6 +54,8 @@ class CScorePanel : public vgui2::Frame, public IViewportPanel virtual void ApplySchemeSettings(vgui2::IScheme *pScheme) override; virtual void OnThink() override; virtual void OnCommand(const char *command) override; + virtual void PaintBackground() override; + virtual void Paint() override; // IViewportPanel overrides virtual const char *GetName() override; @@ -70,6 +74,15 @@ class CScorePanel : public vgui2::Frame, public IViewportPanel static constexpr float HIGHLIGHT_KILLER_TIME = 10.f; static constexpr float UPDATE_PERIOD = 0.5f; + //! First index of custom cell images in m_pImageList (avatars use 1..MAX_PLAYERS) + static constexpr int CELL_IMAGE_BASE = MAX_PLAYERS + 1; + + //! Width of a row is the width of the list minus this padding (SectionedListPanel::LayoutPanels) + static constexpr int LIST_ROW_PADDING = 10; + + //! Gap at the right of a cell (COLUMN_DATA_GAP of SectionedListPanel) + static constexpr int COLUMN_DATA_GAP = 2; + enum class MenuAction { Mute, @@ -102,6 +115,31 @@ class CScorePanel : public vgui2::Frame, public IViewportPanel int nTeamID = 0; }; + enum class ColumnType + { + Rank, + Avatar, + Name, + SteamID, + Eff, + Frags, + Deaths, + Ping, + Custom, + }; + + struct CustomColumn + { + ColumnType type = ColumnType::Custom; + int nColumnID = -1; //!< Column id in the store for ColumnType::Custom + int nSlot = -1; //!< Cell image slot of an image column, -1 for a text column + int iAlign = 0; //!< 0 left, 1 center, 2 right + int iFlags = 0; //!< SectionedListPanel column flags + int iWidth = 0; + char szName[32] = {}; //!< Column name, also the key in row data + wchar_t wszTitle[64] = {}; + }; + struct MenuData { // Menu items @@ -138,6 +176,25 @@ class CScorePanel : public vgui2::Frame, public IViewportPanel char m_szSpectatorTag[32] = "(spectator)"; + // Custom scoreboard (docs/scoreboard-protocol.md) + vgui2::Label *m_pLeaderTitleLabel = nullptr; + vgui2::Label *m_pLeaderLineLabel = nullptr; + std::vector m_CustomColumns; + ScoreCellStyle m_CellStyle; + char m_szLayoutFile[64] = {}; + wchar_t m_wszTag[32] = {}; + bool m_bCustom = false; + bool m_bGunGame = false; + bool m_bSectionsDirty = false; //!< A section was created outside of RefreshItems + int m_iStoreSerial = -1; + int m_iSchemaSerial = -1; + int m_iSortedTeamCount = 0; + int m_iDefaultLineSpacing = 0; + int m_iLineSpacingExtra = 0; //!< Added to the line spacing while a Steps column is visible + int m_iLevelColumn = -1; + int m_iWeaponColumn = -1; + int m_iProgressColumn = -1; + // Column widths CPanelAnimationVarAliasType(int, m_iColumnWidthAvatar, "column_avatar", "26", "proportional_int"); CPanelAnimationVarAliasType(int, m_iColumnWidthName, "column_name", "170", "proportional_int"); @@ -152,6 +209,41 @@ class CScorePanel : public vgui2::Frame, public IViewportPanel CPanelAnimationVarAliasType(int, m_iVerticalMargin, "vertical_margin", "30", "proportional_int"); CPanelAnimationVarAliasType(int, m_iBottomPadding, "bottom_padding", "4", "proportional_int"); + // Custom scoreboard. A key set in ScorePanel_.res must also be set in ScorePanel.res: + // otherwise it keeps the preset value after switching back. + CPanelAnimationVarAliasType(int, m_iColumnWidthRank, "column_rank", "24", "proportional_int"); + CPanelAnimationVarAliasType(int, m_iColumnWidthNameMin, "column_name_min", "100", "proportional_int"); + CPanelAnimationVar(vgui2::HFont, m_CellFont, "cell_font", "Default"); + CPanelAnimationVar(vgui2::HFont, m_BadgeFont, "badge_font", "DefaultVerySmall"); + CPanelAnimationVar(Color, m_CellFilledColor, "cell_filled_color", "255 160 0 255"); + CPanelAnimationVar(Color, m_CellEmptyColor, "cell_empty_color", "84 56 16 255"); + CPanelAnimationVar(Color, m_CellCurrentColor, "cell_current_color", "255 255 255 255"); + CPanelAnimationVar(Color, m_CellLastColor, "cell_last_color", "255 64 32 255"); + CPanelAnimationVar(Color, m_BadgeBgColor, "badge_bgcolor", "255 160 0 255"); + CPanelAnimationVar(Color, m_BadgeFgColor, "badge_fgcolor", "0 0 0 255"); + CPanelAnimationVarAliasType(int, m_iCellDotSize, "cell_dot_size", "6", "proportional_int"); + CPanelAnimationVarAliasType(int, m_iCellDotGap, "cell_dot_gap", "2", "proportional_int"); + CPanelAnimationVarAliasType(int, m_iCellStripTall, "cell_strip_tall", "2", "proportional_int"); + CPanelAnimationVarAliasType(int, m_iCellStripGap, "cell_strip_gap", "1", "proportional_int"); + CPanelAnimationVarAliasType(int, m_iCellSpacing, "cell_spacing", "3", "proportional_int"); + + // GunGame preset, set in ScorePanel_gungame.res + CPanelAnimationVar(int, m_iGGWidePercent, "gg_wide_percent", "70"); + CPanelAnimationVar(int, m_iGGTopPercent, "gg_top_percent", "10"); + CPanelAnimationVar(int, m_iGGPingHigh, "gg_ping_high", "100"); + CPanelAnimationVar(Color, m_GGOwnRowColor, "gg_own_row_bgcolor", "255 160 0 56"); + CPanelAnimationVar(Color, m_GGFinalRowColor, "gg_final_row_bgcolor", "255 64 32 40"); + CPanelAnimationVar(Color, m_GGEmphasisColor, "gg_emphasis_color", "255 176 0 255"); + CPanelAnimationVar(Color, m_GGPlaceFirstColor, "gg_place_first_color", "255 160 0 255"); + CPanelAnimationVar(Color, m_GGPlaceFirstTextColor, "gg_place_first_textcolor", "0 0 0 255"); + CPanelAnimationVar(Color, m_GGPlaceTopColor, "gg_place_top_color", "112 72 16 255"); + CPanelAnimationVar(Color, m_GGPlaceFinalColor, "gg_place_final_color", "255 64 32 255"); + CPanelAnimationVar(Color, m_GGPingHighColor, "gg_ping_high_color", "255 80 80 255"); + CPanelAnimationVar(Color, m_GGBannerBgColor, "gg_banner_bgcolor", "255 64 32 48"); + CPanelAnimationVar(Color, m_GGBannerAccentColor, "gg_banner_accent_color", "255 160 0 255"); + CPanelAnimationVarAliasType(int, m_iGGBannerPadding, "gg_banner_padding", "3", "proportional_int"); + CPanelAnimationVarAliasType(int, m_iGGBannerAccentWide, "gg_banner_accent_wide", "2", "proportional_int"); + /** * Updates all labels, recreates all sections, recalculates all data. * Called when panel becomes visible. @@ -269,6 +361,67 @@ class CScorePanel : public vgui2::Frame, public IViewportPanel * Sorts rows in DESC order by frags. */ static bool StaticPlayerSortFuncByFrags(vgui2::SectionedListPanel *list, int itemID1, int itemID2); + + /** + * Returns true if team ilhs goes before team irhs. + */ + bool IsTeamBefore(int ilhs, int irhs); + + /** + * Loads ScorePanel_.res if the active preset has one, ScorePanel.res otherwise. + */ + void UpdateLayoutFile(); + + /** + * Builds m_CustomColumns. Sets the width of the panel in the GunGame preset. + */ + void BuildCustomColumns(); + + /** + * Returns the cell image at an index of m_pImageList. Creates it on first use. + */ + CScoreCellImage *GetCellImage(int index); + + /** + * Fills custom cells of a player row. + */ + void UpdateCustomCells(CPlayerInfo *pi, KeyValues *kv); + + /** + * Fills custom cells of a team section header. + */ + void UpdateCustomTeamHeader(int nTeamID); + + /** + * Updates the map line and the leader banner of the GunGame preset. + */ + void UpdateGunGameHeader(int iPlayerCount); + + /** + * Returns the place for the rank column, 0 for none. + */ + int GetPlayerRank(int client); + int GetTeamRank(int nTeamID); + + /** + * Returns true if the GunGame player is on the last level. + */ + bool IsOnLastLevel(int client); + + /** + * Returns true if a level value is on its last level (cur = max). + */ + static bool IsLastLevel(const CScoreboardData::Value &level); + + /** + * Returns true if player client1 goes before client2 in the custom scoreboard. + */ + static bool IsPlayerBefore(int client1, int client2); + + /** + * Sorts rows by the sort keys of the custom scoreboard. + */ + static bool StaticPlayerSortFuncCustom(vgui2::SectionedListPanel *list, int itemID1, int itemID2); }; #endif \ No newline at end of file diff --git a/src/game/client/vgui/score_panel_cells.cpp b/src/game/client/vgui/score_panel_cells.cpp new file mode 100644 index 00000000..05f158f7 --- /dev/null +++ b/src/game/client/vgui/score_panel_cells.cpp @@ -0,0 +1,426 @@ +#include +#include +#include +#include +#include +#include "hud.h" +#include "cl_util.h" +#include "hud_renderer.h" +#include "vgui/score_panel_cells.h" + +namespace +{ + +constexpr wchar_t ELLIPSIS = 0x2026; + +int GetTextWide(vgui2::HFont font, const wchar_t *text) +{ + int wide = 0; + + for (; *text; text++) + wide += vgui2::surface()->GetCharacterWidth(font, *text); + + return wide; +} + +/** + * Cuts the text with an ellipsis to fit into maxWide. Returns the width of the result. + */ +int FitText(vgui2::HFont font, wchar_t *text, int maxWide) +{ + int wide = GetTextWide(font, text); + + if (wide <= maxWide) + return wide; + + int ellipsisWide = vgui2::surface()->GetCharacterWidth(font, ELLIPSIS); + int len = 0; + wide = 0; + + for (; text[len]; len++) + { + int charWide = vgui2::surface()->GetCharacterWidth(font, text[len]); + + if (wide + charWide + ellipsisWide > maxWide) + break; + + wide += charWide; + } + + text[len] = ELLIPSIS; + text[len + 1] = L'\0'; + return wide + ellipsisWide; +} + +/** + * Draws a box with round corners line by line, so it doesn't depend on alpha blending. + */ +void DrawRoundedBox(int x0, int y0, int x1, int y1, int radius, Color color) +{ + radius = std::min(radius, std::min(x1 - x0, y1 - y0) / 2); + vgui2::surface()->DrawSetColor(color); + vgui2::surface()->DrawFilledRect(x0, y0 + radius, x1, y1 - radius); + + for (int i = 0; i < radius; i++) + { + float dy = radius - i - 0.5f; + int inset = (int)(radius - sqrtf(radius * radius - dy * dy) + 0.5f); + vgui2::surface()->DrawFilledRect(x0 + inset, y0 + i, x1 - inset, y0 + i + 1); + vgui2::surface()->DrawFilledRect(x0 + inset, y1 - i - 1, x1 - inset, y1 - i); + } +} + +int GetBadgePadding(const ScoreCellStyle &style) +{ + return vgui2::surface()->GetFontTall(style.hBadgeFont) / 3; +} + +int GetScoreBadgeWide(const ScoreCellStyle &style, const wchar_t *text) +{ + return GetTextWide(style.hBadgeFont, text) + 2 * GetBadgePadding(style); +} + +} + +CScoreCellImage::CScoreCellImage(const ScoreCellStyle &style) + : m_Style(style) +{ +} + +void CScoreCellImage::Clear() +{ + m_Kind = Kind::Empty; + m_iSprite = -1; + m_iCur = 0; + m_iMax = 0; + m_MarkColor = Color(0, 0, 0, 0); + m_wszText[0] = L'\0'; + m_wszBadge[0] = L'\0'; +} + +void CScoreCellImage::SetValue(bhl::sb::E_Display display, const CScoreboardData::Value &value) +{ + Clear(); + + if (value.IsEmpty()) + return; + + if (value.type == bhl::sb::E_ValueType::Progress && value.iMax > 0 + && (display == bhl::sb::E_Display::Meter || display == bhl::sb::E_Display::Steps)) + { + m_Kind = display == bhl::sb::E_Display::Meter ? Kind::Meter : Kind::Steps; + m_iCur = value.iValue; + m_iMax = value.iMax; + return; + } + + m_Kind = Kind::Text; + value.ToString(m_wszText, sizeof(m_wszText)); + + if (value.type == bhl::sb::E_ValueType::Icon && display == bhl::sb::E_Display::Icon && value.szSprite[0]) + { + m_Kind = Kind::Icon; + m_iSprite = gHUD.GetSpriteIndex(value.szSprite); + } +} + +void CScoreCellImage::SetText(const wchar_t *text) +{ + Clear(); + m_Kind = Kind::Text; + V_wcsncpy(m_wszText, text, sizeof(m_wszText)); +} + +void CScoreCellImage::SetPlace(int place, Color markColor) +{ + Clear(); + + if (place <= 0) + return; + + m_Kind = Kind::Place; + m_iCur = place; + m_MarkColor = markColor; +} + +void CScoreCellImage::SetBadge(const wchar_t *badge) +{ + V_wcsncpy(m_wszBadge, badge ? badge : L"", sizeof(m_wszBadge)); +} + +void CScoreCellImage::SetAlign(int align) +{ + m_iAlign = align; +} + +void CScoreCellImage::Paint() +{ + switch (m_Kind) + { + case Kind::Text: + case Kind::Icon: + PaintText(); + break; + case Kind::Meter: + PaintMeter(); + break; + case Kind::Steps: + PaintSteps(); + break; + case Kind::Place: + PaintPlace(); + break; + case Kind::Empty: + break; + } +} + +void CScoreCellImage::SetPos(int x, int y) +{ + m_iX = x; + m_iY = y; +} + +void CScoreCellImage::GetContentSize(int &wide, int &tall) +{ + wide = m_iWide; + tall = m_iTall; +} + +void CScoreCellImage::GetSize(int &wide, int &tall) +{ + GetContentSize(wide, tall); +} + +void CScoreCellImage::SetSize(int wide, int tall) +{ + m_iWide = wide; + m_iTall = tall; +} + +void CScoreCellImage::SetColor(Color col) +{ + m_Color = col; +} + +int CScoreCellImage::GetAlignOffset(int contentWide) +{ + int freeWide = std::max(m_iWide - contentWide, 0); + + if (m_iAlign == 1) + return freeWide / 2; + else if (m_iAlign == 2) + return freeWide; + + return 0; +} + +void CScoreCellImage::PaintText() +{ + vgui2::HFont font = m_Style.hFont; + int spacing = m_Style.iSpacing; + int yCenter = m_iY + m_iTall / 2; + + // Sprite scaled to the row height with its aspect ratio kept + wrect_t rc = {}; + int iconWide = 0; + int iconTall = 0; + + if (m_Kind == Kind::Icon && m_iSprite != -1 && CHudRenderer::Get().IsAvailable()) + { + rc = gHUD.GetSpriteRect(m_iSprite); + + if (rc.GetWidth() > 0 && rc.GetHeight() > 0) + { + iconTall = std::max(m_iTall - 2 * spacing, 1); + iconWide = rc.GetWidth() * iconTall / rc.GetHeight(); + + if (iconWide > m_iWide) + { + iconWide = m_iWide; + iconTall = rc.GetHeight() * iconWide / rc.GetWidth(); + } + } + } + + int iconSpace = iconWide > 0 ? iconWide + spacing : 0; + int badgeSpace = m_wszBadge[0] ? GetScoreBadgeWide(m_Style, m_wszBadge) + spacing : 0; + + wchar_t text[ARRAYSIZE(m_wszText)]; + V_wcsncpy(text, m_wszText, sizeof(text)); + int textWide = FitText(font, text, std::max(m_iWide - iconSpace - badgeSpace, 0)); + + int x = m_iX + GetAlignOffset(iconSpace + textWide + badgeSpace); + + if (iconWide > 0 && iconTall > 0) + { + CHudRenderer::SpriteSet(gHUD.GetSprite(m_iSprite), m_Color.r(), m_Color.g(), m_Color.b()); + CHudRenderer::SpriteDrawAdditiveScaled(0, x, yCenter - iconTall / 2, iconWide, iconTall, &rc); + x += iconSpace; + } + + DrawCellText(font, x, yCenter - vgui2::surface()->GetFontTall(font) / 2, m_Color, text); + + if (badgeSpace > 0) + DrawScoreBadge(m_Style, x + textWide + spacing, yCenter, m_wszBadge); +} + +void CScoreCellImage::PaintMeter() +{ + vgui2::HFont font = m_Style.hFont; + wchar_t counter[32]; + V_snwprintf(counter, ARRAYSIZE(counter), L"%d/%d", m_iCur, m_iMax); + + int counterWide = GetTextWide(font, counter); + int spacing = m_Style.iSpacing; + int gap = m_Style.iDotGap; + int maxDots = bhl::sb::MAX_DOTS; + int dot = (m_iWide - counterWide - spacing - (maxDots - 1) * gap) / maxDots; + dot = std::min(std::min(dot, m_Style.iDotSize), m_iTall); + + // The bar has the length of a full row of dots + int barWide = dot > 0 ? maxDots * dot + (maxDots - 1) * gap : 0; + int x = m_iX + GetAlignOffset(barWide + spacing + counterWide); + int y = m_iY + (m_iTall - dot) / 2; + int cur = std::clamp(m_iCur, 0, m_iMax); + + if (dot > 0 && m_iMax <= maxDots) + { + for (int i = 0; i < m_iMax; i++) + { + int dotX = x + i * (dot + gap); + DrawRoundedBox(dotX, y, dotX + dot, y + dot, dot / 2, i < cur ? m_Style.filledColor : m_Style.emptyColor); + } + } + else if (dot > 0) + { + DrawRoundedBox(x, y, x + barWide, y + dot, dot / 2, m_Style.emptyColor); + + if (cur > 0) + DrawRoundedBox(x, y, x + std::max(barWide * cur / m_iMax, dot), y + dot, dot / 2, m_Style.filledColor); + } + + DrawCellText(font, x + barWide + spacing, m_iY + (m_iTall - vgui2::surface()->GetFontTall(font)) / 2, m_Color, counter); +} + +void CScoreCellImage::PaintSteps() +{ + vgui2::HFont font = m_Style.hFont; + wchar_t text[32]; + V_snwprintf(text, ARRAYSIZE(text), L"%d/%d", m_iCur, m_iMax); + + int textTall = vgui2::surface()->GetFontTall(font); + int stripTall = m_Style.iStripTall; + int y = m_iY + (m_iTall - (textTall + m_Style.iStripGap + stripTall)) / 2; + DrawCellText(font, m_iX + GetAlignOffset(GetTextWide(font, text)), y, m_Color, text); + + int stripY = y + textTall + m_Style.iStripGap; + + if (m_iMax * 2 > m_iWide) + { + // Too many steps for separate segments + int fillWide = m_iWide * std::clamp(m_iCur, 0, m_iMax) / m_iMax; + vgui2::surface()->DrawSetColor(m_Style.filledColor); + vgui2::surface()->DrawFilledRect(m_iX, stripY, m_iX + fillWide, stripY + stripTall); + vgui2::surface()->DrawSetColor(m_Style.emptyColor); + vgui2::surface()->DrawFilledRect(m_iX + fillWide, stripY, m_iX + m_iWide, stripY + stripTall); + return; + } + + int gap = m_iMax * 3 <= m_iWide ? 1 : 0; + + for (int i = 0; i < m_iMax; i++) + { + int x0 = m_iX + i * (m_iWide + gap) / m_iMax; + int x1 = m_iX + (i + 1) * (m_iWide + gap) / m_iMax - gap; + Color color; + + if (i == m_iCur - 1) + color = m_Style.currentColor; + else if (i < m_iCur - 1) + color = m_Style.filledColor; + else if (i == m_iMax - 1) + color = m_Style.lastColor; + else + color = m_Style.emptyColor; + + vgui2::surface()->DrawSetColor(color); + vgui2::surface()->DrawFilledRect(x0, stripY, x1, stripY + stripTall); + } +} + +void CScoreCellImage::PaintPlace() +{ + vgui2::HFont font = m_Style.hFont; + wchar_t text[16]; + V_snwprintf(text, ARRAYSIZE(text), L"%d", m_iCur); + + int textWide = GetTextWide(font, text); + int textTall = vgui2::surface()->GetFontTall(font); + int textY = m_iY + (m_iTall - textTall) / 2; + + if (m_MarkColor.a() == 0) + { + DrawCellText(font, m_iX + GetAlignOffset(textWide), textY, m_Color, text); + return; + } + + int size = std::min(std::max(textWide, textTall) + m_Style.iSpacing, m_iTall); + int x = m_iX + GetAlignOffset(size); + int y = m_iY + (m_iTall - size) / 2; + DrawRoundedBox(x, y, x + size, y + size, size / 2, m_MarkColor); + DrawCellText(font, x + (size - textWide) / 2, textY, m_Color, text); +} + +void DrawScoreBadge(const ScoreCellStyle &style, int x, int yCenter, const wchar_t *text) +{ + int padding = GetBadgePadding(style); + int tall = vgui2::surface()->GetFontTall(style.hBadgeFont); + int y = yCenter - tall / 2; + + DrawRoundedBox(x, y, x + GetScoreBadgeWide(style, text), y + tall, padding, style.badgeBgColor); + DrawCellText(style.hBadgeFont, x + padding, y, style.badgeFgColor, text); +} + +void DrawCellText(vgui2::HFont font, int x, int y, Color color, const wchar_t *text) +{ + vgui2::surface()->DrawSetTextFont(font); + vgui2::surface()->DrawSetTextColor(color); + vgui2::surface()->DrawSetTextPos(x, y); + vgui2::surface()->DrawPrintText(text, wcslen(text)); +} + +void ConstructScoreText(wchar_t *buf, int bufSizeBytes, const char *token, int count, const wchar_t *arg1, const wchar_t *arg2, const wchar_t *arg3) +{ + wchar_t *format = g_pVGuiLocalize->Find(token); + + if (!format) + { + buf[0] = L'\0'; + return; + } + + g_pVGuiLocalize->ConstructString(buf, bufSizeBytes, format, count, arg1, arg2, arg3); +} + +void FormatScoreKills(wchar_t *buf, int bufSizeBytes, int kills) +{ + char token[32]; + wchar_t number[16]; + snprintf(token, sizeof(token), "BHL_GG_Kills%s", CScoreboardData::GetPluralSuffix(kills)); + V_snwprintf(number, ARRAYSIZE(number), L"%d", kills); + ConstructScoreText(buf, bufSizeBytes, token, 1, number); +} + +void ScoreTextToUpper(wchar_t *text) +{ + for (; *text; text++) + { + wchar_t c = *text; + + if ((c >= L'a' && c <= L'z') || (c >= 0xE0 && c <= 0xFE && c != 0xF7) || (c >= 0x430 && c <= 0x44F)) + *text = c - 0x20; + else if (c >= 0x450 && c <= 0x45F) + *text = c - 0x50; + } +} diff --git a/src/game/client/vgui/score_panel_cells.h b/src/game/client/vgui/score_panel_cells.h new file mode 100644 index 00000000..7f6c10e0 --- /dev/null +++ b/src/game/client/vgui/score_panel_cells.h @@ -0,0 +1,121 @@ +#ifndef VGUI_SCORE_PANEL_CELLS_H +#define VGUI_SCORE_PANEL_CELLS_H +#include +#include +#include +#include "scoreboard_data.h" + +/** + * Fonts, colors and sizes of custom scoreboard cells. + * Owned by CScorePanel and shared by all cells. + * Fills are drawn opaque: after text the engine may draw translucent fills without blending. + */ +struct ScoreCellStyle +{ + vgui2::HFont hFont = vgui2::INVALID_FONT; + vgui2::HFont hBadgeFont = vgui2::INVALID_FONT; + Color filledColor; //!< Filled dots and bar, passed steps + Color emptyColor; //!< Empty dots and bar, next steps + Color currentColor; //!< Current step + Color lastColor; //!< Last step + Color badgeBgColor; + Color badgeFgColor; + int iDotSize = 0; //!< Maximum diameter of a dot + int iDotGap = 0; + int iStripTall = 0; //!< Height of the steps strip + int iStripGap = 0; //!< Distance between the steps text and the strip + int iSpacing = 0; //!< Distance between icon, text, badge and counter +}; + +/** + * Image of a custom scoreboard cell: text, icon, meter, steps or place. + * Draws within the bounds set by the row. An empty cell draws nothing. + */ +class CScoreCellImage : public vgui2::IImage +{ +public: + CScoreCellImage(const ScoreCellStyle &style); + + /** + * Sets a value of the store drawn as display (docs/scoreboard-protocol.md, 6.6). + * Content setters clear the badge. + */ + void SetValue(bhl::sb::E_Display display, const CScoreboardData::Value &value); + void SetText(const wchar_t *text); + + /** + * Sets a place with a round mark behind it. + * @param place Place, 0 for an empty cell + * @param markColor Color of the mark, alpha 0 for no mark + */ + void SetPlace(int place, Color markColor); + + //! Sets the badge after the text, nullptr for none + void SetBadge(const wchar_t *badge); + + //! @param align 0 left, 1 center, 2 right + void SetAlign(int align); + + // IImage overrides + virtual void Paint() override; + virtual void SetPos(int x, int y) override; + virtual void GetContentSize(int &wide, int &tall) override; + virtual void GetSize(int &wide, int &tall) override; + virtual void SetSize(int wide, int tall) override; + virtual void SetColor(Color col) override; + +private: + enum class Kind + { + Empty, + Text, + Icon, + Meter, + Steps, + Place, + }; + + const ScoreCellStyle &m_Style; + Kind m_Kind = Kind::Empty; + int m_iAlign = 0; + int m_iX = 0, m_iY = 0; + int m_iWide = 0, m_iTall = 0; + int m_iSprite = -1; + int m_iCur = 0, m_iMax = 0; + Color m_Color = Color(255, 255, 255, 255); + Color m_MarkColor = Color(0, 0, 0, 0); + wchar_t m_wszText[128] = {}; + wchar_t m_wszBadge[32] = {}; + + void Clear(); + int GetAlignOffset(int contentWide); + void PaintText(); + void PaintMeter(); + void PaintSteps(); + void PaintPlace(); +}; + +/** + * Draws a badge vertically centered on yCenter. + */ +void DrawScoreBadge(const ScoreCellStyle &style, int x, int yCenter, const wchar_t *text); + +void DrawCellText(vgui2::HFont font, int x, int y, Color color, const wchar_t *text); + +/** + * Builds a string from a localization token with %s1..%s3. + * A missing token gives an empty string. + */ +void ConstructScoreText(wchar_t *buf, int bufSizeBytes, const char *token, int count, const wchar_t *arg1, const wchar_t *arg2 = nullptr, const wchar_t *arg3 = nullptr); + +/** + * Builds "N kills" with the plural form of the client language. + */ +void FormatScoreKills(wchar_t *buf, int bufSizeBytes, int kills); + +/** + * Converts the string to uppercase, including Latin-1 and Cyrillic letters (towupper doesn't in the C locale). + */ +void ScoreTextToUpper(wchar_t *text); + +#endif diff --git a/src/game/server/CBugfixedServer.cpp b/src/game/server/CBugfixedServer.cpp index e2f25171..56f690a8 100644 --- a/src/game/server/CBugfixedServer.cpp +++ b/src/game/server/CBugfixedServer.cpp @@ -21,6 +21,25 @@ CBugfixedServer *serverapi() return &g_staticserver; } +CON_COMMAND(bhl_caps, "Prints capabilities of connected clients") +{ + serverapi()->PrintClientCaps(); +} + +//! Parses "_bhl": 1 to 8 hex digits, anything else is 0 +static bhl::E_ClientCaps ParseClientCaps(const char *value) +{ + if (!value) + return bhl::E_ClientCaps::None; + + size_t len = strlen(value); + + if (len < 1 || len > 8 || strspn(value, "0123456789abcdefABCDEF") != len) + return bhl::E_ClientCaps::None; + + return (bhl::E_ClientCaps)strtoul(value, nullptr, 16); +} + //---------------------------------------------------------------------------------------------------- // CBugfixedServer //---------------------------------------------------------------------------------------------------- @@ -41,6 +60,14 @@ void CBugfixedServer::ClientConnect(edict_t *pEntity) ResetPlayerData(idx); const char *authId = GETPLAYERAUTHID(pEntity); + m_pClientInfo[idx].isConnected = true; + m_pClientInfo[idx].isBot = (pEntity->v.flags & FL_FAKECLIENT) || (authId && !strcmp(authId, "BOT")); + m_Scoreboard.ClearPlayer(idx); + ReadClientCaps(pEntity, g_engfuncs.pfnGetInfoKeyBuffer(pEntity)); + + if (m_pClientInfo[idx].isBot && m_pClientInfo[idx].capsSource == CAPS_SOURCE_UNKNOWN) + m_pClientInfo[idx].capsSource = CAPS_SOURCE_NONE; + // Bots can't receive network messages if (pEntity->v.flags & FL_FAKECLIENT) { @@ -78,6 +105,12 @@ void CBugfixedServer::PlayerPostThink(edict_t *pEntity) CheckClientSteamID(pEntity); m_pClientInfo[idx].nextAuthCheck = gpGlobals->time + 0.1; } + + if (m_pClientInfo[idx].isCapsQueryDeferred && gpGlobals->time >= m_pClientInfo[idx].nextCapsQuery) + { + QueryClientCaps(pEntity); + m_pClientInfo[idx].nextCapsQuery = gpGlobals->time + 0.1; + } } void CBugfixedServer::CvarValueCallback(const edict_t *pEnt, int requestID, const char *cvarName, const char *value) @@ -106,6 +139,13 @@ void CBugfixedServer::CvarValueCallback(const edict_t *pEnt, int requestID, cons int iValue = atoi(value); m_pClientInfo[idx].isColorEnabled = (iValue == 1); } + else if (requestID == REQUESTID_CAPS && !strcmp(cvarName, bhl::sb::CAPS_KEY)) + { + // Other plugins get their answers here too, hence the name check. + // Userinfo wins over a late answer. + if (m_pClientInfo[idx].isCapsQueried && m_pClientInfo[idx].capsSource != CAPS_SOURCE_USERINFO) + SetClientCaps(idx, ParseClientCaps(value), CAPS_SOURCE_QUERY); + } } bool CBugfixedServer::IsClientSupportsReceived(int index) @@ -113,6 +153,93 @@ bool CBugfixedServer::IsClientSupportsReceived(int index) return m_pClientInfo[index].isSupportsReceived; } +void CBugfixedServer::ClientUserInfoChanged(edict_t *pEntity, char *infobuffer) +{ + int idx = ENTINDEX(pEntity); + if (idx < 1 || idx > gpGlobals->maxClients) + return; + + ReadClientCaps(pEntity, infobuffer); +} + +void CBugfixedServer::ClientDisconnect(edict_t *pEntity) +{ + int idx = ENTINDEX(pEntity); + if (idx < 1 || idx > gpGlobals->maxClients) + return; + + m_Scoreboard.ClearPlayer(idx); + ResetPlayerData(idx); +} + +void CBugfixedServer::InitHUD(edict_t *pEntity) +{ + int idx = ENTINDEX(pEntity); + bhl_client_info_t &clientInfo = m_pClientInfo[idx]; + const char *authId = GETPLAYERAUTHID(pEntity); + + clientInfo.isReady = true; + clientInfo.isProxy = (pEntity->v.flags & FL_PROXY) || (authId && !strcmp(authId, "HLTV")); + + // Also when inactive: a schema turned on later must still wait for the InitHUD burst + if (IsScoreboardClient(idx)) + m_Scoreboard.StartFullSync(idx, true); + + QueryClientCaps(pEntity); +} + +void CBugfixedServer::StartFrame() +{ + m_Scoreboard.StartFrame(); +} + +void CBugfixedServer::ServerDeactivate() +{ + for (bhl_client_info_t &clientInfo : m_pClientInfo) + clientInfo.isReady = false; + + m_Scoreboard.ClearAll(); +} + +bool CBugfixedServer::IsClientConnected(int idx) +{ + return m_pClientInfo[idx].isConnected; +} + +bool CBugfixedServer::IsScoreboardClient(int idx) +{ + const bhl_client_info_t &clientInfo = m_pClientInfo[idx]; + + return clientInfo.isReady && !clientInfo.isBot && !clientInfo.isProxy + && IsEnumFlagSet(clientInfo.caps, bhl::E_ClientCaps::ScoreboardV1); +} + +void CBugfixedServer::QueryUnknownClientCaps() +{ + for (int i = 1; i <= gpGlobals->maxClients; i++) + { + if (m_pClientInfo[i].isReady) + QueryClientCaps(INDEXENT(i)); + } +} + +void CBugfixedServer::PrintClientCaps() +{ + static const char *sourceNames[] = { "unknown", "userinfo", "query", "none" }; + + g_engfuncs.pfnServerPrint(UTIL_VarArgs("%4s %-32s %8s %s\n", "slot", "name", "caps", "source")); + + for (int i = 1; i <= gpGlobals->maxClients; i++) + { + const bhl_client_info_t &clientInfo = m_pClientInfo[i]; + + if (!clientInfo.isConnected) + continue; + + g_engfuncs.pfnServerPrint(UTIL_VarArgs("%4d %-32s %8x %s\n", i, STRING(INDEXENT(i)->v.netname), (unsigned int)clientInfo.caps, sourceNames[clientInfo.capsSource])); + } +} + void CBugfixedServer::ResetPlayerData(int idx) { m_pClientInfo[idx] = bhl_client_info_t(); @@ -129,32 +256,13 @@ void CBugfixedServer::CheckClientSteamID(edict_t *pEntity) } else { - bool isAuthed = false; - bool allowQuery = false; - const char *authId = GETPLAYERAUTHID(pEntity); + E_CvarQuery query = GetCvarQueryState(pEntity); - if (authId) + if (query != CVARQUERY_PENDING) { - if (strcmp(authId, "STEAM_ID_PENDING") != 0) - { - isAuthed = true; - clientInfo.isAuthed = true; - - if (!strcmp(authId, "STEAM_ID_LAN") || !strncmp(authId, "VALVE_", 6)) - { - // p47 clients don't support QueryClientCvarValue2 - allowQuery = false; - } - else - { - allowQuery = true; - } - } - } + clientInfo.isAuthed = true; - if (isAuthed) - { - if (allowQuery) + if (query == CVARQUERY_ALLOWED) QueryClientCvars(pEntity); else QueryUnsupportedClientCvars(pEntity); @@ -162,6 +270,20 @@ void CBugfixedServer::CheckClientSteamID(edict_t *pEntity) } } +CBugfixedServer::E_CvarQuery CBugfixedServer::GetCvarQueryState(edict_t *pEntity) +{ + const char *authId = GETPLAYERAUTHID(pEntity); + + if (!authId || !strcmp(authId, "STEAM_ID_PENDING")) + return CVARQUERY_PENDING; + + // p47 clients don't support QueryClientCvarValue2 + if (!strcmp(authId, "STEAM_ID_LAN") || !strncmp(authId, "VALVE_", 6)) + return CVARQUERY_DENIED; + + return CVARQUERY_ALLOWED; +} + void CBugfixedServer::QueryClientCvars(edict_t *pEntity) { g_engfuncs.pfnQueryClientCvarValue2(pEntity, "aghl_supports", REQUESTID_SUPPORTS); @@ -187,6 +309,68 @@ void CBugfixedServer::OnClientSupportsReceived(edict_t *pEntity) m_pClientInfo[ENTINDEX(pEntity)].isSupportsReceived = true; } +void CBugfixedServer::ReadClientCaps(edict_t *pEntity, char *infobuffer) +{ + int idx = ENTINDEX(pEntity); + bhl_client_info_t &clientInfo = m_pClientInfo[idx]; + const char *value = g_engfuncs.pfnInfoKeyValue(infobuffer, bhl::sb::CAPS_KEY); + + if (value[0]) + { + SetClientCaps(idx, ParseClientCaps(value), CAPS_SOURCE_USERINFO); + } + else if (clientInfo.capsSource == CAPS_SOURCE_USERINFO) + { + clientInfo.capsSource = CAPS_SOURCE_UNKNOWN; + clientInfo.isCapsQueried = false; + + if (clientInfo.isReady) + QueryClientCaps(pEntity); + } +} + +void CBugfixedServer::QueryClientCaps(edict_t *pEntity) +{ + int idx = ENTINDEX(pEntity); + bhl_client_info_t &clientInfo = m_pClientInfo[idx]; + + clientInfo.isCapsQueryDeferred = false; + + if (clientInfo.capsSource != CAPS_SOURCE_UNKNOWN || clientInfo.isCapsQueried) + return; + + if (!m_Scoreboard.IsActive() && !sv_bhl_query_vars.GetBool()) + return; + + E_CvarQuery query = (clientInfo.isBot || clientInfo.isProxy) ? CVARQUERY_DENIED : GetCvarQueryState(pEntity); + + if (query == CVARQUERY_ALLOWED) + { + clientInfo.isCapsQueried = true; + g_engfuncs.pfnQueryClientCvarValue2(pEntity, bhl::sb::CAPS_KEY, REQUESTID_CAPS); + } + else if (query == CVARQUERY_DENIED) + { + SetClientCaps(idx, bhl::E_ClientCaps::None, CAPS_SOURCE_NONE); + } + else + { + clientInfo.isCapsQueryDeferred = true; + } +} + +void CBugfixedServer::SetClientCaps(int idx, bhl::E_ClientCaps caps, E_CapsSource source) +{ + bool hadScoreboard = IsScoreboardClient(idx); + + m_pClientInfo[idx].caps = caps; + m_pClientInfo[idx].capsSource = source; + + // A client that lost the cap is skipped by the scoreboard without a Reset + if (!hadScoreboard && IsScoreboardClient(idx)) + m_Scoreboard.StartFullSync(idx, false); +} + //---------------------------------------------------------------------------------------------------- // IBugfixedServer methods //---------------------------------------------------------------------------------------------------- @@ -351,3 +535,18 @@ void CBugfixedServer::SetPlayerScore(int idx, int frags, int deaths) pPlayer->m_iDeaths = deaths; pPlayer->SendScoreInfo(); } + +bhl::E_ClientCaps CBugfixedServer::GetClientCaps(int idx) +{ + if (idx < 1 || idx > gpGlobals->maxClients) + { + UTIL_LogPrintf("CBugfixedServer::GetClientCaps(): invalid player id (%d)\n", idx); + return bhl::E_ClientCaps::None; + } + return m_pClientInfo[idx].caps; +} + +bhl::IScoreboardExt *CBugfixedServer::GetScoreboard() +{ + return &m_Scoreboard; +} diff --git a/src/game/server/CBugfixedServer.h b/src/game/server/CBugfixedServer.h index 6ba5ae04..083f31d9 100644 --- a/src/game/server/CBugfixedServer.h +++ b/src/game/server/CBugfixedServer.h @@ -5,6 +5,7 @@ #include #include "eiface.h" #include "progdefs.h" +#include "CScoreboardExt.h" #ifndef BUGFIXEDAPI_REQUEST_BASE #define BUGFIXEDAPI_REQUEST_BASE 1 @@ -23,6 +24,21 @@ class CBugfixedServer : public bhl::IBugfixedServer void PlayerPostThink(edict_t *pEntity); void CvarValueCallback(const edict_t *pEnt, int requestID, const char *cvarName, const char *value); bool IsClientSupportsReceived(int index); + void ClientUserInfoChanged(edict_t *pEntity, char *infobuffer); + void ClientDisconnect(edict_t *pEntity); + void InitHUD(edict_t *pEntity); + void StartFrame(); + void ServerDeactivate(); + + bool IsClientConnected(int idx); + + //! Whether the client gets "BhlScore": passed InitHUD, has ScoreboardV1, not a bot or HLTV + bool IsScoreboardClient(int idx); + + //! Queries "_bhl" from clients that passed InitHUD and haven't reported it + void QueryUnknownClientCaps(); + + void PrintClientCaps(); private: enum E_RequestType @@ -37,9 +53,25 @@ class CBugfixedServer : public bhl::IBugfixedServer REQUESTID_VERSION = 0, REQUESTID_SUPPORTS, REQUESTID_COLOR, + REQUESTID_CAPS, REQUESTID_END }; + enum E_CvarQuery + { + CVARQUERY_ALLOWED = 0, + CVARQUERY_DENIED, //!< p47 or LAN client + CVARQUERY_PENDING //!< No SteamID yet + }; + + enum E_CapsSource + { + CAPS_SOURCE_UNKNOWN = 0, + CAPS_SOURCE_USERINFO, + CAPS_SOURCE_QUERY, + CAPS_SOURCE_NONE + }; + struct bhl_client_info_t { CGameVersion version; @@ -49,17 +81,32 @@ class CBugfixedServer : public bhl::IBugfixedServer bool isAuthed = false; //!< Whether the player has received a SteamID float nextAuthCheck = 0; //!< Next time to check for SteamID bool isSupportsReceived = false; + + bool isConnected = false; + bool isReady = false; //!< InitHUD was sent + bool isBot = false; //!< Cached on connect because Spawn clears FL_FAKECLIENT + bool isProxy = false; //!< HLTV + bhl::E_ClientCaps caps = bhl::E_ClientCaps::None; + E_CapsSource capsSource = CAPS_SOURCE_UNKNOWN; + bool isCapsQueried = false; + bool isCapsQueryDeferred = false; //!< Waits for a SteamID + float nextCapsQuery = 0; }; bhl_client_info_t m_pClientInfo[MAX_PLAYERS + 1]; CGameVersion m_ServerVersion; bhl::E_MotdType m_nMotdType = bhl::E_MotdType::All; + CScoreboardExt m_Scoreboard; void ResetPlayerData(int idx); void CheckClientSteamID(edict_t *pEntity); + E_CvarQuery GetCvarQueryState(edict_t *pEntity); void QueryClientCvars(edict_t *pEntity); void QueryUnsupportedClientCvars(edict_t *pEntity); void OnClientSupportsReceived(edict_t *pEntity); + void ReadClientCaps(edict_t *pEntity, char *infobuffer); + void QueryClientCaps(edict_t *pEntity); + void SetClientCaps(int idx, bhl::E_ClientCaps caps, E_CapsSource source); public: //---------------------------------------------------------------------------------------------------- @@ -77,6 +124,8 @@ class CBugfixedServer : public bhl::IBugfixedServer virtual void ShowMotdFromString(bhl::E_MotdType type, int idx, const char *str); virtual void ShowMotdFromFile(bhl::E_MotdType type, int idx, const char *file); virtual void SetPlayerScore(int idx, int frags, int deaths); + virtual bhl::E_ClientCaps GetClientCaps(int idx); + virtual bhl::IScoreboardExt *GetScoreboard(); }; CBugfixedServer *serverapi(); diff --git a/src/game/server/CMakeLists.txt b/src/game/server/CMakeLists.txt index abc27166..b85269f5 100644 --- a/src/game/server/CMakeLists.txt +++ b/src/game/server/CMakeLists.txt @@ -40,6 +40,8 @@ set( SOURCE_FILES controller.cpp crossbow.cpp crowbar.cpp + CScoreboardExt.cpp + CScoreboardExt.h decals.h defaultai.cpp defaultai.h diff --git a/src/game/server/CScoreboardExt.cpp b/src/game/server/CScoreboardExt.cpp new file mode 100644 index 00000000..fccfb12b --- /dev/null +++ b/src/game/server/CScoreboardExt.cpp @@ -0,0 +1,871 @@ +#include "extdll.h" +#include "util.h" +#include "cbase.h" +#include "gamerules.h" +#include "CBugfixedServer.h" +#include "CScoreboardExt.h" + +extern int gmsgBhlScore; + +//! Copies a string and truncates it on a UTF-8 character boundary +template +static void CopyString(char (&dst)[N], const char *src) +{ + if (!src) + src = ""; + + int len = (int)strlen(src); + + if (len >= (int)N) + { + len = (int)N - 1; + + while (len > 0 && ((unsigned char)src[len] & 0xC0) == 0x80) + len--; + } + + memcpy(dst, src, len); + dst[len] = '\0'; +} + +static bool IsValidKey(const char *key) +{ + if (!key) + return false; + + int len = (int)strlen(key); + return len >= 1 && len <= bhl::sb::MAX_KEY_LEN && (int)strspn(key, "abcdefghijklmnopqrstuvwxyz0123456789_") == len; +} + +static int ClampWord(int value) +{ + return std::clamp(value, 0, 65535); +} + +static bool IsByteProgress(int cur, int max) +{ + return cur >= 0 && cur <= 255 && max >= 0 && max <= 255; +} + +//---------------------------------------------------------------------------------------------------- +// CScoreboardExt +//---------------------------------------------------------------------------------------------------- +void CScoreboardExt::ClearAll() +{ + ClearSchema(); + + for (char *name : m_szTeamNames) + name[0] = '\0'; + + m_iTeamCount = 0; + + for (client_state_t &state : m_Clients) + state = client_state_t(); +} + +void CScoreboardExt::ClearPlayer(int idx) +{ + bool hasCells = false; + + for (value_t &cell : m_Cells[idx]) + { + if (cell.type != bhl::sb::E_ValueType::None) + { + hasCells = true; + cell = value_t(); + } + } + + for (client_state_t &state : m_Clients) + { + if (m_bActive && (hasCells || state.cellsDirty[idx])) + state.playersCleared |= 1ULL << (idx - 1); + + state.cellsDirty[idx] = 0; + } + + m_Clients[idx] = client_state_t(); +} + +void CScoreboardExt::StartFullSync(int idx, bool delay) +{ + client_state_t &state = m_Clients[idx]; + float nextSendTime = delay ? gpGlobals->time + FULL_SYNC_DELAY : state.nextSendTime; + + state = client_state_t(); + state.nextSendTime = nextSendTime; + state.isResetPending = true; + + if (!m_bActive) + return; + + state.isConfigPending = true; + state.columnsPending = (1u << m_iColumnCount) - 1; + + for (int i = 0; i < m_iListCount; i++) + { + if (m_Lists[i].count == 0) + continue; + + state.listsResized |= 1u << i; + + for (int j = 0; j < m_Lists[i].count; j++) + { + if (m_Lists[i].items[j].type != bhl::sb::E_ValueType::None) + state.listItemsDirty[i] |= 1ULL << j; + } + } + + for (int target = 0; target < MAX_TARGETS; target++) + { + for (int column = 0; column < m_iColumnCount; column++) + { + if (m_Cells[target][column].type != bhl::sb::E_ValueType::None) + state.cellsDirty[target] |= 1u << column; + } + } +} + +void CScoreboardExt::StartFrame() +{ + if (!gmsgBhlScore) + return; + + if (m_bActive) + { + for (int i = 0; i < m_iTeamCount; i++) + { + int index = g_pGameRules ? g_pGameRules->GetTeamIndex(m_szTeamNames[i]) : -1; + m_TeamNumbers[i] = index >= 0 && index < MAX_TEAMS ? index + 1 : 0; + } + } + + for (int i = 1; i <= gpGlobals->maxClients; i++) + { + if (!serverapi()->IsScoreboardClient(i) || gpGlobals->time < m_Clients[i].nextSendTime) + continue; + + if (!SendToClient(i)) + m_Clients[i].nextSendTime = gpGlobals->time + BUDGET_DELAY; + } +} + +//---------------------------------------------------------------------------------------------------- +// IScoreboardExt methods +//---------------------------------------------------------------------------------------------------- +void CScoreboardExt::Reset() +{ + ClearSchema(); + + for (int i = 1; i <= MAX_PLAYERS; i++) + { + if (i <= gpGlobals->maxClients && serverapi()->IsScoreboardClient(i)) + StartFullSync(i, false); + else + m_Clients[i] = client_state_t(); + } +} + +void CScoreboardExt::SetConfig(unsigned int hideFlags, const char *preset, const char *title, const char *tag) +{ + m_iHideFlags = hideFlags & 0xFFFF; + CopyString(m_szPreset, preset); + CopyString(m_szTitle, title); + CopyString(m_szTag, tag); + + if (m_bActive) + { + for (client_state_t &state : m_Clients) + state.isConfigPending = true; + + return; + } + + m_bActive = true; + + for (int i = 1; i <= gpGlobals->maxClients; i++) + { + if (serverapi()->IsScoreboardClient(i)) + StartFullSync(i, false); + } + + serverapi()->QueryUnknownClientCaps(); +} + +bool CScoreboardExt::AddColumn(const char *key, const char *title, int display, int width, int sort, unsigned int flags) +{ + if (!IsValidKey(key)) + return false; + + int id = FindColumn(key); + + if (id == -1) + { + if (m_iColumnCount == bhl::sb::MAX_COLUMNS) + return false; + + id = m_iColumnCount++; + } + + column_t &column = m_Columns[id]; + CopyString(column.key, key); + CopyString(column.title, title); + column.display = std::clamp(display, 0, 255); + column.flags = flags & 0xFFFF; + column.width = std::clamp(width, 0, 255); + column.sort = std::clamp(sort, 0, 255); + + if (column.display == (int)bhl::sb::E_Display::Builtin) + { + for (int target = 0; target < MAX_TARGETS; target++) + ClearCell(target, id); + } + + if (m_bActive) + { + for (client_state_t &state : m_Clients) + state.columnsPending |= 1u << id; + } + + return true; +} + +int CScoreboardExt::GetTeamTarget(const char *teamName) +{ + if (!teamName || !teamName[0]) + return -1; + + char name[MAX_TEAM_NAME]; + CopyString(name, teamName); + + for (int i = 0; i < m_iTeamCount; i++) + { + if (!_stricmp(m_szTeamNames[i], name)) + return TEAM_TARGET_BASE + i; + } + + if (m_iTeamCount == MAX_TEAMS) + return -1; + + CopyString(m_szTeamNames[m_iTeamCount], name); + return TEAM_TARGET_BASE + m_iTeamCount++; +} + +void CScoreboardExt::SetInt(int target, const char *key, int value) +{ + value_t cell; + cell.type = bhl::sb::E_ValueType::Int; + cell.value = value; + SetCell(target, key, cell); +} + +void CScoreboardExt::SetText(int target, const char *key, const char *text) +{ + value_t cell; + cell.type = bhl::sb::E_ValueType::Text; + CopyString(cell.text, text); + SetCell(target, key, cell); +} + +void CScoreboardExt::SetIcon(int target, const char *key, const char *sprite, const char *text) +{ + value_t cell; + cell.type = bhl::sb::E_ValueType::Icon; + CopyString(cell.sprite, sprite); + CopyString(cell.text, text); + SetCell(target, key, cell); +} + +void CScoreboardExt::SetProgress(int target, const char *key, int cur, int max) +{ + value_t cell; + cell.type = bhl::sb::E_ValueType::Progress; + cell.value = cur; + cell.max = max; + SetCell(target, key, cell); +} + +void CScoreboardExt::Clear(int target, const char *key) +{ + if (key && key[0]) + { + SetCell(target, key, value_t()); + return; + } + + int cellTarget = GetCellTarget(target); + + if (cellTarget == -1) + return; + + for (int column = 0; column < m_iColumnCount; column++) + ClearCell(cellTarget, column); +} + +bool CScoreboardExt::ListResize(const char *key, int count) +{ + if (!IsValidKey(key)) + return false; + + int id = FindList(key); + + if (id == -1) + { + if (m_iListCount == bhl::sb::MAX_LISTS) + return false; + + id = m_iListCount++; + CopyString(m_Lists[id].key, key); + } + + list_t &list = m_Lists[id]; + count = std::clamp(count, 0, bhl::sb::MAX_LIST_ITEMS); + + if (list.count == count) + return true; + + for (int i = count; i < list.count; i++) + list.items[i] = value_t(); + + uint64_t itemsMask = count == bhl::sb::MAX_LIST_ITEMS ? ~0ULL : (1ULL << count) - 1; + + // The client still has old values there if it missed the smaller total, so grown items are sent even if empty + uint64_t grownItems = count > list.count ? itemsMask & ~((1ULL << list.count) - 1) : 0; + + list.count = count; + + if (m_bActive) + { + for (client_state_t &state : m_Clients) + { + state.listsResized |= 1u << id; + state.listItemsDirty[id] = (state.listItemsDirty[id] & itemsMask) | grownItems; + } + } + + return true; +} + +void CScoreboardExt::ListSetInt(const char *key, int index, int value) +{ + value_t item; + item.type = bhl::sb::E_ValueType::Int; + item.value = value; + SetListItem(key, index, item); +} + +void CScoreboardExt::ListSetText(const char *key, int index, const char *text) +{ + value_t item; + item.type = bhl::sb::E_ValueType::Text; + CopyString(item.text, text); + SetListItem(key, index, item); +} + +void CScoreboardExt::ListSetIcon(const char *key, int index, const char *sprite, const char *text) +{ + value_t item; + item.type = bhl::sb::E_ValueType::Icon; + CopyString(item.sprite, sprite); + CopyString(item.text, text); + SetListItem(key, index, item); +} + +//---------------------------------------------------------------------------------------------------- +// State +//---------------------------------------------------------------------------------------------------- +void CScoreboardExt::ClearSchema() +{ + m_bActive = false; + m_iHideFlags = 0; + m_szPreset[0] = '\0'; + m_szTitle[0] = '\0'; + m_szTag[0] = '\0'; + + for (column_t &column : m_Columns) + column = column_t(); + + m_iColumnCount = 0; + + for (list_t &list : m_Lists) + { + list.key[0] = '\0'; + list.count = 0; + + for (value_t &item : list.items) + item = value_t(); + } + + m_iListCount = 0; + + for (auto &cells : m_Cells) + { + for (value_t &cell : cells) + cell = value_t(); + } +} + +int CScoreboardExt::GetCellTarget(int target) +{ + if (target == bhl::sb::TARGET_GLOBAL) + return 0; + + if (target >= 1 && target <= gpGlobals->maxClients) + return serverapi()->IsClientConnected(target) ? target : -1; + + if (target >= TEAM_TARGET_BASE && target < TEAM_TARGET_BASE + m_iTeamCount) + return FIRST_TEAM + target - TEAM_TARGET_BASE; + + return -1; +} + +int CScoreboardExt::FindColumn(const char *key) +{ + if (!key) + return -1; + + for (int i = 0; i < m_iColumnCount; i++) + { + if (!strcmp(m_Columns[i].key, key)) + return i; + } + + return -1; +} + +int CScoreboardExt::FindList(const char *key) +{ + if (!key) + return -1; + + for (int i = 0; i < m_iListCount; i++) + { + if (!strcmp(m_Lists[i].key, key)) + return i; + } + + return -1; +} + +void CScoreboardExt::SetCell(int target, const char *key, const value_t &value) +{ + int cellTarget = GetCellTarget(target); + int column = FindColumn(key); + + if (cellTarget == -1 || column == -1 || m_Columns[column].display == (int)bhl::sb::E_Display::Builtin) + return; + + value_t &cell = m_Cells[cellTarget][column]; + + if (IsEqual(cell, value)) + return; + + cell = value; + + if (m_bActive) + { + for (client_state_t &state : m_Clients) + state.cellsDirty[cellTarget] |= 1u << column; + } +} + +void CScoreboardExt::ClearCell(int target, int column) +{ + value_t &cell = m_Cells[target][column]; + + if (cell.type == bhl::sb::E_ValueType::None) + return; + + cell = value_t(); + + if (m_bActive) + { + for (client_state_t &state : m_Clients) + state.cellsDirty[target] |= 1u << column; + } +} + +void CScoreboardExt::SetListItem(const char *key, int index, const value_t &value) +{ + int id = FindList(key); + + if (id == -1 || index < 0 || index >= m_Lists[id].count) + return; + + value_t &item = m_Lists[id].items[index]; + + if (IsEqual(item, value)) + return; + + item = value; + + if (m_bActive) + { + for (client_state_t &state : m_Clients) + state.listItemsDirty[id] |= 1ULL << index; + } +} + +//---------------------------------------------------------------------------------------------------- +// Sending +//---------------------------------------------------------------------------------------------------- +bool CScoreboardExt::SendToClient(int idx) +{ + client_state_t &state = m_Clients[idx]; + edict_t *pEdict = INDEXENT(idx); + + m_iBytesLeft = FRAME_BUDGET; + + if (state.isResetPending) + { + if (!BeginMessage(pEdict, 2)) + return false; + + WRITE_BYTE((int)bhl::sb::E_Op::Reset); + WRITE_BYTE(bhl::sb::PROTOCOL_VERSION); + MESSAGE_END(); + state.isResetPending = false; + } + + if (!m_bActive) + return true; + + UpdateClientTeams(state); + + if (state.isConfigPending) + { + int size = 3 + (int)strlen(m_szPreset) + 1 + (int)strlen(m_szTitle) + 1 + (int)strlen(m_szTag) + 1; + + if (!BeginMessage(pEdict, size)) + return false; + + WRITE_BYTE((int)bhl::sb::E_Op::Config); + WRITE_SHORT(m_iHideFlags); + WRITE_STRING(m_szPreset); + WRITE_STRING(m_szTitle); + WRITE_STRING(m_szTag); + MESSAGE_END(); + state.isConfigPending = false; + } + + for (int i = 0; i < m_iColumnCount; i++) + { + if (!(state.columnsPending & (1u << i))) + continue; + + if (!SendColumn(pEdict, i)) + return false; + + state.columnsPending &= ~(1u << i); + } + + for (int i = 0; i < m_iListCount; i++) + { + if (!SendList(pEdict, state, i)) + return false; + } + + return SendValues(pEdict, state); +} + +void CScoreboardExt::UpdateClientTeams(client_state_t &state) +{ + // Without mp_teamlist team indexes change when teams appear and disappear + for (int i = 0; i < m_iTeamCount; i++) + { + int number = m_TeamNumbers[i]; + + if (state.teamNumbers[i] == number) + continue; + + if (state.teamNumbers[i] != 0) + state.teamsCleared |= 1ULL << (state.teamNumbers[i] - 1); + + state.teamNumbers[i] = number; + state.cellsDirty[FIRST_TEAM + i] = 0; + + if (number == 0) + continue; + + for (int column = 0; column < m_iColumnCount; column++) + { + if (m_Cells[FIRST_TEAM + i][column].type != bhl::sb::E_ValueType::None) + state.cellsDirty[FIRST_TEAM + i] |= 1u << column; + } + } +} + +bool CScoreboardExt::BeginMessage(edict_t *pEdict, int size) +{ + if (size > m_iBytesLeft) + return false; + + m_iBytesLeft -= size; + MESSAGE_BEGIN(MSG_ONE, gmsgBhlScore, NULL, pEdict); + return true; +} + +bool CScoreboardExt::SendColumn(edict_t *pEdict, int id) +{ + const column_t &column = m_Columns[id]; + int size = 7 + (int)strlen(column.key) + 1 + (int)strlen(column.title) + 1; + + if (!BeginMessage(pEdict, size)) + return false; + + WRITE_BYTE((int)bhl::sb::E_Op::Column); + WRITE_BYTE(id); + WRITE_BYTE(column.display); + WRITE_SHORT(column.flags); + WRITE_BYTE(column.width); + WRITE_BYTE(column.sort); + WRITE_STRING(column.key); + WRITE_STRING(column.title); + MESSAGE_END(); + return true; +} + +bool CScoreboardExt::SendList(edict_t *pEdict, client_state_t &state, int id) +{ + const list_t &list = m_Lists[id]; + uint64_t &dirty = state.listItemsDirty[id]; + unsigned int resized = 1u << id; + int headerSize = 4 + (int)strlen(list.key) + 1; + + while (dirty || (state.listsResized & resized)) + { + int start = 0; + int end = 0; + int size = headerSize; + + if (dirty) + { + int last = bhl::sb::MAX_LIST_ITEMS - 1; + + while (!(dirty & (1ULL << start))) + start++; + + while (!(dirty & (1ULL << last))) + last--; + + // Clean items between dirty ones are sent again to keep the run contiguous + end = start; + + while (end <= last && size + GetValueSize(list.items[end]) <= bhl::sb::MAX_MSG_SIZE) + size += GetValueSize(list.items[end++]); + } + + if (!BeginMessage(pEdict, size)) + return false; + + WRITE_BYTE((int)bhl::sb::E_Op::List); + WRITE_BYTE(id); + WRITE_BYTE(list.count); + WRITE_BYTE(start); + WRITE_STRING(list.key); + + for (int i = start; i < end; i++) + { + WriteValue(list.items[i]); + dirty &= ~(1ULL << i); + } + + MESSAGE_END(); + state.listsResized &= ~resized; + } + + return true; +} + +bool CScoreboardExt::SendValues(edict_t *pEdict, client_state_t &state) +{ + m_iMsgCellCount = 0; + m_iMsgSize = 1; + + // Clears go first: a team number may already be reused by another team + for (int i = 1; i <= MAX_PLAYERS; i++) + { + if ((state.playersCleared & (1ULL << (i - 1))) && !AddValuesCell(pEdict, state, i, -1, bhl::sb::ALL_COLUMNS)) + return false; + } + + for (int i = 1; i <= MAX_TEAMS; i++) + { + if ((state.teamsCleared & (1ULL << (i - 1))) && !AddValuesCell(pEdict, state, bhl::sb::TARGET_TEAM_BASE + i, -1, bhl::sb::ALL_COLUMNS)) + return false; + } + + for (int target = 0; target < MAX_TARGETS; target++) + { + unsigned int dirty = state.cellsDirty[target]; + + if (!dirty) + continue; + + int wire = target; + + if (target >= FIRST_TEAM) + { + int number = state.teamNumbers[target - FIRST_TEAM]; + + if (number == 0) + { + state.cellsDirty[target] = 0; + continue; + } + + wire = bhl::sb::TARGET_TEAM_BASE + number; + } + + for (int column = 0; column < m_iColumnCount; column++) + { + if ((dirty & (1u << column)) && !AddValuesCell(pEdict, state, wire, target, column)) + return false; + } + } + + return FlushValues(pEdict, state); +} + +bool CScoreboardExt::AddValuesCell(edict_t *pEdict, client_state_t &state, int wire, int target, int column) +{ + int cellSize = 1 + (target == -1 ? 2 : GetValueSize(m_Cells[target][column])); + bool isSameGroup = m_iMsgCellCount > 0 && m_MsgCells[m_iMsgCellCount - 1].wire == wire; + int size = isSameGroup ? cellSize : cellSize + 2; + + if (m_iMsgSize + size > bhl::sb::MAX_MSG_SIZE) + { + if (!FlushValues(pEdict, state)) + return false; + + size = cellSize + 2; + } + + msg_cell_t &cell = m_MsgCells[m_iMsgCellCount++]; + cell.wire = wire; + cell.target = target; + cell.column = column; + m_iMsgSize += size; + return true; +} + +bool CScoreboardExt::FlushValues(edict_t *pEdict, client_state_t &state) +{ + if (m_iMsgCellCount == 0) + return true; + + if (!BeginMessage(pEdict, m_iMsgSize)) + return false; + + WRITE_BYTE((int)bhl::sb::E_Op::Values); + + for (int i = 0; i < m_iMsgCellCount;) + { + int wire = m_MsgCells[i].wire; + int count = 1; + + while (i + count < m_iMsgCellCount && m_MsgCells[i + count].wire == wire) + count++; + + WRITE_BYTE(wire); + WRITE_BYTE(count); + + for (; count > 0; count--, i++) + { + const msg_cell_t &cell = m_MsgCells[i]; + WRITE_BYTE(cell.column); + + if (cell.target != -1) + { + WriteValue(m_Cells[cell.target][cell.column]); + state.cellsDirty[cell.target] &= ~(1u << cell.column); + } + else + { + WriteValue(value_t()); + + if (wire > bhl::sb::TARGET_TEAM_BASE) + state.teamsCleared &= ~(1ULL << (wire - bhl::sb::TARGET_TEAM_FIRST)); + else + state.playersCleared &= ~(1ULL << (wire - bhl::sb::TARGET_PLAYER_FIRST)); + } + } + } + + MESSAGE_END(); + m_iMsgCellCount = 0; + m_iMsgSize = 1; + return true; +} + +bool CScoreboardExt::IsEqual(const value_t &a, const value_t &b) +{ + return a.type == b.type && a.value == b.value && a.max == b.max && !strcmp(a.text, b.text) && !strcmp(a.sprite, b.sprite); +} + +int CScoreboardExt::GetValueSize(const value_t &value) +{ + int len = 0; + + switch (value.type) + { + case bhl::sb::E_ValueType::Int: + if (value.value >= -128 && value.value <= 127) + len = 1; + else if (value.value >= -32768 && value.value <= 32767) + len = 2; + else + len = 4; + break; + case bhl::sb::E_ValueType::Text: + len = (int)strlen(value.text) + 1; + break; + case bhl::sb::E_ValueType::Icon: + len = (int)strlen(value.sprite) + 1 + (int)strlen(value.text) + 1; + break; + case bhl::sb::E_ValueType::Progress: + len = IsByteProgress(value.value, value.max) ? 2 : 4; + break; + } + + return 2 + len; +} + +void CScoreboardExt::WriteValue(const value_t &value) +{ + int len = GetValueSize(value) - 2; + + WRITE_BYTE((int)value.type); + WRITE_BYTE(len); + + switch (value.type) + { + case bhl::sb::E_ValueType::Int: + if (len == 1) + WRITE_CHAR(value.value); + else if (len == 2) + WRITE_SHORT(value.value); + else + WRITE_LONG(value.value); + break; + case bhl::sb::E_ValueType::Text: + WRITE_STRING(value.text); + break; + case bhl::sb::E_ValueType::Icon: + WRITE_STRING(value.sprite); + WRITE_STRING(value.text); + break; + case bhl::sb::E_ValueType::Progress: + if (len == 2) + { + WRITE_BYTE(value.value); + WRITE_BYTE(value.max); + } + else + { + WRITE_SHORT(ClampWord(value.value)); + WRITE_SHORT(ClampWord(value.max)); + } + break; + } +} diff --git a/src/game/server/CScoreboardExt.h b/src/game/server/CScoreboardExt.h new file mode 100644 index 00000000..5caec39b --- /dev/null +++ b/src/game/server/CScoreboardExt.h @@ -0,0 +1,153 @@ +#ifndef CSCOREBOARDEXT_H +#define CSCOREBOARDEXT_H + +#include +#include +#include +#include "eiface.h" +#include "cdll_dll.h" + +/** + * Implementation of IScoreboardExt: keeps the scoreboard state and sends it + * to the clients in "BhlScore" messages. + * @see docs/scoreboard-protocol.md + */ +class CScoreboardExt : public bhl::IScoreboardExt +{ +public: + bool IsActive() { return m_bActive; } + + //! Clears everything without sending anything. Called on map change. + void ClearAll(); + + //! Clears cells and the sync state of a player slot. Called when the slot is taken or freed. + void ClearPlayer(int idx); + + /** + * Schedules Reset for the client, and everything else if the schema is active. + * @param delay Send nothing for FULL_SYNC_DELAY (InitHUD has just sent a lot) + */ + void StartFullSync(int idx, bool delay); + + //! Sends pending data to the clients + void StartFrame(); + + //---------------------------------------------------------------------------------------------------- + // IScoreboardExt methods + //---------------------------------------------------------------------------------------------------- + virtual void Reset(); + virtual void SetConfig(unsigned int hideFlags, const char *preset, const char *title, const char *tag); + virtual bool AddColumn(const char *key, const char *title, int display, int width, int sort, unsigned int flags); + virtual int GetTeamTarget(const char *teamName); + virtual void SetInt(int target, const char *key, int value); + virtual void SetText(int target, const char *key, const char *text); + virtual void SetIcon(int target, const char *key, const char *sprite, const char *text); + virtual void SetProgress(int target, const char *key, int cur, int max); + virtual void Clear(int target, const char *key); + virtual bool ListResize(const char *key, int count); + virtual void ListSetInt(const char *key, int index, int value); + virtual void ListSetText(const char *key, int index, const char *text); + virtual void ListSetIcon(const char *key, int index, const char *sprite, const char *text); + +private: + static constexpr int TEAM_TARGET_BASE = 0x100; //!< GetTeamTarget returns this plus the team slot + static constexpr int FIRST_TEAM = MAX_PLAYERS + 1; //!< Index of the first team in m_Cells + static constexpr int MAX_TARGETS = FIRST_TEAM + MAX_TEAMS; + static constexpr int FRAME_BUDGET = 512; //!< Bytes per client per frame + static constexpr float FULL_SYNC_DELAY = 0.5f; //!< Seconds after InitHUD before the full sync starts + static constexpr float BUDGET_DELAY = 0.1f; //!< Seconds to wait after the budget ran out, lets the reliable channel drain + static constexpr int MAX_MSG_CELLS = bhl::sb::MAX_MSG_SIZE / 3; + + struct value_t + { + bhl::sb::E_ValueType type = bhl::sb::E_ValueType::None; + int value = 0; //!< Int value or Progress cur + int max = 0; //!< Progress max + char text[bhl::sb::MAX_TEXT_LEN + 1] = {}; //!< Text value or Icon text + char sprite[bhl::sb::MAX_TEXT_LEN + 1] = {}; + }; + + struct column_t + { + char key[bhl::sb::MAX_KEY_LEN + 1] = {}; + char title[bhl::sb::MAX_COLUMN_TITLE_LEN + 1] = {}; + int display = 0; + int flags = 0; + int width = 0; + int sort = 0; + }; + + struct list_t + { + char key[bhl::sb::MAX_KEY_LEN + 1] = {}; + int count = 0; + value_t items[bhl::sb::MAX_LIST_ITEMS]; + }; + + struct client_state_t + { + float nextSendTime = 0; //!< Nothing is sent to the client before this time + bool isResetPending = false; + bool isConfigPending = false; + unsigned int columnsPending = 0; //!< Bit per column id + unsigned int listsResized = 0; //!< Bit per list id + uint64_t listItemsDirty[bhl::sb::MAX_LISTS] = {}; + unsigned int cellsDirty[MAX_TARGETS] = {}; //!< Bit per column id + uint64_t playersCleared = 0; //!< Bit (slot - 1): all cells of the player must be cleared + uint64_t teamsCleared = 0; //!< Bit (team number - 1): all cells of the team number must be cleared + int teamNumbers[MAX_TEAMS] = {}; //!< Team number the cells of a team slot were sent with, 0 if none + }; + + struct msg_cell_t + { + int wire; //!< Target as sent + int target; //!< Index in m_Cells, -1 to clear all cells of the wire target + int column; + }; + + bool m_bActive = false; + int m_iHideFlags = 0; + char m_szPreset[bhl::sb::MAX_PRESET_LEN + 1] = {}; + char m_szTitle[bhl::sb::MAX_TITLE_LEN + 1] = {}; + char m_szTag[bhl::sb::MAX_TAG_LEN + 1] = {}; + + column_t m_Columns[bhl::sb::MAX_COLUMNS]; + int m_iColumnCount = 0; + list_t m_Lists[bhl::sb::MAX_LISTS]; + int m_iListCount = 0; + char m_szTeamNames[MAX_TEAMS][MAX_TEAM_NAME] = {}; + int m_iTeamCount = 0; + int m_TeamNumbers[MAX_TEAMS] = {}; //!< Team numbers of the team slots in the current frame + value_t m_Cells[MAX_TARGETS][bhl::sb::MAX_COLUMNS]; + + client_state_t m_Clients[MAX_PLAYERS + 1]; + + int m_iBytesLeft = 0; + msg_cell_t m_MsgCells[MAX_MSG_CELLS]; + int m_iMsgCellCount = 0; + int m_iMsgSize = 0; + + void ClearSchema(); + int GetCellTarget(int target); + int FindColumn(const char *key); + int FindList(const char *key); + void SetCell(int target, const char *key, const value_t &value); + void ClearCell(int target, int column); + void SetListItem(const char *key, int index, const value_t &value); + + //! Returns false if the budget ran out before everything was sent + bool SendToClient(int idx); + void UpdateClientTeams(client_state_t &state); + bool BeginMessage(edict_t *pEdict, int size); + bool SendColumn(edict_t *pEdict, int id); + bool SendList(edict_t *pEdict, client_state_t &state, int id); + bool SendValues(edict_t *pEdict, client_state_t &state); + bool AddValuesCell(edict_t *pEdict, client_state_t &state, int wire, int target, int column); + bool FlushValues(edict_t *pEdict, client_state_t &state); + + static bool IsEqual(const value_t &a, const value_t &b); + static int GetValueSize(const value_t &value); + static void WriteValue(const value_t &value); +}; + +#endif diff --git a/src/game/server/client.cpp b/src/game/server/client.cpp index 68471370..7a12e308 100644 --- a/src/game/server/client.cpp +++ b/src/game/server/client.cpp @@ -100,6 +100,8 @@ GLOBALS ASSUMED SET: g_fGameOver */ void ClientDisconnect(edict_t *pEntity) { + serverapi()->ClientDisconnect(pEntity); + if (g_fGameOver) return; @@ -674,6 +676,8 @@ it gets sent into the rest of the engine. */ void ClientUserInfoChanged(edict_t *pEntity, char *infobuffer) { + serverapi()->ClientUserInfoChanged(pEntity, infobuffer); + // Is the client spawned yet? if (!pEntity->pvPrivateData) return; @@ -749,6 +753,7 @@ void ServerDeactivate(void) // Peform any shutdown operations here... // + serverapi()->ServerDeactivate(); } void ServerActivate(edict_t *pEdictList, int edictCount, int clientMax) @@ -841,6 +846,8 @@ void StartFrame(void) if (g_pGameRules) g_pGameRules->Think(); + serverapi()->StartFrame(); + if (g_fGameOver) return; diff --git a/src/game/server/multiplay_gamerules.cpp b/src/game/server/multiplay_gamerules.cpp index 4a34a9ab..90cc8456 100644 --- a/src/game/server/multiplay_gamerules.cpp +++ b/src/game/server/multiplay_gamerules.cpp @@ -469,6 +469,8 @@ void CHalfLifeMultiplay ::InitHUD(CBasePlayer *pl) if (!sv_bhl_defer_motd.GetBool() || serverapi()->IsClientSupportsReceived(pl->entindex())) SendDefaultMOTDToClient(pl->edict()); + serverapi()->InitHUD(pl->edict()); + // loop through all active players and send their score and team info to the new client for (int i = 1; i <= gpGlobals->maxClients; i++) { diff --git a/src/game/server/player.cpp b/src/game/server/player.cpp index 58c9fb46..97852715 100644 --- a/src/game/server/player.cpp +++ b/src/game/server/player.cpp @@ -35,6 +35,7 @@ #include "gamerules.h" #include "game.h" #include "hltv.h" +#include // #define DUCKFIX @@ -216,6 +217,7 @@ int gmsgViewMode = 0; int gmsgVGUIMenu = 0; int gmsgStatusIcon = 0; int gmsgFog = 0; +int gmsgBhlScore = 0; const char *const gCustomMessages[] = { "IconInfo", @@ -287,6 +289,7 @@ void LinkUserMessages(void) } gmsgFog = REG_USER_MSG("Fog", 7); + gmsgBhlScore = REG_USER_MSG(bhl::sb::MSG_NAME, -1); } LINK_ENTITY_TO_CLASS(player, CBasePlayer); diff --git a/src/game/shared/CMakeLists.txt b/src/game/shared/CMakeLists.txt index a5843ff4..f1d816a8 100644 --- a/src/game/shared/CMakeLists.txt +++ b/src/game/shared/CMakeLists.txt @@ -7,7 +7,9 @@ add_sources( enum_utils.h IBugfixedServer.h IGameVersion.h + IScoreboardExt.h mathlib.cpp + ScoreboardProtocol.h voice_common.h ) diff --git a/src/game/shared/ClientSupportsFlags.h b/src/game/shared/ClientSupportsFlags.h index 45b933f8..a67434ee 100644 --- a/src/game/shared/ClientSupportsFlags.h +++ b/src/game/shared/ClientSupportsFlags.h @@ -12,5 +12,13 @@ enum class E_ClientSupports : unsigned int HtmlMotd = (1 << 1) }; +//! Features the client reports in the "_bhl" userinfo key (docs/scoreboard-protocol.md) +enum class E_ClientCaps : unsigned int +{ + None = 0, + ScoreboardV1 = (1 << 0), + GunGameHudV1 = (1 << 1) +}; + } #endif diff --git a/src/game/shared/IBugfixedServer.h b/src/game/shared/IBugfixedServer.h index 0099366b..c61d1725 100644 --- a/src/game/shared/IBugfixedServer.h +++ b/src/game/shared/IBugfixedServer.h @@ -2,11 +2,12 @@ #define IBUGFIXEDAPI_H #include #include +#include #include #define IBUGFIXEDSERVER_NAME "IBugfixedServer" #define IBUGFIXEDSERVER_MAJOR 1 -#define IBUGFIXEDSERVER_MINOR 0 +#define IBUGFIXEDSERVER_MINOR 2 class CGameRules; class IGameVersion; @@ -146,6 +147,23 @@ class IBugfixedServer : public IBaseInterface * @param deaths Number of deaths */ virtual void SetPlayerScore(int idx, int frags, int deaths) = 0; + + /** + * Returns features the client reports in the "_bhl" userinfo key or cvar. + * Returns None for an empty slot or a client that doesn't report anything. + * + * Added in version v1.2 + * + * @param idx Client index [1; (maxplayers)] + */ + virtual bhl::E_ClientCaps GetClientCaps(int idx) = 0; + + /** + * Returns the scoreboard extension. Never null. + * + * Added in version v1.2 + */ + virtual bhl::IScoreboardExt *GetScoreboard() = 0; }; } #endif diff --git a/src/game/shared/IScoreboardExt.h b/src/game/shared/IScoreboardExt.h new file mode 100644 index 00000000..bdbe09f4 --- /dev/null +++ b/src/game/shared/IScoreboardExt.h @@ -0,0 +1,73 @@ +#ifndef ISCOREBOARDEXT_H +#define ISCOREBOARDEXT_H + +namespace bhl +{ + +/** + * Server-side scoreboard extension (docs/scoreboard-protocol.md). + * + * Columns and lists are addressed by keys, wire ids are assigned by the server. + * Targets: + * 0 - the whole game; + * 1 .. maxClients - a player; + * a value of GetTeamTarget - a team. + * Any other target is ignored. + * + * New methods must be added to the end. + */ +class IScoreboardExt +{ +public: + /** + * Removes the schema, all cells and lists and sends Reset to the clients. + */ + virtual void Reset() = 0; + + /** + * Sets the config and turns the custom scoreboard on. + * @param hideFlags bhl::sb::E_ConfigFlags + * @param preset Client preset name, "" for the generic look + * @param title Replaces the server name if not empty + * @param tag Badge next to the title + */ + virtual void SetConfig(unsigned int hideFlags, const char *preset, const char *title, const char *tag) = 0; + + /** + * Adds a column or replaces the column with the same key. + * @param display bhl::sb::E_Display + * @param sort 0 or priority starting at 1, plus bhl::sb::SORT_ASC + * @param flags bhl::sb::E_ColumnFlags + * @return false if the key is invalid or there are no free columns + */ + virtual bool AddColumn(const char *key, const char *title, int display, int width, int sort, unsigned int flags) = 0; + + /** + * Returns an opaque target of a team that stays valid until the map changes, or -1. + */ + virtual int GetTeamTarget(const char *teamName) = 0; + + virtual void SetInt(int target, const char *key, int value) = 0; + virtual void SetText(int target, const char *key, const char *text) = 0; + virtual void SetIcon(int target, const char *key, const char *sprite, const char *text) = 0; + virtual void SetProgress(int target, const char *key, int cur, int max) = 0; + + /** + * Clears a cell, or every cell of the target if key is null or empty. + */ + virtual void Clear(int target, const char *key) = 0; + + /** + * Creates the list on first use and sets its size. + * @return false if the key is invalid or there are no free lists + */ + virtual bool ListResize(const char *key, int count) = 0; + + virtual void ListSetInt(const char *key, int index, int value) = 0; + virtual void ListSetText(const char *key, int index, const char *text) = 0; + virtual void ListSetIcon(const char *key, int index, const char *sprite, const char *text) = 0; +}; + +} + +#endif diff --git a/src/game/shared/ScoreboardProtocol.h b/src/game/shared/ScoreboardProtocol.h new file mode 100644 index 00000000..a9673c36 --- /dev/null +++ b/src/game/shared/ScoreboardProtocol.h @@ -0,0 +1,90 @@ +#ifndef SCOREBOARDPROTOCOL_H +#define SCOREBOARDPROTOCOL_H +#include + +/** + * Constants of the "BhlScore" user message. + * See docs/scoreboard-protocol.md for the format. + */ +namespace bhl::sb +{ + +constexpr int PROTOCOL_VERSION = 1; +constexpr const char *MSG_NAME = "BhlScore"; +constexpr const char *CAPS_KEY = "_bhl"; + +constexpr int MAX_MSG_SIZE = 192; +constexpr int MAX_COLUMNS = 16; +constexpr int MAX_LISTS = 8; +constexpr int MAX_LIST_ITEMS = 64; +constexpr int MAX_DOTS = 10; + +//! String limits in bytes, without the terminating NUL +constexpr int MAX_KEY_LEN = 15; +constexpr int MAX_COLUMN_TITLE_LEN = 31; +constexpr int MAX_PRESET_LEN = 15; +constexpr int MAX_TITLE_LEN = 63; +constexpr int MAX_TAG_LEN = 15; +constexpr int MAX_TEXT_LEN = 31; + +//! Column id that means "every column of the target" (only with E_ValueType::None) +constexpr int ALL_COLUMNS = 0xFF; + +constexpr int SORT_ASC = 0x80; +constexpr int SORT_PRIORITY_MASK = 0x7F; + +constexpr int TARGET_GLOBAL = 0x00; +constexpr int TARGET_PLAYER_FIRST = 0x01; +constexpr int TARGET_PLAYER_LAST = 0x40; +constexpr int TARGET_TEAM_BASE = 0x80; +constexpr int TARGET_TEAM_FIRST = 0x81; +constexpr int TARGET_TEAM_LAST = 0xC0; + +enum class E_Op : unsigned int +{ + Reset = 0, + Config = 1, + Column = 2, + Values = 3, + List = 4, +}; + +enum class E_ValueType : unsigned int +{ + None = 0, + Int = 1, + Text = 2, + Icon = 3, + Progress = 4, +}; + +enum class E_Display : unsigned int +{ + Text = 0, + Icon = 1, + Meter = 2, + Builtin = 3, + Steps = 4, +}; + +enum class E_ConfigFlags : unsigned int +{ + None = 0, + HideFrags = (1 << 0), + HideDeaths = (1 << 1), + HideEff = (1 << 2), + HideSteamID = (1 << 3), +}; + +enum class E_ColumnFlags : unsigned int +{ + None = 0, + Hidden = (1 << 0), + AlignCenter = (1 << 1), + AlignRight = (2 << 1), + Primary = (1 << 3), +}; + +} + +#endif From 7a864400310b78bb928572085ce6e876e56fd587 Mon Sep 17 00:00:00 2001 From: et-nik Date: Mon, 12 Oct 2026 16:34:58 +0200 Subject: [PATCH 10/19] fixes and updates --- docs/scoreboard-protocol.md | 198 +++++++------ gamedir/CMakeLists.txt | 1 - gamedir/ui/resource/ClientSchemeBase.res | 2 +- gamedir/ui/resource/ScorePanel_gungame.res | 105 ------- .../language/bugfixedhl_english.utf8.txt | 7 +- .../language/bugfixedhl_russian.utf8.txt | 7 +- src/game/client/hud/gungame_hud.cpp | 8 +- src/game/client/hud_renderer.cpp | 13 +- src/game/client/hud_renderer.h | 5 +- src/game/client/scoreboard_data.cpp | 27 +- src/game/client/vgui/score_panel.cpp | 275 ++++++------------ src/game/client/vgui/score_panel.h | 31 +- src/game/client/vgui/score_panel_cells.cpp | 230 ++++++++++----- src/game/client/vgui/score_panel_cells.h | 27 +- 14 files changed, 390 insertions(+), 546 deletions(-) delete mode 100644 gamedir/ui/resource/ScorePanel_gungame.res diff --git a/docs/scoreboard-protocol.md b/docs/scoreboard-protocol.md index 7199db21..30a70583 100644 --- a/docs/scoreboard-protocol.md +++ b/docs/scoreboard-protocol.md @@ -195,7 +195,7 @@ The client drops the schema, all cells and all lists and returns to the standard | `flags` | `word` | See below | | `preset` | `string` | Up to 15 bytes; `""` means the generic look | | `title` | `string` | Up to 63 bytes; replaces the server name if not `""` | -| `tag` | `string` | Up to 15 bytes; a badge next to the title: `FFA` | +| `tag` | `string` | Up to 15 bytes; a badge after the server name: `FFA` | | Bit | Name | Meaning | |------|---------------|-------------------------| @@ -364,13 +364,17 @@ messages. | Message | Bytes | |----------------------------|-----------| | `Reset` | 2 | -| `Config` | ~25 | -| `Column` × 9 | ~15–30 | +| `Config` | ~17 | +| `Column` × 8 | ~13–33 | | `List` `levels`, 24 levels | 2 × ≤ 192 | | `Values`, 32 players | 7 × ≤ 192 | | Level-up of one player | ~33 | | Kill without level-up | ~18 | | Warmup second | ~8 | +| Warmup start or end | ~130 | + +At the start and the end of the warmup the GunGame plugin sends the `level`, `weapon`, `progress`, +`kills` and `score` columns again (8.1). ### 4.6 Limits @@ -406,7 +410,7 @@ Plugins only change the state and mark the changed cells and list items dirty fo client. In `StartFrame` the server walks the ready clients that have `ScoreboardV1` and sends: 1. `Reset`, if one is pending; -2. `Config` and every `Column`, if the header is pending; +2. `Config`, if it is pending, and every pending `Column`; 3. the dirty list items packed into `List` messages; 4. the dirty cells packed into `Values` messages. @@ -459,15 +463,15 @@ still stored. - Column order: `rank`, Avatar, Name, then SteamID, Eff, Frags and Deaths at their default places unless the schema moves them, then custom and `Builtin` columns by `id`, then Ping unless moved. Hidden standard columns and `Hidden` custom columns are left out. +- The panel keeps the size, place, frame and header of the standard scoreboard (`ScorePanel.res`). - Name takes all free width. If the other columns need more, Name shrinks down to 100 units (`column_name_min`), then down to 80 units; columns that still don't fit are dropped from the end. -- A preset may bring its own layout file `ScorePanel_.res`. Without it, `ScorePanel.res` - is used. - While a `Steps` column is visible, rows are taller so the strip fits under the text. - Team section headers show team cells as text in the same columns (`ModifyColumn`; the list - control can't draw images in headers): `Icon` as its name, `Progress` as `cur/max`. Team frags - and deaths follow the `Hide*` flags. + control can't draw images in headers): `Icon` as its name, `Progress` as `cur/max`. A `Meter` + column with `max ≤ 10` stays empty, like dots without a counter. Team frags and deaths follow + the `Hide*` flags. ### 6.4 Sorting and places @@ -481,18 +485,20 @@ still stored. ### 6.5 `hud_scores` -With an active schema and a `Primary` column, `hud_scores` shows that column as text instead of -frags and sorts the same way as the scoreboard. Without a `Primary` column it doesn't change. +With an active schema, `hud_scores` uses the first `Primary` column (lowest `id`) that isn't +`Hidden`. It shows that column as text instead of frags and sorts the same way as the scoreboard. +Without such a column it doesn't change. ### 6.6 Drawing -- `Icon`: the sprite from `hud.txt`, scaled to the row height with its aspect ratio kept and drawn - additively like the kill feed, tinted with the row text color. The text follows to the right. +- `Icon`: the sprite from `hud.txt`, scaled to the row height with its aspect ratio kept and tinted + with the row text color. The text follows to the right. The client reads the sprite file and + draws it as a VGUI2 texture, so icons work with every renderer, the software one included. + The brightness of a pixel becomes its alpha, so the icon looks like an additive sprite. - `Meter`, the same element as in the GunGame HUD (8.4.3): - - `max ≤ 10`: `cur` filled dots and `max − cur` empty ones, drawn from a procedural circle texture; - - `max > 10`: a rounded bar of the same length as 10 dots, filled to `cur / max`; - - the `cur/max` counter stands to the right. In the scoreboard it is always shown, in the HUD - only next to the bar. + - `max ≤ 10`: `cur` filled dots and `max − cur` empty ones, without a counter; + - `max > 10`: a rounded bar of the same length as 10 dots, filled to `cur / max`, with the + `cur/max` counter to the right. - `Steps`: `cur/max` as text; below it a strip of `max` segments. Segments before `cur` are filled, segment `cur` is highlighted, the rest are dimmed, the last one is marked. - `Progress` in a `Text` column: `cur/max`. @@ -506,20 +512,22 @@ frags and sorts the same way as the scoreboard. Without a `Primary` column it do ### 6.8 Debug commands -- `hud_scoreboard_test [preset]` fills the store with fake data for the current players without - a server. +- `hud_scoreboard_test [preset|off] [phase] [phase_left]` fills the store with fake data for the + current players without a server. With `phase` 1 or 2 it shows the warmup columns, like the + GunGame plugin. - `hud_scoreboard_dump` prints the store to the console. ## 7. Client behaviour: standard scoreboard Without an active schema the scoreboard is the same as now. The place column appears only when a -schema adds the built-in `rank` column. The own-row highlight and the ping highlight from section 8 -exist only in the `gungame` preset. +schema adds the built-in `rank` column. With a schema the scoreboard keeps the standard look: size, +place, header, fonts, column titles and row highlights. ## 8. GunGame preset -The preset follows two mockups made for 1920×1080: "TAB" for the scoreboard and "Main" for the -game screen. Interface strings are localized (section 10); the mockups use Russian. +The HUD widget follows the "Main" mockup made for 1920×1080. The scoreboard keeps the look of the +standard BugfixedHL scoreboard and only adds the GunGame columns, the tag badge and the leader +banner. Interface strings are localized (section 10); the examples use Russian. ### 8.1 Data @@ -531,9 +539,8 @@ The plugin fills these keys: | `level` | column | player, team | `Progress` | Current level, 1-based / number of levels | | `weapon` | column | player, team | `Icon` | Weapon of the current level | | `progress` | column | player, team | `Progress` | Kills on the current level / kills it needs | -| `kills` | column | player, team | `Int` | Kills in the match | -| `deaths` | builtin | — | — | Standard deaths, moved after `kills` | -| `score` | column | player, team | `Int` | Progress P, hidden, first sort key | +| `kills` | column | player, team | `Int` | Kills in the warmup, then in the match | +| `score` | column | player, team | `Int` | Progress P, hidden, first sort key in the match | | `phase` | column | the whole game | `Int` | 0 game, 1 warmup, 2 start countdown, 3 finished | | `phase_left` | column | the whole game | `Int` | Seconds left in the warmup or the countdown | | `levels` | list | the whole game | `Icon` | Weapon of every level, in order | @@ -543,7 +550,13 @@ The plugin fills these keys: them by `gg_teamplay_multigoal`. Ordering by P gives the same order as the plugin's `Sort_RankPos` (level, then kills). - `kills` counts kills of other players. Suicides and team kills don't count. The counter is reset - together with the scores after the warmup. + together with the scores when the match starts. +- `Config` hides the standard Frags, Deaths, Eff and SteamID columns and leaves the title empty, so + the header shows the server name. The tag is `FFA` or `TEAM`. +- Levels are the same for everybody in the warmup. While `phase` is 1 or 2 the plugin sends the + columns again: `level`, `weapon` and `progress` become `Hidden`, `kills` becomes visible, + `Primary` instead of `level` and the first sort key, `score` the second one. When the match + starts it sends the match columns: `kills` is `Hidden` and the second sort key. - A player is on the last level when `level.cur = level.max`. - Weapon names come from the client table (10.3) for standard HL sprites. `Icon.text` from the server is used only for other sprites. @@ -553,7 +566,7 @@ The plugin fills these keys: The scoreboard and the HUD use the same rules. - Participants are players that are not spectators. Bots count. -- Places follow P: equal P share a place (`1, 1, 3`). +- Places follow P: equal P share a place (`1, 1, 3`). In the warmup they follow `kills`. - In teamplay places are counted among teams that have participants. Team names come from `TeamNames`, team P from the team `score` cell. - Overtake: the neighbour is the nearest participant with a strictly greater P; @@ -564,62 +577,54 @@ The scoreboard and the HUD use the same rules. #### 8.3.1 Placement -- Layout file `ScorePanel_gungame.res`. -- Centered horizontally, about 70% of the screen width, but not narrower than the columns plus - the Name minimum; on 4:3 screens it is wider. The top edge is about 10% of the screen height down. -- One row per player; the table grows down. When rows don't fit, the existing compact spacing - is used, then scrolling. -- No server name, timer or hint line. +- Size, place, frame and fonts of the standard scoreboard (`ScorePanel.res`). +- One row per player. When rows don't fit, the existing compact spacing is used, then scrolling. #### 8.3.2 Header -Left: - -- the title and the tag badge from `Config`: `GUNGAME` and `FFA`; -- below them, one line with the map and the player count: `crossfire · 12 / 16 игроков` - (connected / max players). There are no icon files yet, so the line has no icons. +The header of the standard scoreboard: the server name, the map below it and the player count on +the right. The tag badge from `Config` (`FFA` or `TEAM`) follows the server name. -Right, the banner `ЛИДЕР НА ПОСЛЕДНЕМ УРОВНЕ`: +The banner `Лидер на последнем уровне` stands left of the player count, on the lines of the server +and map names: - shown while the player or team on the first place is on the last level; -- an accent bar instead of the crown icon, the banner title and the line - `Kr1sTaL · Crowbar · 1 убийство до победы`: +- an accent bar, the banner title and the line `Kr1sTaL · Crowbar · 1 убийство до победы`: the leader's name, the weapon and `progress.max − progress.cur` kills left; - in teamplay the line names the team; -- if several leaders share the first place, the first row in sort order is shown. +- if several leaders share the first place, the first row in sort order is shown; +- the server name is cut so that it and the tag end before the banner. #### 8.3.3 Columns -`#` · Avatar · `ИГРОК` · `УРОВЕНЬ` · `ОРУЖИЕ` · `ПРОГРЕСС` · `УБИЙСТВА` · `СМЕРТИ` · `ПИНГ` +In the match: `#` · Avatar · Name · `Уровень` · `Оружие` · `Прогресс` · Ping -- Headers are drawn in uppercase. -- The player column takes all free width; the others have fixed widths. -- Numbers in the last three columns are aligned right. -- Avatars follow `hud_scoreboard_showavatars`. SteamID and Eff are hidden. +In the warmup: `#` · Avatar · Name · `Убийства` · Ping -| Column | Shows | -|------------|-----------------------------------------------------------------------------------------| -| `#` | Place. The first three places are marked, the first stronger than the others. | -| `ИГРОК` | Name without color codes, cut with `…`. The own row has the `ТЫ` badge after the name. | -| `УРОВЕНЬ` | `9/14` with the strip of all levels below (`Steps`); the last level is marked. | -| `ОРУЖИЕ` | Weapon icon and name. On the last level the `ФИНАЛ` badge follows the name. | -| `ПРОГРЕСС` | Dots (filled for done, empty for left) and `1/2` (`Meter`). Dots = kills on this level. | -| `УБИЙСТВА` | `kills` | -| `СМЕРТИ` | Standard deaths | -| `ПИНГ` | Ping without loss (`hud_scoreboard_showloss` is ignored); 100 and above is highlighted | +- Column titles, the name and the ping are drawn as in the standard scoreboard. +- The name column takes all free width; the others have fixed widths. +- Avatars follow `hud_scoreboard_showavatars`. Frags, Deaths, SteamID and Eff are hidden. + +| Column | Shows | +|------------|-------------------------------------------------------------------------------------------| +| `#` | Place as a number | +| `Уровень` | `9/14` with the strip of all levels below (`Steps`); the last level is marked | +| `Оружие` | Weapon icon and name. On the last level the `ФИНАЛ` badge follows the name | +| `Прогресс` | Dots for kills on this level, filled for done; above 10 kills a bar and `16/25` (`Meter`) | +| `Убийства` | `kills`, aligned right; only in the warmup | #### 8.3.4 Highlighted rows -- Own row: the whole row is highlighted, the name is emphasized, `ТЫ` follows it. -- A player on the last level: the row is highlighted, the level number and the weapon icon are - emphasized, `ФИНАЛ` follows the weapon. If this player is the leader, the first-place mark - shows the final too. +- The own row and the last killer are highlighted as in the standard scoreboard. +- A player on the last level: `ФИНАЛ` follows the weapon. #### 8.3.5 Teamplay -- Sections per team, as in the current BugfixedHL scoreboard; sections are ordered by team P. -- A team header shows the team place, level, weapon, progress, kills and deaths. -- Players inside a team are sorted by `kills` (the second sort key). +- Sections per team, as in the current BugfixedHL scoreboard; sections are ordered by team P, in + the warmup by team `kills`. +- A team header shows the team place, level, weapon and, above 10 kills, the progress counter; + in the warmup the place and kills. +- Players inside a team are sorted by `kills`. - Spectators stay in their own section at the bottom. ### 8.4 HUD widget @@ -632,7 +637,7 @@ two elements: the place block at the top center and the level bar at the bottom - The widget is on when the `gungame` preset is active and both `hud_scoreboard_custom` and `hud_gungame` are 1. - It follows the usual HUD rules: hidden with `hud_draw 0` and during intermission. It is also - hidden while the scoreboard is open, because the GunGame table starts near the top. + hidden while the scoreboard is open, because a long table reaches the top of the screen. - A spectator in first-person mode sees the data of the observed player. In other spectator modes the widget is hidden. - With `phase = 3` (finished) the widget is hidden; the plugin's winner message and final table @@ -793,8 +798,8 @@ native bhl_sb_list_set_icon(const key[], index, const sprite[], const text[]); The plugin keeps working without the module: `set_module_filter` and `set_native_filter` in `plugin_natives` let it load, and every call is guarded by a flag. The `level * 100` frags hack -stays for old clients. A new per-player counter keeps the kills in the match for the `kills` -column. +stays for old clients. A new per-player counter keeps the kills of the warmup and then of the +match for the `kills` column. ```pawn Scoreboard_Setup() @@ -805,15 +810,10 @@ Scoreboard_Setup() new bool:isTeamPlay = get_pcvar_num(cvar[CVAR_TEAMPLAY]) == 1 bhl_sb_reset() - bhl_sb_config(BHL_SB_HIDE_FRAGS | BHL_SB_HIDE_EFF | BHL_SB_HIDE_STEAMID, "gungame", "GUNGAME", - isTeamPlay ? "TEAM" : "FFA") + bhl_sb_config(BHL_SB_HIDE_FRAGS | BHL_SB_HIDE_DEATHS | BHL_SB_HIDE_EFF | BHL_SB_HIDE_STEAMID, + "gungame", "", isTeamPlay ? "TEAM" : "FFA") bhl_sb_add_column("rank", "", BHL_SB_BUILTIN) - bhl_sb_add_column("level", "#BHL_SB_Level", BHL_SB_STEPS, 60, 0, BHL_SB_COL_PRIMARY) - bhl_sb_add_column("weapon", "#BHL_SB_Weapon", BHL_SB_ICON, 120) - bhl_sb_add_column("progress", "#BHL_SB_Progress", BHL_SB_METER, 90) - bhl_sb_add_column("kills", "#BHL_SB_Kills", BHL_SB_TEXT, 60, 2, BHL_SB_COL_RIGHT) - bhl_sb_add_column("deaths", "", BHL_SB_BUILTIN, 0, 0, BHL_SB_COL_RIGHT) - bhl_sb_add_column("score", "", BHL_SB_TEXT, 0, 1, BHL_SB_COL_HIDDEN) + Scoreboard_SetColumns(g_isWarmup) bhl_sb_add_column("phase", "", BHL_SB_TEXT, 0, 0, BHL_SB_COL_HIDDEN) bhl_sb_add_column("phase_left", "", BHL_SB_TEXT, 0, 0, BHL_SB_COL_HIDDEN) @@ -823,6 +823,19 @@ Scoreboard_Setup() bhl_sb_list_set_icon("levels", i, g_levelIcon[i], g_levelWeaponName[i]) } +// Called again with the other value when the warmup starts or ends; cells are kept +Scoreboard_SetColumns(bool:warmup) +{ + new BhlSbColumnFlags:levelFlags = warmup ? BHL_SB_COL_HIDDEN : BHL_SB_COL_NONE + new BhlSbColumnFlags:killsFlags = warmup ? BHL_SB_COL_PRIMARY : BHL_SB_COL_HIDDEN + + bhl_sb_add_column("level", "#BHL_SB_Level", BHL_SB_STEPS, 60, 0, warmup ? BHL_SB_COL_HIDDEN : BHL_SB_COL_PRIMARY) + bhl_sb_add_column("weapon", "#BHL_SB_Weapon", BHL_SB_ICON, 120, 0, levelFlags) + bhl_sb_add_column("progress", "#BHL_SB_Progress", BHL_SB_METER, 90, 0, levelFlags) + bhl_sb_add_column("kills", "#BHL_SB_Kills", BHL_SB_TEXT, 60, warmup ? 1 : 2, BHL_SB_COL_RIGHT | killsFlags) + bhl_sb_add_column("score", "", BHL_SB_TEXT, 0, warmup ? 2 : 1, BHL_SB_COL_HIDDEN) +} + Scoreboard_UpdatePlayer(id) { if (!g_bhlApi) @@ -849,6 +862,7 @@ Names of plugin variables and helpers in the example are illustrative. | `On_PlayerKilled` | `Scoreboard_UpdatePlayer(killer)` | | `Update_TeamData` | Teammates and `bhl_sb_team(teamName)` cells | | `WarmUp_Timer` | `phase` 1 or 2 and `phase_left`; `phase` 0 at the end | +| `Scoreboard_SetPhase` | Warmup or match columns when the phase changes | | `resetPlayersScore` | `kills` 0 for everyone | | `endgame` | Final values for everyone, `phase` 3 | | Auto-save restore | `Scoreboard_UpdatePlayer(id)` | @@ -874,14 +888,9 @@ The client adds tokens to `bugfixedhl_*.txt`: | `BHL_SB_Weapon` | Weapon | Оружие | | `BHL_SB_Progress` | Progress | Прогресс | | `BHL_SB_Kills` | Kills | Убийства | -| `BHL_GG_ColPlayer` | Player | Игрок | -| `BHL_GG_You` | YOU | ТЫ | | `BHL_GG_Final` | FINAL | ФИНАЛ | -| `BHL_GG_LeaderFinal` | LEADER ON THE LAST LEVEL | ЛИДЕР НА ПОСЛЕДНЕМ УРОВНЕ | +| `BHL_GG_LeaderFinal` | Leader on the last level | Лидер на последнем уровне | | `BHL_GG_LeaderLine` | %s1 · %s2 · %s3 to win | %s1 · %s2 · %s3 до победы | -| `BHL_GG_PlayersOne` | %s1 / %s2 player | %s1 / %s2 игрок | -| `BHL_GG_PlayersFew` | %s1 / %s2 players | %s1 / %s2 игрока | -| `BHL_GG_PlayersMany` | %s1 / %s2 players | %s1 / %s2 игроков | | `BHL_GG_Place` | PLACE %s1 / %s2 | МЕСТО %s1 / %s2 | | `BHL_GG_Overtake` | To pass %s1: %s2 | До обгона %s1: %s2 | | `BHL_GG_Lead` | Lead: %s1 | Отрыв: %s1 | @@ -893,8 +902,6 @@ The client adds tokens to `bugfixedhl_*.txt`: | `BHL_GG_KillsFew` | %s1 kills | %s1 убийства | | `BHL_GG_KillsMany` | %s1 kills | %s1 убийств | -`Players*` takes the plural form from the second number. - ### 10.2 Plural forms The client picks the `One`, `Few` or `Many` token by the rule of its language: @@ -976,16 +983,20 @@ Protocol and server: - Map change, reconnect, joining mid-game, GunGame on and off, teamplay. - 32 players with bots: the full sync never triggers `Reliable channel overflowed`. - The full sync arrives after the client's `VidInit` and nothing is lost. -- Malformed messages from a debug server command: the client doesn't crash. +- Malformed messages: the client doesn't crash (checked offline by feeding the parser). GunGame scoreboard: -- 640×480, 1280×720 and 1920×1080: the table fits; on 4:3 it is wider than 70%. -- 12 and 32 players: the table grows down, then compact spacing, then scrolling. -- 9, 14 and 24 levels in the level strip; dots with 1–10 kills and the bar with more. -- Ties: shared places, the banner with several leaders on the last level. +- 640×480, 1280×720 and 1920×1080: the table has the size of the standard one and the columns fit. +- 12 and 32 players: compact spacing, then scrolling. +- 9, 14 and 24 levels in the level strip; dots without a counter with 1–10 kills, the bar with + the counter with more. +- Warmup: level, weapon and progress are hidden, kills and places by kills are shown; the match + columns come back when the match starts. +- Ties: shared places, the banner with several leaders on the last level; a long server name + next to the banner. - Teamplay with 2 and 4 teams: team headers, players by kills, spectators at the bottom. -- Avatars on and off; own row, last-level rows, ping 100 and above. +- Weapon icons in the scoreboard and the level bar with the OpenGL and the software renderer. - A weapon with a non-standard sprite shows the name from the config. GunGame HUD: @@ -1006,8 +1017,7 @@ GunGame HUD: 1. Are the opt-out settings needed, and are `hud_scoreboard_custom` and `hud_gungame` good names? 2. Icon tint in the scoreboard: the row text color or the HUD color? 3. Color codes in `Text` values: strip them in version 1, or draw them like in player names? -4. Exact sizes and colors from the mockups: dots, bar, level cells and their minimum, row height, - column widths, highlight colors, top-3 marks. -5. Icons for the map, the player count and the crown: files from the designer. -6. In teamplay, should player rows repeat the team level, weapon and progress, or leave them empty? -7. Weapon names marked as proposals in 10.3. +4. Exact sizes and colors of the HUD widget from the mockup: dots, bar, level cells and their + minimum. +5. In teamplay, should player rows repeat the team level, weapon and progress, or leave them empty? +6. Weapon names marked as proposals in 10.3. diff --git a/gamedir/CMakeLists.txt b/gamedir/CMakeLists.txt index b4eb9313..c72e5ebb 100644 --- a/gamedir/CMakeLists.txt +++ b/gamedir/CMakeLists.txt @@ -79,7 +79,6 @@ set( CLIENT_FILES ui/resource/MOTD.res ui/resource/open_source_software.txt ui/resource/ScorePanel.res - ui/resource/ScorePanel_gungame.res ui/resource/SpectatorInfoPanel.res ui/resource/TeamMenu.res diff --git a/gamedir/ui/resource/ClientSchemeBase.res b/gamedir/ui/resource/ClientSchemeBase.res index 6a70c83e..c938b313 100644 --- a/gamedir/ui/resource/ClientSchemeBase.res +++ b/gamedir/ui/resource/ClientSchemeBase.res @@ -597,7 +597,7 @@ Scheme } } - // GunGame HUD and scoreboard + // GunGame HUD "GunGameHudLarge" // place line of the HUD widget { "1" diff --git a/gamedir/ui/resource/ScorePanel_gungame.res b/gamedir/ui/resource/ScorePanel_gungame.res deleted file mode 100644 index 6e893b0c..00000000 --- a/gamedir/ui/resource/ScorePanel_gungame.res +++ /dev/null @@ -1,105 +0,0 @@ -/////////////////////////////////////////////////////////// -// Scoreboard layout of the "gungame" preset -// -// Loaded instead of ScorePanel.res while a server with the GunGame -// plugin sends the custom scoreboard. Keys that are not set here -// come from ScorePanel.res. -// -// Set here only keys that ScorePanel.res also has, or "gg_" keys: -// any other key would keep its GunGame value after switching back. -/////////////////////////////////////////////////////////// -#base "ScorePanel.res" - -"ui/resource/ScorePanel_gungame.res" -{ - "ScorePanel" - { - // Position and size are set in code: see gg_wide_percent and gg_top_percent - "xpos" "c-300" - "wide" "600" - - // Column widths. The player column takes the free width. - "column_avatar" "20" - "column_deaths" "50" - "column_ping" "50" - - // Minimum distance between the bottom edge of the score panel and the bottom edge of the screen - "vertical_margin" "20" - - // Width in percent of the screen width. The panel is wider if the columns need it. - "gg_wide_percent" "70" - - // Distance from the top edge of the screen in percent of the screen height - "gg_top_percent" "10" - - // Ping from this value is highlighted - "gg_ping_high" "100" - "gg_ping_high_color" "255 80 80 255" - - // Rows of this player and of players on the last level - "gg_own_row_bgcolor" "255 160 0 56" - "gg_final_row_bgcolor" "255 64 32 40" - - // Own name, level and weapon on the last level - "gg_emphasis_color" "255 176 0 255" - - // Marks of the first three places. Use opaque colors. - "gg_place_first_color" "255 160 0 255" - "gg_place_first_textcolor" "0 0 0 255" - "gg_place_top_color" "112 72 16 255" - "gg_place_final_color" "255 64 32 255" // First place on the last level - - // Banner "Leader on the last level" - "gg_banner_bgcolor" "255 64 32 48" - "gg_banner_accent_color" "255 160 0 255" - "gg_banner_padding" "3" - "gg_banner_accent_wide" "2" - } - "ServerName" - { - "xpos" "8" - "ypos" "4" - "wide" "320" - "tall" "18" - "font" "GunGameHudLarge" - } - "MapName" - { - "xpos" "8" - "ypos" "23" - "wide" "320" - "tall" "12" - } - "PlayerCount" - { - "visible" "0" - } - "LeaderTitle" - { - "fieldName" "LeaderTitle" - "xpos" "0" - "ypos" "5" - "wide" "100" - "tall" "12" - "visible" "0" - "textAlignment" "east" - "font" "GunGameHudText" - "fgcolor_override" "255 160 0 255" - } - "LeaderLine" - { - "fieldName" "LeaderLine" - "xpos" "0" - "ypos" "18" - "wide" "100" - "tall" "12" - "visible" "0" - "textAlignment" "east" - "font" "Default" - } - "PlayerList" - { - "xpos" "8" - "ypos" "40" - } -} diff --git a/gamedir/ui/resource/language/bugfixedhl_english.utf8.txt b/gamedir/ui/resource/language/bugfixedhl_english.utf8.txt index 09faedcb..cab9d871 100644 --- a/gamedir/ui/resource/language/bugfixedhl_english.utf8.txt +++ b/gamedir/ui/resource/language/bugfixedhl_english.utf8.txt @@ -32,14 +32,9 @@ "BHL_SB_Kills" "Kills" // GunGame -"BHL_GG_ColPlayer" "Player" -"BHL_GG_You" "YOU" "BHL_GG_Final" "FINAL" -"BHL_GG_LeaderFinal" "LEADER ON THE LAST LEVEL" +"BHL_GG_LeaderFinal" "Leader on the last level" "BHL_GG_LeaderLine" "%s1 · %s2 · %s3 to win" -"BHL_GG_PlayersOne" "%s1 / %s2 player" -"BHL_GG_PlayersFew" "%s1 / %s2 players" -"BHL_GG_PlayersMany" "%s1 / %s2 players" "BHL_GG_Place" "PLACE %s1 / %s2" "BHL_GG_Overtake" "To pass %s1: %s2" "BHL_GG_Lead" "Lead: %s1" diff --git a/gamedir/ui/resource/language/bugfixedhl_russian.utf8.txt b/gamedir/ui/resource/language/bugfixedhl_russian.utf8.txt index 7bcb6617..70cce4b1 100644 --- a/gamedir/ui/resource/language/bugfixedhl_russian.utf8.txt +++ b/gamedir/ui/resource/language/bugfixedhl_russian.utf8.txt @@ -32,14 +32,9 @@ "BHL_SB_Kills" "Убийства" // GunGame -"BHL_GG_ColPlayer" "Игрок" -"BHL_GG_You" "ТЫ" "BHL_GG_Final" "ФИНАЛ" -"BHL_GG_LeaderFinal" "ЛИДЕР НА ПОСЛЕДНЕМ УРОВНЕ" +"BHL_GG_LeaderFinal" "Лидер на последнем уровне" "BHL_GG_LeaderLine" "%s1 · %s2 · %s3 до победы" -"BHL_GG_PlayersOne" "%s1 / %s2 игрок" -"BHL_GG_PlayersFew" "%s1 / %s2 игрока" -"BHL_GG_PlayersMany" "%s1 / %s2 игроков" "BHL_GG_Place" "МЕСТО %s1 / %s2" "BHL_GG_Overtake" "До обгона %s1: %s2" "BHL_GG_Lead" "Отрыв: %s1" diff --git a/src/game/client/hud/gungame_hud.cpp b/src/game/client/hud/gungame_hud.cpp index 816e1817..f50327ca 100644 --- a/src/game/client/hud/gungame_hud.cpp +++ b/src/game/client/hud/gungame_hud.cpp @@ -10,7 +10,6 @@ #include "hud/gungame_hud.h" #include "vgui/client_viewport.h" #include "vgui/score_panel_cells.h" -#include "hud_renderer.h" static constexpr int PHASE_WARMUP = 1; static constexpr int PHASE_COUNTDOWN = 2; @@ -476,7 +475,7 @@ void CHudGunGamePanel::PaintBackground() } } - if (m_iLevelCount == 0 || !CHudRenderer::Get().IsAvailable()) + if (m_iLevelCount == 0) return; for (int i = 0; i < m_iBarShown; i++) @@ -501,10 +500,7 @@ void CHudGunGamePanel::PaintBackground() int x = m_iBarX + i * (m_iBarCellWide + m_iCellGap) + (m_iBarCellWide - wide) / 2; int y = m_iBarY + (m_iCellTall - tall) / 2; - Color color = GetColor(level > m_iLevel ? m_iAlphaDim : 255); - - CHudRenderer::SpriteSet(gHUD.GetSprite(sprite), color.r() * color.a() / 255, color.g() * color.a() / 255, color.b() * color.a() / 255); - CHudRenderer::SpriteDrawAdditiveScaled(0, x, y, wide, tall, &rc); + DrawScoreSprite(sprite, x, y, wide, tall, GetColor(level > m_iLevel ? m_iAlphaDim : 255)); } } diff --git a/src/game/client/hud_renderer.cpp b/src/game/client/hud_renderer.cpp index 7289ce8e..cd104601 100644 --- a/src/game/client/hud_renderer.cpp +++ b/src/game/client/hud_renderer.cpp @@ -52,12 +52,7 @@ void CHudRenderer::SpriteDrawAdditive(int frame, int x, int y, const wrect_t *pr s_Instance.DrawSprite(frame, x, y, -1, -1, prc, SpriteDrawMode::Additive); } -void CHudRenderer::SpriteDrawAdditiveScaled(int frame, int x, int y, int width, int height, const wrect_t *prc) -{ - s_Instance.DrawSprite(frame, x, y, -1, -1, prc, SpriteDrawMode::Additive, width, height); -} - -void CHudRenderer::DrawSprite(int frame, float x, float y, float width, float height, const wrect_t *prc, SpriteDrawMode mode, float outWidth, float outHeight) +void CHudRenderer::DrawSprite(int frame, float x, float y, float width, float height, const wrect_t *prc, SpriteDrawMode mode) { if (m_hPic <= 0) { @@ -103,12 +98,6 @@ void CHudRenderer::DrawSprite(int frame, float x, float y, float width, float he s[1] = t[1] = 1.0f; } - if (outWidth > 0 && outHeight > 0) - { - width = outWidth; - height = outHeight; - } - const model_t *spriteModel = gEngfuncs.GetSpritePointer(m_hPic); if (!spriteModel) diff --git a/src/game/client/hud_renderer.h b/src/game/client/hud_renderer.h index d1811376..8031768c 100644 --- a/src/game/client/hud_renderer.h +++ b/src/game/client/hud_renderer.h @@ -14,9 +14,6 @@ class CHudRenderer static void SpriteDraw(int frame, int x, int y, const wrect_t *prc); static void SpriteDrawAdditive(int frame, int x, int y, const wrect_t *prc); - //! Draws the sprite rectangle stretched to width x height - static void SpriteDrawAdditiveScaled(int frame, int x, int y, int width, int height, const wrect_t *prc); - private: enum class SpriteDrawMode { @@ -27,7 +24,7 @@ class CHudRenderer HSPRITE m_hPic = 0; uint8_t m_SpriteColor[4]; - void DrawSprite(int frame, float x, float y, float width, float height, const wrect_t *prc, SpriteDrawMode mode, float outWidth = -1, float outHeight = -1); + void DrawSprite(int frame, float x, float y, float width, float height, const wrect_t *prc, SpriteDrawMode mode); }; #endif diff --git a/src/game/client/scoreboard_data.cpp b/src/game/client/scoreboard_data.cpp index 2032be7c..10e5327b 100644 --- a/src/game/client/scoreboard_data.cpp +++ b/src/game/client/scoreboard_data.cpp @@ -441,7 +441,7 @@ int CScoreboardData::FindPrimaryColumn() const { for (int i = 0; i < MAX_COLUMNS; i++) { - if (m_Columns[i].bValid && m_Columns[i].IsPrimary()) + if (m_Columns[i].bValid && m_Columns[i].IsPrimary() && !m_Columns[i].IsHidden()) return i; } @@ -736,7 +736,6 @@ void CScoreboardData::TestCommand() COL_WEAPON, COL_PROGRESS, COL_KILLS, - COL_DEATHS, COL_SCORE, COL_PHASE, COL_PHASE_LEFT, @@ -758,7 +757,6 @@ void CScoreboardData::TestCommand() { "weapon", "#BHL_SB_Weapon", E_Display::Icon, 120, 0, E_ColumnFlags::None }, { "progress", "#BHL_SB_Progress", E_Display::Meter, 90, 0, E_ColumnFlags::None }, { "kills", "#BHL_SB_Kills", E_Display::Text, 60, 2, E_ColumnFlags::AlignRight }, - { "deaths", "", E_Display::Builtin, 0, 0, E_ColumnFlags::AlignRight }, { "score", "", E_Display::Text, 0, 1, E_ColumnFlags::Hidden }, { "phase", "", E_Display::Text, 0, 0, E_ColumnFlags::Hidden }, { "phase_left", "", E_Display::Text, 0, 0, E_ColumnFlags::Hidden }, @@ -790,10 +788,11 @@ void CScoreboardData::TestCommand() constexpr int LEVEL_COUNT = static_cast(std::size(s_Levels)); + int phase = gEngfuncs.Cmd_Argc() >= 3 ? atoi(gEngfuncs.Cmd_Argv(2)) : 0; + m_bConfigReceived = true; - m_ConfigFlags = static_cast(static_cast(E_ConfigFlags::HideFrags) | static_cast(E_ConfigFlags::HideEff) | static_cast(E_ConfigFlags::HideSteamID)); + m_ConfigFlags = static_cast(static_cast(E_ConfigFlags::HideFrags) | static_cast(E_ConfigFlags::HideDeaths) | static_cast(E_ConfigFlags::HideEff) | static_cast(E_ConfigFlags::HideSteamID)); V_strcpy_safe(m_szPreset, preset); - V_strcpy_safe(m_szTitle, "GUNGAME"); V_strcpy_safe(m_szTag, gHUD.m_Teamplay ? "TEAM" : "FFA"); for (int i = 0; i < static_cast(std::size(s_Columns)); i++) @@ -808,6 +807,22 @@ void CScoreboardData::TestCommand() V_strcpy_safe(column.szTitle, s_Columns[i].pszTitle); } + // Warmup and countdown show kills instead of levels, like the plugin + if (phase == 1 || phase == 2) + { + for (int col : { COL_LEVEL, COL_WEAPON, COL_PROGRESS }) + SetEnumFlag(m_Columns[col].flags, E_ColumnFlags::Hidden); + + ClearEnumFlag(m_Columns[COL_LEVEL].flags, E_ColumnFlags::Primary); + SetEnumFlag(m_Columns[COL_KILLS].flags, E_ColumnFlags::Primary); + m_Columns[COL_KILLS].iSort = 1; + m_Columns[COL_SCORE].iSort = 2; + } + else + { + SetEnumFlag(m_Columns[COL_KILLS].flags, E_ColumnFlags::Hidden); + } + UpdateSortColumns(); List &levels = m_Lists[0]; @@ -818,7 +833,7 @@ void CScoreboardData::TestCommand() for (int i = 0; i < LEVEL_COUNT; i++) levels.items[i] = MakeIcon(s_Levels[i].pszSprite, s_Levels[i].pszName); - m_GlobalValues[COL_PHASE] = MakeInt(gEngfuncs.Cmd_Argc() >= 3 ? atoi(gEngfuncs.Cmd_Argv(2)) : 0); + m_GlobalValues[COL_PHASE] = MakeInt(phase); m_GlobalValues[COL_PHASE_LEFT] = MakeInt(gEngfuncs.Cmd_Argc() >= 4 ? atoi(gEngfuncs.Cmd_Argv(3)) : 0); int playerCount = 0; diff --git a/src/game/client/vgui/score_panel.cpp b/src/game/client/vgui/score_panel.cpp index 9b329a5c..58836280 100644 --- a/src/game/client/vgui/score_panel.cpp +++ b/src/game/client/vgui/score_panel.cpp @@ -1,6 +1,5 @@ #include #include -#include #include #include #include @@ -180,8 +179,7 @@ CScorePanel::CScorePanel() CreatePlayerMenu(); - Q_strncpy(m_szLayoutFile, VGUI2_ROOT_DIR "resource/ScorePanel.res", sizeof(m_szLayoutFile)); - LoadControlSettings(m_szLayoutFile); + LoadControlSettings(VGUI2_ROOT_DIR "resource/ScorePanel.res"); SetVisible(false); } @@ -191,7 +189,7 @@ void CScorePanel::UpdateServerName() CScoreboardData &data = CScoreboardData::Get(); // The title of the custom scoreboard replaces the server name - if (m_bCustom && (data.GetTitle()[0] || m_bGunGame)) + if (m_bCustom && data.GetTitle()[0]) CScoreboardData::LocalizeString(data.GetTitle(), wbuf, sizeof(wbuf)); else g_pVGuiLocalize->ConvertANSIToUnicode(g_pViewport->GetServerName(), wbuf, sizeof(wbuf)); @@ -333,7 +331,7 @@ void CScorePanel::PaintBackground() m_pLeaderTitleLabel->GetBounds(x, y, wide, tall); m_pLeaderLineLabel->GetBounds(lineX, lineY, lineWide, lineTall); - int x0 = std::min(x, lineX) - m_iGGBannerPadding; + int x0 = std::min(x, lineX) - m_iGGBannerAccentWide - m_iGGBannerPadding; int y0 = y - m_iGGBannerPadding; int x1 = std::max(x + wide, lineX + lineWide) + m_iGGBannerPadding; int y1 = lineY + lineTall + m_iGGBannerPadding; @@ -421,24 +419,11 @@ void CScorePanel::OnItemContextMenu(int itemID) void CScorePanel::FullUpdate() { CScoreboardData &data = CScoreboardData::Get(); - bool bWasGunGame = m_bGunGame; m_bCustom = data.IsActive(); m_bGunGame = m_bCustom && data.IsGunGame(); m_iStoreSerial = data.GetSerial(); m_iSchemaSerial = data.GetSchemaSerial(); - // The GunGame preset sets the bounds in code, only a reload restores them - if (bWasGunGame != m_bGunGame) - m_szLayoutFile[0] = '\0'; - - UpdateLayoutFile(); - - if (!m_bGunGame) - { - m_pLeaderTitleLabel->SetVisible(false); - m_pLeaderLineLabel->SetVisible(false); - } - UpdateServerName(); UpdateMapName(); RefreshItems(); @@ -895,8 +880,6 @@ void CScorePanel::UpdateScoresAndCounts() snprintf(buf, sizeof(buf), "%d/%d", iPlayerCount, gEngfuncs.GetMaxClients()); m_pPlayerCountLabel->SetText(buf); - if (m_bGunGame) - UpdateGunGameHeader(iPlayerCount); } int CScorePanel::GetNameColumnWidth() @@ -924,7 +907,7 @@ Color CScorePanel::GetPlayerBgColor(CPlayerInfo *pi) { if (pi->IsThisPlayer()) { - return m_bGunGame ? m_GGOwnRowColor : m_ThisPlayerBgColor; + return m_ThisPlayerBgColor; } else if (m_iKillerIndex == pi->GetIndex()) { @@ -946,10 +929,6 @@ Color CScorePanel::GetPlayerBgColor(CPlayerInfo *pi) return color; } } - else if (m_bGunGame && IsOnLastLevel(pi->GetIndex())) - { - return m_GGFinalRowColor; - } return Color(0, 0, 0, 0); } @@ -1198,7 +1177,6 @@ void CScorePanel::RestoreSize() void CScorePanel::Resize() { SizeMode mode = GetSizeMode(); - int top = m_bGunGame ? ScreenHeight * m_iGGTopPercent / 100 : m_iVerticalMargin; // Returns true if scrollbar was enabled auto fnUpdateSize = [&](int &height) { @@ -1214,10 +1192,10 @@ void CScorePanel::Resize() listHeight = max(m_iMinHeight, tall); height += listHeight; - if (ScreenHeight - height < top + m_iVerticalMargin) + if (ScreenHeight - height < m_iVerticalMargin * 2) { // It didn't fit - height = ScreenHeight - top - m_iVerticalMargin; + height = ScreenHeight - m_iVerticalMargin * 2; listHeight = height - addHeight; m_pPlayerList->SetVerticalScrollbar(true); bIsOverflowed = true; @@ -1253,10 +1231,13 @@ void CScorePanel::Resize() GetSize(wide, tall); SetSize(wide, height); - // Move to center. The GunGame preset grows down from the top edge. + // Move to center GetPos(x, y); - y = m_bGunGame ? top : (ScreenHeight - height) / 2; + y = (ScreenHeight - height) / 2; SetPos(x, y); + + // A new size lays out the children from the layout file, which moves the banner + UpdateLeaderBanner(); } bool CScorePanel::StaticPlayerSortFuncByFrags(vgui2::SectionedListPanel *list, int itemID1, int itemID2) @@ -1314,36 +1295,6 @@ bool CScorePanel::IsTeamBefore(int ilhs, int irhs) return ilhs > irhs; } -void CScorePanel::UpdateLayoutFile() -{ - char path[64]; - char preset[bhl::sb::MAX_PRESET_LEN + 1]; - Q_strncpy(path, VGUI2_ROOT_DIR "resource/ScorePanel.res", sizeof(path)); - Q_strncpy(preset, CScoreboardData::Get().GetPreset(), sizeof(preset)); - Q_strlower(preset); - - // The preset comes from the server, so only [a-z0-9_] may get into the file name - bool bValidPreset = m_bCustom && preset[0]; - - for (const char *c = preset; *c && bValidPreset; c++) - bValidPreset = (*c >= 'a' && *c <= 'z') || (*c >= '0' && *c <= '9') || *c == '_'; - - if (bValidPreset) - { - char presetPath[64]; - snprintf(presetPath, sizeof(presetPath), VGUI2_ROOT_DIR "resource/ScorePanel_%s.res", preset); - - if (g_pFullFileSystem->FileExists(presetPath)) - Q_strncpy(path, presetPath, sizeof(path)); - } - - if (!Q_strcmp(path, m_szLayoutFile)) - return; - - Q_strncpy(m_szLayoutFile, path, sizeof(m_szLayoutFile)); - LoadControlSettings(m_szLayoutFile); -} - void CScorePanel::BuildCustomColumns() { m_CustomColumns.clear(); @@ -1421,10 +1372,6 @@ void CScorePanel::BuildCustomColumns() Q_strncpy(col.szName, s_StdColumnNames[(int)type], sizeof(col.szName)); CScoreboardData::LocalizeString(title, col.wszTitle, sizeof(col.wszTitle)); - - if (m_bGunGame) - ScoreTextToUpper(col.wszTitle); - m_CustomColumns.push_back(col); }; @@ -1444,7 +1391,7 @@ void CScorePanel::BuildCustomColumns() width = m_iColumnWidthAvatar; break; case ColumnType::Name: - title = m_bGunGame ? "#BHL_GG_ColPlayer" : "#PlayerName"; + title = "#PlayerName"; break; case ColumnType::SteamID: title = "#BHL_Scores_ColSteamID"; @@ -1467,7 +1414,7 @@ void CScorePanel::BuildCustomColumns() bVisible = !data.IsStdColumnHidden(bhl::sb::E_ConfigFlags::HideDeaths); break; case ColumnType::Ping: - title = (hud_scoreboard_showloss.GetBool() && !m_bGunGame) ? "#BHL_Scores_ColPingLoss" : "#BHL_Scores_ColPing"; + title = hud_scoreboard_showloss.GetBool() ? "#BHL_Scores_ColPingLoss" : "#BHL_Scores_ColPing"; width = m_iColumnWidthPing; break; case ColumnType::Custom: @@ -1486,13 +1433,8 @@ void CScorePanel::BuildCustomColumns() if (pColumn->szTitle[0]) title = pColumn->szTitle; } - else if (m_bGunGame && type == ColumnType::Ping) - { - align = 2; - } - bool bCell = type == ColumnType::Rank || (m_bGunGame && (type == ColumnType::Name || type == ColumnType::Ping)); - fnAddColumn(type, -1, title, width, align, bCell); + fnAddColumn(type, -1, title, width, align, false); }; // Standard columns moved by Builtin columns @@ -1569,24 +1511,12 @@ void CScorePanel::BuildCustomColumns() fnAddStdColumn(ColumnType::Ping, nullptr); // Name takes the free width and shrinks to its minimum, then columns are dropped from the end - int listX, listY; - m_pPlayerList->GetPos(listX, listY); int reservedWide = LIST_ROW_PADDING + m_pPlayerList->GetScrollBar()->GetWide(); int otherWide = 0; for (const CustomColumn &col : m_CustomColumns) otherWide += col.iWidth; - if (m_bGunGame) - { - int x, y; - int wide = std::max(ScreenWidth * m_iGGWidePercent / 100, otherWide + m_iColumnWidthNameMin + reservedWide + 2 * listX); - wide = std::min(wide, ScreenWidth); - GetPos(x, y); - SetBounds((ScreenWidth - wide) / 2, y, wide, GetTall()); - m_pPlayerList->SetWide(wide - 2 * listX); - } - int freeWide = m_pPlayerList->GetWide() - reservedWide; // On narrow screens Name gives up to a fifth of its minimum before a column is dropped @@ -1630,15 +1560,27 @@ void CScorePanel::UpdateCustomCells(CPlayerInfo *pi, KeyValues *kv) for (const CustomColumn &col : m_CustomColumns) { - if (col.nSlot == -1) + if (col.type == ColumnType::Rank) { - if (col.type == ColumnType::Custom) - { - data.GetPlayerValue(client, col.nColumnID).ToString(wbuf, sizeof(wbuf)); - Q_WStringToUTF8(wbuf, buf, sizeof(buf)); - kv->SetString(col.szName, buf); - } + // With team sections the place is shown in team headers + int place = m_PlayerData[client].nTeamID == HEADER_SECTION_ID ? GetPlayerRank(client) : 0; + buf[0] = '\0'; + if (place > 0) + snprintf(buf, sizeof(buf), "%d", place); + + kv->SetString(col.szName, buf); + continue; + } + + if (col.type != ColumnType::Custom) + continue; + + if (col.nSlot == -1) + { + data.GetPlayerValue(client, col.nColumnID).ToString(wbuf, sizeof(wbuf)); + Q_WStringToUTF8(wbuf, buf, sizeof(buf)); + kv->SetString(col.szName, buf); continue; } @@ -1648,67 +1590,10 @@ void CScorePanel::UpdateCustomCells(CPlayerInfo *pi, KeyValues *kv) pCell->SetSize(col.iWidth - COLUMN_DATA_GAP, lineSpacing); pCell->SetAlign(col.iAlign); pCell->SetColor(color); + pCell->SetValue(data.GetColumn(col.nColumnID).display, data.GetPlayerValue(client, col.nColumnID)); - switch (col.type) - { - case ColumnType::Rank: - { - // With team sections the place is shown in team headers - int place = m_PlayerData[client].nTeamID == HEADER_SECTION_ID ? GetPlayerRank(client) : 0; - Color markColor(0, 0, 0, 0); - - if (m_bGunGame && place == 1) - { - markColor = bLastLevel ? m_GGPlaceFinalColor : m_GGPlaceFirstColor; - pCell->SetColor(m_GGPlaceFirstTextColor); - } - else if (m_bGunGame && place >= 2 && place <= 3) - { - markColor = m_GGPlaceTopColor; - } - - pCell->SetPlace(place, markColor); - break; - } - case ColumnType::Name: - { - RemoveColorCodes(kv->GetString(col.szName), buf, sizeof(buf)); - Q_UTF8ToWString(buf, wbuf, sizeof(wbuf), STRINGCONVERT_REPLACE); - pCell->SetText(wbuf); - - if (pi->IsThisPlayer()) - { - pCell->SetColor(m_GGEmphasisColor); - pCell->SetBadge(g_pVGuiLocalize->Find("#BHL_GG_You")); - } - - break; - } - case ColumnType::Ping: - { - V_snwprintf(wbuf, ARRAYSIZE(wbuf), L"%d", pi->GetPing()); - pCell->SetText(wbuf); - - if (pi->GetPing() >= m_iGGPingHigh) - pCell->SetColor(m_GGPingHighColor); - - break; - } - case ColumnType::Custom: - { - pCell->SetValue(data.GetColumn(col.nColumnID).display, data.GetPlayerValue(client, col.nColumnID)); - - if (bLastLevel && (col.nColumnID == m_iLevelColumn || col.nColumnID == m_iWeaponColumn)) - pCell->SetColor(m_GGEmphasisColor); - - if (bLastLevel && col.nColumnID == m_iWeaponColumn) - pCell->SetBadge(g_pVGuiLocalize->Find("#BHL_GG_Final")); - - break; - } - default: - break; - } + if (bLastLevel && col.nColumnID == m_iWeaponColumn) + pCell->SetBadge(g_pVGuiLocalize->Find("#BHL_GG_Final")); kv->SetInt(col.szName, index); } @@ -1736,51 +1621,43 @@ void CScorePanel::UpdateCustomTeamHeader(int nTeamID) } else if (bIsTeam) { - data.GetTeamValue(nTeamID, col.nColumnID).ToString(wbuf, sizeof(wbuf)); + const CScoreboardData::Value &value = data.GetTeamValue(nTeamID, col.nColumnID); + + // Like dots in rows, a short progress has no counter + if (data.GetColumn(col.nColumnID).display != bhl::sb::E_Display::Meter || value.type != bhl::sb::E_ValueType::Progress || value.iMax > bhl::sb::MAX_DOTS) + value.ToString(wbuf, sizeof(wbuf)); } m_pPlayerList->ModifyColumn(nTeamID, col.szName, wbuf); } } -void CScorePanel::UpdateGunGameHeader(int iPlayerCount) +void CScorePanel::UpdateLeaderBanner() { CScoreboardData &data = CScoreboardData::Get(); wchar_t wbuf[256]; - wchar_t wbuf2[128]; - wchar_t wnum1[16]; - wchar_t wnum2[16]; - char buf[64]; - - int maxPlayers = gEngfuncs.GetMaxClients(); - V_snwprintf(wnum1, ARRAYSIZE(wnum1), L"%d", iPlayerCount); - V_snwprintf(wnum2, ARRAYSIZE(wnum2), L"%d", maxPlayers); - snprintf(buf, sizeof(buf), "BHL_GG_Players%s", CScoreboardData::GetPluralSuffix(maxPlayers)); - ConstructScoreText(wbuf2, sizeof(wbuf2), buf, 2, wnum1, wnum2); - - wchar_t wmap[64]; - V_FileBase(gEngfuncs.pfnGetLevelName(), buf, sizeof(buf)); - g_pVGuiLocalize->ConvertANSIToUnicode(buf, wmap, sizeof(wmap)); - V_snwprintf(wbuf, ARRAYSIZE(wbuf), L"%ls \u00B7 %ls", wmap, wbuf2); - m_pMapNameLabel->SetText(wbuf); // Leader: the first team in teamplay, the first participant otherwise int leader = 0; + bool bIsTeam = false; - for (int i = 1; i <= MAX_TEAMS; i++) + if (m_bGunGame) { - if (m_TeamData[i].iPlayerCount > 0 && (leader == 0 || IsTeamBefore(i, leader))) - leader = i; - } + for (int i = 1; i <= MAX_TEAMS; i++) + { + if (m_TeamData[i].iPlayerCount > 0 && (leader == 0 || IsTeamBefore(i, leader))) + leader = i; + } - bool bIsTeam = leader != 0; + bIsTeam = leader != 0; - for (int i = 1; i <= MAX_PLAYERS && !bIsTeam; i++) - { - CPlayerInfo *pi = GetPlayerInfo(i); + for (int i = 1; i <= MAX_PLAYERS && !bIsTeam; i++) + { + CPlayerInfo *pi = GetPlayerInfo(i); - if (pi->IsConnected() && !pi->IsSpectator() && (leader == 0 || IsPlayerBefore(i, leader))) - leader = i; + if (pi->IsConnected() && !pi->IsSpectator() && (leader == 0 || IsPlayerBefore(i, leader))) + leader = i; + } } auto fnGetValue = [&](int col) -> const CScoreboardData::Value & { @@ -1792,7 +1669,13 @@ void CScorePanel::UpdateGunGameHeader(int iPlayerCount) m_pLeaderLineLabel->SetVisible(bShowBanner); if (!bShowBanner) + { + if (m_iServerNameWide != -1) + m_pServerNameLabel->SetWide(m_iServerNameWide); + + m_iServerNameWide = -1; return; + } wchar_t wname[128]; wchar_t wweapon[64] = L""; @@ -1819,20 +1702,36 @@ void CScorePanel::UpdateGunGameHeader(int iPlayerCount) ConstructScoreText(wbuf, sizeof(wbuf), "BHL_GG_LeaderLine", 3, wname, wweapon, wkills); m_pLeaderTitleLabel->SetText("#BHL_GG_LeaderFinal"); + m_pLeaderTitleLabel->SetFgColor(m_GGBannerAccentColor); m_pLeaderLineLabel->SetText(wbuf); - // Align the right edge of the banner with the player list - int listX, listY, x, y, titleWide, lineWide, tall; - m_pPlayerList->GetPos(listX, listY); + // Both lines end left of the player count, on the lines of the server and the map name + int nameX, nameY, nameWide, nameTall, mapX, mapY, mapWide, mapTall, countX, countY, countWide, countTall; + int mapTextWide, countTextWide, titleWide, lineWide, tall; + m_pServerNameLabel->GetBounds(nameX, nameY, nameWide, nameTall); + m_pMapNameLabel->GetBounds(mapX, mapY, mapWide, mapTall); + m_pPlayerCountLabel->GetBounds(countX, countY, countWide, countTall); + m_pMapNameLabel->GetContentSize(mapTextWide, tall); + m_pPlayerCountLabel->GetContentSize(countTextWide, tall); m_pLeaderTitleLabel->GetContentSize(titleWide, tall); m_pLeaderLineLabel->GetContentSize(lineWide, tall); - int wide = std::max(titleWide, lineWide); - int bannerX = GetWide() - listX - m_iGGBannerPadding - wide; - m_pLeaderTitleLabel->GetPos(x, y); - m_pLeaderTitleLabel->SetBounds(bannerX, y, wide, m_pLeaderTitleLabel->GetTall()); - m_pLeaderLineLabel->GetPos(x, y); - m_pLeaderLineLabel->SetBounds(bannerX, y, wide, m_pLeaderLineLabel->GetTall()); + if (m_iServerNameWide == -1) + m_iServerNameWide = nameWide; + + int tagWide = m_wszTag[0] ? GetScoreBadgeWide(m_CellStyle, m_wszTag) + m_CellStyle.iSpacing : 0; + int boxLeft = m_iGGBannerAccentWide + m_iGGBannerPadding + m_CellStyle.iSpacing; + int bannerRight = countX + countWide - countTextWide - m_CellStyle.iSpacing - m_iGGBannerPadding; + + // A long line is cut, so the map name and a third of the server name stay visible + int bannerMinX = std::max(mapX + mapTextWide, nameX + tagWide + (bannerRight - nameX) / 3) + boxLeft; + int wide = std::min(std::max(titleWide, lineWide), std::max(bannerRight - bannerMinX, 0)); + int bannerX = bannerRight - wide; + m_pLeaderTitleLabel->SetBounds(bannerX, nameY, wide, nameTall); + m_pLeaderLineLabel->SetBounds(bannerX, mapY, wide, mapTall); + + // The server name and its tag end before the banner + m_pServerNameLabel->SetWide(std::clamp(bannerX - boxLeft - tagWide - nameX, 0, m_iServerNameWide)); } int CScorePanel::GetPlayerRank(int client) diff --git a/src/game/client/vgui/score_panel.h b/src/game/client/vgui/score_panel.h index 245b5be5..fe9deb59 100644 --- a/src/game/client/vgui/score_panel.h +++ b/src/game/client/vgui/score_panel.h @@ -181,7 +181,6 @@ class CScorePanel : public vgui2::Frame, public IViewportPanel vgui2::Label *m_pLeaderLineLabel = nullptr; std::vector m_CustomColumns; ScoreCellStyle m_CellStyle; - char m_szLayoutFile[64] = {}; wchar_t m_wszTag[32] = {}; bool m_bCustom = false; bool m_bGunGame = false; @@ -194,6 +193,7 @@ class CScorePanel : public vgui2::Frame, public IViewportPanel int m_iLevelColumn = -1; int m_iWeaponColumn = -1; int m_iProgressColumn = -1; + int m_iServerNameWide = -1; //!< Width of the server name label before the leader banner cut it // Column widths CPanelAnimationVarAliasType(int, m_iColumnWidthAvatar, "column_avatar", "26", "proportional_int"); @@ -209,8 +209,7 @@ class CScorePanel : public vgui2::Frame, public IViewportPanel CPanelAnimationVarAliasType(int, m_iVerticalMargin, "vertical_margin", "30", "proportional_int"); CPanelAnimationVarAliasType(int, m_iBottomPadding, "bottom_padding", "4", "proportional_int"); - // Custom scoreboard. A key set in ScorePanel_.res must also be set in ScorePanel.res: - // otherwise it keeps the preset value after switching back. + // Custom scoreboard CPanelAnimationVarAliasType(int, m_iColumnWidthRank, "column_rank", "24", "proportional_int"); CPanelAnimationVarAliasType(int, m_iColumnWidthNameMin, "column_name_min", "100", "proportional_int"); CPanelAnimationVar(vgui2::HFont, m_CellFont, "cell_font", "Default"); @@ -227,21 +226,10 @@ class CScorePanel : public vgui2::Frame, public IViewportPanel CPanelAnimationVarAliasType(int, m_iCellStripGap, "cell_strip_gap", "1", "proportional_int"); CPanelAnimationVarAliasType(int, m_iCellSpacing, "cell_spacing", "3", "proportional_int"); - // GunGame preset, set in ScorePanel_gungame.res - CPanelAnimationVar(int, m_iGGWidePercent, "gg_wide_percent", "70"); - CPanelAnimationVar(int, m_iGGTopPercent, "gg_top_percent", "10"); - CPanelAnimationVar(int, m_iGGPingHigh, "gg_ping_high", "100"); - CPanelAnimationVar(Color, m_GGOwnRowColor, "gg_own_row_bgcolor", "255 160 0 56"); - CPanelAnimationVar(Color, m_GGFinalRowColor, "gg_final_row_bgcolor", "255 64 32 40"); - CPanelAnimationVar(Color, m_GGEmphasisColor, "gg_emphasis_color", "255 176 0 255"); - CPanelAnimationVar(Color, m_GGPlaceFirstColor, "gg_place_first_color", "255 160 0 255"); - CPanelAnimationVar(Color, m_GGPlaceFirstTextColor, "gg_place_first_textcolor", "0 0 0 255"); - CPanelAnimationVar(Color, m_GGPlaceTopColor, "gg_place_top_color", "112 72 16 255"); - CPanelAnimationVar(Color, m_GGPlaceFinalColor, "gg_place_final_color", "255 64 32 255"); - CPanelAnimationVar(Color, m_GGPingHighColor, "gg_ping_high_color", "255 80 80 255"); + // Banner "Leader on the last level" of the GunGame preset CPanelAnimationVar(Color, m_GGBannerBgColor, "gg_banner_bgcolor", "255 64 32 48"); CPanelAnimationVar(Color, m_GGBannerAccentColor, "gg_banner_accent_color", "255 160 0 255"); - CPanelAnimationVarAliasType(int, m_iGGBannerPadding, "gg_banner_padding", "3", "proportional_int"); + CPanelAnimationVarAliasType(int, m_iGGBannerPadding, "gg_banner_padding", "1", "proportional_int"); CPanelAnimationVarAliasType(int, m_iGGBannerAccentWide, "gg_banner_accent_wide", "2", "proportional_int"); /** @@ -368,12 +356,7 @@ class CScorePanel : public vgui2::Frame, public IViewportPanel bool IsTeamBefore(int ilhs, int irhs); /** - * Loads ScorePanel_.res if the active preset has one, ScorePanel.res otherwise. - */ - void UpdateLayoutFile(); - - /** - * Builds m_CustomColumns. Sets the width of the panel in the GunGame preset. + * Builds m_CustomColumns. */ void BuildCustomColumns(); @@ -393,9 +376,9 @@ class CScorePanel : public vgui2::Frame, public IViewportPanel void UpdateCustomTeamHeader(int nTeamID); /** - * Updates the map line and the leader banner of the GunGame preset. + * Updates the leader banner of the GunGame preset. It stands in the header left of the player count. */ - void UpdateGunGameHeader(int iPlayerCount); + void UpdateLeaderBanner(); /** * Returns the place for the rank column, 0 for none. diff --git a/src/game/client/vgui/score_panel_cells.cpp b/src/game/client/vgui/score_panel_cells.cpp index 05f158f7..134ac6a4 100644 --- a/src/game/client/vgui/score_panel_cells.cpp +++ b/src/game/client/vgui/score_panel_cells.cpp @@ -1,11 +1,13 @@ #include #include +#include +#include #include #include #include +#include #include "hud.h" #include "cl_util.h" -#include "hud_renderer.h" #include "vgui/score_panel_cells.h" namespace @@ -13,6 +15,18 @@ namespace constexpr wchar_t ELLIPSIS = 0x2026; +constexpr int SPRITE_IDENT = ('P' << 24) | ('S' << 16) | ('D' << 8) | 'I'; +constexpr int SPRITE_VERSION = 2; +constexpr int SPRITE_INDEXALPHA = 2; +constexpr int SPRITE_ALPHATEST = 3; +constexpr int SPRITE_MAX_SIZE = 1024; + +constexpr int TEXTURE_NOT_CREATED = -2; +constexpr int TEXTURE_FAILED = -1; + +//! VGUI2 textures of hud.txt sprites by sprite index +std::vector s_SpriteTextures; + int GetTextWide(vgui2::HFont font, const wchar_t *text) { int wide = 0; @@ -75,9 +89,101 @@ int GetBadgePadding(const ScoreCellStyle &style) return vgui2::surface()->GetFontTall(style.hBadgeFont) / 3; } -int GetScoreBadgeWide(const ScoreCellStyle &style, const wchar_t *text) +/** + * Reads rectangle rc of the first frame of a sprite file as RGBA. + * Alpha is the brightness and colors are scaled up by it, so blending looks like additive drawing. + */ +bool LoadSpriteRGBA(const char *path, const wrect_t &rc, std::vector &rgba, int &wide, int &tall) { - return GetTextWide(style.hBadgeFont, text) + 2 * GetBadgePadding(style); + int length = 0; + unsigned char *file = gEngfuncs.COM_LoadFile(path, 5, &length); + + if (!file) + return false; + + int pos = 0; + auto fnRead = [&](void *dest, int size) { + if (size < 0 || pos + size > length) + return false; + + memcpy(dest, file + pos, size); + pos += size; + return true; + }; + + // dsprite_t: ident, version, type, texFormat, boundingradius, width, height, numframes, beamlength, synctype + int header[10]; + short paletteSize = 0; + unsigned char palette[256][3]; + int frameType = 0; + int frame[4]; // origin x, origin y, width, height + + bool bValid = fnRead(header, sizeof(header)) && header[0] == SPRITE_IDENT && header[1] == SPRITE_VERSION && header[7] > 0 + && fnRead(&paletteSize, sizeof(paletteSize)) && paletteSize > 0 && paletteSize <= 256 + && fnRead(palette, paletteSize * 3) && fnRead(&frameType, sizeof(frameType)) && frameType == 0 + && fnRead(frame, sizeof(frame)) && frame[2] > 0 && frame[3] > 0 && frame[2] <= SPRITE_MAX_SIZE && frame[3] <= SPRITE_MAX_SIZE + && pos + frame[2] * frame[3] <= length; + + if (bValid) + { + int texFormat = header[3]; + int x0 = std::clamp(rc.left, 0, frame[2]); + int x1 = std::clamp(rc.right, x0, frame[2]); + int y0 = std::clamp(rc.top, 0, frame[3]); + int y1 = std::clamp(rc.bottom, y0, frame[3]); + const unsigned char *pixels = file + pos; + wide = x1 - x0; + tall = y1 - y0; + // Transparent texels are white, so filtering doesn't darken the edges + rgba.assign(wide * tall * 4, 255); + + for (int y = 0; y < tall; y++) + { + for (int x = 0; x < wide; x++) + { + int index = pixels[(y0 + y) * frame[2] + x0 + x]; + int color[3]; + + for (int i = 0; i < 3; i++) + { + if (texFormat == SPRITE_INDEXALPHA) + color[i] = paletteSize == 256 ? palette[255][i] * index / 255 : 0; + else if (texFormat == SPRITE_ALPHATEST && index == 255) + color[i] = 0; + else + color[i] = index < paletteSize ? palette[index][i] : 0; + } + + int alpha = std::max(std::max(color[0], color[1]), color[2]); + unsigned char *out = &rgba[(y * wide + x) * 4]; + + for (int i = 0; i < 3 && alpha > 0; i++) + out[i] = static_cast(color[i] * 255 / alpha); + + out[3] = static_cast(alpha); + } + } + + bValid = wide > 0 && tall > 0; + } + + gEngfuncs.COM_FreeFile(file); + return bValid; +} + +int CreateSpriteTexture(int sprite) +{ + const model_t *model = gEngfuncs.GetSpritePointer(gHUD.GetSprite(sprite)); + std::vector rgba; + int wide = 0; + int tall = 0; + + if (!model || !LoadSpriteRGBA(model->name, gHUD.GetSpriteRect(sprite), rgba, wide, tall)) + return TEXTURE_FAILED; + + int id = vgui2::surface()->CreateNewTextureID(true); + vgui2::surface()->DrawSetTextureRGBA(id, rgba.data(), wide, tall, true, false); + return id; } } @@ -93,7 +199,6 @@ void CScoreCellImage::Clear() m_iSprite = -1; m_iCur = 0; m_iMax = 0; - m_MarkColor = Color(0, 0, 0, 0); m_wszText[0] = L'\0'; m_wszBadge[0] = L'\0'; } @@ -124,25 +229,6 @@ void CScoreCellImage::SetValue(bhl::sb::E_Display display, const CScoreboardData } } -void CScoreCellImage::SetText(const wchar_t *text) -{ - Clear(); - m_Kind = Kind::Text; - V_wcsncpy(m_wszText, text, sizeof(m_wszText)); -} - -void CScoreCellImage::SetPlace(int place, Color markColor) -{ - Clear(); - - if (place <= 0) - return; - - m_Kind = Kind::Place; - m_iCur = place; - m_MarkColor = markColor; -} - void CScoreCellImage::SetBadge(const wchar_t *badge) { V_wcsncpy(m_wszBadge, badge ? badge : L"", sizeof(m_wszBadge)); @@ -167,9 +253,6 @@ void CScoreCellImage::Paint() case Kind::Steps: PaintSteps(); break; - case Kind::Place: - PaintPlace(); - break; case Kind::Empty: break; } @@ -222,13 +305,12 @@ void CScoreCellImage::PaintText() int yCenter = m_iY + m_iTall / 2; // Sprite scaled to the row height with its aspect ratio kept - wrect_t rc = {}; int iconWide = 0; int iconTall = 0; - if (m_Kind == Kind::Icon && m_iSprite != -1 && CHudRenderer::Get().IsAvailable()) + if (m_Kind == Kind::Icon && m_iSprite != -1) { - rc = gHUD.GetSpriteRect(m_iSprite); + const wrect_t &rc = gHUD.GetSpriteRect(m_iSprite); if (rc.GetWidth() > 0 && rc.GetHeight() > 0) { @@ -254,8 +336,7 @@ void CScoreCellImage::PaintText() if (iconWide > 0 && iconTall > 0) { - CHudRenderer::SpriteSet(gHUD.GetSprite(m_iSprite), m_Color.r(), m_Color.g(), m_Color.b()); - CHudRenderer::SpriteDrawAdditiveScaled(0, x, yCenter - iconTall / 2, iconWide, iconTall, &rc); + DrawScoreSprite(m_iSprite, x, yCenter - iconTall / 2, iconWide, iconTall, m_Color); x += iconSpace; } @@ -268,23 +349,31 @@ void CScoreCellImage::PaintText() void CScoreCellImage::PaintMeter() { vgui2::HFont font = m_Style.hFont; - wchar_t counter[32]; - V_snwprintf(counter, ARRAYSIZE(counter), L"%d/%d", m_iCur, m_iMax); + int maxDots = bhl::sb::MAX_DOTS; + bool bBar = m_iMax > maxDots; + + // Only the bar has a counter: dots are easy to count + wchar_t counter[32] = L""; + int counterSpace = 0; + + if (bBar) + { + V_snwprintf(counter, ARRAYSIZE(counter), L"%d/%d", m_iCur, m_iMax); + counterSpace = m_Style.iSpacing + GetTextWide(font, counter); + } - int counterWide = GetTextWide(font, counter); - int spacing = m_Style.iSpacing; int gap = m_Style.iDotGap; - int maxDots = bhl::sb::MAX_DOTS; - int dot = (m_iWide - counterWide - spacing - (maxDots - 1) * gap) / maxDots; + int dot = (m_iWide - counterSpace - (maxDots - 1) * gap) / maxDots; dot = std::min(std::min(dot, m_Style.iDotSize), m_iTall); // The bar has the length of a full row of dots int barWide = dot > 0 ? maxDots * dot + (maxDots - 1) * gap : 0; - int x = m_iX + GetAlignOffset(barWide + spacing + counterWide); + int contentWide = bBar ? barWide + counterSpace : std::max(m_iMax * (dot + gap) - gap, 0); + int x = m_iX + GetAlignOffset(contentWide); int y = m_iY + (m_iTall - dot) / 2; int cur = std::clamp(m_iCur, 0, m_iMax); - if (dot > 0 && m_iMax <= maxDots) + if (dot > 0 && !bBar) { for (int i = 0; i < m_iMax; i++) { @@ -300,7 +389,8 @@ void CScoreCellImage::PaintMeter() DrawRoundedBox(x, y, x + std::max(barWide * cur / m_iMax, dot), y + dot, dot / 2, m_Style.filledColor); } - DrawCellText(font, x + barWide + spacing, m_iY + (m_iTall - vgui2::surface()->GetFontTall(font)) / 2, m_Color, counter); + if (bBar) + DrawCellText(font, x + barWide + m_Style.iSpacing, m_iY + (m_iTall - vgui2::surface()->GetFontTall(font)) / 2, m_Color, counter); } void CScoreCellImage::PaintSteps() @@ -349,29 +439,6 @@ void CScoreCellImage::PaintSteps() } } -void CScoreCellImage::PaintPlace() -{ - vgui2::HFont font = m_Style.hFont; - wchar_t text[16]; - V_snwprintf(text, ARRAYSIZE(text), L"%d", m_iCur); - - int textWide = GetTextWide(font, text); - int textTall = vgui2::surface()->GetFontTall(font); - int textY = m_iY + (m_iTall - textTall) / 2; - - if (m_MarkColor.a() == 0) - { - DrawCellText(font, m_iX + GetAlignOffset(textWide), textY, m_Color, text); - return; - } - - int size = std::min(std::max(textWide, textTall) + m_Style.iSpacing, m_iTall); - int x = m_iX + GetAlignOffset(size); - int y = m_iY + (m_iTall - size) / 2; - DrawRoundedBox(x, y, x + size, y + size, size / 2, m_MarkColor); - DrawCellText(font, x + (size - textWide) / 2, textY, m_Color, text); -} - void DrawScoreBadge(const ScoreCellStyle &style, int x, int yCenter, const wchar_t *text) { int padding = GetBadgePadding(style); @@ -382,6 +449,30 @@ void DrawScoreBadge(const ScoreCellStyle &style, int x, int yCenter, const wchar DrawCellText(style.hBadgeFont, x + padding, y, style.badgeFgColor, text); } +int GetScoreBadgeWide(const ScoreCellStyle &style, const wchar_t *text) +{ + return GetTextWide(style.hBadgeFont, text) + 2 * GetBadgePadding(style); +} + +void DrawScoreSprite(int sprite, int x, int y, int wide, int tall, Color color) +{ + if (sprite < 0 || wide <= 0 || tall <= 0) + return; + + if (sprite >= static_cast(s_SpriteTextures.size())) + s_SpriteTextures.resize(sprite + 1, TEXTURE_NOT_CREATED); + + if (s_SpriteTextures[sprite] == TEXTURE_NOT_CREATED) + s_SpriteTextures[sprite] = CreateSpriteTexture(sprite); + + if (s_SpriteTextures[sprite] == TEXTURE_FAILED) + return; + + vgui2::surface()->DrawSetTexture(s_SpriteTextures[sprite]); + vgui2::surface()->DrawSetColor(color); + vgui2::surface()->DrawTexturedRect(x, y, x + wide, y + tall); +} + void DrawCellText(vgui2::HFont font, int x, int y, Color color, const wchar_t *text) { vgui2::surface()->DrawSetTextFont(font); @@ -411,16 +502,3 @@ void FormatScoreKills(wchar_t *buf, int bufSizeBytes, int kills) V_snwprintf(number, ARRAYSIZE(number), L"%d", kills); ConstructScoreText(buf, bufSizeBytes, token, 1, number); } - -void ScoreTextToUpper(wchar_t *text) -{ - for (; *text; text++) - { - wchar_t c = *text; - - if ((c >= L'a' && c <= L'z') || (c >= 0xE0 && c <= 0xFE && c != 0xF7) || (c >= 0x430 && c <= 0x44F)) - *text = c - 0x20; - else if (c >= 0x450 && c <= 0x45F) - *text = c - 0x50; - } -} diff --git a/src/game/client/vgui/score_panel_cells.h b/src/game/client/vgui/score_panel_cells.h index 7f6c10e0..ffbee88a 100644 --- a/src/game/client/vgui/score_panel_cells.h +++ b/src/game/client/vgui/score_panel_cells.h @@ -28,7 +28,7 @@ struct ScoreCellStyle }; /** - * Image of a custom scoreboard cell: text, icon, meter, steps or place. + * Image of a custom scoreboard cell: text, icon, meter or steps. * Draws within the bounds set by the row. An empty cell draws nothing. */ class CScoreCellImage : public vgui2::IImage @@ -41,14 +41,6 @@ class CScoreCellImage : public vgui2::IImage * Content setters clear the badge. */ void SetValue(bhl::sb::E_Display display, const CScoreboardData::Value &value); - void SetText(const wchar_t *text); - - /** - * Sets a place with a round mark behind it. - * @param place Place, 0 for an empty cell - * @param markColor Color of the mark, alpha 0 for no mark - */ - void SetPlace(int place, Color markColor); //! Sets the badge after the text, nullptr for none void SetBadge(const wchar_t *badge); @@ -72,7 +64,6 @@ class CScoreCellImage : public vgui2::IImage Icon, Meter, Steps, - Place, }; const ScoreCellStyle &m_Style; @@ -83,7 +74,6 @@ class CScoreCellImage : public vgui2::IImage int m_iSprite = -1; int m_iCur = 0, m_iMax = 0; Color m_Color = Color(255, 255, 255, 255); - Color m_MarkColor = Color(0, 0, 0, 0); wchar_t m_wszText[128] = {}; wchar_t m_wszBadge[32] = {}; @@ -92,7 +82,6 @@ class CScoreCellImage : public vgui2::IImage void PaintText(); void PaintMeter(); void PaintSteps(); - void PaintPlace(); }; /** @@ -100,6 +89,15 @@ class CScoreCellImage : public vgui2::IImage */ void DrawScoreBadge(const ScoreCellStyle &style, int x, int yCenter, const wchar_t *text); +int GetScoreBadgeWide(const ScoreCellStyle &style, const wchar_t *text); + +/** + * Draws a sprite of hud.txt stretched to wide x tall and tinted with color. + * Unlike CHudRenderer it draws a VGUI2 texture, so it works with every renderer. + * The sprite is drawn with alpha blending, its brightness is the alpha, like an additive sprite. + */ +void DrawScoreSprite(int sprite, int x, int y, int wide, int tall, Color color); + void DrawCellText(vgui2::HFont font, int x, int y, Color color, const wchar_t *text); /** @@ -113,9 +111,4 @@ void ConstructScoreText(wchar_t *buf, int bufSizeBytes, const char *token, int c */ void FormatScoreKills(wchar_t *buf, int bufSizeBytes, int kills); -/** - * Converts the string to uppercase, including Latin-1 and Cyrillic letters (towupper doesn't in the C locale). - */ -void ScoreTextToUpper(wchar_t *text); - #endif From 754ae9dc28e23de7fb400214b97b44160fd62f30 Mon Sep 17 00:00:00 2001 From: et-nik Date: Mon, 12 Oct 2026 21:36:48 +0200 Subject: [PATCH 11/19] fixes and updates --- docs/scoreboard-protocol-review.html | 271 ++ docs/scoreboard-protocol.md | 2043 +++++++++++---- .../amxmodx/scripting/include/bugfixedapi.inc | 295 ++- gamedir/ui/resource/ClientSchemeBase.res | 98 +- .../language/bugfixedhl_english.utf8.txt | 27 +- .../language/bugfixedhl_russian.utf8.txt | 27 +- gamedir/ui/scripts/HudLayoutBase.res | 51 +- src/bugfixedapi_amxx/bhl_api.h | 9 +- src/bugfixedapi_amxx/bugfixedapi_amxx.cpp | 299 ++- src/game/client/CMakeLists.txt | 6 +- src/game/client/hud.cpp | 18 +- src/game/client/hud.h | 5 +- src/game/client/hud/gungame_hud.cpp | 536 ---- src/game/client/hud/gungame_hud.h | 95 - src/game/client/hud/jumpspeed.cpp | 8 +- src/game/client/hud/scores.cpp | 16 +- src/game/client/hud/server_panel.cpp | 917 +++++++ src/game/client/hud/server_panel.h | 122 + src/game/client/hud/speedometer.cpp | 8 +- src/game/client/hud/statusbar.cpp | 6 - src/game/client/hud/timer.cpp | 11 +- src/game/client/scoreboard_data.cpp | 2233 ++++++++++++++--- src/game/client/scoreboard_data.h | 418 ++- src/game/client/scoreboard_template.cpp | 993 ++++++++ src/game/client/scoreboard_template.h | 283 +++ src/game/client/vgui/score_panel.cpp | 560 +++-- src/game/client/vgui/score_panel.h | 69 +- src/game/client/vgui/score_panel_cells.cpp | 213 +- src/game/client/vgui/score_panel_cells.h | 52 +- src/game/server/CBugfixedServer.cpp | 69 +- src/game/server/CBugfixedServer.h | 10 +- src/game/server/CScoreboardExt.cpp | 1134 +++++++-- src/game/server/CScoreboardExt.h | 132 +- src/game/shared/ClientSupportsFlags.h | 7 +- src/game/shared/IBugfixedServer.h | 16 +- src/game/shared/IScoreboardExt.h | 140 +- src/game/shared/ScoreboardProtocol.h | 377 ++- 37 files changed, 9340 insertions(+), 2234 deletions(-) create mode 100644 docs/scoreboard-protocol-review.html delete mode 100644 src/game/client/hud/gungame_hud.cpp delete mode 100644 src/game/client/hud/gungame_hud.h create mode 100644 src/game/client/hud/server_panel.cpp create mode 100644 src/game/client/hud/server_panel.h create mode 100644 src/game/client/scoreboard_template.cpp create mode 100644 src/game/client/scoreboard_template.h diff --git a/docs/scoreboard-protocol-review.html b/docs/scoreboard-protocol-review.html new file mode 100644 index 00000000..87b676df --- /dev/null +++ b/docs/scoreboard-protocol-review.html @@ -0,0 +1,271 @@ + + + + + + + Таблица счёта и HUD — разбор нового протокола + + + +
+
BugfixedHL · технический разбор12 октября 2026
+
+

Суть · сообщения · вопросы к проекту

+

Как сервер задаёт таблицу счёта и игровой интерфейс

+

Таблица результатов игроков — scoreboard. Текст, значки и индикаторы поверх игры — HUD. Правила обмена данными называются протоколом. Новый протокол позволяет серверу настраивать оба представления из одного набора значений.

+
Пока проектРазобран второй черновик документа — Draft 2, версия протокола 1. Далее описано предлагаемое поведение. Сравнение с предыдущим черновиком и замечания собраны в конце; готовность реализации здесь не подтверждается.
+ +
+
+
+
01

Данные общие, представлений два

+

Серверный модуль с правилами режима — плагин — задаёт значения и оформление. Игровая программа пользователя — клиент — хранит их и рисует интерфейс. Ей не нужно знать правила конкретного режима, например GunGame, где игрок проходит уровни оружия.

+
+
Плагин

Задаёт столбцы, уровни, оружие, тексты и видимость.

+
Сервер

Хранит состояние и отправляет изменения каждому клиенту.

+
Клиент

Обновляет таблицу и HUD из одного хранилища данных.

+
+
+
Владелец значения
Вся игра, игрок или команда. В сообщении это target.
+
Ячейка
Значение для одного владельца в одном столбце: например, уровень игрока.
+
Ключ
Короткое имя, например level. Плагин использует имена; сервер назначает числовые номера — id.
+
Элемент
Один объект HUD: строка, значок, индикатор или лента значков.
+
Шаблон и вариант
Текст с местами для подстановки данных — шаблон. Один из альтернативных текстов элемента — вариант.
+
Ссылка на значение
Имя, по которому клиент берёт ячейку или вычисленное значение для элемента.
+
+

Набор настроек таблицы и её столбцов называется схемой. Столбец может быть скрыт, но его данные всё равно доступны для сортировки и HUD.

+

Основание: документ, §2, §5.1, §8.1.

+
+
+
02

Что именно идёт по сети

+

Байт — единица данных из восьми двоичных разрядов, или битов. Один байт хранит число от 0 до 255. Набор битов-переключателей называется битовой маской. Ниже байты записаны в шестнадцатеричной системе: 0x03 означает число 3, 0xFF — 255.

+
+
Сообщение BhlScoreДо 192 байт, включая код операции
+
1 байт: что сделатьОстальные байты: данные операции
+

Это двоичный формат. Одно сообщение содержит одну операцию. Движок доставляет его надёжно одному клиенту через режим MSG_ONE. Ограничение 192 байта относится к содержимому BhlScore; служебные заголовки сети здесь не считаются.

+
+

Первый байт — код операции (op). Поле — отдельная часть сообщения. Тип поля определяет его размер и способ чтения:

+
+ + + + +
ТипРазмерСмысл
byte1 байтЦелое 0…255.
short / word2 байтаЦелое −32 768…32 767 / 0…65 535.
long4 байтаЦелое −2³¹…2³¹−1; в поле видимости те же 32 бита служат переключателями.
stringДлина текста + 1Текст в UTF-8 — кодировке с разным числом байтов на символ. Конец обозначает нулевой байт 00, называемый NUL.
+

В многобайтовом числе младший байт идёт первым — порядок little-endian: число 300 передаётся как 2C 01. Лимиты текста считаются в байтах без завершающего NUL, а не в буквах.

+

Выберите операцию. В записи ниже поле:тип указывает имя и тип, квадратные скобки — повторяющуюся группу.

+
+ +
+
+

Values · значения ячеек

до 192 байт
+

Передаёт одну или несколько групп ячеек. Каждая группа относится к игре, игроку или команде.

+
target — владелец значенияcount — число ячеекcolumn — номер столбцаtype — тип значенияlen — длина данныхpayload — данные значения
+
op:byte → [target:byte → count:byte → [column:byte → type:byte → len:byte → payload:len байт] × count] до конца сообщения
+

Новый тип можно пропустить по длине len. Для неизвестного типа ячейка очищается. Остальные ячейки сообщения продолжают читаться.

+
+
Какими бывают значения ячеек и элементов списка +

Каждое значение имеет обёртку type:byte → len:byte → payload. Длина len учитывает только данные после этих двух байтов. «Текущий / максимальный» далее сокращены до cur / max.

+
+ + + + + + +
Тип значенияКод / длина данныхДанные
Пусто — None0 / 0Очищает ячейку.
Число — Int1 / 1, 2 или 4Целое со знаком, включая однобайтовый вариант.
Текст — Text2 / 1…32Одна строка с NUL.
Значок — Icon3 / 2…64Имя готового изображения клиента — спрайта — и подпись: две строки с NUL. Само изображение не передаётся.
Прогресс — Progress4 / 2 или 4cur, затем max: два byte или два word.
Часы — Clock5 / 5ms:long — миллисекунды; flags:byte — настройки. Бит 0: идут; бит 1: обратный отсчёт. Клиент продолжает отсчёт сам.
+

target: 00 — игра; 01…40 — игроки 1–64; 81…C0 — команды 1–64. Столбец FF вместе с None очищает все ячейки владельца. Список — именованная последовательность значений всей игры; длинный список делится между сообщениями.

+
+
Все восемь форматов одной таблицей +

Поля перечислены в порядке передачи после op:byte. Набор битов-переключателей называется битовой маской; такую роль играют поля flags, visible и hide. Текст с местами для подстановки данных называется шаблоном.

+
+ + + + + + + + +
ОперацияПоля после кода операции
00 Resetversion:byte
01 Configflags:word → title:string → tag:string
02 Columnid:byte → display:byte → flags:word → width:byte → sort:byte → key:string → title:string → host:byte
03 Values[target:byte → count:byte → [column:byte → type:byte → len:byte → payload:len байт] × count] до конца
04 Listid:byte → total:byte → start:byte → key:string → [type:byte → len:byte → payload:len байт] до конца
05 Elementid:byte → kind:byte → flags:word → x:short → y:short → align:byte → place:byte → parent:byte → gap:byte → color:4 byte → font:byte → select:string → value:string → list:string → count:byte → [id:byte → value:short] × count. Для удаления: только id и kind = 0.
06 Templateid:byte → variant:byte → text:string
07 HudStatevisible:long → hide:word
+
+

Передача всего текущего состояния называется полной синхронизацией. После неё сервер отправляет только изменения.

+
Порядок отправки, ограничения и защита от ошибок +

Сначала сброс, затем определения и данные, в конце — тексты и видимость:

+
Reset→Config / Column→List→Values→Element→Template→HudState
+

После входа синхронизация начинается примерно через 0,5 с. Бюджет — около 512 байт на клиента за кадр, затем при его исчерпании пауза около 0,1 с. Далее отправляются изменения; несколько записей одной ячейки за кадр сворачиваются в последнее значение.

+

Лимиты: 32 столбца, 32 элемента, 8 списков по 64 значения, 8 вариантов текста на элемент, 16 подстановок на шаблон. Текст шаблона — до 188 байт: 1 + 1 + 1 + 188 + 1 = 192 с заголовком и NUL. Слишком длинный шаблон отклоняется целиком.

+

Неизвестные операции игнорируются. Неверный тип или повреждённые данные значения очищают ячейку. Если Values оборвалось, уже применённые ячейки сохраняются. У фиксированных операций можно добавлять поля в конец; Values и List расширяются новыми типами либо операциями.

+
+

Основание: документ, §4–5. Это форматы Draft 2.

+
+
+
03

Одна строка игрока — 28 байт

+

Пример из документа: игрок 5, уровень 12 из 24, оружие MP5, одно убийство из трёх. Номера столбцов: уровень — 1, оружие — 2, прогресс убийств — 3. Нажмите на блок байтов, чтобы разобрать его.

+
+
+

Сообщение Values

+
1 / 3
+ +
+ + + + + +
+

Столбец 3; тип 4 — пара «текущее / максимум»; длина данных 2 байта; текущее 1, максимум 3.

+

В документе указано 27 байт для группы: это верно. Вместе с кодом операции всё сообщение занимает 28 байт.

+
+
+
+

Условный вид · одни и те же данные

+
ИгрокУровеньОружиеУбийства
Игрок 512 / 24MP51 / 3
+

Индикатор HUD

+

Таблица упрощена для объяснения.

+
+

Если изменились только убийства, достаточно отправить одну ячейку — 8 байт:03 05 01 03 04 02 01 03

+

Текст и оформление HUD повторно передавать не нужно. Ползунок демонстрирует формат, а не переход на следующий уровень по правилам игры.

+
+
+

Основание: документ, §4.4.

+
+
+
04

Как данные превращаются в HUD

+

Элемент — один объект на экране. Сервер задаёт его вид, положение, цвет, размер текста и источник значения. Есть четыре вида:

+
+
Строка — Text

Место, отрыв, время или другой текст.

Индикатор — Meter

Прогресс точками или полосой.

Лента — Strip

Последовательность значков, например уровни оружия.

Значок — Icon

Изображение с необязательной подписью.

+
+
+
+

Текст пересчитывает клиент

+

Шаблон — текст с подстановками в фигурных скобках. Ссылка внутри скобок выбирает ячейку по ключу либо вычисляемое клиентом значение с @.

+

Например, @rival — имя ближайшего соперника впереди; @pass — сколько единиц счёта нужно для обгона. Здесь единица счёта соответствует одному убийству.

+
До обгона {@rival}: {@pass|# убийство|# убийства|# убийств}
+

Вертикальная черта | разделяет формы слова; # заменяется числом. Имя и число подставляются из данных.

+
3
+
До обгона Соперник: 3 убийства
+

Если обязательного значения нет, вся строка скрывается. Подстановка вида {key?} допускает отсутствие значения.

+
+
+

Чьи данные и чьи тексты

+

Игрок видит свои данные; наблюдатель — данные того, за кем следит. Поиск ячейки: игрок → его команда → вся игра, до первого найденного значения. Без наблюдаемого игрока доступны только общие ячейки.

+

Язык и видимость принадлежат смотрящему клиенту. Сервер может отправить русскому наблюдателю русский текст с данными другого игрока.

+

До восьми альтернативных текстов элемента называются вариантами. Поле select выбирает их по числу 0–7, например по фазе матча. Это не программный код: условия режима остаются в плагине.

+

Имя готового перевода — токен локализации, например #BHL_HUD_Place. Его перевод уже хранится у клиента. Плагин также может отправить собственный готовый текст на языке пользователя.

+
+
+
Положение и показ элементов +

Для положения относительно экрана координаты x / y передаются как доля размера экрана, умноженная на 8192. Специальное значение −8192 означает центр; y = 205 — примерно 2,5% высоты от верхнего края. Выравнивание выбирает, какую точку элемента привязать к позиции.

+

Можно размещать элемент у другого элемента, рядом с числами здоровья и боезапаса либо в верхней части таблицы. Элемент появляется только при разрешённой видимости, подходящем состоянии игры и наличии содержимого. Показ надписи в заголовке таблицы не зависит от настройки экранных элементов HUD.

+

Сервер может попросить скрыть таймер, строку следующей карты, дополнительные таймеры и нижние индикаторы скорости. Настройка пользователя, отключающая серверные элементы, отменяет эти запросы.

+
+
+

Совместимость: клиент выбирает возможности

+

Набор битов-переключателей — битовая маска возможностей — передаётся серверу под именем _bhl. Бит 0, ScoreboardV1, разрешает получать данные; бит 1, HudV1, сообщает, что клиент рисует элементы HUD. Ниже предполагается новый активный сервер с таблицей и HUD.

+
+
_bhl3

Данные приходят. Новая таблица и серверные элементы включены. Плагин отключает заменённые ими собственные надписи.

+

Управляющие настройки: hud_scoreboard_custom и hud_server_elements. Старый клиент не получает BhlScore; новый клиент на старом сервере сохраняет стандартный интерфейс. Бит HudV1 сам по себе не разрешает отправку: он имеет смысл только вместе со ScoreboardV1.

+
+

Основание: документ, §3, §8, §10–11.

+
+
+
05

Что важно закрыть до реализации

+

Архитектура разделяет правила режима, данные и отображение. Форматы основных сообщений определены. Ниже — вопросы к полноте спецификации, а не подтверждённые ошибки уже работающего Draft 2.

+
+

Что меняется относительно предыдущего черновика

+
+ + + + + +
ПровереноПредыдущий черновикВ проекте Draft 2
ОперацииТолько 0…4Дополнительно Element, Template, HudState
Столбцы и типы16 столбцов; нет часов и отметок после ячейки32; часы Clock и отметки Badge
Формат ConfigМежду flags и title есть имя готового оформления — presetПоле preset удалено
Возможность HUDСпециально для GunGame: GunGameHudV1Общая для режимов: HudV1
Интерфейс модуля и сервераНабор функций взаимодействия — API — версии 1.2Требуется API 1.3
+

Сборки двух черновиков нельзя смешивать: клиент, сервер, модуль и плагин должны обновляться вместе. Одинаковый номер протокола 1 не означает совместимость этих черновиков.

+

База сравнения — сохранённая ревизия кода 7a864400310b. В рабочей копии уже начат перенос общих объявлений на Draft 2. Ниже — файлы и строки базовой ревизии; ссылки открывают рабочие файлы: ScoreboardProtocol.h, строки 17, 43–68; CScoreboardExt.cpp, 537–546; ClientSupportsFlags.h, 20; IBugfixedServer.h, 10. Документ: §9.1, §11.

+
+
1

Восстановить данные после очистки клиентом

При переинициализации изображения — событии VidInit — клиент очищает хранилище. Но среди причин полной синхронизации этого события нет. Если сервер не выполняет повторную подготовку интерфейса и возможности не меняются, состояние нечем восстановить.

Уточнить: сохранять данные при таком событии либо явно описать запрос и гарантированный запуск повторной синхронизации.

Документ: §3.2, §5.3, §6.1; строки 99–103, 658–665, 705–707.

+
2

Безопасно заменить уже видимый элемент

Новое определение сохраняет прежние шаблоны на клиенте. Определение и новые тексты могут прийти в разных кадрах из-за лимита отправки. Если старый бит видимости включён, новое оформление может временно использовать старый текст.

Уточнить: сначала скрывать или удалять заменяемый элемент либо применять определение и тексты совместно, только после их получения.

Документ: §4.3 Element / HudState, §5.2; строки 471–474, 507–509, 641–654.

+
3

Определить время часов при поздней отправке

Клиент запускает часы от момента получения. Не описано, как сервер пересчитывает их значение после задержки или при подключении нового игрока. Для отсчёта, заданного минуту назад, нельзя просто повторить исходное число.

Уточнить: хранить время установки и перед отправкой вычислять актуальное значение, включая остановку обратного отсчёта на нуле.

Документ: §4.3 Clock, §5.1–5.3, §9.2; строки 367–371, 612–617, 658–665, 1518–1519.

+
Ещё один граничный случай: ссылка на собственное значение

Поле value допускает встроенные ссылки, а @value обозначает это же поле. Для value = @value и value = ^@value не задано завершение вычисления. Следует запретить такие привязки или считать цикл отсутствующим значением. Основание: §4.3, §8.10–8.11, §9.2.

+
Вывод ревью: протокол можно объяснить как «определения + значения + тексты + видимость». Перед реализацией нужно закрепить восстановление состояния, порядок замены элементов и поведение часов. Проверка в игре остаётся отдельным этапом.
+
+
+
+

Источник: docs/scoreboard-protocol.md, рабочая версия Draft 2 на 12.10.2026; сопоставлена с базовой ревизией кода 7a864400310b. Номера строк документа относятся к этой версии. Исходный документ не изменён.

+

Отчёт работает без сети. Примеры — иллюстрации формата, не подключение к игре и не реализация протокола. Воспроизведение записей игры, трансляции матчей и другие серверные реализации исключены из объёма проекта самим документом.

+
+ +
+ + + diff --git a/docs/scoreboard-protocol.md b/docs/scoreboard-protocol.md index 30a70583..db5331c8 100644 --- a/docs/scoreboard-protocol.md +++ b/docs/scoreboard-protocol.md @@ -1,17 +1,23 @@ -# Scoreboard extension protocol +# Scoreboard and HUD extension protocol -Protocol version 1. Implemented in the BugfixedHL client and server, in `bugfixedapi_amxx` and in the -GunGame plugin. +Status: Draft 2, not released. Protocol version 1. Covers the BugfixedHL client and server, +`bugfixedapi_amxx` and the GunGame plugin. -This document describes how a BugfixedHL server sends a custom scoreboard layout and extra values -for players, teams and the whole game to BugfixedHL clients, and how the GunGame scoreboard and -HUD widget use that data. The first consumer is the GunGame plugin. +This document describes how a BugfixedHL server sends to BugfixedHL clients a custom scoreboard +layout, extra values for players, teams and the whole game, and HUD elements defined by server +plugins. The client knows no game mode: a mode such as GunGame builds its scoreboard and HUD from +generic parts through plugin natives. The first consumer is the GunGame plugin (9.3). ## 1. Goals - A server plugin can add columns to the scoreboard, hide some standard columns, move the others and fill cells for players, teams and the whole game. -- HUD widgets read the same data. The first one is the GunGame HUD (8.4). +- A server plugin can put HUD elements anywhere on the screen: text lines, icons, meters and icon + strips. It chooses the position, alignment, color and font of each element, when it is shown, + and its texts. Texts show cell values and places computed by the client. +- Texts are client localization tokens or the plugin's own texts, sent to every player in his + language. +- The client contains no logic of a game mode. - Full backward compatibility in both directions: - old clients (older BugfixedHL, Valve, AG, OpenAG) on a new server see the standard scoreboard and HUD and never receive the new message; @@ -28,23 +34,31 @@ User messages carry strings, are reliable and can be sent to a single client. ## 2. Overview ``` -plugin (AMXX) ── natives ──▶ bugfixedapi_amxx ── IBugfixedServer ──▶ hl.so: scoreboard state +plugin (AMXX) ── natives ──▶ bugfixedapi_amxx ── IBugfixedServer ──▶ hl.so: scoreboard and HUD state │ "BhlScore" user message, MSG_ONE, only to clients with ScoreboardV1 ▼ - client.dll: scoreboard store ──▶ ScorePanel, hud_scores, - GunGame HUD widget + client.dll: store ──▶ ScorePanel, hud_scores, + HUD elements (HudServerPanel) ``` -| Term | Meaning | -|--------|----------------------------------------------------------------| -| Schema | `Config` plus the list of columns | -| Target | Owner of a value: the whole game, a player or a team | -| Cell | One value, addressed by target and column | -| List | A named array of values that belongs to the whole game | -| Preset | Client-side look and behaviour bound to a name, e.g. `gungame` | -| Caps | Bitmask of client features, reported by the client in `_bhl` | +The server keeps one state for everybody plus per-player overrides of texts and visibility, and +sends every client its own view of it. The client evaluates texts every frame from the store, for +the player it looks at. + +| Term | Meaning | +|----------|---------------------------------------------------------------------------| +| Schema | `Config` plus the list of columns | +| Target | Owner of a value: the whole game, a player or a team | +| Cell | One value, addressed by target and column | +| List | A named array of values that belongs to the whole game | +| Element | A HUD item defined by the server: `Text`, `Icon`, `Meter` or `Strip` | +| Template | Text of an element with placeholders, evaluated by the client (8.10) | +| Variant | One of up to 8 templates of an element, chosen by a value | +| Viewer | The client that draws the HUD | +| Subject | The player whose data an element shows: the viewer or the observed player | +| Caps | Bitmask of client features, reported by the client in `_bhl` | ## 3. Client capabilities @@ -53,19 +67,25 @@ plugin (AMXX) ── natives ──▶ bugfixedapi_amxx ── IBugfixedServer The client reports its features in the cvar and userinfo key `_bhl`. The value is a bitmask written as lowercase hex without a prefix, at most 8 digits: `1`, `3`, `1f`. -The server parses it with `strtoul(value, &end, 16)`. An empty value, trailing characters or more -than 8 digits mean `0`. Unknown bits are ignored. +The server accepts only 1–8 hex digits of either case, without a sign, spaces or `0x`, and parses +them with `strtoul(value, nullptr, 16)`. Any other value, an empty one included, means `0`. Unknown +bits are ignored. -| Bit | Mask | Name | Meaning | -|------|-------|----------------|----------------------------------------------------------| -| 0 | `0x1` | `ScoreboardV1` | Understands `BhlScore` protocol version 1 | -| 1 | `0x2` | `GunGameHudV1` | Draws the GunGame HUD widget; the plugin drops its texts | -| 2–31 | — | reserved | Clients send 0, servers ignore | +| Bit | Mask | Name | Meaning | +|------|-------|----------------|-----------------------------------------------------------------| +| 0 | `0x1` | `ScoreboardV1` | Understands `BhlScore` protocol version 1 and receives its data | +| 1 | `0x2` | `HudV1` | Draws HUD elements; the plugin drops its own HUD texts | +| 2–31 | — | reserved | Clients send 0, servers ignore | -`GunGameHudV1` is only set together with `ScoreboardV1`, because the widget reads the store. +`HudV1` is only set together with `ScoreboardV1`, because elements read the store. The server +doesn't look at `HudV1` when it sends: every client with `ScoreboardV1` gets the HUD data too. The +bit tells plugins which players need their own HUD texts. The server clears `HudV1` when +`ScoreboardV1` is not set or the client is a bot or an HLTV proxy, so a plugin never drops its texts +for a client that gets no data. `bhl_get_client_caps()` returns this normalized value. -Bits are never reused or redefined. An incompatible protocol change gets a new bit -(`ScoreboardV2`), and the server sends the new format only to clients that have that bit. +Bits are never reused or redefined after release. An incompatible protocol change gets a new bit +(`ScoreboardV2`), and the server sends the new format only to clients that have that bit. Before +release, bit 1 and `Config` changed meaning; draft 1 builds are not compatible (11). `_bhl` doesn't replace `aghl_supports`. The MOTD flags stay where they are. @@ -75,7 +95,7 @@ Bits are never reused or redefined. An incompatible protocol change gets a new b - No `FCVAR_ARCHIVE` or `FCVAR_BHL_ARCHIVE`: the value is computed, it must not be saved to configs. - No `FCVAR_PRIVILEGED`: the engine answers a cvar query for such cvars with `CVAR is privileged`, which would break the server fallback from 3.3. -- The cvar is registered with the caps of the build as its default value, so the key is in +- The cvar is registered with the caps of the build as its default value (`3`), so the key is in userinfo from the first connect. - One owner function, `CHud::UpdateCapsUserinfo()`, computes the caps from the build features and client settings and writes `_bhl`. It runs: @@ -90,9 +110,24 @@ Bits are never reused or redefined. An incompatible protocol change gets a new b - if the key is still wrong on the next check, it prints one console message (most likely the userinfo is full). The server can still detect the client with the cvar query from 3.3. - Client settings: - - `hud_scoreboard_custom 0` clears `ScoreboardV1` and `GunGameHudV1`. The server stops sending - data, the client shows the standard scoreboard. Setting it back to 1 brings a full sync. - - `hud_gungame 0` clears `GunGameHudV1`. The plugin shows its own HUD texts again. + + | Cvar | Default | Flags | Meaning | + |-------------------------|---------|---------------------|------------------------------------------------------| + | `hud_scoreboard_custom` | 1 | `FCVAR_ARCHIVE` | Show the custom scoreboard when the server sends one | + | `hud_server_elements` | 1 | `FCVAR_BHL_ARCHIVE` | Draw HUD elements defined by the server | + + - `ScoreboardV1` is set while either cvar is 1, `HudV1` while `hud_server_elements` is 1. + - `hud_scoreboard_custom 0` alone: the client still receives the data and draws elements, and + shows the standard scoreboard. + - `hud_server_elements 0` alone: `HudV1` is cleared. The client draws no screen elements (the + banner rows stay, 6.8) and ignores requests to hide standard HUD parts (8.12). The plugin shows + its own HUD texts again. Nothing is sent again. + - Both 0: both bits are cleared and the server stops sending. When the client clears + `ScoreboardV1` in `_bhl`, it clears its store as on `Reset`. Setting either cvar back to 1 + brings a full sync. + - While `ScoreboardV1` is cleared, the client ignores `BhlScore`. After it sets the bit again, it + ignores every message except `Reset` until a `Reset` or `VidInit`, so changes meant for the old + store are never applied to the empty one. ### 3.3 Server side @@ -108,15 +143,20 @@ For every client the server keeps `caps` and the source they came from: 1. `ClientConnect` and `ClientUserInfoChanged` read `_bhl` from userinfo. If the key is present, it is parsed and the source becomes `Userinfo`. Userinfo always wins: a query answer that arrives later doesn't overwrite it. If the key disappears from userinfo, the source goes back - to `Unknown`. -2. In `InitHUD`, if the source is `Unknown` and either a schema is active or `sv_bhl_query_vars` - is 1, the server calls `QueryClientCvarValue2(_bhl)` with a new `REQUESTID_CAPS`. It applies the - same p47 and LAN checks as the existing `aghl_*` queries. If a schema becomes active later on the - map, clients that are still `Unknown` are queried at that moment. + to `Unknown` and the caps stay as they are until the query of step 2 gives new ones; a client + past `InitHUD` is queried at once. +2. In `InitHUD`, if the source is `Unknown` and either the extension is active (5.1) or + `sv_bhl_query_vars` is 1, the server calls `QueryClientCvarValue2(_bhl)` with a new + `REQUESTID_CAPS`. It applies the same p47 and LAN checks as the existing `aghl_*` queries and + waits while the SteamID is pending. If the extension becomes active later on the map, clients + that are still `Unknown` are queried at that moment. + While the source is `Query` and the extension is active, the server queries `_bhl` again every + 10 s, so a changed client setting reaches it. 3. An answer that doesn't parse (`Bad CVAR request`, `CVAR is privileged`, empty) means `0`. 4. Every change of `caps` fires the plugin forward `bhl_client_caps_changed(id)`. - `ScoreboardV1` appeared after `InitHUD`: the client gets a full sync (5.3). - `ScoreboardV1` disappeared: the server stops sending to that client and doesn't send `Reset`. + - Only `HudV1` changed: nothing is sent; the forward lets the plugin switch its own HUD texts. Each layer covers a different case: @@ -128,6 +168,12 @@ Each layer covers a different case: The server command `bhl_caps` prints slot, name, caps and source for every connected client. +Known limitation: with the source `Query` the server sees a changed setting only with the next +answer, up to 10 s later. A client that switches both cvars off and back on between two answers +clears its store and waits for a `Reset` (3.2), but the server never saw `ScoreboardV1` disappear +and sends only changes. The client shows the standard scoreboard and no elements until the next +map or a reconnect. + ## 4. Message `BhlScore` ### 4.1 Transport @@ -138,11 +184,14 @@ The server command `bhl_caps` prints slot, name, caps and source for every conne `MSG_ONE_UNRELIABLE`, and never to bots or HLTV proxies. - Old clients never receive it, so it doesn't matter how their engine handles unknown messages. - An old server never registers it, so the client hook never fires. + - Every message is built for one client, so per-player texts and visibility cost no extra + format: the server sends each client its own values. - One message carries one operation. The first byte is the opcode, the rest is its payload. The client ignores messages with unknown opcodes, which lets new opcodes be added safely. -- `Reset`, `Config` and `Column` are read field by field, and trailing bytes after the known fields - are ignored. Later versions may append fields to them. `Values` and `List` have no room for - trailing fields and are extended through new value types. +- `Reset`, `Config`, `Column`, `Element`, `Template` and `HudState` are read field by field, and + trailing bytes after the known fields are ignored. Later versions may append fields to them. + `Values` and `List` have no room for trailing fields and are extended through new value types or + new opcodes. ### 4.2 Data types @@ -151,7 +200,6 @@ All integers are little-endian, as written by `WRITE_*` and read by `READ_*`. | Type | Bytes | Write / read | Range | |----------|-------|--------------------------------|-----------------------| | `byte` | 1 | `WRITE_BYTE` / `READ_BYTE` | 0 … 255 | -| `char` | 1 | `WRITE_CHAR` / `READ_CHAR` | −128 … 127 | | `short` | 2 | `WRITE_SHORT` / `READ_SHORT` | −32768 … 32767 | | `word` | 2 | `WRITE_SHORT` / `READ_WORD` | 0 … 65535 | | `long` | 4 | `WRITE_LONG` / `READ_LONG` | −2³¹ … 2³¹−1 | @@ -159,24 +207,33 @@ All integers are little-endian, as written by `WRITE_*` and read by `READ_*`. Strings: -- A string starting with `#` is a localization token resolved by VGUI2 on the client. If the token - is missing, the client shows the string without the leading `#`. -- Plugins can only use tokens shipped with the client in `ui/resource/language/bugfixedhl_*.txt`. - The client adds generic tokens for common columns, see section 10. -- Color codes (`^1` … `^9`) are not interpreted in version 1. The client strips them. -- The server truncates strings to the limits from 4.6. The client truncates them again - if they are still too long. +- A client token is `#` followed by `[A-Za-z_][A-Za-z0-9_]*`. A Column title, the Config title and + tag, and the text of a `Text` or `Icon` value (in cells and list items) that is exactly a token + is resolved by VGUI2 on the client. If the token is missing, the client shows it without the + leading `#`. Any other string is shown as it is: `#1` stays `#1`. Templates follow 8.10. +- Plugins can only use tokens shipped with the client in + `ui/resource/language/bugfixedhl_*.utf8.txt`. The client ships generic tokens for columns and HUD + texts, see section 10. +- Color codes (`^` and a digit) are not interpreted in version 1. The client strips them from every + string except `select`, `value` and `list` of an `Element` and the text of a `Template`, where `^` + starts a ref (8.10); the template parser drops them from literals and word forms. +- The server truncates strings to the limits from 4.7 on a UTF-8 character boundary; templates are + never cut (9.2). The client truncates strings again if they are still too long, on a UTF-8 + character boundary. ### 4.3 Opcodes -| Op | Name | Payload | -|--------|----------|---------------------------------------------| -| `0x00` | `Reset` | Protocol version | -| `0x01` | `Config` | Hidden standard columns, preset, title, tag | -| `0x02` | `Column` | One column definition | -| `0x03` | `Values` | Cells for one or more targets | -| `0x04` | `List` | Items of one list | -| other | reserved | Ignored by the client | +| Op | Name | Payload | +|--------|------------|------------------------------------------------| +| `0x00` | `Reset` | Protocol version | +| `0x01` | `Config` | Hidden standard columns, title, tag | +| `0x02` | `Column` | One column definition | +| `0x03` | `Values` | Cells for one or more targets | +| `0x04` | `List` | Items of one list | +| `0x05` | `Element` | One HUD element definition, or a removal | +| `0x06` | `Template` | One template variant of an element | +| `0x07` | `HudState` | Visible elements and hidden standard HUD parts | +| other | reserved | Ignored by the client | #### `Reset` (`0x00`) @@ -184,18 +241,18 @@ Strings: |-----------|--------|-----------------------| | `version` | `byte` | Protocol version, `1` | -The client drops the schema, all cells and all lists and returns to the standard scoreboard. -`version` is informational: the client reads the fields it knows. A version 1 client accepts any -`version ≥ 1` and ignores a `Reset` with `version 0`. +The client drops the schema, all cells, lists, elements and templates, sets the HUD state to "no +element visible, no standard part hidden" and returns to the standard scoreboard. `version` is +informational: the client reads the fields it knows. A version 1 client accepts any `version ≥ 1` +and ignores a `Reset` with `version 0`. #### `Config` (`0x01`) -| Field | Type | Notes | -|----------|----------|------------------------------------------------------| -| `flags` | `word` | See below | -| `preset` | `string` | Up to 15 bytes; `""` means the generic look | -| `title` | `string` | Up to 63 bytes; replaces the server name if not `""` | -| `tag` | `string` | Up to 15 bytes; a badge after the server name: `FFA` | +| Field | Type | Notes | +|---------|----------|------------------------------------------------------| +| `flags` | `word` | See below | +| `title` | `string` | Up to 63 bytes; replaces the server name if not `""` | +| `tag` | `string` | Up to 15 bytes; a badge after the server name: `FFA` | | Bit | Name | Meaning | |------|---------------|-------------------------| @@ -209,40 +266,46 @@ The server can't hide Avatar, Name and Ping. Avatars follow the player's `hud_scoreboard_showavatars`. The first `Config` after a `Reset` (or after `VidInit`) turns the custom scoreboard on. -A repeated `Config` replaces the previous one. - -`preset` selects client-side look and behaviour, see 6.7. An unknown preset falls back to the -generic look. +A repeated `Config` replaces the previous one. HUD elements don't need a `Config`: a plugin that +only wants HUD elements leaves the standard scoreboard in place. A `Config` without a whole `flags` +is ignored; a missing `title` or `tag` is `""`. #### `Column` (`0x02`) | Field | Type | Notes | |-----------|----------|----------------------------------------------------------------------------------| -| `id` | `byte` | 0–15 | +| `id` | `byte` | 0–31 | | `display` | `byte` | How cells are drawn, see below | | `flags` | `word` | See below | | `width` | `byte` | Proportional units as in `ScorePanel.res`; `0` is the default | | `sort` | `byte` | `0`: not a sort key; bits 0–6: priority, 1 first; bit 7: ascending | | `key` | `string` | Up to 15 bytes of `[a-z0-9_]`, unique: `level`, `weapon` | | `title` | `string` | Up to 31 bytes, text or `#token`; `""` for a built-in column keeps its own title | +| `host` | `byte` | `Badge` only: id of the column the badge follows; `0xFF` otherwise or if unknown | A `Column` with an existing `id` replaces that column's definition; its cells are kept. Columns are shown in ascending `id` order. The server assigns ids, plugins address columns -by `key`. Presets and HUD widgets use `key` to find data by meaning without depending on ids. +by `key`. Templates and elements also refer to columns by `key` (8.10), so they don't depend on ids. +The server keeps `host` as a key and resolves it when it builds the message (5.1). + +The client ignores a `Column` with an `id` of 32 or more, and one that ends before `key` or whose +`key` has no NUL. A missing `title` is `""`, a missing `host` is `0xFF`. `Builtin` and `Badge` +columns are never sort keys; keys with the same priority are ordered by `id`. Display kinds: -| Value | Name | Draws | -|-------|-----------|----------------------------------------------------------------------------------| -| 0 | `Text` | Any cell as text | -| 1 | `Icon` | `Icon` cells as sprite and text; other cells as text | -| 2 | `Meter` | `Progress` cells as dots or a bar with a `cur/max` counter (6.6); others as text | -| 3 | `Builtin` | A standard column, chosen by `key`; cells are ignored | -| 4 | `Steps` | `Progress` cells as `cur/max` with a strip of `max` steps below (6.6) | -| other | — | Same as `Text` | +| Value | Name | Draws | +|-------|-----------|------------------------------------------------------------------------------------| +| 0 | `Text` | Any cell as text | +| 1 | `Icon` | `Icon` cells as sprite and text; other cells as text | +| 2 | `Meter` | `Progress` cells as dots or a bar with a `cur/max` counter (6.6); others as text | +| 3 | `Builtin` | A standard column, chosen by `key`; cells are ignored | +| 4 | `Steps` | `Progress` cells as `cur/max` with a strip of `max` steps below (6.6) | +| 5 | `Badge` | Not a column of its own: cells are drawn as badges after the cells of `host` (6.7) | +| other | — | Same as `Text` | Default widths for `width = 0`: `Text` 60, `Icon` 100, `Meter` 90, `Steps` 60. A `Builtin` column -keeps the width of its standard column. +keeps the width of its standard column. A `Badge` column takes no width. Built-in columns: @@ -254,21 +317,26 @@ Built-in columns: | `eff` | Eff | Also follows `hud_scoreboard_showeff` | | `steamid` | SteamID | Also follows `hud_scoreboard_showsteamid` | | `ping` | Ping | | -| other | — | The column is ignored | +| other | — | The client ignores the column; the server accepts it | A `Builtin` column moves a standard column to its own position. Standard columns that the schema -doesn't mention keep their default places. `Hide*` flags win over a `Builtin` column. +doesn't mention keep their default places. `Hide*` flags win over a `Builtin` column. The client +ignores a `Hidden` `Builtin` column: the standard column keeps its default place, and a hidden +`rank` gives no place column. Column flags: -| Bits | Name | Meaning | -|------|-----------|-------------------------------------------------------------| -| 0 | `Hidden` | Data only: not drawn, still used for sorting and by widgets | -| 1–2 | `Align` | 0 left, 1 center, 2 right; 3 is treated as left | -| 3 | `Primary` | The main score: `hud_scores` shows it instead of frags | -| 4–15 | reserved | Sent as 0, ignored | +| Bits | Name | Meaning | +|------|------------|--------------------------------------------------------------| +| 0 | `Hidden` | Data only: not drawn, still used for sorting and by elements | +| 1–2 | `Align` | 0 left, 1 center, 2 right; 3 is treated as left | +| 3 | `Primary` | The main score: `hud_scores` shows it instead of frags | +| 4 | `MarkLast` | `Steps`: the last step has its own color (6.6) | +| 5–15 | reserved | Sent as 0, ignored | -A `Hidden` column can carry values for the whole game only, for example the GunGame phase. +A `Hidden` column can carry values for the whole game only, for example a game phase. The server +sends `sort = 0` and clears `Primary` for a `Badge` column. `Hidden` on a `Badge` column hides its +badges. #### `Values` (`0x03`) @@ -306,6 +374,7 @@ Value types: | 2 | `Text` | 1–32 | `string` | | 3 | `Icon` | 2–64 | `string sprite`, `string text` | | 4 | `Progress` | 2 or 4 | `cur`, `max`: two `byte` for `len` 2, two `word` for 4 | +| 5 | `Clock` | 5 | `long ms`, `byte flags`: bit 0 runs, bit 1 counts down | | other | — | any | Unknown type: the cell is cleared | - A known type with a wrong `len` or a broken payload clears the cell. @@ -313,11 +382,17 @@ Value types: already applied and drops the rest. - Cells of columns that don't exist yet are stored and shown when the column arrives. - `Icon.sprite` is a sprite name from `hud.txt`, the same names the kill feed uses (`d_9mmAR`). - If the client doesn't have the sprite, it draws only `text`. + If the client doesn't have the sprite, it draws only `text`. For standard HL weapon sprites the + client shows its own weapon name instead of `text` (10.3). - `Progress` with `max = 0` is drawn as `cur`. +- `Clock` is a time the client runs itself, for timers that change every frame. On arrival the + client stores its own time `t0`. A stopped clock is `ms`; a running one is `ms + (now − t0)`, or + `ms − (now − t0)` when it counts down, and stops at 0. Its number is the current value in whole + seconds, rounded up when it has the "counts down" flag (running or stopped) and down otherwise; + `time2` (8.10) shows the milliseconds. -Sort keys: `Int` uses the value, `Progress` uses `cur`, `Text` and `Icon` compare text -case-insensitively. Empty cells go after filled ones. +Sort keys: `Int` uses the value, `Progress` uses `cur`, `Clock` its number, `Text` and `Icon` +compare text case-insensitively. Empty cells go after filled ones. #### `List` (`0x04`) @@ -341,6 +416,125 @@ List := op:byte(0x04) id:byte total:byte start:byte key:string Value* - `total = 0` removes the list. - Items added by a resize are always sent, as `None` if they were not set. +#### `Element` (`0x05`) + +``` +Element := op:byte(0x05) id:byte kind:byte + flags:word x:short y:short align:byte place:byte parent:byte gap:byte + color:byte{4} font:byte select:string value:string list:string + count:byte Param{count} +Param := id:byte value:short +``` + +| Field | Type | Notes | +|----------|----------------|--------------------------------------------------------------------------------------------------------| +| `id` | `byte` | 0–31, assigned by the server. `0xFF` with kind `None` removes every element | +| `kind` | `byte` | 0 `None` (remove), 1 `Text`, 2 `Meter`, 3 `Strip`, 4 `Icon`; other values remove the element | +| `flags` | `word` | See below | +| `x` | `short` | Horizontal position in 1/8192 of the screen width; `-8192` (−1.0) is the center (8.4) | +| `y` | `short` | Vertical position, the same way | +| `align` | `byte` | Anchors: bits 0–1 horizontal, bits 2–3 vertical, see below | +| `place` | `byte` | What the position is relative to, see below | +| `parent` | `byte` | Element id for the parent places; `0xFF` otherwise or if the parent doesn't exist | +| `gap` | `byte` | Proportional units: distance to the parent, or the margin on the numbers row (8.4) | +| `color` | `byte` × 4 | r, g, b, a. With `HudColor` only `a` is used | +| `font` | `byte` | Font id (8.5); unknown ids mean 0 | +| `select` | `string` | `Text`: a ref whose number picks the variant (8.10); `""` means variant 0 | +| `value` | `string` | The bound ref: `{@value}`, the progress of a `Meter`, the icon of an `Icon`, the position of a `Strip` | +| `list` | `string` | `Strip`: key of the list with the icons; `""` otherwise | +| `count` | `byte` | Number of params, 0–16 | +| `Param` | `byte` `short` | Kind param id and value (8.7–8.9); unknown ids and params of other kinds are ignored, values clamped | + +- hl.so converts a screen fraction `f` from the plugin to `(int)floor(f · 8192 + 0.5)`, clamped to + −32768…32767. `x = −8192` exactly is the center. This is the fixed point of `TE_TEXTMESSAGE`, + which `set_hudmessage` also uses, but rounded instead of truncated: 0.025 is 205, not 204. +- A ref in `select` and `value` is a column key or a built-in value such as `@state` (8.11), + optionally with the prefix `^` and one of the formats `cur`, `max` and `left` (8.10): + `level:left`. The longest valid ref has 21 bytes: `^`, a key of 15 bytes and `:left`. With a + format the value is an `Int`: a `Meter` or an `Icon` bound to it has no content, a `Strip` uses + it as the position. `list` is a list key. +- The server keeps `parent` as a key and resolves it when it builds the message (5.1). +- With kind `None` the message ends after `kind`. + +Anchors: + +| Bits | Anchor | 0 | 1 | 2 | 3 | +|------|------------|------|------|--------|--------| +| 0–1 | Horizontal | auto | left | center | right | +| 2–3 | Vertical | auto | top | middle | bottom | + +Places: + +| Value | Name | Position | +|-------|----------------|-------------------------------------------------------------------------| +| 0 | `Screen` | `x`, `y` and the anchors | +| 1 | `Parent` | Below or above element `parent`; `x` and the horizontal anchor as usual | +| 2 | `NumbersRow` | On the row of the HL health, armor and ammo numbers; `x` as usual | +| 3 | `BannerTop` | Scoreboard banner, on the server name row (6.8) | +| 4 | `BannerBottom` | Scoreboard banner, on the map name row (6.8) | +| 5 | `ParentLeft` | Left of element `parent`, centered vertically on it | +| 6 | `ParentRight` | Right of element `parent`, centered vertically on it | +| other | — | Same as `Screen` | + +`Parent`, `ParentLeft` and `ParentRight` are the parent places (8.4). + +Flags: + +| Bit | Name | Meaning | +|------|----------------|--------------------------------------------------------------------------------------| +| 0 | `HudColor` | rgb follows `hud_color`; on a banner row, the scheme color of the row (6.8) | +| 1 | `Subject` | Needs a subject (8.2): hidden when there is none | +| 2 | `NoScoreboard` | Hidden while the scoreboard is open | +| 3 | `Leader` | The subject is the first row of the scoreboard order instead of the viewer's subject | +| 4–15 | reserved | Sent as 0, ignored | + +- The client ignores an `Element` with an id of 32 or more (except `0xFF` with `None`), and one + that ends before `font`. A missing string, or one without a NUL, means `""`. Params are read + while bytes remain, at most `count` and at most 16; missing params take their defaults. +- A definition for an existing id replaces it. An `Element` never changes templates: the client + drops the templates of an id only on a removal (kind `None` or an unknown kind, for that id or + `0xFF`) and on `Reset`. When the server drops the texts of an element, it sends all its + variants again (5.2). +- The largest message is a `Strip`, the kind with the most params: 18 fixed bytes, strings of 22, + 22 and 16 bytes and 1 + 11 × 3 bytes of params, 112 bytes. + +#### `Template` (`0x06`) + +``` +Template := op:byte(0x06) id:byte variant:byte text:string +``` + +| Field | Type | Notes | +|-----------|----------|------------------------------------------------------------| +| `id` | `byte` | Element id | +| `variant` | `byte` | 0–7 | +| `text` | `string` | Template (8.10), up to 188 bytes; `""` removes the variant | + +- The client ignores a `Template` for an undefined element, a variant of 8 or more, and a text + without a NUL. The server always sends `Element` first. +- The server sends the text the plugin set for this player, or the default text (5.4). The client + doesn't know which one it got. +- The largest message is 192 bytes. + +#### `HudState` (`0x07`) + +``` +HudState := op:byte(0x07) visible:long hide:word +``` + +| Field | Type | Notes | +|-----------|--------|--------------------------------------------------------| +| `visible` | `long` | Bit per element id: the plugin shows the element (8.3) | +| `hide` | `word` | Standard HUD parts to hide (8.12) | + +The message is absolute: it replaces the previous state. After `Reset` and `VidInit` both fields +are 0. The server sends `HudState` after element definitions and templates (5.2), so elements +never appear before their texts. + +- `visible` is an unsigned 32-bit mask. Bits of undefined ids are stored and apply when the + element arrives. +- A `HudState` shorter than 5 bytes is ignored; a missing `hide` means 0. + ### 4.4 Example: one GunGame row Player 5 is on level 12 of 24 with the MP5 and has 1 of 3 kills. Column ids: `level` 1, @@ -359,39 +553,78 @@ The group takes 27 bytes. With the `kills` and hidden `score` cells (8–10 more takes 35–37 bytes, so one message holds 5 players and a full sync of 32 players needs 7 `Values` messages. -### 4.5 Sizes for GunGame +### 4.5 Example: one element -| Message | Bytes | -|----------------------------|-----------| -| `Reset` | 2 | -| `Config` | ~17 | -| `Column` × 8 | ~13–33 | -| `List` `levels`, 24 levels | 2 × ≤ 192 | -| `Values`, 32 players | 7 × ≤ 192 | -| Level-up of one player | ~33 | -| Kill without level-up | ~18 | -| Warmup second | ~8 | -| Warmup start or end | ~130 | +The place line of GunGame: a `Text` element at the top center, large font, `hud_color`. Its +variant is chosen by the `phase` cell, and `{@value}` in its templates is the `phase_left` cell. + +``` +05 op Element +00 01 id 0, kind Text +07 00 flags: HudColor, Subject, NoScoreboard +00 e0 x = -8192: center +cd 00 y = 205: 0.025 · 8192 = 204.8, rounded +00 00 align: auto anchors; place: Screen +ff 00 no parent, gap 0 +00 00 00 ff color: rgb ignored (HudColor), alpha 255 +01 font: HudServerLarge +70 68 61 73 65 00 select "phase" +70 68 61 73 65 5f 6c 65 66 74 00 value "phase_left" +00 list "" +00 no params +``` + +The message takes 37 bytes. Variant 0 with a client token takes 18: + +``` +06 00 00 op Template, element 0, variant 0 +23 42 48 4c 5f 48 55 44 5f 50 6c 61 63 65 00 "#BHL_HUD_Place" +``` + +### 4.6 Sizes for GunGame + +| Message | Bytes | +|-----------------------------------------|-------------------------------| +| `Reset` | 2 | +| `Config` | ~8 | +| `Column` × 9 | ~14–34 | +| `List` `levels`, 24 levels | 2 × ≤ 192 | +| `Values`, 32 players | 7 × ≤ 192 | +| `Element` × 6 | 28–37, 192 in all | +| `Template` × 9, plugin texts in Russian | 18–115, ~500 in all | +| `HudState` | 7 | +| Level-up of one player | ~33, +17 when `final` changes | +| Kill without level-up | ~18 | +| Warmup second | ~8 | +| Warmup start or end | ~140 | At the start and the end of the warmup the GunGame plugin sends the `level`, `weapon`, `progress`, -`kills` and `score` columns again (8.1). - -### 4.6 Limits - -| What | Limit | -|------------------------|---------------| -| Message payload | 192 bytes | -| Columns | 16 (ids 0–15) | -| Lists | 8 (ids 0–7) | -| List items | 64 | -| Column and list `key` | 15 bytes | -| Column title | 31 bytes | -| Preset name | 15 bytes | -| Config title | 63 bytes | -| Config tag | 15 bytes | -| `Text` value | 31 bytes | -| `Icon` sprite and text | 31 bytes each | -| Dots | `max ≤ 10` | +`kills` and `score` columns again and changes the visible elements (9.3). The banner needs no +traffic until the win: its rows are chosen by the leader's `level` cell (9.3). + +### 4.7 Limits + +| What | Limit | +|------------------------------|-------------------------| +| Message payload | 192 bytes | +| Columns | 32 (ids 0–31) | +| Lists | 8 (ids 0–7) | +| List items | 64 | +| Column and list `key` | 15 bytes | +| Column title | 31 bytes | +| Config title | 63 bytes | +| Config tag | 15 bytes | +| `Text` value | 31 bytes | +| `Icon` sprite and text | 31 bytes each | +| Dots in a scoreboard `Meter` | `max ≤ 10` | +| Elements | 32 (ids 0–31) | +| Element key (server only) | 15 bytes of `[a-z0-9_]` | +| Ref in `select` and `value` | 21 bytes (4.3) | +| Params per element | 16 | +| Variants per element | 8 | +| Template | 188 bytes | +| Placeholders per template | 16 | +| Evaluated text | 255 UTF-16 units | String limits are in bytes, without the terminating NUL. @@ -399,70 +632,117 @@ String limits are in bytes, without the terminating NUL. ### 5.1 State -One object in `hl.so`, `CScoreboardExt`, holds the config, the columns, the lists and -the cells of the whole game, every player and every team. For each client it also keeps `caps`, -their source, a `ready` flag (set after `InitHUD`), pending `Reset` and header flags and sets of -dirty cells and list items. +One object in `hl.so`, `CScoreboardExt`, holds the config, the columns, the lists, the cells of +the whole game, every player and every team, the HUD elements with their default templates and +visibility, the hidden standard HUD parts, and the per-player overrides of templates and +visibility (5.4). For each client it also keeps `caps`, their source, a `ready` flag (set after +`InitHUD`), pending `Reset`, header, elements, templates and HUD state, and sets of dirty cells +and list items. + +- Column masks have 32 bits, one per column id. The mask of all columns is built without + `1u << 32`, which is undefined in C++. +- Element parents and badge hosts are stored as keys and resolved to ids when a message is built, + `0xFF` when the key doesn't exist. Adding, removing or re-adding an element or a column marks + pending every element or badge column that names it. + +The extension is active from the first `Config`, element or hidden standard part until the plugin +resets it or the map changes. While it is inactive, a client gets only `Reset`. + +All plugins share this one state. Columns, lists and elements of different plugins live side by +side when their keys differ, so a plugin prefixes its keys (`gg_`). `bhl_sb_reset()` clears the +whole state, of every plugin. ### 5.2 Sending -Plugins only change the state and mark the changed cells and list items dirty for every ready -client. In `StartFrame` the server walks the ready clients that have `ScoreboardV1` and sends: +Plugins only change the state and mark the changes pending for every ready client. In +`StartFrame` the server walks the ready clients that have `ScoreboardV1` and sends: 1. `Reset`, if one is pending; 2. `Config`, if it is pending, and every pending `Column`; 3. the dirty list items packed into `List` messages; -4. the dirty cells packed into `Values` messages. +4. the dirty cells packed into `Values` messages; +5. every pending `Element`: definitions and removals; +6. every pending `Template`, with the text for this client; +7. `HudState`, if it is pending, with the visibility for this client. A client gets at most about 512 bytes per frame. When its budget is used up, nothing more is sent to it for about 0.1 s. A client with nothing pending gets small updates every frame. Several -changes of one cell in one frame produce one value. +changes of one cell, element, template or visibility in one frame produce one message. A setter +that writes the value already stored marks nothing, but a write for player 0 still drops the +overrides (5.4). + +Whenever the server drops the texts of an element (removal, kind change, an id given to another +key), it marks all 8 variants of that id pending for every client. A variant without a text is sent +as `""`, and only to a client that holds that variant. Templates of an id that has no element are +not sent. So a removal and a new element with the same id in one frame, or during the 0.1 s pause, +never leave old variants on the client. A removal goes only to a client that has the element, and +`HudState` only to a client whose visibility or hidden parts differ from what it has. ### 5.3 Full sync -A full sync is `Reset`, the header, every list item and every non-empty cell marked dirty for -that client. It starts: +A full sync is `Reset`, the header, every list item, every non-empty cell, every element, every +template this client should have and `HudState`, marked pending for that client. It starts: -- about 0.5 s after `InitHUD` of a client with `ScoreboardV1` (without a schema only `Reset` is - sent); +- about 0.5 s after `InitHUD` of a client with `ScoreboardV1` (while the extension is inactive + only `Reset` is sent); - when `ScoreboardV1` appears after `InitHUD`; -- for every ready client, when a plugin turns a schema on in the middle of a map (a client that - is still in its 0.5 s wait after `InitHUD` keeps it). +- for every ready client, when a plugin turns the extension on in the middle of a map (a client + that is still in its 0.5 s wait after `InitHUD` keeps it). `InitHUD` already sends `ScoreInfo` and `TeamInfo` for every player and the MOTD. The engine moves a client's reliable buffer (about 4 KB on HLDS) out only after the previous reliable message is acknowledged, so the sync is paced by time, not by frames, to avoid `Reliable channel overflowed`: it starts after the `InitHUD` burst and drains at about 5 KB/s. With 32 players a -GunGame sync takes about 0.6 s. +GunGame sync is about 2.8 KB and takes about 0.6 s. + +### 5.4 Per-player texts and visibility -### 5.4 Events +Templates and element visibility have a default and optional overrides for single players: -| Event | Server | -|----------------------|----------------------------------------------------------------| -| Map change | State is cleared; the plugin sets the schema again | -| Plugin resets schema | `Reset` to every ready client; the schema is off | -| Player disconnects | Slot cells are cleared; `0xFF`/`None` for the slot to everyone | -| Player changes team | Nothing: placement comes from `TeamInfo` and `ScoreInfo` | -| Client loses the cap | Nothing more is sent to that client | +- A write for player 0 sets the default and drops the overrides of the same template variant, or + of the same visibility bit, for every player: the last write wins. It always drops them, even + when the default doesn't change. Only clients whose effective value changed get a message. +- A write for player N sets an override for that client only. An override equal to the default + is dropped. +- Each client gets its override if it has one, otherwise the default. +- Overrides are cleared when the player slot is cleared (connect, disconnect), when the element is + removed, on reset and on map change. A kind change clears the text overrides of the element and + keeps the visibility ones (9.2). +- The overrides are kept apart from the per-client sync state, because a full sync resets that + state. + +The hidden standard HUD parts have no overrides. + +### 5.5 Events + +| Event | Server | +|-----------------------------|------------------------------------------------------------------------------| +| Map change | State is cleared; the plugin sets everything again | +| Plugin resets the extension | `Reset` to every ready client; the extension is off | +| Plugin removes an element | `Element` with kind `None`; `0xFF` when it removes all | +| Player disconnects | Slot cells and overrides are cleared; `0xFF`/`None` for the slot to everyone | +| Player changes team | Nothing: placement comes from `TeamInfo` and `ScoreInfo` | +| Client loses `ScoreboardV1` | Nothing more is sent to that client | ## 6. Client behaviour: scoreboard ### 6.1 Store -The store, `CScoreboardData`, is cleared on `VidInit` and on `Reset`. A player's cells -are cleared when the slot becomes empty, even if the server didn't say so. +The store, `CScoreboardData`, holds the schema, cells, lists, elements, templates and the HUD +state. It is cleared on `VidInit`, on `Reset` and when the client clears `ScoreboardV1` in `_bhl` +(3.2). A player's cells are cleared when the slot becomes empty, even if the server didn't say so. ### 6.2 Activation The custom scoreboard is shown when a `Config` arrived after the last `Reset` or `VidInit` and -`hud_scoreboard_custom` allows it. Otherwise the standard scoreboard is shown; incoming data is -still stored. +`hud_scoreboard_custom` is 1. Otherwise the standard scoreboard is shown; incoming data is still +stored and HUD elements still use it. ### 6.3 Layout - Column order: `rank`, Avatar, Name, then SteamID, Eff, Frags and Deaths at their default places unless the schema moves them, then custom and `Builtin` columns by `id`, then Ping unless moved. - Hidden standard columns and `Hidden` custom columns are left out. + Hidden standard columns, `Hidden` custom columns and `Badge` columns are left out. - The panel keeps the size, place, frame and header of the standard scoreboard (`ScorePanel.res`). - Name takes all free width. If the other columns need more, Name shrinks down to 100 units (`column_name_min`), then down to 80 units; columns that still don't fit are dropped from the @@ -470,24 +750,40 @@ still stored. - While a `Steps` column is visible, rows are taller so the strip fits under the text. - Team section headers show team cells as text in the same columns (`ModifyColumn`; the list control can't draw images in headers): `Icon` as its name, `Progress` as `cur/max`. A `Meter` - column with `max ≤ 10` stays empty, like dots without a counter. Team frags and deaths follow - the `Hide*` flags. + column with `max ≤ 10` stays empty, like dots without a counter. Badges of team cells follow + their host cell as in player rows (6.7). Team frags and deaths follow the `Hide*` flags. ### 6.4 Sorting and places - Players inside a section and the teams are sorted by the sort keys in priority order. Ties fall - back to the standard order (frags descending, deaths ascending), then to the index. Teams are - sorted by team cells; a team without cells keeps the standard order. -- The place in the `rank` column depends only on the first sort key: equal values share a place - (`1, 1, 3`). Further keys only order the rows. Without sort keys the place follows row order. + back to the standard order (frags descending, deaths ascending), then to the player index or the + team number, ascending. Teams are sorted by team cells; a team without cells keeps the standard + order. +- Team frags and deaths come from `TeamScore`; until the server sends one, they are the sums over + the team's players, as in the standard scoreboard. +- Participants are connected players that are not spectators; bots count. +- The number of a player or a team is its first-key `Int`, `Progress.cur` or `Clock` seconds. + Without sort keys it is its frags, and larger is better. +- The place in the `rank` column depends only on the first sort key: 1 + the number of entities + whose first-key cell sorts strictly before, compared as the column sorts, so equal values share a + place (`1, 1, 3`). An entity with an empty first-key cell has no place. Further keys only order + the rows. Without sort keys equal frags share a place. +- Team mode: with sort keys, at least one team with participants has a non-empty first-key team + cell; without sort keys, at least one participant is in a team. In team mode the ranked entities + are the teams with participants, the first row is the first of them in team order, and the + ranked entity of any player is his team. Otherwise the ranked entities are the participants, the + first row is the first participant in player order, and the ranked entity of a player is the + player. - With team sections the place is shown in the team header and counted among teams; player rows leave `rank` empty. Without teams the place is shown in player rows. +- The store computes the order, so HUD elements with `Leader` (8.2) and `^` refs (8.10) work with + the standard scoreboard too. ### 6.5 `hud_scores` With an active schema, `hud_scores` uses the first `Primary` column (lowest `id`) that isn't -`Hidden`. It shows that column as text instead of frags and sorts the same way as the scoreboard. -Without such a column it doesn't change. +`Hidden`, `Builtin` or `Badge`. It shows that column as text instead of frags and sorts the same +way as the scoreboard. Without such a column it doesn't change. ### 6.6 Drawing @@ -495,27 +791,72 @@ Without such a column it doesn't change. with the row text color. The text follows to the right. The client reads the sprite file and draws it as a VGUI2 texture, so icons work with every renderer, the software one included. The brightness of a pixel becomes its alpha, so the icon looks like an additive sprite. -- `Meter`, the same element as in the GunGame HUD (8.4.3): - - `max ≤ 10`: `cur` filled dots and `max − cur` empty ones, without a counter; - - `max > 10`: a rounded bar of the same length as 10 dots, filled to `cur / max`, with the - `cur/max` counter to the right. +- `Meter` keeps the dot look of the scoreboard, which is not the HUD `Meter` (8.7). Dots are discs + of `cell_dot_size` with `cell_dot_gap` between them, smaller when the column or the row is too + small for 10 of them: + - `max ≤ 10`: `cur` dots in `cell_filled_color` and `max − cur` dim ones in `cell_empty_color`, + without a counter; + - `max > 10`: a rounded bar of the same length as 10 dots in `cell_empty_color`, filled to + `cur / max` (at least one dot) in `cell_filled_color`, with the `cur/max` counter to the right. - `Steps`: `cur/max` as text; below it a strip of `max` segments. Segments before `cur` are - filled, segment `cur` is highlighted, the rest are dimmed, the last one is marked. + filled, segment `cur` is highlighted, the rest are dimmed. With `MarkLast` a dimmed last segment + uses `cell_last_color`. When the column has less than 2 pixels per segment, the strip is one bar + filled to `cur / max`. - `Progress` in a `Text` column: `cur/max`. - -### 6.7 Presets - -| Preset | Behaviour | -|-----------|--------------------------------------------------| -| `""` | Generic: only what the schema describes | -| `gungame` | The GunGame scoreboard and HUD widget, section 8 | - -### 6.8 Debug commands - -- `hud_scoreboard_test [preset|off] [phase] [phase_left]` fills the store with fake data for the - current players without a server. With `phase` 1 or 2 it shows the warmup columns, like the - GunGame plugin. -- `hud_scoreboard_dump` prints the store to the console. +- `Clock` in any column: written with `time` (8.10). A running clock is refreshed at least once a + second while the scoreboard is open. + +### 6.7 Badges + +- A non-empty cell of a `Badge` column is drawn as a badge after the content of the cell of + column `host`, with the look of the tag badge (`badge_font`, `badge_bgcolor`, `badge_fgcolor`). + This holds in player rows with player cells and in team headers with team cells, so in GunGame + teamplay the `final` badge follows the team's weapon. +- The badge text is the cell drawn as text: a `#token` is localized. +- A badge is drawn even when the host cell is empty. In a narrow column the text of the host cell + is cut first; badges that still don't fit are left out. +- No badge is drawn when the `Badge` column is `Hidden`, or when `host` is missing, hidden, + `Builtin` or a `Badge` column, or is cut off by the layout. Several badges after one cell are + drawn in `id` order. + +### 6.8 Banner + +The custom scoreboard has a banner in its header, left of the player count, on the rows of the +server name and the map name. Its two rows are `Text` elements placed `BannerTop` and +`BannerBottom`. The plugin decides what a row says and when, through templates, `select` and +visibility; the client knows no game mode. + +- A row shows the lowest-id `Text` element with that place that is visible in `HudState` and whose + text is not empty. +- `Subject` and `Leader` apply as on the screen (8.2). A row with `Leader` is not drawn when there + are no participants. `x`, `y`, `align`, `gap`, `font` and `NoScoreboard` are ignored. + `hud_server_elements` and the other rules from 8.3 don't apply: the banner belongs to the + scoreboard. +- `Icon`, `Meter` and `Strip` elements with a banner place are not drawn. +- The banner is drawn when at least one of its rows is drawn. +- Look: a box (`banner_bgcolor` 255 64 32 48) with an accent bar on the left + (`banner_accent_color` 255 160 0 255, `banner_accent_wide` 2, `banner_padding` 1). The rows use + the fonts of the server name and the map name labels. With `HudColor` the top row uses + `banner_accent_color` and the bottom row the header text color; otherwise rows use the element + color. +- Layout: + - the right edge is at the left edge of the player count text, minus the spacing and the padding; + - rows are cut so that the map name and a third of the server name stay visible; + - the server name is narrowed so that the name and the tag end before the banner; + - the banner is laid out again whenever the evaluated text of a row changes, and on every change + of the header (server name, map name, player count, tag). + +### 6.9 Debug commands + +- `hud_scoreboard_test [off]` fills the store with fake data for the current players without a + server. It builds real `BhlScore` messages and feeds them to the parser: columns `rank`, `stage` + (`Steps`, `MarkLast`), `item` (`Icon`), `progress` (`Meter`), hidden `score` as the first sort + key, a badge after `item`, a list `items`, and elements that use the client tokens (place line, + rival line, meter, strip, banner). +- `hud_scoreboard_dump` prints the store: schema, cells, lists, elements, templates with their + parse errors, the HUD state, the subject and the built-in values. +- `hud_server_eval "