feat: support Linux/ARM cross-platform build and AVA2 feature updates

- Port server core and libraries to Linux and 32-bit ARM (armhf):
  * Replace FreeBSD kqueue with Linux epoll in libthecore fdwatch
  * Fix unaligned float and 64-bit int memory stores in utils.h str_to_number to avoid ARM VFP alignment fault (SIGBUS)
  * Fix getopt loop variable type in main.cpp (char -> int) to eliminate infinite loop caused by default unsigned char on ARM
  * Add -fsigned-char and multi-architecture flags to Makefiles (x86_64 -m32, i386, and ARM armhf)
  * Update libsql for modern MariaDB client library (removed reconnect field) and C++20 concept/syntax compatibility
  * Replace Win32 xdirent with standard POSIX dirent on Unix/Linux
  * Include xmd5 in libthecore on non-FreeBSD platforms
- AVA2 unlock features and tools:
  * Material stacking up to 2000 count, refine material resolution and test suites
  * AVA2 ticket shop and point drop configuration updates
This commit is contained in:
shenlei
2026-11-11 00:59:49 -08:00
parent 30ea96f418
commit bb0963210e
71 changed files with 1778 additions and 485 deletions
@@ -43,7 +43,8 @@ bool LC_IsKorea(){return false;}bool LC_IsYMIR(){return false;}
#define M2_DELETE(p) delete (p)
#define M2_DESTROY_ITEM(p) ITEM_MANAGER::instance().DestroyItem(p)
struct Desc {const char* GetHostName(){return "mock";}};
struct CHARACTER {struct Points{CItem* pItems[400]={};WORD bItemGrid[400]={};CItem* pCubeItems[4]={};CItem* pSashMaterials[3]={};}m_pointsInstant;int64_t gold=1000;CItem* m_pQuestItem=nullptr;
struct CHARACTER {struct Cells{CItem* pItems[400]={};WORD bItemGrid[400]={};CItem* pCubeItems[4]={};CItem* pSashMaterials[3]={};};struct Points:Cells{Cells* pItemCells=this;Points()=default;Points(const Points& x):Cells(x){} Points& operator=(const Points& x){static_cast<Cells&>(*this)=x;pItemCells=this;return *this;}}m_pointsInstant;
const Cells& ItemCells()const{return m_pointsInstant;}int64_t gold=1000;CItem* m_pQuestItem=nullptr;
const char* GetName(){return "mock";}unsigned GetPlayerID(){return 1;}Desc* GetDesc(){return nullptr;}
CItem* GetInventoryItem(unsigned cell){return m_pointsInstant.pItems[cell];}void SetGold(int64_t value){gold=value;}
bool PortCubeInstallImage(const PortCube::InventoryImage&,const std::vector<CItem*>&,const std::vector<CItem*>&);};
@@ -57,7 +58,10 @@ struct DBDesc {void DBPacketHeader(unsigned,unsigned,unsigned){++packets;}void P
struct CSkillProto {};
struct CSkillManager {static CSkillManager& instance(){static CSkillManager m;return m;}CSkillProto* Get(unsigned){static CSkillProto p;return skills?&p:nullptr;}};
struct Limit {unsigned type=0;long value=0;};
struct TItemTable {unsigned bType=ITEM_WEAPON,bSubType=0,bSize=1;union{unsigned flags=0;unsigned dwFlags;};long values[3]={7,9,0};Limit limits[2];int sAddonType=0;unsigned bAlterToMagicItemPct=100,bGainSocketPct=0;};
namespace PortMaterialStackPolicy {inline unsigned Limit(unsigned,bool stackable,bool,unsigned){return stackable?2000:200;}inline bool LegacyGrowthMode(){return false;}}
namespace quest {struct CQuestManager{static CQuestManager& instance(){static CQuestManager q;return q;}int GetEventFlag(const char*){return 0;}};}
constexpr unsigned ITEM_ANTIFLAG_STACK=1;
struct TItemTable {unsigned dwAntiFlags=0,dwVnum=0;unsigned bType=ITEM_WEAPON,bSubType=0,bSize=1;union{unsigned flags=0;unsigned dwFlags;};long values[3]={7,9,0};Limit limits[2];int sAddonType=0;unsigned bAlterToMagicItemPct=100,bGainSocketPct=0;};
struct Attr {BYTE bType=0;short sValue=0;};
#pragma pack(push,1)
struct Extra {int32_t sockets[5]={};BYTE types[8]={};int16_t values[8]={};char name[25]={};};
@@ -76,7 +80,7 @@ struct CItem {
void SetWindow(unsigned w){m_bWindow=w;}unsigned GetWindow(){return m_bWindow;}
bool isLocked(){return locked;}bool IsExchanging(){return exchanging;}bool PortCubeHasPendingMutation(){return clock;}
void PortCubeInitNewAttach();bool PortCubeRestoreMetadata(const PortEconomy::Reward&);void PortCubeAttachRestored(CHARACTER*,WORD);
bool IsStackable(){return proto->flags&1;}unsigned GetFlag(){return proto->flags;}long GetValue(unsigned i){return proto->values[i];}
unsigned GetStackLimit(){return IsStackable()?2000:200;}bool IsStackable(){return proto->flags&1;}unsigned GetFlag(){return proto->flags;}long GetValue(unsigned i){return proto->values[i];}
void SetID(unsigned value){id=value;}unsigned GetID(){return id;}void SetVID(unsigned value){vid=value;}unsigned GetVID(){return vid;}
void SetSkipSave(bool value){m_bSkipSave=value;}bool GetSkipSave(){return m_bSkipSave;}
void Save();void UpdatePacket(){if(!m_portCubeTemplate)++packets;}
+5 -5
View File
@@ -16,12 +16,12 @@ using DWORD=uint32_t;using BYTE=uint8_t;using WORD=uint16_t;
const int SHOP_HOST_ITEM_MAX_NUM=40,HEADER_GC_SHOP=38,CHAT_TYPE_COMMAND=1;
enum {SHOP_SUBHEADER_GC_START,SHOP_SUBHEADER_GC_END,SHOP_SUBHEADER_GC_UPDATE_ITEM,SHOP_SUBHEADER_GC_UPDATE_PRICE,SHOP_SUBHEADER_GC_OK,SHOP_SUBHEADER_GC_NOT_ENOUGH_MONEY,SHOP_SUBHEADER_GC_SOLDOUT,SHOP_SUBHEADER_GC_INVENTORY_FULL,SHOP_SUBHEADER_GC_INVALID_POS,SHOP_SUBHEADER_GC_SOLD_OUT,SHOP_SUBHEADER_GC_START_EX,SHOP_SUBHEADER_GC_NOT_ENOUGH_MONEY_EX,SHOP_SUBHEADER_GC_START_ITEM_CURRENCY,SHOP_SUBHEADER_GC_NOT_ENOUGH_ITEM};
#pragma pack(push,1)
struct WireItem { DWORD vnum;int64_t price;BYTE count,display_pos;char rest[33]; };
struct WireItem { DWORD vnum;int64_t price;WORD count;BYTE display_pos;char rest[33]; };
struct TPacketGCShopStart { DWORD owner_vid;WireItem items[40]; };
struct TPacketGCShop { BYTE header;WORD size;BYTE subheader; };
#pragma pack(pop)
static_assert(sizeof(WireItem)==47,"baseline item");
struct TShopItemTable { DWORD vnum;BYTE count; };
static_assert(sizeof(WireItem)==48,"baseline item");
struct TShopItemTable { DWORD vnum;WORD count; };
struct Desc { std::string frame;void BufferedPacket(const void* p,size_t n){frame.assign((const char*)p,n);}void Packet(const void* p,size_t n){frame.append((const char*)p,n);} };
class CShop;
struct Character {
@@ -43,7 +43,7 @@ struct CQuestManager {PC pc;static CQuestManager& instance(){static CQuestManage
struct ITEM_MANAGER {bool valid=true;static ITEM_MANAGER& instance(){static ITEM_MANAGER i;return i;}const int* GetTable(DWORD){static int proto=1;return valid?&proto:nullptr;}};
class CShop {
protected:
struct SHOP_ITEM {DWORD vnum=0;BYTE count=0;int price=0;};
struct SHOP_ITEM {DWORD vnum=0;WORD count=0;int price=0;};
using GuestMapType=std::map<Character*,bool>;
GuestMapType m_map_guest;std::vector<SHOP_ITEM> m_itemVector;
public:
@@ -56,7 +56,7 @@ main=r'''
int main(){
Character c;c.items[90011]=30;
assert(Ava2OpenTicketShop(&c));assert(Ava2IsTicketShop(c.GetShop()));assert(c.GetShopOwner()==&c);
assert(c.desc.frame.size()==2208);
assert(c.desc.frame.size()==2248);
Ava2ShopStart start;memcpy(&start,c.desc.frame.data()+sizeof(TPacketGCShop),sizeof(start));
assert(start.shop.owner_vid==0 && start.shop.items[7].vnum==25170 && start.prices[0].vnum==90011 && start.prices[7].count==30);
assert(c.GetShop()->Buy(&c,0)==SHOP_SUBHEADER_GC_OK);assert(c.items[25163]==1 && c.items[90011]==20 && c.gold==123456);
+8 -8
View File
@@ -9,7 +9,7 @@ ROOT=Path(__file__).resolve().parents[2]
class CubeHandshake(unittest.TestCase):
def test_actual_game_snapshot_covers_all_owned_windows_and_metadata(self):
body=(ROOT/'src/server/game/src/port_cube_actor.cpp').read_text().split('struct Snapshot ',1)[1].split('bool matches(',1)[0]
body=(ROOT/'src/server/game/src/port_cube_actor.cpp').read_bytes().decode('latin1').split('struct Snapshot ',1)[1].split('bool matches(',1)[0]
source=r'''
#include "src/server/common/cube_handshake.h"
#include "src/server/common/cube_craft.h"
@@ -52,7 +52,7 @@ int main(){CHARACTER ch,foreign;Item item;item.owner=&ch;item.sockets[0]=INT32_M
subprocess.run([str(exe)],check=True)
def test_bounded_wire_and_fail_closed_actor_state(self):
prefix=(ROOT/'tests/features/fixtures/cube_batch_probe.cpp').read_text().split('int main(int argc,char** argv)',1)[0]
prefix=(ROOT/'tests/features/fixtures/cube_batch_probe.cpp').read_bytes().decode('latin1').split('int main(int argc,char** argv)',1)[0]
tests=r'''
#include "src/server/common/cube_handshake.h"
int main(){
@@ -96,7 +96,7 @@ int main(){
subprocess.run([str(exe)],check=True)
def test_flush_includes_dirty_detached_items_without_stealing_other_owners(self):
body=(ROOT/'src/server/game/src/port_cube_flush.inc').read_text()
body=(ROOT/'src/server/game/src/port_cube_flush.inc').read_bytes().decode('latin1')
source=r'''
#include <cassert>
#include <unordered_set>
@@ -120,14 +120,14 @@ int main(){CHARACTER a{1},b{2};CItem owned{&a,1},detached{nullptr,1},foreign{&b,
subprocess.run([str(exe)],check=True)
def test_game_dispatch_keeps_gate_closed_and_saves_precede_submit(self):
source=(ROOT/'src/server/game/src/port_cube_actor.cpp').read_text()
source=(ROOT/'src/server/game/src/port_cube_actor.cpp').read_bytes().decode('latin1')
self.assertIn('if(!PortCube::HandshakeEnabled||!PortCube::ActorMutationAuditComplete)return false;',source)
self.assertLess(source.index('ch->SaveReal();'),source.index('o.flow.Submit(true,now)'))
self.assertIn('FlushDelayedSaveForPlayer(f.player)',source)
self.assertIn('PortCubeActorHeld(this)',(ROOT/'src/server/game/src/char_item.cpp').read_text())
self.assertIn('PortCubeActorForget(this)',(ROOT/'src/server/game/src/char.cpp').read_text())
self.assertIn('PortCubeActorTick();',(ROOT/'src/server/game/src/main.cpp').read_text())
db=(ROOT/'src/server/game/src/input_db.cpp').read_text()
self.assertIn('PortCubeActorHeld(this)',(ROOT/'src/server/game/src/char_item.cpp').read_bytes().decode('latin1'))
self.assertIn('PortCubeActorForget(this)',(ROOT/'src/server/game/src/char.cpp').read_bytes().decode('latin1'))
self.assertIn('PortCubeActorTick();',(ROOT/'src/server/game/src/main.cpp').read_bytes().decode('latin1'))
db=(ROOT/'src/server/game/src/input_db.cpp').read_bytes().decode('latin1')
self.assertIn('!PortCube::DecodeHandshake(pRealData,size_t(iSize),frame)',db)
# These two legacy-encoding files only receive narrow ASCII insertions.
self.assertIn(b'#include "port_cube_flush.inc"',(ROOT/'src/server/game/src/item_manager.cpp').read_bytes())
+12 -9
View File
@@ -36,7 +36,7 @@ class CubeMutation(unittest.TestCase):
self.assertIn('misses aliases',report['warning'])
def test_item_admission_is_read_only_and_preserves_expiry_paths(self):
body=(SRC/'port_cube_item.inc').read_text()
body=(SRC/'port_cube_item.inc').read_bytes().decode('latin1')
run(r'''
#include <cassert>
#include <initializer_list>
@@ -53,7 +53,7 @@ int main(){CItem item;assert(item.PortCubeHasPendingMutation());Proto proto;item
''')
def test_actual_preparation_admission_combines_context_and_owned_item_hazards(self):
body=function((SRC/'port_cube_actor.cpp').read_text(),'uint32_t PortCubeAdmission(')
body=function((SRC/'port_cube_actor.cpp').read_bytes().decode('latin1'),'uint32_t PortCubeAdmission(')
run(r'''
#include "src/server/common/cube_mutation.h"
#include <cassert>
@@ -74,8 +74,8 @@ int main(){using namespace PortCube;CHARACTER ch;Item item;ch.items={&item};asse
ch.desc=false;assert(PortCubeAdmission(&ch)==MissingState);assert(PortCubeAdmission(nullptr)==MissingState);
}
''')
current=(SRC/'item.cpp').read_text()
original=subprocess.check_output(['git','show','HEAD:src/server/game/src/item.cpp'],cwd=ROOT).decode()
current=(SRC/'item.cpp').read_bytes().decode('latin1')
original=subprocess.check_output(['git','show','HEAD:src/server/game/src/item.cpp'],cwd=ROOT).decode('latin1')
for event in ['unique_expire_event','timer_based_on_wear_expire_event','real_time_expire_event','accessory_socket_expire_event']:
current_body=function(current,'EVENTFUNC('+event+')')
original_body=function(original,'EVENTFUNC('+event+')')
@@ -84,12 +84,15 @@ int main(){using namespace PortCube;CHARACTER ch;Item item;ch.items={&item};asse
# original expiry deadlines, effects and scheduling stay exact.
checked='const item_vid_event_info* info = dynamic_cast<const item_vid_event_info*>(event->info); // PORT: prepared clock info is a checked subtype.'
self.assertEqual(current_body.count(checked),1)
legacy=re.search(r'[^\n]*info = reinterpret_cast<[^\n]*',original_body).group(0).lstrip()
current_body=current_body.replace(checked,legacy)
legacy=re.search(r'[^\n]*info = reinterpret_cast<[^\n]*',original_body)
if legacy:
current_body=current_body.replace(checked,legacy.group(0).lstrip())
else:
self.assertIn(checked,original_body)
self.assertEqual(current_body,original_body)
def test_item_save_notifies_but_does_not_drop_or_redirect_original_save(self):
body=function((SRC/'item.cpp').read_text(),'void CItem::Save()')
body=function((SRC/'item.cpp').read_bytes().decode('latin1'),'void CItem::Save()')
run(r'''
#include "src/server/common/cube_mutation.h"
#include <cassert>
@@ -124,7 +127,7 @@ int main(){PC pc;pc.SetFlag("gem.points",5);assert(pc.m_FlagMap.at("gem.points")
''')
def test_switchbot_yields_whole_roll_before_state_rng_or_cost(self):
text=(SRC/'port_switchbot.cpp').read_text()
text=(SRC/'port_switchbot.cpp').read_bytes().decode('latin1')
prefix=text.split('void CSwitchbot::SwitchItems()',1)[1].split('for (BYTE bSlot',1)[0]
run(r'''
#include <cassert>
@@ -142,7 +145,7 @@ int main(){CSwitchbot bot;bot.SwitchItems();assert(rolls==0);held=false;bot.Swit
self.assertLess(text.index('PortCubeActorHeld(',text.index('void CSwitchbot::SwitchItems()')),text.index('m_table.finished[bSlot] = false;',text.index('void CSwitchbot::SwitchItems()')))
def test_gold_and_lifecycle_notifications_are_not_setter_vetoes(self):
text=(SRC/'char.cpp').read_text()
text=(SRC/'char.cpp').read_bytes().decode('latin1')
self.assertIn('if(type==POINT_GOLD&&amount)PortCubeAssetMutation(this,PortCube::GoldWrite);',function(text,'void CHARACTER::PointChange('))
for signature in ['void CHARACTER::Disconnect(', 'bool CHARACTER::WarpSet(long x, long y, long lPrivateMapIndex, BYTE targetChannel)']:
self.assertIn('PortCubeAssetMutation(this,PortCube::LifecycleWrite);',function(text,signature))
+5 -5
View File
@@ -10,7 +10,7 @@ ROOT = Path(__file__).resolve().parents[2]
class CubeRecovery(unittest.TestCase):
def test_wire_and_actual_game_preload_controller(self):
body = (ROOT/'src/server/game/src/port_cube_recovery.cpp').read_text()
body = (ROOT/'src/server/game/src/port_cube_recovery.cpp').read_bytes().decode('latin1')
body = re.sub(r'^#include[^\n]*\n', '', body, flags=re.M)
# Explicit audit-gate substitute, never modify the production constants.
body = body.replace('return PortCube::HandshakeEnabled&&PortCube::ActorMutationAuditComplete;', 'return auditedGate;')
@@ -101,13 +101,13 @@ int main(){
subprocess.run([str(exe)],check=True)
def test_real_select_dispatch_and_frame_whitelist(self):
select=(ROOT/'src/server/game/src/input_login.cpp').read_text().split('void CInputLogin::CharacterSelect(',1)[1].split('bool NewPlayerTable',1)[0]
select=(ROOT/'src/server/game/src/input_login.cpp').read_bytes().decode('latin1').split('void CInputLogin::CharacterSelect(',1)[1].split('bool NewPlayerTable',1)[0]
self.assertLess(select.index('PortCubeRecoverySelect('),select.index('DBPacket(HEADER_GD_PLAYER_LOAD'))
db=(ROOT/'src/server/game/src/input_db.cpp').read_text()
db=(ROOT/'src/server/game/src/input_db.cpp').read_bytes().decode('latin1')
self.assertIn('!PortCube::IsDbHandshakeReply(frame.message)',db)
self.assertIn('PortCubeRecoveryReply(m_dwHandle,c_pData,size)',db)
self.assertIn('PortCubeRecoveryTick();',(ROOT/'src/server/game/src/main.cpp').read_text())
self.assertIn('port_cube_recovery.cpp',(ROOT/'src/server/game/src/Makefile').read_text())
self.assertIn('PortCubeRecoveryTick();',(ROOT/'src/server/game/src/main.cpp').read_bytes().decode('latin1'))
self.assertIn('port_cube_recovery.cpp',(ROOT/'src/server/game/src/Makefile').read_bytes().decode('latin1'))
if __name__ == '__main__':
@@ -0,0 +1,51 @@
"""Compile actual merge/split metadata helpers with an explicit attribute-lock DB boundary."""
from pathlib import Path
import subprocess,tempfile,unittest
ROOT=Path(__file__).resolve().parents[2]
class Identity(unittest.TestCase):
def test_actual_helpers_preserve_identity_and_fail_closed(self):
source=(ROOT/'src/server/game/src/item.cpp').read_bytes().decode('latin1')
actual=source[source.index('bool CItem::CanStackWith('):source.index('DWORD CItem::GetCount()')]
prefix=r'''
#include <cassert>
#include <cstring>
#include <cstdint>
struct Proto {unsigned dwVnum=30006,dwAntiFlags=0;};
constexpr unsigned ITEM_FLAG_STACKABLE=4,ITEM_ANTIFLAG_STACK=32768;
struct Extra {unsigned char bytes[69]={};};
struct CItem {Proto proto;const Proto* m_pProto=&proto;unsigned m_dwVnum=30006,m_dwMaskVnum=0,m_dwSIGVnum=0,m_lFlag=4;
bool m_bExchanging=false,m_isLocked=false,m_portAttrLockLoaded=false;unsigned m_portAttrLock=0,storedMask=0;
int32_t m_alSockets[3]={};unsigned char m_aAttr[21]={};Extra m_portExtra;
unsigned GetOriginalVnum(){return m_dwVnum;}const int32_t* GetSockets(){return m_alSockets;}
void SetSockets(const int32_t* s){memcpy(m_alSockets,s,sizeof(m_alSockets));}void CopyAttributeTo(CItem* x){memcpy(x->m_aAttr,m_aAttr,sizeof(m_aAttr));}
const Extra& GetPortExtra(){return m_portExtra;}void SetPortExtra(const Extra& x){m_portExtra=x;}
bool CanStackWith(const CItem*)const;bool CopyStackStateTo(CItem*);
};
static bool failRead=false,failWrite=false;
unsigned PortAttrLockGet(CItem* x){if(!x->m_portAttrLockLoaded&&!failRead){x->m_portAttrLock=x->storedMask;x->m_portAttrLockLoaded=true;}return x->m_portAttrLock;}
bool PortAttrLockSet(void*,CItem* x,unsigned m){if(failWrite)return false;x->storedMask=x->m_portAttrLock=m;return x->m_portAttrLockLoaded=true;}
'''
cases=r'''
int main(){CItem a,b;assert(a.CanStackWith(&b));
b.m_alSockets[0]=1;assert(!a.CanStackWith(&b));b.m_alSockets[0]=0;
b.m_aAttr[20]=1;assert(!a.CanStackWith(&b));b.m_aAttr[20]=0;
b.m_portExtra.bytes[68]=1;assert(!a.CanStackWith(&b));b.m_portExtra.bytes[68]=0;
b.storedMask=1;b.m_portAttrLockLoaded=false;assert(!a.CanStackWith(&b));assert(b.m_portAttrLockLoaded);
a.storedMask=1;a.m_portAttrLockLoaded=false;assert(a.CanStackWith(&b));
b.m_isLocked=true;assert(!a.CanStackWith(&b));b.m_isLocked=false;
b.m_bExchanging=true;assert(!a.CanStackWith(&b));b.m_bExchanging=false;
b.proto.dwAntiFlags=ITEM_ANTIFLAG_STACK;assert(!a.CanStackWith(&b));b.proto.dwAntiFlags=0;
b.m_dwVnum++;assert(!a.CanStackWith(&b));b.m_dwVnum--;
b.m_dwMaskVnum=99;assert(!a.CanStackWith(&b));b.m_dwMaskVnum=0;
b.m_dwSIGVnum=1;assert(!a.CanStackWith(&b));b.m_dwSIGVnum=0;
a.m_alSockets[2]=123;a.m_aAttr[20]=9;a.m_portExtra.bytes[68]=7;
CItem split;failWrite=true;assert(!a.CopyStackStateTo(&split));failWrite=false;assert(a.CopyStackStateTo(&split));
assert(split.storedMask==1&&a.CanStackWith(&split));
CItem unavailable;failRead=true;assert(!unavailable.CopyStackStateTo(&split)&&!unavailable.CanStackWith(&b));
}
'''
with tempfile.TemporaryDirectory() as td:
p=Path(td)/'probe.cpp';p.write_text(prefix+actual+cases);exe=Path(td)/'probe'
subprocess.run(['c++','-std=c++17','-fsanitize=address,undefined',str(p),'-o',str(exe)],check=True)
subprocess.run([str(exe)],check=True)
if __name__=='__main__':unittest.main()
@@ -0,0 +1,48 @@
#!/usr/bin/env python3
"""Compile the active item-level material policy and verify its grant/storage rules."""
import pathlib
import subprocess
import tempfile
root = pathlib.Path(__file__).resolve().parents[2]
source = r'''
#include <cstdint>
typedef uint8_t BYTE;
typedef uint16_t WORD;
#include "src/server/common/length.h"
#include "src/server/common/item_length.h"
#include "src/server/game/src/port_material_stack_policy.h"
#include <cassert>
int main() {
using namespace PortMaterialStackPolicy;
for (auto t : {ITEM_USE, ITEM_AUTOUSE, ITEM_MATERIAL, ITEM_METIN,
ITEM_RESOURCE, ITEM_BLEND, ITEM_EXTRACT})
assert(Limit(t, true, false) == 2000);
assert(Limit(ITEM_USE, false, false) == 200);
assert(Limit(ITEM_USE, true, true) == 200);
assert(Limit(ITEM_QUEST, true, false) == 200);
assert(Limit(ITEM_TREASURE_BOX, true, false) == 200);
assert(Limit(ITEM_WEAPON, false, false) == 200);
assert(GrantLimit(ITEM_WEAPON, false, false) == 1);
assert(GrantLimit(ITEM_USE, true, true) == 1);
setenv("PORT_MATERIAL_STACK_QA_LOGIN", "alice,bob", 1);
assert(QAAllowed("alice") && QAAllowed("bob") && !QAAllowed("ali") && !QAAllowed("eve"));
unsetenv("PORT_MATERIAL_STACK_QA_LOGIN");
assert(QAAllowed("eve"));
setenv("PORT_MATERIAL_STACK_LEGACY_MODE", "1", 1);
assert(LegacyGrowthMode());
assert(Limit(ITEM_USE, true, false) == 2000); // Reading old wide rows remains safe.
unsetenv("PORT_MATERIAL_STACK_LEGACY_MODE");
assert(!LegacyGrowthMode());
RefineIngredients().insert(999001);
assert(Limit(ITEM_QUEST, true, false, 999001) == 2000);
assert(Limit(ITEM_QUEST, true, false, 999002) == 200);
}
'''.replace('#include <cassert>', '#include <cassert>\n#include <initializer_list>')
with tempfile.TemporaryDirectory() as td:
path = pathlib.Path(td) / 'policy.cpp'
path.write_text(source)
exe = pathlib.Path(td) / 'policy'
subprocess.run(['c++', '-std=c++11', '-I', str(root), str(path), '-o', str(exe)], check=True)
subprocess.run([str(exe)], check=True)
print('PASS: material stack policy')
@@ -0,0 +1,41 @@
"""Actual refinement debit planner with explicit inventory primitives; no RNG or wallet substitutes."""
import subprocess,tempfile,unittest
from pathlib import Path
ROOT=Path(__file__).resolve().parents[2]
class Refine(unittest.TestCase):
def test_atomic_aggregate_debits_across_storage_and_invalid_sources(self):
code=r'''
#include <algorithm>
#include <map>
#include <vector>
#include <cstdint>
#include <cassert>
#define ENABLE_SPECIAL_STORAGE
using DWORD=uint32_t;using BYTE=uint8_t;
enum{INVENTORY=1,UPGRADE_INVENTORY=8,BOOK_INVENTORY,STONE_INVENTORY,CHANGE_INVENTORY,COSTUME_INVENTORY};
constexpr unsigned INVENTORY_MAX_NUM=225,SPECIAL_INVENTORY_MAX_NUM=180;
struct Material{DWORD vnum,count;};struct TRefineTable{unsigned material_count=0;Material materials[5]={};};
struct TItemPos{unsigned window,cell;TItemPos(unsigned w,unsigned c):window(w),cell(c){}};
struct Character;
struct Item{unsigned id,cell,vnum,count;Character* owner=nullptr;bool equipped=false,exchanging=false,locked=false,skip=false;
unsigned GetID(){return id;}unsigned GetCell(){return cell;}unsigned GetVnum(){return vnum;}unsigned GetCount(){return count;}
Character* GetOwner(){return owner;}bool IsEquipped(){return equipped;}bool IsExchanging(){return exchanging;}bool isLocked(){return locked;}bool GetSkipSave(){return skip;}void SetCount(unsigned n){assert(n<=count);count=n;}};
using LPITEM=Item*;struct Shop{unsigned selling=0;bool IsSellingItem(unsigned id){return id==selling;}};
struct Character{std::map<std::pair<unsigned,unsigned>,Item*> items;Shop shop;Item* GetItem(TItemPos p){auto it=items.find({p.window,p.cell});return it==items.end()?nullptr:it->second;}Shop* GetMyShop(){return &shop;}};
using LPCHARACTER=Character*;
#include "src/server/game/src/port_refine_materials.h"
int main(){Character ch;Item a{1,0,30053,2000,&ch},b{2,1,30006,1000,&ch};ch.items[{UPGRADE_INVENTORY,0}]=&a;ch.items[{INVENTORY,1}]=&b;
TRefineTable r;r.material_count=1;r.materials[0]={30053,1};assert(PortRefineTakeMaterials(&ch,&r)&&a.count==1999);
r.material_count=2;r.materials[0]={30053,1000};r.materials[1]={30053,1000};assert(!PortRefineTakeMaterials(&ch,&r)&&a.count==1999);
r.materials[1].count=999;assert(PortRefineTakeMaterials(&ch,&r)&&a.count==0);
r.material_count=1;r.materials[0]={30006,256};
for(unsigned kind=0;kind<5;++kind){b.equipped=kind==0;b.exchanging=kind==1;b.locked=kind==2;b.skip=kind==3;ch.shop.selling=kind==4?b.id:0;assert(!PortRefineTakeMaterials(&ch,&r)&&b.count==1000);}
b.equipped=b.exchanging=b.locked=b.skip=false;ch.shop.selling=0;assert(PortRefineTakeMaterials(&ch,&r)&&b.count==744);
r.material_count=2;r.materials[0]={30006,500};r.materials[1]={30053,1};assert(!PortRefineTakeMaterials(&ch,&r)&&b.count==744);
r.material_count=0;assert(PortRefineTakeMaterials(&ch,&r));
}
'''
with tempfile.TemporaryDirectory() as td:
p=Path(td)/'probe.cpp';p.write_text(code);exe=Path(td)/'probe'
subprocess.run(['c++','-std=c++17','-fsanitize=address,undefined','-I'+str(ROOT),str(p),'-o',str(exe)],check=True);subprocess.run([str(exe)],check=True)
if __name__=='__main__':unittest.main()
+5 -2
View File
@@ -20,8 +20,9 @@ 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.chance==5000 && mob.minimum==3 && mob.maximum==5);
assert(stone.chance==10000 && stone.minimum==15 && stone.maximum==30);
assert(mob.dailyCap==0 && stone.dailyCap==0);
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));
@@ -29,6 +30,8 @@ int main() {
assert(PortPointDropAmount(8,500,500)==0);
assert(PortPointDropAmount(8,UINT64_MAX,500)==0);
assert(PortPointDropAmount(8,UINT64_MAX,0)==8);
assert(PortPointDropAmount(30,500,stone.dailyCap)==30);
assert(PortPointDropAmount(30,1000000,stone.dailyCap)==30);
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;
+79
View File
@@ -0,0 +1,79 @@
"""Operational point rollout must target the intended DB and enable chances last."""
import importlib.util
import json
from pathlib import Path
import tempfile
import unittest
from unittest.mock import Mock, patch
ROOT = Path(__file__).resolve().parents[2]
spec = importlib.util.spec_from_file_location(
'point_rollout', ROOT / 'tools/ava2-itemshop/configure_point_drops.py')
rollout = importlib.util.module_from_spec(spec)
spec.loader.exec_module(rollout)
class PointRollout(unittest.TestCase):
def test_only_reviewed_rules_are_enabled_after_caps_and_eligibility(self):
approved = json.loads((ROOT / 'tools/ava2-itemshop/points-wide.json').read_text())
self.assertEqual(rollout.APPROVED, approved)
commands = rollout.rollout({}, approved)
self.assertEqual(commands[:2], [('points_mob_chance', 0), ('points_stone_chance', 0)])
self.assertEqual(commands[-2:], [('points_mob_chance', 5000), ('points_stone_chance', 10000)])
self.assertIn(('points_daily_cap', 0), commands[2:-2])
self.assertIn(('points_mob_min', 3), commands[2:-2])
self.assertIn(('points_mob_max', 5), commands[2:-2])
self.assertIn(('points_stone_min', 15), commands[2:-2])
self.assertIn(('points_stone_max', 30), commands[2:-2])
self.assertIn(('points_max_overlevel', 15), commands[2:-2])
self.assertEqual(dict(commands), approved)
self.assertEqual(rollout.rollout(approved, approved), [])
def test_restoring_absent_flags_disables_rewards(self):
disabled = {key: 0 for key in rollout.APPROVED}
commands = rollout.rollout(rollout.APPROVED, disabled)
self.assertTrue(commands)
self.assertEqual(dict(commands), disabled)
self.assertFalse(any(value for key, value in commands if key in rollout.CHANCES))
def test_schema_and_db_port_mismatches_fail_closed(self):
with tempfile.TemporaryDirectory() as directory:
config = Path(directory) / 'CONFIG'
database = Path(directory) / 'conf.txt'
config.write_text('PORT: 13040\nDB_PORT: 15040\nADMINPAGE_IP: 127.0.0.1\n'
'ADMINPAGE_PASSWORD: local-test-only\n')
database.write_text('SQL_PLAYER = "localhost player_sb root test"\n'
'SQL_ACCOUNT = "localhost account_sb root test"\n')
rollout.validate_target(config, database, 'player_sb', 'account_sb', 15040)
with self.assertRaisesRegex(RuntimeError, 'schemas'):
rollout.validate_target(config, database, 'player', 'account', 15040)
with self.assertRaisesRegex(RuntimeError, 'DB_PORT'):
rollout.validate_target(config, database, 'player_sb', 'account_sb', 15000)
with self.assertRaisesRegex(RuntimeError, 'schema name'):
rollout.validate_target(config, database, 'player; DROP DATABASE player', 'account', 15040)
def test_lan_listener_uses_allowlisted_loopback_source_and_checks_event_ack(self):
connection = Mock()
connection.recv.side_effect = [b'\xff' * 15, rollout.socket.timeout(),
b'UNKNOWN\n', b'EVENT FLAG CHANGE points_mob_chance\n']
with patch.object(rollout.socket, 'create_connection', return_value=connection) as connect:
admin = rollout.Admin({'port': '13040', 'adminpage_password': 'test-only'},
'192.168.21.203')
admin.event('points_mob_chance', 500)
connect.assert_called_once_with(('192.168.21.203', 13040), timeout=3,
source_address=('127.0.0.1', 0))
self.assertEqual(connection.sendall.call_args_list[-1].args,
(b'@EVENT points_mob_chance 500\n',))
def test_unaccepted_event_does_not_count_as_applied(self):
connection = Mock()
connection.recv.side_effect = [rollout.socket.timeout(), b'UNKNOWN\n', b'UNKNOWN\n']
with patch.object(rollout.socket, 'create_connection', return_value=connection):
admin = rollout.Admin({'port': '13040', 'adminpage_password': 'test-only'},
'192.168.21.203')
with self.assertRaisesRegex(RuntimeError, 'rejected'):
admin.event('points_mob_chance', 500)
if __name__ == '__main__':
unittest.main()
@@ -108,6 +108,18 @@ int main(){
// Zero grants are durable results; later replay does not recalculate the cap.
handler.m_map_lEventFlag["points_daily_cap"]=16;assert(settle(handler,r)==0 && granted()==0 && durable.coins==116);
handler.m_map_lEventFlag["points_daily_cap"]=500;assert(settle(handler,r)==0 && granted()==0 && durable.coins==116);
// Removing the daily cap permits new rewards even after exceeding the old
// allowance. Committed tokens, including old zero grants, still replay once.
durable.rewards["old_daily_total"]={1,3,8021,1000,1000};
handler.m_map_lEventFlag["points_daily_cap"]=0;
assert(settle(handler,r)==0 && granted()==0 && durable.coins==116);
handler.m_map_lEventFlag["points_stone_min"]=15;
handler.m_map_lEventFlag["points_stone_max"]=30;r.count=30;
strcpy(r.token,"4123456789abcdef0123456789abcdef");
assert(settle(handler,r)==0 && granted()==30 && durable.coins==146);
assert(settle(handler,r)==0 && granted()==30 && durable.coins==146);
strcpy(r.token,"5123456789abcdef0123456789abcdef");
assert(settle(handler,r)==0 && granted()==30 && durable.coins==176);
}
'''
with tempfile.TemporaryDirectory() as tmp:
+10 -6
View File
@@ -27,8 +27,8 @@ enum {POINT_GOLD,PORT_BP_NPC_SPEND,QUICKSLOT_TYPE_ITEM,DRAGON_SOUL_INVENTORY,INV
bool LC_IsYMIR(){return false;}bool LC_IsKorea(){return false;}
struct Character;using LPCHARACTER=Character*;
struct TItemPos{TItemPos(int,int){}};
struct Item {DWORD vnum=19,id=1;BYTE count=1;Character* owner=nullptr;
DWORD GetVnum(){return vnum;}DWORD GetID(){return id;}BYTE GetCount(){return count;}
struct Item {DWORD vnum=19,id=1;uint16_t count=1;Character* owner=nullptr;
DWORD GetVnum(){return vnum;}DWORD GetID(){return id;}uint16_t GetCount(){return count;}
Character* GetOwner(){return owner;}int GetSize(){return 1;}bool IsDragonSoul(){return false;}
const char* GetName(){return "item";}int GetCell(){return 0;}
void RemoveFromCharacter(){owner=nullptr;}void AddToCharacter(Character* c,TItemPos){owner=c;}
@@ -43,21 +43,25 @@ struct Character {int64_t gold=0;bool full=false;int writes=0,saves=0;
struct ITEM_MANAGER {std::map<int,Item*> items;int created=0,destroyed=0;
static ITEM_MANAGER& instance(){static ITEM_MANAGER m;return m;}
Item* Find(int id){return items.count(id)?items[id]:nullptr;}
Item* CreateItem(DWORD vnum,BYTE count){auto* item=new Item;item->vnum=vnum;item->count=count;items[++created+10]=item;return item;}
Item* CreateItem(DWORD vnum,uint16_t count){auto* item=new Item;item->vnum=vnum;item->count=count;items[++created+10]=item;return item;}
void Destroy(Item* item){++destroyed;for(auto it=items.begin();it!=items.end();)if(it->second==item)it=items.erase(it);else ++it;delete item;}
void FlushDelayedSave(Item*){}
~ITEM_MANAGER(){for(auto& it:items)if(it.first!=1)delete it.second;}
};
#define M2_DESTROY_ITEM(i) ITEM_MANAGER::instance().Destroy(i)
struct LogManager {static LogManager& instance(){static LogManager m;return m;}template<class...T>void HackLog(T...){}template<class...T>void GoldBarLog(T...){}template<class...T>void ItemLog(T...){} };
struct LogManager {static LogManager& instance(){static LogManager m;return m;}template<class...T>void HackLog(T...){}template<class...T>void CharLog(T...){}template<class...T>void GoldBarLog(T...){}template<class...T>void ItemLog(T...){} };
namespace quest {struct CQuestManager {int tax=3;static CQuestManager& instance(){static CQuestManager q;return q;}int GetEventFlag(const char* key){return std::string(key)=="personal_shop"?tax:1;} };}
struct CMonarch {int64_t total=0;static CMonarch& instance(){static CMonarch m;return m;}void SendtoDBAddMoney(int64_t money,int,Character*){total+=money;} };
struct DBManager {int64_t logged=0;static DBManager& instance(){static DBManager m;return m;}void SendMoneyLog(int,DWORD,int64_t gold){logged+=gold;} };
void PortBpCount(Character*,int,int,int64_t){}void VCardUse(Character*,Character*,Item*){}
struct CShop {struct SHOP_ITEM{DWORD vnum=19;int64_t price=0;BYTE count=1;Item* pkItem=nullptr;int itemid=1;};
struct CShop {struct SHOP_ITEM{int cheque=0;DWORD vnum=19;int64_t price=0;uint16_t count=1;Item* pkItem=nullptr;int itemid=1;};
using GuestMapType=std::map<Character*,bool>;GuestMapType m_map_guest;std::vector<SHOP_ITEM> m_itemVector;
Character* m_pkPC=nullptr;bool IsPCShop(){return m_pkPC!=nullptr;}void BroadcastUpdateItem(BYTE){}int Buy(Character*,BYTE);
};
'''
harness += r'''
constexpr int CHEQUE_MAX=999999,SHOP_SUBHEADER_GC_NOT_ENOUGH_CHEQUE=13;
bool PortChequeClientSupported(Character*){return true;}int PortChequeGet(Character*){return 0;}bool PortChequeCanChange(Character*,int){return true;}void PortChequeChange(Character*,int){}
'''
extra_source=(ROOT/'src/server/game/src/shopEx.cpp').read_bytes().decode('latin1')
extra_body=extra_source[extra_source.index('int CShopEx::Buy('):]
@@ -75,7 +79,7 @@ struct CShopEx:CShop {std::vector<TShopTableEx> m_vec_shopTabs;int GetTabCount()
main = r'''
int main(){
Character buyer,seller;Item item;item.owner=&seller;ITEM_MANAGER::instance().items[1]=&item;
CShop shop;shop.m_pkPC=&seller;shop.m_itemVector.resize(1);auto& row=shop.m_itemVector[0];row.price=300000000000LL;row.pkItem=&item;
item.count=2000;CShop shop;shop.m_pkPC=&seller;shop.m_itemVector.resize(1);auto& row=shop.m_itemVector[0];row.price=300000000000LL;row.pkItem=&item;
shop.m_map_guest[&buyer]=true; // PC shop never charges an empire multiplier.
buyer.gold=400000000000LL;seller.gold=GOLD_MAX_64-291000000000LL+1;
assert(shop.Buy(&buyer,0)==SHOP_SUBHEADER_GC_NOT_ENOUGH_MONEY);