feat: add account point rewards and extended item storage
Implement configurable kill rewards with account-wide daily limits, transactional deduplication, and game-to-db retries. Add the approved wide rules and tested isolation tooling. Stage wear40 equipment and persistent extra item metadata with an explicit migration plan and client revision gate. Track all 168 remaining offers; sixteen have staged data/assets, while live acceptance and other systems remain incomplete. This commit is not a production deployment.
This commit is contained in:
File diff suppressed because it is too large
Load Diff
@@ -78,8 +78,12 @@ enum EItemTypes
|
||||
ITEM_BELT, //34 벨트
|
||||
ITEM_SHINING, //35 AVA2 shining (not ported, keeps the AVA2 numbering)
|
||||
ITEM_NEW_RINGS, //36 AVA2 new rings (port_rings.cpp), worn in WEAR_RINGS_1/2
|
||||
ITEM_PET, // PORT: AVA2 growable pets, explicit item type 37.
|
||||
};
|
||||
|
||||
enum EPetSubTypes { PET_LEVELABLE, PET_EGG, PET_TRANSPORTBOX, PET_PROTEIN, PET_CHANGE_NAME_ITEM, PET_DEW, PET_SKILL, PET_PRIMIUM_FEEDSTUFF, PET_ATTR_CHANGE, PET_ATTR_DETERMINE, PET_EXPFOOD_PER, PET_SKILL_DEL_BOOK, PET_SKILL_ALL_DEL_BOOK, PET_EXPFOOD, PET_FEEDSTUFF };
|
||||
enum EShiningSubTypes { SHINING_WEAPON, SHINING_ARMOR, SHINING_SPECIAL };
|
||||
|
||||
enum EMetinSubTypes
|
||||
{
|
||||
METIN_NORMAL,
|
||||
@@ -119,6 +123,9 @@ enum ECostumeSubTypes
|
||||
COSTUME_MOUNT = 2, // AVA2 mount costume (value0 = horse race)
|
||||
COSTUME_SASH = 3, // AVA2 sash (85001..85024)
|
||||
COSTUME_MOUNT_SKIN = 4, // AVA2 mount skin (value0 = horse race, needs COSTUME_MOUNT)
|
||||
COSTUME_WEAPON = 5, // PORT: preserve existing mount-skin subtype 4.
|
||||
COSTUME_NEW_SASH = 6,
|
||||
COSTUME_PET = 7,
|
||||
COSTUME_NUM_TYPES,
|
||||
};
|
||||
|
||||
|
||||
@@ -64,7 +64,7 @@ enum EMisc
|
||||
DRAGON_SOUL_REFINE_GRID_SIZE = 15,
|
||||
MAX_AMOUNT_OF_MALL_BONUS = 20,
|
||||
|
||||
WEAR_MAX_NUM = 32,
|
||||
WEAR_MAX_NUM = 40, // PORT: shop costume/pet/shining equipment.
|
||||
|
||||
//LIMIT_GOLD
|
||||
GOLD_MAX = 2000000000,
|
||||
@@ -144,7 +144,14 @@ enum EWearPositions
|
||||
WEAR_RINGS_1, // 28 : AVA2 new ring (ITEM_NEW_RINGS)
|
||||
WEAR_RINGS_2, // 29 : AVA2 new ring
|
||||
|
||||
WEAR_MAX = 32 //
|
||||
WEAR_COSTUME_WEAPON = 30,
|
||||
WEAR_COSTUME_PET = 31,
|
||||
WEAR_PET = 32,
|
||||
WEAR_COSTUME_NEW_SASH = 33,
|
||||
WEAR_SHINING_WEAPON = 34,
|
||||
WEAR_SHINING_ARMOR = 35,
|
||||
WEAR_SHINING_SPECIAL = 36,
|
||||
WEAR_MAX = 40 // PORT: extended appearance equipment.
|
||||
};
|
||||
|
||||
enum EDragonSoulDeckType
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
#pragma once
|
||||
#include <stdint.h>
|
||||
#include <algorithm>
|
||||
#include <string>
|
||||
|
||||
// User-authorized extension. Chance uses basis points; zero disables that source.
|
||||
struct PortPointDropRule {
|
||||
int chance, minimum, maximum, minimumLevel, maximumOverlevel, dailyCap;
|
||||
bool valid() const {
|
||||
return chance >= 0 && chance <= 10000 && minimum >= 1 && maximum >= minimum &&
|
||||
maximum <= 1000000 && minimumLevel >= 0 && maximumOverlevel >= 0 && dailyCap >= 0;
|
||||
}
|
||||
bool eligible(int targetLevel, int playerLevel) const {
|
||||
return valid() && chance > 0 && targetLevel >= minimumLevel && playerLevel > 0 &&
|
||||
(!maximumOverlevel || playerLevel - targetLevel <= maximumOverlevel);
|
||||
}
|
||||
};
|
||||
|
||||
template<class Lookup> PortPointDropRule PortPointRule(Lookup flag, bool stone) {
|
||||
const std::string prefix = stone ? "points_stone_" : "points_mob_";
|
||||
const int minimum = flag(prefix + "min");
|
||||
const int maximum = flag(prefix + "max");
|
||||
return {flag(prefix + "chance"), minimum ? minimum : 1,
|
||||
maximum ? maximum : (minimum ? minimum : 1), flag("points_min_level"),
|
||||
flag("points_max_overlevel"), flag("points_daily_cap")};
|
||||
}
|
||||
|
||||
inline uint32_t PortPointDropAmount(uint32_t requested, uint64_t earned, uint32_t cap) {
|
||||
if (!cap) return requested;
|
||||
if (earned >= cap) return 0;
|
||||
return static_cast<uint32_t>(std::min<uint64_t>(requested, cap - earned));
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
#pragma once
|
||||
#include <stdint.h>
|
||||
#include <string>
|
||||
#include <cstring>
|
||||
|
||||
// PORT: supplementary AVA2 pet/rarity state. Classic item packets retain 3 sockets / 7 attributes.
|
||||
#pragma pack(push,1)
|
||||
struct PortItemExtra {
|
||||
int32_t sockets[5];
|
||||
uint8_t types[8];
|
||||
int16_t values[8];
|
||||
char name[25];
|
||||
};
|
||||
#pragma pack(pop)
|
||||
static_assert(sizeof(PortItemExtra)==69,"extended item state");
|
||||
|
||||
inline std::string PortItemExtraHex(const PortItemExtra& extra) {
|
||||
static const char digits[]="0123456789abcdef";
|
||||
const auto p=reinterpret_cast<const unsigned char*>(&extra);
|
||||
std::string result(sizeof(extra)*2,'0');
|
||||
for(unsigned i=0;i<sizeof(extra);++i){result[2*i]=digits[p[i]>>4];result[2*i+1]=digits[p[i]&15];}
|
||||
return result;
|
||||
}
|
||||
inline bool PortItemExtraRead(const char* hex,PortItemExtra& extra) {
|
||||
std::memset(&extra,0,sizeof(extra));
|
||||
if(!hex || !*hex)return true;
|
||||
if(std::strlen(hex)!=sizeof(extra)*2)return false;
|
||||
auto nibble=[](char c){return c>='0' && c<='9'?c-'0':c>='A' && c<='F'?c-'A'+10:c>='a' && c<='f'?c-'a'+10:-1;};
|
||||
auto p=reinterpret_cast<unsigned char*>(&extra);
|
||||
for(unsigned i=0;i<sizeof(extra);++i){int a=nibble(hex[2*i]),b=nibble(hex[2*i+1]);if(a<0 || b<0){std::memset(&extra,0,sizeof(extra));return false;}p[i]=(a<<4)|b;}
|
||||
extra.name[24]=0;return true;
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
#include "port_item_extra.h"
|
||||
#ifndef __INC_TABLES_H__
|
||||
#define __INC_TABLES_H__
|
||||
|
||||
@@ -398,6 +399,7 @@ typedef struct SPlayerItem
|
||||
TPlayerItemAttribute aAttr[ITEM_ATTRIBUTE_MAX_NUM];
|
||||
|
||||
DWORD owner;
|
||||
PortItemExtra extra; // PORT: internal game/db state, not a classic client packet.
|
||||
} TPlayerItem;
|
||||
|
||||
typedef struct SQuickslot
|
||||
|
||||
@@ -143,7 +143,7 @@ void AuctionManager::LoadAuctionItem()
|
||||
for (int i = 0; i < rows; ++i)
|
||||
{
|
||||
MYSQL_ROW row = mysql_fetch_row(res);
|
||||
TPlayerItem item;
|
||||
TPlayerItem item={};
|
||||
|
||||
int cur = 0;
|
||||
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
#include "DBManager.h"
|
||||
#include "ItemAwardManager.h"
|
||||
#include "../../common/ava2_itemshop.h"
|
||||
#include "../../common/point_drop.h"
|
||||
#include <memory>
|
||||
#include <sstream>
|
||||
#include <cctype>
|
||||
@@ -65,7 +66,49 @@ bool valid(const Ava2ShopProduct& p) {return p.id && p.vnum && p.price>=0 && p.p
|
||||
void CClientManager::Ava2ItemShop(CPeer* peer,DWORD handle,const char* data,DWORD length) {
|
||||
if (length!=sizeof(Ava2ShopRequest))return;
|
||||
Ava2ShopRequest r;memcpy(&r,data,sizeof(r));
|
||||
if (r.operation>2 || !r.account || !r.player || r.token[32] || r.name[24] || r.ip[15])return;
|
||||
if (r.operation>3 || !r.account || !r.player || r.token[32] || r.name[24] || r.ip[15])return;
|
||||
if(r.operation==3) {
|
||||
// This operation has no client command. Only an authenticated game peer may report a kill.
|
||||
if(!peer->GetChannel() || strlen(r.token)!=32 || r.count<1 || r.count>1000000 || !r.expectedVnum || r.expectedVnum>255)return;
|
||||
for(char c:std::string(r.token))if(!std::isxdigit(static_cast<unsigned char>(c)))return;
|
||||
const std::string adb=accountDB(),aid=decimal(r.account);
|
||||
uint8_t status=6;uint32_t granted=0;int64_t balance=0;
|
||||
auto mob=std::find_if(m_vec_mobTable.begin(),m_vec_mobTable.end(),[&](const TMobTable& m){return m.dwVnum==r.product;});
|
||||
const bool validMob=mob!=m_vec_mobTable.end() && (mob->bType==0 || mob->bType==2);
|
||||
const auto rule=PortPointRule([&](const std::string& key){auto it=m_map_lEventFlag.find(key);return it==m_map_lEventFlag.end()?0:int(it->second);},validMob && mob->bType==2);
|
||||
auto engine=query("SELECT COUNT(*) FROM information_schema.tables WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME='port_point_rewards' AND ENGINE='InnoDB'");
|
||||
if(validMob && !adb.empty() && transactional(adb) && ok(engine) && engine->Get()->uiNumRows==1 && atoi(mysql_fetch_row(engine->Get()->pSQLResult)[0])==1) {
|
||||
Transaction tx;
|
||||
if(tx.active) {
|
||||
auto owner=query("SELECT account_id FROM player WHERE id="+decimal(r.player));
|
||||
auto wallet=query("SELECT coins FROM "+adb+".account WHERE id="+aid+" FOR UPDATE");
|
||||
if(ok(owner) && owner->Get()->uiNumRows==1 && strtoul(mysql_fetch_row(owner->Get()->pSQLResult)[0],0,10)==r.account && ok(wallet) && wallet->Get()->uiNumRows==1) {
|
||||
balance=strtoll(mysql_fetch_row(wallet->Get()->pSQLResult)[0],0,10);
|
||||
auto previous=query("SELECT account_id,vnum,requested,amount FROM port_point_rewards WHERE token='"+std::string(r.token)+"'");
|
||||
if(ok(previous) && previous->Get()->uiNumRows==1) {
|
||||
auto row=mysql_fetch_row(previous->Get()->pSQLResult);
|
||||
if(strtoul(row[0],0,10)==r.account && strtoul(row[1],0,10)==r.product && strtoul(row[2],0,10)==r.count){granted=strtoul(row[3],0,10);status=0;}else status=7;
|
||||
} else if(ok(previous)) {
|
||||
if(!rule.eligible(mob->bLevel,r.expectedVnum) || r.count<uint32_t(rule.minimum) || r.count>uint32_t(rule.maximum))status=1;
|
||||
else {
|
||||
auto earned=query("SELECT COALESCE(SUM(amount),0) FROM port_point_rewards WHERE account_id="+aid+" AND reward_day=CURDATE()");
|
||||
if(ok(earned) && earned->Get()->uiNumRows==1) {
|
||||
granted=PortPointDropAmount(r.count,strtoull(mysql_fetch_row(earned->Get()->pSQLResult)[0],0,10),rule.dailyCap);
|
||||
if(balance<0 || uint64_t(balance)>uint64_t(INT64_MAX)-granted){status=1;granted=0;}
|
||||
else {
|
||||
bool success=run("UPDATE "+adb+".account SET coins=coins+"+decimal(granted)+" WHERE id="+aid);
|
||||
success=success && run("INSERT INTO port_point_rewards(token,account_id,player_id,vnum,requested,amount,reward_day) VALUES('"+std::string(r.token)+"',"+aid+","+decimal(r.player)+","+decimal(r.product)+","+decimal(r.count)+","+decimal(granted)+",CURDATE())");
|
||||
if(success){if(tx.commit()){balance+=granted;status=0;}else status=8;}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
std::vector<char> out;append(out,uint8_t(9));append(out,status);out.insert(out.end(),r.token,r.token+32);append(out,granted);append(out,balance);
|
||||
reply(peer,handle,r,out);return;
|
||||
}
|
||||
auto login=GetLoginDataByAID(r.account);
|
||||
if (!login || !login->IsPlay() || login->GetConnectedPeerHandle()!=peer->GetHandle())return;
|
||||
bool owned=false;for (const auto& p:login->GetAccountRef().players)if(p.dwID==r.player)owned=true;
|
||||
|
||||
@@ -138,6 +138,9 @@ void CItemCache::OnFlush()
|
||||
p->aAttr[6].bType, p->aAttr[6].sValue);
|
||||
}
|
||||
|
||||
const std::string extraHex=PortItemExtraHex(p->extra);
|
||||
iLen += snprintf(szColumns+iLen,sizeof(szColumns)-iLen,", port_extra");
|
||||
iValueLen += snprintf(szValues+iValueLen,sizeof(szValues)-iValueLen,", X'%s'",extraHex.c_str());
|
||||
char szItemQuery[QUERY_MAX_LEN + QUERY_MAX_LEN];
|
||||
snprintf(szItemQuery, sizeof(szItemQuery), "REPLACE INTO item%s (%s) VALUES(%s)", GetTablePostfix(), szColumns, szValues);
|
||||
|
||||
|
||||
@@ -581,7 +581,7 @@ void CClientManager::RESULT_SAFEBOX_LOAD(CPeer * pkPeer, SQLMsg * msg)
|
||||
"attrtype3, attrvalue3, "
|
||||
"attrtype4, attrvalue4, "
|
||||
"attrtype5, attrvalue5, "
|
||||
"attrtype6, attrvalue6 "
|
||||
"attrtype6, attrvalue6, HEX(port_extra) "
|
||||
"FROM item%s WHERE owner_id=%d AND window='%s'",
|
||||
GetTablePostfix(), pi->account_id, pi->ip[0] == 0 ? "SAFEBOX" : "MALL");
|
||||
|
||||
@@ -673,7 +673,7 @@ void CClientManager::RESULT_SAFEBOX_LOAD(CPeer * pkPeer, SQLMsg * msg)
|
||||
if ((iPos = grid.FindBlank(1, it->second->bSize)) == -1)
|
||||
break;
|
||||
|
||||
TPlayerItem item;
|
||||
TPlayerItem item={};
|
||||
memset(&item, 0, sizeof(TPlayerItem));
|
||||
|
||||
// DWORD dwSocket2 = 0;
|
||||
@@ -1307,7 +1307,7 @@ void CClientManager::QUERY_ITEM_SAVE(CPeer * pkPeer, const char * c_pData)
|
||||
|
||||
delete c;
|
||||
}
|
||||
char szQuery[512];
|
||||
char szQuery[2048];
|
||||
|
||||
snprintf(szQuery, sizeof(szQuery),
|
||||
"REPLACE INTO item%s (id, owner_id, window, pos, count, vnum, socket0, socket1, socket2, "
|
||||
@@ -1317,8 +1317,8 @@ void CClientManager::QUERY_ITEM_SAVE(CPeer * pkPeer, const char * c_pData)
|
||||
"attrtype3, attrvalue3, "
|
||||
"attrtype4, attrvalue4, "
|
||||
"attrtype5, attrvalue5, "
|
||||
"attrtype6, attrvalue6) "
|
||||
"VALUES(%u, %u, %d, %d, %u, %u, %ld, %ld, %ld, %d, %d, %d, %d, %d, %d, %d, %d, %d, %d, %d, %d, %d, %d)",
|
||||
"attrtype6, attrvalue6, port_extra) "
|
||||
"VALUES(%u, %u, %d, %d, %u, %u, %ld, %ld, %ld, %d, %d, %d, %d, %d, %d, %d, %d, %d, %d, %d, %d, %d, %d, X'%s')",
|
||||
GetTablePostfix(),
|
||||
p->id,
|
||||
p->owner,
|
||||
@@ -1335,7 +1335,7 @@ void CClientManager::QUERY_ITEM_SAVE(CPeer * pkPeer, const char * c_pData)
|
||||
p->aAttr[3].bType, p->aAttr[3].sValue,
|
||||
p->aAttr[4].bType, p->aAttr[4].sValue,
|
||||
p->aAttr[5].bType, p->aAttr[5].sValue,
|
||||
p->aAttr[6].bType, p->aAttr[6].sValue);
|
||||
p->aAttr[6].bType, p->aAttr[6].sValue, PortItemExtraHex(p->extra).c_str());
|
||||
|
||||
CDBManager::instance().ReturnQuery(szQuery, QID_ITEM_SAVE, pkPeer->GetHandle(), NULL);
|
||||
}
|
||||
@@ -4711,7 +4711,7 @@ void CClientManager::AuctionGetAuctionedItem (CPeer * peer, DWORD actor_id, DWOR
|
||||
return;
|
||||
}
|
||||
|
||||
TPlayerItem item;
|
||||
TPlayerItem item={};
|
||||
result = AuctionManager::instance().GetAuctionedItem(actor_id, item_id, item);
|
||||
|
||||
if (result <= AUCTION_FAIL)
|
||||
@@ -4751,7 +4751,7 @@ void CClientManager::AuctionBuySoldItem (CPeer * peer, DWORD actor_id, DWORD ite
|
||||
return;
|
||||
}
|
||||
|
||||
TPlayerItem item;
|
||||
TPlayerItem item={};
|
||||
result = AuctionManager::instance().BuySoldItem(actor_id, item_id, item);
|
||||
|
||||
if (result <= AUCTION_FAIL)
|
||||
@@ -4791,7 +4791,7 @@ void CClientManager::AuctionCancelAuction (CPeer * peer, DWORD actor_id, DWORD i
|
||||
return;
|
||||
}
|
||||
|
||||
TPlayerItem item;
|
||||
TPlayerItem item={};
|
||||
result = AuctionManager::instance().CancelAuction(actor_id, item_id, item);
|
||||
|
||||
if (result <= AUCTION_FAIL)
|
||||
@@ -4831,7 +4831,7 @@ void CClientManager::AuctionCancelWish (CPeer * peer, DWORD actor_id, DWORD item
|
||||
return;
|
||||
}
|
||||
|
||||
TPlayerItem item;
|
||||
TPlayerItem item={};
|
||||
result = AuctionManager::instance().CancelWish(actor_id, item_num);
|
||||
|
||||
if (result <= AUCTION_FAIL)
|
||||
@@ -4870,7 +4870,7 @@ void CClientManager::AuctionCancelSale (CPeer * peer, DWORD actor_id, DWORD item
|
||||
return;
|
||||
}
|
||||
|
||||
TPlayerItem item;
|
||||
TPlayerItem item={};
|
||||
result = AuctionManager::instance().CancelSale(actor_id, item_id, item);
|
||||
|
||||
if (result <= AUCTION_FAIL)
|
||||
|
||||
@@ -65,6 +65,7 @@ bool CreateItemTableFromRes(MYSQL_RES * res, std::vector<TPlayerItem> * pVec, DW
|
||||
str_to_number(item.aAttr[j].sValue, row[cur++]);
|
||||
}
|
||||
|
||||
PortItemExtraRead(mysql_num_fields(res)>unsigned(cur)?row[cur]:NULL,item.extra);
|
||||
item.owner = dwPID;
|
||||
}
|
||||
|
||||
@@ -321,7 +322,7 @@ void CClientManager::QUERY_PLAYER_LOAD(CPeer * peer, DWORD dwHandle, TPlayerLoad
|
||||
else
|
||||
{
|
||||
snprintf(szQuery, sizeof(szQuery),
|
||||
"SELECT id,window+0,pos,count,vnum,socket0,socket1,socket2,attrtype0,attrvalue0,attrtype1,attrvalue1,attrtype2,attrvalue2,attrtype3,attrvalue3,attrtype4,attrvalue4,attrtype5,attrvalue5,attrtype6,attrvalue6 "
|
||||
"SELECT id,window+0,pos,count,vnum,socket0,socket1,socket2,attrtype0,attrvalue0,attrtype1,attrvalue1,attrtype2,attrvalue2,attrtype3,attrvalue3,attrtype4,attrvalue4,attrtype5,attrvalue5,attrtype6,attrvalue6,HEX(port_extra) "
|
||||
"FROM item%s WHERE owner_id=%d AND (window < %d or window = %d or window = %d)",
|
||||
GetTablePostfix(), pTab->id, SAFEBOX, DRAGON_SOUL_INVENTORY, SWITCHBOT);
|
||||
|
||||
@@ -378,7 +379,7 @@ void CClientManager::QUERY_PLAYER_LOAD(CPeer * peer, DWORD dwHandle, TPlayerLoad
|
||||
// 아이템 가져오기
|
||||
//--------------------------------------------------------------
|
||||
snprintf(queryStr, sizeof(queryStr),
|
||||
"SELECT id,window+0,pos,count,vnum,socket0,socket1,socket2,attrtype0,attrvalue0,attrtype1,attrvalue1,attrtype2,attrvalue2,attrtype3,attrvalue3,attrtype4,attrvalue4,attrtype5,attrvalue5,attrtype6,attrvalue6 "
|
||||
"SELECT id,window+0,pos,count,vnum,socket0,socket1,socket2,attrtype0,attrvalue0,attrtype1,attrvalue1,attrtype2,attrvalue2,attrtype3,attrvalue3,attrtype4,attrvalue4,attrtype5,attrvalue5,attrtype6,attrvalue6,HEX(port_extra) "
|
||||
"FROM item%s WHERE owner_id=%d AND (window < %d or window = %d or window = %d)",
|
||||
GetTablePostfix(), packet->player_id, SAFEBOX, DRAGON_SOUL_INVENTORY, SWITCHBOT);
|
||||
CDBManager::instance().ReturnQuery(queryStr, QID_ITEM, peer->GetHandle(), new ClientHandleInfo(dwHandle, packet->player_id));
|
||||
|
||||
@@ -79,7 +79,7 @@ int get_Item_Type_Value(string inputString)
|
||||
|
||||
"ITEM_RING",
|
||||
"ITEM_BELT", //35개 (EItemTypes 값으로 치면 34)
|
||||
"ITEM_SHINING", "ITEM_NEW_RINGS", // AVA2 35 (not ported), 36 new rings
|
||||
"ITEM_SHINING", "ITEM_NEW_RINGS", "ITEM_PET", // AVA2 35 (not ported), 36 new rings
|
||||
};
|
||||
|
||||
|
||||
@@ -123,8 +123,10 @@ int get_Item_SubType_Value(int type_value, string inputString)
|
||||
"RESOURCE_STONE", "RESOURCE_METIN", "RESOURCE_ORE" };
|
||||
static string arSub16[] = { "UNIQUE_NONE", "UNIQUE_BOOK", "UNIQUE_SPECIAL_RIDE", "UNIQUE_3", "UNIQUE_4", "UNIQUE_5",
|
||||
"UNIQUE_6", "UNIQUE_7", "UNIQUE_8", "UNIQUE_9", "USE_SPECIAL"};
|
||||
static string arSub28[] = { "COSTUME_BODY", "COSTUME_HAIR", "COSTUME_MOUNT", "COSTUME_SASH", "COSTUME_MOUNT_SKIN" };
|
||||
static string arSub28[] = { "COSTUME_BODY", "COSTUME_HAIR", "COSTUME_MOUNT", "COSTUME_SASH", "COSTUME_MOUNT_SKIN", "COSTUME_WEAPON", "COSTUME_NEW_SASH", "COSTUME_PET" };
|
||||
static string arSub29[] = { "DS_SLOT1", "DS_SLOT2", "DS_SLOT3", "DS_SLOT4", "DS_SLOT5", "DS_SLOT6" };
|
||||
static string arSub35[] = { "SHINING_WEAPON", "SHINING_ARMOR", "SHINING_SPECIAL" };
|
||||
static string arSub37[] = { "PET_LEVELABLE", "PET_EGG", "PET_TRANSPORTBOX", "PET_PROTEIN", "PET_CHANGE_NAME_ITEM", "PET_DEW", "PET_SKILL", "PET_PRIMIUM_FEEDSTUFF", "PET_ATTR_CHANGE", "PET_ATTR_DETERMINE", "PET_EXPFOOD_PER", "PET_SKILL_DEL_BOOK", "PET_SKILL_ALL_DEL_BOOK", "PET_EXPFOOD", "PET_FEEDSTUFF" };
|
||||
static string arSub31[] = { "EXTRACT_DRAGON_SOUL", "EXTRACT_DRAGON_HEART" };
|
||||
|
||||
static string* arSubType[] = {0, //0
|
||||
@@ -162,8 +164,9 @@ int get_Item_SubType_Value(int type_value, string inputString)
|
||||
0, //32
|
||||
0, //33 반지
|
||||
0, //34 벨트
|
||||
0, //35 ITEM_SHINING
|
||||
arSub35, //35 ITEM_SHINING
|
||||
0, //36 ITEM_NEW_RINGS
|
||||
arSub37, //37 ITEM_PET
|
||||
};
|
||||
static int arNumberOfSubtype[_countof(arSubType)] = {
|
||||
0,
|
||||
@@ -201,8 +204,9 @@ int get_Item_SubType_Value(int type_value, string inputString)
|
||||
0, // 32
|
||||
0, // 33 반지
|
||||
0, // 34 벨트
|
||||
0, // 35
|
||||
sizeof(arSub35)/sizeof(arSub35[0]), // 35
|
||||
0, // 36
|
||||
sizeof(arSub37)/sizeof(arSub37[0]), // 37
|
||||
};
|
||||
|
||||
|
||||
|
||||
@@ -715,6 +715,7 @@ bool AuctionManager::InsertItem (TPlayerItem* player_item)
|
||||
}
|
||||
item->SetSockets(player_item->alSockets);
|
||||
item->SetAttributes(player_item->aAttr);
|
||||
item->SetPortExtra(player_item->extra);
|
||||
item->SetWindow(AUCTION);
|
||||
|
||||
return true;
|
||||
|
||||
@@ -10,6 +10,67 @@
|
||||
#include "../../common/ava2_itemshop.h"
|
||||
#include <sstream>
|
||||
#include <cctype>
|
||||
#include <map>
|
||||
#include <sys/time.h>
|
||||
#include <unistd.h>
|
||||
#include "char_manager.h"
|
||||
#include "questmanager.h"
|
||||
#include "config.h"
|
||||
#include "../../common/point_drop.h"
|
||||
|
||||
namespace {
|
||||
struct PendingPoints { Ava2ShopRequest request; unsigned handle; int attempts; time_t next; };
|
||||
std::map<std::string, PendingPoints> pendingPoints;
|
||||
LPEVENT pointRetryEvent = NULL;
|
||||
EVENTINFO(PointRetryInfo) {};
|
||||
EVENTFUNC(RetryPoints) {
|
||||
for(auto it=pendingPoints.begin();it!=pendingPoints.end();) {
|
||||
auto& p=it->second;
|
||||
if(get_global_time()<p.next){++it;continue;}
|
||||
if(p.attempts>=12) {
|
||||
sys_err("POINT_DROP: retry exhausted account=%u token=%s",p.request.account,p.request.token);
|
||||
it=pendingPoints.erase(it);continue;
|
||||
}
|
||||
db_clientdesc->DBPacket(76,p.handle,&p.request,sizeof(p.request));
|
||||
++p.attempts;p.next=get_global_time()+10;++it;
|
||||
}
|
||||
if(pendingPoints.empty()){pointRetryEvent=NULL;return 0;}
|
||||
return PASSES_PER_SEC(1);
|
||||
}
|
||||
bool PointReply(const Ava2ShopReply& reply,const char* data) {
|
||||
if(reply.size!=46 || uint8_t(data[0])!=9)return false;
|
||||
char token[33]={};memcpy(token,data+2,32);
|
||||
const auto found=pendingPoints.find(token);
|
||||
if(found==pendingPoints.end() || found->second.request.account!=reply.account || found->second.request.player!=reply.player)return true;
|
||||
const uint8_t status=uint8_t(data[1]);
|
||||
if(status==6 || status==8)return true; // Same durable token retries transaction/commit uncertainty.
|
||||
pendingPoints.erase(found);
|
||||
uint32_t amount=0;int64_t balance=0;memcpy(&amount,data+34,4);memcpy(&balance,data+38,8);
|
||||
auto ch=CHARACTER_MANAGER::instance().FindByPID(reply.player);
|
||||
if(status || !amount || balance<0 || !ch || !ch->GetDesc() || ch->GetDesc()->GetAccountTable().id!=reply.account)return true;
|
||||
const char* version=strstr(ch->GetDesc()->GetClientVersion(),"mt");
|
||||
if(version && atoi(version+2)>=20261021)
|
||||
ch->ChatPacket(CHAT_TYPE_COMMAND,"MTPOINTS %u %lld",amount,static_cast<long long>(balance));
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
void Ava2PointDrop(CHARACTER* ch,CHARACTER* victim) {
|
||||
if(!ch || !victim || !ch->IsPC() || !ch->GetDesc() || victim->IsPC() || victim->IsPet() ||
|
||||
(!victim->IsMonster() && !victim->IsStone()))return;
|
||||
const auto rule=PortPointRule([](const std::string& key){return quest::CQuestManager::instance().GetEventFlag(key);},victim->IsStone());
|
||||
if(!rule.eligible(victim->GetLevel(),ch->GetLevel()) || number(1,10000)>rule.chance)return;
|
||||
if(pendingPoints.size()>=4096){sys_err("POINT_DROP: pending queue full");return;}
|
||||
Ava2ShopRequest p={};p.operation=3;p.account=ch->GetDesc()->GetAccountTable().id;p.player=ch->GetPlayerID();
|
||||
p.product=victim->GetRaceNum();p.count=number(rule.minimum,rule.maximum);p.expectedVnum=ch->GetLevel();
|
||||
static const uint64_t boot=[](){timeval t;gettimeofday(&t,NULL);return (uint64_t(t.tv_sec)*1000000+t.tv_usec) ^ (uint64_t(getpid())<<32);}();
|
||||
static uint64_t serial=0;
|
||||
snprintf(p.token,sizeof(p.token),"%016llx%016llx",static_cast<unsigned long long>(boot),static_cast<unsigned long long>(++serial));
|
||||
strlcpy(p.name,ch->GetName(),sizeof(p.name));
|
||||
PendingPoints pending={p,ch->GetDesc()->GetHandle(),1,get_global_time()+10};pendingPoints.emplace(p.token,pending);
|
||||
db_clientdesc->DBPacket(76,pending.handle,&p,sizeof(p));
|
||||
if(!pointRetryEvent)pointRetryEvent=event_create(RetryPoints,AllocEventInfo<PointRetryInfo>(),PASSES_PER_SEC(1));
|
||||
}
|
||||
ACMD(do_ishop) {
|
||||
if(!ch || !ch->IsPC() || !ch->GetDesc() || ch->IsWarping() || ch->IsDead())return;
|
||||
const char* version=strstr(ch->GetDesc()->GetClientVersion(),"mt");
|
||||
@@ -33,6 +94,7 @@ ACMD(do_ishop) {
|
||||
}
|
||||
void Ava2ItemShopReply(unsigned long handle,const char* data) {
|
||||
Ava2ShopReply r;memcpy(&r,data,sizeof(r));
|
||||
if(PointReply(r,data+sizeof(r)))return;
|
||||
auto d=DESC_MANAGER::instance().FindByHandle(handle);
|
||||
if(!d || !d->IsPhase(PHASE_GAME) || !d->GetCharacter() || d->GetAccountTable().id!=r.account || d->GetCharacter()->GetPlayerID()!=r.player)return;
|
||||
#pragma pack(push,1)
|
||||
|
||||
@@ -1,2 +1,4 @@
|
||||
#pragma once
|
||||
class CHARACTER;
|
||||
void Ava2ItemShopReply(unsigned long handle,const char* data);
|
||||
void Ava2PointDrop(CHARACTER* player, CHARACTER* victim);
|
||||
|
||||
@@ -242,6 +242,7 @@ void CHARACTER::Initialize()
|
||||
m_dwLastDeadTime = get_dword_time()-180000;
|
||||
|
||||
m_bSkipSave = false;
|
||||
m_pointDropProcessed = false;
|
||||
|
||||
m_bItemLoaded = false;
|
||||
|
||||
@@ -5723,6 +5724,7 @@ void CHARACTER::LoadSafebox(int iSize, DWORD dwGold, int iItemCount, TPlayerItem
|
||||
item->SetSkipSave(true);
|
||||
item->SetSockets(pItems->alSockets);
|
||||
item->SetAttributes(pItems->aAttr);
|
||||
item->SetPortExtra(pItems->extra);
|
||||
|
||||
if (!m_pkSafebox->Add(pItems->pos, item))
|
||||
{
|
||||
@@ -5818,6 +5820,7 @@ void CHARACTER::LoadMall(int iItemCount, TPlayerItem * pItems)
|
||||
item->SetSkipSave(true);
|
||||
item->SetSockets(pItems->alSockets);
|
||||
item->SetAttributes(pItems->aAttr);
|
||||
item->SetPortExtra(pItems->extra);
|
||||
|
||||
if (!m_pkMall->Add(pItems->pos, item))
|
||||
M2_DESTROY_ITEM(item);
|
||||
|
||||
@@ -832,6 +832,7 @@ class CHARACTER : public CEntity, public CFSM, public CHorseRider
|
||||
DWORD m_dwPlayStartTime;
|
||||
BYTE m_bAddChrState;
|
||||
bool m_bSkipSave;
|
||||
bool m_pointDropProcessed; // PORT: one point-roll per defeated entity.
|
||||
std::string m_stMobile;
|
||||
char m_szMobileAuth[5];
|
||||
BYTE m_bChatCounter;
|
||||
|
||||
@@ -42,6 +42,7 @@
|
||||
#include "DragonLair.h"
|
||||
#include <random>
|
||||
#include "port_battlepass_hooks.h"
|
||||
#include "ava2_itemshop.h"
|
||||
#include <algorithm>
|
||||
DWORD AdjustExpByLevel(const LPCHARACTER ch, const DWORD exp)
|
||||
{
|
||||
@@ -739,6 +740,21 @@ void CHARACTER::RewardGold(LPCHARACTER pkAttacker)
|
||||
|
||||
void CHARACTER::Reward(bool bItemDrop)
|
||||
{
|
||||
// PORT: point ownership follows the highest present damage contributor even when EXP is zero.
|
||||
if(bItemDrop && !m_pointDropProcessed)
|
||||
{
|
||||
m_pointDropProcessed=true;
|
||||
LPCHARACTER pointOwner=NULL;int highestDamage=0;
|
||||
for(const auto& damage:m_map_kDamage)
|
||||
{
|
||||
LPCHARACTER attacker=CHARACTER_MANAGER::instance().Find(damage.first);
|
||||
if(!attacker || !attacker->IsPC() || attacker->GetMapIndex()!=GetMapIndex() ||
|
||||
DISTANCE_APPROX(GetX()-attacker->GetX(),GetY()-attacker->GetY())>5000)continue;
|
||||
if(damage.second.iTotalDamage>highestDamage){highestDamage=damage.second.iTotalDamage;pointOwner=attacker;}
|
||||
}
|
||||
Ava2PointDrop(pointOwner,this);
|
||||
}
|
||||
|
||||
if (GetRaceNum() == 5001) // 왜구는 돈을 무조건 드롭
|
||||
{
|
||||
PIXEL_POSITION pos;
|
||||
|
||||
@@ -495,6 +495,7 @@ void CHARACTER::SetItem(TItemPos Cell, LPITEM pItem)
|
||||
}
|
||||
}
|
||||
PortAttrLockSend(this,pItem,Cell.window_type,Cell.cell);
|
||||
if(pItem)PortItemExtraSend(this,pItem,Cell.window_type,Cell.cell);
|
||||
}
|
||||
|
||||
LPITEM CHARACTER::GetWear(BYTE bCell) const
|
||||
|
||||
@@ -256,7 +256,7 @@ void CInputDB::PlayerCreateSuccess(LPDESC d, const char * data)
|
||||
d->Packet(&pack, sizeof(TPacketGCPlayerCreateSuccess));
|
||||
|
||||
// 기본 무기와 귀환부를 지급
|
||||
TPlayerItem t;
|
||||
TPlayerItem t={};
|
||||
memset(&t, 0, sizeof(t));
|
||||
|
||||
if (china_event_server)
|
||||
@@ -1573,6 +1573,7 @@ void CInputDB::ItemLoad(LPDESC d, const char * c_pData)
|
||||
item->SetSkipSave(true);
|
||||
item->SetSockets(p->alSockets);
|
||||
item->SetAttributes(p->aAttr);
|
||||
item->SetPortExtra(p->extra);
|
||||
|
||||
if ((p->window == INVENTORY && ch->GetInventoryItem(p->pos)) ||
|
||||
(p->window == EQUIPMENT && ch->GetWear(p->pos)))
|
||||
|
||||
@@ -559,6 +559,13 @@ typedef struct SPacketGTLogin
|
||||
|
||||
void CInputLogin::Entergame(LPDESC d, const char * data)
|
||||
{
|
||||
// PORT: wear40 moves dragon-soul/belt cells; older clients must not enter this world.
|
||||
const char* revision=strstr(d->GetClientVersion(),"mt");
|
||||
if(!revision || atoi(revision+2)<20261022)
|
||||
{
|
||||
if(d->GetCharacter())d->GetCharacter()->ChatPacket(CHAT_TYPE_INFO,"Please update the client before entering the game.");
|
||||
d->DelayedDisconnect(1);return;
|
||||
}
|
||||
LPCHARACTER ch;
|
||||
|
||||
if (!(ch = d->GetCharacter()))
|
||||
|
||||
@@ -51,6 +51,7 @@ void CItem::Initialize()
|
||||
m_pProto = NULL;
|
||||
m_bExchanging = false;
|
||||
memset(&m_alSockets, 0, sizeof(m_alSockets));
|
||||
memset(&m_portExtra,0,sizeof(m_portExtra));
|
||||
memset(&m_aAttr, 0, sizeof(m_aAttr));
|
||||
m_portAttrLock = 0;
|
||||
m_portAttrLockLoaded = false;
|
||||
@@ -230,6 +231,7 @@ void CItem::UpdatePacket()
|
||||
sys_log(2, "UpdatePacket %s -> %s", GetName(), m_pOwner->GetName());
|
||||
m_pOwner->GetDesc()->Packet(&pack, sizeof(pack));
|
||||
PortAttrLockSend(m_pOwner,this,GetWindow(),GetCell());
|
||||
SendPortExtra();
|
||||
}
|
||||
|
||||
DWORD CItem::GetCount()
|
||||
@@ -1154,7 +1156,8 @@ void CItem::SetSockets(const long * c_al)
|
||||
|
||||
void CItem::SetSocket(int i, long v, bool bLog)
|
||||
{
|
||||
assert(i < ITEM_SOCKET_MAX_NUM);
|
||||
if(i>=3 && i<8){m_portExtra.sockets[i-3]=v;UpdatePacket();Save();return;}
|
||||
if(i<0 || i>=ITEM_SOCKET_MAX_NUM)return;
|
||||
m_alSockets[i] = v;
|
||||
UpdatePacket();
|
||||
Save();
|
||||
@@ -2249,4 +2252,30 @@ bool CItem::IsSameSpecialGroup(const LPITEM item) const
|
||||
return true;
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
||||
void PortItemExtraSend(CHARACTER* owner,CItem* item,BYTE window,WORD cell)
|
||||
{
|
||||
if(!owner || !item || !owner->GetDesc())return;
|
||||
const char* version=strstr(owner->GetDesc()->GetClientVersion(),"mt");
|
||||
if(!version || atoi(version+2)<20261022)return;
|
||||
#pragma pack(push,1)
|
||||
struct Packet { uint8_t header;uint32_t size;uint8_t op,window;uint16_t cell;uint32_t vnum,id;PortItemExtra extra; };
|
||||
#pragma pack(pop)
|
||||
Packet p={93,sizeof(Packet),10,window,cell,item->GetVnum(),item->GetID(),item->GetPortExtra()};
|
||||
owner->GetDesc()->Packet(&p,sizeof(p));
|
||||
}
|
||||
void CItem::SendPortExtra(){PortItemExtraSend(GetOwner(),this,GetWindow(),GetCell());}
|
||||
|
||||
|
||||
void CItem::SetPortAttribute(int index, BYTE type, short value)
|
||||
{
|
||||
if(index<0 || index>=15)return;
|
||||
if(index<7){SetForceAttribute(index,type,value);return;}
|
||||
m_portExtra.types[index-7]=type;m_portExtra.values[index-7]=value;
|
||||
UpdatePacket();Save();
|
||||
}
|
||||
void CItem::SetNewName(const char* name)
|
||||
{
|
||||
strlcpy(m_portExtra.name,name ? name : "",sizeof(m_portExtra.name));
|
||||
UpdatePacket();Save();
|
||||
}
|
||||
|
||||
@@ -108,10 +108,20 @@ class CItem : public CEntity
|
||||
|
||||
bool CreateSocket(BYTE bSlot, BYTE bGold);
|
||||
const long * GetSockets() { return &m_alSockets[0]; }
|
||||
long GetSocket(int i) { return m_alSockets[i]; }
|
||||
long GetSocket(int i) { return i>=0 && i<3 ? m_alSockets[i] : i>=3 && i<8 ? m_portExtra.sockets[i-3] : 0; }
|
||||
|
||||
void SetSockets(const long * al);
|
||||
void SetSocket(int i, long v, bool bLog = true);
|
||||
const PortItemExtra& GetPortExtra() const { return m_portExtra; }
|
||||
void SetPortExtra(const PortItemExtra& extra) { m_portExtra=extra; m_portExtra.name[24]=0; }
|
||||
void SendPortExtra();
|
||||
// PORT: AVA2 growth pets use fifteen skill slots; normal items retain seven.
|
||||
BYTE GetPortAttributeType(int i) const { return i>=0 && i<7 ? m_aAttr[i].bType : i>=7 && i<15 ? m_portExtra.types[i-7] : 0; }
|
||||
short GetPortAttributeValue(int i) const { return i>=0 && i<7 ? m_aAttr[i].sValue : i>=7 && i<15 ? m_portExtra.values[i-7] : 0; }
|
||||
void SetPortAttribute(int i, BYTE type, short value);
|
||||
const char* GetNewName() const { return m_portExtra.name; }
|
||||
void SetNewName(const char* name);
|
||||
|
||||
|
||||
int GetSocketCount();
|
||||
bool AddSocket();
|
||||
@@ -288,6 +298,7 @@ class CItem : public CEntity
|
||||
|
||||
bool m_bExchanging; ///< 현재 교환중 상태
|
||||
|
||||
PortItemExtra m_portExtra{};
|
||||
long m_alSockets[ITEM_SOCKET_MAX_NUM]; // 아이템 소캣
|
||||
TPlayerItemAttribute m_aAttr[ITEM_ATTRIBUTE_MAX_NUM];
|
||||
|
||||
@@ -346,3 +357,6 @@ int GetNewRingAttrMaxValue(BYTE bApply); // port_rings.cpp, 0 = not in the ring
|
||||
int GetPendantAttrMaxValue(BYTE bApply); // port_pendant.cpp, 0 = not in the talisman pool
|
||||
|
||||
#endif
|
||||
|
||||
// PORT: supplementary item metadata for AVA2 systems.
|
||||
void PortItemExtraSend(CHARACTER* owner,CItem* item,BYTE window,WORD cell);
|
||||
|
||||
@@ -454,7 +454,7 @@ void ITEM_MANAGER::SaveSingleItem(LPITEM item)
|
||||
|
||||
sys_log(1, "ITEM_SAVE %s:%d in %s window %d", item->GetName(), item->GetID(), item->GetOwner()->GetName(), item->GetWindow());
|
||||
|
||||
TPlayerItem t;
|
||||
TPlayerItem t={};
|
||||
|
||||
t.id = item->GetID();
|
||||
t.window = item->GetWindow();
|
||||
@@ -464,6 +464,7 @@ void ITEM_MANAGER::SaveSingleItem(LPITEM item)
|
||||
t.owner = (t.window == SAFEBOX || t.window == MALL) ? item->GetOwner()->GetDesc()->GetAccountTable().id : item->GetOwner()->GetPlayerID();
|
||||
thecore_memcpy(t.alSockets, item->GetSockets(), sizeof(t.alSockets));
|
||||
thecore_memcpy(t.aAttr, item->GetAttributes(), sizeof(t.aAttr));
|
||||
t.extra=item->GetPortExtra();
|
||||
|
||||
db_clientdesc->DBPacketHeader(HEADER_GD_ITEM_SAVE, 0, sizeof(TPlayerItem));
|
||||
db_clientdesc->Packet(&t, sizeof(TPlayerItem));
|
||||
|
||||
@@ -80,6 +80,7 @@ bool CSafebox::Add(DWORD dwPos, LPITEM pkItem)
|
||||
thecore_memcpy(pack.aAttr, pkItem->GetAttributes(), sizeof(pack.aAttr));
|
||||
|
||||
m_pkChrOwner->GetDesc()->Packet(&pack, sizeof(pack));
|
||||
PortItemExtraSend(m_pkChrOwner,pkItem,m_bWindowMode,dwPos);
|
||||
sys_log(1, "SAFEBOX: ADD %s %s count %d", m_pkChrOwner->GetName(), pkItem->GetName(), pkItem->GetCount());
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,64 @@
|
||||
"""Exercise paid item state round trips and inventory migration boundaries."""
|
||||
import importlib.util
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
spec = importlib.util.spec_from_file_location(
|
||||
'extended_items', ROOT/'tools/ava2-itemshop/migrate_extended_items.py')
|
||||
migration = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(migration)
|
||||
|
||||
|
||||
class ExtendedItems(unittest.TestCase):
|
||||
def test_quickslot_boundaries(self):
|
||||
positions = [0, 224, 225, 256, 257, 268, 269, 286, 287, 302, 303, 65535]
|
||||
source = b''.join(bytes([1])+p.to_bytes(2, 'little') for p in positions)
|
||||
# Skill and emotion quickslots may contain the same numeric positions.
|
||||
source += bytes([2, 1, 1, 3, 31, 1]) + bytes(108-len(source)-6)
|
||||
result = migration.quickslots(source)
|
||||
expected = [0, 224, 225, 256, 265, 276, 269, 286, 295, 310, 303, 65535]
|
||||
self.assertEqual([int.from_bytes(result[i+1:i+3], 'little')
|
||||
for i in range(0, 36, 3)], expected)
|
||||
self.assertEqual(result[36:], source[36:])
|
||||
self.assertEqual(migration.quickslots(b''), b'')
|
||||
with self.assertRaises(ValueError):
|
||||
migration.quickslots(bytes(107))
|
||||
|
||||
def test_extra_round_trip_and_corruption(self):
|
||||
source = r'''
|
||||
#include "src/server/common/port_item_extra.h"
|
||||
#include <cassert>
|
||||
#include <limits>
|
||||
int main() {
|
||||
PortItemExtra source={},decoded={};
|
||||
source.sockets[0]=std::numeric_limits<int32_t>::min();
|
||||
source.sockets[4]=std::numeric_limits<int32_t>::max();
|
||||
source.types[0]=99;source.types[7]=255;
|
||||
source.values[0]=-32768;source.values[7]=32767;
|
||||
std::memcpy(source.name,"abcdefghijklmnopqrstuvwx",24);
|
||||
auto hex=PortItemExtraHex(source);
|
||||
assert(hex.size()==138);
|
||||
assert(PortItemExtraRead(hex.c_str(),decoded));
|
||||
assert(!std::memcmp(&source,&decoded,sizeof(source)));
|
||||
// Empty DB values are pre-migration items and must load as empty state.
|
||||
assert(PortItemExtraRead("",decoded));
|
||||
PortItemExtra zero={};assert(!std::memcmp(&zero,&decoded,sizeof(zero)));
|
||||
assert(!PortItemExtraRead("00",decoded));
|
||||
hex[137]='g';assert(!PortItemExtraRead(hex.c_str(),decoded));
|
||||
assert(!std::memcmp(&zero,&decoded,sizeof(zero)));
|
||||
hex=std::string(138,'f');assert(PortItemExtraRead(hex.c_str(),decoded));
|
||||
assert(decoded.name[24]==0);
|
||||
}
|
||||
'''
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
cpp, exe = Path(tmp)/'extra.cpp', Path(tmp)/'extra'
|
||||
cpp.write_text(source)
|
||||
subprocess.run(['c++', '-std=c++17', '-I'+str(ROOT), str(cpp), '-o', str(exe)], check=True)
|
||||
subprocess.run([str(exe)], check=True)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -0,0 +1,49 @@
|
||||
"""Compile the shipping eligibility/cap arithmetic, including boundary and overflow cases."""
|
||||
import json
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
|
||||
|
||||
class PointDrop(unittest.TestCase):
|
||||
def test_approved_rules_and_cap(self):
|
||||
flags = json.loads((ROOT/'tools/ava2-itemshop/points-wide.json').read_text())
|
||||
entries = ','.join('{"%s",%d}' % entry for entry in flags.items())
|
||||
source = r'''
|
||||
#include "src/server/common/point_drop.h"
|
||||
#include <map>
|
||||
#include <cassert>
|
||||
int main() {
|
||||
std::map<std::string,int> flags={ENTRIES};
|
||||
auto lookup=[&](const std::string& key){return flags[key];};
|
||||
auto mob=PortPointRule(lookup,false),stone=PortPointRule(lookup,true);
|
||||
assert(mob.chance==500 && mob.minimum==1 && mob.maximum==1);
|
||||
assert(stone.chance==10000 && stone.minimum==3 && stone.maximum==8);
|
||||
assert(mob.eligible(105,120));assert(!mob.eligible(104,120));
|
||||
assert(stone.eligible(120,1));assert(!stone.eligible(0,1));
|
||||
assert(!stone.eligible(120,0));
|
||||
assert(PortPointDropAmount(8,498,500)==2);
|
||||
assert(PortPointDropAmount(8,500,500)==0);
|
||||
assert(PortPointDropAmount(8,UINT64_MAX,500)==0);
|
||||
assert(PortPointDropAmount(8,UINT64_MAX,0)==8);
|
||||
flags["points_mob_chance"]=0;assert(!PortPointRule(lookup,false).eligible(105,120));
|
||||
flags["points_stone_chance"]=10001;assert(!PortPointRule(lookup,true).valid());
|
||||
flags["points_stone_chance"]=10000;flags["points_stone_min"]=-1;
|
||||
assert(!PortPointRule(lookup,true).valid());
|
||||
flags["points_stone_min"]=9;flags["points_stone_max"]=3;
|
||||
assert(!PortPointRule(lookup,true).valid());
|
||||
}
|
||||
'''.replace('ENTRIES', entries)
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
src = Path(tmp)/'test.cpp'
|
||||
exe = Path(tmp)/'test'
|
||||
src.write_text(source)
|
||||
subprocess.run(['c++', '-std=c++17', '-I'+str(ROOT), str(src), '-o', str(exe)], check=True)
|
||||
subprocess.run([str(exe)], check=True)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -0,0 +1,29 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Build game/db without either Makefile's production installation default."""
|
||||
import argparse
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
|
||||
|
||||
def main():
|
||||
p = argparse.ArgumentParser(description=__doc__)
|
||||
p.add_argument('--source', type=Path, required=True, help='directory containing server/ and extern/')
|
||||
p.add_argument('--output', type=Path, required=True)
|
||||
p.add_argument('--target', choices=['game', 'db'], required=True)
|
||||
p.add_argument('--jobs', type=int, default=1)
|
||||
a = p.parse_args()
|
||||
source, output = a.source.resolve(), a.output.resolve()
|
||||
for destination in (output, (output/'bin').resolve(), (output/'work').resolve()):
|
||||
if destination == Path('/usr/metin2/server') or Path('/usr/metin2/server') in destination.parents:
|
||||
p.error('build outputs must not be inside the production server tree')
|
||||
for name in ('bin', 'work', 'obj-'+a.target):
|
||||
(output/name).mkdir(parents=True, exist_ok=True)
|
||||
# DB uses DBDIR, game uses GAMEDIR. Always override both, even when building one target.
|
||||
subprocess.run(['gmake', '-j%d' % max(1, a.jobs), 'BINDIR='+str(output/'work'),
|
||||
'GAMEDIR='+str(output/'bin'), 'DBDIR='+str(output/'bin'),
|
||||
'OBJDIR='+str(output/('obj-'+a.target))],
|
||||
cwd=source/'server'/a.target/'src', check=True)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -22,6 +22,13 @@ CREATE TABLE IF NOT EXISTS port_itemshop_orders (
|
||||
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
UNIQUE KEY request_once(account_id,token), KEY limits_by_account(account_id,product,created_at)
|
||||
) ENGINE=InnoDB;
|
||||
CREATE TABLE IF NOT EXISTS port_point_rewards (
|
||||
token CHAR(32) CHARACTER SET ascii COLLATE ascii_bin PRIMARY KEY,
|
||||
account_id INT UNSIGNED NOT NULL,player_id INT UNSIGNED NOT NULL,vnum INT UNSIGNED NOT NULL,
|
||||
requested INT UNSIGNED NOT NULL,amount INT UNSIGNED NOT NULL,reward_day DATE NOT NULL,
|
||||
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
KEY daily_account(account_id,reward_day)
|
||||
) ENGINE=InnoDB;
|
||||
ALTER TABLE ishop_data ENGINE=InnoDB;
|
||||
ALTER TABLE item_award ENGINE=InnoDB;
|
||||
ALTER TABLE `{a.account}`.account ENGINE=InnoDB;
|
||||
|
||||
@@ -0,0 +1,96 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Plan/apply the 32->40 wear-slot migration with cores/db stopped and a full backup.
|
||||
|
||||
The saved plan contains exact row IDs and before/after values. Reapplying that same plan
|
||||
is safe after interruption; never regenerate a plan from partially migrated data.
|
||||
"""
|
||||
import argparse
|
||||
import json
|
||||
from pathlib import Path
|
||||
import re
|
||||
import subprocess
|
||||
|
||||
NAME = 'ava2-shop-wear-40'
|
||||
|
||||
|
||||
def quickslots(blob):
|
||||
if not blob:
|
||||
return blob
|
||||
if len(blob) != 108:
|
||||
raise ValueError('Expected 36 three-byte quick slots')
|
||||
output = bytearray(blob)
|
||||
for index in range(0, len(blob), 3):
|
||||
kind, lo, hi = blob[index:index+3]
|
||||
pos = lo | hi << 8
|
||||
if kind == 1 and (257 <= pos <= 268 or 287 <= pos <= 302):
|
||||
output[index+1:index+3] = (pos+8).to_bytes(2, 'little')
|
||||
return bytes(output)
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('--player', required=True)
|
||||
parser.add_argument('--plan', type=Path, required=True)
|
||||
parser.add_argument('--apply', action='store_true')
|
||||
args = parser.parse_args()
|
||||
if not re.fullmatch('[A-Za-z0-9_]+', args.player):
|
||||
parser.error('Invalid database name')
|
||||
|
||||
def sql(query):
|
||||
result = subprocess.run(['mysql', '-N', '-B', args.player], input=query,
|
||||
text=True, capture_output=True, check=True)
|
||||
return [line.split('\t') for line in result.stdout.splitlines()]
|
||||
|
||||
sql('CREATE TABLE IF NOT EXISTS mt_migration(name VARCHAR(64) PRIMARY KEY,done DATETIME);')
|
||||
if sql("SELECT name FROM mt_migration WHERE name='%s';" % NAME):
|
||||
print(NAME + ': already applied')
|
||||
return
|
||||
if args.plan.exists():
|
||||
plan = json.loads(args.plan.read_text())
|
||||
if plan['schema'] != args.player:
|
||||
raise RuntimeError('Plan belongs to another database')
|
||||
else:
|
||||
# Equipped DS cells are relative; belt cells in INVENTORY are absolute.
|
||||
bad = sql("SELECT i.id FROM item i LEFT JOIN item_proto p ON i.vnum=p.vnum "
|
||||
"WHERE i.window='EQUIPMENT' AND i.pos>=32 AND "
|
||||
"(i.pos>43 OR p.type IS NULL OR p.type NOT IN (29,30));")
|
||||
if bad:
|
||||
raise RuntimeError('Unexpected occupied extended equipment cells; inspect before migration')
|
||||
items = sql("SELECT id,pos FROM item WHERE (window='EQUIPMENT' AND pos BETWEEN 32 AND 43) "
|
||||
"OR (window='INVENTORY' AND pos BETWEEN 287 AND 302) ORDER BY pos DESC;")
|
||||
plan = {'schema': args.player, 'items': [[int(i), int(p), int(p)+8] for i, p in items],
|
||||
'quickslots': []}
|
||||
for table in ('player', 'player_deleted'):
|
||||
for pid, value in sql('SELECT id,HEX(quickslot) FROM `%s`;' % table):
|
||||
old = bytes.fromhex(value)
|
||||
new = quickslots(old)
|
||||
if old != new:
|
||||
plan['quickslots'].append([table, int(pid), old.hex(), new.hex()])
|
||||
args.plan.parent.mkdir(parents=True, exist_ok=True)
|
||||
args.plan.write_text(json.dumps(plan, indent=2)+'\n')
|
||||
args.plan.chmod(0o600)
|
||||
print('planned items=%d quickslots=%d' % (len(plan['items']), len(plan['quickslots'])))
|
||||
if not args.apply:
|
||||
return
|
||||
# Every update is conditional on its original value, allowing safe saved-plan replay.
|
||||
for item, old, new in plan['items']:
|
||||
row = sql('SELECT pos FROM item WHERE id=%d;' % item)
|
||||
if row not in ([[str(old)]], [[str(new)]]):
|
||||
raise RuntimeError('Item changed since planning; cores/db must stay stopped')
|
||||
sql('UPDATE item SET pos=%d WHERE id=%d AND pos=%d;' % (new, item, old))
|
||||
for table, pid, old, new in plan['quickslots']:
|
||||
row = sql('SELECT HEX(quickslot) FROM `%s` WHERE id=%d;' % (table, pid))
|
||||
if not row or row[0][0].lower() not in (old, new):
|
||||
raise RuntimeError('Quickslot changed since planning')
|
||||
sql("UPDATE `%s` SET quickslot=X'%s' WHERE id=%d AND HEX(quickslot)='%s';" %
|
||||
(table, new, pid, old.upper()))
|
||||
columns = sql("SELECT COLUMN_NAME FROM information_schema.columns WHERE TABLE_SCHEMA=DATABASE() "
|
||||
"AND TABLE_NAME='item' AND COLUMN_NAME='port_extra';")
|
||||
if not columns:
|
||||
sql("ALTER TABLE item ADD port_extra VARBINARY(69) NOT NULL DEFAULT ''; ")
|
||||
sql("INSERT INTO mt_migration(name,done) VALUES('%s',NOW());" % NAME)
|
||||
print(NAME + ': applied; retain the saved plan for recovery')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,11 @@
|
||||
{
|
||||
"points_mob_chance": 500,
|
||||
"points_mob_min": 1,
|
||||
"points_mob_max": 1,
|
||||
"points_stone_chance": 10000,
|
||||
"points_stone_min": 3,
|
||||
"points_stone_max": 8,
|
||||
"points_min_level": 1,
|
||||
"points_max_overlevel": 15,
|
||||
"points_daily_cap": 500
|
||||
}
|
||||
Reference in New Issue
Block a user