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>
This commit is contained in:
shenlei
2026-10-16 09:11:36 +09:00
co-authored by Claude Opus 5.5
parent 1bdaae8807
commit 7f4e8b3f76
15 changed files with 964 additions and 0 deletions
+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);
+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());
+3
View File
@@ -51,6 +51,7 @@
#include "auction_manager.h"
#endif
#include "port_premium.h"
#include "port_battlepass_hooks.h"
const int ITEM_BROKEN_METIN_VNUM = 28960;
// CHANGE_ITEM_ATTRIBUTES
@@ -924,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();
@@ -1197,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();
+2
View File
@@ -14,6 +14,7 @@ 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);
@@ -607,6 +608,7 @@ struct command_info cmd_info[] =
{ "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 } /* 반드시 이 것이 마지막이어야 한다. */
};
+9
View File
@@ -47,6 +47,7 @@
#include "port_pickup.h"
#include "port_chest.h"
#include "port_premium.h"
#include "port_battlepass_runtime.h"
ACMD(do_port_vip)
{
@@ -55,6 +56,14 @@ ACMD(do_port_vip)
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;
extern int g_nPortalLimitTime;
+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;
+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
+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())
{