From 1a367197f50a6fd12a877838678c9cd7e7f59ce3 Mon Sep 17 00:00:00 2001 From: shen <> Date: Thu, 15 Oct 2026 02:28:03 -0700 Subject: [PATCH] Add feature query protocol and scheduled event drop gates --- docs/FEATURE-DUNGEON-CALENDAR.md | 25 ++++ docs/FEATURE-QUERY-PROTOCOL.md | 72 +++++++++++ src/server/game/src/char.h | 2 + src/server/game/src/cmd.cpp | 2 + src/server/game/src/cmd_general.cpp | 3 + src/server/game/src/item_manager.cpp | 8 +- src/server/game/src/item_manager.h | 7 ++ src/server/game/src/port_calendar.h | 68 ++++++++++ src/server/game/src/port_calendar_runtime.h | 24 ++++ src/server/game/src/port_dungeon_rules.h | 8 ++ src/server/game/src/port_dungeons.h | 62 +++++++++ src/server/game/src/port_feature_types.h | 10 ++ src/server/game/src/port_features.h | 99 +++++++++++++++ src/server/game/src/port_wiki_queries.inc | 51 ++++++++ tests/features/dungeon_lua_probe.cpp | 72 +++++++++++ tests/features/test_calendar.py | 72 +++++++++++ tests/features/test_queries.py | 132 ++++++++++++++++++++ tools/calendar/port_events.tsv.example | 6 + 18 files changed, 721 insertions(+), 2 deletions(-) create mode 100644 docs/FEATURE-DUNGEON-CALENDAR.md create mode 100644 docs/FEATURE-QUERY-PROTOCOL.md create mode 100644 src/server/game/src/port_calendar.h create mode 100644 src/server/game/src/port_calendar_runtime.h create mode 100644 src/server/game/src/port_dungeon_rules.h create mode 100644 src/server/game/src/port_dungeons.h create mode 100644 src/server/game/src/port_feature_types.h create mode 100644 src/server/game/src/port_features.h create mode 100644 src/server/game/src/port_wiki_queries.inc create mode 100644 tests/features/dungeon_lua_probe.cpp create mode 100644 tests/features/test_calendar.py create mode 100644 tests/features/test_queries.py create mode 100644 tools/calendar/port_events.tsv.example diff --git a/docs/FEATURE-DUNGEON-CALENDAR.md b/docs/FEATURE-DUNGEON-CALENDAR.md new file mode 100644 index 00000000..49e2cd63 --- /dev/null +++ b/docs/FEATURE-DUNGEON-CALENDAR.md @@ -0,0 +1,25 @@ +# PORT dungeon / calendar extension + +The `dungeons` query reads only the installed dragon_lair_access / dragon_lair_weekly settings functions and own PC flags through GetPCForce. It preserves the quest Lua stack/context. This adapter is specific to the audited quest implementation: changes to its flag names, NPCs or admission logic require review. Only the function settings are dynamic, not an arbitrary automatic quest interpreter. No gate bypass or reward/warp command is added. + +Calendar uses a stateless interval scheduler shared by the actual drop gates and the read-only query. Configure `LocaleService_GetBasePath()/port_events.tsv` (same shared locale path for all cores): + +``` +MTCALENDAR 1 +# id kind UTC_start_epoch UTC_end_epoch channel empire +``` + +Kinds 1 and 2 enable the existing moonlight-box and Christmas-sock branches in CreateQuestDropItem. They do not replace the probabilities, RNG or eligibility in those branches. Existing administrator event flags remain effective independently; ending a scheduled interval does not clear an unrelated administrator flag. Other activity types are rejected. Scope 0 means all channels/empires; channel 1..255, empire 1..3. Time is Unix UTC, start inclusive/end exclusive, unsigned 32-bit bounds; ID unique/nonzero, at most 256 events / 64 KiB. Overlapping intervals do not multiply a drop. There are no repeated start/end grants or database mutations. + +Use `tools/calendar/port_events.tsv.example` as a valid empty template. Review dates and effects before publishing. Write a temporary file then atomic rename on the common locale filesystem. Each process refreshes within 5 seconds; runtime uses server time for every interval check so restarts and clock adjustments do not leave event flags stuck on. Atomic inode replacement is detected even for same-size/same-second edits. An invalid/missing file clears scheduled effects and returns schedule_unavailable. Roll back by publishing a valid empty schedule. The production file was not installed by development/validation. + +Validation: + +``` +python3 tests/features/test_queries.py +python3 tests/features/test_calendar.py +``` + +On FreeBSD compile `tests/features/dungeon_lua_probe.cpp` with `-std=c++17`, game/src and liblua/include include paths, linking project's liblualib.a then liblua.a and -lm. Run with the installed compiled quest files `quest/object/state/dragon_lair_access` and `dragon_lair_weekly`. This independent process does not connect to the game/DB and does not modify quest files. It verifies actual task functions rather than hardcoded fixture timing alone. + +The full game target was rebuilt only under `/root/metin2-features-dev`, with forced rebuild of item_manager.cpp/cmd_general.cpp. No production binary replacement, restart, DB migration or event activation occurred. Live deployment acceptance, real Android interaction, other dungeons and other activity types remain outside this batch. diff --git a/docs/FEATURE-QUERY-PROTOCOL.md b/docs/FEATURE-QUERY-PROTOCOL.md new file mode 100644 index 00000000..37d19208 --- /dev/null +++ b/docs/FEATURE-QUERY-PROTOCOL.md @@ -0,0 +1,72 @@ +# PORT read-only query protocol v1 + +Date: 2026-10-15. Implementation: `src/server/game/src/port_features.h`, `port_wiki_queries.inc`. +Client: metin2-client `FeatureServiceScript.inc`. This is a narrow transport adaptation of AVA2 encyclopedia/drop/chest/details features, not a copy of AVA2 packet numbers or item layout. + +Request through existing CG chat command: + +``` +/mt_features 1 REQUEST cap +/mt_features 1 REQUEST mob MOB_VNUM OFFSET +/mt_features 1 REQUEST chest ITEM_VNUM OFFSET +/mt_features 1 REQUEST sources ITEM_VNUM OFFSET +/mt_features 1 REQUEST stats +/mt_features 1 REQUEST dungeons +/mt_features 1 REQUEST calendar 1 OFFSET +``` + +REQUEST: 1..2147483647, independent for each game session's pending command. Subject: unsigned 32-bit nonzero ID. OFFSET: 0..4096. Other versions, excess arguments, oversized tokens, signed/overflow identifiers are rejected. Queries require an own PC descriptor. Per-character throttle: 250 ms. No gameplay mutation, consumption, random draws or database write. + +Replies use existing `CHAT_TYPE_COMMAND`; no binary struct is serialized: + +``` +MTF1 cap REQUEST 1 MASK SERVER_TIME +MTF1 begin REQUEST KIND SUBJECT OFFSET TOTAL MODE SERVER_TIME +MTF1 row REQUEST INDEX ITEM COUNT RULE MIN MAX WEIGHT GROUP_TOTAL RARE +MTF1 stat REQUEST INDEX KEY SIGNED_VALUE +MTF1 event REQUEST INDEX EVENT_ID KIND START END CHANNEL EMPIRE ACTIVE +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. + +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. + +Rules: + +| RULE | Meaning of MIN/MAX and weights | +|---|---| +| 0 | rank common drop; MIN/MAX = eligible player levels | +| 1 | independent monster drop group; weight is original configured threshold, not final probability | +| 2 | weighted kill group; MIN = original kill-per-drop parameter; weight/group total describe the conditional selection | +| 3 | level group; MIN = player minimum level; original denominator 1,000,000 | +| 4 | glove/premium eligibility required; threshold still subject to runtime drop modifiers | +| 5 | monster-template extra item | +| 10 | NORMAL chest, select one weighted entry | +| 11 | PCT chest, independent comparison per entry against a 1..100 random integer | +| 20/21 | reverse source is a NORMAL/PCT chest, ITEM is the chest ID | + +For sources with rules below 20, ITEM is a monster ID. For chest rewards, IDs 1..7 are the existing CSpecialItemGroup reward enum: GOLD, EXP, MOB, SLOW, DRAIN_HP, POISON, MOB_GROUP. COUNT is the original amount/effect/target parameter, not always an item count. QUEST/SPECIAL groups are not treated as chest rewards. A matching item template and GIFTBOX/TREASURE_BOX type are required. + +Errors: rate, invalid, missing, offset, unsupported, unsupported_chest, too_many. Empty mob/source pages refer only to covered regular drop paths. Quest/event/hard-coded/map-specific/extra-stone-drop paths are not advertised as exhaustively queried. Chest preview does not validate current inventory keys/eligibility or grant rewards; original use path owns those checks. + +Stats use stable text keys mapped to this build's POINT constants. LEVEL/HP/SP and maxima use the actual character getters; other keys use own character GetPoint. No access to another player's stats and no AVA2 numeric point aliases. This is a point snapshot, not a final damage simulator or all-source multiplier breakdown. + +## Tests / build + +``` +python3 tests/features/test_queries.py +``` + +The test compiles production query and command bodies against original group classes. It checks all supported group paths, live fixture changes, common-only polymorph filtering, NORMAL/PCT weights, special reward IDs, unsupported groups, own stats/HP getter, source pages, throttle/invalid requests and zero RNG calls. + +FreeBSD target build was completed in `/root/metin2-features-dev/src/server/game/src`, with both BINDIR and GAMEDIR pointed to the isolated directory. The Makefile moves its output: never omit GAMEDIR during validation. Includes added to the legacy build require dependency regeneration or explicit `-W item_manager.cpp -W cmd_general.cpp`; after char.h changes rebuild all affected units. + +No live 203 binary was replaced, no service was restarted and no DB schema was changed by this batch. The staged build is not a production deployment. Live acceptance and mobile device validation remain pending; switchbot/attribute locks and battlepass are not claimed implemented. The subsequent dungeon/calendar batch is documented in FEATURE-DUNGEON-CALENDAR.md. + +## Dungeon/calendar snapshots + +`dungeons` uses subject/offset 0 and a complete stat-style snapshot, capped at 128 fields. Mandatory lair keys: end, join_end, phase (0 new run possible, 1 join window, 2 room busy), ticket, tickets, boss, owned, alive, npc, map, each prefixed `lair_`. The original strict negative cooldown test is preserved: a new run is available only after end, not at end. `lair_phase` is not authorization to enter. Optional weekly group must be complete: weekly_end, weekly_hunt_end, weekly_active, weekly_npc, weekly_map. These are personal collection-task times, independent of shared room admission. A running/unloaded own quest returns busy; missing/invalid settings return unsupported. + +`calendar` uses subject 1, offset 0..4096, page size 8, total at most 256. Event rows contain only bounded IDs/numeric data. Kind 1 moonlight-box, 2 Christmas-sock; time/scope semantics in FEATURE-DUNGEON-CALENDAR.md. ACTIVE reflects the interval and requesting character's current channel/empire. UI renders UTC dates, resynchronizes after sleep, and only fires opt-in reminders from freshly confirmed snapshots. No client-authored schedule or progress update command exists. diff --git a/src/server/game/src/char.h b/src/server/game/src/char.h index b568e627..3a1d411a 100755 --- a/src/server/game/src/char.h +++ b/src/server/game/src/char.h @@ -517,6 +517,8 @@ class CHARACTER : public CEntity, public CFSM, public CHorseRider ////////////////////////////////////////////////////////////////////////////////// public: + DWORD m_portFeatureLastQuery = 0; // PORT: read-only query throttle, not persisted. + 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 5c2c9b13..38cb1e63 100755 --- a/src/server/game/src/cmd.cpp +++ b/src/server/game/src/cmd.cpp @@ -9,6 +9,7 @@ ACMD(do_autohunt_pull); ACMD(do_server_bonuses); ACMD(do_port_biolog); +ACMD(do_port_features); ACMD(do_user_horse_ride); ACMD(do_user_horse_back); ACMD(do_user_horse_feed); @@ -283,6 +284,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 }, { "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 3845a115..ca8ab7ae 100755 --- a/src/server/game/src/cmd_general.cpp +++ b/src/server/game/src/cmd_general.cpp @@ -40,6 +40,9 @@ #include "autohunt_pull.h" #include "biolog_remote.h" +#include "port_dungeons.h" +#include "port_calendar_runtime.h" +#include "port_features.h" extern int g_server_id; diff --git a/src/server/game/src/item_manager.cpp b/src/server/game/src/item_manager.cpp index 89be0ab2..149608d4 100755 --- a/src/server/game/src/item_manager.cpp +++ b/src/server/game/src/item_manager.cpp @@ -17,6 +17,8 @@ #include "locale_service.h" #include "item.h" #include "item_manager.h" +#include "mob_manager.h" +#include "port_calendar_runtime.h" #include "../../common/VnumHelper.h" #include "DragonSoul.h" @@ -1400,7 +1402,7 @@ void ITEM_MANAGER::CreateQuestDropItem(LPCHARACTER pkChr, LPCHARACTER pkKiller, __DropEvent_RefineBox_DropItem(*pkKiller, *pkChr, *this, vec_item); // 크리스마스 양말 - if (quest::CQuestManager::instance().GetEventFlag("xmas_sock")) + if (quest::CQuestManager::instance().GetEventFlag("xmas_sock") || PortScheduledDrop(2,pkKiller)) { //const DWORD SOCK_ITEM_VNUM = 50010; DWORD SOCK_ITEM_VNUM = 0; @@ -1442,7 +1444,7 @@ void ITEM_MANAGER::CreateQuestDropItem(LPCHARACTER pkChr, LPCHARACTER pkKiller, } // 월광 보합 - if (quest::CQuestManager::instance().GetEventFlag("drop_moon")) + if (quest::CQuestManager::instance().GetEventFlag("drop_moon") || PortScheduledDrop(1,pkKiller)) { const DWORD ITEM_VNUM = 50011; @@ -1775,3 +1777,5 @@ void ITEM_MANAGER::CopyAllAttrTo(LPITEM pkOldItem, LPITEM pkNewItem) // 매직 아이템 설정 pkOldItem->CopyAttributeTo(pkNewItem); } + +#include "port_wiki_queries.inc" diff --git a/src/server/game/src/item_manager.h b/src/server/game/src/item_manager.h index 8259209d..01aa3060 100755 --- a/src/server/game/src/item_manager.h +++ b/src/server/game/src/item_manager.h @@ -1,5 +1,6 @@ #ifndef __INC_ITEM_MANAGER__ #define __INC_ITEM_MANAGER__ +#include "port_feature_types.h" #ifdef M2_USE_POOL #include "pool.h" @@ -217,6 +218,9 @@ class CMobItemGroup } // END_OF_MOB_DROP_ITEM_BUG_FIX + const std::vector& PortWikiItems() const { return m_vecItems; } + const std::vector& PortWikiWeights() const { return m_vecProbs; } + const SMobItemGroupInfo& GetOne() const { return m_vecItems[GetOneIndex()]; @@ -383,6 +387,9 @@ class ITEM_MANAGER : public singleton bool GetVnumByOriginalName(const char * c_pszName, DWORD & r_dwVnum); bool GetDropPct(LPCHARACTER pkChr, LPCHARACTER pkKiller, OUT int& iDeltaPercent, OUT int& iRandRange); + std::vector PortWikiDrops(DWORD race); + std::vector PortWikiChest(DWORD vnum); + bool CreateDropItem(LPCHARACTER pkChr, LPCHARACTER pkKiller, std::vector & vec_item); bool ReadCommonDropItemFile(const char * c_pszFileName); diff --git a/src/server/game/src/port_calendar.h b/src/server/game/src/port_calendar.h new file mode 100644 index 00000000..648f1a9c --- /dev/null +++ b/src/server/game/src/port_calendar.h @@ -0,0 +1,68 @@ +#ifndef PORT_CALENDAR_H +#define PORT_CALENDAR_H +#include +#include +#include +#include +#include +#include +#include +#include +// Stateless schedule: the same intervals gate real drop branches and client calendar. +// No timer callback grants rewards, toggles a global flag or stacks a probability. +struct PortCalendarEvent { + unsigned id,kind,start,end,channel,empire; + bool Active(long long now,unsigned ch,unsigned faction)const { + return now>=start && now events; + bool valid=false; + bool Parse(std::istream& input) { + std::vector next;std::set ids;std::string line;unsigned bytes=0; + bool header=false,okay=true; + while(std::getline(input,line)) { + bytes+=unsigned(line.size()+1);if(bytes>65536){okay=false;break;} + if(line.empty() || line[0]=='#')continue; + if(!header){if(line!="MTCALENDAR 1"){okay=false;break;}header=true;continue;} + std::istringstream row(line);std::vector values;std::string token; + while(row>>token) { + unsigned long long value=0; + if(token.empty() || token.size()>10){okay=false;break;} + for(char c:token){if(c<'0'||c>'9'){okay=false;break;}value=value*10+(c-'0');} + if(!okay || value>std::numeric_limits::max()){okay=false;break;} + values.push_back(unsigned(value)); + } + if(!okay || values.size()!=6 || next.size()>=256){okay=false;break;} + PortCalendarEvent event={values[0],values[1],values[2],values[3],values[4],values[5]}; + if(!event.id || (event.kind!=1 && event.kind!=2) || event.start>=event.end || event.channel>255 || event.empire>3 || !ids.insert(event.id).second){okay=false;break;} + next.push_back(event); + } + valid=okay && header && !input.bad(); + if(valid) {std::sort(next.begin(),next.end(),[](const PortCalendarEvent& a,const PortCalendarEvent& b){return a.start!=b.start?a.start65536 || size<0){valid=false;events.clear();return;} + std::ifstream file(path);Parse(file); + } +private: + bool checked=false,loaded=false;unsigned lastCheck=0;time_t modified=0;off_t size=0;ino_t inode=0; +}; +inline PortCalendar& PortEvents() {static PortCalendar schedule;return schedule;} +#endif diff --git a/src/server/game/src/port_calendar_runtime.h b/src/server/game/src/port_calendar_runtime.h new file mode 100644 index 00000000..ca037381 --- /dev/null +++ b/src/server/game/src/port_calendar_runtime.h @@ -0,0 +1,24 @@ +#ifndef PORT_CALENDAR_RUNTIME_H +#define PORT_CALENDAR_RUNTIME_H +#include "port_calendar.h" +#include "locale_service.h" +inline PortCalendar& PortCurrentEvents() { + auto& schedule=PortEvents();schedule.Refresh(LocaleService_GetBasePath()+"/port_events.tsv",get_dword_time());return schedule; +} +inline bool PortScheduledDrop(unsigned kind,LPCHARACTER killer) { + return killer && PortCurrentEvents().Active(kind,get_global_time(),g_bChannel,killer->GetEmpire()); +} +inline void PortCalendarQuery(LPCHARACTER ch,unsigned request,unsigned offset) { + auto& schedule=PortCurrentEvents(); + if(!schedule.valid){ch->ChatPacket(CHAT_TYPE_COMMAND,"MTF1 error %u schedule_unavailable",request);return;} + if(offset>schedule.events.size()){ch->ChatPacket(CHAT_TYPE_COMMAND,"MTF1 error %u offset",request);return;} + const long long now=get_global_time(); + ch->ChatPacket(CHAT_TYPE_COMMAND,"MTF1 begin %u calendar 1 %u %u 0 %lld",request,offset,unsigned(schedule.events.size()),now); + unsigned sent=0; + for(unsigned i=offset;iChatPacket(CHAT_TYPE_COMMAND,"MTF1 event %u %u %u %u %u %u %u %u %u",request,i,e.id,e.kind,e.start,e.end,e.channel,e.empire,unsigned(e.Active(now,g_bChannel,ch->GetEmpire()))); + } + ch->ChatPacket(CHAT_TYPE_COMMAND,"MTF1 end %u %u",request,sent); +} +#endif diff --git a/src/server/game/src/port_dungeon_rules.h b/src/server/game/src/port_dungeon_rules.h new file mode 100644 index 00000000..e0468f18 --- /dev/null +++ b/src/server/game/src/port_dungeon_rules.h @@ -0,0 +1,8 @@ +#ifndef PORT_DUNGEON_RULES_H +#define PORT_DUNGEON_RULES_H +// Match dragon_lair_access: join window is inclusive, new run requires remaining < 0. +struct PortLairState { long long end, joinEnd; unsigned phase; }; +inline PortLairState PortLair(long long start, unsigned cooldown, unsigned join, long long now) { + return {start+cooldown,start+join, start+join>=now?1u:start+cooldown>=now?2u:0u}; +} +#endif diff --git a/src/server/game/src/port_dungeons.h b/src/server/game/src/port_dungeons.h new file mode 100644 index 00000000..84bd2f19 --- /dev/null +++ b/src/server/game/src/port_dungeons.h @@ -0,0 +1,62 @@ +#ifndef PORT_DUNGEONS_H +#define PORT_DUNGEONS_H +#include "port_dungeon_rules.h" +#include "questpc.h" +#include +// Only audited settings functions are invoked; never switch quest/player context. +// They read event flags and return settings, without RNG, items, warps or quest writes. +static bool PortDungeonSettings(const char* questName,const char* function, + const std::vector& fields,std::vector& out) { + lua_State* L=quest::CQuestManager::instance().GetLuaState(); + if(!L)return false; + const int top=lua_gettop(L); + lua_getglobal(L,questName); + if(!lua_istable(L,-1)){lua_settop(L,top);return false;} + lua_pushstring(L,function);lua_rawget(L,-2); + if(!lua_isfunction(L,-1) || lua_pcall(L,0,1,0)!=0 || !lua_istable(L,-1)) { + lua_settop(L,top);return false; + } + out.clear();bool valid=true; + for(const char* field:fields) { + lua_pushstring(L,field);lua_rawget(L,-2); + const double value=lua_tonumber(L,-1); + if(lua_type(L,-1)!=LUA_TNUMBER || !std::isfinite(value) || value<0 || value>2147483647 || std::floor(value)!=value)valid=false; + out.push_back(valid?unsigned(value):0);lua_pop(L,1); + } + lua_settop(L,top);return valid; +} +static bool PortDungeonQuery(LPCHARACTER ch,unsigned request) { + auto& manager=quest::CQuestManager::instance(); + quest::PC* pc=manager.GetPCForce(ch->GetPlayerID()); + if(!pc || !pc->IsLoaded() || pc->IsRunning()) { + ch->ChatPacket(CHAT_TYPE_COMMAND,"MTF1 error %u busy",request);return true; + } + std::vector lair,weekly; + if(!manager.GetQuestIndexByName("dragon_lair_access") || + !PortDungeonSettings("dragon_lair_access","get_settings",{"cooldown_time","group_time","access_item","access_item_amount","dragon_vnum"},lair) || + !lair[0] || lair[1]>lair[0] || !ITEM_MANAGER::instance().GetTable(lair[2])) { + ch->ChatPacket(CHAT_TYPE_COMMAND,"MTF1 error %u unsupported",request);return true; + } + const long long now=get_global_time(); + const long long start=manager.GetEventFlag("dragon_lair_time"); + const auto state=PortLair(start,lair[0],lair[1],now); + std::vector> values={ + {"lair_end",state.end},{"lair_join_end",state.joinEnd},{"lair_phase",state.phase}, + {"lair_ticket",lair[2]},{"lair_tickets",lair[3]},{"lair_boss",lair[4]}, + {"lair_owned",ch->CountSpecifyItem(lair[2])},{"lair_alive",manager.GetEventFlag("dragon_lair_alive")}, + {"lair_npc",30121},{"lair_map",208}}; + // Personal weekly collection quest is deliberately separate from shared room admission. + if(manager.GetQuestIndexByName("dragon_lair_weekly") && + PortDungeonSettings("dragon_lair_weekly","set_settings",{"cooldown_time","time_to_hunt"},weekly) && weekly[0] && weekly[1]) { + const long long last=pc->GetFlag("dragon_lair_weekly.lasttime"); + values.push_back({"weekly_end",last?last+weekly[0]:0}); + values.push_back({"weekly_hunt_end",last?last+weekly[1]:0}); + values.push_back({"weekly_active",pc->GetFlag("dragon_lair_weekly.__status")==manager.GetQuestStateIndex("dragon_lair_weekly","hunt_item")}); + values.push_back({"weekly_npc",30122});values.push_back({"weekly_map",73}); + } + ch->ChatPacket(CHAT_TYPE_COMMAND,"MTF1 begin %u dungeons 0 0 %u 0 %lld",request,unsigned(values.size()),now); + for(unsigned i=0;iChatPacket(CHAT_TYPE_COMMAND,"MTF1 stat %u %u %s %lld",request,i,values[i].first,values[i].second); + ch->ChatPacket(CHAT_TYPE_COMMAND,"MTF1 end %u %u",request,unsigned(values.size()));return true; +} +#endif diff --git a/src/server/game/src/port_feature_types.h b/src/server/game/src/port_feature_types.h new file mode 100644 index 00000000..4c3bc73e --- /dev/null +++ b/src/server/game/src/port_feature_types.h @@ -0,0 +1,10 @@ +#ifndef METIN2_PORT_FEATURE_TYPES_H +#define METIN2_PORT_FEATURE_TYPES_H +#include +// All fields are encoded explicitly as bounded decimal tokens, never native structs. +struct PortWikiRow { + unsigned item, count, rule, minimum, maximum, weight, total, rare; +}; +enum PortWikiRule { WIKI_COMMON=0, WIKI_DROP=1, WIKI_KILL=2, WIKI_LEVEL=3, + WIKI_GLOVE=4, WIKI_ETC=5, WIKI_SINGLE=10, WIKI_INDEPENDENT=11 }; +#endif diff --git a/src/server/game/src/port_features.h b/src/server/game/src/port_features.h new file mode 100644 index 00000000..8b7dedc9 --- /dev/null +++ b/src/server/game/src/port_features.h @@ -0,0 +1,99 @@ +#ifndef METIN2_PORT_FEATURES_H +#define METIN2_PORT_FEATURES_H +#include +#include +#include +#include +// Own-player read-only protocol v1. Capability bits: drops, chests, stats, reverse sources, dungeon snapshots. +static bool PortFeatureNumber(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>std::numeric_limits::max())return false; + value=unsigned(result);return true; +} +struct PortStat {const char* key;unsigned point;}; +static const PortStat kPortStats[]={ + {"level",POINT_LEVEL},{"hp",POINT_HP},{"maxhp",POINT_MAX_HP},{"sp",POINT_SP},{"maxsp",POINT_MAX_SP}, + {"attack",POINT_ATT_GRADE},{"defense",POINT_DEF_GRADE},{"magic_attack",POINT_MAGIC_ATT_GRADE},{"magic_defense",POINT_MAGIC_DEF_GRADE}, + {"attack_speed",POINT_ATT_SPEED},{"cast_speed",POINT_CASTING_SPEED},{"move_speed",POINT_MOV_SPEED}, + {"monster",POINT_ATTBONUS_MONSTER},{"stone",POINT_ATTBONUS_STONE},{"boss",POINT_ATTBONUS_BOSS},{"human",POINT_ATTBONUS_HUMAN}, + {"animal",POINT_ATTBONUS_ANIMAL},{"orc",POINT_ATTBONUS_ORC},{"milgyo",POINT_ATTBONUS_MILGYO},{"undead",POINT_ATTBONUS_UNDEAD},{"devil",POINT_ATTBONUS_DEVIL}, + {"warrior",POINT_ATTBONUS_WARRIOR},{"assassin",POINT_ATTBONUS_ASSASSIN},{"sura",POINT_ATTBONUS_SURA},{"shaman",POINT_ATTBONUS_SHAMAN}, + {"critical",POINT_CRITICAL_PCT},{"penetrate",POINT_PENETRATE_PCT},{"poison",POINT_POISON_PCT},{"stun",POINT_STUN_PCT},{"slow",POINT_SLOW_PCT}, + {"block",POINT_BLOCK},{"dodge",POINT_DODGE},{"resist_human",POINT_RESIST_HUMAN}, + {"resist_warrior",POINT_RESIST_WARRIOR},{"resist_assassin",POINT_RESIST_ASSASSIN},{"resist_sura",POINT_RESIST_SURA},{"resist_shaman",POINT_RESIST_SHAMAN}, + {"sword",POINT_RESIST_SWORD},{"twohand",POINT_RESIST_TWOHAND},{"dagger",POINT_RESIST_DAGGER},{"bell",POINT_RESIST_BELL},{"fan",POINT_RESIST_FAN},{"bow",POINT_RESIST_BOW}, + {"magic",POINT_RESIST_MAGIC},{"fire",POINT_RESIST_FIRE},{"electric",POINT_RESIST_ELEC},{"wind",POINT_RESIST_WIND},{"poison_reduce",POINT_POISON_REDUCE}, + {"hp_regen",POINT_HP_REGEN},{"sp_regen",POINT_SP_REGEN},{"steal_hp",POINT_STEAL_HP},{"steal_sp",POINT_STEAL_SP}, + {"exp_bonus",POINT_EXP_DOUBLE_BONUS},{"gold_bonus",POINT_GOLD_DOUBLE_BONUS},{"item_bonus",POINT_ITEM_DROP_BONUS}, + {"skill_damage",POINT_SKILL_DAMAGE_BONUS},{"normal_damage",POINT_NORMAL_HIT_DAMAGE_BONUS}, + {"skill_defense",POINT_SKILL_DEFEND_BONUS},{"normal_defense",POINT_NORMAL_HIT_DEFEND_BONUS}, + {"anti_critical",POINT_RESIST_CRITICAL},{"anti_penetrate",POINT_RESIST_PENETRATE}, + {"melee_magic",POINT_MELEE_MAGIC_ATT_BONUS_PER} +}; +ACMD(do_port_features) { + if(!ch || !ch->IsPC() || !ch->GetDesc())return; + std::istringstream input(argument);std::vector args;std::string token; + while(input>>token) {if(token.size()>32 || args.size()>=5)return;args.push_back(token);} + unsigned request=0,subject=0,offset=0; + if(args.size()<3 || args[0]!="1" || !PortFeatureNumber(args[1],request) || !request || request>2147483647)return; + const std::string& kind=args[2]; + if (get_dword_time()-ch->m_portFeatureLastQuery<250 && ch->m_portFeatureLastQuery) { + 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=="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()); + for(unsigned i=0;iGetHP():point==POINT_MAX_HP?ch->GetMaxHP(): + point==POINT_SP?ch->GetSP():point==POINT_MAX_SP?ch->GetMaxSP():point==POINT_LEVEL?ch->GetLevel():ch->GetPoint(point); + ch->ChatPacket(CHAT_TYPE_COMMAND,"MTF1 stat %u %u %s %lld",request,i,kPortStats[i].key,value); + } + ch->ChatPacket(CHAT_TYPE_COMMAND,"MTF1 end %u %u",request,unsigned(sizeof(kPortStats)/sizeof(kPortStats[0])));return; + } + if(args.size()!=5 || !PortFeatureNumber(args[3],subject) || !subject || !PortFeatureNumber(args[4],offset) || offset>4096) { + ch->ChatPacket(CHAT_TYPE_COMMAND,"MTF1 error %u invalid",request);return; + } + if(kind=="calendar" && subject==1) {PortCalendarQuery(ch,request,offset);return;} + std::vector rows; + unsigned mode=0; + auto& manager=ITEM_MANAGER::instance(); + if(kind=="mob") { + const CMob* mob=CMobManager::instance().Get(subject); + if(!mob || (mob->m_table.bType!=CHAR_TYPE_MONSTER && mob->m_table.bType!=CHAR_TYPE_STONE)) { + ch->ChatPacket(CHAT_TYPE_COMMAND,"MTF1 error %u missing",request);return; + } + rows=manager.PortWikiDrops(subject); + } + else if(kind=="chest") { + rows=manager.PortWikiChest(subject); + if(rows.empty()){ch->ChatPacket(CHAT_TYPE_COMMAND,"MTF1 error %u unsupported_chest",request);return;} + mode=rows[0].rule; + } + else if(kind=="sources") { + if(!manager.GetTable(subject)){ch->ChatPacket(CHAT_TYPE_COMMAND,"MTF1 error %u missing",request);return;} + for(auto it=CMobManager::instance().begin();it!=CMobManager::instance().end();++it) + for(auto row:manager.PortWikiDrops(it->first)) + if(row.item==subject){row.item=it->first;rows.push_back(row);} + // Chest entries are tagged with mode 20/21 so the client distinguishes them from monsters. + for(const auto& table:manager.GetTable()) + if(table.bType==ITEM_GIFTBOX || table.bType==ITEM_TREASURE_BOX) + for(auto row:manager.PortWikiChest(table.dwVnum)) + if(row.item==subject && row.item>CSpecialItemGroup::MOB_GROUP){row.item=table.dwVnum;row.rule+=10;rows.push_back(row);} + } + else {ch->ChatPacket(CHAT_TYPE_COMMAND,"MTF1 error %u unsupported",request);return;} + if(rows.size()>4096){ch->ChatPacket(CHAT_TYPE_COMMAND,"MTF1 error %u too_many",request);return;} + if(offset>rows.size()){ch->ChatPacket(CHAT_TYPE_COMMAND,"MTF1 error %u offset",request);return;} + ch->ChatPacket(CHAT_TYPE_COMMAND,"MTF1 begin %u %s %u %u %u %u %lld",request,kind.c_str(),subject,offset,unsigned(rows.size()),mode,(long long)get_global_time()); + unsigned sent=0; + for(unsigned i=offset;iChatPacket(CHAT_TYPE_COMMAND,"MTF1 row %u %u %u %u %u %u %u %u %u %u",request,i,r.item,r.count,r.rule,r.minimum,r.maximum,r.weight,r.total,r.rare); + } + ch->ChatPacket(CHAT_TYPE_COMMAND,"MTF1 end %u %u",request,sent); +} +#endif diff --git a/src/server/game/src/port_wiki_queries.inc b/src/server/game/src/port_wiki_queries.inc new file mode 100644 index 00000000..c47e14cb --- /dev/null +++ b/src/server/game/src/port_wiki_queries.inc @@ -0,0 +1,51 @@ +// PORT read-only views of the exact loaded tables used by CreateDropItem. +// No RNG, CreateItem, quest execution or state mutation is permitted here. +std::vector ITEM_MANAGER::PortWikiDrops(DWORD race) { + std::vector out; + const CMob* mob=CMobManager::instance().Get(race); + if (!mob || (mob->m_table.bType!=CHAR_TYPE_MONSTER && mob->m_table.bType!=CHAR_TYPE_STONE)) return out; + auto add=[&](unsigned id,unsigned count,unsigned rule,unsigned low,unsigned high,unsigned weight,unsigned total,unsigned rare=0) { + TItemTable* table=GetTable(id); + if (!table || !count || !weight) return; + if (rule==WIKI_COMMON && table->bType==ITEM_POLYMORPH && mob->m_table.dwPolymorphItemVnum!=id) return; + out.push_back({id,count,rule,low,high,weight,total,rare}); + }; + if (mob->m_table.bRankm_table.bRank]) + add(row.m_dwVnum,1,WIKI_COMMON,row.m_iLevelStart,row.m_iLevelEnd,row.m_iPercent,0); + auto drop=m_map_pkDropItemGroup.find(race); + if (drop!=m_map_pkDropItemGroup.end() && drop->second) + for (const auto& row:drop->second->GetVector()) add(row.dwVnum,row.iCount,WIKI_DROP,0,0,row.dwPct,0); + auto kill=m_map_pkMobItemGroup.find(race); + if (kill!=m_map_pkMobItemGroup.end() && kill->second && !kill->second->IsEmpty()) { + const auto& rows=kill->second->PortWikiItems();const auto& probs=kill->second->PortWikiWeights(); + for (size_t i=0;isecond->GetKillPerDrop(),0, + probs[i]-(i?probs[i-1]:0),probs.back(),rows[i].iRarePct); + } + auto level=m_map_pkLevelItemGroup.find(race); + if (level!=m_map_pkLevelItemGroup.end() && level->second) + for (const auto& row:level->second->GetVector()) add(row.dwVNum,row.iCount,WIKI_LEVEL,level->second->GetLevelLimit(),0,row.dwPct,1000000); + auto glove=m_map_pkGloveItemGroup.find(race); + if (glove!=m_map_pkGloveItemGroup.end() && glove->second) + for (const auto& row:glove->second->GetVector()) add(row.dwVnum,row.iCount,WIKI_GLOVE,0,0,row.dwPct,0); + auto etc=m_map_dwEtcItemDropProb.find(mob->m_table.dwDropItemVnum); + if (etc!=m_map_dwEtcItemDropProb.end()) add(etc->first,1,WIKI_ETC,0,0,etc->second,0); + return out; +} + +std::vector ITEM_MANAGER::PortWikiChest(DWORD vnum) { + std::vector out; + const TItemTable* item=GetTable(vnum); + if (!item || (item->bType!=ITEM_GIFTBOX && item->bType!=ITEM_TREASURE_BOX)) return out; + const CSpecialItemGroup* group=GetSpecialItemGroup(vnum); + if (!group || group->IsEmpty() || (group->m_bType!=CSpecialItemGroup::NORMAL && group->m_bType!=CSpecialItemGroup::PCT)) return out; + const auto& rows=group->m_vecItems;const auto& probs=group->m_vecProbs; + for (size_t i=0;im_bType==CSpecialItemGroup::PCT?WIKI_INDEPENDENT:WIKI_SINGLE, + 0,0,unsigned(weight),group->m_bType==CSpecialItemGroup::PCT?100u:unsigned(probs.back()),unsigned(rows[i].rare)}); + } + return out; +} diff --git a/tests/features/dungeon_lua_probe.cpp b/tests/features/dungeon_lua_probe.cpp new file mode 100644 index 00000000..303fad57 --- /dev/null +++ b/tests/features/dungeon_lua_probe.cpp @@ -0,0 +1,72 @@ +// Run on FreeBSD against the project's real Lua 5.0 library and installed compiled quest states. +// No game process, DB, network or live state is modified. +#include +#include +#include +#include +#include +#include +extern "C" { +#include "lua.h" +#include "lauxlib.h" +} +#define __QUEST_PC_H +#define CHAT_TYPE_COMMAND 5 +namespace quest { +struct PC { + bool loaded=true,running=false;std::map flags; + bool IsLoaded(){return loaded;}bool IsRunning(){return running;} + int GetFlag(const std::string& key){return flags[key];} +}; +struct CQuestManager { + lua_State* L=nullptr;PC pc;std::map events;int currentPlayer=98765; + static CQuestManager& instance(){static CQuestManager q;return q;} + lua_State* GetLuaState(){return L;} + PC* GetPCForce(unsigned id){assert(id==123);return &pc;} + int GetEventFlag(const std::string& name){return events[name];} + unsigned GetQuestIndexByName(const std::string&){return 1;} + int GetQuestStateIndex(const std::string&,const std::string&){ + const int top=lua_gettop(L);lua_getglobal(L,"dragon_lair_weekly");lua_pushstring(L,"hunt_item");lua_rawget(L,-2); + int result=int(lua_tonumber(L,-1));lua_settop(L,top);return result; + } +}; +} +struct ITEM_MANAGER { + static ITEM_MANAGER& instance(){static ITEM_MANAGER m;return m;} + void* GetTable(unsigned vnum){return vnum==30179?this:nullptr;} +}; +static long long now=1700000000;static long long get_global_time(){return now;} +struct Character { + std::vector messages; + unsigned GetPlayerID(){return 123;}int CountSpecifyItem(unsigned){return 7;} + void ChatPacket(int,const char* format,...) { + char out[1024];va_list args;va_start(args,format);vsnprintf(out,sizeof(out),format,args);va_end(args);messages.emplace_back(out); + } +}; +using LPCHARACTER=Character*; +#include "port_dungeons.h" +static int eventFlag(lua_State* L) { + lua_pushnumber(L,quest::CQuestManager::instance().GetEventFlag(lua_tostring(L,1)));return 1; +} +static bool contains(const Character& c,const char* text){for(auto& s:c.messages)if(s.find(text)!=std::string::npos)return true;return false;} +int main(int argc,char** argv){ + assert(argc==3);auto& q=quest::CQuestManager::instance();q.L=lua_open();assert(q.L); + lua_newtable(q.L);lua_pushstring(q.L,"get_event_flag");lua_pushcfunction(q.L,eventFlag);lua_rawset(q.L,-3);lua_setglobal(q.L,"game"); + assert(luaL_loadfile(q.L,argv[1])==0 && lua_pcall(q.L,0,0,0)==0); + assert(luaL_loadfile(q.L,argv[2])==0 && lua_pcall(q.L,0,0,0)==0); + q.events["dragon_lair_time"]=now-100;q.events["dragon_lair_alive"]=1; + q.pc.flags["dragon_lair_weekly.lasttime"]=now-1000; + q.pc.flags["dragon_lair_weekly.__status"]=q.GetQuestStateIndex("dragon_lair_weekly","hunt_item"); + Character ch;const int top=lua_gettop(q.L);PortDungeonQuery(&ch,1); + assert(contains(ch,"lair_tickets 3") && contains(ch,"lair_phase 1") && contains(ch,"weekly_active 1")); + assert(contains(ch,"weekly_end 1700560600") && contains(ch,"lair_owned 7")); + assert(q.currentPlayer==98765 && lua_gettop(q.L)==top); + q.events["dragon_lair_amount"]=-1;ch.messages.clear();PortDungeonQuery(&ch,2);assert(contains(ch,"lair_tickets 0")); + q.events["dragon_lair_amount"]=5;ch.messages.clear();PortDungeonQuery(&ch,3);assert(contains(ch,"lair_tickets 5")); + now+=3500;ch.messages.clear();PortDungeonQuery(&ch,4);assert(contains(ch,"lair_phase 2")); + ++now;ch.messages.clear();PortDungeonQuery(&ch,5);assert(contains(ch,"lair_phase 0")); + q.pc.running=true;ch.messages.clear();PortDungeonQuery(&ch,6);assert(ch.messages.back()=="MTF1 error 6 busy");q.pc.running=false; + lua_pushnil(q.L);lua_setglobal(q.L,"dragon_lair_access");ch.messages.clear();PortDungeonQuery(&ch,7);assert(ch.messages.back()=="MTF1 error 7 unsupported"); + assert(lua_gettop(q.L)==top && q.currentPlayer==98765); + lua_close(q.L);puts("PASS: installed quest settings in real Lua 5.0; shared/personal deadlines, ticket overrides, boundaries, stack/context, busy/missing"); +} diff --git a/tests/features/test_calendar.py b/tests/features/test_calendar.py new file mode 100644 index 00000000..4cdd9214 --- /dev/null +++ b/tests/features/test_calendar.py @@ -0,0 +1,72 @@ +#!/usr/bin/env python3 +"""Exercise production interval/parser bodies, including restarts, scopes and atomic reload.""" +from pathlib import Path +import subprocess +import tempfile +SRC=Path(__file__).resolve().parents[2]/'src/server/game/src' +CODE=r''' +#include +#include +#include +#include "port_calendar.h" +#define CHAT_TYPE_COMMAND 5 +static unsigned tick=20000;static long long now=150;static unsigned char g_bChannel=2; +static std::string base; +const std::string& LocaleService_GetBasePath(){return base;} +static unsigned get_dword_time(){return tick;} +static long long get_global_time(){return now;} +struct Character { + unsigned empire=3;std::vector messages; + unsigned GetEmpire(){return empire;} + void ChatPacket(int,const char* format,...) { + char out[1024];va_list args;va_start(args,format);vsnprintf(out,sizeof(out),format,args);va_end(args);messages.emplace_back(out); + } +}; +using LPCHARACTER=Character*; +#include "port_calendar_runtime.h" +static bool load(PortCalendar& c,const char* text){std::istringstream in(text);return c.Parse(in);} +int main(int argc,char** argv){ + assert(argc==2);PortCalendar c; + assert(load(c,"MTCALENDAR 1\n2 1 100 200 0 0\n1 2 100 200 2 3\n3 1 150 250 0 0\n")); + assert(c.events[0].id==1 && !c.Active(1,99,1,1) && c.Active(1,100,1,1)); + assert(c.Active(1,200,1,1) && !c.Active(1,250,1,1)); // overlapping intervals do not multiply + assert(c.Active(2,199,2,3) && !c.Active(2,200,2,3)); + assert(!c.Active(2,150,1,3) && !c.Active(2,150,2,1)); + for(const auto* bad:{"", "MTCALENDAR 2\n", "MTCALENDAR 1\n1 3 1 2 0 0\n", "MTCALENDAR 1\n1 1 2 2 0 0\n", + "MTCALENDAR 1\n1 1 1 2 0 0\n1 2 2 3 0 0\n", "MTCALENDAR 1\n1 1 -1 2 0 0\n", "MTCALENDAR 1\n1 1 1 4294967296 0 0\n"}) { + assert(!load(c,bad));assert(!c.valid && c.events.empty() && !c.Active(1,150,1,1)); + } + const std::string path=argv[1],next=path+".next"; + {std::ofstream f(path);f<<"MTCALENDAR 1\n1 1 100 200 0 0\n";} + c.Refresh(path,100);assert(c.Active(1,150,1,1)); + {std::ofstream f(next);f<<"MTCALENDAR 1\n1 2 100 200 0 0\n";} + assert(rename(next.c_str(),path.c_str())==0); + c.Refresh(path,200);assert(c.Active(1,150,1,1)); // explicit reload bound + c.Refresh(path,5100);assert(!c.Active(1,150,1,1) && c.Active(2,150,1,1)); + PortCalendar restarted;restarted.Refresh(path,1);assert(restarted.Active(2,150,1,1)); + {std::ofstream f(next);f<<"broken";}assert(rename(next.c_str(),path.c_str())==0); + c.Refresh(path,10100);assert(!c.valid && c.events.empty()); + remove(path.c_str());c.Refresh(path,15100);assert(!c.valid); + assert(load(c,"MTCALENDAR 1\n") && c.events.empty()); + base=path.substr(0,path.find_last_of('/')); + {std::ofstream f(path);f<<"MTCALENDAR 1\n1 1 100 200 2 3\n2 2 100 200 1 1\n";} + Character ch;PortCalendarQuery(&ch,1,0); + assert(ch.messages.front()=="MTF1 begin 1 calendar 1 0 2 0 150"); + assert(ch.messages[1]=="MTF1 event 1 0 1 1 100 200 2 3 1"); + assert(ch.messages[2]=="MTF1 event 1 1 2 2 100 200 1 1 0"); + assert(PortScheduledDrop(1,&ch) && !PortScheduledDrop(2,&ch)); + now=200;assert(!PortScheduledDrop(1,&ch)); + PortCalendarQuery(&ch,2,999);assert(ch.messages.back()=="MTF1 error 2 offset"); + remove(path.c_str());tick+=5000;PortCalendarQuery(&ch,3,0); + assert(ch.messages.back()=="MTF1 error 3 schedule_unavailable" && !PortScheduledDrop(1,&ch)); + puts("PASS: schedule parsing, UTC interval edges, scope, overlaps, restart, atomic reload, invalid/missing fail closed"); +} +''' +with tempfile.TemporaryDirectory(prefix='mt-calendar-') as folder: + p=Path(folder);(p/'test.cpp').write_text(CODE) + subprocess.run(['c++','-std=c++17','-I'+str(SRC),str(p/'test.cpp'),'-o',str(p/'test')],check=True) + subprocess.run([str(p/'test'),str(p/'port_events.tsv')],check=True) +# Both real quest-drop branches use this gate, retaining the original probability/eligibility code. +source=(SRC/'item_manager.cpp').read_bytes() +assert b'GetEventFlag("drop_moon") || PortScheduledDrop(1,pkKiller)' in source +assert b'GetEventFlag("xmas_sock") || PortScheduledDrop(2,pkKiller)' in source diff --git a/tests/features/test_queries.py b/tests/features/test_queries.py new file mode 100644 index 00000000..82eacf9a --- /dev/null +++ b/tests/features/test_queries.py @@ -0,0 +1,132 @@ +#!/usr/bin/env python3 +"""Compile the production query/protocol bodies against original group classes and deterministic fixtures.""" +from pathlib import Path +import re +import subprocess +import tempfile +ROOT=Path(__file__).resolve().parents[2] +SRC=ROOT/'src/server/game/src' +header=(SRC/'item_manager.h').read_bytes().decode('latin1') +groups=header[header.index('class CSpecialAttrGroup'):header.index('class ITEM;')] +points=sorted(set(re.findall(r'\bPOINT_[A-Z_]+', (SRC/'port_features.h').read_text()))) +code=r''' +#include +#include +#include +#include +#include +#include +#include +using namespace std; +using DWORD=unsigned;using BYTE=unsigned char; +#define itertype(v) decltype((v).begin()) +static int rng=0;int number(int,int){++rng;return 1;} +enum {ITEM_POLYMORPH=19,ITEM_GIFTBOX=23,ITEM_TREASURE_BOX=20,CHAR_TYPE_MONSTER=0,CHAR_TYPE_STONE=2,MOB_RANK_MAX_NUM=6,ITEM_NAME_MAX_LEN=24}; +POINTS +GROUPS +#include "port_feature_types.h" +#include "item_manager_private_types.h" +std::vector g_vec_pkCommonDropItem[MOB_RANK_MAX_NUM]; +struct TItemTable{unsigned dwVnum;unsigned bType=0;}; +struct MobTable{unsigned bType=0,bRank=0,dwPolymorphItemVnum=0,dwDropItemVnum=0;}; +struct CMob{MobTable m_table;}; +class CMobManager { + public:std::map mobs; + static CMobManager& instance(){static CMobManager m;return m;} + const CMob* Get(unsigned id){auto it=mobs.find(id);return it==mobs.end()?nullptr:it->second;} + auto begin(){return mobs.begin();}auto end(){return mobs.end();} +}; +class ITEM_MANAGER { + public: + std::vector tables; + std::map m_map_pkDropItemGroup; + std::map m_map_pkMobItemGroup; + std::map m_map_pkLevelItemGroup; + std::map m_map_pkGloveItemGroup; + std::map m_map_dwEtcItemDropProb; + std::map special; + static ITEM_MANAGER& instance(){static ITEM_MANAGER m;return m;} + TItemTable* GetTable(unsigned id){for(auto& t:tables)if(t.dwVnum==id)return &t;return nullptr;} + const std::vector& GetTable(){return tables;} + const CSpecialItemGroup* GetSpecialItemGroup(unsigned id){auto it=special.find(id);return it==special.end()?nullptr:it->second;} + std::vector PortWikiDrops(DWORD race); + std::vector PortWikiChest(DWORD id); +}; +#include "port_wiki_queries.inc" +static DWORD clockms=1000;unsigned get_dword_time(){return clockms;}long long get_global_time(){return 1700000000;} +struct Character { + unsigned m_portFeatureLastQuery=0;bool pc=true;std::vector messages;std::map points; + bool IsPC(){return pc;}void* GetDesc(){return this;} + int GetPoint(unsigned point){return points[point];} + int GetHP(){return 123;}int GetMaxHP(){return 500;}int GetSP(){return 42;}int GetMaxSP(){return 100;}int GetLevel(){return 30;} + void ChatPacket(int,const char* format,...) { + char out[1024];va_list args;va_start(args,format);vsnprintf(out,sizeof(out),format,args);va_end(args); + assert(strlen(out)<512);messages.emplace_back(out); + } +}; +using LPCHARACTER=Character*; +#define CHAT_TYPE_COMMAND 5 +#define ACMD(name) void name(LPCHARACTER ch,const char* argument) +#include +static void PortCalendarQuery(LPCHARACTER,unsigned,unsigned){} +static bool PortDungeonQuery(LPCHARACTER,unsigned){return true;} +#include "port_features.h" +#include "port_dungeon_rules.h" +static void query(Character& ch,const char* text){clockms+=300;do_port_features(&ch,text);} +int main(){ + assert(PortLair(100,3600,300,400).phase==1); // inclusive join boundary + assert(PortLair(100,3600,300,401).phase==2); + assert(PortLair(100,3600,300,3700).phase==2); // original strict-negative availability + assert(PortLair(100,3600,300,3701).phase==0); + assert(PortLair(0,3600,300,1700000000).phase==0); + auto& items=ITEM_MANAGER::instance();auto& mobs=CMobManager::instance(); + items.tables={{19,0},{30006,0},{30220,0},{50011,23},{50012,23},{50013,23},{70104,19}}; + CMob mob;mob.m_table.dwDropItemVnum=30220;mobs.mobs[101]=&mob; + CMob npc;npc.m_table.bType=1;mobs.mobs[9001]=&npc; + g_vec_pkCommonDropItem[0].emplace_back(1,30,50,19); + g_vec_pkCommonDropItem[0].emplace_back(1,30,50,70104); // Wrong polymorph mob must be excluded. + CDropItemGroup drop(0,101,"fixture");drop.AddItem(30006,100,2);items.m_map_pkDropItemGroup[101]=&drop; + CMobItemGroup kill(101,50,"fixture");kill.AddItem(19,1,20,0);kill.AddItem(30006,3,80,5);items.m_map_pkMobItemGroup[101]=&kill; + CLevelItemGroup level(20);level.AddItem(30220,10,1);items.m_map_pkLevelItemGroup[101]=&level; + CBuyerThiefGlovesItemGroup glove(0,101,"fixture");glove.AddItem(19,25,1);items.m_map_pkGloveItemGroup[101]=&glove; + items.m_map_dwEtcItemDropProb[30220]=40; + auto rows=items.PortWikiDrops(101);assert(rows.size()==7); + assert(rows[0].rule==WIKI_COMMON && rows[0].minimum==1 && rows[0].maximum==30); + assert(rows[1].item==30006 && rows[1].count==2); + assert(rows[2].weight==20 && rows[3].weight==80 && rows[3].total==100 && rows[3].rare==5); + assert(rows[4].rule==WIKI_LEVEL && rows[4].minimum==20); + assert(rows[5].rule==WIKI_GLOVE && rows[6].rule==WIKI_ETC); + assert(items.PortWikiDrops(9001).empty() && items.PortWikiDrops(99999).empty()); + drop.AddItem(30220,25,1);assert(items.PortWikiDrops(101).size()==8); + drop.AddItem(70104,1,1);assert(items.PortWikiDrops(101).size()==9); // Non-common groups retain configured polymorph candidates. // Sees active changes, not exported text. + CSpecialItemGroup chest(50011);chest.AddItem(19,1,80,0);chest.AddItem(1,500,20,0);items.special[50011]=&chest; + CSpecialItemGroup multi(50012,CSpecialItemGroup::PCT);multi.AddItem(19,2,20,0);multi.AddItem(3,101,150,0);items.special[50012]=&multi; + CSpecialItemGroup attr(50013,CSpecialItemGroup::SPECIAL);attr.AddItem(19,1,100,0);items.special[50013]=&attr; + auto rewards=items.PortWikiChest(50011);assert(rewards.size()==2 && rewards[0].weight==80 && rewards[1].weight==20 && rewards[1].item==1 && rewards[1].count==500); + 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"); + 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"); + query(ch,"1 5 chest 50013 0");assert(ch.messages.back()=="MTF1 error 5 unsupported_chest"); + query(ch,"1 6 sources 30006 0");assert(ch.messages.back()=="MTF1 end 6 2"); + ch.messages.clear();ch.points[POINT_ATTBONUS_STONE]=10;query(ch,"1 7 stats"); + bool stone=false,hp=false;for(auto& line:ch.messages){stone|=line.find(" stone 10")!=std::string::npos;hp|=line.find(" hp 123")!=std::string::npos;} + assert(stone && hp && ch.messages.size()==sizeof(kPortStats)/sizeof(kPortStats[0])+2); + do_port_features(&ch,"1 8 stats");assert(ch.messages.back()=="MTF1 error 8 rate"); + for(auto bad:{"2 9 stats","1 0 cap","1 -1 cap","1 4294967296 cap","1 10 cap too many extra"}) { + auto size=ch.messages.size();query(ch,bad);assert(ch.messages.size()==size); + } + assert(rng==0); // Neither previews nor reverse lookup advance gameplay RNG. + puts("PASS: actual query/protocol bodies; active groups, conditions, weights, special rewards, stats, pagination, validation; RNG untouched"); +} +''' +# cstring is required by the stub logger, before its declaration. +code=code.replace('#include ','#include \n#include ') +code=code.replace('POINTS','enum {'+', '.join([points[0]+'=1']+points[1:])+'};').replace('GROUPS',groups) +with tempfile.TemporaryDirectory(prefix='mt-feature-query-') as folder: + path=Path(folder);(path/'test.cpp').write_text(code) + subprocess.run(['c++','-std=c++17','-I'+str(SRC),str(path/'test.cpp'),'-o',str(path/'test')],check=True) + subprocess.run([str(path/'test')],check=True) diff --git a/tools/calendar/port_events.tsv.example b/tools/calendar/port_events.tsv.example new file mode 100644 index 00000000..2bfe8d5b --- /dev/null +++ b/tools/calendar/port_events.tsv.example @@ -0,0 +1,6 @@ +# Copy to locale base/port_events.tsv to enable a schedule. Empty schedule has no effects. +# Replace atomically. Every core refreshes within 5s; use common shared locale storage. +# All times are Unix seconds in UTC. Start inclusive, end exclusive. +# Columns: unique_id kind start end channel empire (0 = all channels/empires). +# Supported kind: 1 moonlight-box drop, 2 Christmas-sock drop, using existing drop rules. +MTCALENDAR 1