From afb3dfb1db502861b4ff01b80e90fca5bd6bf71d Mon Sep 17 00:00:00 2001 From: shenlei Date: Thu, 15 Oct 2026 19:45:10 +0900 Subject: [PATCH] Add server-authoritative switchbot (automatic attribute change) v1 /mt_switchbot 1 attrs|start|stop|status runs one bot per character that calls the original UseItem path every 250 ms, so checks, probabilities, ItemLog CHANGE_ATTRIBUTE and scroll use are the manual path's. Up to two alternatives of 1-5 targets; stops on matched/limit/no_scroll/item_gone/ rejected/busy/stopped, erased on logout or warp. Per-roll INFO lines are held back via a quiet flag on ChatPacket. MTF1 cap mask advertises 64. Verified live on 203 with an extra channel-5 core (port 13040) running the isolated build: limit, matched, already-matched, move during run, stop and logout during run; 72 ItemLog rows for 72 rolls. No attribute lock yet. Co-Authored-By: Claude Opus 5.5 --- docs/FEATURE-QUERY-PROTOCOL.md | 2 +- docs/FEATURE-SWITCHBOT.md | 78 ++++++++++ src/server/game/src/char.cpp | 6 + src/server/game/src/char.h | 3 + src/server/game/src/cmd.cpp | 2 + src/server/game/src/cmd_general.cpp | 1 + src/server/game/src/port_features.h | 2 +- src/server/game/src/port_switchbot.h | 216 +++++++++++++++++++++++++++ tests/features/test_queries.py | 2 +- tests/features/test_switchbot.py | 174 +++++++++++++++++++++ 10 files changed, 483 insertions(+), 3 deletions(-) create mode 100644 docs/FEATURE-SWITCHBOT.md create mode 100644 src/server/game/src/port_switchbot.h create mode 100644 tests/features/test_switchbot.py diff --git a/docs/FEATURE-QUERY-PROTOCOL.md b/docs/FEATURE-QUERY-PROTOCOL.md index 37d19208..4d817d6d 100644 --- a/docs/FEATURE-QUERY-PROTOCOL.md +++ b/docs/FEATURE-QUERY-PROTOCOL.md @@ -29,7 +29,7 @@ MTF1 end REQUEST ROW_COUNT MTF1 error REQUEST ERROR ``` -MASK: 1 mob drops, 2 chest preview, 4 own stats, 8 item sources, 16 dungeon snapshots, 32 scheduled calendar. Unknown capability bits are ignored; unknown versions are rejected. Capability advertises the query implementation; missing quest/config can still return unsupported/schedule_unavailable. The client negotiates before business queries; old servers time out to unsupported, not an empty result. +MASK: 1 mob drops, 2 chest preview, 4 own stats, 8 item sources, 16 dungeon snapshots, 32 scheduled calendar, 64 switchbot (separate `/mt_switchbot` / `MTSB1` protocol, see FEATURE-SWITCHBOT.md). Unknown capability bits are ignored; unknown versions are rejected. Capability advertises the query implementation; missing quest/config can still return unsupported/schedule_unavailable. The client negotiates before business queries; old servers time out to unsupported, not an empty result. Each drop/chest/source page contains at most 8 rows, with consecutive absolute indices. TOTAL is capped at 4096; stats are one complete bounded snapshot (currently the named keys in kPortStats, less than 128). Client commits only a complete, matching begin/rows/end sequence. Unknown/stale request IDs cannot overwrite the current selection. Each line is bounded below 512 bytes; rows contain IDs and values, not server-provided script/names/markup. diff --git a/docs/FEATURE-SWITCHBOT.md b/docs/FEATURE-SWITCHBOT.md new file mode 100644 index 00000000..62d9af32 --- /dev/null +++ b/docs/FEATURE-SWITCHBOT.md @@ -0,0 +1,78 @@ +# PORT switchbot (automatic attribute change), v1 + +AVA2-style automatic rerolling (reference: AVA2 `new_switchbot.cpp` / `uiswitchbot.py`), rebuilt so that the server stays authoritative and the existing reroll path is unchanged. Source: `src/server/game/src/port_switchbot.h`, command `mt_switchbot` (cmd.cpp), quiet-INFO hook in `CHARACTER::ChatPacket` (char.cpp), fields in char.h. No attribute lock, no DB schema, no packet header, no P2P transfer. + +## Rules + +- Each roll calls the original `CHARACTER::UseItem(scroll cell, target cell)`. All checks, probabilities, the addon handling, `ItemLog CHANGE_ATTRIBUTE` and scroll consumption are the manual path's. That includes the 71151/76023 restriction (weapon/body, level limit <= 40) and the GM quest flag. A roll counts only when exactly one scroll of the chosen vnum was consumed. Otherwise the bot stops with `rejected` and resends the original INFO line once. +- The per-roll INFO lines (`属性已å�˜æ›´`) are held back while the bot calls UseItem (`m_portQuietInfo`); all other chat types pass through. +- Only `ITEM_USE / USE_CHANGE_ATTRIBUTE` scrolls are accepted. `USE_CHANGE_ATTRIBUTE2` has no handler in this server's UseItemEx. +- Target item: inventory cell, not costume, attribute set != -1, at least one attribute, not equipped or in an exchange. It is bound by item ID. +- One bot per character. One roll every 250 ms (`PASSES_PER_SEC(1)/4`). Limit 1..1000 rolls. +- Targets: up to 2 alternatives, each 1..5 distinct (apply, minimum). An alternative matches when every target is found among the 5 normal attribute slots with value >= minimum. Any matching alternative stops the bot (AVA2 CheckItem semantics). The bot also checks before it starts, so an item that already matches consumes nothing. +- Allowed targets are the applies the attribute table can roll for this item's set, excluding the item's base proto applies. The maximum is `lValues[min(maxLevelBySet,5)-1]`. Items with an addon type also allow skill damage 30 / normal hit 65, the item_addon bounds. +- Every tick re-checks the state and stops with a reason. This replaces AVA2's hooks into every move/trade path. + - Character gone, VID changed (logout or warp) or descriptor lost: the bot is erased silently. + - `busy`: dead, warping, `!CanHandleItem()`, exchange, own shop, shop, safebox or cube open. + - `item_gone`: the item is missing, has another owner, has left the inventory window or is equipped. + - `no_scroll`, `limit`, `matched`, `rejected`, `stopped`. +- No offline rolling. Rolls stop when the player leaves, and every completed roll has already been saved and logged by the original path. + +## Protocol (CHAT_TYPE_COMMAND, version 1) + +Requests (250 ms per-character throttle; tokens <= 10 chars, <= 30 tokens): + +``` +/mt_switchbot 1 attrs CELL +/mt_switchbot 1 start CELL SCROLL_VNUM LIMIT N1 (APPLY MIN)*N1 [N2 (APPLY MIN)*N2] +/mt_switchbot 1 stop +/mt_switchbot 1 status +``` + +Replies: + +``` +MTSB1 attrs CELL VNUM COUNT +MTSB1 attr INDEX APPLY MAX (COUNT rows, INDEX 0..COUNT-1) +MTSB1 attrs_end CELL COUNT +MTSB1 state ACTIVE CELL VNUM ROLLS LIMIT SCROLL SCROLLS REASON +MTSB1 error VERB CODE +``` + +`REASON` is one of `running matched limit no_scroll item_gone rejected busy stopped idle`. Error codes: + +| Code | Meaning | +| --- | --- | +| `rate` | throttled | +| `invalid` | malformed | +| `item` | no item in that cell | +| `equipped` | equipped or in an exchange | +| `no_attr` | the item cannot be rerolled | +| `scroll` | the scroll is missing or the wrong type | +| `target` | the apply is not allowed, above the maximum or a duplicate | +| `running` | this character already has a bot | +| `busy` | see the busy states above | + +A state line is pushed after every roll and when the bot stops. When the reason is `item_gone`, CELL and VNUM are 0. + +Capability: the MTF1 cap mask advertises bit 64 (63 -> 127). Clients that don't know it ignore it, and the client also times out to "unsupported" against old servers. + +## Verification + +- `tests/features/test_switchbot.py` compiles the production header against stubs of the UseItem/ChatPacket contract. It covers the allowed list (proto exclusion, set filter, level cap, addon), validation, two alternatives, the already-matched start, quiet INFO, limit, `no_scroll`, `rejected` (INFO resent once), `item_gone`, `busy`, stop/status/idle and silent erase on a VID change. +- `tests/features/test_queries.py` was updated for cap mask 127. +- FreeBSD build of the whole game target on 203 in `/root/metin2-features-dev` (BINDIR=GAMEDIR=`/root/metin2-features-dev/bin`), log `/root/metin2-features-dev/switchbot-build.log`, with no warnings from the new code. The live `/usr/metin2` binary was not replaced and no service was restarted. +- Live test on 2026-10-15. 203 ran an extra core (`/usr/metin2/server/channel5/first`: CHANNEL 5, PORT 13040, P2P 14040, MAP_ALLOW 1 21 41) with its `game` symlinked to the isolated binary. The macOS native client (`--live-server 192.168.21.203:11000:13040`) drove [SA]Admin, sword 279, scroll 71084: + - `attrs` returned 14 rows for the sword (18 for armor 12019), received complete. + - limit 10 → `limit` after 10 rolls. State lines arrived about every 0.24 s (about 4 rolls/s); the scroll count fell 200 → 190. + - Two alternatives with minimum 1 → `matched` after 18 rolls. + - Start on an item that already matches → `matched` with 0 rolls and no scroll used. + - Moving the item 33 → 90 mid-run → the run continued, the state line reported cell 90, and `stop` → `stopped`. + - Client exit mid-run (8 rolls) → `log.log` stopped at the exit second. The CHANGE_ATTRIBUTE row count (72 = 10+18+12+12+12+8) stayed the same 20 s later. + - Every roll wrote one `CHANGE_ATTRIBUTE` row. The core's syserr shows no new errors; the `new_quest_lv52` LUA_ERROR also appears on the live cores. +- Not done yet: `busy` and `no_scroll` on the real server (unit tests only), and Android device validation. + +## Open items + +- Attribute lock: AVA2 stores it at attribute index 7, which the current 7-slot layout cannot hold. It needs its own storage design (see the client migration plan, phase 6). +- In 203 `player.item_proto`, 71084, 71151, 76014, 76023 and 39028 are USE/USE_CHANGE_ATTRIBUTE (subtype 18); 71302 (the AVA2 talisman scroll) does not exist. The bot accepts any `USE_CHANGE_ATTRIBUTE` scroll and leaves item rules to the original path. diff --git a/src/server/game/src/char.cpp b/src/server/game/src/char.cpp index c1ca0073..1e556ed3 100755 --- a/src/server/game/src/char.cpp +++ b/src/server/game/src/char.cpp @@ -3940,6 +3940,12 @@ void CHARACTER::ChatPacket(BYTE type, const char * format, ...) int len = vsnprintf(chatbuf, sizeof(chatbuf), format, args); va_end(args); + if (m_portQuietInfo && type == CHAT_TYPE_INFO) + { + m_portLastInfo = chatbuf; + return; + } + struct packet_chat pack_chat; pack_chat.header = HEADER_GC_CHAT; diff --git a/src/server/game/src/char.h b/src/server/game/src/char.h index 3a1d411a..c5ccee11 100755 --- a/src/server/game/src/char.h +++ b/src/server/game/src/char.h @@ -518,6 +518,9 @@ class CHARACTER : public CEntity, public CFSM, public CHorseRider public: DWORD m_portFeatureLastQuery = 0; // PORT: read-only query throttle, not persisted. + DWORD m_portSwitchbotLastCommand = 0; // PORT: switchbot command throttle. + bool m_portQuietInfo = false; // PORT: switchbot rolls hold back per-roll INFO lines... + std::string m_portLastInfo; // ...keeping the last one to report a rejected roll. LPCHARACTER FindCharacterInView(const char * name, bool bFindPCOnly); void UpdatePacket(); diff --git a/src/server/game/src/cmd.cpp b/src/server/game/src/cmd.cpp index 38cb1e63..cada55e2 100755 --- a/src/server/game/src/cmd.cpp +++ b/src/server/game/src/cmd.cpp @@ -10,6 +10,7 @@ ACMD(do_autohunt_pull); ACMD(do_server_bonuses); ACMD(do_port_biolog); ACMD(do_port_features); +ACMD(do_port_switchbot); ACMD(do_user_horse_ride); ACMD(do_user_horse_back); ACMD(do_user_horse_feed); @@ -285,6 +286,7 @@ struct command_info cmd_info[] = { "!RESERVED!", NULL, 0, POS_DEAD, GM_IMPLEMENTOR }, /* ¹Ýµå½Ã ÀÌ °ÍÀÌ Ã³À½À̾î¾ß ÇÑ´Ù. */ { "autohunt_pull", do_autohunt_pull, 0, POS_STANDING, GM_PLAYER }, { "mt_features", do_port_features, 0, POS_DEAD, GM_PLAYER }, + { "mt_switchbot", do_port_switchbot, 0, POS_DEAD, GM_PLAYER }, { "bio", do_port_biolog, 0, POS_DEAD, GM_PLAYER }, { "biolog", do_port_biolog, 0, POS_DEAD, GM_PLAYER }, { "server_bonuses", do_server_bonuses, 0, POS_DEAD, GM_PLAYER }, diff --git a/src/server/game/src/cmd_general.cpp b/src/server/game/src/cmd_general.cpp index ca8ab7ae..21c5bf13 100755 --- a/src/server/game/src/cmd_general.cpp +++ b/src/server/game/src/cmd_general.cpp @@ -43,6 +43,7 @@ #include "port_dungeons.h" #include "port_calendar_runtime.h" #include "port_features.h" +#include "port_switchbot.h" extern int g_server_id; diff --git a/src/server/game/src/port_features.h b/src/server/game/src/port_features.h index 8b7dedc9..c8f09964 100644 --- a/src/server/game/src/port_features.h +++ b/src/server/game/src/port_features.h @@ -43,7 +43,7 @@ ACMD(do_port_features) { ch->ChatPacket(CHAT_TYPE_COMMAND,"MTF1 error %u rate",request);return; } ch->m_portFeatureLastQuery=get_dword_time(); - if(kind=="cap" && args.size()==3) {ch->ChatPacket(CHAT_TYPE_COMMAND,"MTF1 cap %u 1 63 %lld",request,(long long)get_global_time());return;} + if(kind=="cap" && args.size()==3) {ch->ChatPacket(CHAT_TYPE_COMMAND,"MTF1 cap %u 1 127 %lld",request,(long long)get_global_time());return;} if(kind=="dungeons" && args.size()==3) {PortDungeonQuery(ch,request);return;} if(kind=="stats" && args.size()==3) { ch->ChatPacket(CHAT_TYPE_COMMAND,"MTF1 begin %u stats 0 0 %u 0 %lld",request,unsigned(sizeof(kPortStats)/sizeof(kPortStats[0])),(long long)get_global_time()); diff --git a/src/server/game/src/port_switchbot.h b/src/server/game/src/port_switchbot.h new file mode 100644 index 00000000..4570bebe --- /dev/null +++ b/src/server/game/src/port_switchbot.h @@ -0,0 +1,216 @@ +#ifndef METIN2_PORT_SWITCHBOT_H +#define METIN2_PORT_SWITCHBOT_H +// PORT: AVA2-style automatic attribute change. Every roll goes through the original +// CHARACTER::UseItem change-attribute path, so its checks, probabilities, log and consumption apply unchanged. +// One bound item per character; not persisted; stops on logout, warp, busy windows or any rejected roll. +#include +#include +#include +#include +#include + +static const unsigned kPortSwitchAlternatives=2, kPortSwitchTargets=5, kPortSwitchLimit=1000; +static const unsigned kPortSwitchAddonSkillMax=30, kPortSwitchAddonNormalMax=65; // CItemAddonManager::ApplyAddonTo bounds. + +struct PortSwitchTarget {unsigned apply;int value;}; +struct PortSwitchbot { + DWORD pid=0,item=0,scroll=0;unsigned limit=0,rolls=0;VID vid; + std::vector alternatives[kPortSwitchAlternatives]; + LPEVENT event; +}; +static std::map g_portSwitchbots; + +static bool PortSwitchNumber(const std::string& text,unsigned& value) { + if(text.empty() || text.size()>10)return false; + unsigned long long result=0; + for(char c:text){if(c<'0'||c>'9')return false;result=result*10+(c-'0');} + if(result>0xffffffffull)return false; + value=unsigned(result);return true; +} + +// Attribute types a reroll of this item can produce, with the highest value each can reach. +static std::vector > PortSwitchAllowed(LPITEM item) { + std::vector > allowed; + const int set=item->GetAttributeSetIndex(); + if(set<0)return allowed; + const TItemTable* proto=item->GetProto(); + for(unsigned apply=0;applysecond.bMaxLevelBySet[set]; + if(!level)continue; + bool base=false; + for(int i=0;iaApplies[i].bType==apply; + const long value=it->second.lValues[(level>5?5:level)-1]; + if(!base && value>0)allowed.push_back(std::make_pair(apply,int(value))); + } + if(proto && proto->sAddonType) { + allowed.push_back(std::make_pair(unsigned(APPLY_SKILL_DAMAGE_BONUS),int(kPortSwitchAddonSkillMax))); + allowed.push_back(std::make_pair(unsigned(APPLY_NORMAL_HIT_DAMAGE_BONUS),int(kPortSwitchAddonNormalMax))); + } + return allowed; +} + +// AVA2 CheckItem semantics over the five normal slots: any one configured alternative fully satisfied. +static bool PortSwitchMatches(LPITEM item,const PortSwitchbot& bot) { + for(const auto& alternative:bot.alternatives) { + if(alternative.empty())continue; + bool all=true; + for(const auto& target:alternative) { + bool found=false; + for(int i=0;iGetAttribute(i); + found=attr.bType==target.apply && attr.sValue>=target.value; + } + all&=found; + } + if(all)return true; + } + return false; +} + +static bool PortSwitchBusy(LPCHARACTER ch) { + return ch->IsDead() || ch->IsWarping() || !ch->CanHandleItem() || ch->GetExchange() || ch->GetMyShop() || + ch->GetShopOwner() || ch->IsOpenSafebox() || ch->IsCubeOpen(); +} + +static LPITEM PortSwitchItem(LPCHARACTER ch,const PortSwitchbot& bot) { + LPITEM item=ITEM_MANAGER::instance().Find(bot.item); + if(!item || item->GetOwner()!=ch || item->GetWindow()!=INVENTORY || item->GetCell()>=INVENTORY_MAX_NUM || item->IsEquipped())return NULL; + return item; +} + +static bool PortSwitchScroll(LPITEM scroll) { + return scroll && scroll->GetType()==ITEM_USE && scroll->GetSubType()==USE_CHANGE_ATTRIBUTE; +} + +static void PortSwitchState(LPCHARACTER ch,const PortSwitchbot* bot,bool active,const char* reason) { + LPITEM item=bot?PortSwitchItem(ch,*bot):NULL; + ch->ChatPacket(CHAT_TYPE_COMMAND,"MTSB1 state %u %u %u %u %u %u %d %s",unsigned(active),item?unsigned(item->GetCell()):0u, + item?unsigned(item->GetVnum()):0u,bot?bot->rolls:0u,bot?bot->limit:0u,bot?unsigned(bot->scroll):0u, + bot?ch->CountSpecifyItem(bot->scroll):0,reason); +} + +// One roll. Returns NULL to keep running, otherwise the stop reason. +static const char* PortSwitchStep(LPCHARACTER ch,PortSwitchbot& bot) { + if(PortSwitchBusy(ch))return "busy"; + LPITEM item=PortSwitchItem(ch,bot); + if(!item)return "item_gone"; + if(PortSwitchMatches(item,bot))return "matched"; + if(bot.rolls>=bot.limit)return "limit"; + LPITEM scroll=ch->FindSpecifyItem(bot.scroll); + if(!PortSwitchScroll(scroll))return "no_scroll"; + const int before=ch->CountSpecifyItem(bot.scroll); + ch->m_portQuietInfo=true;ch->m_portLastInfo.clear(); + ch->UseItem(TItemPos(INVENTORY,scroll->GetCell()),TItemPos(INVENTORY,item->GetCell())); + ch->m_portQuietInfo=false; + // Success is judged by the original path consuming exactly one scroll, not by its return value. + if(ch->CountSpecifyItem(bot.scroll)!=before-1) { + if(!ch->m_portLastInfo.empty())ch->ChatPacket(CHAT_TYPE_INFO,"%s",ch->m_portLastInfo.c_str()); + return "rejected"; + } + ++bot.rolls; + item=PortSwitchItem(ch,bot); + if(!item)return "item_gone"; + return PortSwitchMatches(item,bot)?"matched":bot.rolls>=bot.limit?"limit":NULL; +} + +EVENTINFO(PortSwitchbotInfo){DWORD pid;PortSwitchbotInfo():pid(0){}}; + +EVENTFUNC(port_switchbot_event) { + PortSwitchbotInfo* info=dynamic_cast(event->info); + if(!info)return 0; + auto it=g_portSwitchbots.find(info->pid); + if(it==g_portSwitchbots.end())return 0; + PortSwitchbot& bot=it->second; + LPCHARACTER ch=CHARACTER_MANAGER::instance().Find(bot.vid); + // A new instance after logout or warp carries a new VID; the bot does not follow it. + if(!ch || ch->GetPlayerID()!=bot.pid || !ch->GetDesc()) {bot.event=NULL;g_portSwitchbots.erase(it);return 0;} + const char* reason=PortSwitchStep(ch,bot); + if(!reason) {PortSwitchState(ch,&bot,true,"running");return PASSES_PER_SEC(1)/4;} + PortSwitchState(ch,&bot,false,reason); + bot.event=NULL;g_portSwitchbots.erase(it); + return 0; +} + +static void PortSwitchStop(LPCHARACTER ch,const char* reason) { + auto it=g_portSwitchbots.find(ch->GetPlayerID()); + if(it==g_portSwitchbots.end()) {PortSwitchState(ch,NULL,false,"idle");return;} + if(it->second.event)event_cancel(&it->second.event); + PortSwitchState(ch,&it->second,false,reason); + g_portSwitchbots.erase(it); +} + +static void PortSwitchAttrs(LPCHARACTER ch,unsigned cell) { + LPITEM item=cellGetItem(TItemPos(INVENTORY,cell)):NULL; + if(!item){ch->ChatPacket(CHAT_TYPE_COMMAND,"MTSB1 error attrs item");return;} + if(item->GetType()==ITEM_COSTUME || item->GetAttributeSetIndex()<0){ch->ChatPacket(CHAT_TYPE_COMMAND,"MTSB1 error attrs no_attr");return;} + auto allowed=PortSwitchAllowed(item); + ch->ChatPacket(CHAT_TYPE_COMMAND,"MTSB1 attrs %u %u %u",cell,unsigned(item->GetVnum()),unsigned(allowed.size())); + for(unsigned i=0;iChatPacket(CHAT_TYPE_COMMAND,"MTSB1 attr %u %u %d",i,allowed[i].first,allowed[i].second); + ch->ChatPacket(CHAT_TYPE_COMMAND,"MTSB1 attrs_end %u %u",cell,unsigned(allowed.size())); +} + +// start CELL SCROLL LIMIT N1 (APPLY VALUE)*N1 [N2 (APPLY VALUE)*N2] +static const char* PortSwitchStart(LPCHARACTER ch,const std::vector& args) { + unsigned cell=0,scrollVnum=0,limit=0; + if(args.size()<6 || !PortSwitchNumber(args[2],cell) || !PortSwitchNumber(args[3],scrollVnum) || + !PortSwitchNumber(args[4],limit) || !limit || limit>kPortSwitchLimit)return "invalid"; + if(g_portSwitchbots.count(ch->GetPlayerID()))return "running"; + if(PortSwitchBusy(ch))return "busy"; + LPITEM item=cellGetItem(TItemPos(INVENTORY,cell)):NULL; + if(!item)return "item"; + if(item->IsEquipped() || item->IsExchanging())return "equipped"; + if(item->GetType()==ITEM_COSTUME || item->GetAttributeSetIndex()<0 || !item->GetAttributeCount())return "no_attr"; + if(!PortSwitchScroll(ch->FindSpecifyItem(scrollVnum)))return "scroll"; + PortSwitchbot bot;bot.pid=ch->GetPlayerID();bot.vid=ch->GetVID();bot.item=item->GetID();bot.scroll=scrollVnum;bot.limit=limit; + const auto allowed=PortSwitchAllowed(item); + size_t at=5; + for(unsigned alt=0;altkPortSwitchTargets || at+count*2>args.size())return "invalid"; + for(unsigned i=0;iunsigned(max))return "target"; + for(const auto& t:bot.alternatives[alt])if(t.apply==apply)return "target"; + bot.alternatives[alt].push_back(PortSwitchTarget{apply,int(value)}); + } + } + if(at!=args.size())return "invalid"; + if(PortSwitchMatches(item,bot)) {PortSwitchState(ch,&bot,false,"matched");return NULL;} + PortSwitchbot& stored=g_portSwitchbots[bot.pid];stored=bot; + PortSwitchbotInfo* info=AllocEventInfo();info->pid=bot.pid; + stored.event=event_create(port_switchbot_event,info,PASSES_PER_SEC(1)/4); + PortSwitchState(ch,&stored,true,"running"); + return NULL; +} + +ACMD(do_port_switchbot) { + if(!ch || !ch->IsPC() || !ch->GetDesc())return; + std::istringstream input(argument);std::vector args;std::string token; + while(input>>token){if(token.size()>10 || args.size()>=30)return;args.push_back(token);} + if(args.size()<2 || args[0]!="1")return; + const std::string& verb=args[1]; + if(get_dword_time()-ch->m_portSwitchbotLastCommand<250 && ch->m_portSwitchbotLastCommand) { + ch->ChatPacket(CHAT_TYPE_COMMAND,"MTSB1 error %s rate",verb.c_str());return; + } + ch->m_portSwitchbotLastCommand=get_dword_time(); + unsigned cell=0; + if(verb=="attrs" && args.size()==3 && PortSwitchNumber(args[2],cell)) PortSwitchAttrs(ch,cell); + else if(verb=="stop" && args.size()==2) PortSwitchStop(ch,"stopped"); + else if(verb=="status" && args.size()==2) { + auto it=g_portSwitchbots.find(ch->GetPlayerID()); + if(it==g_portSwitchbots.end())PortSwitchState(ch,NULL,false,"idle"); + else PortSwitchState(ch,&it->second,true,"running"); + } + else if(verb=="start") { + const char* error=PortSwitchStart(ch,args); + if(error)ch->ChatPacket(CHAT_TYPE_COMMAND,"MTSB1 error start %s",error); + } + else ch->ChatPacket(CHAT_TYPE_COMMAND,"MTSB1 error %s invalid",verb.size()<=10?verb.c_str():"unknown"); +} +#endif diff --git a/tests/features/test_queries.py b/tests/features/test_queries.py index 82eacf9a..b7e9501d 100644 --- a/tests/features/test_queries.py +++ b/tests/features/test_queries.py @@ -106,7 +106,7 @@ int main(){ assert(rewards[0].total==100 && rewards[0].rule==WIKI_SINGLE); rewards=items.PortWikiChest(50012);assert(rewards[1].rule==WIKI_INDEPENDENT && rewards[1].weight==150 && rewards[1].total==100); assert(items.PortWikiChest(50013).empty() && items.PortWikiChest(19).empty()); - Character ch;query(ch,"1 1 cap");assert(ch.messages.back()=="MTF1 cap 1 1 63 1700000000"); + Character ch;query(ch,"1 1 cap");assert(ch.messages.back()=="MTF1 cap 1 1 127 1700000000"); ch.messages.clear();query(ch,"1 2 mob 101 0");assert(ch.messages.size()==10 && ch.messages.back()=="MTF1 end 2 8"); query(ch,"1 3 mob 101 999");assert(ch.messages.back()=="MTF1 error 3 offset"); query(ch,"1 4 mob 9001 0");assert(ch.messages.back()=="MTF1 error 4 missing"); diff --git a/tests/features/test_switchbot.py b/tests/features/test_switchbot.py new file mode 100644 index 00000000..e1efa59a --- /dev/null +++ b/tests/features/test_switchbot.py @@ -0,0 +1,174 @@ +#!/usr/bin/env python3 +"""Compile the production switchbot header against stubs of the original UseItem/ChatPacket contract.""" +from pathlib import Path +import subprocess +import tempfile +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') +code=r''' +#include +#include +#include +#include +#include +#include +#include +#include +#include +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 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> events; +template 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;} +struct CHARACTER; +struct CItem { + 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]; + 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];} + 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 IsEquipped(){return equipped;}bool IsExchanging(){return exchanging;} +}; +using LPITEM=CItem*; +struct ITEM_MANAGER{ + static const int MAX_NORM_ATTR_NUM=5;std::vector 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;} +}; +struct CHARACTER { + 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 messages,info;std::vector inventory; + std::deque>> 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;iattrs[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 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" +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);} + + // Allowed list: proto applies excluded, set filter, level cap picks lValues[level-1]. + cmd("1 attrs 10"); + assert(ch.messages.size()==4 && 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" && last()=="MTSB1 attrs_end 10 2"); + 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"); + + // 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"); + 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); + + // 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()); + + // 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"); + + // 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(); + + // 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); + + // 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"); +} +''' +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)