Port the AVA2 switchbot (自动洗练) 1:1

AVA2 new_switchbot ported as port_switchbot.{h,cpp}: SWITCHBOT item window (7),
CG/GC 171 and GG 31 with AVA2 subheaders and field order, pack(1) structs pinned
by static_assert, 0.1 s roll, P2P hand-over on warp, boot ALTER of
player.item.window. Switchers come from the inventory; current checks and
ItemLog are kept. Clients sending "mt20261016" or newer as the version
timestamp get the switchbot; older clients are left alone.

The v1 /mt_switchbot chat command, its lock verb and query capability bit 64
are removed (cap mask 1023 -> 959).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
shenlei
2026-10-16 20:26:06 +09:00
co-authored by Claude Opus 5.5
parent c6813cd653
commit a28393b16b
39 changed files with 1485 additions and 555 deletions
+102 -209
View File
@@ -1,218 +1,111 @@
#!/usr/bin/env python3
"""Compile the production switchbot header against stubs of the original UseItem/ChatPacket contract."""
"""AVA2 switchbot (docs/FEATURE-SWITCHBOT.md): the SWITCHBOT window (7), AVA2's headers 171 / GG 31 with the
same subheaders and field order, wire sizes pinned by static_assert and mirrored by the client, the window
hooks, the P2P hand-over, the boot ALTER and the switcher choice. The old /mt_switchbot command is gone."""
from pathlib import Path
import subprocess
import tempfile
import re
ROOT=Path(__file__).resolve().parents[2]
SRC=ROOT/'src/server/game/src'
# The quiet-INFO branch must stay in the real ChatPacket; the stub below mirrors it.
assert 'if (m_portQuietInfo && type == CHAT_TYPE_INFO)' in (SRC/'char.cpp').read_bytes().decode('latin1')
assert '"mt_switchbot", do_port_switchbot' in (SRC/'cmd.cpp').read_bytes().decode('latin1')
lock_use=(SRC/'port_attr_lock.cpp').read_text().split('const char* PortAttrLockUse(',1)[1]
code=r'''
#include <cassert>
#include <cstdarg>
#include <cstdio>
#include <cstring>
#include <deque>
#include <map>
#include <memory>
#include <string>
#include <vector>
using DWORD=unsigned;using BYTE=unsigned char;
enum {MAX_APPLY_NUM=100,ITEM_APPLY_MAX_NUM=3,ATTRIBUTE_SET_MAX_NUM=11,INVENTORY_MAX_NUM=225,INVENTORY=1,EQUIPMENT=2};
enum {ITEM_USE=3,ITEM_COSTUME=28,USE_CHANGE_ATTRIBUTE=10,USE_ADD_ATTRIBUTE=11,APPLY_MAX_HP=1,APPLY_STR=3,APPLY_CRITICAL=15,
APPLY_ATTBONUS_MONSTER=63,APPLY_NORMAL_HIT_DAMAGE_BONUS=72,APPLY_SKILL_DAMAGE_BONUS=71};
enum {CHAT_TYPE_INFO=1,CHAT_TYPE_COMMAND=5};
struct TItemAttrTable{long lValues[5];BYTE bMaxLevelBySet[ATTRIBUTE_SET_MAX_NUM];};
std::map<DWORD,TItemAttrTable> g_map_itemAttr;
struct TItemApply{BYTE bType;long lValue;};
struct TItemTable{TItemApply aApplies[ITEM_APPLY_MAX_NUM];short sAddonType=0;};
struct TPlayerItemAttribute{BYTE bType=0;short sValue=0;};
struct TItemPos{BYTE window_type;unsigned cell;TItemPos(BYTE w,unsigned c):window_type(w),cell(c){}};
struct VID{DWORD id=0;bool operator==(const VID& o)const{return id==o.id;}};
struct event_info_data{virtual ~event_info_data(){}};
struct EVENT{event_info_data* info;long (*func)(EVENT*,long);bool cancelled=false;};
using LPEVENT=EVENT*;
std::vector<std::unique_ptr<EVENT>> events;
template<class T> T* AllocEventInfo(){return new T;}
LPEVENT event_create(long (*f)(LPEVENT,long),event_info_data* info,long){events.emplace_back(new EVENT{info,f});return events.back().get();}
void event_cancel(LPEVENT* e){if(*e)(*e)->cancelled=true;*e=nullptr;}
#define EVENTFUNC(name) long (name) (LPEVENT event, long processing_time)
#define EVENTINFO(name) struct name : public event_info_data
#define PASSES_PER_SEC(s) ((s)*4)
static DWORD clockms=1000;DWORD get_dword_time(){return clockms;}
class CHARACTER;
class CItem {public:
DWORD id,vnum;BYTE type,subtype;int set=0;unsigned cell;BYTE window=INVENTORY;bool equipped=false,exchanging=false;int count=1;
CHARACTER* owner=nullptr;TItemTable proto{};TPlayerItemAttribute attrs[7];
long value2=0;bool IsCostumeEnchant(){return vnum>=54001 && vnum<=54267 && value2;}int GetPendantScrollKind(){return vnum==71302||vnum==53996;}
DWORD GetID(){return id;}DWORD GetVnum(){return vnum;}BYTE GetType(){return type;}BYTE GetSubType(){return subtype;}
int GetAttributeSetIndex(){return set;}const TItemTable* GetProto(){return &proto;}
const TPlayerItemAttribute& GetAttribute(int i){return attrs[i];}BYTE GetAttributeType(int i){return attrs[i].bType;}
int GetAttributeCount(){int n=0;for(int i=0;i<5;++i)n+=attrs[i].bType!=0;return n;}
CHARACTER* GetOwner(){return owner;}BYTE GetWindow(){return window;}unsigned GetCell(){return cell;}
bool isLocked(){return false;}int GetCount(){return count;}void SetCount(int n){count=n;}
bool IsEquipped(){return equipped;}bool IsExchanging(){return exchanging;}
};
using LPITEM=CItem*;
struct ITEM_MANAGER{
static const int MAX_NORM_ATTR_NUM=5;std::vector<CItem*> items;
static ITEM_MANAGER& instance(){static ITEM_MANAGER m;return m;}
LPITEM Find(DWORD id){for(auto* i:items)if(i->id==id)return i;return nullptr;}
};
class CHARACTER {public:
DWORD m_portSwitchbotLastCommand=0;bool m_portQuietInfo=false;std::string m_portLastInfo;
DWORD pid=7;VID vid;bool desc=true,busy=false,dead=false,reject=false;int uses=0;
std::vector<std::string> messages,info;std::vector<CItem*> inventory;
std::deque<std::vector<std::pair<BYTE,short>>> rolls;
bool IsPC(){return true;}void* GetDesc(){return desc?this:nullptr;}DWORD GetPlayerID(){return pid;}const VID& GetVID(){return vid;}
bool IsDead(){return dead;}bool IsWarping(){return false;}bool CanHandleItem(){return !busy;}
void* GetExchange(){return nullptr;}void* GetMyShop(){return nullptr;}void* GetShopOwner(){return nullptr;}
bool IsOpenSafebox(){return false;}bool IsCubeOpen(){return false;}
LPITEM GetItem(TItemPos p){for(auto* i:inventory)if(i->window==p.window_type&&i->cell==p.cell)return i;return nullptr;}
LPITEM FindSpecifyItem(DWORD v){for(auto* i:inventory)if(i->vnum==v&&i->count>0)return i;return nullptr;}
int CountSpecifyItem(DWORD v){int n=0;for(auto* i:inventory)if(i->vnum==v)n+=i->count;return n;}
void ChatPacket(BYTE type,const char* format,...) {
char out[513];va_list args;va_start(args,format);vsnprintf(out,sizeof(out),format,args);va_end(args);
if(m_portQuietInfo && type==CHAT_TYPE_INFO){m_portLastInfo=out;return;}
(type==CHAT_TYPE_INFO?info:messages).emplace_back(out);
}
// Original contract: INFO line on every call, one scroll consumed per successful change.
bool UseItem(TItemPos scroll,TItemPos target) {
++uses;LPITEM s=GetItem(scroll),t=GetItem(target);assert(s && t && s->subtype==USE_CHANGE_ATTRIBUTE);
if(reject){ChatPacket(CHAT_TYPE_INFO,"cannot change");return false;}
auto roll=rolls.front();rolls.pop_front();
for(int i=0;i<5;++i)t->attrs[i]=TPlayerItemAttribute{};
for(size_t i=0;i<roll.size();++i){t->attrs[i].bType=roll[i].first;t->attrs[i].sValue=roll[i].second;}
--s->count;ChatPacket(CHAT_TYPE_INFO,"changed");return true;
}
};
using LPCHARACTER=CHARACTER*;
struct CHARACTER_MANAGER{
std::vector<CHARACTER*> chars;static CHARACTER_MANAGER& instance(){static CHARACTER_MANAGER m;return m;}
LPCHARACTER Find(const VID& v){for(auto* c:chars)if(c->vid==v)return c;return nullptr;}
};
#define ACMD(name) void name(LPCHARACTER ch,const char* argument)
#include "port_switchbot.h"
// Lock storage stub: the real one is a player.mt_item_attr_lock row (port_attr_lock.cpp).
static std::map<DWORD,unsigned> locks;static bool lockFail=false;
unsigned PortAttrLockGet(CItem* item){return locks[item->id];}
bool PortAttrLockSet(CHARACTER*,CItem* item,unsigned mask){if(lockFail)return false;locks[item->id]=mask;return true;}
const char* PortAttrLockUse(@LOCK_USE@
static CHARACTER ch;
static void cmd(const char* text){clockms+=300;ch.messages.clear();do_port_switchbot(&ch,text);}
static long tick(){for(auto& e:events)if(!e->cancelled&&e->func){long r=e->func(e.get(),0);if(!r)e->func=nullptr;return r;}return -1;}
static const std::string& last(){return ch.messages.back();}
int main(){
g_map_itemAttr[APPLY_MAX_HP]={{500,1000,1500,2000,2500},{5,5}};
g_map_itemAttr[APPLY_STR]={{2,4,6,8,12},{5,0}}; // body only (set 0)
g_map_itemAttr[APPLY_CRITICAL]={{1,2,3,5,10},{0,5}}; // not on set 0
g_map_itemAttr[APPLY_ATTBONUS_MONSTER]={{2,4,6,8,10},{3,5}}; // level-capped at 3 on set 0
ch.vid.id=99;CHARACTER_MANAGER::instance().chars.push_back(&ch);
CItem armor{1001,11209,2,0,0,10};armor.owner=&ch;armor.proto.aApplies[0]={APPLY_MAX_HP,100};armor.attrs[0]={APPLY_STR,2};armor.attrs[1]={APPLY_CRITICAL,1};
CItem scroll{2001,71084,ITEM_USE,USE_CHANGE_ATTRIBUTE,-1,20};scroll.owner=&ch;scroll.count=3;
CItem adder{2002,71085,ITEM_USE,USE_ADD_ATTRIBUTE,-1,21};adder.owner=&ch;
CItem plain{1002,50001,ITEM_USE,0,-1,30};plain.owner=&ch;
for(auto* i:{&armor,&scroll,&adder,&plain}){ch.inventory.push_back(i);ITEM_MANAGER::instance().items.push_back(i);}
SRC=ROOT/'src/server'
CLIENT=ROOT.parent/'metin2-client/src/port/UserInterface'
def source(name):return (SRC/name).read_bytes().decode('latin1')
def enum_after(text,start,end):
body=text[text.index(start):];body=body[:body.index(end)]
return re.findall(r'^\s*([A-Z_0-9]+)\s*[,=]',body,re.M)
def struct(text,name):
body=text[text.index('struct %s\n'%name):];body=body[:body.index('};')]
return re.findall(r'^\s*([A-Za-z_][A-Za-z_0-9]*)\s+(\w+)(\[[^;]*\])?;',body,re.M)
// Allowed list: proto applies excluded, set filter, level cap picks lValues[level-1].
cmd("1 attrs 10");
assert(ch.messages.size()==5 && ch.messages[0]=="MTSB1 attrs 10 11209 2");
assert(ch.messages[1]=="MTSB1 attr 0 3 12" && ch.messages[2]=="MTSB1 attr 1 63 6" && ch.messages[3]=="MTSB1 attrs_end 10 2");
assert(last()=="MTSB1 lock 10 11209 0");
armor.proto.sAddonType=1;cmd("1 attrs 10");assert(ch.messages[3]=="MTSB1 attr 2 71 30" && ch.messages[4]=="MTSB1 attr 3 72 65");armor.proto.sAddonType=0;
cmd("1 attrs 30");assert(last()=="MTSB1 error attrs no_attr");
cmd("1 attrs 99");assert(last()=="MTSB1 error attrs item");
do_port_switchbot(&ch,"1 attrs 10");assert(last()=="MTSB1 error attrs rate");
length=source('common/length.h')
windows=enum_after(length,'enum EWindows','};')
assert windows.index('SWITCHBOT')==7 and windows[6]=='BELT_INVENTORY',windows
for k,v in (('SWITCHBOT_SLOT_COUNT',6),('SWITCHBOT_SLOT_COUNT_REAL',5),('SWITCHBOT_ALTERNATIVE_COUNT',2),('SWITCHBOT_NORM_ATTR_NUM',5)):
assert re.search(r'\b%s = %d,'%(k,v),length),k
assert 'bool IsSwitchbotPosition() const' in length
// Validation.
for(auto bad:{"1 start 10 71084 0 1 3 1","1 start 10 71084 1001 1 3 1","1 start 10 71084 5 1 3","1 start 10 71084 5 1 3 0",
"1 start 10 71084 5 6 3 1 3 1 3 1 3 1 3 1 3 1","1 start 10 71084 5 1 3 1 1","1 start 10 71084 5 1 3 -1","1 start 10 71084 5 0"})
{cmd(bad);assert(last()=="MTSB1 error start invalid");}
cmd("1 start 10 71084 5 1 1 100");assert(last()=="MTSB1 error start target"); // base proto apply
cmd("1 start 10 71084 5 1 3 13");assert(last()=="MTSB1 error start target"); // above max
cmd("1 start 10 71084 5 2 3 1 3 2");assert(last()=="MTSB1 error start target"); // duplicate
cmd("1 start 10 71085 5 1 3 4");assert(last()=="MTSB1 error start scroll");
cmd("1 start 10 50001 5 1 3 4");assert(last()=="MTSB1 error start scroll");
// AVA2 costume enchants share USE_CHANGE_ATTRIBUTE but are no switchers (port_costume_attr.cpp).
CItem enchant{2004,54001,ITEM_USE,USE_CHANGE_ATTRIBUTE,-1,23};enchant.owner=&ch;enchant.value2=2;ch.inventory.push_back(&enchant);
cmd("1 start 10 54001 5 1 3 4");assert(last()=="MTSB1 error start scroll");
cmd("1 start 30 71084 5 1 3 4");assert(last()=="MTSB1 error start no_attr");
armor.equipped=true;cmd("1 start 10 71084 5 1 3 4");assert(last()=="MTSB1 error start equipped");armor.equipped=false;
cmd("1 start 10 71084 5 1 3 2");assert(last()=="MTSB1 state 0 10 11209 0 5 71084 3 matched" && events.empty()); // already satisfied
assert(ch.uses==0);
packet=source('game/src/packet.h')
for name,v in (('HEADER_CG_SWITCHBOT',171),('HEADER_GC_SWITCHBOT',171),('HEADER_GG_SWITCHBOT',31)):
assert re.search(r'\b%s\s*= %d,'%(name,v),packet),name
cg=enum_after(packet,'enum ECGSwitchbotSubheader','};');gc=enum_after(packet,'enum EGCSwitchbotSubheader','};')
assert cg==['SUBHEADER_CG_SWITCHBOT_START','SUBHEADER_CG_SWITCHBOT_STOP'],cg
assert gc==['SUBHEADER_GC_SWITCHBOT_UPDATE','SUBHEADER_GC_SWITCHBOT_UPDATE_ITEM','SUBHEADER_GC_SWITCHBOT_SEND_ATTRIBUTE_INFORMATION'],gc
head=[('BYTE','header'),('int','size'),('BYTE','subheader'),('BYTE','slot')]
for name in ('TPacketCGSwitchbot','TPacketGCSwitchbot'):
assert [(t,n) for t,n,_ in struct(packet,name)]==head,name
upd=struct(packet,'TSwitchbotUpdateItem')
assert upd==[('BYTE','slot',''),('DWORD','vnum',''),('WORD','count',''),('long','alSockets','[ITEM_SOCKET_MAX_NUM]'),
('TPlayerItemAttribute','aAttr','[ITEM_ATTRIBUTE_MAX_NUM]')],upd
tables=source('common/tables.h')
assert tables.index('#pragma pack(1)')<tables.index('struct TSwitchbotTable')<tables.rindex('#pragma pack()')
assert packet.index('#pragma pack(1)')<packet.index('struct TSwitchbotUpdateItem')<packet.rindex('#pragma pack()')
table=[n for _,n,_ in struct(tables,'TSwitchbotTable')]
assert table==['player_id','active','finished','items','alternatives'],table
// Run: two alternatives, first roll misses, second satisfies alternative 2; INFO spam suppressed.
ch.rolls={{{APPLY_STR,4},{APPLY_CRITICAL,1}},{{APPLY_ATTBONUS_MONSTER,6},{APPLY_STR,2}}};
cmd("1 start 10 71084 10 1 3 8 2 63 6 3 2");assert(last()=="MTSB1 state 1 10 11209 0 10 71084 3 running");
cmd("1 start 10 71084 10 1 3 8");assert(last()=="MTSB1 error start running");
ch.messages.clear();assert(tick()==1);assert(last()=="MTSB1 state 1 10 11209 1 10 71084 2 running");
assert(tick()==0 && last()=="MTSB1 state 0 10 11209 2 10 71084 1 matched");
assert(ch.info.empty() && !ch.m_portQuietInfo && ch.uses==2 && g_portSwitchbots.empty());
port=source('game/src/port_switchbot.cpp')
sizes={'TSwitchbotTable':220,'TSwitchbotAttributeAlternativeTable':15,'TSwitchbottAttributeTable':9,'TSwitchbotUpdateItem':40}
for name,size in sizes.items():assert 'static_assert(sizeof(%s) == %d,'%(name,size) in port,name
assert 'static_assert(sizeof(TPacketCGSwitchbot) == 7 && sizeof(TPacketGCSwitchbot) == 7,' in port
assert 'static_assert(sizeof(TPacketGGSwitchbot) == 223,' in port
// Limit, then scroll exhaustion.
scroll.count=5;ch.rolls={{{APPLY_STR,2}},{{APPLY_STR,2}},{{APPLY_STR,2}}};
cmd("1 start 10 71084 2 1 3 12");ch.messages.clear();tick();
assert(tick()==0 && last()=="MTSB1 state 0 10 11209 2 2 71084 3 limit");
scroll.count=1;cmd("1 start 10 71084 5 1 3 12");ch.messages.clear();tick();
assert(tick()==0 && last()=="MTSB1 state 0 10 11209 1 5 71084 0 no_scroll");
# switcher choice and roll path
for text in ('const float c_fSpeed = 0.1f;','return FindUsableSwitcher(ch, 71302);','s_adwLow[] = { 71151, 76023 };',
's_adwNormal[] = { 71084, 39028 };','ItemLog(pkOwner, pkScroll, "SWITCHBOT", szHint);',
'"switchbot_end %d"','"switchbot_stop noattr %d"','"switchbot_stop nochanger %d"',
'SWITCHBOT_ATTRIBUTE_SET_NEW_RINGS = ATTRIBUTE_SET_MAX_NUM,','GetNewRingAttrMaxValue(','GetPendantAttrMaxValue(',
"'BELT_INVENTORY','SWITCHBOT') NOT NULL DEFAULT 'INVENTORY'"):
assert text in port,text
# costume enchants and the other talisman scrolls never roll: only these vnums are looked up
assert 'IsCostumeEnchant' not in port and 'GetPendantScrollKind' not in port
// Rejected roll: no consumption, the original INFO is surfaced once.
scroll.count=2;ch.reject=true;cmd("1 start 10 71084 5 1 3 12");tick();
assert(last()=="MTSB1 state 0 10 11209 0 5 71084 2 rejected" && ch.info.size()==1 && ch.info[0]=="cannot change");
ch.reject=false;ch.info.clear();
items=source('game/src/char_item.cpp')
for text in ('return m_pointsInstant.pSwitchbotItems[wCell];','CSwitchbotManager::Instance().RegisterItem(GetPlayerID(), pItem->GetID(), wCell);',
'CSwitchbotManager::Instance().UnregisterItem(GetPlayerID(), wCell);','pItem->SetWindow(SWITCHBOT);',
'if (wCell >= SWITCHBOT_SLOT_COUNT_REAL)\n\t\t\t\treturn false;','"switchbot_error active"','"switchbot_error invalid"',
'if (!other.IsSwitchbotPosition() && !other.IsDefaultInventoryPosition())'):
assert text in items,text
assert items.count('if (Cell.IsSwitchbotPosition())\t// PORT: switchbot items go back to the inventory first')==2 # drop + give
char_h=source('game/src/char.h')
assert re.search(r'LPITEM\s+pSwitchbotItems\[SWITCHBOT_SLOT_COUNT\];',char_h) and 'm_portSwitchbotLastCommand' not in char_h
assert 'if (m_bWindow == SWITCHBOT)' in source('game/src/item.cpp')
assert 'if (item_pos.IsSwitchbotPosition())' in source('game/src/exchange.cpp')
inputs=source('game/src/input_main.cpp')
assert inputs.count('p->ItemPos.IsSwitchbotPosition()')==2 # safebox checkin + checkout
assert 'case HEADER_CG_SWITCHBOT:\n\t\t\tif ((iExtraLen = Switchbot(ch, c_pData, m_iBufferLeft)) < 0)' in inputs
info=source('game/src/packet_info.cpp')
assert 'Set(HEADER_CG_SWITCHBOT, sizeof(TPacketCGSwitchbot), "Switchbot", true);' in info
assert re.search(r'Set\(HEADER_GG_SWITCHBOT,\s*sizeof\(TPacketGGSwitchbot\),\s*"Switchbot",\s*false\);',info)
assert 'case HEADER_GG_SWITCHBOT:' in source('game/src/input_p2p.cpp')
char=source('game/src/char.cpp')
warp=char[char.index('CSwitchbotManager::Instance().SetIsWarping(GetPlayerID(), true);'):]
assert warp.index('P2PSendSwitchbot(GetPlayerID(), p.wPort)')<warp.index('GetDesc()->Packet(&p, sizeof(TPacketGCWarp))')
assert 'CSwitchbotManager::Instance().EnterGame(ch);' in source('game/src/input_login.cpp')
# version gate: only "mt<date>" clients from PORT_SWITCHBOT_CLIENT_VERSION on get GC_SWITCHBOT at EnterGame
assert 'enum { PORT_SWITCHBOT_CLIENT_VERSION = 20261016 };' in source('game/src/port_switchbot.h')
enter=port[port.index('void CSwitchbotManager::EnterGame'):];enter=enter[:enter.index('\n}\n')]
assert enter.index('if (!SwitchbotHelper::IsClientSupported(ch))\n\t\treturn;')<enter.index('SendItemAttributeInformations(ch);')
assert "c_pszVersion[0] == 'm' && c_pszVersion[1] == 't' && atoi(c_pszVersion + 2) >= PORT_SWITCHBOT_CLIENT_VERSION" in port
assert 'case SWITCHBOT:' in source('game/src/input_db.cpp')
main=source('game/src/main.cpp')
assert 'CSwitchbotManager switchbotManager;' in main and 'PortSwitchbotBoot();' in main
assert source('db/src/ClientManagerPlayer.cpp').count('SAFEBOX, DRAGON_SOUL_INVENTORY, SWITCHBOT')==3
assert 'port_switchbot.cpp' in source('game/src/Makefile')
assert '"mt_switchbot"' not in source('game/src/cmd.cpp') and 'port_switchbot.h' not in source('game/src/cmd_general.cpp')
// Item moved to equipment, busy character, manual stop, logout/warp (VID change) erases silently.
ch.rolls={{{APPLY_STR,2}}};cmd("1 start 10 71084 5 1 3 12");armor.window=EQUIPMENT;tick();
assert(last()=="MTSB1 state 0 0 0 0 5 71084 2 item_gone");armor.window=INVENTORY;
cmd("1 start 10 71084 5 1 3 12");ch.busy=true;tick();assert(last()=="MTSB1 state 0 10 11209 0 5 71084 2 busy");ch.busy=false;
cmd("1 start 10 71084 5 1 3 12");cmd("1 stop");assert(last()=="MTSB1 state 0 10 11209 0 5 71084 2 stopped" && tick()==-1);
cmd("1 stop");assert(last()=="MTSB1 state 0 0 0 0 0 0 0 idle");
cmd("1 start 10 71084 5 1 3 12");cmd("1 status");assert(last()=="MTSB1 state 1 10 11209 0 5 71084 2 running");
ch.vid.id=100;ch.messages.clear();assert(tick()==0 && ch.messages.empty() && g_portSwitchbots.empty());
assert(ch.uses==6);
// AVA2 lock costs: no material, partial attributes, persistence failure never consume.
CItem lockMaterial{2100,50348,ITEM_USE,USE_CHANGE_ATTRIBUTE,-1,40};lockMaterial.owner=&ch;lockMaterial.count=20;
CItem unlockMaterial{2101,50349,ITEM_USE,USE_CHANGE_ATTRIBUTE,-1,41};unlockMaterial.owner=&ch;unlockMaterial.count=20;
cmd("1 lock 10 0");assert(last()=="MTSB1 error lock material");
ch.inventory.push_back(&lockMaterial);ch.inventory.push_back(&unlockMaterial);
cmd("1 lock 10 0");assert(last()=="MTSB1 error lock five_attr" && lockMaterial.count==20);
armor.attrs[3]={APPLY_MAX_HP,500};armor.attrs[4]={APPLY_STR,1};
// Lock toggle: five slots filled, max two groups, not on the rolling item.
armor.attrs[0]={APPLY_STR,2};armor.attrs[1]={APPLY_CRITICAL,1};armor.attrs[2]={APPLY_ATTBONUS_MONSTER,2};
cmd("1 lock 10 0");assert(last()=="MTSB1 lock 10 11209 1");
cmd("1 lock 10 2");assert(last()=="MTSB1 lock 10 11209 5");
cmd("1 lock 10 1");assert(last()=="MTSB1 error lock max");
cmd("1 lock 10 3");assert(last()=="MTSB1 error lock max");
cmd("1 lock 10 5");assert(last()=="MTSB1 error lock slot");
cmd("1 lock 10 0");assert(last()=="MTSB1 lock 10 11209 4" && locks[1001]==4);
cmd("1 lock 10 1");assert(last()=="MTSB1 lock 10 11209 6");
cmd("1 attrs 10");assert(last()=="MTSB1 lock 10 11209 6");
cmd("1 lock 30 0");assert(last()=="MTSB1 error lock no_attr");
cmd("1 lock 99 0");assert(last()=="MTSB1 error lock item");
cmd("1 lock 10");assert(last()=="MTSB1 error lock invalid");
assert(lockMaterial.count==17 && unlockMaterial.count==19);
lockFail=true;cmd("1 lock 10 1");assert(last()=="MTSB1 error lock db" && locks[1001]==6);lockFail=false;assert(unlockMaterial.count==19);
ch.rolls={{{APPLY_STR,2}}};cmd("1 start 10 71084 5 1 3 12");cmd("1 lock 10 1");assert(last()=="MTSB1 error lock running");
cmd("1 stop");
// Addon weapon: slots 0 and 1 lock together and count as one group.
armor.proto.sAddonType=1;locks[1001]=0;armor.attrs[3]={APPLY_MAX_HP,500};
cmd("1 lock 10 1");assert(last()=="MTSB1 lock 10 11209 3");
cmd("1 lock 10 3");assert(last()=="MTSB1 lock 10 11209 11");
cmd("1 lock 10 2");assert(last()=="MTSB1 error lock max");
cmd("1 lock 10 0");assert(last()=="MTSB1 lock 10 11209 8");
armor.proto.sAddonType=0;armor.attrs[2]=armor.attrs[3]=TPlayerItemAttribute{};locks.clear();
// Malformed or foreign input is ignored or rejected without side effects.
cmd("2 status");assert(ch.messages.empty());
cmd("1 explode");assert(last()=="MTSB1 error explode invalid");
cmd("1 start 99999999999 71084 5 1 3 12");assert(ch.messages.empty()); // overlong token
puts("PASS: allowed targets, validation, alternatives, original UseItem path, quiet INFO, stop reasons, VID drop");
}
'''.replace('@LOCK_USE@',lock_use)
with tempfile.TemporaryDirectory(prefix='mt-switchbot-') as folder:
path=Path(folder);(path/'test.cpp').write_text(code)
subprocess.run(['c++','-std=c++17','-Wall','-I'+str(SRC),str(path/'test.cpp'),'-o',str(path/'test')],check=True)
subprocess.run([str(path/'test')],check=True)
# the client mirrors headers, subheaders, structs and sizes (packets in Packet.h, the table in PythonSwitchbot.h)
cpacket=CLIENT/'Packet.h'
if cpacket.is_file():
client=cpacket.read_bytes().decode('latin1')
for name in ('HEADER_CG_SWITCHBOT','HEADER_GC_SWITCHBOT'):
assert re.search(r'\b%s\s*= 171,'%name,client),name
assert enum_after(client,'enum ECGSwitchbotSubheader','};')==cg
assert enum_after(client,'enum EGCSwitchbotSubheader','};')==gc
assert [n for _,n,_ in struct(client,'TSwitchbotUpdateItem')]==[n for _,n,_ in upd]
assert 'static_assert(sizeof(TSwitchbotUpdateItem) == 40,' in client
assert 'static_assert(sizeof(TPacketCGSwitchbot) == 7 && sizeof(TPacketGCSwitchbot) == 7,' in client
stream=(CLIENT/'PythonNetworkStreamPhaseGame.cpp').read_bytes().decode('latin1')
assert 'strncpy(kVersionPacket.timestamp, "mt20261016", sizeof(kVersionPacket.timestamp)-1);' in stream
pyswitch=(CLIENT/'PythonSwitchbot.h').read_bytes().decode('latin1')
ctable=pyswitch[pyswitch.index('struct TSwitchbotTable'):];ctable=ctable[:ctable.index('};')]
assert re.findall(r'^\s*[A-Za-z_][\w:]*\s+(\w+)(?:\[[^;]*\])?;',ctable,re.M)==table,ctable
for name in ('TSwitchbotTable','TSwitchbotAttributeAlternativeTable','TSwitchbottAttributeTable'):
assert 'static_assert(sizeof(CPythonSwitchbot::%s) == %d,'%(name,sizes[name]) in pyswitch,name
print('PASS: SWITCHBOT window 7, version gate mt20261016, CG/GC 171 + GG 31, AVA2 subheaders/fields, sizes 220/15/9/40/7/223, window hooks, P2P, boot ALTER, switchers 71302/71151/76023/71084/39028')