Author SHA1 Message Date
shenleiandClaude Opus 5.5 7f4e8b3f76 Add the battle pass (port of AVA2 ENABLE_BATTLE_PASS)
Monthly seasons from share/locale/<locale>/port_battlepass.tsv, up to ten
missions (kills, boss, stone, play time, fishing, refine, level, NPC spend,
NPC sell) with per-mission and final rewards. Progress is counted in memory
and flushed additively on save; claims are idempotent via INSERT IGNORE.
Client protocol: /mt_bp 1 info|claim N|close -> MTBP1 lines.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 09:11:36 +09:00
shenleiandClaude Opus 5.5 1bdaae8807 Record the VIP card production deploy
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 03:48:38 +09:00
shenleiandClaude Opus 5.5 69e335ba9c Add VIP cards extending the seven premium services
Using 38001 (7 days) or 38002 (30 days) moves every account.account
*_expire column to max(now, end) + days, capped at 400 days left, with a
1 s gap per player. The db core only hands out the login-time premium
times (CLoginData), so the game reads the row back after a card and on
every enter-game and updates m_aiPremiumTimes and the 500..506 icons.
/mt_vip 1 status reports the remaining seconds. docs/FEATURE-VIP.md.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 02:13:17 +09:00
shenleiandClaude Opus 5.5 3590a06946 Keep feature commands at the end of the command table
interpret_command picks the first entry whose name starts with the typed
command. mt_features sat near the top, so /m ran mt_features instead of mob
and /mt instead of mto. The four mt_* entries now sit after the original
commands; test_cmd_prefix.py checks that no original abbreviation changes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 01:37:41 +09:00
shenleiandClaude Opus 5.5 06b96c62d1 Record the batch chest production deploy
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-15 23:47:49 +09:00
22 changed files with 1376 additions and 4 deletions
+111
View File
@@ -0,0 +1,111 @@
# PORT battle pass
A monthly mission pass, ported from AVA2's `ENABLE_BATTLE_PASS` (the window behind `uibattlepassex.py`). A season is a time window with up to ten missions. Each mission has its own reward, and a final reward unlocks once every mission is done. The pass is free for every player; AVA2 sold a ticket item (25150–25161), and this port has none.
Source:
- `src/server/game/src/port_battlepass.h`: config, per-player state and bag fit; standard C++ only.
- `port_battlepass_runtime.h`: game side, included only by cmd_general.cpp.
- `port_battlepass_hooks.h`: hook declarations for the other files.
Tables: `tools/battlepass/schema.sql`. Season file: `tools/battlepass/port_battlepass.tsv`. Test: `tests/features/test_battlepass.py`.
## Season file
The file is `<locale base>/port_battlepass.tsv`, for example `share/locale/newcibn/port_battlepass.tsv`. Every core checks it at most once every 5 s and reloads it when its mtime, size or inode changes, the same rule the event calendar uses. Replace it atomically with a temporary file and `mv`.
```
MTBATTLEPASS 1
season ID START END unix seconds, [START, END)
mission SLOT TYPE SUB TARGET [VNUM COUNT]x0..3
final VNUM COUNT [VNUM COUNT]x0..5
```
- Any error disables the whole file; the game logs `PORT_BP: port_battlepass.tsv disabled: line N: why`. Errors include:
- a bad number or a duplicate slot;
- overlapping seasons;
- a season without missions;
- a sub on a type that takes none.
- Slot numbers are 1..10. A season ID must never be reused: progress and claims are stored per season ID.
- A reward must be a bag item:
- not a dragon soul stone;
- size 1..3;
- at most 24 stacks per claim.
A bad reward is caught when someone claims it: the answer is `config`, `sys_err` logs it, and the slot stays claimable after the file is fixed.
| Type | Counts | SUB |
|---|---|---|
| 1 | monster kills (not boss, not stone) | mob vnum or 0 |
| 2 | boss kills (rank ≥ boss) | mob vnum or 0 |
| 3 | metin stone kills | stone vnum or 0 |
| 4 | seconds online | 0 |
| 5 | fish caught | item vnum or 0 |
| 6 | successful refines | resulting item vnum or 0 |
| 7 | levels gained | 0 |
| 8 | gold paid to NPC shops | 0 |
| 9 | items sold to NPC shops | item vnum (required) |
A kill counts for the player that `CHARACTER::Reward` gives the quest kill event to, which is the `DistributeExp` attacker. As in AVA2, it counts only when the monster is within 20 levels of the player. A party member who is not that attacker gets nothing. Type 9 needs a vnum because selling any item could be farmed with cheap shop items.
The shipped file has seasons 202610–202612, starting at local midnight on the first of each month (Europe/Berlin, the server's zone). Each has:
- eight missions, rewards taken from 40250 items;
- a final reward of the three pearls and 70024.
The targets follow the scale of AVA2's month 10 (`player.battle_pass`).
## Storage
```
player.mt_battlepass_progress (pid, season, slot, value, target) PRIMARY KEY (pid, season, slot)
player.mt_battlepass_claim (pid, season, slot, claimed_at) PRIMARY KEY (pid, season, slot); slot 0 = final
```
**Counting.** Events are counted in memory, as the delta per slot. `CHARACTER::SaveReal`, which covers the periodic save, logout and warp, adds play time, then queues one upsert on the game's ordered SQL connection:
`value = LEAST(value + delta, target)`
Because the write adds, a core does not need to have read the row first. Two cores that both see the player during a warp add their own deltas, with no overwrite.
**Loading.** At the first event or `/mt_bp`, a `FuncQuery` reads the stored values and claims. Flushes queued after that read are added on top. A generation number drops the answers of a session that has already ended.
**Season change.** The counts of the old season are written while that season is still in the file. The new season then loads its own rows.
**Claims.** A claim checks four things before writing anything:
1. the state is loaded;
2. the mission is complete;
3. the slot is not claimed yet;
4. all the stacks fit in the bag. The fit is first-fit in `GetEmptyInventory` order, and a size-2 or size-3 item stays inside one 45-cell page.
Only then does it run `INSERT IGNORE` into the claim table synchronously. Only the request whose insert affected a row creates the items, into the cells checked before. A double click, a retry or another core finds the row already there and gets `claimed`. Each item gets an `MT_BP_CLAIM` item log with the hint `SEASON SLOT`, and the character is saved right away.
Known limits:
- If the core crashes between the claim row and the item save, that reward is lost. The claim row and the item log are there for a GM to compensate.
- While a warp is in flight, the window can show slightly less progress than is stored. Nothing is lost or counted twice.
## Protocol
```
/mt_bp 1 info | 1 claim SLOT | 1 close
MTBP1 season ID START END NOW COUNT
MTBP1 mission SLOT TYPE SUB TARGET VALUE CLAIMED [VNUM COUNT]...
MTBP1 final CLAIMED ALLDONE [VNUM COUNT]...
MTBP1 end
MTBP1 none no season running (or no valid file)
MTBP1 progress SLOT VALUE pushed while the window is open
MTBP1 done SLOT a mission was finished (always sent)
MTBP1 claimed SLOT the reward is in the bag; a full info follows
MTBP1 error loading|slot|claimed|incomplete|space|config|db|rate|invalid
```
- `info` before the load is answered as soon as the load arrives.
- A `done` for a mission that an event finished before the load is sent when the load arrives.
- `info` and `claim` share a 300 ms gap per player (`rate`).
- A wrong version, more than three tokens, or a token longer than 10 characters gets no answer.
## Setup
1. Apply `tools/battlepass/schema.sql` once.
2. Copy `port_battlepass.tsv` to the locale base directory.
3. Restart the cores with the new binary.
Without the file, every `/mt_bp` answers `none` and nothing is counted or written.
+6
View File
@@ -50,3 +50,9 @@ There is no MTF1 capability bit (the mask stays 511). The client marks the serve
- remaining 20 of 50037 → `done 50037 20 20 done 0`, 11 gained vnums;
- plain right click without Ctrl still uses one box the original way.
- `log.log` only has the original path's rows (`SYSTEM`, `TREASURE_EXP`, `TREASURE_GOLD`). syserr shows only the pre-existing `new_quest_lv52` LUA_ERROR.
## Production deployment
- Deployed 2026-10-15 16:43 with the user's approval, 0 players online. Server main bc32475, game sha256 `412977c7…` (the channel-5 tested binary), db unchanged. Package `/root/deploy-features/20261015-chest`, backup `/root/backup-bin/20261015-164314`, rollback `sh /root/deploy-features/20261015-chest/deploy.sh rollback`. `/usr/metin2/src` was synced (cmd.cpp, cmd_general.cpp, port_chest.h).
- On the first start the db core exited at boot (`QueryLocaleSet: ... errno 2013 Lost connection to MySQL server during query`, db.core kept as `db.core.164339` in the package). MySQL itself had not restarted and the db binary is unchanged. A clean stop of every core and a db-first start (db, auth, CH1–CH4, game99, then channel5) came up normally: 14 game, 1 db, 1 auth, port 15000 listening. If this repeats, check `ps` for `./db` after every deploy, not only the game count.
- CH1 (13000) acceptance with the channel-5 scenario: 50037 ×10 → `done 50037 10 10 done 0` (8 vnums, equal to the bag difference); 50070 ×4 in 4 cells → `done 50070 4 4 done 100000`; 71036 → `error kind`, then `error rate`; remaining 20 → `done 50037 20 20 done 0`; plain use unchanged. syserr only has the pre-existing `new_quest_lv52` LUA_ERROR.
+101
View File
@@ -0,0 +1,101 @@
# PORT VIP card
A card extends all seven original premium services of the account. 40250 has the services but no in-game way to grant them. Source: `src/server/game/src/port_premium.h`, the hook in `CHARACTER::UseItem` (char_item.cpp), the enter-game refresh in input_login.cpp, `CHARACTER::PortSetPremiumTime` (char.h) and `/mt_vip` (cmd_general.cpp, cmd.cpp). Item data (size, flags, names, shop): metin2-client `tools/server/vip-card`.
## Services
`account.account` holds one end time per service. The game keeps them in `m_aiPremiumTimes` and shows affect `AFFECT_PREMIUM_START + i` (500..506) as the icon.
| i | Premium | Column | Effect on newcibn |
|---|---|---|---|
| 0 | `PREMIUM_EXP` | `silver_expire` | monster exp ×1.2 × `mob_exp_buyer`/100 (char_battle.cpp) |
| 1 | `PREMIUM_ITEM` | `gold_expire` | item drop rate |
| 2 | `PREMIUM_SAFEBOX` | `safebox_expire` | safebox size 3 (input_db.cpp) |
| 3 | `PREMIUM_AUTOLOOT` | `autoloot_expire` | gold goes straight to the bag (char_battle.cpp) |
| 4 | `PREMIUM_FISH_MIND` | `fish_mind_expire` | fishing |
| 5 | `PREMIUM_MARRIAGE_FAST` | `marriage_fast_expire` | marriage love points |
| 6 | `PREMIUM_GOLD` | `money_drop_rate_expire` | gold drop rate |
## Cards
| Vnum | Days |
|---|---|
| 38001 | 7 |
| 38002 | 30 |
Both are unused `ITEM_NONE` rows in 40250. `PortVipUseCard` runs in `UseItem` after the sex check, before any type handling, so the item type does not matter.
When a card is used:
1. The card is refused, and not consumed, in two cases:
- the player used a card or `/mt_vip` less than 1 s ago (`rate`);
- for any service, the remaining time plus the card would exceed 400 days (`full`). The `int` end times stay far below 2038.
2. Otherwise one card is consumed, with an `MT_VIP_CARD` item log whose hint is the number of days.
3. One `UPDATE` moves every column to `GREATEST(UNIX_TIMESTAMP(col), UNIX_TIMESTAMP()) + days × 86400`. A service that has expired restarts from now; a running one is extended.
## Freshness
Auth reads the columns only at login and passes them to the db core's `CLoginData`. Every later player load, such as a warp or a core change, fills `TPlayerTable.aiPremiumTimes` from that login-time copy. So after a card, and on every enter-game, the game reads the row itself.
`PortVipRefresh` handles this:
- It queues `SELECT UNIX_TIMESTAMP(col)... FROM account.account WHERE id=` through `DBManager::FuncQuery`. That is the same ordered queue and connection as the card's `UPDATE`, so the read sees the update.
- The answer finds the player again by PID and checks the account ID; if the player has left, nothing happens.
- For each service whose end changed, it sets `m_aiPremiumTimes[i]`, then either adds the affect with the remaining duration or removes it if the service has expired.
- It logs `PORT_VIP: <name> type <i> end <unix>`.
The db core is not changed.
## Protocol
```
/mt_vip 1 status ask for the remaining time
MTVIP1 times R0 R1 R2 R3 R4 R5 R6 remaining seconds per service (0 = none), PREMIUM_EXP .. PREMIUM_GOLD
MTVIP1 added VNUM DAYS a card was consumed; a times line follows once the row is read back
MTVIP1 error CODE rate full invalid
```
- `status` and card use share the 1 s throttle per player.
- A wrong version, or more than three tokens, gets no answer; an old client never sends one.
- The client (metin2-client `src/platform/ScriptLib/VipScript.inc`, module `mt_vip`) treats a `status` with no answer within 3 s as a server without the feature.
## Exp bonus
On newcibn the premium exp branch multiplies by 1.2 and then by `GetMobExpRate`, which returns event flag `mob_exp_buyer` (default 100). `/e mob_exp_buyer 167` gives 1.2 × 1.67 ≈ 2.0, that is +100 %. Event flags live in `player.quest` (pid 0) and every core shares them, so the flag is set once, by a GM, at deploy.
## Verification
- `tests/features/test_vip.py` checks the wiring:
- the command entry is at the end of `cmd_info`;
- the include is outside the `__AUCTION__` block;
- the hook sits between the sex check and the summon-item block;
- the refresh runs after the login affect loop.
- It also compiles the production header against a stub account table, the ordered SQL queue and the affects. It covers:
- a 7-day card, the read-back and the icons;
- the gap refusal, then a 30-day card stacked onto the current end;
- the 400-day cap: no card consumed, no query;
- other items left untouched;
- the enter-game refresh over stale values;
- a service expired by hand, and the `status` command;
- a player who leaves before the answer, and a missing account row.
- Live test, channel5 (2026-10-15), Admin account with all expire values reset to 0:
- 38002 (30 days) set all seven columns to now + 30 days, added affects 500..506 and returned `times 2592000…`.
- Two 38001 used through the inventory right-click, 2 s apart, extended to 44 days.
- A same-map `/warp` reloaded the player with the login-time 30 days. The refresh logged the seven `PORT_VIP` corrections to 44 days, and the panel showed "剩余 43 天 23 小时" for every service.
- Earlier, with premium, autoloot gold went straight to the bag; without it, the gold stayed on the ground.
## Production deployment
- Deployed 2026-10-16 (server clock 2026-10-15 20:44) with the user's approval, 0 players online. Server main 69e335b, which includes the `/m` command-prefix fix 3590a06. Game sha256 `8d0bf9f0…` (the channel-5 tested binary); db unchanged.
- Package: `/root/deploy-features/20261016-vip` (metin2-client `tools/server` at main 32372c2a).
- Binary backup: `/root/backup-bin/20261015-204352`.
- Rollback: `sh /root/deploy-features/20261016-vip/deploy.sh rollback`. The data backups are in `/root/backup-vip-card/20261015-204353` and `/root/backup-npcshop/item_mall-20261015-204353`.
- `/usr/metin2/src` was synced with the six changed files.
- `deploy.sh go` stops every core, then installs the game. It runs `vip-card/install.sh` and the item-mall shop install while the db core is down, since db reads `item_proto.txt` at boot. Then it starts db alone, waits for port 15000, and starts auth, CH1–CH4, game99 and channel5: 14 game, 1 db, 1 auth.
- At boot the db core rewrites `player.item_proto` from the txt, with `locale_name` `Noname` for every item; names come from `item_names.txt`. Both cards: size 1, flag 8196, antiflag 256.
- `/e mob_exp_buyer 167` was set from CH1. Every core logged `QUEST eventflag mob_exp_buyer 167`, and the row is in `player.quest` (pid 0).
- CH1 (13000) acceptance:
- `/m 101` spawned and `/purge` removed it.
- 9010 (map a1) lists 38001/38002. A buyer from another empire pays the original triple price (shop.cpp), 15 000 000 for a 7-day card.
- Two 38001 bought: each takes one cell (a shop buy never merges), and dragging one onto the other gives a stack of 2.
- Using one: `added 38001 7`, then `times 4400055…`. The panel shows 50 days 22 hours for all seven services.
- syserr only has the pre-existing `new_quest_lv52` LUA_ERROR.
+6
View File
@@ -57,6 +57,7 @@
// #include "HackShield.h"
#include "skill_power.h"
#include "buff_on_attributes.h"
#include "port_battlepass_hooks.h"
#ifdef __PET_SYSTEM__
#include "PetSystem.h"
@@ -1304,6 +1305,8 @@ void CHARACTER::SaveReal()
marriage::TMarriage* pMarriage = marriage::CManager::instance().Get(GetPlayerID());
if (pMarriage)
pMarriage->Save();
PortBpSave(this); // PORT: battle pass progress
}
void CHARACTER::FlushDelayedSaveItem()
@@ -1393,6 +1396,7 @@ void CHARACTER::Disconnect(const char * c_pszReason)
SaveAffect();
m_bIsLoadedAffect = false;
PortBpLogout(this); // PORT: battle pass, after the last save
m_bSkipSave = true; // 이 이후에는 더이상 저장하면 안된다.
@@ -3063,6 +3067,8 @@ void CHARACTER::PointChange(BYTE type, int amount, bool bAmount, bool bBroadcast
if (amount)
{
if (amount > 0)
PortBpCount(this, PORT_BP_LEVEL_UP, 0, amount); // PORT: battle pass
quest::CQuestManager::instance().LevelUp(GetPlayerID());
LogManager::instance().LevelLog(this, val, GetRealPoint(POINT_PLAYTIME) + (get_dword_time() - m_dwPlayStartTime) / 60000);
+2
View File
@@ -1746,6 +1746,8 @@ class CHARACTER : public CEntity, public CFSM, public CHorseRider
public:
int GetPremiumRemainSeconds(BYTE bType) const;
// PORT: the VIP card re-reads the account end times (port_premium.h).
void PortSetPremiumTime(BYTE bType, int iTime) { if (bType < PREMIUM_MAX_NUM) m_aiPremiumTimes[bType] = iTime; }
private:
int m_aiPremiumTimes[PREMIUM_MAX_NUM];
+3
View File
@@ -40,6 +40,7 @@
#include "BlueDragon.h"
#include "DragonLair.h"
#include <random>
#include "port_battlepass_hooks.h"
#include <algorithm>
DWORD AdjustExpByLevel(const LPCHARACTER ch, const DWORD exp)
{
@@ -785,6 +786,8 @@ void CHARACTER::Reward(bool bItemDrop)
pkAttacker->UpdateAlignment(2);
pkAttacker->SetQuestNPCID(GetVID());
// PORT: battle pass kill, credited like the quest kill below (port_battlepass_runtime.h).
PortBpKill(pkAttacker, this);
quest::CQuestManager::instance().Kill(pkAttacker->GetPlayerID(), GetRaceNum());
CHARACTER_MANAGER::instance().KillLog(GetRaceNum());
+8
View File
@@ -50,6 +50,8 @@
#ifdef __AUCTION__
#include "auction_manager.h"
#endif
#include "port_premium.h"
#include "port_battlepass_hooks.h"
const int ITEM_BROKEN_METIN_VNUM = 28960;
// CHANGE_ITEM_ATTRIBUTES
@@ -923,6 +925,7 @@ bool CHARACTER::DoRefine(LPITEM item, bool bMoneyOnly)
{
ITEM_MANAGER::CopyAllAttrTo(item, pkNewItem);
LogManager::instance().ItemLog(this, pkNewItem, "REFINE SUCCESS", pkNewItem->GetName());
PortBpCount(this, PORT_BP_REFINE, pkNewItem->GetVnum(), 1); // PORT: battle pass
WORD bCell = item->GetCell();
@@ -1196,6 +1199,7 @@ bool CHARACTER::DoRefineWithScroll(LPITEM item)
{
ITEM_MANAGER::CopyAllAttrTo(item, pkNewItem);
LogManager::instance().ItemLog(this, pkNewItem, "REFINE SUCCESS", pkNewItem->GetName());
PortBpCount(this, PORT_BP_REFINE, pkNewItem->GetVnum(), 1); // PORT: battle pass
WORD bCell = item->GetCell();
@@ -5207,6 +5211,10 @@ bool CHARACTER::UseItem(TItemPos Cell, TItemPos DestCell)
return false;
}
// PORT: VIP card (port_premium.h)
if (PortVipUseCard(this, item))
return true;
//PREVENT_TRADE_WINDOW
if (IS_SUMMON_ITEM(item->GetVnum()))
{
+10 -4
View File
@@ -13,6 +13,8 @@ ACMD(do_port_features);
ACMD(do_port_switchbot);
ACMD(do_port_pickup);
ACMD(do_port_chest);
ACMD(do_port_vip);
ACMD(do_port_bp);
ACMD(do_user_horse_ride);
ACMD(do_user_horse_back);
ACMD(do_user_horse_feed);
@@ -287,10 +289,6 @@ struct command_info cmd_info[] =
{
{ "!RESERVED!", NULL, 0, POS_DEAD, GM_IMPLEMENTOR }, /* 반드시 이 것이 처음이어야 한다. */
{ "autohunt_pull", do_autohunt_pull, 0, POS_STANDING, GM_PLAYER },
{ "mt_features", do_port_features, 0, POS_DEAD, GM_PLAYER },
{ "mt_switchbot", do_port_switchbot, 0, POS_DEAD, GM_PLAYER },
{ "mt_pickup", do_port_pickup, 0, POS_DEAD, GM_PLAYER },
{ "mt_chest", do_port_chest, 0, POS_DEAD, GM_PLAYER },
{ "bio", do_port_biolog, 0, POS_DEAD, GM_PLAYER },
{ "biolog", do_port_biolog, 0, POS_DEAD, GM_PLAYER },
{ "server_bonuses", do_server_bonuses, 0, POS_DEAD, GM_PLAYER },
@@ -603,6 +601,14 @@ struct command_info cmd_info[] =
{ "ds_list", do_ds_list, 0, POS_DEAD, GM_PLAYER },
{ "do_clear_affect", do_clear_affect, 0, POS_DEAD, GM_LOW_WIZARD},
// PORT: feature commands stay at the end: commands are prefix matched in table order, so an entry placed
// earlier would take over abbreviations of original commands (/m -> mob, /mt -> mto).
{ "mt_features", do_port_features, 0, POS_DEAD, GM_PLAYER },
{ "mt_switchbot", do_port_switchbot, 0, POS_DEAD, GM_PLAYER },
{ "mt_pickup", do_port_pickup, 0, POS_DEAD, GM_PLAYER },
{ "mt_chest", do_port_chest, 0, POS_DEAD, GM_PLAYER },
{ "mt_vip", do_port_vip, 0, POS_DEAD, GM_PLAYER },
{ "mt_bp", do_port_bp, 0, POS_DEAD, GM_PLAYER },
{ "\n", NULL, 0, POS_DEAD, GM_IMPLEMENTOR } /* 반드시 이 것이 마지막이어야 한다. */
};
+17
View File
@@ -46,6 +46,23 @@
#include "port_switchbot.h"
#include "port_pickup.h"
#include "port_chest.h"
#include "port_premium.h"
#include "port_battlepass_runtime.h"
ACMD(do_port_vip)
{
if (!ch || !ch->IsPC() || !ch->GetDesc())
return;
PortVipCommand(ch, argument);
}
// PORT: battle pass (port_battlepass_runtime.h)
ACMD(do_port_bp)
{
if (!ch || !ch->IsPC() || !ch->GetDesc())
return;
PortBpCommand(ch, argument);
}
extern int g_server_id;
+2
View File
@@ -23,6 +23,7 @@
#include "affect.h"
#include "unique_item.h"
#include "port_battlepass_hooks.h"
#endif
namespace fishing
@@ -634,6 +635,7 @@ void Take(fishing_event_info* info, LPCHARACTER ch)
if (item_vnum)
{
FishingSuccess(ch);
PortBpCount(ch, PORT_BP_CATCH_FISH, item_vnum, 1); // PORT: battle pass
TPacketGCFishing p;
p.header = HEADER_GC_FISHING;
+5
View File
@@ -28,6 +28,9 @@
#include "block_country.h"
#include "dev_log.h"
#include "log.h"
#include "db.h"
#include "item.h"
#include "port_premium.h"
#include "horsename_manager.h"
#include "MarkManager.h"
// #include "HackShield.h"
@@ -642,6 +645,8 @@ void CInputLogin::Entergame(LPDESC d, const char * data)
ch->AddAffect(AFFECT_PREMIUM_START + i, POINT_NONE, 0, 0, remain, 0, true);
sys_log(0, "PREMIUM: %s type %d %dmin", ch->GetName(), i, remain);
}
// PORT: the db core keeps the login-time premium ends; a VIP card used since then is in the account table.
PortVipRefresh(ch, false);
if (LC_IsEurope())
{
+226
View File
@@ -0,0 +1,226 @@
#ifndef PORT_BATTLEPASS_H
#define PORT_BATTLEPASS_H
// PORT: battle pass, from AVA2's ENABLE_BATTLE_PASS (the monthly mission pass behind uibattlepassex.py). A season
// is a time window from port_battlepass.tsv with up to ten missions, each with its own reward, and a final reward
// once every mission is done. Only real server events count: kills, fishing, refines, level ups, NPC shop trades
// and play time; the client only asks and claims. Progress and claims live in player.mt_battlepass_progress and
// player.mt_battlepass_claim (unique per player, season and slot). Design: docs/FEATURE-BATTLEPASS.md.
// This header holds the game-independent part: the config, the per-player state and the bag fit.
#include <algorithm>
#include <fstream>
#include <istream>
#include <limits>
#include <set>
#include <sstream>
#include <string>
#include <sys/stat.h>
#include <vector>
enum PortBpType {
PORT_BP_NONE,
PORT_BP_KILL_MONSTER, // sub: mob vnum, 0 = any normal monster (not a boss or a stone)
PORT_BP_KILL_BOSS, // sub: mob vnum, 0 = any boss
PORT_BP_KILL_STONE, // sub: stone vnum, 0 = any metin stone
PORT_BP_PLAYTIME, // seconds online
PORT_BP_CATCH_FISH, // sub: caught item vnum, 0 = any
PORT_BP_REFINE, // successful refines; sub: resulting item vnum, 0 = any
PORT_BP_LEVEL_UP, // levels gained
PORT_BP_NPC_SPEND, // gold paid to NPC shops
PORT_BP_NPC_SELL, // items sold to NPC shops; sub (required): item vnum
PORT_BP_TYPE_MAX
};
static const unsigned kPortBpSlots=10; // mission slots 1..10; slot 0 is the final reward
static const unsigned kPortBpMissionRewards=3; // AVA2 BATTLE_SUB_REWARD
static const unsigned kPortBpFinalRewards=6; // AVA2 BATTLE_REWARD_MAX
static const unsigned long long kPortBpMaxTarget=1000000000000ULL;
static const unsigned kPortBpMaxRewardCount=10000;
struct PortBpReward {unsigned vnum,count;};
struct PortBpMission {
unsigned slot,type,sub;unsigned long long target;std::vector<PortBpReward> rewards;
bool Matches(unsigned kind,unsigned what)const{return type==kind && (!sub || sub==what);}
};
struct PortBpSeason {
unsigned id,start,end;std::vector<PortBpMission> missions;std::vector<PortBpReward> final;
const PortBpMission* Slot(unsigned slot)const {
for(const auto& m:missions)if(m.slot==slot)return &m;
return nullptr;
}
bool Has(unsigned kind)const {
for(const auto& m:missions)if(m.type==kind)return true;
return false;
}
};
// Whole-file config: any error disables the battle pass rather than running half a season.
class PortBpConfig {
public:
std::vector<PortBpSeason> seasons;
bool valid=false;
std::string error;
bool Parse(std::istream& input) {
std::vector<PortBpSeason> next;std::string line;unsigned bytes=0,number=0;bool header=false;
error.clear();
auto fail=[&](const char* why){error="line "+std::to_string(number)+": "+why;return false;};
auto run=[&]()->bool {
while(std::getline(input,line)) {
++number;bytes+=unsigned(line.size()+1);
if(bytes>65536)return fail("file too large");
if(!line.empty() && line.back()=='\r')line.pop_back();
if(line.empty() || line[0]=='#')continue;
if(!header){if(line!="MTBATTLEPASS 1")return fail("header");header=true;continue;}
std::istringstream row(line);std::string word,token;std::vector<unsigned long long> v;
row>>word;
while(row>>token) {
unsigned long long value=0;
if(token.size()>13)return fail("number too long");
for(char c:token){if(c<'0'||c>'9')return fail("not a number");value=value*10+unsigned(c-'0');}
v.push_back(value);
}
if(word=="season") {
if(v.size()!=3 || !v[0] || v[0]>0xffffffffULL || v[1]>=v[2] || v[2]>0xffffffffULL)return fail("season ID START END");
if(next.size()>=64)return fail("too many seasons");
for(const auto& s:next)if(s.id==v[0])return fail("duplicate season id");
next.push_back(PortBpSeason{unsigned(v[0]),unsigned(v[1]),unsigned(v[2]),{},{}});
continue;
}
if(next.empty())return fail("mission or final before season");
PortBpSeason& season=next.back();
std::vector<PortBpReward> rewards;
auto pairs=[&](size_t from,unsigned most)->bool {
if((v.size()-from)%2 || (v.size()-from)/2>most)return false;
for(size_t i=from;i<v.size();i+=2) {
if(!v[i] || v[i]>0xffffffffULL || !v[i+1] || v[i+1]>kPortBpMaxRewardCount)return false;
rewards.push_back(PortBpReward{unsigned(v[i]),unsigned(v[i+1])});
}
return true;
};
if(word=="mission") {
if(v.size()<4 || !pairs(4,kPortBpMissionRewards))return fail("mission SLOT TYPE SUB TARGET [VNUM COUNT]x0..3");
if(!v[0] || v[0]>kPortBpSlots || season.Slot(unsigned(v[0])))return fail("slot 1..10, once per season");
if(!v[1] || v[1]>=PORT_BP_TYPE_MAX)return fail("type");
if(v[2]>0xffffffffULL)return fail("sub");
const unsigned type=unsigned(v[1]);
const bool subAllowed=type!=PORT_BP_PLAYTIME && type!=PORT_BP_LEVEL_UP && type!=PORT_BP_NPC_SPEND;
if(v[2] && !subAllowed)return fail("this type takes sub 0");
if(!v[2] && type==PORT_BP_NPC_SELL)return fail("NPC sell needs an item vnum");
if(!v[3] || v[3]>kPortBpMaxTarget)return fail("target");
season.missions.push_back(PortBpMission{unsigned(v[0]),type,unsigned(v[2]),v[3],rewards});
continue;
}
if(word=="final") {
if(!season.final.empty() || !pairs(0,kPortBpFinalRewards) || rewards.empty())return fail("final VNUM COUNT x1..6, once per season");
season.final=rewards;
continue;
}
return fail("unknown line");
}
if(input.bad())return fail("read error");
if(!header)return fail("header");
if(next.empty())return fail("no season");
std::sort(next.begin(),next.end(),[](const PortBpSeason& a,const PortBpSeason& b){return a.start<b.start;});
for(size_t i=0;i<next.size();++i) {
if(next[i].missions.empty()){number=0;return fail("season without missions");}
if(i && next[i].start<next[i-1].end){number=0;return fail("seasons overlap");}
std::sort(next[i].missions.begin(),next[i].missions.end(),[](const PortBpMission& a,const PortBpMission& b){return a.slot<b.slot;});
}
return true;
};
valid=run();
if(valid)seasons.swap(next);
else seasons.clear();
return valid;
}
const PortBpSeason* Active(long long now)const {
if(!valid)return nullptr;
for(const auto& s:seasons)if(now>=s.start && now<s.end)return &s;
return nullptr;
}
// Same contract as the event calendar: an atomic file replacement is picked up by every core within 5 s.
bool Refresh(const std::string& path,unsigned tick) {
if(checked && unsigned(tick-lastCheck)<5000)return false;
checked=true;lastCheck=tick;
struct stat info;
if(stat(path.c_str(),&info)!=0){const bool had=loaded;valid=false;seasons.clear();loaded=false;error="missing";return had;}
if(loaded && info.st_mtime==modified && info.st_size==size && info.st_ino==inode)return false;
loaded=true;modified=info.st_mtime;size=info.st_size;inode=info.st_ino;
if(size>65536 || size<0){valid=false;seasons.clear();error="file too large";return true;}
std::ifstream file(path);Parse(file);
return true;
}
private:
bool checked=false,loaded=false;unsigned lastCheck=0;time_t modified=0;off_t size=0;ino_t inode=0;
};
// One player's view of the active season. base is what the database held when the load was queued, plus every
// flush queued after it; delta is counted here and not flushed yet. Flushes add, so a missed load never loses
// progress and the stored value is capped at the target by the database itself.
struct PortBpState {
unsigned season=0,generation=0;
bool loaded=false,watching=false,wantInfo=false;
unsigned long long base[kPortBpSlots+1]={},delta[kPortBpSlots+1]={},inflight[kPortBpSlots+1]={};
std::set<unsigned> claimed; // slots; 0 = final
unsigned playtimeMark=0; // get_dword_time() up to which play time has been counted
unsigned lastCommand=0;
unsigned long long Value(const PortBpMission& m)const {return std::min(m.target,base[m.slot]+delta[m.slot]);}
bool Done(const PortBpMission& m)const {return base[m.slot]+delta[m.slot]>=m.target;}
bool AllDone(const PortBpSeason& s)const {
for(const auto& m:s.missions)if(!Done(m))return false;
return true;
}
void Reset(unsigned id) {
season=id;loaded=false;wantInfo=false;claimed.clear();
std::fill(base,base+kPortBpSlots+1,0ULL);std::fill(delta,delta+kPortBpSlots+1,0ULL);std::fill(inflight,inflight+kPortBpSlots+1,0ULL);
}
};
// Adds amount to every unfinished mission of this kind; returns the slots that changed and those it finished.
inline void PortBpAdd(const PortBpSeason& season,PortBpState& state,unsigned kind,unsigned what,unsigned long long amount,
std::vector<unsigned>& changed,std::vector<unsigned>& finished) {
if(!amount)return;
for(const auto& m:season.missions) {
if(!m.Matches(kind,what) || state.Done(m))continue;
const unsigned long long left=m.target-(state.base[m.slot]+state.delta[m.slot]);
state.delta[m.slot]+=std::min(left,amount);
changed.push_back(m.slot);
if(state.Done(m))finished.push_back(m.slot);
}
}
// Why a claim of slot (0 = final) cannot go ahead, or nullptr.
inline const char* PortBpClaimError(const PortBpSeason& season,const PortBpState& state,unsigned slot) {
if(!state.loaded)return "loading";
if(slot>kPortBpSlots)return "slot";
if(slot) {
const PortBpMission* m=season.Slot(slot);
if(!m)return "slot";
if(state.claimed.count(slot))return "claimed";
if(!state.Done(*m))return "incomplete";
if(m->rewards.empty())return "slot";
} else {
if(season.final.empty())return "slot";
if(state.claimed.count(0))return "claimed";
if(!state.AllDone(season))return "incomplete";
}
return nullptr;
}
// First-fit placement of item sizes into a bag of pages, the order CHARACTER::GetEmptyInventory searches: an item
// of size s at cell c takes c, c+width, ... c+width*(s-1), all in c's page. free is updated with the cells taken.
inline bool PortBpFit(std::vector<bool>& free,unsigned page,unsigned width,const std::vector<unsigned>& sizes,std::vector<unsigned>& cells) {
cells.clear();
for(unsigned size:sizes) {
bool placed=false;
for(unsigned c=0;c<free.size() && !placed;++c) {
if(!size || c%page+width*(size-1)>=page)continue;
bool ok=true;
for(unsigned k=0;k<size && ok;++k)ok=c+width*k<free.size() && free[c+width*k];
if(!ok)continue;
for(unsigned k=0;k<size;++k)free[c+width*k]=false;
cells.push_back(c);placed=true;
}
if(!placed)return false;
}
return true;
}
#endif
@@ -0,0 +1,10 @@
#ifndef PORT_BATTLEPASS_HOOKS_H
#define PORT_BATTLEPASS_HOOKS_H
// PORT: battle pass event hooks; defined in port_battlepass_runtime.h (cmd_general.cpp). docs/FEATURE-BATTLEPASS.md.
#include "port_battlepass.h"
class CHARACTER;
void PortBpCount(CHARACTER* ch,unsigned kind,unsigned what,unsigned long long amount); // a real event, never rate-scaled
void PortBpKill(CHARACTER* attacker,CHARACTER* victim); // CHARACTER::Reward, the quest kill attacker
void PortBpSave(CHARACTER* ch); // CHARACTER::SaveReal
void PortBpLogout(CHARACTER* ch); // CHARACTER::Disconnect, after the last save
#endif
@@ -0,0 +1,245 @@
#ifndef PORT_BATTLEPASS_RUNTIME_H
#define PORT_BATTLEPASS_RUNTIME_H
// PORT: battle pass, game side (port_battlepass.h has the config and state). Protocol: docs/FEATURE-BATTLEPASS.md.
// Included once, by cmd_general.cpp; the hooks in other files go through port_battlepass_hooks.h.
#include <map>
#include <memory>
#include <sstream>
#include <string>
#include <vector>
#include "port_battlepass_hooks.h"
static const unsigned kPortBpGapMs=300; // per-player gap between /mt_bp commands
static const unsigned kPortBpMaxStacks=24; // reward items one claim may put in the bag
static const int kPortBpKillLevelDelta=20; // AVA2: kills count only within 20 levels of the monster
inline PortBpConfig& PortBpConfigFile() {static PortBpConfig config;return config;}
inline const PortBpSeason* PortBpSeasonNow() {
PortBpConfig& config=PortBpConfigFile();
if(config.Refresh(LocaleService_GetBasePath()+"/port_battlepass.tsv",get_dword_time()) && !config.valid && config.error!="missing")
sys_err("PORT_BP: port_battlepass.tsv disabled: %s",config.error.c_str());
return config.Active(get_global_time());
}
inline std::map<DWORD,PortBpState>& PortBpStates() {static std::map<DWORD,PortBpState> states;return states;}
inline void PortBpSendRewards(std::string& line,const std::vector<PortBpReward>& rewards) {
for(const auto& r:rewards)line+=" "+std::to_string(r.vnum)+" "+std::to_string(r.count);
}
inline void PortBpSendInfo(LPCHARACTER ch,const PortBpSeason& season,PortBpState& state) {
state.watching=true;state.wantInfo=false;
ch->ChatPacket(CHAT_TYPE_COMMAND,"MTBP1 season %u %u %u %lld %u",season.id,season.start,season.end,(long long)get_global_time(),unsigned(season.missions.size()));
for(const auto& m:season.missions) {
std::string line="MTBP1 mission "+std::to_string(m.slot)+" "+std::to_string(m.type)+" "+std::to_string(m.sub)+" "+
std::to_string(m.target)+" "+std::to_string(state.Value(m))+" "+std::to_string(state.claimed.count(m.slot));
PortBpSendRewards(line,m.rewards);
ch->ChatPacket(CHAT_TYPE_COMMAND,"%s",line.c_str());
}
std::string line="MTBP1 final "+std::to_string(state.claimed.count(0))+" "+std::to_string(int(state.AllDone(season)));
PortBpSendRewards(line,season.final);
ch->ChatPacket(CHAT_TYPE_COMMAND,"%s",line.c_str());
ch->ChatPacket(CHAT_TYPE_COMMAND,"MTBP1 end");
}
// Queues the deltas as one additive, capped upsert on the game's ordered SQL connection.
inline void PortBpFlush(DWORD pid,PortBpState& state,const PortBpSeason* season) {
if(!state.season || !season || season->id!=state.season)return;
std::string values;
for(const auto& m:season->missions) {
const unsigned long long d=state.delta[m.slot];
if(!d)continue;
values+=std::string(values.empty()?"":",")+"("+std::to_string(pid)+","+std::to_string(state.season)+","+std::to_string(m.slot)+","+
std::to_string(std::min(d,m.target))+","+std::to_string(m.target)+")";
state.base[m.slot]+=d;state.delta[m.slot]=0;
if(!state.loaded)state.inflight[m.slot]+=d;
}
if(values.empty())return;
DBManager::instance().Query("INSERT INTO player.mt_battlepass_progress (pid,season,slot,value,target) VALUES %s "
"ON DUPLICATE KEY UPDATE value=LEAST(value+VALUES(value),VALUES(target)),target=VALUES(target)",values.c_str());
}
inline void PortBpLoad(DWORD pid,PortBpState& state) {
static unsigned generations=0;
state.generation=++generations;
std::fill(state.inflight,state.inflight+kPortBpSlots+1,0ULL);
const unsigned season=state.season,generation=state.generation;
DBManager::instance().FuncQuery([pid,season,generation](SQLMsg* msg) {
auto it=PortBpStates().find(pid);
if(it==PortBpStates().end() || it->second.generation!=generation || it->second.season!=season)return;
PortBpState& state=it->second;
if(!msg->Get()){sys_err("PORT_BP: load failed pid %u season %u",pid,season);return;}
unsigned long long stored[kPortBpSlots+1]={};
for(unsigned i=0;i<msg->Get()->uiNumRows;++i) {
MYSQL_ROW row=mysql_fetch_row(msg->Get()->pSQLResult);
if(!row || !row[0] || !row[1] || !row[2])continue;
const unsigned slot=unsigned(strtoul(row[1],nullptr,10));
if(slot>kPortBpSlots)continue;
if(row[0][0]=='p')state.base[slot]=(stored[slot]=strtoull(row[2],nullptr,10))+state.inflight[slot];
else state.claimed.insert(slot);
}
state.loaded=true;
LPCHARACTER ch=CHARACTER_MANAGER::instance().FindByPID(pid);
const PortBpSeason* now=PortBpConfigFile().Active(get_global_time());
if(!ch || !now || now->id!=season)return;
// PortBpNotify held back the done notices of events counted before the load; send those now.
for(const auto& m:now->missions)
if(stored[m.slot]<m.target && state.Done(m))ch->ChatPacket(CHAT_TYPE_COMMAND,"MTBP1 done %u",m.slot);
if(state.wantInfo)PortBpSendInfo(ch,*now,state);
},"SELECT 'p',slot,value FROM player.mt_battlepass_progress WHERE pid=%u AND season=%u "
"UNION ALL SELECT 'c',slot,0 FROM player.mt_battlepass_claim WHERE pid=%u AND season=%u",pid,season,pid,season);
}
inline const PortBpSeason* PortBpFindSeason(unsigned id) {
for(const auto& s:PortBpConfigFile().seasons)if(s.id==id)return &s;
return nullptr;
}
// The player's state for the active season, or nullptr when no season runs. A season change first writes what
// was counted for the old season, while its definition is still in the file, then starts a fresh load.
inline PortBpState* PortBpSync(LPCHARACTER ch,const PortBpSeason*& season) {
if(!ch || !ch->IsPC() || !ch->GetDesc())return nullptr;
season=PortBpSeasonNow();
const DWORD pid=ch->GetPlayerID();
auto& states=PortBpStates();
auto it=states.find(pid);
if(!season && it==states.end())return nullptr;
if(it==states.end()) {
it=states.emplace(pid,PortBpState()).first;
it->second.playtimeMark=get_dword_time();
}
PortBpState& state=it->second;
const unsigned id=season?season->id:0;
if(state.season!=id) {
if(state.season)PortBpFlush(pid,state,PortBpFindSeason(state.season));
const bool watching=state.watching;
state.Reset(id);state.watching=watching;
state.playtimeMark=get_dword_time();
if(id)PortBpLoad(pid,state);
}
return season?&state:nullptr;
}
inline void PortBpNotify(LPCHARACTER ch,const PortBpSeason& season,PortBpState& state,const std::vector<unsigned>& changed,const std::vector<unsigned>& finished) {
if(state.watching)
for(unsigned slot:changed)ch->ChatPacket(CHAT_TYPE_COMMAND,"MTBP1 progress %u %llu",slot,state.Value(*season.Slot(slot)));
if(!state.loaded)return; // values are not known yet; the window shows them once it is loaded
for(unsigned slot:finished)ch->ChatPacket(CHAT_TYPE_COMMAND,"MTBP1 done %u",slot);
}
inline void PortBpAccruePlaytime(LPCHARACTER ch,const PortBpSeason& season,PortBpState& state) {
const unsigned now=get_dword_time(),seconds=(now-state.playtimeMark)/1000;
if(!seconds)return;
state.playtimeMark+=seconds*1000;
if(!season.Has(PORT_BP_PLAYTIME))return;
std::vector<unsigned> changed,finished;
PortBpAdd(season,state,PORT_BP_PLAYTIME,0,seconds,changed,finished);
PortBpNotify(ch,season,state,changed,finished);
}
// Every hook calls this with a real event; amount is a count, gold or levels, never scaled by an event rate.
void PortBpCount(LPCHARACTER ch,unsigned kind,unsigned what,unsigned long long amount) {
const PortBpSeason* season=nullptr;
PortBpState* state=PortBpSync(ch,season);
if(!state || !amount || !season->Has(kind))return;
std::vector<unsigned> changed,finished;
PortBpAdd(*season,*state,kind,what,amount,changed,finished);
PortBpNotify(ch,*season,*state,changed,finished);
}
// CHARACTER::Reward: the attacker DistributeExp picked, the one the quest kill event goes to.
void PortBpKill(LPCHARACTER attacker,LPCHARACTER victim) {
if(!attacker || !victim || !attacker->IsPC() || victim->IsPC())return;
const int gap=int(victim->GetLevel())-int(attacker->GetLevel());
if(gap>kPortBpKillLevelDelta || gap<-kPortBpKillLevelDelta)return;
const unsigned kind=victim->IsStone()?PORT_BP_KILL_STONE:victim->GetMobRank()>=MOB_RANK_BOSS?PORT_BP_KILL_BOSS:PORT_BP_KILL_MONSTER;
PortBpCount(attacker,kind,victim->GetRaceNum(),1);
}
// CHARACTER::SaveReal: the periodic and logout save also writes the battle pass.
void PortBpSave(LPCHARACTER ch) {
const PortBpSeason* season=nullptr;
PortBpState* state=PortBpSync(ch,season);
if(!state)return;
PortBpAccruePlaytime(ch,*season,*state);
PortBpFlush(ch->GetPlayerID(),*state,season);
}
// CHARACTER::Disconnect, after the last save.
void PortBpLogout(LPCHARACTER ch) {
if(ch && ch->IsPC())PortBpStates().erase(ch->GetPlayerID());
}
struct PortBpStack {unsigned vnum,count,size;};
inline const char* PortBpStacks(const std::vector<PortBpReward>& rewards,std::vector<PortBpStack>& stacks) {
stacks.clear();
for(const auto& r:rewards) {
const TItemTable* table=ITEM_MANAGER::instance().GetTable(r.vnum);
if(!table || table->bType==ITEM_DS || !table->bSize || table->bSize>3)return "config";
const bool stackable=IS_SET(table->dwFlags,ITEM_FLAG_STACKABLE) && !IS_SET(table->dwAntiFlags,ITEM_ANTIFLAG_STACK);
for(unsigned left=r.count;left;) {
const unsigned count=stackable?std::min<unsigned>(left,ITEM_MAX_COUNT):1;
stacks.push_back(PortBpStack{r.vnum,count,table->bSize});left-=count;
if(stacks.size()>kPortBpMaxStacks)return "config";
}
}
return nullptr;
}
// /mt_bp 1 claim SLOT. The claim row is written first and synchronously; only the request that inserted it hands
// out the items, into cells checked free beforehand, so retries, double clicks and other cores cannot pay twice.
inline void PortBpClaim(LPCHARACTER ch,const PortBpSeason& season,PortBpState& state,unsigned slot) {
if(const char* error=PortBpClaimError(season,state,slot)){ch->ChatPacket(CHAT_TYPE_COMMAND,"MTBP1 error %s",error);return;}
const std::vector<PortBpReward>& rewards=slot?season.Slot(slot)->rewards:season.final;
std::vector<PortBpStack> stacks;
if(const char* error=PortBpStacks(rewards,stacks)){
sys_err("PORT_BP: season %u slot %u has a reward that cannot go to the bag",season.id,slot);
ch->ChatPacket(CHAT_TYPE_COMMAND,"MTBP1 error %s",error);return;
}
std::vector<bool> free(INVENTORY_MAX_NUM);
for(unsigned c=0;c<INVENTORY_MAX_NUM;++c)free[c]=ch->IsEmptyItemGrid(TItemPos(INVENTORY,c),1);
std::vector<unsigned> sizes,cells;
for(const auto& s:stacks)sizes.push_back(s.size);
if(!PortBpFit(free,INVENTORY_PAGE_SIZE,5,sizes,cells)){ch->ChatPacket(CHAT_TYPE_COMMAND,"MTBP1 error space");return;}
const DWORD pid=ch->GetPlayerID();
std::unique_ptr<SQLMsg> msg(DBManager::instance().DirectQuery(
"INSERT IGNORE INTO player.mt_battlepass_claim (pid,season,slot,claimed_at) VALUES (%u,%u,%u,%lld)",pid,season.id,slot,(long long)get_global_time()));
if(!msg || !msg->Get()){sys_err("PORT_BP: claim insert failed pid %u season %u slot %u",pid,season.id,slot);ch->ChatPacket(CHAT_TYPE_COMMAND,"MTBP1 error db");return;}
state.claimed.insert(slot);
if(msg->Get()->uiAffectedRows!=1){ch->ChatPacket(CHAT_TYPE_COMMAND,"MTBP1 error claimed");return;}
const std::string hint=std::to_string(season.id)+" "+std::to_string(slot);
for(size_t i=0;i<stacks.size();++i) {
LPITEM item=ITEM_MANAGER::instance().CreateItem(stacks[i].vnum,stacks[i].count);
if(!item){sys_err("PORT_BP: cannot create %u x%u for pid %u season %u slot %u",stacks[i].vnum,stacks[i].count,pid,season.id,slot);continue;}
item->AddToCharacter(ch,TItemPos(INVENTORY,cells[i]));
ITEM_MANAGER::instance().FlushDelayedSave(item);
LogManager::instance().ItemLog(ch,item,"MT_BP_CLAIM",hint.c_str());
}
sys_log(0,"PORT_BP: %s claimed season %u slot %u (%u stacks)",ch->GetName(),season.id,slot,unsigned(stacks.size()));
ch->ChatPacket(CHAT_TYPE_COMMAND,"MTBP1 claimed %u",slot);
ch->Save();
}
// /mt_bp 1 info | /mt_bp 1 claim SLOT | /mt_bp 1 close
inline void PortBpCommand(LPCHARACTER ch,const char* argument) {
std::istringstream input(argument);std::vector<std::string> args;std::string token;
while(input>>token){if(token.size()>10 || args.size()>=3)return;args.push_back(token);}
if(args.empty() || args[0]!="1")return;
const PortBpSeason* season=nullptr;
PortBpState* state=PortBpSync(ch,season);
const bool info=args.size()==2 && args[1]=="info",close=args.size()==2 && args[1]=="close";
const bool claim=args.size()==3 && args[1]=="claim" && args[2].size()<=2 && args[2].find_first_not_of("0123456789")==std::string::npos;
if(!info && !close && !claim){ch->ChatPacket(CHAT_TYPE_COMMAND,"MTBP1 error invalid");return;}
if(!state){if(!close)ch->ChatPacket(CHAT_TYPE_COMMAND,"MTBP1 none");return;}
if(close){state->watching=false;return;}
if(state->lastCommand && get_dword_time()-state->lastCommand<kPortBpGapMs){ch->ChatPacket(CHAT_TYPE_COMMAND,"MTBP1 error rate");return;}
state->lastCommand=get_dword_time();
PortBpAccruePlaytime(ch,*season,*state);
if(info) {
if(state->loaded)PortBpSendInfo(ch,*season,*state);
else {state->wantInfo=true;state->watching=true;}
return;
}
PortBpClaim(ch,*season,*state,unsigned(atoi(args[2].c_str())));
if(state->loaded)PortBpSendInfo(ch,*season,*state);
}
#endif
+103
View File
@@ -0,0 +1,103 @@
#ifndef METIN2_PORT_PREMIUM_H
#define METIN2_PORT_PREMIUM_H
// PORT: VIP card. Using card 38001 (7 days) or 38002 (30 days) extends all seven premium services of the account
// (account.account *_expire) from the later of now and their current end. The original server reads these columns
// only when auth logs the account in, and the db core hands those login-time values to every later player load
// (CLoginData), so after a card and on every enter-game the game re-reads them and updates m_aiPremiumTimes and the
// AFFECT_PREMIUM_START+i icons. Protocol: docs/FEATURE-VIP.md.
#include <cstdlib>
#include <map>
#include <sstream>
#include <string>
#include <vector>
static const int kPortVipTypes=7; // PREMIUM_EXP .. PREMIUM_GOLD, in account column order
static const char* const kPortVipColumns[kPortVipTypes]={"silver_expire","gold_expire","safebox_expire",
"autoloot_expire","fish_mind_expire","marriage_fast_expire","money_drop_rate_expire"};
static const DWORD kPortVipCards[][2]={{38001,7},{38002,30}};
static const int kPortVipMaxDays=400; // remaining time a card may reach, far from the 2038 limit of the int times
static const DWORD kPortVipGapMs=1000;
inline int PortVipCardDays(DWORD vnum) {
for(const auto& card:kPortVipCards)if(card[0]==vnum)return int(card[1]);
return 0;
}
// One throttle per player id for card use and status requests: both queue a query whose answer updates memory.
inline bool PortVipThrottled(LPCHARACTER ch) {
static std::map<DWORD,DWORD> last;
DWORD& at=last[ch->GetPlayerID()];
if(at && get_dword_time()-at<kPortVipGapMs)return true;
at=get_dword_time();
return false;
}
// The account's end times (unix seconds) are the truth: premium state, icons, and on request the client.
inline void PortVipApply(LPCHARACTER ch,const int* times,bool report) {
const int now=get_global_time();
std::string line="MTVIP1 times";
for(int i=0;i<kPortVipTypes;++i) {
const int remain=times[i]-now;
if(times[i]!=ch->GetPremiumRemainSeconds(i)+now) {
ch->PortSetPremiumTime(i,times[i]);
if(remain>0)ch->AddAffect(AFFECT_PREMIUM_START+i,POINT_NONE,0,0,remain,0,true);
else ch->RemoveAffect(AFFECT_PREMIUM_START+i);
sys_log(0,"PORT_VIP: %s type %d end %d",ch->GetName(),i,times[i]);
}
line+=" "+std::to_string(remain>0?remain:0);
}
if(report)ch->ChatPacket(CHAT_TYPE_COMMAND,"%s",line.c_str());
}
inline void PortVipRefresh(LPCHARACTER ch,bool report) {
if(!ch->GetDesc())return;
const DWORD pid=ch->GetPlayerID(),account=ch->GetDesc()->GetAccountTable().id;
std::string columns;
for(int i=0;i<kPortVipTypes;++i)columns+=std::string(i?",":"")+"UNIX_TIMESTAMP("+kPortVipColumns[i]+")";
DBManager::instance().FuncQuery([pid,account,report](SQLMsg* msg) {
LPCHARACTER ch=CHARACTER_MANAGER::instance().FindByPID(pid);
if(!ch || !ch->GetDesc() || ch->GetDesc()->GetAccountTable().id!=account)return;
if(!msg->Get() || msg->Get()->uiNumRows!=1){sys_err("PORT_VIP: account %u not found",account);return;}
MYSQL_ROW row=mysql_fetch_row(msg->Get()->pSQLResult);
int times[kPortVipTypes];
for(int i=0;i<kPortVipTypes;++i)times[i]=row[i]?atoi(row[i]):0;
PortVipApply(ch,times,report);
},"SELECT %s FROM account.account WHERE id=%u",columns.c_str(),account);
}
// Called by CHARACTER::UseItem before the original item handling: true when the item is a VIP card, used or not.
inline bool PortVipUseCard(LPCHARACTER ch,LPITEM item) {
const int days=PortVipCardDays(item->GetVnum());
if(!days)return false;
if(!ch->IsPC() || !ch->GetDesc())return true;
if(PortVipThrottled(ch)){ch->ChatPacket(CHAT_TYPE_COMMAND,"MTVIP1 error rate");return true;}
for(int i=0;i<kPortVipTypes;++i) {
const int remain=ch->GetPremiumRemainSeconds(i);
if((remain>0?remain:0)+days*86400>kPortVipMaxDays*86400){ch->ChatPacket(CHAT_TYPE_COMMAND,"MTVIP1 error full");return true;}
}
const DWORD vnum=item->GetVnum(),account=ch->GetDesc()->GetAccountTable().id;
std::string sets;
for(int i=0;i<kPortVipTypes;++i) {
const std::string column=kPortVipColumns[i];
sets+=(i?",":"")+column+"=FROM_UNIXTIME(GREATEST(UNIX_TIMESTAMP("+column+"),UNIX_TIMESTAMP())+"+
std::to_string(days*86400)+")";
}
LogManager::instance().ItemLog(ch,item,"MT_VIP_CARD",std::to_string(days).c_str());
item->SetCount(item->GetCount()-1);
// Same connection as the refresh, which therefore reads the updated row.
DBManager::instance().Query("UPDATE account.account SET %s WHERE id=%u",sets.c_str(),account);
ch->ChatPacket(CHAT_TYPE_COMMAND,"MTVIP1 added %u %d",unsigned(vnum),days);
PortVipRefresh(ch,true);
return true;
}
// /mt_vip 1 status -> MTVIP1 times (seven remaining seconds, PREMIUM_EXP .. PREMIUM_GOLD)
inline void PortVipCommand(LPCHARACTER ch,const char* argument) {
std::istringstream input(argument);std::vector<std::string> args;std::string token;
while(input>>token){if(token.size()>10 || args.size()>=3)return;args.push_back(token);}
if(args.empty() || args[0]!="1")return;
if(args.size()!=2 || args[1]!="status"){ch->ChatPacket(CHAT_TYPE_COMMAND,"MTVIP1 error invalid");return;}
if(PortVipThrottled(ch)){ch->ChatPacket(CHAT_TYPE_COMMAND,"MTVIP1 error rate");return;}
PortVipRefresh(ch,true);
}
#endif
+3
View File
@@ -19,6 +19,7 @@
#include "mob_manager.h"
#include "locale_service.h"
#include "unique_item.h"
#include "port_battlepass_hooks.h"
// MT: the sockets ITEM_MANAGER::CreateItem gives a new item of this vnum (its remaining time), sent
// with an NPC shop's items so the client tooltip shows how long a bought one lasts instead of 0.
@@ -341,6 +342,8 @@ int CShop::Buy(LPCHARACTER ch, BYTE pos)
}
ch->PointChange(POINT_GOLD, -dwPrice, false);
if (!m_pkPC)
PortBpCount(ch, PORT_BP_NPC_SPEND, 0, dwPrice); // PORT: battle pass, NPC shops only
//¼¼±Ý °è»ê
DWORD dwTax = 0;
+2
View File
@@ -25,6 +25,7 @@
#include <boost/algorithm/string/predicate.hpp>
#include "shop_manager.h"
#include <cctype>
#include "port_battlepass_hooks.h"
CShopManager::CShopManager()
{
@@ -347,6 +348,7 @@ void CShopManager::Sell(LPCHARACTER ch, BYTE bCell, BYTE bCount)
ch->ChatPacket(CHAT_TYPE_INFO, LC_TEXT("판매금액의 %d %% 가 세금으로 나가게됩니다"), iVal);
DBManager::instance().SendMoneyLog(MONEY_LOG_SHOP, item->GetVnum(), dwPrice);
PortBpCount(ch, PORT_BP_NPC_SELL, item->GetVnum(), bCount); // PORT: battle pass
if (bCount == item->GetCount())
{
+272
View File
@@ -0,0 +1,272 @@
#!/usr/bin/env python3
"""Battle pass: the wiring of the hooks, then the production headers compiled against stubs of the characters,
the bag, the item table and an in-memory player database (ordered async queue plus synchronous direct queries)."""
from pathlib import Path
import subprocess
import tempfile
ROOT=Path(__file__).resolve().parents[2]
SRC=ROOT/'src/server/game/src'
TSV=ROOT/'tools/battlepass/port_battlepass.tsv'
def source(name):return (SRC/name).read_bytes().decode('latin1')
cmd=source('cmd.cpp')
assert 'ACMD(do_port_bp);' in cmd
entry=cmd.index('{ "mt_bp", do_port_bp, 0, POS_DEAD, GM_PLAYER },')
assert entry<cmd.index('{ "\\n",',entry) and cmd.count('"mt_bp"')==1
general=source('cmd_general.cpp')
assert '#include "port_battlepass_runtime.h"' in general and 'PortBpCommand(ch, argument);' in general
for name in ('char.cpp','char_battle.cpp','char_item.cpp','fishing.cpp','shop.cpp','shop_manager.cpp'):
assert '#include "port_battlepass_hooks.h"' in source(name),name
assert '#include "port_battlepass_runtime.h"' not in source(name),name
battle=source('char_battle.cpp')
reward=battle.index('void CHARACTER::Reward(bool bItemDrop)')
assert reward<battle.index('PortBpKill(pkAttacker, this);')<battle.index('quest::CQuestManager::instance().Kill(pkAttacker->GetPlayerID(), GetRaceNum());',reward)
assert battle.count('PortBpKill(')==1
item=source('char_item.cpp')
assert item.count('PortBpCount(this, PORT_BP_REFINE, pkNewItem->GetVnum(), 1);')==2==item.count('"REFINE SUCCESS"')
assert '#endif\n#include "port_premium.h"\n#include "port_battlepass_hooks.h"\n' in item # outside __AUCTION__
fishing=source('fishing.cpp')
assert fishing.index('FishingSuccess(ch);\n\t\t\t\t\tPortBpCount(ch, PORT_BP_CATCH_FISH, item_vnum, 1);')>fishing.index('void Take(')
shop=source('shop.cpp')
assert 'ch->PointChange(POINT_GOLD, -dwPrice, false);\n\tif (!m_pkPC)\n\t\tPortBpCount(ch, PORT_BP_NPC_SPEND, 0, dwPrice);' in shop
sell=source('shop_manager.cpp')
assert sell.index('void CShopManager::Sell(')<sell.index('PortBpCount(ch, PORT_BP_NPC_SELL, item->GetVnum(), bCount);')
char=source('char.cpp')
save=char.index('void CHARACTER::SaveReal()')
assert save<char.index('PortBpSave(this);')<char.index('void CHARACTER::FlushDelayedSaveItem()')
disc=char.index('void CHARACTER::Disconnect(')
assert char.index('SaveAffect();',disc)<char.index('PortBpLogout(this);',disc)<char.index('m_bSkipSave = true;',disc)
level=char.index('case POINT_LEVEL:')
assert level<char.index('PortBpCount(this, PORT_BP_LEVEL_UP, 0, amount);',level)<char.index('quest::CQuestManager::instance().LevelUp(GetPlayerID());',level)
code=r'''
#include <cassert>
#include <cstdarg>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <deque>
#include <functional>
#include <map>
#include <set>
#include <string>
#include <tuple>
#include <vector>
using DWORD=unsigned;using BYTE=unsigned char;using WORD=unsigned short;
enum {CHAT_TYPE_INFO=1,CHAT_TYPE_COMMAND=5,MOB_RANK_BOSS=4,ITEM_DS=29,ITEM_FLAG_STACKABLE=1<<2,ITEM_ANTIFLAG_STACK=1<<15,
ITEM_MAX_COUNT=200,INVENTORY=1,INVENTORY_PAGE_SIZE=45,INVENTORY_MAX_NUM=225};
#define IS_SET(flag,bit) ((flag)&(bit))
static long long now=1790900000;static DWORD clockms=1000;
long long get_global_time(){return now;}DWORD get_dword_time(){return clockms;}
static std::string basePath;std::string LocaleService_GetBasePath(){return basePath;}
static std::vector<std::string> logs;
void sys_log(int,const char* f,...){char o[1024];va_list a;va_start(a,f);vsnprintf(o,sizeof(o),f,a);va_end(a);logs.push_back(o);}
void sys_err(const char* f,...){char o[1024];va_list a;va_start(a,f);vsnprintf(o,sizeof(o),f,a);va_end(a);logs.push_back(std::string("ERR ")+o);}
static std::string format(const char* f,va_list a){char o[8192];vsnprintf(o,sizeof(o),f,a);return o;}
struct TItemPos{BYTE window_type;WORD cell;TItemPos(BYTE w,WORD c):window_type(w),cell(c){}};
struct TItemTable{BYTE bType,bSize;DWORD dwFlags,dwAntiFlags;};
// --- player database
static std::map<std::tuple<DWORD,DWORD,DWORD>,std::pair<unsigned long long,unsigned long long>> progress; // value,target
static std::set<std::tuple<DWORD,DWORD,DWORD>> claims;
static bool dbDown=false;
using MYSQL_ROW=char**;
struct Result{std::vector<std::vector<std::string>> rows;size_t next=0;std::vector<char*> cells;};
struct SQLResult{unsigned uiNumRows=0,uiAffectedRows=0;Result* pSQLResult=nullptr;};
struct SQLMsg{SQLResult result;Result data;bool ok=true;SQLResult* Get(){return ok?&result:nullptr;}};
MYSQL_ROW mysql_fetch_row(Result* r){
if(r->next>=r->rows.size())return nullptr;auto& row=r->rows[r->next++];r->cells.clear();
for(auto& c:row)r->cells.push_back(&c[0]);return r->cells.data();}
static int selects=0;
struct DBManager{
std::deque<std::function<void()>> queue;std::vector<std::string> queries;
static DBManager& instance(){static DBManager m;return m;}
void Query(const char* f,...){va_list a;va_start(a,f);std::string q=format(f,a);va_end(a);queries.push_back(q);
queue.push_back([q]{
assert(q.rfind("INSERT INTO player.mt_battlepass_progress (pid,season,slot,value,target) VALUES (",0)==0);
assert(q.find("ON DUPLICATE KEY UPDATE value=LEAST(value+VALUES(value),VALUES(target)),target=VALUES(target)")!=std::string::npos);
const char* p=q.c_str()+q.find("VALUES (")+7;unsigned pid,season,slot;unsigned long long v,t;int n;
while(sscanf(p,"(%u,%u,%u,%llu,%llu)%n",&pid,&season,&slot,&v,&t,&n)==5){
auto& row=progress[std::make_tuple(pid,season,slot)];row.first=std::min(row.first+v,t);row.second=t;p+=n;if(*p==',')++p;else break;}
});}
template<class F> void FuncQuery(F f,const char* fmt,...){va_list a;va_start(a,fmt);std::string q=format(fmt,a);va_end(a);queries.push_back(q);++selects;
queue.push_back([f,q]{unsigned pid,season,pid2,season2;
assert(sscanf(q.c_str(),"SELECT 'p',slot,value FROM player.mt_battlepass_progress WHERE pid=%u AND season=%u "
"UNION ALL SELECT 'c',slot,0 FROM player.mt_battlepass_claim WHERE pid=%u AND season=%u",&pid,&season,&pid2,&season2)==4);
assert(pid==pid2 && season==season2);
SQLMsg m;m.ok=!dbDown;m.result.pSQLResult=&m.data;
for(auto& e:progress)if(std::get<0>(e.first)==pid && std::get<1>(e.first)==season)
m.data.rows.push_back({"p",std::to_string(std::get<2>(e.first)),std::to_string(e.second.first)});
for(auto& e:claims)if(std::get<0>(e)==pid && std::get<1>(e)==season)m.data.rows.push_back({"c",std::to_string(std::get<2>(e)),"0"});
m.result.uiNumRows=unsigned(m.data.rows.size());f(&m);});}
SQLMsg* DirectQuery(const char* f,...){va_list a;va_start(a,f);std::string q=format(f,a);va_end(a);queries.push_back(q);
SQLMsg* m=new SQLMsg;m->ok=!dbDown;unsigned pid,season,slot;long long at;
assert(sscanf(q.c_str(),"INSERT IGNORE INTO player.mt_battlepass_claim (pid,season,slot,claimed_at) VALUES (%u,%u,%u,%lld)",&pid,&season,&slot,&at)==4 && at==now);
if(m->ok)m->result.uiAffectedRows=claims.insert(std::make_tuple(pid,season,slot)).second?1:0;
return m;}
void Run(){while(!queue.empty()){auto job=queue.front();queue.pop_front();job();}}
};
// --- characters, bag and items
class CHARACTER;
struct CItem{DWORD vnum,count;CHARACTER* owner=nullptr;unsigned cell=0;bool AddToCharacter(CHARACTER* ch,TItemPos pos);DWORD GetVnum(){return vnum;}};
using LPITEM=CItem*;
struct DESC{};
class CHARACTER{public:
DESC desc;bool online=true,pc=true,stone=false;DWORD pid=7,race=101;int level=50;BYTE rank=0;int saves=0;
std::vector<std::string> messages;std::vector<bool> used=std::vector<bool>(INVENTORY_MAX_NUM,false);std::vector<CItem*> bag;
const char* GetName(){return "Admin";}bool IsPC(){return pc;}DESC* GetDesc(){return online?&desc:nullptr;}DWORD GetPlayerID(){return pid;}
int GetLevel(){return level;}bool IsStone(){return stone;}BYTE GetMobRank(){return rank;}DWORD GetRaceNum(){return race;}
bool IsEmptyItemGrid(TItemPos p,BYTE size){assert(p.window_type==INVENTORY && size==1);return !used[p.cell];}
void Save(){++saves;}
void ChatPacket(BYTE type,const char* f,...){va_list a;va_start(a,f);std::string s=format(f,a);va_end(a);assert(type==CHAT_TYPE_COMMAND);messages.push_back(s);}
};
using LPCHARACTER=CHARACTER*;
static std::map<DWORD,TItemTable> tables={{70043,{1,1,0,0}},{71153,{3,1,ITEM_FLAG_STACKABLE,0}},{25041,{3,1,ITEM_FLAG_STACKABLE,0}},
{71032,{3,1,ITEM_FLAG_STACKABLE,0}},{50513,{3,1,ITEM_FLAG_STACKABLE,0}},{27992,{3,1,ITEM_FLAG_STACKABLE,0}},{27993,{3,1,ITEM_FLAG_STACKABLE,0}},
{27994,{3,1,ITEM_FLAG_STACKABLE,0}},{70024,{3,1,ITEM_FLAG_STACKABLE,0}},{19,{1,2,0,0}},{11299,{2,3,0,0}},{110000,{ITEM_DS,1,0,0}},
{71084,{3,1,ITEM_FLAG_STACKABLE,ITEM_ANTIFLAG_STACK}},{71094,{3,1,ITEM_FLAG_STACKABLE,0}},{27987,{3,1,ITEM_FLAG_STACKABLE,0}},
{25040,{3,1,ITEM_FLAG_STACKABLE,0}}};
bool CItem::AddToCharacter(CHARACTER* ch,TItemPos pos){
const unsigned size=tables[vnum].bSize;
for(unsigned k=0;k<size;++k){assert(pos.cell+5*k<INVENTORY_MAX_NUM && !ch->used[pos.cell+5*k]);ch->used[pos.cell+5*k]=true;}
assert(pos.cell/45==(pos.cell+5*(size-1))/45);owner=ch;cell=pos.cell;ch->bag.push_back(this);return true;}
static int flushedItems=0;
struct ITEM_MANAGER{static ITEM_MANAGER& instance(){static ITEM_MANAGER m;return m;}
TItemTable* GetTable(DWORD v){auto it=tables.find(v);return it==tables.end()?nullptr:&it->second;}
LPITEM CreateItem(DWORD v,DWORD c){return new CItem{v,c};}
void FlushDelayedSave(LPITEM){++flushedItems;}};
static std::vector<std::string> itemlog;
struct LogManager{static LogManager& instance(){static LogManager m;return m;}
void ItemLog(LPCHARACTER,LPITEM item,const char* what,const char* hint){itemlog.push_back(std::string(what)+" "+std::to_string(item->vnum)+"x"+std::to_string(item->count)+" "+hint);}};
static std::map<DWORD,CHARACTER*> online;
struct CHARACTER_MANAGER{static CHARACTER_MANAGER& instance(){static CHARACTER_MANAGER m;return m;}
LPCHARACTER FindByPID(DWORD pid){auto it=online.find(pid);return it==online.end()?nullptr:it->second;}};
#include "port_battlepass_runtime.h"
#include <fstream>
#include <sstream>
static DBManager& db=DBManager::instance();
static void tick(unsigned ms=1000){clockms+=ms;}
static std::string Last(CHARACTER* c){return c->messages.empty()?"":c->messages.back();}
static bool Said(CHARACTER* c,const std::string& line,size_t from=0){for(size_t i=from;i<c->messages.size();++i)if(c->messages[i]==line)return true;return false;}
static void WriteConfig(const std::string& text){std::ofstream(basePath+"/port_battlepass.tsv.tmp")<<text;
std::rename((basePath+"/port_battlepass.tsv.tmp").c_str(),(basePath+"/port_battlepass.tsv").c_str());tick(5001);}
static void Kill(CHARACTER* a,DWORD race,BYTE rank=0,bool stone=false,int level=50){CHARACTER m;m.pc=false;m.race=race;m.rank=rank;m.stone=stone;m.level=level;PortBpKill(a,&m);}
static bool Parses(const std::string& text){PortBpConfig c;std::istringstream in(text);return c.Parse(in);}
int main(int argc,char** argv){
basePath=argv[1];
// --- the shipped config
{PortBpConfig c;std::ifstream in(argv[2]);assert(c.Parse(in));assert(c.seasons.size()==3 && c.seasons[0].id==202610);
for(auto& s:c.seasons){assert(s.missions.size()==8 && s.final.size()==4);for(auto& m:s.missions)for(auto& r:m.rewards)assert(tables.count(r.vnum));
for(auto& r:s.final)assert(tables.count(r.vnum));}
assert(c.seasons[0].end==c.seasons[1].start && c.Active(1790805600)==&c.seasons[0] && !c.Active(1790805599));}
// --- config validation: any bad line disables the whole file
const std::string H="MTBATTLEPASS 1\nseason 1 100 200\n";
assert(Parses(H+"mission 1 1 0 10\n") && Parses(H+"mission 1 9 27992 10 1 1\nfinal 1 1\n"));
for(auto bad:{"mission 1 9 0 10\n","mission 1 4 5 10\n","mission 11 1 0 10\n","mission 1 1 0 10\nmission 1 2 0 10\n","mission 1 1 0 10 1 1 2 2 3 3 4 4\n",
"mission 1 1 0 10\nfinal 1 1\nfinal 1 1\n","mission 1 1 0 0\n","mission 1 10 0 10\n","mission 1 1 0 10\nbogus\n","mission 1 1 0 10 5\n",
"mission 1 1 0 10 5 0\n","mission 1 1 0 x\n","mission 1 1 0 10\nfinal\n"})assert(!Parses(H+bad));
assert(!Parses("MTBATTLEPASS 2\n") && !Parses(H) && !Parses("MTBATTLEPASS 1\nmission 1 1 0 10\n"));
assert(!Parses(H+"mission 1 1 0 10\nseason 2 150 300\nmission 1 1 0 10\n") && Parses(H+"mission 1 1 0 10\nseason 2 200 300\nmission 1 1 0 10\n"));
// --- bag fit: first fit in GetEmptyInventory order, a tall item stays inside its page
{std::vector<bool> free(90,true);std::vector<unsigned> cells;
for(unsigned c=0;c<45;++c)if(c<40)free[c]=false; // first page: only its last row (40..44) is free
assert(PortBpFit(free,45,5,{1,3,1},cells) && cells==std::vector<unsigned>({40,45,41}));
std::vector<bool> none(45,false);none[44]=true;assert(!PortBpFit(none,45,5,{2},cells));}
// --- no file: no season
CHARACTER* a=new CHARACTER;online[7]=a;
PortBpCommand(a,"1 info");assert(Last(a)=="MTBP1 none");Kill(a,101);db.Run();assert(progress.empty() && PortBpStates().empty());
// --- a season running now with small targets
const std::string cfg="MTBATTLEPASS 1\nseason 77 "+std::to_string(now-100)+" "+std::to_string(now+100000)+"\n"
"mission 1 1 0 5 70043 1 71153 450\nmission 2 2 0 2 25041 2\nmission 3 3 0 1 11299 1\nmission 4 4 0 3600 71032 1\n"
"mission 5 1 2493 2 19 3\nmission 6 7 0 2 110000 1\nfinal 27992 2 27993 1 27994 1 70024 1\n"
"season 78 "+std::to_string(now+100000)+" "+std::to_string(now+200000)+"\nmission 1 1 0 5 70043 1\n";
WriteConfig(cfg);
// info before the load answers once it arrives; counting before the load is kept
PortBpCommand(a,"1 info");assert(a->messages.size()==1 && PortBpStates()[7].wantInfo);
Kill(a,101);Kill(a,101);
db.Run();assert(Said(a,"MTBP1 season 77 "+std::to_string(now-100)+" "+std::to_string(now+100000)+" "+std::to_string(now)+" 6"));
assert(Said(a,"MTBP1 mission 1 1 0 5 2 0 70043 1 71153 450") && Said(a,"MTBP1 final 0 0 27992 2 27993 1 27994 1 70024 1") && Last(a)=="MTBP1 end");
// kill kinds: normal / boss / stone / level gap / specific vnum / a player victim
size_t mark=a->messages.size();
Kill(a,101);assert(Last(a)=="MTBP1 progress 1 3");
Kill(a,691,MOB_RANK_BOSS);assert(Last(a)=="MTBP1 progress 2 1");
Kill(a,8001,0,true);assert(Said(a,"MTBP1 progress 3 1",mark) && Last(a)=="MTBP1 done 3");
Kill(a,101,0,false,71);Kill(a,101,0,false,29);assert(PortBpStates()[7].Value(*PortBpConfigFile().seasons[0].Slot(1))==3);
Kill(a,101,0,false,70);assert(Last(a)=="MTBP1 progress 1 4");
Kill(a,2493,MOB_RANK_BOSS);assert(Said(a,"MTBP1 progress 2 2",mark) && Last(a)=="MTBP1 done 2" && !Said(a,"MTBP1 progress 5 1",mark));
{CHARACTER pc;pc.pid=8;PortBpKill(a,&pc);CHARACTER mob;mob.pc=false;PortBpKill(&mob,a);}
// a boss of the specific vnum counts for slot 5 only through its own kind: slot 5 is "kill monster 2493"
assert(PortBpStates()[7].Value(*PortBpConfigFile().seasons[0].Slot(5))==0);
// close stops the progress pushes; a finished mission is still announced
PortBpCommand(a,"1 close");mark=a->messages.size();Kill(a,101);assert(Last(a)=="MTBP1 done 1" && a->messages.size()==mark+1);
// 2493 counts for its own slot (any-monster slot 1 is full already)
mark=a->messages.size();Kill(a,2493);Kill(a,2493);Kill(a,2493);
assert(PortBpStates()[7].Value(*PortBpConfigFile().seasons[0].Slot(5))==2 && a->messages.size()==mark+1 && Last(a)=="MTBP1 done 5");
// --- save writes deltas additively, capped in the database
a->saves=0;PortBpSave(a);db.Run();
assert(progress[std::make_tuple(7u,77u,1u)].first==5 && progress[std::make_tuple(7u,77u,2u)].first==2 && progress[std::make_tuple(7u,77u,3u)].first==1);
const size_t queries=db.queries.size();PortBpSave(a);db.Run();assert(db.queries.size()==queries); // nothing new, no query
// play time: an hour online
tick(3600*1000);PortBpSave(a);db.Run();assert(progress[std::make_tuple(7u,77u,4u)].first==3600);
// --- claims
tick();PortBpCommand(a,"1 claim 6");assert(Said(a,"MTBP1 error incomplete"));
tick();PortBpCommand(a,"1 claim 1");
assert(Said(a,"MTBP1 claimed 1") && claims.count(std::make_tuple(7u,77u,1u)) && a->bag.size()==1+3); // 70043 + 200,200,50
assert(a->bag[1]->vnum==71153 && a->bag[1]->count==200 && a->bag[3]->count==50 && itemlog.back()=="MT_BP_CLAIM 71153x50 77 1" && flushedItems==4);
assert(Said(a,"MTBP1 mission 1 1 0 5 5 1 70043 1 71153 450"));
PortBpCommand(a,"1 claim 1");assert(Last(a)=="MTBP1 error rate");
tick();PortBpCommand(a,"1 claim 1");assert(Said(a,"MTBP1 error claimed") && a->bag.size()==4);
// another core already paid slot 2: the insert finds the row and nothing is given
claims.insert(std::make_tuple(7u,77u,2u));tick();PortBpCommand(a,"1 claim 2");assert(Said(a,"MTBP1 error claimed") && a->bag.size()==4);
// the database is down: no items
dbDown=true;tick();PortBpCommand(a,"1 claim 3");assert(Said(a,"MTBP1 error db") && a->bag.size()==4);dbDown=false;
claims.erase(std::make_tuple(7u,77u,3u));PortBpStates()[7].claimed.erase(3);
// full bag: the size-3 armor does not fit, no claim row
for(unsigned c=0;c<INVENTORY_MAX_NUM;++c)if(c%45<35)a->used[c]=true;
tick();PortBpCommand(a,"1 claim 3");assert(Said(a,"MTBP1 error space") && !claims.count(std::make_tuple(7u,77u,3u)));
for(unsigned c=0;c<INVENTORY_MAX_NUM;++c)if(c%45<35 && c>=45)a->used[c]=false;
tick();PortBpCommand(a,"1 claim 3");assert(Said(a,"MTBP1 claimed 3") && a->bag.back()->vnum==11299 && a->bag.back()->cell==45);
// a dragon soul stone in the config is refused at claim time (and logged), the slot stays claimable
{PortBpState& s=PortBpStates()[7];s.delta[6]=2;}
tick();PortBpCommand(a,"1 claim 6");assert(Said(a,"MTBP1 error config") && !claims.count(std::make_tuple(7u,77u,6u)));
assert(logs.back()=="ERR PORT_BP: season 77 slot 6 has a reward that cannot go to the bag");
// the final reward needs every mission
tick();PortBpCommand(a,"1 claim 0");assert(Said(a,"MTBP1 error incomplete"));
tick();PortBpCommand(a,"1 claim 11");assert(Said(a,"MTBP1 error slot"));
for(auto bad:{"1 claim","1 claim x","1 claim 123","1 open"}){tick();mark=a->messages.size();PortBpCommand(a,bad);assert(a->messages.size()==mark+1 && Last(a)=="MTBP1 error invalid");}
mark=a->messages.size();PortBpCommand(a,"2 info");PortBpCommand(a,"1 a b c");PortBpCommand(a,"1 claim 1 2");PortBpCommand(a,"1 claim 12345678901");assert(a->messages.size()==mark);
{PortBpState& s=PortBpStates()[7];for(unsigned i=1;i<=6;++i)s.delta[i]+=100000;} // everything done
tick();PortBpCommand(a,"1 claim 0");assert(Said(a,"MTBP1 claimed 0") && Said(a,"MTBP1 final 1 1 27992 2 27993 1 27994 1 70024 1"));
// --- logout writes and forgets; a new session loads the claims
PortBpSave(a);PortBpLogout(a);db.Run();assert(!PortBpStates().count(7) && progress[std::make_tuple(7u,77u,6u)].first==2);
assert(progress[std::make_tuple(7u,77u,4u)].first==3600);
tick();mark=a->messages.size();PortBpCommand(a,"1 info");db.Run();
assert(Said(a,"MTBP1 mission 1 1 0 5 5 1 70043 1 71153 450",mark) && Said(a,"MTBP1 mission 3 3 0 1 1 1 11299 1",mark) && Said(a,"MTBP1 final 1 1 27992 2 27993 1 27994 1 70024 1",mark));
// --- a flush queued before the load answers is not counted twice
CHARACTER* b=new CHARACTER;b->pid=9;online[9]=b;
progress[std::make_tuple(9u,77u,1u)]={2,5};
Kill(b,101);PortBpSave(b);Kill(b,101);db.Run();
assert(progress[std::make_tuple(9u,77u,1u)].first==3 && PortBpStates()[9].Value(*PortBpConfigFile().seasons[0].Slot(1))==4);
// a stale load (logout and back before the answer) is ignored
PortBpLogout(b);Kill(b,101);PortBpLogout(b);Kill(b,101);db.Run();
assert(PortBpStates()[9].loaded && PortBpStates()[9].Value(*PortBpConfigFile().seasons[0].Slot(1))==4); // 3 stored + 1, the lost delta of the dropped session aside
// a mission finished before the load answers is announced once the load arrives; one already stored done is not
{CHARACTER* c=new CHARACTER;c->pid=10;online[10]=c;progress[std::make_tuple(10u,77u,2u)]={2,2};
Kill(c,8001,0,true);Kill(c,691,MOB_RANK_BOSS);assert(!Said(c,"MTBP1 done 3") && !Said(c,"MTBP1 done 2"));
db.Run();assert(Said(c,"MTBP1 done 3") && !Said(c,"MTBP1 done 2"));}
// --- season change: the old season's deltas are written, the new one starts from its own rows
Kill(b,101);now+=100000;tick(5001);Kill(b,101);db.Run();
assert(progress[std::make_tuple(9u,77u,1u)].first==5 && progress.count(std::make_tuple(9u,78u,1u))==0 && PortBpStates()[9].season==78);
PortBpSave(b);db.Run();assert(progress[std::make_tuple(9u,78u,1u)].first==1);
// --- the file is removed: no season, nothing counted
std::remove((basePath+"/port_battlepass.tsv").c_str());tick(5001);mark=b->messages.size();
PortBpCommand(b,"1 info");assert(Last(b)=="MTBP1 none");
WriteConfig("MTBATTLEPASS 1\nseason 1 1 2\n");tick();PortBpCommand(b,"1 info");assert(Last(b)=="MTBP1 none" && logs.back().find("ERR PORT_BP: port_battlepass.tsv disabled: ")==0);
puts("PASS: config, fit, kills, pushes, save, play time, claims (idempotent, space, db, config), final, reload, load race, season change");
}
'''
with tempfile.TemporaryDirectory(prefix='mt-bp-') as folder:
path=Path(folder);(path/'test.cpp').write_text(code);(path/'locale').mkdir()
subprocess.run(['c++','-std=c++17','-Wall','-I'+str(SRC),str(path/'test.cpp'),'-o',str(path/'test')],check=True)
subprocess.run([str(path/'test'),str(path/'locale'),str(TSV)],check=True)
+37
View File
@@ -0,0 +1,37 @@
#!/usr/bin/env python3
"""Port commands must not take over abbreviations of the original commands.
interpret_command (cmd.cpp) picks the first table entry whose name starts with the typed command
(strncmp over the typed length; do_cmd entries need an exact match). A port command placed before an
original one would steal its abbreviations, as mt_features once did with /m (mob) and /mt (mto).
"""
from pathlib import Path
import re
ROOT=Path(__file__).resolve().parents[2]
text=(ROOT/'src/server/game/src/cmd.cpp').read_bytes().decode('latin1')
table=text.split('struct command_info cmd_info[] =',1)[1]
entries=re.findall(r'\{\s*"((?:[^"\\]|\\.)*)",\s*([A-Za-z_0-9]+|NULL)',table)
assert entries[0][0]=='!RESERVED!'
end=[i for i,(name,_) in enumerate(entries) if name=='\\n']
assert end,'table sentinel not found'
entries=entries[1:end[0]]
PORT=lambda name:name.startswith('mt_')
port=[name for name,_ in entries if PORT(name)]
assert {'mt_features','mt_switchbot','mt_pickup','mt_chest'}<=set(port),port
def resolve(rows,cmd):
for name,fn in rows:
if fn=='do_cmd':
if name==cmd:return name
elif name.startswith(cmd):return name
return None
original=[(name,fn) for name,fn in entries if not PORT(name)]
for name in port:assert resolve(entries,name)==name,name
for name,_ in original:
for k in range(1,len(name)+1):
typed=name[:k]
assert resolve(entries,typed)==resolve(original,typed),'/%s now runs %s instead of %s'%(typed,resolve(entries,typed),resolve(original,typed))
for typed in ('m','mt','mo'):assert not PORT(resolve(entries,typed) or ''),typed
assert resolve(entries,'m')=='mob' and resolve(entries,'mt')=='mto'
print('cmd prefix ok: %d commands, %d port'%(len(entries),len(port)))
+137
View File
@@ -0,0 +1,137 @@
#!/usr/bin/env python3
"""Compile the production VIP card header against stubs of the account table, the ordered async SQL queue and
the premium affects."""
from pathlib import Path
import subprocess
import tempfile
ROOT=Path(__file__).resolve().parents[2]
SRC=ROOT/'src/server/game/src'
def source(name):return (SRC/name).read_bytes().decode('latin1')
cmd=source('cmd.cpp')
assert 'ACMD(do_port_vip);' in cmd and '"mt_vip", do_port_vip, 0, POS_DEAD, GM_PLAYER' in cmd
general=source('cmd_general.cpp')
assert '#include "port_premium.h"' in general and 'PortVipCommand(ch, argument);' in general
item=source('char_item.cpp')
use=item.index('bool CHARACTER::UseItem(TItemPos Cell, TItemPos DestCell)')
hook=item.index('if (PortVipUseCard(this, item))',use)
assert '#endif\n#include "port_premium.h"\n' in item # not inside the __AUCTION__ block
assert item.index('FN_check_item_sex(this, item)',use)<hook<item.index('IS_SUMMON_ITEM(item->GetVnum())',use)
login=source('input_login.cpp')
assert login.index('AFFECT_PREMIUM_START + i')<login.index('PortVipRefresh(ch, false);')
assert 'void\t\t\t\tPortSetPremiumTime(BYTE bType, int iTime)' in source('char.h')
code=r'''
#include <cassert>
#include <cstdarg>
#include <cstdio>
#include <cstring>
#include <deque>
#include <functional>
#include <map>
#include <string>
#include <vector>
using DWORD=unsigned;using BYTE=unsigned char;
enum {CHAT_TYPE_INFO=1,CHAT_TYPE_COMMAND=5,POINT_NONE=0,AFFECT_PREMIUM_START=500,PREMIUM_MAX_NUM=9};
static int now=1700000000;static DWORD clockms=1000;
int get_global_time(){return now;}DWORD get_dword_time(){return clockms;}
static std::vector<std::string> logs;
void sys_log(int,const char* format,...){char out[512];va_list a;va_start(a,format);vsnprintf(out,sizeof(out),format,a);va_end(a);logs.push_back(out);}
void sys_err(const char* format,...){char out[512];va_list a;va_start(a,format);vsnprintf(out,sizeof(out),format,a);va_end(a);logs.push_back(std::string("ERR ")+out);}
static std::string format(const char* f,va_list a){char out[4096];vsnprintf(out,sizeof(out),f,a);return out;}
// Account table: id -> seven end times (0 = never), as UNIX_TIMESTAMP reads them.
static std::map<DWORD,std::vector<int>> accounts;
using MYSQL_ROW=char**;
struct Rows{char* cells[7];char text[7][16];};
struct SQLResult{unsigned uiNumRows;Rows* pSQLResult;Rows rows;};
struct SQLMsg{SQLResult result;bool ok=true;SQLResult* Get(){return ok?&result:nullptr;}};
MYSQL_ROW mysql_fetch_row(Rows* r){return r->cells;}
struct DBManager{
std::deque<std::function<void()>> queue;std::vector<std::string> queries;
static DBManager& instance(){static DBManager m;return m;}
void Query(const char* f,...){va_list a;va_start(a,f);std::string q=format(f,a);va_end(a);queries.push_back(q);
queue.push_back([q]{DWORD id;int secs;
const char* where=strstr(q.c_str()," WHERE id=");assert(where && sscanf(where," WHERE id=%u",&id)==1);
const char* add=strstr(q.c_str(),"UNIX_TIMESTAMP())+");assert(add && sscanf(add,"UNIX_TIMESTAMP())+%d)",&secs)==1);
for(int& t:accounts[id])t=(t>now?t:now)+secs;});}
template<class F> void FuncQuery(F f,const char* fmt,...){va_list a;va_start(a,fmt);std::string q=format(fmt,a);va_end(a);queries.push_back(q);
queue.push_back([f,q]{DWORD id;assert(sscanf(strstr(q.c_str()," WHERE id="), " WHERE id=%u",&id)==1);
SQLMsg m{};auto it=accounts.find(id);m.result.uiNumRows=it==accounts.end()?0:1;m.result.pSQLResult=&m.result.rows;
for(int i=0;i<7;++i){m.result.rows.cells[i]=m.result.rows.text[i];snprintf(m.result.rows.text[i],16,"%d",it==accounts.end()?0:it->second[i]);}
f(&m);});}
void Run(){while(!queue.empty()){auto job=queue.front();queue.pop_front();job();}}
};
struct CItem{DWORD vnum;int count;DWORD GetVnum(){return vnum;}int GetCount(){return count;}void SetCount(int c){count=c;}};
using LPITEM=CItem*;
struct TAccountTable{DWORD id;};
struct DESC{TAccountTable table;TAccountTable& GetAccountTable(){return table;}};
struct CHARACTER{
DESC desc;bool online=true;int premium[PREMIUM_MAX_NUM]={};std::map<DWORD,long> affects;std::vector<std::string> messages;
const char* GetName(){return "Admin";}bool IsPC(){return true;}DESC* GetDesc(){return online?&desc:nullptr;}DWORD GetPlayerID(){return 7;}
int GetPremiumRemainSeconds(BYTE t)const{return t<PREMIUM_MAX_NUM?premium[t]-now:0;}
void PortSetPremiumTime(BYTE t,int v){if(t<PREMIUM_MAX_NUM)premium[t]=v;}
bool AddAffect(DWORD type,BYTE,long,DWORD,long duration,long,bool override){assert(override);affects[type]=duration;return true;}
bool RemoveAffect(DWORD type){return affects.erase(type)>0;}
void ChatPacket(BYTE type,const char* f,...){va_list a;va_start(a,f);std::string s=format(f,a);va_end(a);assert(type==CHAT_TYPE_COMMAND);messages.push_back(s);}
};
using LPCHARACTER=CHARACTER*;
static CHARACTER* player=nullptr;
struct CHARACTER_MANAGER{static CHARACTER_MANAGER& instance(){static CHARACTER_MANAGER m;return m;}
LPCHARACTER FindByPID(DWORD pid){return player && pid==7?player:nullptr;}};
static std::vector<std::string> itemlog;
struct LogManager{static LogManager& instance(){static LogManager m;return m;}
void ItemLog(LPCHARACTER,LPITEM item,const char* how,const char* hint){assert(item->count>0);itemlog.push_back(std::string(how)+" "+std::to_string(item->vnum)+" "+hint);}};
#include "port_premium.h"
static DBManager& db=DBManager::instance();
static const std::string& last(){return player->messages.back();}
static void tick(){clockms+=1100;}
int main(){
const int DAY=86400;
accounts[1]=std::vector<int>(7,0);
player=new CHARACTER;player->desc.table.id=1;
// Fresh account: 7 days from now on all seven columns, one card consumed, icons 500..506 for 7 days.
CItem card{38001,2};
assert(PortVipUseCard(player,&card) && card.count==1 && itemlog.back()=="MT_VIP_CARD 38001 7");
assert(db.queries[0].rfind("UPDATE account.account SET silver_expire=FROM_UNIXTIME(GREATEST(UNIX_TIMESTAMP(silver_expire),UNIX_TIMESTAMP())+604800),gold_expire=",0)==0);
assert(db.queries[0].find("money_drop_rate_expire=FROM_UNIXTIME(GREATEST(UNIX_TIMESTAMP(money_drop_rate_expire),UNIX_TIMESTAMP())+604800) WHERE id=1")!=std::string::npos);
assert(db.queries[1]=="SELECT UNIX_TIMESTAMP(silver_expire),UNIX_TIMESTAMP(gold_expire),UNIX_TIMESTAMP(safebox_expire),UNIX_TIMESTAMP(autoloot_expire),UNIX_TIMESTAMP(fish_mind_expire),UNIX_TIMESTAMP(marriage_fast_expire),UNIX_TIMESTAMP(money_drop_rate_expire) FROM account.account WHERE id=1");
assert(last()=="MTVIP1 added 38001 7" && player->premium[0]==0); // memory waits for the read-back
db.Run();
assert(last()=="MTVIP1 times 604800 604800 604800 604800 604800 604800 604800");
for(int i=0;i<7;++i)assert(player->premium[i]==now+7*DAY && player->affects[500+i]==7*DAY && accounts[1][i]==now+7*DAY);
assert(!player->affects.count(507) && player->premium[7]==0);
// A second card inside the gap is refused and kept; after it, 30 days add to the current end.
CItem month{38002,1};
assert(PortVipUseCard(player,&month) && last()=="MTVIP1 error rate" && month.count==1);
tick();now+=DAY;assert(PortVipUseCard(player,&month) && month.count==0);db.Run();
assert(last()=="MTVIP1 times 3110400 3110400 3110400 3110400 3110400 3110400 3110400" && player->premium[3]==now-DAY+37*DAY);
// Past the 400-day cap: refused before anything is consumed or queried.
const size_t queries=db.queries.size();CItem many{38002,20};
for(int k=0;k<13;++k){tick();assert(PortVipUseCard(player,&many));db.Run();} // 36 days left: 12 cards reach 396
assert(last()=="MTVIP1 error full" && many.count==8 && db.queries.size()==queries+24);
// Not a card: untouched, nothing queried.
CItem other{27001,5};assert(!PortVipUseCard(player,&other) && other.count==5 && db.queries.size()==queries+24);
// Enter-game on another core: the db core still has the login-time ends (here, none); the refresh restores them.
tick();const auto stale=player->messages.size();
for(int i=0;i<PREMIUM_MAX_NUM;++i)player->premium[i]=0;player->affects.clear();
PortVipRefresh(player,false);db.Run();
assert(player->messages.size()==stale && player->premium[6]==accounts[1][6] && player->affects[506]==accounts[1][6]-now);
// Expired in the account (edited by hand): state and icon go away; unchanged types keep their icon untouched.
accounts[1][2]=now-5;player->affects[502]=1;player->affects[503]=12345;
PortVipRefresh(player,false);db.Run();
assert(player->GetPremiumRemainSeconds(2)<0 && !player->affects.count(502) && player->affects[503]==12345);
// Status command: version, validation, throttle, report of remaining seconds (0 when expired).
tick();PortVipCommand(player,"1 status");db.Run();assert(last().rfind("MTVIP1 times ",0)==0 && last().find(" 0 ")!=std::string::npos);
PortVipCommand(player,"1 status");assert(last()=="MTVIP1 error rate");
for(auto bad:{"1 stats","1","1 status x"}){tick();PortVipCommand(player,bad);assert(last()=="MTVIP1 error invalid");}
const auto quiet=player->messages.size();tick();PortVipCommand(player,"2 status");PortVipCommand(player,"1 status x y z");
assert(player->messages.size()==quiet);
// The player left before the read-back: nothing is touched.
tick();PortVipCommand(player,"1 status");CHARACTER* gone=player;player=nullptr;db.Run();assert(gone->messages.size()==quiet);
// Missing account row: logged, no state change.
player=gone;player->desc.table.id=99;tick();PortVipRefresh(player,true);db.Run();assert(logs.back()=="ERR PORT_VIP: account 99 not found");
puts("PASS: card use and read-back, stacking, gap, cap, other items, enter-game refresh, expiry, status command");
}
'''
with tempfile.TemporaryDirectory(prefix='mt-vip-') as folder:
path=Path(folder);(path/'test.cpp').write_text(code)
subprocess.run(['c++','-std=c++17','-Wall','-I'+str(SRC),str(path/'test.cpp'),'-o',str(path/'test')],check=True)
subprocess.run([str(path/'test')],check=True)
+50
View File
@@ -0,0 +1,50 @@
# PORT battle pass seasons (docs/FEATURE-BATTLEPASS.md). Installed as share/locale/newcibn/port_battlepass.tsv;
# every core rereads it within 5 s of an atomic replace. Any error disables the battle pass (see syserr PORT_BP).
#
# season ID START END unix seconds, START inclusive, END exclusive; seasons must not overlap
# mission SLOT TYPE SUB TARGET [VNUM COUNT]x0..3
# SLOT 1..10. Progress and claims are stored per season and slot: do not reuse a slot for another mission
# within a running season.
# TYPE 1 kill monster (SUB mob vnum or 0 = any normal monster) 2 kill boss (SUB vnum or 0)
# 3 kill metin stone (SUB vnum or 0) 4 seconds online 5 catch fish (SUB item vnum or 0)
# 6 successful refine (SUB result vnum or 0) 7 levels gained 8 gold paid to NPC shops
# 9 items sold to NPC shops (SUB item vnum, required)
# Kills count for the player the quest kill goes to, within 20 levels of the monster.
# final VNUM COUNT x1..6 once every mission of the season is done
MTBATTLEPASS 1
# 2026-10 (Europe/Berlin)
season 202610 1790805600 1793487600
mission 1 1 0 20000 70043 1 71153 5
mission 2 2 0 30 25041 2 71032 1
mission 3 3 0 300 50513 3
mission 4 4 0 172800 71094 2
mission 5 5 0 100 27987 5
mission 6 6 0 50 25040 2
mission 7 7 0 5 71153 5
mission 8 8 0 50000000 71084 20
final 27992 2 27993 1 27994 1 70024 1
# 2026-11 (Europe/Berlin)
season 202611 1793487600 1796079600
mission 1 1 0 20000 70043 1 71153 5
mission 2 2 0 30 25041 2 71032 1
mission 3 3 0 300 50513 3
mission 4 4 0 172800 71094 2
mission 5 5 0 100 27987 5
mission 6 6 0 50 25040 2
mission 7 7 0 5 71153 5
mission 8 8 0 50000000 71084 20
final 27992 2 27993 1 27994 1 70024 1
# 2026-12 (Europe/Berlin)
season 202612 1796079600 1798758000
mission 1 1 0 20000 70043 1 71153 5
mission 2 2 0 30 25041 2 71032 1
mission 3 3 0 300 50513 3
mission 4 4 0 172800 71094 2
mission 5 5 0 100 27987 5
mission 6 6 0 50 25040 2
mission 7 7 0 5 71153 5
mission 8 8 0 50000000 71084 20
final 27992 2 27993 1 27994 1 70024 1
1 # PORT battle pass seasons (docs/FEATURE-BATTLEPASS.md). Installed as share/locale/newcibn/port_battlepass.tsv;
2 # every core rereads it within 5 s of an atomic replace. Any error disables the battle pass (see syserr PORT_BP).
3 #
4 # season ID START END unix seconds, START inclusive, END exclusive; seasons must not overlap
5 # mission SLOT TYPE SUB TARGET [VNUM COUNT]x0..3
6 # SLOT 1..10. Progress and claims are stored per season and slot: do not reuse a slot for another mission
7 # within a running season.
8 # TYPE 1 kill monster (SUB mob vnum or 0 = any normal monster) 2 kill boss (SUB vnum or 0)
9 # 3 kill metin stone (SUB vnum or 0) 4 seconds online 5 catch fish (SUB item vnum or 0)
10 # 6 successful refine (SUB result vnum or 0) 7 levels gained 8 gold paid to NPC shops
11 # 9 items sold to NPC shops (SUB item vnum, required)
12 # Kills count for the player the quest kill goes to, within 20 levels of the monster.
13 # final VNUM COUNT x1..6 once every mission of the season is done
14 MTBATTLEPASS 1
15 # 2026-10 (Europe/Berlin)
16 season 202610 1790805600 1793487600
17 mission 1 1 0 20000 70043 1 71153 5
18 mission 2 2 0 30 25041 2 71032 1
19 mission 3 3 0 300 50513 3
20 mission 4 4 0 172800 71094 2
21 mission 5 5 0 100 27987 5
22 mission 6 6 0 50 25040 2
23 mission 7 7 0 5 71153 5
24 mission 8 8 0 50000000 71084 20
25 final 27992 2 27993 1 27994 1 70024 1
26 # 2026-11 (Europe/Berlin)
27 season 202611 1793487600 1796079600
28 mission 1 1 0 20000 70043 1 71153 5
29 mission 2 2 0 30 25041 2 71032 1
30 mission 3 3 0 300 50513 3
31 mission 4 4 0 172800 71094 2
32 mission 5 5 0 100 27987 5
33 mission 6 6 0 50 25040 2
34 mission 7 7 0 5 71153 5
35 mission 8 8 0 50000000 71084 20
36 final 27992 2 27993 1 27994 1 70024 1
37 # 2026-12 (Europe/Berlin)
38 season 202612 1796079600 1798758000
39 mission 1 1 0 20000 70043 1 71153 5
40 mission 2 2 0 30 25041 2 71032 1
41 mission 3 3 0 300 50513 3
42 mission 4 4 0 172800 71094 2
43 mission 5 5 0 100 27987 5
44 mission 6 6 0 50 25040 2
45 mission 7 7 0 5 71153 5
46 mission 8 8 0 50000000 71084 20
47 final 27992 2 27993 1 27994 1 70024 1
+20
View File
@@ -0,0 +1,20 @@
-- PORT: battle pass tables (docs/FEATURE-BATTLEPASS.md). Idempotent; run once on the player database.
-- Progress: one row per player, season and mission slot; the game adds deltas and MySQL caps them at target.
CREATE TABLE IF NOT EXISTS player.mt_battlepass_progress (
pid INT UNSIGNED NOT NULL,
season INT UNSIGNED NOT NULL,
slot TINYINT UNSIGNED NOT NULL,
value BIGINT UNSIGNED NOT NULL DEFAULT 0,
target BIGINT UNSIGNED NOT NULL DEFAULT 0,
updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (pid, season, slot)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
-- Claims: the primary key is the idempotency guard; only the request whose INSERT IGNORE adds the row pays out.
-- slot 0 is the final reward.
CREATE TABLE IF NOT EXISTS player.mt_battlepass_claim (
pid INT UNSIGNED NOT NULL,
season INT UNSIGNED NOT NULL,
slot TINYINT UNSIGNED NOT NULL,
claimed_at INT UNSIGNED NOT NULL,
PRIMARY KEY (pid, season, slot)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;