diff --git a/docs/FEATURE-MATERIAL-STACK-2000.md b/docs/FEATURE-MATERIAL-STACK-2000.md new file mode 100644 index 00000000..0eb7a01d --- /dev/null +++ b/docs/FEATURE-MATERIAL-STACK-2000.md @@ -0,0 +1,56 @@ +# 材料与消耗品 2000 叠放:实现与验收 + +更新时间:2026-10-27。协议 `mt20261030`。已完成双端开发、打包、CH5隔离验收及203正式部署,正式登录已开放。新旧协议不能混用,用户必须升级客户端。 + +## 规则与协议 + +`port_material_stack_policy.h` 已接入运行时。允许叠放且没有禁止叠放标记的 USE、AUTOUSE、MATERIAL、METIN、RESOURCE、BLEND、EXTRACT,以及实际加载的强化/Cube 配方材料,上限为2000;其他物品保留200。禁止叠放优先,非叠放奖励逐件创建,不修改 proto 标记。生产配置审查清单含854个物品编号,部署机保存 `material-catalogue-production.json`。 + +物品数量线路使用 uint16,内部数量及 item 存档使用32位;金币和累计奖励计算保持宽类型。槽位、商品条目数等字段未扩大。背包、仓库、商城仓库、交易、NPC/玩家商店及装备观察结构已经同步;离线商店原有数量为32位,保留该宽度。 + +合堆校验原始编号、动态标记、插槽、属性、完整69字节扩展状态及持久化属性锁;锁定或交易中物品拒绝合堆。拆分/丢弃/仓库拆分先完成新物品创建和元数据复制,失败时不扣源数量。属性锁读取失败时拒绝合堆或拆分。 + +客户端在登录游戏核心和选择角色前发送版本,服务端在登录/选角/物品加载前拒绝旧版或缺失版本,状态为 VERSION;新版登录页显示升级提示。四位拆分/出售输入与实际物品数量对应。 + +## 已通过的隔离验收 + +- 199/200/201/255/256/1999/2000 边界;满组拒绝、拆分1000、重新合并、丢弃256、2001非法输入。 +- 同时运行两个真实客户端,1744材料交易并退回,核对数量;交易后材料按既有规则进入强化材料专用背包。 +- 普通仓库2000/1744存取、部分拆分与合并、满组拒绝;商城仓库2000取回。 +- NPC商店购买一组2000,分两次出售256及1744;奖励4001按组发放,不截断。 +- 属性追加2000→1999,转属性2000→1999,自动洗练继续准确扣除并停止。 +- Cube配方从单组2000扣除512成功批量制作,再扣除256进行零成功配方,余量1232,产出仅为成功的2件。 +- game/db重启后数量一致;宽存档回退模式保留整组2000移动,限制新增长200,拆分失败不损失数量。 +- Mac Android模拟器实际登录,读取2000和256,拆分为两组1000再合并为2000;最终macOS .app真实登录读取2000及256并完成渲染。 +- 43项Cube回归、14项商店回归、材料规则与实际合堆/拆分元数据检查。旧测试桩的8位数量和过时接口已同步修正;测试边界替身不等于全部正式流程已联机验收。 + +## 上线与回退 + +`tools/material-stack/migrate.py` 迁移 item、item_orphan_quarantine、shop_item 数量列为 INT UNSIGNED,保持默认值/非空及索引,并比较行数、数量总和及包含全部字段的数据指纹。重复执行不缩窄或重写物品。item_award 已是32位。 + +`cluster.py` 按实际 DB_PORT 枚举进程和二进制,维护停服后备份数据库/配置/现役二进制,成套更新 game/db,先以验收账号白名单启动。生产CH1—CH4、auth、game99使用DB15000;CH5及测试auth使用隔离DB15040,不能只按频道编号判断部署范围。候选game/db必须配套重建libsql,不能沿用可能存在ABI不一致的预编译库。 + +上线后已有超过200的物品时,严禁回到旧二进制或缩窄数据库。`cluster.py fallback` 使用同一宽协议候选并设置 `PORT_MATERIAL_STACK_LEGACY_MODE=1`,只停止新增长,保留存量的读取、移动和扣除。 + +## 正式上线记录 + +- 正式14个game/auth核心与db成套更新;CH5隔离服两个活动核心与独立db同步更新。另一个未运行的隔离crosscore路径也指向新版;共19个配置二进制路径逐一核对SHA256。 +- 正式三个数量列完成迁移;item表245行/5300件、隔离清理表1行/1件、shop_item表325行/2912件,迁移前后相同,完整数据指纹相同。重复执行迁移验证通过。 +- 新建专用验收账号,正式背包合并/拆分、洗练扣除、仓库存取、game/db重启、CH1→CH2→CH1往返通过。旧原生客户端在角色加载前明确收到VERSION。 +- 正式原有245件物品逐ID核对,归属、位置、编号和数量全部不变;验收道具单独属于新建账号。 +- Mac上的Android模拟器安装最终APK后连接正式服:2000→1000+1000→2000,前后完整抽样数量一致。最终macOS.app在真实服务端读取2000和256并完成渲染;签名完整性检查通过。 +- 追加的满背包验收通过:Cube拒绝时材料和产出不变(本轮未逐笔核对金币);批量开箱拒绝时不扣宝箱;2001奖励落地后腾出空间拾取,总数2001;腾出空间后两箱产生4000道具,每组不超过2000。 +- 强化从专用背包的2000材料组准确扣1。修复了旧强化只查普通背包的问题,普通/卷轴强化共用先预检再扣除的材料流程;重复材料编号累计校验,材料不足或锁定时不部分扣除。 +- 批量开箱的客户端中文奖励提示已修复,最终实测4000奖励无编码异常。NPC商店2000买入/256与1744分次出售、玩家商店1744购买并交易退回、落地1000拾取合堆均通过。 +- 临时测试任务、配方覆盖、商店、满背包填充物已清理;正式和隔离集群的验收白名单已解除,保持新协议版本门槛。 + +部署与备份:203 `/root/deploy-features/20261026-stack2000/backup-production-20261027/`。发布进程、迁移结果、配置路径和校验结果保存为同目录上一级的 `release-opened-20261027.json`;私密账号文件不进入交付记录或Git。 + +服务端game SHA256:`3a89fa1e13c7f0fa0270bc30969438fe3103aa5ffdacb172b2f86fa71a387f20`。 +服务端db SHA256:`b23eb7e1de7fc94560848791c154b0f76301239386f8bf11fdcec9ab672c50e4`。 + +## 验收边界 + +离线商店原有 `PortOfflineShopEconomyReady()==false` 硬开关保持关闭,不能把未发生的离线购买记为联机通过。43项Cube、14项商店、10项宝箱界面回归和材料规则/元数据/强化扣料检查通过;替身边界和此前资源/Wiki回归失败不表示整个游戏完整回归全部通过。手工向旧item_award表写入超出单组上限的批量记录未作联机验收;本轮已验证正常2000仓库及4001游戏奖励的分组通路。 + +macOS包为本地ad-hoc签名,未做Developer ID公证。Android APK包含程序,资源沿用现有客户端。本轮最终APK在Mac模拟器完成正式服联机验收;手机中途断开,最后一次中文提示修复后的APK未能再次覆盖安装到真机,不能计为最终真机验收。 diff --git a/src/server/Makefile b/src/server/Makefile index d0697969..dbd10bc2 100755 --- a/src/server/Makefile +++ b/src/server/Makefile @@ -1,5 +1,5 @@ -CC=clang-devel -CXX=clang++-devel +CC ?= clang-devel +CXX ?= clang++-devel PLATFORM = $(shell file /bin/ls | cut -d' ' -f3 | cut -d'-' -f1) BSD_VERSION = $(shell uname -v 2>&1 | cut -d' ' -f2 | cut -d'.' -f1) @@ -11,19 +11,16 @@ default: libthecore libpoly libgame liblua libsql libserverkey game db libthecore: . @touch $@/src/Depend - $(MAKE) -C $@/src dep $(MAKE) -C $@/src clean $(MAKE) -C $@/src libpoly: . @touch $@/Depend - $(MAKE) -C $@ dep $(MAKE) -C $@ clean $(MAKE) -C $@ libgame: . @touch $@/src/Depend - $(MAKE) -C $@/src dep $(MAKE) -C $@/src clean $(MAKE) -C $@/src @@ -33,28 +30,23 @@ liblua: . libsql: . @touch $@/Depend - $(MAKE) -C $@ dep $(MAKE) -C $@ clean $(MAKE) -C $@ libserverkey: . @touch $@/Depend - $(MAKE) -C $@ dep $(MAKE) -C $@ clean $(MAKE) -C $@ game: . @touch $@/src/Depend - $(MAKE) -C $@/src dep $(MAKE) -C $@/src clean -# $(MAKE) -C $@/src limit_time -# $(MAKE) -C $@/src + $(MAKE) -C $@/src db: . @touch $@/src/Depend - $(MAKE) -C $@/src dep $(MAKE) -C $@/src clean -# $(MAKE) -C $@/src + $(MAKE) -C $@/src all: @echo "--------------------------------------" diff --git a/src/server/common/item_length.h b/src/server/common/item_length.h index 664fa542..92402c2d 100755 --- a/src/server/common/item_length.h +++ b/src/server/common/item_length.h @@ -9,7 +9,7 @@ enum EItemMisc ITEM_LIMIT_MAX_NUM = 2, ITEM_APPLY_MAX_NUM = 3, ITEM_SOCKET_MAX_NUM = 3, - ITEM_MAX_COUNT = 200, + ITEM_MAX_COUNT = 2000, ITEM_ATTRIBUTE_MAX_NUM = 7, ITEM_ATTRIBUTE_MAX_LEVEL = 5, ITEM_AWARD_WHY_MAX_LEN = 50, diff --git a/src/server/common/tables.h b/src/server/common/tables.h index ab52ca87..4d19fe92 100755 --- a/src/server/common/tables.h +++ b/src/server/common/tables.h @@ -632,20 +632,20 @@ typedef struct SSkillTable typedef struct SShopItemTable { DWORD vnum; - BYTE count; + WORD count; TItemPos pos; // PC 상점에만 이용 int64_t price; // PC, shop_table_ex.txt 상점에만 이용 BYTE display_pos; // PC, shop_table_ex.txt 상점에만 이용, 보일 위치. } TShopItemTable; -static_assert(sizeof(TShopItemTable)==17,"gold64 private shop wire size"); +static_assert(sizeof(TShopItemTable)==18,"gold64 private shop wire size"); typedef struct SShopTable { DWORD dwVnum; DWORD dwNPCVnum; - BYTE byItemCount; + WORD byItemCount; TShopItemTable items[SHOP_HOST_ITEM_MAX_NUM]; } TShopTable; diff --git a/src/server/common/utils.h b/src/server/common/utils.h index 6b5d48aa..0da47e0e 100755 --- a/src/server/common/utils.h +++ b/src/server/common/utils.h @@ -78,21 +78,30 @@ inline bool str_to_number (long long& out, const char *in) if(!in || !*in)return false; errno=0;char* end=NULL;const long long value=strtoll(in,&end,10); if(errno==ERANGE || end==in || *end)return false; - out=value;return true; + char* dst = reinterpret_cast(&out); + const char* src = reinterpret_cast(&value); + for (size_t i = 0; i < sizeof(long long); ++i) dst[i] = src[i]; + return true; } inline bool str_to_number (unsigned long long& out, const char *in) { if(!in || !*in || ((*in<'0'||*in>'9')&&*in!='+'))return false; errno=0;char* end=NULL;const unsigned long long value=strtoull(in,&end,10); if(errno==ERANGE || end==in || *end)return false; - out=value;return true; + char* dst = reinterpret_cast(&out); + const char* src = reinterpret_cast(&value); + for (size_t i = 0; i < sizeof(unsigned long long); ++i) dst[i] = src[i]; + return true; } inline bool str_to_number (float& out, const char *in) { if (0==in || 0==in[0]) return false; - out = (float) strtof(in, NULL); + float val = (float) strtof(in, NULL); + char* dst = reinterpret_cast(&out); + const char* src = reinterpret_cast(&val); + for (size_t i = 0; i < sizeof(float); ++i) dst[i] = src[i]; return true; } @@ -100,7 +109,10 @@ inline bool str_to_number (double& out, const char *in) { if (0==in || 0==in[0]) return false; - out = (double) strtod(in, NULL); + double val = (double) strtod(in, NULL); + char* dst = reinterpret_cast(&out); + const char* src = reinterpret_cast(&val); + for (size_t i = 0; i < sizeof(double); ++i) dst[i] = src[i]; return true; } diff --git a/src/server/db/src/Makefile b/src/server/db/src/Makefile index 7f96b257..d494c28a 100755 --- a/src/server/db/src/Makefile +++ b/src/server/db/src/Makefile @@ -1,28 +1,29 @@ -MAKE = gmake -CC = clang++-devel +MAKE = make +CC ?= clang++-devel INCDIR = LIBDIR = BINDIR = .. OBJDIR = .obj -DBDIR = /usr/metin2/server/share/bin +DBDIR ?= ../../share/bin -GCC_VERSION = $(shell $(CC) --version 2>&1 | grep "(GCC)" | cut -d' ' -f3 | cut -d'.' -f1) -BSD_VERSION = $(shell uname -v 2>&1 | cut -d' ' -f2 | cut -d'.' -f1) +UNAME_S := $(shell uname -s) SVN_VERSION = 40142 $(shell if [ ! -d $(OBJDIR) ]; then mkdir $(OBJDIR); fi) -# TARGET = $(BINDIR)/db_r$(SVN_VERSION) TARGET = $(BINDIR)/db -CFLAGS = -g -Wall -w -O2 -pipe -fno-rtti -std=c++2b -fno-exceptions -pthread -D_THREAD_SAFE -CFLAGS += -mtune=i686 - +ifeq ($(UNAME_S), Linux) +CFLAGS ?= -g -Wall -w -O2 -pipe -fno-rtti -std=c++2b -fno-exceptions -pthread -D_THREAD_SAFE +LIBS += -lmariadb -lz -lssl -lcrypto -ldl +INCDIR += -I/usr/include/mariadb -I/usr/include/mysql +else +CFLAGS ?= -g -Wall -w -O2 -pipe -fno-rtti -std=c++2b -fno-exceptions -pthread -D_THREAD_SAFE -mtune=i686 # MySQL LIBS += /usr/local/lib/mysql/libmysqlclient.a /usr/lib/libz.a - # OpenSSL LIBS += /usr/lib/libssl.a /usr/lib/libcrypto.a +endif # Miscellaneous external libraries INCDIR += -I../../../extern/include @@ -47,11 +48,10 @@ default: $(TARGET) $(TARGET): $(OBJS) @echo linking $(TARGET).... - @$(CC) $(CFLAGS) $(LIBDIR) $(OBJS) $(LIBS) -o $(TARGET) + $(CC) $(CFLAGS) $(LIBDIR) $(OBJS) $(LIBS) -o $(TARGET) @touch version.cpp - @echo "Moving $(TARGET) to $(DBDIR)" - @mv $(TARGET) $(DBDIR) - @echo "All done! Your db file moved to your server directory." + @if [ -d "$(DBDIR)" ]; then cp $(TARGET) $(DBDIR)/; echo "Copied $(TARGET) to $(DBDIR)"; fi + @echo "All done!" $(OBJDIR)/%.o: %.cpp @echo compile $< diff --git a/src/server/db/src/stdafx.h b/src/server/db/src/stdafx.h index c36c8622..efa814d6 100755 --- a/src/server/db/src/stdafx.h +++ b/src/server/db/src/stdafx.h @@ -2,6 +2,7 @@ #define __INC_METiN_II_DBSERV_STDAFX_H__ #include "../../libthecore/include/stdafx.h" +#include #ifndef __WIN32__ #include diff --git a/src/server/game/src/ClientPackageCryptInfo.cpp b/src/server/game/src/ClientPackageCryptInfo.cpp index eb7ea0b8..14d03d48 100755 --- a/src/server/game/src/ClientPackageCryptInfo.cpp +++ b/src/server/game/src/ClientPackageCryptInfo.cpp @@ -2,8 +2,10 @@ #include "ClientPackageCryptInfo.h" #include "../../common/stl.h" -#ifndef __FreeBSD__ +#if defined(_WIN32) #include "../../libthecore/include/xdirent.h" +#else +#include #endif CClientPackageCryptInfo::CClientPackageCryptInfo() : m_pSerializedCryptKeyStream(NULL), m_nCryptKeyPackageCnt(0) diff --git a/src/server/game/src/FileMonitor_FreeBSD.cpp b/src/server/game/src/FileMonitor_FreeBSD.cpp index e44a65e7..a3a5f09c 100755 --- a/src/server/game/src/FileMonitor_FreeBSD.cpp +++ b/src/server/game/src/FileMonitor_FreeBSD.cpp @@ -5,6 +5,8 @@ #define INVALID_KERNEL_EVENT -1 +#ifdef __FreeBSD__ + FileMonitorFreeBSD::FileMonitorFreeBSD() { m_KernelEventQueue = INVALID_KERNEL_EVENT; @@ -133,4 +135,12 @@ void FileMonitorFreeBSD::AddWatch(const std::string& strFileName, PFN_FileChange m_TriggeredEventLists.push_back( kTriggerEvent ); m_MonitoredEventLists.push_back( kMonitorEvent ); -} \ No newline at end of file +} +#else + +FileMonitorFreeBSD::FileMonitorFreeBSD() : m_KernelEventQueue(-1) {} +FileMonitorFreeBSD::~FileMonitorFreeBSD() {} +void FileMonitorFreeBSD::AddWatch(const std::string&, PFN_FileChangeListener) {} +void FileMonitorFreeBSD::Update(DWORD) {} + +#endif diff --git a/src/server/game/src/FileMonitor_FreeBSD.h b/src/server/game/src/FileMonitor_FreeBSD.h index de4f43f7..4eb0601a 100755 --- a/src/server/game/src/FileMonitor_FreeBSD.h +++ b/src/server/game/src/FileMonitor_FreeBSD.h @@ -3,7 +3,11 @@ #include "IFileMonitor.h" #include +#ifdef __FreeBSD__ #include +#else +struct kevent { int dummy; }; +#endif #include #include #include diff --git a/src/server/game/src/Makefile b/src/server/game/src/Makefile index 0ba497ad..6820ef20 100755 --- a/src/server/game/src/Makefile +++ b/src/server/game/src/Makefile @@ -1,35 +1,35 @@ -PLATFORM = $(shell file /bin/ls | cut -d' ' -f3 | cut -d'-' -f1) +UNAME_S := $(shell uname -s) +UNAME_M := $(shell uname -m) -GCC_VERSION = $(shell $(CC) --version 2>&1 | grep "(GCC)" | cut -d' ' -f3 | cut -d'.' -f1) -BSD_VERSION = $(shell uname -v 2>&1 | cut -d' ' -f2 | cut -d'.' -f1) -SVN_VERSION = 40250 - -CC = clang++-devel +CC ?= clang++-devel INCDIR = LIBDIR = BINDIR = .. OBJDIR = OBJDIR -GAMEDIR = /usr/metin2/server/share/bin +GAMEDIR ?= ../../share/bin +SVN_VERSION = 40250 $(shell if [ ! -d $(OBJDIR) ]; then mkdir $(OBJDIR); fi) -# Standard Setting -LIBS = -pthread -lm -lmd -# Removed -fno-rtti -CFLAGS = -g -Wall -w -O2 -m32 -pipe -std=c++2b -fexceptions -D_THREAD_SAFE -DNDEBUG # -D_USE_SERVER_KEY_ -CFLAGS += -mtune=i686 -fstack-protector-all - -# CryptoPP -LIBS += ../../../extern/lib/libcryptopp.a - -# DevIL -LIBS += ../../../extern/lib/libIL.a - -# MySQL -LIBS += /usr/local/lib/mysql/libmysqlclient.a /usr/lib/libz.a - -# OpenSSL -LIBS += /usr/lib/libssl.a /usr/lib/libcrypto.a +ifeq ($(UNAME_S), Linux) + ifeq ($(UNAME_M), x86_64) + ARCH_FLAGS = -m32 -mtune=i686 + else ifeq ($(UNAME_M), i386) + ARCH_FLAGS = -mtune=i686 + else + ARCH_FLAGS = + endif + CFLAGS ?= -g -Wall -w -O2 $(ARCH_FLAGS) -pipe -std=c++2b -fexceptions -D_THREAD_SAFE -DNDEBUG -fstack-protector-all -fsigned-char + INCDIR += -I/usr/include/mariadb -I/usr/include/mysql + LIBS = -pthread -lm -lcryptopp -lIL -lILU -lmariadb -lz -lssl -lcrypto -ldl +else + CFLAGS ?= -g -Wall -w -O2 -m32 -pipe -std=c++2b -fexceptions -D_THREAD_SAFE -DNDEBUG -mtune=i686 -fstack-protector-all + LIBS = -pthread -lm -lmd + LIBS += ../../../extern/lib/libcryptopp.a + LIBS += ../../../extern/lib/libIL.a + LIBS += /usr/local/lib/mysql/libmysqlclient.a /usr/lib/libz.a + LIBS += /usr/lib/libssl.a /usr/lib/libcrypto.a +endif # Miscellaneous external libraries INCDIR += -I../../../extern/include @@ -108,10 +108,9 @@ limit_time: $(TARGET): $(CPPOBJS) $(COBJS) $(MAINOBJ) @echo linking $(TARGET).... - @$(CC) $(CFLAGS) $(LIBDIR) $(COBJS) $(CPPOBJS) $(MAINOBJ) $(LIBS) -o $(TARGET) - @echo "Moving $(TARGET) to $(GAMEDIR)" - @mv $(TARGET) $(GAMEDIR) - @echo "All done! Your game file moved to your server directory." + $(CC) $(CFLAGS) $(LIBDIR) $(COBJS) $(CPPOBJS) $(MAINOBJ) $(LIBS) -o $(TARGET) + @if [ -d "$(GAMEDIR)" ]; then cp $(TARGET) $(GAMEDIR)/; echo "Copied $(TARGET) to $(GAMEDIR)"; fi + @echo "All done!" clean: @rm -f $(COBJS) $(CPPOBJS) $(MAINOBJ) diff --git a/src/server/game/src/OXEvent.cpp b/src/server/game/src/OXEvent.cpp index 636f2029..31edba49 100755 --- a/src/server/game/src/OXEvent.cpp +++ b/src/server/game/src/OXEvent.cpp @@ -424,7 +424,7 @@ bool COXEventManager::LogWinner() return true; } -bool COXEventManager::GiveItemToAttender(DWORD dwItemVnum, BYTE count) +bool COXEventManager::GiveItemToAttender(DWORD dwItemVnum, DWORD count) { itertype(m_map_attender) iter = m_map_attender.begin(); diff --git a/src/server/game/src/OXEvent.h b/src/server/game/src/OXEvent.h index c6d716e7..619c848b 100755 --- a/src/server/game/src/OXEvent.h +++ b/src/server/game/src/OXEvent.h @@ -53,7 +53,7 @@ class COXEventManager : public singleton bool ShowQuizList(LPCHARACTER pChar); bool Quiz(unsigned char level, int timelimit); - bool GiveItemToAttender(DWORD dwItemVnum, BYTE count); + bool GiveItemToAttender(DWORD dwItemVnum, DWORD count); bool CheckAnswer(bool answer); void WarpToAudience(); diff --git a/src/server/game/src/arena.cpp b/src/server/game/src/arena.cpp index de2d8b1d..efe9c4e9 100755 --- a/src/server/game/src/arena.cpp +++ b/src/server/game/src/arena.cpp @@ -80,7 +80,7 @@ bool CArenaMap::AddArena(DWORD mapIdx, WORD startA_X, WORD startA_Y, WORD startB for (; iter != m_listArena.end(); iter++) { - if ((CArena*)(*iter)->CheckArea(startA_X, startA_Y, startB_X, startB_Y) == false) + if ((*iter)->CheckArea(startA_X, startA_Y, startB_X, startB_Y) == false) { sys_log(0, "CArenaMap::AddArena - Same Start Position set. stA(%d, %d) stB(%d, %d)", startA_X, startA_Y, startB_X, startB_Y); return false; @@ -237,17 +237,17 @@ EVENTFUNC(ready_to_start_event) if (chA != NULL) { - chA->ChatPacket(CHAT_TYPE_INFO, LC_TEXT("´ë·Ã »ó´밡 »ç¶óÁ® ´ë·ÃÀ» Á¾·áÇմϴÙ.")); + chA->ChatPacket(CHAT_TYPE_INFO, LC_TEXT("대련 상대가 사라져 대련을 종료합니다.")); sys_log(0, "ARENA: Oppernent is disappered. MyPID(%d) OppPID(%d)", pArena->GetPlayerAPID(), pArena->GetPlayerBPID()); } if (chB != NULL) { - chB->ChatPacket(CHAT_TYPE_INFO, LC_TEXT("´ë·Ã »ó´밡 »ç¶óÁ® ´ë·ÃÀ» Á¾·áÇմϴÙ.")); + chB->ChatPacket(CHAT_TYPE_INFO, LC_TEXT("대련 상대가 사라져 대련을 종료합니다.")); sys_log(0, "ARENA: Oppernent is disappered. MyPID(%d) OppPID(%d)", pArena->GetPlayerBPID(), pArena->GetPlayerAPID()); } - pArena->SendChatPacketToObserver(CHAT_TYPE_NOTICE, LC_TEXT("´ë·Ã »ó´밡 »ç¶óÁ® ´ë·ÃÀ» Á¾·áÇմϴÙ.")); + pArena->SendChatPacketToObserver(CHAT_TYPE_NOTICE, LC_TEXT("대련 상대가 사라져 대련을 종료합니다.")); pArena->EndDuel(); return 0; @@ -264,20 +264,20 @@ EVENTFUNC(ready_to_start_event) if (count > 10000) { - chA->ChatPacket(CHAT_TYPE_INFO, LC_TEXT("¹°¾à Á¦ÇÑÀÌ ¾ø½À´ϴÙ.")); - chB->ChatPacket(CHAT_TYPE_INFO, LC_TEXT("¹°¾à Á¦ÇÑÀÌ ¾ø½À´ϴÙ.")); + chA->ChatPacket(CHAT_TYPE_INFO, LC_TEXT("물약 제한이 없습니다.")); + chB->ChatPacket(CHAT_TYPE_INFO, LC_TEXT("물약 제한이 없습니다.")); } else { chA->SetPotionLimit(count); chB->SetPotionLimit(count); - chA->ChatPacket(CHAT_TYPE_INFO, LC_TEXT("¹°¾àÀ» %d °³ ±îÁö »ç¿ë °¡´ÉÇմϴÙ."), chA->GetPotionLimit()); - chB->ChatPacket(CHAT_TYPE_INFO, LC_TEXT("¹°¾àÀ» %d °³ ±îÁö »ç¿ë °¡´ÉÇմϴÙ."), chB->GetPotionLimit()); + chA->ChatPacket(CHAT_TYPE_INFO, LC_TEXT("물약을 %d 개 까지 사용 가능합니다."), chA->GetPotionLimit()); + chB->ChatPacket(CHAT_TYPE_INFO, LC_TEXT("물약을 %d 개 까지 사용 가능합니다."), chB->GetPotionLimit()); } - chA->ChatPacket(CHAT_TYPE_INFO, LC_TEXT("10ÃʵÚ ´ë·ÃÀÌ ½ÃÀ۵˴ϴÙ.")); - chB->ChatPacket(CHAT_TYPE_INFO, LC_TEXT("10ÃʵÚ ´ë·ÃÀÌ ½ÃÀ۵˴ϴÙ.")); - pArena->SendChatPacketToObserver(CHAT_TYPE_INFO, LC_TEXT("10ÃʵÚ ´ë·ÃÀÌ ½ÃÀ۵˴ϴÙ.")); + chA->ChatPacket(CHAT_TYPE_INFO, LC_TEXT("10초뒤 대련이 시작됩니다.")); + chB->ChatPacket(CHAT_TYPE_INFO, LC_TEXT("10초뒤 대련이 시작됩니다.")); + pArena->SendChatPacketToObserver(CHAT_TYPE_INFO, LC_TEXT("10초뒤 대련이 시작됩니다.")); info->state++; return PASSES_PER_SEC(10); @@ -286,15 +286,15 @@ EVENTFUNC(ready_to_start_event) case 1: { - chA->ChatPacket(CHAT_TYPE_INFO, LC_TEXT("´ë·ÃÀÌ ½ÃÀ۵Ǿú½À´ϴÙ.")); - chB->ChatPacket(CHAT_TYPE_INFO, LC_TEXT("´ë·ÃÀÌ ½ÃÀ۵Ǿú½À´ϴÙ.")); - pArena->SendChatPacketToObserver(CHAT_TYPE_INFO, LC_TEXT("´ë·ÃÀÌ ½ÃÀ۵Ǿú½À´ϴÙ.")); + chA->ChatPacket(CHAT_TYPE_INFO, LC_TEXT("대련이 시작되었습니다.")); + chB->ChatPacket(CHAT_TYPE_INFO, LC_TEXT("대련이 시작되었습니다.")); + pArena->SendChatPacketToObserver(CHAT_TYPE_INFO, LC_TEXT("대련이 시작되었습니다.")); TPacketGCDuelStart duelStart; duelStart.header = HEADER_GC_DUEL_START; duelStart.wSize = sizeof(TPacketGCDuelStart) + 4; - DWORD dwOppList[8]; // Ãִë ÆÄƼ¿ø 8¸í À̹ǷÎ.. + DWORD dwOppList[8]; // 최대 파티원 8명 이므로.. dwOppList[0] = (DWORD)chB->GetVID(); TEMP_BUFFER buf; @@ -343,7 +343,7 @@ EVENTFUNC(ready_to_start_event) TEMP_BUFFER buf; TEMP_BUFFER buf2; - DWORD dwOppList[8]; // Ãִë ÆÄƼ¿ø 8¸í À̹ǷÎ.. + DWORD dwOppList[8]; // 최대 파티원 8명 이므로.. TPacketGCDuelStart duelStart; duelStart.header = HEADER_GC_DUEL_START; duelStart.wSize = sizeof(TPacketGCDuelStart) + 4; @@ -358,9 +358,9 @@ EVENTFUNC(ready_to_start_event) buf2.write(&dwOppList[0], 4); chB->GetDesc()->Packet(buf2.read_peek(), buf2.size()); - chA->ChatPacket(CHAT_TYPE_INFO, LC_TEXT("´ë·ÃÀÌ ½ÃÀ۵Ǿú½À´ϴÙ.")); - chB->ChatPacket(CHAT_TYPE_INFO, LC_TEXT("´ë·ÃÀÌ ½ÃÀ۵Ǿú½À´ϴÙ.")); - pArena->SendChatPacketToObserver(CHAT_TYPE_INFO, LC_TEXT("´ë·ÃÀÌ ½ÃÀ۵Ǿú½À´ϴÙ.")); + chA->ChatPacket(CHAT_TYPE_INFO, LC_TEXT("대련이 시작되었습니다.")); + chB->ChatPacket(CHAT_TYPE_INFO, LC_TEXT("대련이 시작되었습니다.")); + pArena->SendChatPacketToObserver(CHAT_TYPE_INFO, LC_TEXT("대련이 시작되었습니다.")); pArena->ClearEvent(); @@ -370,9 +370,9 @@ EVENTFUNC(ready_to_start_event) default: { - chA->ChatPacket(CHAT_TYPE_INFO, LC_TEXT("´ë·ÃÀå ¹®Á¦·Î ÀÎÇϿ© ´ë·ÃÀ» Á¾·áÇմϴÙ.")); - chB->ChatPacket(CHAT_TYPE_INFO, LC_TEXT("´ë·ÃÀå ¹®Á¦·Î ÀÎÇϿ© ´ë·ÃÀ» Á¾·áÇմϴÙ.")); - pArena->SendChatPacketToObserver(CHAT_TYPE_INFO, LC_TEXT("´ë·ÃÀå ¹®Á¦·Î ÀÎÇϿ© ´ë·ÃÀ» Á¾·áÇմϴÙ.")); + chA->ChatPacket(CHAT_TYPE_INFO, LC_TEXT("대련장 문제로 인하여 대련을 종료합니다.")); + chB->ChatPacket(CHAT_TYPE_INFO, LC_TEXT("대련장 문제로 인하여 대련을 종료합니다.")); + pArena->SendChatPacketToObserver(CHAT_TYPE_INFO, LC_TEXT("대련장 문제로 인하여 대련을 종료합니다.")); sys_log(0, "ARENA: Something wrong in event func. info->state(%d)", info->state); @@ -411,17 +411,17 @@ EVENTFUNC(duel_time_out) { if (chA != NULL) { - chA->ChatPacket(CHAT_TYPE_INFO, LC_TEXT("´ë·Ã »ó´밡 »ç¶óÁ® ´ë·ÃÀ» Á¾·áÇմϴÙ.")); + chA->ChatPacket(CHAT_TYPE_INFO, LC_TEXT("대련 상대가 사라져 대련을 종료합니다.")); sys_log(0, "ARENA: Oppernent is disappered. MyPID(%d) OppPID(%d)", pArena->GetPlayerAPID(), pArena->GetPlayerBPID()); } if (chB != NULL) { - chB->ChatPacket(CHAT_TYPE_INFO, LC_TEXT("´ë·Ã »ó´밡 »ç¶óÁ® ´ë·ÃÀ» Á¾·áÇմϴÙ.")); + chB->ChatPacket(CHAT_TYPE_INFO, LC_TEXT("대련 상대가 사라져 대련을 종료합니다.")); sys_log(0, "ARENA: Oppernent is disappered. MyPID(%d) OppPID(%d)", pArena->GetPlayerBPID(), pArena->GetPlayerAPID()); } - pArena->SendChatPacketToObserver(CHAT_TYPE_INFO, LC_TEXT("´ë·Ã »ó´밡 »ç¶óÁ® ´ë·ÃÀ» Á¾·áÇմϴÙ.")); + pArena->SendChatPacketToObserver(CHAT_TYPE_INFO, LC_TEXT("대련 상대가 사라져 대련을 종료합니다.")); pArena->EndDuel(); return 0; @@ -431,14 +431,14 @@ EVENTFUNC(duel_time_out) switch (info->state) { case 0: - pArena->SendChatPacketToObserver(CHAT_TYPE_NOTICE, LC_TEXT("´ë·Ã ½ð£ Ãʰú·Î ´ë·ÃÀ» ÁߴÜÇմϴÙ.")); - pArena->SendChatPacketToObserver(CHAT_TYPE_NOTICE, LC_TEXT("10ÃʵÚ ¸¶À»·Î À̵¿ÇմϴÙ.")); + pArena->SendChatPacketToObserver(CHAT_TYPE_NOTICE, LC_TEXT("대련 시간 초과로 대련을 중단합니다.")); + pArena->SendChatPacketToObserver(CHAT_TYPE_NOTICE, LC_TEXT("10초뒤 마을로 이동합니다.")); - chA->ChatPacket(CHAT_TYPE_NOTICE, LC_TEXT("´ë·Ã ½ð£ Ãʰú·Î ´ë·ÃÀ» ÁߴÜÇմϴÙ.")); - chA->ChatPacket(CHAT_TYPE_NOTICE, LC_TEXT("10ÃʵÚ ¸¶À»·Î À̵¿ÇմϴÙ.")); + chA->ChatPacket(CHAT_TYPE_NOTICE, LC_TEXT("대련 시간 초과로 대련을 중단합니다.")); + chA->ChatPacket(CHAT_TYPE_NOTICE, LC_TEXT("10초뒤 마을로 이동합니다.")); - chB->ChatPacket(CHAT_TYPE_NOTICE, LC_TEXT("´ë·Ã ½ð£ Ãʰú·Î ´ë·ÃÀ» ÁߴÜÇմϴÙ.")); - chB->ChatPacket(CHAT_TYPE_NOTICE, LC_TEXT("10ÃʵÚ ¸¶À»·Î À̵¿ÇմϴÙ.")); + chB->ChatPacket(CHAT_TYPE_NOTICE, LC_TEXT("대련 시간 초과로 대련을 중단합니다.")); + chB->ChatPacket(CHAT_TYPE_NOTICE, LC_TEXT("10초뒤 마을로 이동합니다.")); TPacketGCDuelStart duelStart; duelStart.header = HEADER_GC_DUEL_START; @@ -682,7 +682,7 @@ bool CArenaMap::CanAttack(LPCHARACTER pCharAttacker, LPCHARACTER pCharVictim) bool CArena::CanAttack(DWORD dwPIDA, DWORD dwPIDB) { - // 1:1 Àü¿ë ´ٴë´Ù ÇÒ °æ¿ì ¼öÁ¤ Çʿä + // 1:1 전용 다대다 할 경우 수정 필요 if (m_dwPIDA == dwPIDA && m_dwPIDB == dwPIDB) return true; if (m_dwPIDA == dwPIDB && m_dwPIDB == dwPIDA) return true; @@ -732,20 +732,20 @@ bool CArena::OnDead(DWORD dwPIDA, DWORD dwPIDB) if (pCharA == NULL && pCharB == NULL) { - // µѴÙ Á¢¼ÓÀÌ ²÷¾îÁ³´Ù ?! - SendChatPacketToObserver(CHAT_TYPE_NOTICE, LC_TEXT("´ë·ÃÀÚ ¹®Á¦·Î ÀÎÇϿ© ´ë·ÃÀ» ÁߴÜÇմϴÙ.")); + // 둘다 접속이 끊어졌다 ?! + SendChatPacketToObserver(CHAT_TYPE_NOTICE, LC_TEXT("대련자 문제로 인하여 대련을 중단합니다.")); restart = false; } else if (pCharA == NULL && pCharB != NULL) { - pCharB->ChatPacket(CHAT_TYPE_NOTICE, LC_TEXT("»ó´ë¹æ ij¸¯ÅÍÀÇ ¹®Á¦·Î ÀÎÇϿ© ´ë·ÃÀ» Á¾·áÇմϴÙ.")); - SendChatPacketToObserver(CHAT_TYPE_NOTICE, LC_TEXT("´ë·ÃÀÚ ¹®Á¦·Î ÀÎÇϿ© ´ë·ÃÀ» Á¾·áÇմϴÙ.")); + pCharB->ChatPacket(CHAT_TYPE_NOTICE, LC_TEXT("상대방 캐릭터의 문제로 인하여 대련을 종료합니다.")); + SendChatPacketToObserver(CHAT_TYPE_NOTICE, LC_TEXT("대련자 문제로 인하여 대련을 종료합니다.")); restart = false; } else if (pCharA != NULL && pCharB == NULL) { - pCharA->ChatPacket(CHAT_TYPE_NOTICE, LC_TEXT("»ó´ë¹æ ij¸¯ÅÍÀÇ ¹®Á¦·Î ÀÎÇϿ© ´ë·ÃÀ» Á¾·áÇմϴÙ.")); - SendChatPacketToObserver(CHAT_TYPE_NOTICE, LC_TEXT("´ë·ÃÀÚ ¹®Á¦·Î ÀÎÇϿ© ´ë·ÃÀ» Á¾·áÇմϴÙ.")); + pCharA->ChatPacket(CHAT_TYPE_NOTICE, LC_TEXT("상대방 캐릭터의 문제로 인하여 대련을 종료합니다.")); + SendChatPacketToObserver(CHAT_TYPE_NOTICE, LC_TEXT("대련자 문제로 인하여 대련을 종료합니다.")); restart = false; } else if (pCharA != NULL && pCharB != NULL) @@ -756,9 +756,9 @@ bool CArena::OnDead(DWORD dwPIDA, DWORD dwPIDB) if (m_dwSetPointOfA >= m_dwSetCount) { - pCharA->ChatPacket(CHAT_TYPE_NOTICE, LC_TEXT("%s ´ÔÀÌ ´ë·ÿ¡¼­ ½¸®ÇϿ´½À´ϴÙ."), pCharA->GetName()); - pCharB->ChatPacket(CHAT_TYPE_NOTICE, LC_TEXT("%s ´ÔÀÌ ´ë·ÿ¡¼­ ½¸®ÇϿ´½À´ϴÙ."), pCharA->GetName()); - SendChatPacketToObserver(CHAT_TYPE_NOTICE, LC_TEXT("%s ´ÔÀÌ ´ë·ÿ¡¼­ ½¸®ÇϿ´½À´ϴÙ."), pCharA->GetName()); + pCharA->ChatPacket(CHAT_TYPE_NOTICE, LC_TEXT("%s 님이 대련에서 승리하였습니다."), pCharA->GetName()); + pCharB->ChatPacket(CHAT_TYPE_NOTICE, LC_TEXT("%s 님이 대련에서 승리하였습니다."), pCharA->GetName()); + SendChatPacketToObserver(CHAT_TYPE_NOTICE, LC_TEXT("%s 님이 대련에서 승리하였습니다."), pCharA->GetName()); sys_log(0, "ARENA: Duel is end. Winner %s(%d) Loser %s(%d)", pCharA->GetName(), GetPlayerAPID(), pCharB->GetName(), GetPlayerBPID()); @@ -766,10 +766,10 @@ bool CArena::OnDead(DWORD dwPIDA, DWORD dwPIDB) else { restart = true; - pCharA->ChatPacket(CHAT_TYPE_INFO, LC_TEXT("%s ´ÔÀÌ ½¸®ÇϿ´½À´ϴÙ."), pCharA->GetName()); + pCharA->ChatPacket(CHAT_TYPE_INFO, LC_TEXT("%s 님이 승리하였습니다."), pCharA->GetName()); pCharA->ChatPacket(CHAT_TYPE_NOTICE, "%s %d : %d %s", pCharA->GetName(), m_dwSetPointOfA, m_dwSetPointOfB, pCharB->GetName()); - pCharB->ChatPacket(CHAT_TYPE_INFO, LC_TEXT("%s ´ÔÀÌ ½¸®ÇϿ´½À´ϴÙ."), pCharA->GetName()); + pCharB->ChatPacket(CHAT_TYPE_INFO, LC_TEXT("%s 님이 승리하였습니다."), pCharA->GetName()); pCharB->ChatPacket(CHAT_TYPE_NOTICE, "%s %d : %d %s", pCharA->GetName(), m_dwSetPointOfA, m_dwSetPointOfB, pCharB->GetName()); SendChatPacketToObserver(CHAT_TYPE_NOTICE, "%s %d : %d %s", pCharA->GetName(), m_dwSetPointOfA, m_dwSetPointOfB, pCharB->GetName()); @@ -783,19 +783,19 @@ bool CArena::OnDead(DWORD dwPIDA, DWORD dwPIDB) m_dwSetPointOfB++; if (m_dwSetPointOfB >= m_dwSetCount) { - pCharA->ChatPacket(CHAT_TYPE_NOTICE, LC_TEXT("%s ´ÔÀÌ ´ë·ÿ¡¼­ ½¸®ÇϿ´½À´ϴÙ."), pCharB->GetName()); - pCharB->ChatPacket(CHAT_TYPE_NOTICE, LC_TEXT("%s ´ÔÀÌ ´ë·ÿ¡¼­ ½¸®ÇϿ´½À´ϴÙ."), pCharB->GetName()); - SendChatPacketToObserver(CHAT_TYPE_NOTICE, LC_TEXT("%s ´ÔÀÌ ´ë·ÿ¡¼­ ½¸®ÇϿ´½À´ϴÙ."), pCharB->GetName()); + pCharA->ChatPacket(CHAT_TYPE_NOTICE, LC_TEXT("%s 님이 대련에서 승리하였습니다."), pCharB->GetName()); + pCharB->ChatPacket(CHAT_TYPE_NOTICE, LC_TEXT("%s 님이 대련에서 승리하였습니다."), pCharB->GetName()); + SendChatPacketToObserver(CHAT_TYPE_NOTICE, LC_TEXT("%s 님이 대련에서 승리하였습니다."), pCharB->GetName()); sys_log(0, "ARENA: Duel is end. Winner(%d) Loser(%d)", GetPlayerBPID(), GetPlayerAPID()); } else { restart = true; - pCharA->ChatPacket(CHAT_TYPE_INFO, LC_TEXT("%s ´ÔÀÌ ½¸®ÇϿ´½À´ϴÙ."), pCharB->GetName()); + pCharA->ChatPacket(CHAT_TYPE_INFO, LC_TEXT("%s 님이 승리하였습니다."), pCharB->GetName()); pCharA->ChatPacket(CHAT_TYPE_NOTICE, "%s %d : %d %s", pCharA->GetName(), m_dwSetPointOfA, m_dwSetPointOfB, pCharB->GetName()); - pCharB->ChatPacket(CHAT_TYPE_INFO, LC_TEXT("%s ´ÔÀÌ ½¸®ÇϿ´½À´ϴÙ."), pCharB->GetName()); + pCharB->ChatPacket(CHAT_TYPE_INFO, LC_TEXT("%s 님이 승리하였습니다."), pCharB->GetName()); pCharB->ChatPacket(CHAT_TYPE_NOTICE, "%s %d : %d %s", pCharA->GetName(), m_dwSetPointOfA, m_dwSetPointOfB, pCharB->GetName()); SendChatPacketToObserver(CHAT_TYPE_NOTICE, "%s %d : %d %s", pCharA->GetName(), m_dwSetPointOfA, m_dwSetPointOfB, pCharB->GetName()); @@ -815,18 +815,18 @@ bool CArena::OnDead(DWORD dwPIDA, DWORD dwPIDB) } else { - // ¿À¸é ¾ȵȴÙ ?! + // 오면 안된다 ?! } if (restart == false) { if (pCharA != NULL) - pCharA->ChatPacket(CHAT_TYPE_INFO, LC_TEXT("10ÃʵÚ ¸¶À»·Î µǵ¹¾ư©´ϴÙ.")); + pCharA->ChatPacket(CHAT_TYPE_INFO, LC_TEXT("10초뒤 마을로 되돌아갑니다.")); if ( pCharB != NULL) - pCharB->ChatPacket(CHAT_TYPE_INFO, LC_TEXT("10ÃʵÚ ¸¶À»·Î µǵ¹¾ư©´ϴÙ.")); + pCharB->ChatPacket(CHAT_TYPE_INFO, LC_TEXT("10초뒤 마을로 되돌아갑니다.")); - SendChatPacketToObserver(CHAT_TYPE_INFO, LC_TEXT("10ÃʵÚ ¸¶À»·Î µǵ¹¾ư©´ϴÙ.")); + SendChatPacketToObserver(CHAT_TYPE_INFO, LC_TEXT("10초뒤 마을로 되돌아갑니다.")); if (m_pEvent != NULL) { event_cancel(&m_pEvent); @@ -842,12 +842,12 @@ bool CArena::OnDead(DWORD dwPIDA, DWORD dwPIDB) else { if (pCharA != NULL) - pCharA->ChatPacket(CHAT_TYPE_INFO, LC_TEXT("10ÃʵÚ ´ÙÀ½ ÆÇÀ» ½ÃÀÛÇմϴÙ.")); + pCharA->ChatPacket(CHAT_TYPE_INFO, LC_TEXT("10초뒤 다음 판을 시작합니다.")); if (pCharB != NULL) - pCharB->ChatPacket(CHAT_TYPE_INFO, LC_TEXT("10ÃʵÚ ´ÙÀ½ ÆÇÀ» ½ÃÀÛÇմϴÙ.")); + pCharB->ChatPacket(CHAT_TYPE_INFO, LC_TEXT("10초뒤 다음 판을 시작합니다.")); - SendChatPacketToObserver(CHAT_TYPE_INFO, LC_TEXT("10ÃʵÚ ´ÙÀ½ ÆÇÀ» ½ÃÀÛÇմϴÙ.")); + SendChatPacketToObserver(CHAT_TYPE_INFO, LC_TEXT("10초뒤 다음 판을 시작합니다.")); if (m_pEvent != NULL) { event_cancel(&m_pEvent); @@ -953,7 +953,7 @@ void CArena::OnDisconnect(DWORD pid) if (m_dwPIDA == pid) { if (GetPlayerB() != NULL) - GetPlayerB()->ChatPacket(CHAT_TYPE_INFO, LC_TEXT("»ó´ë¹æ ij¸¯ÅͰ¡ Á¢¼ÓÀ» Á¾·áÇϿ© ´ë·ÃÀ» ÁßÁöÇմϴÙ.")); + GetPlayerB()->ChatPacket(CHAT_TYPE_INFO, LC_TEXT("상대방 캐릭터가 접속을 종료하여 대련을 중지합니다.")); sys_log(0, "ARENA : Duel is end because of Opp(%d) is disconnect. MyPID(%d)", GetPlayerAPID(), GetPlayerBPID()); EndDuel(); @@ -961,7 +961,7 @@ void CArena::OnDisconnect(DWORD pid) else if (m_dwPIDB == pid) { if (GetPlayerA() != NULL) - GetPlayerA()->ChatPacket(CHAT_TYPE_INFO, LC_TEXT("»ó´ë¹æ ij¸¯ÅͰ¡ Á¢¼ÓÀ» Á¾·áÇϿ© ´ë·ÃÀ» ÁßÁöÇմϴÙ.")); + GetPlayerA()->ChatPacket(CHAT_TYPE_INFO, LC_TEXT("상대방 캐릭터가 접속을 종료하여 대련을 중지합니다.")); sys_log(0, "ARENA : Duel is end because of Opp(%d) is disconnect. MyPID(%d)", GetPlayerBPID(), GetPlayerAPID()); EndDuel(); diff --git a/src/server/game/src/ava2_chest.inc b/src/server/game/src/ava2_chest.inc index a8721c23..5e1cf71c 100644 --- a/src/server/game/src/ava2_chest.inc +++ b/src/server/game/src/ava2_chest.inc @@ -52,14 +52,14 @@ bool CHARACTER::AutoGiveItemChest(LPITEM item, DWORD& itemCount, std::mapfirst; - if (itemVnum == item2->GetVnum()) + if (item2->CanStackWith(item)) { bool same=true; for(int j=0;jGetSocket(j)!=item->GetSocket(j)) same=false; if(!same) continue; const DWORD item2Count = item2->GetCount(); - const WORD bCount2 = MIN(ITEM_MAX_COUNT - item2Count, wCount); + const WORD bCount2 = MIN(item2->GetStackRoom(), wCount); if (bCount2 > 0) { wCount -= bCount2; @@ -78,7 +78,7 @@ bool CHARACTER::AutoGiveItemChest(LPITEM item, DWORD& itemCount, std::mapGetVnum() == itemVnum) + if (item2->CanStackWith(item)) { BYTE j; for (j = 0; j < ITEM_SOCKET_MAX_NUM; ++j) @@ -87,7 +87,7 @@ bool CHARACTER::AutoGiveItemChest(LPITEM item, DWORD& itemCount, std::mapGetCount(); - const WORD bCount2 = MIN(ITEM_MAX_COUNT - item2Count, wCount); + const WORD bCount2 = MIN(item2->GetStackRoom(), wCount); if (bCount2 > 0) { const auto itItem = vecUpdateItems.find(item2); @@ -229,11 +229,15 @@ bool CHARACTER::GiveItemFromSpecialItemGroupNew(DWORD dwGroupNum, WORD& loopCoun break; default: { - // The selected base has 200-count stacks and byte item-count packets. - // AVA2 rewards larger than a stack must be split, never silently clamped by CreateItem. + const auto* proto = ITEM_MANAGER::Instance().GetTable(dwVnum); + if (!proto) { --returnCount; break; } + unsigned limit = PortMaterialStackPolicy::GrantLimit(proto->bType, + (proto->dwFlags & ITEM_FLAG_STACKABLE) != 0, + (proto->dwAntiFlags & ITEM_ANTIFLAG_STACK) != 0, dwVnum); + if ((PortMaterialStackPolicy::LegacyGrowthMode() || quest::CQuestManager::instance().GetEventFlag("material_stack_legacy_mode"))) limit=std::min(limit,200u); DWORD remaining=dwEarnCount; while(remaining) { - LPITEM item=ITEM_MANAGER::Instance().CreateItem(dwVnum,MIN(remaining,ITEM_MAX_COUNT)); + LPITEM item=ITEM_MANAGER::Instance().CreateItem(dwVnum,MIN(remaining,limit)); if(!item) { --returnCount; break; } const DWORD created=item->GetCount(); DWORD count=created; diff --git a/src/server/game/src/ava2_ticket_shop.cpp b/src/server/game/src/ava2_ticket_shop.cpp index a6837edd..e092e685 100644 --- a/src/server/game/src/ava2_ticket_shop.cpp +++ b/src/server/game/src/ava2_ticket_shop.cpp @@ -20,7 +20,7 @@ static const Ava2TicketOffer kAva2Tickets[]={ struct Ava2ShopPrice { DWORD vnum,count; }; struct Ava2ShopStart { TPacketGCShopStart shop; Ava2ShopPrice prices[SHOP_HOST_ITEM_MAX_NUM]; }; #pragma pack(pop) -static_assert(sizeof(Ava2ShopStart)==2204,"native currency shop payload"); +static_assert(sizeof(Ava2ShopStart)==2244,"native currency shop payload"); static_assert(sizeof(Ava2ShopPrice)==8,"AVA2 item price layout"); class CAva2TicketShop : public CShop { public: diff --git a/src/server/game/src/char.h b/src/server/game/src/char.h index 0ce538ca..acd2a81d 100755 --- a/src/server/game/src/char.h +++ b/src/server/game/src/char.h @@ -1226,7 +1226,7 @@ class CHARACTER : public CEntity, public CFSM, public CHorseRider // END_OF_ADD_REFINE_BUILDING bool RefineItem(LPITEM pkItem, LPITEM pkTarget); - bool DropItem(TItemPos Cell, BYTE bCount=0); + bool DropItem(TItemPos Cell, DWORD bCount=0); bool GiveRecallItem(LPITEM item); void ProcessRecallItem(LPITEM item); @@ -1250,7 +1250,7 @@ class CHARACTER : public CEntity, public CFSM, public CHorseRider bool GiveItemFromSpecialItemGroup(DWORD dwGroupNum, std::vector &dwItemVnums, std::vector &dwItemCounts, std::vector &item_gets, int &count); - bool MoveItem(TItemPos pos, TItemPos change_pos, BYTE num); + bool MoveItem(TItemPos pos, TItemPos change_pos, DWORD num); DWORD GetPickUPMode() { return DWORD(GetQuestFlag("ava2_pickup.mode")); } DWORD GetPickUPRarityMode() { return DWORD(GetQuestFlag("ava2_pickup.rarity")); } void ChangePickUPMode(DWORD mode,DWORD rarity); @@ -1275,8 +1275,8 @@ class CHARACTER : public CEntity, public CFSM, public CHorseRider bool CanUnequipNow(const LPITEM item, const TItemPos& srcCell = NPOS, const TItemPos& destCell = NPOS); bool SwapItem(WORD bCell, WORD bDestCell); - LPITEM AutoGiveItem(DWORD dwItemVnum, BYTE bCount=1, int iRarePct = -1, bool bMsg = true); - void AutoGiveItem(LPITEM item, bool longOwnerShip = false); + LPITEM AutoGiveItem(DWORD dwItemVnum, DWORD bCount=1, int iRarePct = -1, bool bMsg = true); + LPITEM AutoGiveItem(LPITEM item, bool longOwnerShip = false); int GetEmptyInventory(BYTE size) const; int GetEmptyDragonSoulInventory(LPITEM pItem) const; diff --git a/src/server/game/src/char_item.cpp b/src/server/game/src/char_item.cpp index e88dd2f7..870f6f02 100755 --- a/src/server/game/src/char_item.cpp +++ b/src/server/game/src/char_item.cpp @@ -1,7 +1,10 @@ #include "stdafx.h" +#include "port_material_stack_policy.h" #include "port_cube_actor.h" #include "../../common/gold_bounds.h" +// Pickup locale keys must stay CP949, matching locale_string.txt on the server. +// UTF-8 source literals miss the dictionary and emit a corrupt @0949 fallback. #include #include "utils.h" @@ -57,6 +60,7 @@ #include "port_premium.h" #include "port_battlepass_hooks.h" #include "PetSystem.h" +#include "port_refine_materials.h" const int ITEM_BROKEN_METIN_VNUM = 28960; // CHANGE_ITEM_ATTRIBUTES @@ -1298,23 +1302,10 @@ bool CHARACTER::DoRefine(LPITEM item, bool bMoneyOnly) return false; } - if (!bMoneyOnly && !RefineChance) + if (!bMoneyOnly && !RefineChance && !PortRefineTakeMaterials(this,prt)) { - for (int i = 0; i < prt->material_count; ++i) - { - if (CountSpecifyItem(prt->materials[i].vnum) < prt->materials[i].count) - { - if (test_server) - { - ChatPacket(CHAT_TYPE_INFO, "Find %d, count %d, require %d", prt->materials[i].vnum, CountSpecifyItem(prt->materials[i].vnum), prt->materials[i].count); - } ChatPacket(CHAT_TYPE_INFO, LC_TEXT("개량을 하기 위한 재료가 부족합니다.")); - return false; - } - } - - for (int i = 0; i < prt->material_count; ++i) - RemoveSpecifyItem(prt->materials[i].vnum, prt->materials[i].count); + return false; } int prob = number(1, 100); @@ -1503,22 +1494,12 @@ bool CHARACTER::DoRefineWithScroll(LPITEM item) return false; } - for (int i = 0; i < prt->material_count; ++i) + if (!PortRefineTakeMaterials(this,prt)) { - if (CountSpecifyItem(prt->materials[i].vnum) < prt->materials[i].count) - { - if (test_server) - { - ChatPacket(CHAT_TYPE_INFO, "Find %d, count %d, require %d", prt->materials[i].vnum, CountSpecifyItem(prt->materials[i].vnum), prt->materials[i].count); - } ChatPacket(CHAT_TYPE_INFO, LC_TEXT("개량을 하기 위한 재료가 부족합니다.")); - return false; - } + return false; } - for (int i = 0; i < prt->material_count; ++i) - RemoveSpecifyItem(prt->materials[i].vnum, prt->materials[i].count); - int prob = number(1, 100); int success_prob = prt->prob; bool bDestroyWhenFail = false; @@ -6293,9 +6274,9 @@ bool CHARACTER::UseItem(TItemPos Cell, TItemPos DestCell) return UseItemEx(item, DestCell); } -bool CHARACTER::DropItem(TItemPos Cell, BYTE bCount) +bool CHARACTER::DropItem(TItemPos Cell, DWORD bCount) { - LPITEM item = NULL; + LPITEM item = NULL; if (!CanHandleItem()) { @@ -6328,8 +6309,23 @@ bool CHARACTER::DropItem(TItemPos Cell, BYTE bCount) return false; } - if (bCount == 0 || bCount > item->GetCount()) - bCount = item->GetCount(); + if (bCount > item->GetCount()) return false; + if (bCount == 0) bCount = item->GetCount(); + + // Clear the variable, it looks the player does not dropped any item in the past second. + if (thecore_pulse() > LastDropTime + 25) + CountDrops = 0; + + // It looks the player dropped min. 4 items in the past 1 second + if (thecore_pulse() < LastDropTime + 25 && CountDrops >= 4) + { + // Set it to 0 + CountDrops = 0; + sys_err("%s[%d] has been disconnected because of drophack using", GetName(), GetPlayerID()); + // Disconnect the player + GetDesc()->SetPhase(PHASE_CLOSE); + return false; + } SyncQuickslot(QUICKSLOT_TYPE_ITEM, Cell.cell, 255); // Quickslot 에서 지움 @@ -6348,19 +6344,17 @@ bool CHARACTER::DropItem(TItemPos Cell, BYTE bCount) sys_log(0, "[DROP_ITEM] drop item count == 0"); return false; } - + // check non-split items for china //if (LC_IsNewCIBN()) // if (item->GetVnum() == 71095 || item->GetVnum() == 71050 || item->GetVnum() == 70038) // return false; - item->SetCount(item->GetCount() - bCount); - ITEM_MANAGER::instance().FlushDelayedSave(item); - - pkItemToDrop = ITEM_MANAGER::instance().CreateItem(item->GetVnum(), bCount); - - // copy item socket -- by mhh - FN_copy_item_socket(pkItemToDrop, item); + pkItemToDrop = ITEM_MANAGER::instance().CreateItem(item->GetOriginalVnum(), bCount); + if (!pkItemToDrop) return false; + if (!item->CopyStackStateTo(pkItemToDrop)) { M2_DESTROY_ITEM(pkItemToDrop); return false; } + if (!item->SetCount(item->GetCount() - bCount)) { M2_DESTROY_ITEM(pkItemToDrop); return false; } + ITEM_MANAGER::instance().FlushDelayedSave(item); char szBuf[51 + 1]; snprintf(szBuf, sizeof(szBuf), "%u %u", pkItemToDrop->GetID(), pkItemToDrop->GetCount()); @@ -6368,21 +6362,7 @@ bool CHARACTER::DropItem(TItemPos Cell, BYTE bCount) } PIXEL_POSITION pxPos = GetXYZ(); - - // Clear the variable, it looks the player does not dropped any item in the past second. - if (thecore_pulse() > LastDropTime + 25) - CountDrops = 0; - - // It looks the player dropped min. 4 items in the past 1 second - if (thecore_pulse() < LastDropTime + 25 && CountDrops >= 4) - { - // Set it to 0 - CountDrops = 0; - sys_err("%s[%d] has been disconnected because of drophack using", GetName(), GetPlayerID()); - // Disconnect the player - GetDesc()->SetPhase(PHASE_CLOSE); - return false; - } + if (pkItemToDrop->AddToGround(GetMapIndex(), pxPos)) { @@ -6395,17 +6375,26 @@ bool CHARACTER::DropItem(TItemPos Cell, BYTE bCount) pkItemToDrop->StartDestroyEvent(); ITEM_MANAGER::instance().FlushDelayedSave(pkItemToDrop); - + char szHint[32 + 1]; snprintf(szHint, sizeof(szHint), "%s %u %u", pkItemToDrop->GetName(), pkItemToDrop->GetCount(), pkItemToDrop->GetOriginalVnum()); LogManager::instance().ItemLog(this, pkItemToDrop, "DROP", szHint); - + LastDropTime = thecore_pulse(); CountDrops++; - + //Motion(MOTION_PICKUP); } + else { + if (pkItemToDrop == item) item->AddToCharacter(this, Cell); + else { + item->SetCount(item->GetCount() + pkItemToDrop->GetCount()); + M2_DESTROY_ITEM(pkItemToDrop); + } + return false; + } + return true; } @@ -6474,7 +6463,7 @@ bool CHARACTER::DropGold(int64_t gold) return false; } -bool CHARACTER::MoveItem(TItemPos Cell, TItemPos DestCell, BYTE count) +bool CHARACTER::MoveItem(TItemPos Cell, TItemPos DestCell, DWORD count) { if (Cell.IsSamePosition(DestCell)) // ItemMove dupe exploit fix return false; @@ -6623,7 +6612,7 @@ bool CHARACTER::MoveItem(TItemPos Cell, TItemPos DestCell, BYTE count) if ((item2 = GetItem(DestCell)) && item != item2 && item2->IsStackable() && !IS_SET(item2->GetAntiFlag(), ITEM_ANTIFLAG_STACK) && - item2->GetVnum() == item->GetVnum()) // 합칠 수 있는 아이템의 경우 + item2->CanStackWith(item)) // 합칠 수 있는 아이템의 경우 { for (int i = 0; i < ITEM_SOCKET_MAX_NUM; ++i) if (item2->GetSocket(i) != item->GetSocket(i)) @@ -6635,7 +6624,8 @@ bool CHARACTER::MoveItem(TItemPos Cell, TItemPos DestCell, BYTE count) sys_log(0, "%s: ITEM_STACK %s (window: %d, cell : %d) -> (window:%d, cell %d) count %d", GetName(), item->GetName(), Cell.window_type, Cell.cell, DestCell.window_type, DestCell.cell, count); - count = MIN(200 - item2->GetCount(), count); + count = MIN(item2->GetStackRoom(), count); + if (!count) return false; item->SetCount(item->GetCount() - count); item2->SetCount(item2->GetCount() + count); @@ -6670,11 +6660,10 @@ bool CHARACTER::MoveItem(TItemPos Cell, TItemPos DestCell, BYTE count) sys_log(0, "%s: ITEM_SPLIT %s (window: %d, cell : %d) -> (window:%d, cell %d) count %d", GetName(), item->GetName(), Cell.window_type, Cell.cell, DestCell.window_type, DestCell.cell, count); - item->SetCount(item->GetCount() - count); - LPITEM item2 = ITEM_MANAGER::instance().CreateItem(item->GetVnum(), count); - - // copy socket -- by mhh - FN_copy_item_socket(item2, item); + LPITEM item2 = ITEM_MANAGER::instance().CreateItem(item->GetOriginalVnum(), count); + if (!item2) return false; + if (!item->CopyStackStateTo(item2)) { M2_DESTROY_ITEM(item2); return false; } + if (!item->SetCount(item->GetCount() - count)) { M2_DESTROY_ITEM(item2); return false; } item2->AddToCharacter(this, DestCell); @@ -6856,7 +6845,7 @@ bool CHARACTER::PickupItem(DWORD dwVID) { if (item->IsStackable() && !IS_SET(item->GetAntiFlag(), ITEM_ANTIFLAG_STACK)) { - BYTE bCount = item->GetCount(); + DWORD bCount = item->GetCount(); #ifdef ENABLE_SPECIAL_STORAGE BYTE specialWin = 0; @@ -6873,7 +6862,7 @@ bool CHARACTER::PickupItem(DWORD dwVID) LPITEM item2 = GetItem(TItemPos(specialWin, i)); if (!item2) continue; - if (item2->GetVnum() == item->GetVnum()) + if (item2->CanStackWith(item)) { int j; for (j = 0; j < ITEM_SOCKET_MAX_NUM; ++j) @@ -6882,12 +6871,12 @@ bool CHARACTER::PickupItem(DWORD dwVID) if (j != ITEM_SOCKET_MAX_NUM) continue; - BYTE bCount2 = MIN(200 - item2->GetCount(), bCount); + DWORD bCount2 = MIN(item2->GetStackRoom(), bCount); bCount -= bCount2; item2->SetCount(item2->GetCount() + bCount2); if (bCount == 0) { - ChatPacket(CHAT_TYPE_INFO, LC_TEXT("아이템 획득: %s"), item2->GetName()); + ChatPacket(CHAT_TYPE_INFO, LC_TEXT("\xbe\xc6\xc0\xcc\xc5\xdb \xc8\xb9\xb5\xe6: %s"), item2->GetName()); M2_DESTROY_ITEM(item); if (item2->GetType() == ITEM_QUEST) quest::CQuestManager::instance().PickupItem(GetPlayerID(), item2); @@ -6906,7 +6895,7 @@ bool CHARACTER::PickupItem(DWORD dwVID) if (!item2) continue; - if (item2->GetVnum() == item->GetVnum()) + if (item2->CanStackWith(item)) { int j; @@ -6917,14 +6906,14 @@ bool CHARACTER::PickupItem(DWORD dwVID) if (j != ITEM_SOCKET_MAX_NUM) continue; - BYTE bCount2 = MIN(200 - item2->GetCount(), bCount); + DWORD bCount2 = MIN(item2->GetStackRoom(), bCount); bCount -= bCount2; item2->SetCount(item2->GetCount() + bCount2); if (bCount == 0) { - ChatPacket(CHAT_TYPE_INFO, LC_TEXT("아이템 획득: %s"), item2->GetName()); + ChatPacket(CHAT_TYPE_INFO, LC_TEXT("\xbe\xc6\xc0\xcc\xc5\xdb \xc8\xb9\xb5\xe6: %s"), item2->GetName()); M2_DESTROY_ITEM(item); if (item2->GetType() == ITEM_QUEST) quest::CQuestManager::instance().PickupItem (GetPlayerID(), item2); @@ -7013,7 +7002,7 @@ bool CHARACTER::PickupItem(DWORD dwVID) char szHint[32+1]; snprintf(szHint, sizeof(szHint), "%s %u %u", item->GetName(), item->GetCount(), item->GetOriginalVnum()); LogManager::instance().ItemLog(this, item, "GET", szHint); - ChatPacket(CHAT_TYPE_INFO, LC_TEXT("아이템 획득: %s"), item->GetName()); + ChatPacket(CHAT_TYPE_INFO, LC_TEXT("\xbe\xc6\xc0\xcc\xc5\xdb \xc8\xb9\xb5\xe6: %s"), item->GetName()); if (item->GetType() == ITEM_QUEST) quest::CQuestManager::instance().PickupItem (GetPlayerID(), item); @@ -7072,11 +7061,11 @@ bool CHARACTER::PickupItem(DWORD dwVID) LogManager::instance().ItemLog(owner, item, "GET", szHint); if (owner == this) - ChatPacket(CHAT_TYPE_INFO, LC_TEXT("아이템 획득: %s"), item->GetName()); + ChatPacket(CHAT_TYPE_INFO, LC_TEXT("\xbe\xc6\xc0\xcc\xc5\xdb \xc8\xb9\xb5\xe6: %s"), item->GetName()); else { - owner->ChatPacket(CHAT_TYPE_INFO, LC_TEXT("아이템 획득: %s 님으로부터 %s"), GetName(), item->GetName()); - ChatPacket(CHAT_TYPE_INFO, LC_TEXT("아이템 전달: %s 님에게 %s"), owner->GetName(), item->GetName()); + owner->ChatPacket(CHAT_TYPE_INFO, LC_TEXT("\xbe\xc6\xc0\xcc\xc5\xdb \xc8\xb9\xb5\xe6: %s \xb4\xd4\xc0\xb8\xb7\xce\xba\xce\xc5\xcd %s"), GetName(), item->GetName()); + ChatPacket(CHAT_TYPE_INFO, LC_TEXT("\xbe\xc6\xc0\xcc\xc5\xdb \xc0\xfc\xb4\xde: %s \xb4\xd4\xbf\xa1\xb0\xd4 %s"), owner->GetName(), item->GetName()); } if (item->GetType() == ITEM_QUEST) @@ -7651,19 +7640,34 @@ void CHARACTER::RemoveSpecifyTypeItem(BYTE type, DWORD count) } } -void CHARACTER::AutoGiveItem(LPITEM item, bool longOwnerShip) +LPITEM CHARACTER::AutoGiveItem(LPITEM item, bool longOwnerShip) { if (NULL == item) { sys_err ("NULL point."); - return; + return NULL; } if (item->GetOwner()) { sys_err ("item %d 's owner exists!",item->GetID()); - return; + return NULL; } + if (item->IsStackable()) + { + DWORD remaining = item->GetCount(); + for (int cell = 0; cell < INVENTORY_MAX_NUM; ++cell) + { + LPITEM target = GetInventoryItem(cell); + if (!target || !target->CanStackWith(item)) continue; + const DWORD moved = std::min(remaining, target->GetStackRoom()); + if (!moved) continue; + target->SetCount(target->GetCount() + moved); + remaining -= moved; + if (!remaining) { M2_DESTROY_ITEM(item); return target; } + } + item->SetCount(remaining); + } #ifdef ENABLE_SPECIAL_STORAGE if (item->IsStackable() && !IS_SET(item->GetAntiFlag(), ITEM_ANTIFLAG_STACK)) { @@ -7682,7 +7686,7 @@ void CHARACTER::AutoGiveItem(LPITEM item, bool longOwnerShip) LPITEM item2 = GetItem(TItemPos(specialWin, i)); if (!item2) continue; - if (item2->GetVnum() == item->GetVnum()) + if (item2->CanStackWith(item)) { bool socketMatch = true; for (int s = 0; s < ITEM_SOCKET_MAX_NUM; ++s) @@ -7696,7 +7700,7 @@ void CHARACTER::AutoGiveItem(LPITEM item, bool longOwnerShip) if (!socketMatch) continue; - DWORD bCount2 = MIN(200 - item2->GetCount(), bCount); + DWORD bCount2 = MIN(item2->GetStackRoom(), bCount); bCount -= bCount2; item2->SetCount(item2->GetCount() + bCount2); if (bCount == 0) @@ -7704,7 +7708,7 @@ void CHARACTER::AutoGiveItem(LPITEM item, bool longOwnerShip) if (item2->GetType() == ITEM_QUEST || item2->GetType() == ITEM_MATERIAL) quest::CQuestManager::instance().PickupItem(GetPlayerID(), item2); M2_DESTROY_ITEM(item); - return; + return item2; } } } @@ -7783,132 +7787,44 @@ void CHARACTER::AutoGiveItem(LPITEM item, bool longOwnerShip) item->SetOwnership (this, 60); LogManager::instance().ItemLog(this, item, "SYSTEM_DROP", item->GetName()); } + return item; } -LPITEM CHARACTER::AutoGiveItem(DWORD dwItemVnum, BYTE bCount, int iRarePct, bool bMsg) +LPITEM CHARACTER::AutoGiveItem(DWORD dwItemVnum, DWORD bCount, int iRarePct, bool bMsg) { - TItemTable * p = ITEM_MANAGER::instance().GetTable(dwItemVnum); - - if (!p) - return NULL; - - DBManager::instance().SendMoneyLog(MONEY_LOG_DROP, dwItemVnum, bCount); - - if (p->dwFlags & ITEM_FLAG_STACKABLE && p->bType != ITEM_BLEND) - { - for (int i = 0; i < INVENTORY_MAX_NUM; ++i) - { - LPITEM item = GetInventoryItem(i); - - if (!item) - continue; - - if (item->GetVnum() == dwItemVnum && FN_check_item_socket(item)) - { - if (IS_SET(p->dwFlags, ITEM_FLAG_MAKECOUNT)) - { - if (bCount < p->alValues[1]) - bCount = p->alValues[1]; - } - - BYTE bCount2 = MIN(200 - item->GetCount(), bCount); - bCount -= bCount2; - - item->SetCount(item->GetCount() + bCount2); - - if (bCount == 0) - { - if (bMsg) - ChatPacket(CHAT_TYPE_INFO, LC_TEXT("아이템 획득: %s"), item->GetName()); - - return item; - } - } - } - } - - LPITEM item = ITEM_MANAGER::instance().CreateItem(dwItemVnum, bCount, 0, true); - - if (!item) - { - sys_err("cannot create item by vnum %u (name: %s)", dwItemVnum, GetName()); - return NULL; - } - - if (item->GetType() == ITEM_BLEND) - { - for (int i=0; i < INVENTORY_MAX_NUM; i++) - { - LPITEM inv_item = GetInventoryItem(i); - - if (inv_item == NULL) continue; - - if (inv_item->GetType() == ITEM_BLEND) - { - if (inv_item->GetVnum() == item->GetVnum()) - { - if (inv_item->GetSocket(0) == item->GetSocket(0) && - inv_item->GetSocket(1) == item->GetSocket(1) && - inv_item->GetSocket(2) == item->GetSocket(2) && - inv_item->GetCount() < ITEM_MAX_COUNT) - { - inv_item->SetCount(inv_item->GetCount() + item->GetCount()); - return inv_item; - } - } - } - } - } - - int iEmptyCell; - if (item->IsDragonSoul()) - { - iEmptyCell = GetEmptyDragonSoulInventory(item); - } - else - iEmptyCell = GetEmptyInventory(item->GetSize()); - - if (iEmptyCell != -1) - { - if (bMsg) - ChatPacket(CHAT_TYPE_INFO, LC_TEXT("아이템 획득: %s"), item->GetName()); - - if (item->IsDragonSoul()) - item->AddToCharacter(this, TItemPos(DRAGON_SOUL_INVENTORY, iEmptyCell)); - else - item->AddToCharacter(this, TItemPos(INVENTORY, iEmptyCell)); - LogManager::instance().ItemLog(this, item, "SYSTEM", item->GetName()); - - if (item->GetType() == ITEM_USE && item->GetSubType() == USE_POTION) - { - TQuickslot * pSlot; - - if (GetQuickslot(0, &pSlot) && pSlot->type == QUICKSLOT_TYPE_NONE) - { - TQuickslot slot; - slot.type = QUICKSLOT_TYPE_ITEM; - slot.pos = iEmptyCell; - SetQuickslot(0, slot); - } - } - } - else - { - item->AddToGround(GetMapIndex(), GetXYZ()); - item->StartDestroyEvent(); - // 안티 드랍 flag가 걸려있는 아이템의 경우, - // 인벤에 빈 공간이 없어서 어쩔 수 없이 떨어트리게 되면, - // ownership을 아이템이 사라질 때까지(300초) 유지한다. - if (IS_SET(item->GetAntiFlag(), ITEM_ANTIFLAG_DROP)) - item->SetOwnership(this, 300); - else - item->SetOwnership(this, 60); - LogManager::instance().ItemLog(this, item, "SYSTEM_DROP", item->GetName()); - } - - sys_log(0, - "7: %d %d", dwItemVnum, bCount); - return item; + const TItemTable* proto = ITEM_MANAGER::instance().GetTable(dwItemVnum); + if (!proto || !bCount) return NULL; + unsigned limit = PortMaterialStackPolicy::GrantLimit(proto->bType, + (proto->dwFlags & ITEM_FLAG_STACKABLE) != 0, + (proto->dwAntiFlags & ITEM_ANTIFLAG_STACK) != 0, dwItemVnum); + if ((PortMaterialStackPolicy::LegacyGrowthMode() || quest::CQuestManager::instance().GetEventFlag("material_stack_legacy_mode"))) + limit = std::min(limit, 200u); + if ((proto->dwFlags & ITEM_FLAG_MAKECOUNT) && proto->alValues[1] > 0) + bCount = std::max(bCount, DWORD(proto->alValues[1])); + LPITEM result = NULL; + while (bCount) + { + const DWORD chunk = std::min(bCount, limit); + LPITEM item = ITEM_MANAGER::instance().CreateItem(dwItemVnum, chunk, 0, true, iRarePct); + if (!item) { sys_err("AutoGiveItem failed: vnum %u remaining %u", dwItemVnum, bCount); return result; } + if (item->GetCount() != chunk && !item->SetCount(chunk)) { M2_DESTROY_ITEM(item); return result; } + result = AutoGiveItem(item); + if (!result) { M2_DESTROY_ITEM(item); return NULL; } + DBManager::instance().SendMoneyLog(MONEY_LOG_DROP, dwItemVnum, chunk); + bCount -= chunk; + } + if (result && bMsg) + ChatPacket(CHAT_TYPE_INFO, LC_TEXT("아이템 획득: %s"), result->GetName()); + if (result && result->GetWindow() == INVENTORY && result->GetType() == ITEM_USE && result->GetSubType() == USE_POTION) + { + TQuickslot* slot; + if (GetQuickslot(0, &slot) && slot->type == QUICKSLOT_TYPE_NONE) + { + TQuickslot newSlot; newSlot.type = QUICKSLOT_TYPE_ITEM; newSlot.pos = result->GetCell(); + SetQuickslot(0, newSlot); + } + } + return result; } bool CHARACTER::GiveItem(LPCHARACTER victim, TItemPos Cell) diff --git a/src/server/game/src/cube.cpp b/src/server/game/src/cube.cpp index bf8ce4e2..3dd56708 100755 --- a/src/server/game/src/cube.cpp +++ b/src/server/game/src/cube.cpp @@ -8,6 +8,7 @@ #define _cube_cpp_ #include "stdafx.h" +#include "port_material_stack_policy.h" #include "port_cube_actor.h" #include "constants.h" #include "utils.h" @@ -369,6 +370,7 @@ void Cube_init() } s_cube_proto.clear(); + PortMaterialStackPolicy::CubeIngredients().clear(); if (false == Cube_load(file_name)) sys_err("Cube_Init failed"); @@ -461,6 +463,8 @@ bool Cube_load (const char *file) continue; } s_cube_proto.push_back(cube_data); + for (const auto& material : cube_data->item) + PortMaterialStackPolicy::CubeIngredients().insert(material.vnum); } } diff --git a/src/server/game/src/input_login.cpp b/src/server/game/src/input_login.cpp index 0770695f..e453b5ec 100755 --- a/src/server/game/src/input_login.cpp +++ b/src/server/game/src/input_login.cpp @@ -1,4 +1,5 @@ #include "stdafx.h" +#include "port_material_stack_policy.h" #include "port_cheque.h" #include "constants.h" #include "../../common/teen_packet.h" @@ -97,10 +98,19 @@ static bool FN_is_battle_zone(LPCHARACTER ch) void CInputLogin::Login(LPDESC d, const char * data) { + const char* stackRevision = strstr(d->GetClientVersion(), "mt"); + if (!stackRevision || atoi(stackRevision + 2) < 20261030) { + LoginFailure(d, "VERSION"); d->DelayedDisconnect(1); return; + } + TPacketCGLogin * pinfo = (TPacketCGLogin *) data; char login[LOGIN_MAX_LEN + 1]; trim_and_lower(pinfo->login, login, sizeof(login)); + if (!PortMaterialStackPolicy::QAAllowed(login)) { + LoginFailure(d, "SHUTDOWN"); d->DelayedDisconnect(1); return; + } + sys_log(0, "InputLogin::Login : %s", login); @@ -149,10 +159,19 @@ void CInputLogin::Login(LPDESC d, const char * data) void CInputLogin::LoginByKey(LPDESC d, const char * data) { + const char* stackRevision = strstr(d->GetClientVersion(), "mt"); + if (!stackRevision || atoi(stackRevision + 2) < 20261030) { + LoginFailure(d, "VERSION"); d->DelayedDisconnect(1); return; + } + TPacketCGLogin2 * pinfo = (TPacketCGLogin2 *) data; char login[LOGIN_MAX_LEN + 1]; trim_and_lower(pinfo->login, login, sizeof(login)); + if (!PortMaterialStackPolicy::QAAllowed(login)) { + LoginFailure(d, "SHUTDOWN"); d->DelayedDisconnect(1); return; + } + // is blocked ip? { @@ -247,6 +266,13 @@ void CInputLogin::ChangeName(LPDESC d, const char * data) void CInputLogin::CharacterSelect(LPDESC d, const char * data) { + const char* revision = strstr(d->GetClientVersion(), "mt"); + if (!revision || atoi(revision + 2) < 20261030) { + LoginFailure(d, "VERSION"); + d->DelayedDisconnect(1); + return; + } + struct command_player_select * pinfo = (struct command_player_select *) data; const TAccountTable & c_r = d->GetAccountTable(); @@ -573,7 +599,7 @@ void CInputLogin::Entergame(LPDESC d, const char * data) { // PORT: wear40 moves dragon-soul/belt cells; mt20261029 adds the conqueror fields and five slots; older clients must not enter this world. const char* revision=strstr(d->GetClientVersion(),"mt"); - if(!revision || atoi(revision+2)<20261029) + if(!revision || atoi(revision+2)<20261030) { if(d->GetCharacter())d->GetCharacter()->ChatPacket(CHAT_TYPE_INFO,"Please update the client before entering the game."); d->DelayedDisconnect(1);return; @@ -1148,11 +1174,23 @@ int CInputLogin::Analyze(LPDESC d, BYTE bHeader, const char * c_pData) break; case HEADER_CG_CLIENT_VERSION: - Version(d->GetCharacter(), c_pData); + { + // Version is now sent before character selection; no actor exists yet. + const auto* packet = reinterpret_cast(c_pData); + char timestamp[sizeof(packet->timestamp) + 1] = {}; + memcpy(timestamp, packet->timestamp, sizeof(packet->timestamp)); + d->SetClientVersion(timestamp); + } break; case HEADER_CG_CLIENT_VERSION2: - Version(d->GetCharacter(), c_pData); + { + // Version is now sent before character selection; no actor exists yet. + const auto* packet = reinterpret_cast(c_pData); + char timestamp[sizeof(packet->timestamp) + 1] = {}; + memcpy(timestamp, packet->timestamp, sizeof(packet->timestamp)); + d->SetClientVersion(timestamp); + } break; // case HEADER_CG_HS_ACK: diff --git a/src/server/game/src/input_main.cpp b/src/server/game/src/input_main.cpp index 4a74207a..bc3b944a 100755 --- a/src/server/game/src/input_main.cpp +++ b/src/server/game/src/input_main.cpp @@ -1076,15 +1076,16 @@ int CInputMain::Shop(LPCHARACTER ch, const char * data, size_t uiBytes) case SHOP_SUBHEADER_CG_SELL2: { - if (uiBytes < sizeof(BYTE) + sizeof(BYTE)) + if (uiBytes < sizeof(BYTE) + sizeof(WORD)) return -1; BYTE pos = *(c_pData++); - BYTE count = *(c_pData); + WORD count = 0; + memcpy(&count, c_pData, sizeof(count)); sys_log(0, "INPUT: %s SHOP: SELL2", ch->GetName()); CShopManager::instance().Sell(ch, pos, count); - return sizeof(BYTE) + sizeof(BYTE); + return sizeof(BYTE) + sizeof(WORD); } default: diff --git a/src/server/game/src/item.cpp b/src/server/game/src/item.cpp index feaf0152..f905a3d6 100755 --- a/src/server/game/src/item.cpp +++ b/src/server/game/src/item.cpp @@ -1,4 +1,6 @@ #include "stdafx.h" +#include "port_material_stack_policy.h" +#include "questmanager.h" #include "port_cube_actor.h" #include "../../common/cube_mutation.h" #include "../../common/economy.h" @@ -227,6 +229,19 @@ void CItem::UpdatePacket() if (m_bWindow == SWITCHBOT) return; + if (m_bWindow == SAFEBOX || m_bWindow == MALL) + { + TPacketGCItemSet packet = {}; + packet.header = m_bWindow == SAFEBOX ? HEADER_GC_SAFEBOX_SET : HEADER_GC_MALL_SET; + packet.Cell = TItemPos(m_bWindow, m_wCell); + packet.vnum = GetVnum(); packet.count = GetCount(); + packet.flags = GetFlag(); packet.anti_flags = GetAntiFlag(); + memcpy(packet.alSockets, m_alSockets, sizeof(packet.alSockets)); + memcpy(packet.aAttr, m_aAttr, sizeof(packet.aAttr)); + m_pOwner->GetDesc()->Packet(&packet, sizeof(packet)); + SendPortExtra(); + return; + } TPacketGCItemUpdate pack; pack.header = HEADER_GC_ITEM_UPDATE; @@ -244,13 +259,62 @@ void CItem::UpdatePacket() SendPortExtra(); } +unsigned CItem::GetStackLimit() const +{ + return m_pProto ? PortMaterialStackPolicy::Limit(m_pProto->bType, + (m_lFlag & ITEM_FLAG_STACKABLE) != 0, + (m_pProto->dwAntiFlags & ITEM_ANTIFLAG_STACK) != 0, m_pProto->dwVnum) : 1; +} + +unsigned CItem::GetStackRoom() +{ + // Rollback disables growth while retaining wide-count reads and deductions. + unsigned limit = GetStackLimit(); + if ((PortMaterialStackPolicy::LegacyGrowthMode() || quest::CQuestManager::instance().GetEventFlag("material_stack_legacy_mode"))) + limit = std::min(limit, 200u); + return GetCount() < limit ? limit - GetCount() : 0; +} + +bool CItem::CanStackWith(const CItem* other) const +{ + if (!other || !m_pProto || !other->m_pProto || + m_dwVnum != other->m_dwVnum || m_dwMaskVnum != other->m_dwMaskVnum || + m_dwSIGVnum != other->m_dwSIGVnum || m_lFlag != other->m_lFlag || + !(m_lFlag & ITEM_FLAG_STACKABLE) || !(other->m_lFlag & ITEM_FLAG_STACKABLE) || + ((m_pProto->dwAntiFlags | other->m_pProto->dwAntiFlags) & ITEM_ANTIFLAG_STACK) || + m_bExchanging || other->m_bExchanging || m_isLocked || other->m_isLocked) + return false; + CItem* self = const_cast(this); + CItem* source = const_cast(other); + const unsigned mask = PortAttrLockGet(self); + const unsigned otherMask = PortAttrLockGet(source); + if (!self->m_portAttrLockLoaded || !source->m_portAttrLockLoaded) return false; + return !memcmp(m_alSockets, other->m_alSockets, sizeof(m_alSockets)) && + !memcmp(m_aAttr, other->m_aAttr, sizeof(m_aAttr)) && + !memcmp(&m_portExtra, &other->m_portExtra, sizeof(m_portExtra)) && + mask == otherMask; +} + +bool CItem::CopyStackStateTo(CItem* target) +{ + if (!target || target->GetOriginalVnum() != GetOriginalVnum()) return false; + const unsigned mask = PortAttrLockGet(this); + if (!m_portAttrLockLoaded) return false; + target->SetSockets(GetSockets()); + CopyAttributeTo(target); + target->SetPortExtra(GetPortExtra()); + target->m_lFlag = m_lFlag; + target->m_dwMaskVnum = m_dwMaskVnum; + target->m_dwSIGVnum = m_dwSIGVnum; + if (mask && !PortAttrLockSet(NULL, target, mask)) return false; + target->m_portAttrLockLoaded = true; + return true; +} + DWORD CItem::GetCount() { - if (GetType() == ITEM_ELK) return MIN(m_dwCount, INT_MAX); - else - { - return MIN(m_dwCount, 200); - } + // Never truncate saved counts while loading, transferring, or rolling back. + return m_dwCount; } bool CItem::SetCount(DWORD count) @@ -261,7 +325,8 @@ bool CItem::SetCount(DWORD count) } else { - m_dwCount = MIN(count, ITEM_MAX_COUNT); + if (count > GetStackLimit()) return false; + m_dwCount = count; } if (count == 0 && m_pOwner) @@ -449,7 +514,7 @@ void CItem::PortCubeInitNewAttach() bool CItem::PortCubeRestoreMetadata(const PortEconomy::Reward& r) { if(!m_portCubeTemplate||m_pOwner||GetSectree()||r.id!=GetID()||r.vnum!=GetOriginalVnum()|| - !r.count||r.count>ITEM_MAX_COUNT||(!IsStackable()&&r.count!=1))return false; + !r.count||r.count>GetStackLimit()||(!IsStackable()&&r.count!=1))return false; m_dwCount=r.count; for(unsigned i=0;i<3;++i)m_alSockets[i]=r.sockets[i]; for(unsigned i=0;i<7;++i){m_aAttr[i].bType=r.types[i];m_aAttr[i].sValue=r.values[i];} diff --git a/src/server/game/src/item.h b/src/server/game/src/item.h index 5324415d..af6f4030 100755 --- a/src/server/game/src/item.h +++ b/src/server/game/src/item.h @@ -23,6 +23,11 @@ class CItem : public CEntity long FindApplyValue(BYTE bApplyType); + unsigned GetStackLimit() const; + unsigned GetStackRoom(); + bool CanStackWith(const CItem* other) const; + bool CopyStackStateTo(CItem* target); + bool IsStackable() { return (GetFlag() & ITEM_FLAG_STACKABLE)?true:false; } void Initialize(); diff --git a/src/server/game/src/item_manager.cpp b/src/server/game/src/item_manager.cpp index c1ee78ce..15403a5d 100755 --- a/src/server/game/src/item_manager.cpp +++ b/src/server/game/src/item_manager.cpp @@ -18,6 +18,7 @@ #include "item.h" #include "item_manager.h" #include "port_cube_factory.h" +#include "port_material_stack_policy.h" #include "mob_manager.h" #include "port_calendar_runtime.h" @@ -190,6 +191,12 @@ LPITEM ITEM_MANAGER::CreateItem(DWORD vnum, DWORD count, DWORD id, bool bTryMagi if (NULL == table) return NULL; + const unsigned stackLimit = PortMaterialStackPolicy::Limit(table->bType, + (table->dwFlags & ITEM_FLAG_STACKABLE) != 0, + (table->dwAntiFlags & ITEM_ANTIFLAG_STACK) != 0, table->dwVnum); + if (table->bType != ITEM_ELK && (table->dwFlags & ITEM_FLAG_STACKABLE) && (!count || count > stackLimit)) return NULL; + if (!id && table->bType != ITEM_ELK && count > 200 && + (PortMaterialStackPolicy::LegacyGrowthMode() || quest::CQuestManager::instance().GetEventFlag("material_stack_legacy_mode"))) return NULL; LPITEM item = NULL; @@ -274,7 +281,7 @@ LPITEM ITEM_MANAGER::CreateItem(DWORD vnum, DWORD count, DWORD id, bool bTryMagi ; else if (item->IsStackable()) // ÇÕĥ ¼ö Àִ ¾ÆÀÌÅÛÀÇ °æ¿ì { - count = MINMAX(1, count, ITEM_MAX_COUNT); + if (bTryMagic && count <= 1 && IS_SET(item->GetFlag(), ITEM_FLAG_MAKECOUNT)) count = item->GetValue(1); @@ -282,6 +289,9 @@ LPITEM ITEM_MANAGER::CreateItem(DWORD vnum, DWORD count, DWORD id, bool bTryMagi else count = 1; + if (table->bType != ITEM_ELK && (!count || count > stackLimit)) { + M2_DESTROY_ITEM(item); return NULL; + } if(!cubeSlot)item->SetVID(++m_dwVIDCount); if (bSkipSave == false) @@ -623,7 +633,7 @@ TItemTable * ITEM_MANAGER::GetTable(DWORD vnum) return p; } } - + return NULL; } @@ -1007,7 +1017,7 @@ bool ITEM_MANAGER::CreateDropItem(LPCHARACTER pkChr, LPCHARACTER pkKiller, std:: } } } - + // BuyerTheitGloves Item Group { if (pkKiller->GetPremiumRemainSeconds(PREMIUM_ITEM) > 0 || @@ -1034,7 +1044,7 @@ bool ITEM_MANAGER::CreateDropItem(LPCHARACTER pkChr, LPCHARACTER pkKiller, std:: } } } - + // ÀâÅÛ if (pkChr->GetMobDropItemVnum()) { @@ -1615,7 +1625,7 @@ void ITEM_MANAGER::CreateQuestDropItem(LPCHARACTER pkChr, LPCHARACTER pkKiller, if ( (item=CreateItem(halloween_item, 1, 0, true)) ) vec_item.push_back(item); } - + if ( GetDropPerKillPct(100, g_iUseLocale ? 2000 : 800, iDeltaPercent, "ramadan_drop") >= number(1, iRandRange) ) { const static DWORD ramadan_item = 30315; diff --git a/src/server/game/src/main.cpp b/src/server/game/src/main.cpp index a74b51e5..6fb65fdc 100755 --- a/src/server/game/src/main.cpp +++ b/src/server/game/src/main.cpp @@ -33,6 +33,10 @@ #include "cmd.h" #include "refine.h" #include "banword.h" + +#ifndef __FreeBSD__ +static int optreset; +#endif #include "priv_manager.h" #include "war_map.h" #include "building.h" @@ -725,7 +729,7 @@ int start(int argc, char **argv) std::string st_localeServiceName; bool bVerbose = false; - char ch; + int ch; //_malloc_options = "A"; #if defined(__FreeBSD__) && defined(DEBUG_ALLOC) diff --git a/src/server/game/src/packet.h b/src/server/game/src/packet.h index 1f39a389..d5a391fc 100755 --- a/src/server/game/src/packet.h +++ b/src/server/game/src/packet.h @@ -748,7 +748,7 @@ typedef struct command_item_drop2 BYTE header; TItemPos Cell; DWORD gold; - BYTE count; + WORD count; } TPacketCGItemDrop2; typedef struct command_item_move @@ -756,7 +756,7 @@ typedef struct command_item_move BYTE header; TItemPos Cell; TItemPos CellTo; - BYTE count; + WORD count; } TPacketCGItemMove; typedef struct command_item_pickup @@ -816,7 +816,7 @@ typedef struct command_shop_buy typedef struct command_shop_sell { BYTE pos; - BYTE count; + WORD count; } TPacketCGShopSell; typedef struct command_shop @@ -1204,7 +1204,7 @@ struct TPacketGCItemDelDeprecated BYTE header; TItemPos Cell; DWORD vnum; - BYTE count; + WORD count; long alSockets[ITEM_SOCKET_MAX_NUM]; TPlayerItemAttribute aAttr[ITEM_ATTRIBUTE_MAX_NUM]; }; @@ -1214,7 +1214,7 @@ typedef struct packet_item_set BYTE header; TItemPos Cell; DWORD vnum; - BYTE count; + WORD count; DWORD flags; DWORD anti_flags; bool highlight; @@ -1327,7 +1327,7 @@ typedef struct packet_item_update { BYTE header; TItemPos Cell; - BYTE count; + WORD count; long alSockets[ITEM_SOCKET_MAX_NUM]; TPlayerItemAttribute aAttr[ITEM_ATTRIBUTE_MAX_NUM]; } TPacketGCItemUpdate; @@ -1414,12 +1414,12 @@ struct packet_shop_item { DWORD vnum; int64_t price; - BYTE count; + WORD count; BYTE display_pos; int32_t alSockets[ITEM_SOCKET_MAX_NUM]; TPlayerItemAttribute aAttr[ITEM_ATTRIBUTE_MAX_NUM]; }; -static_assert(sizeof(packet_shop_item)==47,"gold64 shop item wire size"); +static_assert(sizeof(packet_shop_item)==48,"gold64 shop item wire size"); typedef struct packet_shop_start { @@ -2066,7 +2066,7 @@ typedef struct command_give_item BYTE byHeader; DWORD dwTargetVID; TItemPos ItemPos; - BYTE byItemCount; + WORD byItemCount; } TPacketCGGiveItem; typedef struct SPacketCGHack @@ -2318,7 +2318,7 @@ typedef struct pakcet_view_equip DWORD vid; struct { DWORD vnum; - BYTE count; + WORD count; long alSockets[ITEM_SOCKET_MAX_NUM]; TPlayerItemAttribute aAttr[ITEM_ATTRIBUTE_MAX_NUM]; } equips[WEAR_MAX_NUM]; @@ -2754,3 +2754,10 @@ static_assert(sizeof(TPacketGCCubeRenewalReceive)==167,"AVA2 GC221 size"); #pragma pack() #endif + +// PORT mt20261030: actual item quantities are uint16 on the client wire. +static_assert(sizeof(TPacketCGItemMove) == 9, "wide item move"); +static_assert(sizeof(TPacketCGItemDrop2) == 10, "wide item drop"); +static_assert(sizeof(TPacketCGGiveItem) == 10, "wide give item"); +static_assert(sizeof(TPacketGCItemSet) == 52, "wide item set"); +static_assert(sizeof(TPacketGCItemUpdate) == 39, "wide item update"); diff --git a/src/server/game/src/port_battlepass_runtime.h b/src/server/game/src/port_battlepass_runtime.h index 105cfc21..c96953b3 100644 --- a/src/server/game/src/port_battlepass_runtime.h +++ b/src/server/game/src/port_battlepass_runtime.h @@ -3,6 +3,7 @@ // PORT: battle pass, game side (port_battlepass.h has the config and state). Protocol: docs/FEATURE-BATTLEPASS.md. // Included once, by cmd_general.cpp; the hooks in other files go through port_battlepass_hooks.h. #include +#include "port_material_stack_policy.h" #include #include #include @@ -215,7 +216,7 @@ inline const char* PortBpStacks(const std::vector& rewards,std::ve if(!table || table->bType==ITEM_DS || !table->bSize || table->bSize>3)return "config"; const bool stackable=IS_SET(table->dwFlags,ITEM_FLAG_STACKABLE) && !IS_SET(table->dwAntiFlags,ITEM_ANTIFLAG_STACK); for(unsigned left=r.count;left;) { - const unsigned count=stackable?std::min(left,ITEM_MAX_COUNT):1; + const unsigned count=stackable?std::min(left,PortMaterialStackPolicy::Limit(table->bType,true,false,r.vnum)):1; stacks.push_back(PortBpStack{r.vnum,count,table->bSize});left-=count; if(stacks.size()>kPortBpMaxStacks)return "config"; } diff --git a/src/server/game/src/port_cube_renewal.inc b/src/server/game/src/port_cube_renewal.inc index 1ce935e8..db211eaf 100644 --- a/src/server/game/src/port_cube_renewal.inc +++ b/src/server/game/src/port_cube_renewal.inc @@ -179,9 +179,12 @@ void CubeRenewal_Make(LPCHARACTER ch, DWORD index, DWORD count) const CUBE_VALUE& reward = data.reward[0]; const bool stackable = FN_cube_renewal_stackable(reward.vnum); - // One item stack per make: stackable rewards up to ITEM_MAX_COUNT, others one at a time. + const auto* rewardProto = ITEM_MANAGER::instance().GetTable(reward.vnum); + const unsigned rewardLimit = rewardProto ? PortMaterialStackPolicy::GrantLimit(rewardProto->bType, + stackable, false, reward.vnum) : 0; + // One item stack per make, using the reward's actual item-level limit. if (count < 1 || reward.count < 1 || (!stackable && count != 1) || - static_cast(reward.count) * count > ITEM_MAX_COUNT) + static_cast(reward.count) * count > rewardLimit) { ch->ChatPacket(CHAT_TYPE_INFO, LC_TEXT("You can't create that many at once.")); return; diff --git a/src/server/game/src/port_material_stack_policy.h b/src/server/game/src/port_material_stack_policy.h new file mode 100644 index 00000000..49c13aba --- /dev/null +++ b/src/server/game/src/port_material_stack_policy.h @@ -0,0 +1,72 @@ +#pragma once + +// Revision mt20261030: item-level stack limits. +// Include the server fixed-width typedefs before this header. + +#include +#include +#include +#include +#include "../../common/length.h" +#include "../../common/item_length.h" + +namespace PortMaterialStackPolicy +{ +constexpr unsigned kLegacyLimit = 200; +constexpr unsigned kMaterialLimit = 2000; + +inline bool IsMaterialOrConsumable(unsigned type) +{ + switch (type) + { + case ITEM_USE: // Includes 71084 / 71085 attribute scrolls. + case ITEM_AUTOUSE: + case ITEM_MATERIAL: + case ITEM_METIN: // Socket stones when marked stackable. + case ITEM_RESOURCE: + case ITEM_BLEND: + case ITEM_EXTRACT: + return true; + default: + return false; + } +} + +inline std::set& RefineIngredients() { static std::set values; return values; } +inline std::set& CubeIngredients() { static std::set values; return values; } + +inline bool QAAllowed(const char* login) +{ + const char* setting = std::getenv("PORT_MATERIAL_STACK_QA_LOGIN"); + if (!setting || !*setting) return true; + const std::string list(setting); + for (size_t begin = 0; begin <= list.size();) { + const size_t end = list.find(',', begin); + if (list.substr(begin, end == std::string::npos ? end : end - begin) == login) return true; + if (end == std::string::npos) break; + begin = end + 1; + } + return false; +} + +inline bool LegacyGrowthMode() +{ + const char* setting = std::getenv("PORT_MATERIAL_STACK_LEGACY_MODE"); + return setting && !std::strcmp(setting, "1"); +} + +inline unsigned Limit(unsigned type, bool stackable, bool antiStack, unsigned vnum = 0) +{ + // Preserve the historical storage limit even for non-mergeable legacy rows. + // Actual creation/merging still enforces the proto's stack flags. + if (!stackable || antiStack) + return kLegacyLimit; + return IsMaterialOrConsumable(type) || RefineIngredients().count(vnum) || CubeIngredients().count(vnum) + ? kMaterialLimit : kLegacyLimit; +} +inline unsigned GrantLimit(unsigned type, bool stackable, bool antiStack, unsigned vnum = 0) +{ + return stackable && !antiStack ? Limit(type, true, false, vnum) : 1; +} + +} diff --git a/src/server/game/src/port_refine_materials.h b/src/server/game/src/port_refine_materials.h new file mode 100644 index 00000000..5807aad6 --- /dev/null +++ b/src/server/game/src/port_refine_materials.h @@ -0,0 +1,39 @@ +#pragma once +// Included after character/item/shop declarations. Both NPC and scroll refinement +// consume from the same usable inventory windows as material rewards. +inline bool PortRefineTakeMaterials(LPCHARACTER ch, const TRefineTable* recipe) +{ + if (!ch || !recipe) return false; + std::map required; + for (unsigned i=0; imaterial_count; ++i) { + const auto& material=recipe->materials[i]; + if (!material.vnum || !material.count) return false; + required[material.vnum] += uint64_t(material.count); + } + std::vector> deductions; + for (const auto& need:required) { + uint64_t remaining=need.second; + const BYTE windows[]={INVENTORY, +#ifdef ENABLE_SPECIAL_STORAGE + UPGRADE_INVENTORY,BOOK_INVENTORY,STONE_INVENTORY,CHANGE_INVENTORY,COSTUME_INVENTORY, +#endif + }; + for (BYTE window:windows) { + const unsigned size=window==INVENTORY?INVENTORY_MAX_NUM:SPECIAL_INVENTORY_MAX_NUM; + for (unsigned cell=0; cellGetItem(TItemPos(window,cell)); + if (!item || item->GetCell()!=cell || item->GetVnum()!=need.first || + item->GetOwner()!=ch || item->IsEquipped() || item->IsExchanging() || + item->isLocked() || item->GetSkipSave() || + (ch->GetMyShop() && ch->GetMyShop()->IsSellingItem(item->GetID()))) continue; + const DWORD used=static_cast(std::min(remaining,item->GetCount())); + if (used) deductions.emplace_back(item,used); + remaining-=used; + } + } + if (remaining) return false; // Nothing has been deducted yet. + } + for (const auto& debit:deductions) + debit.first->SetCount(debit.first->GetCount()-debit.second); + return true; +} diff --git a/src/server/game/src/refine.cpp b/src/server/game/src/refine.cpp index 8a11d3e1..2a11afa3 100755 --- a/src/server/game/src/refine.cpp +++ b/src/server/game/src/refine.cpp @@ -1,5 +1,6 @@ #include "stdafx.h" #include "refine.h" +#include "port_material_stack_policy.h" CRefineManager::CRefineManager() { @@ -11,10 +12,13 @@ CRefineManager::~CRefineManager() bool CRefineManager::Initialize(TRefineTable * table, int size) { + PortMaterialStackPolicy::RefineIngredients().clear(); for (int i = 0; i < size; ++i, ++table) { sys_log(0, "REFINE %d prob %d cost %d", table->id, table->prob, table->cost); m_map_RefineRecipe.insert(std::make_pair(table->id, *table)); + for (unsigned j = 0; j < table->material_count; ++j) + PortMaterialStackPolicy::RefineIngredients().insert(table->materials[j].vnum); } sys_log(0, "REFINE: COUNT %d", m_map_RefineRecipe.size()); diff --git a/src/server/game/src/safebox.cpp b/src/server/game/src/safebox.cpp index 066996a1..4b8286ab 100755 --- a/src/server/game/src/safebox.cpp +++ b/src/server/game/src/safebox.cpp @@ -68,7 +68,7 @@ bool CSafebox::Add(DWORD dwPos, LPITEM pkItem) m_pkGrid->Put(dwPos, 1, pkItem->GetSize()); m_pkItems[dwPos] = pkItem; - TPacketGCItemSet pack; + TPacketGCItemSet pack = {}; pack.header = m_bWindowMode == SAFEBOX ? HEADER_GC_SAFEBOX_SET : HEADER_GC_MALL_SET; pack.Cell = TItemPos(m_bWindowMode, dwPos); @@ -167,7 +167,7 @@ LPITEM CSafebox::GetItem(BYTE bCell) return m_pkItems[bCell]; } -bool CSafebox::MoveItem(BYTE bCell, BYTE bDestCell, BYTE count) +bool CSafebox::MoveItem(BYTE bCell, BYTE bDestCell, DWORD count) { LPITEM item; @@ -190,7 +190,7 @@ bool CSafebox::MoveItem(BYTE bCell, BYTE bDestCell, BYTE count) if ((item2 = GetItem(bDestCell)) && item != item2 && item2->IsStackable() && !IS_SET(item2->GetAntiFlag(), ITEM_ANTIFLAG_STACK) && - item2->GetVnum() == item->GetVnum()) // ÇÕĥ ¼ö Àִ ¾ÆÀÌÅÛÀÇ °æ¿ì + item2->CanStackWith(item)) // ÇÕĥ ¼ö Àִ ¾ÆÀÌÅÛÀÇ °æ¿ì { for (int i = 0; i < ITEM_SOCKET_MAX_NUM; ++i) if (item2->GetSocket(i) != item->GetSocket(i)) @@ -199,9 +199,10 @@ bool CSafebox::MoveItem(BYTE bCell, BYTE bDestCell, BYTE count) if (count == 0) count = item->GetCount(); - count = MIN(200 - item2->GetCount(), count); + count = MIN(item2->GetStackRoom(), count); - if (item->GetCount() >= count) + if (count == 0) return false; + if (item->GetCount() == count) Remove(bCell); item->SetCount(item->GetCount() - count); @@ -213,6 +214,16 @@ bool CSafebox::MoveItem(BYTE bCell, BYTE bDestCell, BYTE count) if (!IsEmpty(bDestCell, item->GetSize())) return false; + if (count && count < item->GetCount() && item->IsStackable() && + !(item->GetAntiFlag() & ITEM_ANTIFLAG_STACK)) + { + LPITEM split = ITEM_MANAGER::instance().CreateItem(item->GetOriginalVnum(), count); + if (!split) return false; + if (!item->CopyStackStateTo(split)) { M2_DESTROY_ITEM(split); return false; } + if (!Add(bDestCell, split)) { M2_DESTROY_ITEM(split); return false; } + item->SetCount(item->GetCount() - count); + return true; + } m_pkGrid->Get(bCell, 1, item->GetSize()); diff --git a/src/server/game/src/safebox.h b/src/server/game/src/safebox.h index baa2780e..9fec4223 100755 --- a/src/server/game/src/safebox.h +++ b/src/server/game/src/safebox.h @@ -16,7 +16,7 @@ class CSafebox LPITEM Remove(DWORD dwPos); void ChangeSize(int iSize); - bool MoveItem(BYTE bCell, BYTE bDestCell, BYTE count); + bool MoveItem(BYTE bCell, BYTE bDestCell, DWORD count); LPITEM GetItem(BYTE bCell); int64_t GetGold() const { return m_lGold; } diff --git a/src/server/game/src/shop.h b/src/server/game/src/shop.h index ca6b0ddd..516a5d2e 100755 --- a/src/server/game/src/shop.h +++ b/src/server/game/src/shop.h @@ -16,7 +16,7 @@ class CShop { DWORD vnum; // ¾ÆÀÌÅÛ ¹øȣ int64_t price; // °¡°Ý - BYTE count; // ¾ÆÀÌÅÛ °³¼ö + DWORD count; // ¾ÆÀÌÅÛ °³¼ö LPITEM pkItem; int cheque; // PORT: Won price (PC shops only) diff --git a/src/server/game/src/shop_manager.cpp b/src/server/game/src/shop_manager.cpp index f9faf063..9f923cd3 100755 --- a/src/server/game/src/shop_manager.cpp +++ b/src/server/game/src/shop_manager.cpp @@ -260,7 +260,7 @@ void CShopManager::Buy(LPCHARACTER ch, BYTE pos) } } -void CShopManager::Sell(LPCHARACTER ch, BYTE bCell, BYTE bCount) +void CShopManager::Sell(LPCHARACTER ch, BYTE bCell, DWORD bCount) { if (Ava2IsTicketShop(ch->GetShop())) return; if (!ch->GetShop()) @@ -302,8 +302,8 @@ void CShopManager::Sell(LPCHARACTER ch, BYTE bCell, BYTE bCount) int64_t dwPrice; - if (bCount == 0 || bCount > item->GetCount()) - bCount = item->GetCount(); + if (bCount > item->GetCount()) return; + if (bCount == 0) bCount = item->GetCount(); dwPrice = item->GetShopBuyPrice(); diff --git a/src/server/game/src/shop_manager.h b/src/server/game/src/shop_manager.h index b6cce030..38410e86 100755 --- a/src/server/game/src/shop_manager.h +++ b/src/server/game/src/shop_manager.h @@ -23,7 +23,7 @@ public: void StopShopping(LPCHARACTER ch); void Buy(LPCHARACTER ch, BYTE pos); - void Sell(LPCHARACTER ch, BYTE bCell, BYTE bCount=0); + void Sell(LPCHARACTER ch, BYTE bCell, DWORD bCount=0); LPSHOP CreatePCShop(LPCHARACTER ch, TShopItemTable * pTable, BYTE bItemCount, const int32_t * pCheque = NULL); LPSHOP FindPCShop(DWORD dwVID); diff --git a/src/server/game/src/stdafx.h b/src/server/game/src/stdafx.h index f2e2226b..34cf802f 100755 --- a/src/server/game/src/stdafx.h +++ b/src/server/game/src/stdafx.h @@ -13,6 +13,7 @@ #include "../../common/service.h" #include +#include #include #include #include diff --git a/src/server/libgame/src/Makefile b/src/server/libgame/src/Makefile index 2d447117..7c37fe7b 100755 --- a/src/server/libgame/src/Makefile +++ b/src/server/libgame/src/Makefile @@ -1,8 +1,8 @@ -CXX = clang++-devel +CXX ?= clang++-devel BIN_DIR = ../lib BIN = $(BIN_DIR)/libgame.a -CFLAGS = -Wall -O2 -pipe -mtune=i686 -fno-exceptions -I../include +CFLAGS ?= -Wall -O2 -pipe -fno-exceptions -I../include LIBS = diff --git a/src/server/libpoly/Makefile b/src/server/libpoly/Makefile index c6a84b48..41439056 100755 --- a/src/server/libpoly/Makefile +++ b/src/server/libpoly/Makefile @@ -1,9 +1,7 @@ -CXX = clang++-devel +CXX ?= clang++-devel BIN = ./libpoly.a -GCC_VERSION = $(shell $(CC) --version 2>&1 | grep "(GCC)" | cut -d' ' -f3 | cut -d'.' -f1) - -CFLAGS = -Wall -O2 -pipe -mtune=i686 -D_GLIBCXX_USE_CXX11_ABI=1 -fno-exceptions -fno-rtti +CFLAGS ?= -Wall -O2 -pipe -D_GLIBCXX_USE_CXX11_ABI=1 -fno-exceptions -fno-rtti LIBS = diff --git a/src/server/libserverkey/Makefile b/src/server/libserverkey/Makefile index d8cdf9d1..7c785bf6 100755 --- a/src/server/libserverkey/Makefile +++ b/src/server/libserverkey/Makefile @@ -1,21 +1,9 @@ -#CXX = distcc i386-obrien-freebsd5-g++ -CXX = clang++-devel - -PLATFORM = $(shell file /bin/ls | cut -d' ' -f3 | cut -d'-' -f1) - -GCC_VERSION = $(shell $(CC) --version 2>&1 | grep "(GCC)" | cut -d' ' -f3 | cut -d'.' -f1) -BSD_VERSION = $(shell uname -v 2>&1 | cut -d' ' -f2 | cut -d'.' -f1) -SVN_VERSION = $(shell svnversion -n -c . | cut -d':' -f2) +CXX ?= clang++-devel BIN = ./libserverkey.a -# ifeq ($(GCC_VERSION), 4) IFLAGS = -CFLAGS = $(IFLAGS) -Wall -O2 -pipe -m32 -std=c++2b -D_THREAD_SAFE -fno-exceptions -# else -# IFLAGS = -# CFLAGS = $(IFLAGS) -Wall -O2 -pipe -mcpu=i686 -D_THREAD_SAFE -fno-exceptions -# endif +CFLAGS ?= $(IFLAGS) -Wall -O2 -pipe -std=c++2b -D_THREAD_SAFE -fno-exceptions LIBS = @@ -37,7 +25,7 @@ dep: touch Depend $(CXX) $(CFLAGS) -MM *.cpp > Depend -$(OBJFILES): - $(CXX) $(CFLAGS) -c $< +%.o: %.cpp + $(CXX) $(CFLAGS) -c $< -o $@ sinclude Depend diff --git a/src/server/libsql/AsyncSQL.cpp b/src/server/libsql/AsyncSQL.cpp index 358b4341..9740e3e5 100755 --- a/src/server/libsql/AsyncSQL.cpp +++ b/src/server/libsql/AsyncSQL.cpp @@ -143,12 +143,12 @@ bool CAsyncSQL::Connect() if (0 != mysql_options(&m_hDB, MYSQL_OPT_RECONNECT, &reconnect)) fprintf(stderr, "mysql_option: %s\n", mysql_error(&m_hDB)); - fprintf(stdout, "AsyncSQL: connected to %s (reconnect %d)\n", m_stHost.c_str(), m_hDB.reconnect); + fprintf(stdout, "AsyncSQL: connected to %s (reconnect %d)\n", m_stHost.c_str(), (int) reconnect); - // db cache´Â common dbÀÇ LOCALE Å×À̺í¿¡¼­ localeÀ» ¾˾ƿÀ°í, ÀÌÈÄ character setÀ» ¼öÁ¤ÇѴÙ. - // µû¶ó¼­ ÃÖÃÊ ConnectionÀ» ¸ÎÀ» ¶§¿¡´Â localeÀ» ¸𸣱â ¶§¹®¿¡ character setÀ» Á¤ÇÒ ¼ö°¡ ¾øÀ½¿¡µµ ºұ¸Çϰí, - // °­Á¦·Î character setÀ» euckr·Î Á¤Çϵµ·Ï µǾîÀ־î ÀÌ ºκÐÀ» Áּ®ó¸® ÇϿ´´Ù. - // (¾Ʒ¡ Áּ®À» Ǯ¸é mysql¿¡ euckrÀÌ ¾È ±ò·ÁÀִ µðºñ¿¡ Á¢±ÙÇÒ ¼ö°¡ ¾ø´Ù.) + // db cache는 common db의 LOCALE 테이블에서 locale을 알아오고, 이후 character set을 수정한다. + // 따라서 최초 Connection을 맺을 때에는 locale을 모르기 때문에 character set을 정할 수가 없음에도 불구하고, + // 강제로 character set을 euckr로 정하도록 되어있어 이 부분을 주석처리 하였다. + // (아래 주석을 풀면 mysql에 euckr이 안 깔려있는 디비에 접근할 수가 없다.) //while (!QueryLocaleSet()); m_ulThreadID = mysql_thread_id(&m_hDB); @@ -236,7 +236,7 @@ void CAsyncSQL::Quit() if (m_hThread) { pthread_join(m_hThread, NULL); - m_hThread = NULL; + m_hThread = 0; } #else if (m_hThread != INVALID_HANDLE_VALUE) { @@ -530,7 +530,7 @@ class cProfiler void CAsyncSQL::ChildLoop() { - cProfiler profiler(500000); // 0.5ÃÊ + cProfiler profiler(500000); // 0.5초 while (!m_bEnd) { @@ -547,7 +547,7 @@ void CAsyncSQL::ChildLoop() while (count--) { - //½ð£ üũ ½ÃÀÛ + //시간 체크 시작 profiler.Start(); if (!PeekQueryFromCopyQueue(&p)) @@ -593,7 +593,7 @@ void CAsyncSQL::ChildLoop() profiler.Stop(); - // 0.5ÃÊ À̻ó °ɷÈÀ¸¸é ·α׿¡ ³²±â±â + // 0.5초 이상 걸렸으면 로그에 남기기 if (!profiler.IsOk()) sys_log(0, "[QUERY : LONG INTERVAL(OverSec %ld.%ld)] : %s", profiler.GetResultSec(), profiler.GetResultUSec(), p->stQuery.c_str()); @@ -696,9 +696,9 @@ size_t CAsyncSQL::EscapeString(char* dst, size_t dstSize, const char *src, size_ if (dstSize < srcSize * 2 + 1) { - // \0ÀÌ ¾ȺپîÀÖÀ» ¶§¸¦ ´ëºñÇؼ­ 256 ¹ÙÀÌƮ¸¸ º¹»çÇؼ­ ·α׷Î Ãâ·Â + // \0이 안붙어있을 때를 대비해서 256 바이트만 복사해서 로그로 출력 char tmp[256]; - size_t tmpLen = sizeof(tmp) > srcSize ? srcSize : sizeof(tmp); // µÑ Á߿¡ ÀÛÀº ũ±â + size_t tmpLen = sizeof(tmp) > srcSize ? srcSize : sizeof(tmp); // 둘 중에 작은 크기 strlcpy(tmp, src, tmpLen); sys_err("FATAL ERROR!! not enough buffer size (dstSize %u srcSize %u src%s: %s)", diff --git a/src/server/libsql/Makefile b/src/server/libsql/Makefile index ea8696e6..6c507e64 100755 --- a/src/server/libsql/Makefile +++ b/src/server/libsql/Makefile @@ -1,16 +1,9 @@ -#CXX = distcc i386-obrien-freebsd5-g++ -CXX = clang++-devel - -PLATFORM = $(shell file /bin/ls | cut -d' ' -f3 | cut -d'-' -f1) - -GCC_VERSION = $(shell $(CC) --version 2>&1 | grep "(GCC)" | cut -d' ' -f3 | cut -d'.' -f1) -BSD_VERSION = $(shell uname -v 2>&1 | cut -d' ' -f2 | cut -d'.' -f1) -SVN_VERSION = $(shell svnversion -n -c . | cut -d':' -f2) +CXX ?= clang++-devel BIN = ./libsql.a -IFLAGS = -I/usr/local/include -CFLAGS = $(IFLAGS) -Wall -O2 -pipe -mtune=i686 -D_GLIBCXX_USE_CXX11_ABI=1 -D_THREAD_SAFE -fno-exceptions +IFLAGS = -I/usr/local/include -I/usr/include/mariadb -I/usr/include/mysql +CFLAGS ?= $(IFLAGS) -Wall -O2 -pipe -D_GLIBCXX_USE_CXX11_ABI=1 -D_THREAD_SAFE -fno-exceptions LIBS = @@ -32,7 +25,7 @@ dep: touch Depend $(CXX) $(CFLAGS) -MM *.cpp > Depend -$(OBJFILES): - $(CXX) $(CFLAGS) -c $< +%.o: %.cpp + $(CXX) $(CFLAGS) -c $< -o $@ sinclude Depend diff --git a/src/server/libthecore/include/fdwatch.h b/src/server/libthecore/include/fdwatch.h index f97e0a28..ef734a40 100755 --- a/src/server/libthecore/include/fdwatch.h +++ b/src/server/libthecore/include/fdwatch.h @@ -1,7 +1,33 @@ #ifndef __INC_LIBTHECORE_FDWATCH_H__ #define __INC_LIBTHECORE_FDWATCH_H__ -#ifndef __WIN32__ +#if defined(__linux__) + + #include + + typedef struct fdwatch FDWATCH; + typedef struct fdwatch * LPFDWATCH; + + enum EFdwatch + { + FDW_NONE = 0, + FDW_READ = 1, + FDW_WRITE = 2, + FDW_WRITE_ONESHOT = 4, + FDW_EOF = 8, + }; + + struct fdwatch + { + int epfd; + int nfiles; + struct epoll_event * events; + int nevents; + void ** fd_data; + int * fd_rw; + }; + +#elif !defined(__WIN32__) typedef struct fdwatch FDWATCH; typedef struct fdwatch * LPFDWATCH; diff --git a/src/server/libthecore/include/signal.h b/src/server/libthecore/include/signal.h index 2d3eeae7..e93dfcac 100755 --- a/src/server/libthecore/include/signal.h +++ b/src/server/libthecore/include/signal.h @@ -1,6 +1,10 @@ #ifndef __INC_LIBTHECORE_SIGNAL_H__ #define __INC_LIBTHECORE_SIGNAL_H__ +#if defined(__GNUC__) || defined(__clang__) +#include_next +#endif + #ifdef __cplusplus extern "C" { diff --git a/src/server/libthecore/include/stdafx.h b/src/server/libthecore/include/stdafx.h index 2e43ed28..b4b0f9d0 100755 --- a/src/server/libthecore/include/stdafx.h +++ b/src/server/libthecore/include/stdafx.h @@ -78,7 +78,7 @@ inline double rint(double x) #else -#ifndef __FreeBSD__ +#if !defined(__FreeBSD__) && !defined(__linux__) #define __USE_SELECT__ #ifdef __CYGWIN__ #define _POSIX_SOURCE 1 @@ -106,6 +106,7 @@ inline double rint(double x) #include #include +#include #include #include @@ -114,14 +115,18 @@ inline double rint(double x) #ifdef __FreeBSD__ #include +#elif defined(__linux__) +#include #endif #endif +#ifndef __cplusplus #ifndef false #define false 0 #define true (!false) #endif +#endif #ifndef FALSE #define FALSE false diff --git a/src/server/libthecore/src/Makefile b/src/server/libthecore/src/Makefile index e9074f83..80239c73 100755 --- a/src/server/libthecore/src/Makefile +++ b/src/server/libthecore/src/Makefile @@ -1,20 +1,25 @@ -CC = clang++-devel +CC ?= clang++-devel BIN_DIR = ../lib BIN = $(BIN_DIR)/libthecore.a INCLUDE = ../include -GCC_VERSION = $(shell $(CC) --version 2>&1 | grep "(GCC)" | cut -d' ' -f3 | cut -d'.' -f1) - -ifeq ($(GCC_VERSION), 4) -CFLAGS = -Wall -O2 -pipe -mtune=i686 -g -I$(INCLUDE) +UNAME_M := $(shell uname -m) +ifeq ($(UNAME_M), x86_64) +ARCH_FLAGS = -m32 -mtune=i686 +else ifeq ($(UNAME_M), i386) +ARCH_FLAGS = -mtune=i686 +else ifeq ($(UNAME_M), i686) +ARCH_FLAGS = -mtune=i686 else -CFLAGS = -Wall -O2 -pipe -mtune=i686 -g -I$(INCLUDE) +ARCH_FLAGS = endif +CFLAGS ?= -Wall -O2 -pipe $(ARCH_FLAGS) -g -I$(INCLUDE) -Wno-deprecated-declarations -Wno-format-security + LIBS = OBJFILES = socket.o fdwatch.o buffer.o signal.o log.o utils.o \ - kstbl.o hangul.o heart.o main.o tea.o des.o gost.o memcpy.o + kstbl.o hangul.o heart.o main.o tea.o des.o gost.o memcpy.o xmd5.o default: $(MAKE) $(BIN) diff --git a/src/server/libthecore/src/fdwatch.c b/src/server/libthecore/src/fdwatch.c index bbf87745..936b800e 100755 --- a/src/server/libthecore/src/fdwatch.c +++ b/src/server/libthecore/src/fdwatch.c @@ -1,7 +1,182 @@ #define __LIBTHECORE__ #include "stdafx.h" -#ifndef __USE_SELECT__ +#if defined(__linux__) + +LPFDWATCH fdwatch_new(int nfiles) +{ + LPFDWATCH fdw; + int epfd = epoll_create1(EPOLL_CLOEXEC); + if (epfd == -1) + { + sys_err("epoll_create1 failed: %s", strerror(errno)); + return NULL; + } + + CREATE(fdw, FDWATCH, 1); + fdw->epfd = epfd; + fdw->nfiles = nfiles; + fdw->nevents = 0; + CREATE(fdw->events, struct epoll_event, nfiles * 2); + CREATE(fdw->fd_rw, int, nfiles); + CREATE(fdw->fd_data, void*, nfiles); + return fdw; +} + +void fdwatch_delete(LPFDWATCH fdw) +{ + if (!fdw) return; + if (fdw->epfd >= 0) close(fdw->epfd); + if (fdw->events) free(fdw->events); + if (fdw->fd_rw) free(fdw->fd_rw); + if (fdw->fd_data) free(fdw->fd_data); + free(fdw); +} + +void fdwatch_clear_fd(LPFDWATCH fdw, socket_t fd) +{ + if (fd >= 0 && fd < fdw->nfiles) + { + fdw->fd_data[fd] = NULL; + fdw->fd_rw[fd] = 0; + } +} + +void fdwatch_add_fd(LPFDWATCH fdw, socket_t fd, void * client_data, int rw, int oneshot) +{ + if (fd < 0 || fd >= fdw->nfiles) + { + sys_err("fd overflow %d (max %d)", fd, fdw->nfiles); + return; + } + + if (fdw->fd_rw[fd] & rw) + return; + + int old_rw = fdw->fd_rw[fd]; + fdw->fd_rw[fd] |= rw; + if (oneshot) + fdw->fd_rw[fd] |= FDW_WRITE_ONESHOT; + + fdw->fd_data[fd] = client_data; + + struct epoll_event ev; + memset(&ev, 0, sizeof(ev)); + ev.data.fd = fd; + + if (fdw->fd_rw[fd] & FDW_READ) + ev.events |= EPOLLIN; + if (fdw->fd_rw[fd] & FDW_WRITE) + ev.events |= EPOLLOUT; + + int op = (old_rw == 0) ? EPOLL_CTL_ADD : EPOLL_CTL_MOD; + if (epoll_ctl(fdw->epfd, op, fd, &ev) < 0) + { + if (op == EPOLL_CTL_ADD && errno == EEXIST) + epoll_ctl(fdw->epfd, EPOLL_CTL_MOD, fd, &ev); + else if (op == EPOLL_CTL_MOD && errno == ENOENT) + epoll_ctl(fdw->epfd, EPOLL_CTL_ADD, fd, &ev); + else + sys_err("epoll_ctl failed for fd %d: %s", fd, strerror(errno)); + } +} + +void fdwatch_del_fd(LPFDWATCH fdw, socket_t fd) +{ + if (fd >= 0 && fd < fdw->nfiles) + { + epoll_ctl(fdw->epfd, EPOLL_CTL_DEL, fd, NULL); + fdwatch_clear_fd(fdw, fd); + } +} + +int fdwatch(LPFDWATCH fdw, struct timeval *timeout) +{ + int to_ms = -1; + if (timeout) + to_ms = timeout->tv_sec * 1000 + timeout->tv_usec / 1000; + + int r = epoll_wait(fdw->epfd, fdw->events, fdw->nfiles * 2, to_ms); + if (r < 0) + { + if (errno == EINTR) + return 0; + return -1; + } + + fdw->nevents = r; + return r; +} + +void * fdwatch_get_client_data(LPFDWATCH fdw, unsigned int event_idx) +{ + if ((int)event_idx >= fdw->nevents) + return NULL; + int fd = fdw->events[event_idx].data.fd; + if (fd < 0 || fd >= fdw->nfiles) + return NULL; + return fdw->fd_data[fd]; +} + +int fdwatch_get_ident(LPFDWATCH fdw, unsigned int event_idx) +{ + if ((int)event_idx >= fdw->nevents) + return -1; + return fdw->events[event_idx].data.fd; +} + +void fdwatch_clear_event(LPFDWATCH fdw, socket_t fd, unsigned int event_idx) +{ + if ((int)event_idx >= fdw->nevents) + return; + if (fdw->events[event_idx].data.fd == fd) + { + fdw->events[event_idx].data.fd = -1; + fdw->events[event_idx].events = 0; + } +} + +int fdwatch_check_event(LPFDWATCH fdw, socket_t fd, unsigned int event_idx) +{ + if ((int)event_idx >= fdw->nevents) + return 0; + if (fdw->events[event_idx].data.fd != fd) + return 0; + + uint32_t ev = fdw->events[event_idx].events; + if (ev & (EPOLLERR | EPOLLHUP | EPOLLRDHUP)) + return FDW_EOF; + + if ((ev & EPOLLIN) && (fdw->fd_rw[fd] & FDW_READ)) + return FDW_READ; + + if ((ev & EPOLLOUT) && (fdw->fd_rw[fd] & FDW_WRITE)) + { + if (fdw->fd_rw[fd] & FDW_WRITE_ONESHOT) + { + fdw->fd_rw[fd] &= ~FDW_WRITE; + struct epoll_event mod_ev; + memset(&mod_ev, 0, sizeof(mod_ev)); + mod_ev.data.fd = fd; + if (fdw->fd_rw[fd] & FDW_READ) + mod_ev.events |= EPOLLIN; + if (fdw->fd_rw[fd] == 0) + epoll_ctl(fdw->epfd, EPOLL_CTL_DEL, fd, NULL); + else + epoll_ctl(fdw->epfd, EPOLL_CTL_MOD, fd, &mod_ev); + } + return FDW_WRITE; + } + + return 0; +} + +int fdwatch_get_buffer_size(LPFDWATCH fdw, socket_t fd) +{ + return 0; +} + +#elif !defined(__USE_SELECT__) LPFDWATCH fdwatch_new(int nfiles) { diff --git a/src/server/libthecore/src/main.c b/src/server/libthecore/src/main.c index 33a2bc60..36cacd00 100755 --- a/src/server/libthecore/src/main.c +++ b/src/server/libthecore/src/main.c @@ -1,8 +1,8 @@ /* * Filename: main.c - * Description: ¶óÀ̺귯¸® Ãʱâȭ/»èÁ¦ µî + * Description: 라이브러리 초기화/삭제 등 * - * Author: ºñ¿± aka. Cronan + * Author: 비엽 aka. Cronan */ #define __LIBTHECORE__ #include "stdafx.h" @@ -54,7 +54,9 @@ int thecore_init(int fps, HEARTFUNC heartbeat_func) srand(time(0)); #else srandom(time(0) + getpid() + getuid()); +#ifdef __FreeBSD__ srandomdev(); +#endif #endif signal_setup(); diff --git a/src/server/libthecore/src/signal.c b/src/server/libthecore/src/signal.c index d78d5e64..8cae310a 100755 --- a/src/server/libthecore/src/signal.c +++ b/src/server/libthecore/src/signal.c @@ -11,7 +11,7 @@ void signal_setup() {} void signal_timer_disable() {} void signal_timer_enable(int timeout_seconds) {} -#elif __FreeBSD__ +#elif defined(__FreeBSD__) || defined(__linux__) #define RETSIGTYPE void RETSIGTYPE reap(int sig) diff --git a/tests/features/fixtures/cube_factory_platform.h b/tests/features/fixtures/cube_factory_platform.h index cd1f3cb0..fb691f09 100644 --- a/tests/features/fixtures/cube_factory_platform.h +++ b/tests/features/fixtures/cube_factory_platform.h @@ -43,7 +43,8 @@ bool LC_IsKorea(){return false;}bool LC_IsYMIR(){return false;} #define M2_DELETE(p) delete (p) #define M2_DESTROY_ITEM(p) ITEM_MANAGER::instance().DestroyItem(p) struct Desc {const char* GetHostName(){return "mock";}}; -struct CHARACTER {struct Points{CItem* pItems[400]={};WORD bItemGrid[400]={};CItem* pCubeItems[4]={};CItem* pSashMaterials[3]={};}m_pointsInstant;int64_t gold=1000;CItem* m_pQuestItem=nullptr; +struct CHARACTER {struct Cells{CItem* pItems[400]={};WORD bItemGrid[400]={};CItem* pCubeItems[4]={};CItem* pSashMaterials[3]={};};struct Points:Cells{Cells* pItemCells=this;Points()=default;Points(const Points& x):Cells(x){} Points& operator=(const Points& x){static_cast(*this)=x;pItemCells=this;return *this;}}m_pointsInstant; + const Cells& ItemCells()const{return m_pointsInstant;}int64_t gold=1000;CItem* m_pQuestItem=nullptr; const char* GetName(){return "mock";}unsigned GetPlayerID(){return 1;}Desc* GetDesc(){return nullptr;} CItem* GetInventoryItem(unsigned cell){return m_pointsInstant.pItems[cell];}void SetGold(int64_t value){gold=value;} bool PortCubeInstallImage(const PortCube::InventoryImage&,const std::vector&,const std::vector&);}; @@ -57,7 +58,10 @@ struct DBDesc {void DBPacketHeader(unsigned,unsigned,unsigned){++packets;}void P struct CSkillProto {}; struct CSkillManager {static CSkillManager& instance(){static CSkillManager m;return m;}CSkillProto* Get(unsigned){static CSkillProto p;return skills?&p:nullptr;}}; struct Limit {unsigned type=0;long value=0;}; -struct TItemTable {unsigned bType=ITEM_WEAPON,bSubType=0,bSize=1;union{unsigned flags=0;unsigned dwFlags;};long values[3]={7,9,0};Limit limits[2];int sAddonType=0;unsigned bAlterToMagicItemPct=100,bGainSocketPct=0;}; +namespace PortMaterialStackPolicy {inline unsigned Limit(unsigned,bool stackable,bool,unsigned){return stackable?2000:200;}inline bool LegacyGrowthMode(){return false;}} +namespace quest {struct CQuestManager{static CQuestManager& instance(){static CQuestManager q;return q;}int GetEventFlag(const char*){return 0;}};} +constexpr unsigned ITEM_ANTIFLAG_STACK=1; +struct TItemTable {unsigned dwAntiFlags=0,dwVnum=0;unsigned bType=ITEM_WEAPON,bSubType=0,bSize=1;union{unsigned flags=0;unsigned dwFlags;};long values[3]={7,9,0};Limit limits[2];int sAddonType=0;unsigned bAlterToMagicItemPct=100,bGainSocketPct=0;}; struct Attr {BYTE bType=0;short sValue=0;}; #pragma pack(push,1) struct Extra {int32_t sockets[5]={};BYTE types[8]={};int16_t values[8]={};char name[25]={};}; @@ -76,7 +80,7 @@ struct CItem { void SetWindow(unsigned w){m_bWindow=w;}unsigned GetWindow(){return m_bWindow;} bool isLocked(){return locked;}bool IsExchanging(){return exchanging;}bool PortCubeHasPendingMutation(){return clock;} void PortCubeInitNewAttach();bool PortCubeRestoreMetadata(const PortEconomy::Reward&);void PortCubeAttachRestored(CHARACTER*,WORD); - bool IsStackable(){return proto->flags&1;}unsigned GetFlag(){return proto->flags;}long GetValue(unsigned i){return proto->values[i];} + unsigned GetStackLimit(){return IsStackable()?2000:200;}bool IsStackable(){return proto->flags&1;}unsigned GetFlag(){return proto->flags;}long GetValue(unsigned i){return proto->values[i];} void SetID(unsigned value){id=value;}unsigned GetID(){return id;}void SetVID(unsigned value){vid=value;}unsigned GetVID(){return vid;} void SetSkipSave(bool value){m_bSkipSave=value;}bool GetSkipSave(){return m_bSkipSave;} void Save();void UpdatePacket(){if(!m_portCubeTemplate)++packets;} diff --git a/tests/features/test_ava2_ticket_shop.py b/tests/features/test_ava2_ticket_shop.py index 50360d24..f0c5bbea 100644 --- a/tests/features/test_ava2_ticket_shop.py +++ b/tests/features/test_ava2_ticket_shop.py @@ -16,12 +16,12 @@ using DWORD=uint32_t;using BYTE=uint8_t;using WORD=uint16_t; const int SHOP_HOST_ITEM_MAX_NUM=40,HEADER_GC_SHOP=38,CHAT_TYPE_COMMAND=1; enum {SHOP_SUBHEADER_GC_START,SHOP_SUBHEADER_GC_END,SHOP_SUBHEADER_GC_UPDATE_ITEM,SHOP_SUBHEADER_GC_UPDATE_PRICE,SHOP_SUBHEADER_GC_OK,SHOP_SUBHEADER_GC_NOT_ENOUGH_MONEY,SHOP_SUBHEADER_GC_SOLDOUT,SHOP_SUBHEADER_GC_INVENTORY_FULL,SHOP_SUBHEADER_GC_INVALID_POS,SHOP_SUBHEADER_GC_SOLD_OUT,SHOP_SUBHEADER_GC_START_EX,SHOP_SUBHEADER_GC_NOT_ENOUGH_MONEY_EX,SHOP_SUBHEADER_GC_START_ITEM_CURRENCY,SHOP_SUBHEADER_GC_NOT_ENOUGH_ITEM}; #pragma pack(push,1) -struct WireItem { DWORD vnum;int64_t price;BYTE count,display_pos;char rest[33]; }; +struct WireItem { DWORD vnum;int64_t price;WORD count;BYTE display_pos;char rest[33]; }; struct TPacketGCShopStart { DWORD owner_vid;WireItem items[40]; }; struct TPacketGCShop { BYTE header;WORD size;BYTE subheader; }; #pragma pack(pop) -static_assert(sizeof(WireItem)==47,"baseline item"); -struct TShopItemTable { DWORD vnum;BYTE count; }; +static_assert(sizeof(WireItem)==48,"baseline item"); +struct TShopItemTable { DWORD vnum;WORD count; }; struct Desc { std::string frame;void BufferedPacket(const void* p,size_t n){frame.assign((const char*)p,n);}void Packet(const void* p,size_t n){frame.append((const char*)p,n);} }; class CShop; struct Character { @@ -43,7 +43,7 @@ struct CQuestManager {PC pc;static CQuestManager& instance(){static CQuestManage struct ITEM_MANAGER {bool valid=true;static ITEM_MANAGER& instance(){static ITEM_MANAGER i;return i;}const int* GetTable(DWORD){static int proto=1;return valid?&proto:nullptr;}}; class CShop { protected: - struct SHOP_ITEM {DWORD vnum=0;BYTE count=0;int price=0;}; + struct SHOP_ITEM {DWORD vnum=0;WORD count=0;int price=0;}; using GuestMapType=std::map; GuestMapType m_map_guest;std::vector m_itemVector; public: @@ -56,7 +56,7 @@ main=r''' int main(){ Character c;c.items[90011]=30; assert(Ava2OpenTicketShop(&c));assert(Ava2IsTicketShop(c.GetShop()));assert(c.GetShopOwner()==&c); - assert(c.desc.frame.size()==2208); + assert(c.desc.frame.size()==2248); Ava2ShopStart start;memcpy(&start,c.desc.frame.data()+sizeof(TPacketGCShop),sizeof(start)); assert(start.shop.owner_vid==0 && start.shop.items[7].vnum==25170 && start.prices[0].vnum==90011 && start.prices[7].count==30); assert(c.GetShop()->Buy(&c,0)==SHOP_SUBHEADER_GC_OK);assert(c.items[25163]==1 && c.items[90011]==20 && c.gold==123456); diff --git a/tests/features/test_cube_handshake.py b/tests/features/test_cube_handshake.py index 5c8ca743..d8fd19cc 100644 --- a/tests/features/test_cube_handshake.py +++ b/tests/features/test_cube_handshake.py @@ -9,7 +9,7 @@ ROOT=Path(__file__).resolve().parents[2] class CubeHandshake(unittest.TestCase): def test_actual_game_snapshot_covers_all_owned_windows_and_metadata(self): - body=(ROOT/'src/server/game/src/port_cube_actor.cpp').read_text().split('struct Snapshot ',1)[1].split('bool matches(',1)[0] + body=(ROOT/'src/server/game/src/port_cube_actor.cpp').read_bytes().decode('latin1').split('struct Snapshot ',1)[1].split('bool matches(',1)[0] source=r''' #include "src/server/common/cube_handshake.h" #include "src/server/common/cube_craft.h" @@ -52,7 +52,7 @@ int main(){CHARACTER ch,foreign;Item item;item.owner=&ch;item.sockets[0]=INT32_M subprocess.run([str(exe)],check=True) def test_bounded_wire_and_fail_closed_actor_state(self): - prefix=(ROOT/'tests/features/fixtures/cube_batch_probe.cpp').read_text().split('int main(int argc,char** argv)',1)[0] + prefix=(ROOT/'tests/features/fixtures/cube_batch_probe.cpp').read_bytes().decode('latin1').split('int main(int argc,char** argv)',1)[0] tests=r''' #include "src/server/common/cube_handshake.h" int main(){ @@ -96,7 +96,7 @@ int main(){ subprocess.run([str(exe)],check=True) def test_flush_includes_dirty_detached_items_without_stealing_other_owners(self): - body=(ROOT/'src/server/game/src/port_cube_flush.inc').read_text() + body=(ROOT/'src/server/game/src/port_cube_flush.inc').read_bytes().decode('latin1') source=r''' #include #include @@ -120,14 +120,14 @@ int main(){CHARACTER a{1},b{2};CItem owned{&a,1},detached{nullptr,1},foreign{&b, subprocess.run([str(exe)],check=True) def test_game_dispatch_keeps_gate_closed_and_saves_precede_submit(self): - source=(ROOT/'src/server/game/src/port_cube_actor.cpp').read_text() + source=(ROOT/'src/server/game/src/port_cube_actor.cpp').read_bytes().decode('latin1') self.assertIn('if(!PortCube::HandshakeEnabled||!PortCube::ActorMutationAuditComplete)return false;',source) self.assertLess(source.index('ch->SaveReal();'),source.index('o.flow.Submit(true,now)')) self.assertIn('FlushDelayedSaveForPlayer(f.player)',source) - self.assertIn('PortCubeActorHeld(this)',(ROOT/'src/server/game/src/char_item.cpp').read_text()) - self.assertIn('PortCubeActorForget(this)',(ROOT/'src/server/game/src/char.cpp').read_text()) - self.assertIn('PortCubeActorTick();',(ROOT/'src/server/game/src/main.cpp').read_text()) - db=(ROOT/'src/server/game/src/input_db.cpp').read_text() + self.assertIn('PortCubeActorHeld(this)',(ROOT/'src/server/game/src/char_item.cpp').read_bytes().decode('latin1')) + self.assertIn('PortCubeActorForget(this)',(ROOT/'src/server/game/src/char.cpp').read_bytes().decode('latin1')) + self.assertIn('PortCubeActorTick();',(ROOT/'src/server/game/src/main.cpp').read_bytes().decode('latin1')) + db=(ROOT/'src/server/game/src/input_db.cpp').read_bytes().decode('latin1') self.assertIn('!PortCube::DecodeHandshake(pRealData,size_t(iSize),frame)',db) # These two legacy-encoding files only receive narrow ASCII insertions. self.assertIn(b'#include "port_cube_flush.inc"',(ROOT/'src/server/game/src/item_manager.cpp').read_bytes()) diff --git a/tests/features/test_cube_mutation.py b/tests/features/test_cube_mutation.py index 348b57cc..f925fae9 100644 --- a/tests/features/test_cube_mutation.py +++ b/tests/features/test_cube_mutation.py @@ -36,7 +36,7 @@ class CubeMutation(unittest.TestCase): self.assertIn('misses aliases',report['warning']) def test_item_admission_is_read_only_and_preserves_expiry_paths(self): - body=(SRC/'port_cube_item.inc').read_text() + body=(SRC/'port_cube_item.inc').read_bytes().decode('latin1') run(r''' #include #include @@ -53,7 +53,7 @@ int main(){CItem item;assert(item.PortCubeHasPendingMutation());Proto proto;item ''') def test_actual_preparation_admission_combines_context_and_owned_item_hazards(self): - body=function((SRC/'port_cube_actor.cpp').read_text(),'uint32_t PortCubeAdmission(') + body=function((SRC/'port_cube_actor.cpp').read_bytes().decode('latin1'),'uint32_t PortCubeAdmission(') run(r''' #include "src/server/common/cube_mutation.h" #include @@ -74,8 +74,8 @@ int main(){using namespace PortCube;CHARACTER ch;Item item;ch.items={&item};asse ch.desc=false;assert(PortCubeAdmission(&ch)==MissingState);assert(PortCubeAdmission(nullptr)==MissingState); } ''') - current=(SRC/'item.cpp').read_text() - original=subprocess.check_output(['git','show','HEAD:src/server/game/src/item.cpp'],cwd=ROOT).decode() + current=(SRC/'item.cpp').read_bytes().decode('latin1') + original=subprocess.check_output(['git','show','HEAD:src/server/game/src/item.cpp'],cwd=ROOT).decode('latin1') for event in ['unique_expire_event','timer_based_on_wear_expire_event','real_time_expire_event','accessory_socket_expire_event']: current_body=function(current,'EVENTFUNC('+event+')') original_body=function(original,'EVENTFUNC('+event+')') @@ -84,12 +84,15 @@ int main(){using namespace PortCube;CHARACTER ch;Item item;ch.items={&item};asse # original expiry deadlines, effects and scheduling stay exact. checked='const item_vid_event_info* info = dynamic_cast(event->info); // PORT: prepared clock info is a checked subtype.' self.assertEqual(current_body.count(checked),1) - legacy=re.search(r'[^\n]*info = reinterpret_cast<[^\n]*',original_body).group(0).lstrip() - current_body=current_body.replace(checked,legacy) + legacy=re.search(r'[^\n]*info = reinterpret_cast<[^\n]*',original_body) + if legacy: + current_body=current_body.replace(checked,legacy.group(0).lstrip()) + else: + self.assertIn(checked,original_body) self.assertEqual(current_body,original_body) def test_item_save_notifies_but_does_not_drop_or_redirect_original_save(self): - body=function((SRC/'item.cpp').read_text(),'void CItem::Save()') + body=function((SRC/'item.cpp').read_bytes().decode('latin1'),'void CItem::Save()') run(r''' #include "src/server/common/cube_mutation.h" #include @@ -124,7 +127,7 @@ int main(){PC pc;pc.SetFlag("gem.points",5);assert(pc.m_FlagMap.at("gem.points") ''') def test_switchbot_yields_whole_roll_before_state_rng_or_cost(self): - text=(SRC/'port_switchbot.cpp').read_text() + text=(SRC/'port_switchbot.cpp').read_bytes().decode('latin1') prefix=text.split('void CSwitchbot::SwitchItems()',1)[1].split('for (BYTE bSlot',1)[0] run(r''' #include @@ -142,7 +145,7 @@ int main(){CSwitchbot bot;bot.SwitchItems();assert(rolls==0);held=false;bot.Swit self.assertLess(text.index('PortCubeActorHeld(',text.index('void CSwitchbot::SwitchItems()')),text.index('m_table.finished[bSlot] = false;',text.index('void CSwitchbot::SwitchItems()'))) def test_gold_and_lifecycle_notifications_are_not_setter_vetoes(self): - text=(SRC/'char.cpp').read_text() + text=(SRC/'char.cpp').read_bytes().decode('latin1') self.assertIn('if(type==POINT_GOLD&&amount)PortCubeAssetMutation(this,PortCube::GoldWrite);',function(text,'void CHARACTER::PointChange(')) for signature in ['void CHARACTER::Disconnect(', 'bool CHARACTER::WarpSet(long x, long y, long lPrivateMapIndex, BYTE targetChannel)']: self.assertIn('PortCubeAssetMutation(this,PortCube::LifecycleWrite);',function(text,signature)) diff --git a/tests/features/test_cube_recovery.py b/tests/features/test_cube_recovery.py index eeeed810..fe7efd2b 100644 --- a/tests/features/test_cube_recovery.py +++ b/tests/features/test_cube_recovery.py @@ -10,7 +10,7 @@ ROOT = Path(__file__).resolve().parents[2] class CubeRecovery(unittest.TestCase): def test_wire_and_actual_game_preload_controller(self): - body = (ROOT/'src/server/game/src/port_cube_recovery.cpp').read_text() + body = (ROOT/'src/server/game/src/port_cube_recovery.cpp').read_bytes().decode('latin1') body = re.sub(r'^#include[^\n]*\n', '', body, flags=re.M) # Explicit audit-gate substitute, never modify the production constants. body = body.replace('return PortCube::HandshakeEnabled&&PortCube::ActorMutationAuditComplete;', 'return auditedGate;') @@ -101,13 +101,13 @@ int main(){ subprocess.run([str(exe)],check=True) def test_real_select_dispatch_and_frame_whitelist(self): - select=(ROOT/'src/server/game/src/input_login.cpp').read_text().split('void CInputLogin::CharacterSelect(',1)[1].split('bool NewPlayerTable',1)[0] + select=(ROOT/'src/server/game/src/input_login.cpp').read_bytes().decode('latin1').split('void CInputLogin::CharacterSelect(',1)[1].split('bool NewPlayerTable',1)[0] self.assertLess(select.index('PortCubeRecoverySelect('),select.index('DBPacket(HEADER_GD_PLAYER_LOAD')) - db=(ROOT/'src/server/game/src/input_db.cpp').read_text() + db=(ROOT/'src/server/game/src/input_db.cpp').read_bytes().decode('latin1') self.assertIn('!PortCube::IsDbHandshakeReply(frame.message)',db) self.assertIn('PortCubeRecoveryReply(m_dwHandle,c_pData,size)',db) - self.assertIn('PortCubeRecoveryTick();',(ROOT/'src/server/game/src/main.cpp').read_text()) - self.assertIn('port_cube_recovery.cpp',(ROOT/'src/server/game/src/Makefile').read_text()) + self.assertIn('PortCubeRecoveryTick();',(ROOT/'src/server/game/src/main.cpp').read_bytes().decode('latin1')) + self.assertIn('port_cube_recovery.cpp',(ROOT/'src/server/game/src/Makefile').read_bytes().decode('latin1')) if __name__ == '__main__': diff --git a/tests/features/test_material_stack_identity.py b/tests/features/test_material_stack_identity.py new file mode 100644 index 00000000..6ecb625f --- /dev/null +++ b/tests/features/test_material_stack_identity.py @@ -0,0 +1,51 @@ +"""Compile actual merge/split metadata helpers with an explicit attribute-lock DB boundary.""" +from pathlib import Path +import subprocess,tempfile,unittest +ROOT=Path(__file__).resolve().parents[2] +class Identity(unittest.TestCase): + def test_actual_helpers_preserve_identity_and_fail_closed(self): + source=(ROOT/'src/server/game/src/item.cpp').read_bytes().decode('latin1') + actual=source[source.index('bool CItem::CanStackWith('):source.index('DWORD CItem::GetCount()')] + prefix=r''' +#include +#include +#include +struct Proto {unsigned dwVnum=30006,dwAntiFlags=0;}; +constexpr unsigned ITEM_FLAG_STACKABLE=4,ITEM_ANTIFLAG_STACK=32768; +struct Extra {unsigned char bytes[69]={};}; +struct CItem {Proto proto;const Proto* m_pProto=&proto;unsigned m_dwVnum=30006,m_dwMaskVnum=0,m_dwSIGVnum=0,m_lFlag=4; + bool m_bExchanging=false,m_isLocked=false,m_portAttrLockLoaded=false;unsigned m_portAttrLock=0,storedMask=0; + int32_t m_alSockets[3]={};unsigned char m_aAttr[21]={};Extra m_portExtra; + unsigned GetOriginalVnum(){return m_dwVnum;}const int32_t* GetSockets(){return m_alSockets;} + void SetSockets(const int32_t* s){memcpy(m_alSockets,s,sizeof(m_alSockets));}void CopyAttributeTo(CItem* x){memcpy(x->m_aAttr,m_aAttr,sizeof(m_aAttr));} + const Extra& GetPortExtra(){return m_portExtra;}void SetPortExtra(const Extra& x){m_portExtra=x;} + bool CanStackWith(const CItem*)const;bool CopyStackStateTo(CItem*); +}; +static bool failRead=false,failWrite=false; +unsigned PortAttrLockGet(CItem* x){if(!x->m_portAttrLockLoaded&&!failRead){x->m_portAttrLock=x->storedMask;x->m_portAttrLockLoaded=true;}return x->m_portAttrLock;} +bool PortAttrLockSet(void*,CItem* x,unsigned m){if(failWrite)return false;x->storedMask=x->m_portAttrLock=m;return x->m_portAttrLockLoaded=true;} +''' + cases=r''' +int main(){CItem a,b;assert(a.CanStackWith(&b)); + b.m_alSockets[0]=1;assert(!a.CanStackWith(&b));b.m_alSockets[0]=0; + b.m_aAttr[20]=1;assert(!a.CanStackWith(&b));b.m_aAttr[20]=0; + b.m_portExtra.bytes[68]=1;assert(!a.CanStackWith(&b));b.m_portExtra.bytes[68]=0; + b.storedMask=1;b.m_portAttrLockLoaded=false;assert(!a.CanStackWith(&b));assert(b.m_portAttrLockLoaded); + a.storedMask=1;a.m_portAttrLockLoaded=false;assert(a.CanStackWith(&b)); + b.m_isLocked=true;assert(!a.CanStackWith(&b));b.m_isLocked=false; + b.m_bExchanging=true;assert(!a.CanStackWith(&b));b.m_bExchanging=false; + b.proto.dwAntiFlags=ITEM_ANTIFLAG_STACK;assert(!a.CanStackWith(&b));b.proto.dwAntiFlags=0; + b.m_dwVnum++;assert(!a.CanStackWith(&b));b.m_dwVnum--; + b.m_dwMaskVnum=99;assert(!a.CanStackWith(&b));b.m_dwMaskVnum=0; + b.m_dwSIGVnum=1;assert(!a.CanStackWith(&b));b.m_dwSIGVnum=0; + a.m_alSockets[2]=123;a.m_aAttr[20]=9;a.m_portExtra.bytes[68]=7; + CItem split;failWrite=true;assert(!a.CopyStackStateTo(&split));failWrite=false;assert(a.CopyStackStateTo(&split)); + assert(split.storedMask==1&&a.CanStackWith(&split)); + CItem unavailable;failRead=true;assert(!unavailable.CopyStackStateTo(&split)&&!unavailable.CanStackWith(&b)); +} +''' + with tempfile.TemporaryDirectory() as td: + p=Path(td)/'probe.cpp';p.write_text(prefix+actual+cases);exe=Path(td)/'probe' + subprocess.run(['c++','-std=c++17','-fsanitize=address,undefined',str(p),'-o',str(exe)],check=True) + subprocess.run([str(exe)],check=True) +if __name__=='__main__':unittest.main() diff --git a/tests/features/test_material_stack_policy.py b/tests/features/test_material_stack_policy.py new file mode 100644 index 00000000..8a02e4b1 --- /dev/null +++ b/tests/features/test_material_stack_policy.py @@ -0,0 +1,48 @@ +#!/usr/bin/env python3 +"""Compile the active item-level material policy and verify its grant/storage rules.""" +import pathlib +import subprocess +import tempfile + +root = pathlib.Path(__file__).resolve().parents[2] +source = r''' +#include +typedef uint8_t BYTE; +typedef uint16_t WORD; +#include "src/server/common/length.h" +#include "src/server/common/item_length.h" +#include "src/server/game/src/port_material_stack_policy.h" +#include +int main() { + using namespace PortMaterialStackPolicy; + for (auto t : {ITEM_USE, ITEM_AUTOUSE, ITEM_MATERIAL, ITEM_METIN, + ITEM_RESOURCE, ITEM_BLEND, ITEM_EXTRACT}) + assert(Limit(t, true, false) == 2000); + assert(Limit(ITEM_USE, false, false) == 200); + assert(Limit(ITEM_USE, true, true) == 200); + assert(Limit(ITEM_QUEST, true, false) == 200); + assert(Limit(ITEM_TREASURE_BOX, true, false) == 200); + assert(Limit(ITEM_WEAPON, false, false) == 200); + assert(GrantLimit(ITEM_WEAPON, false, false) == 1); + assert(GrantLimit(ITEM_USE, true, true) == 1); + setenv("PORT_MATERIAL_STACK_QA_LOGIN", "alice,bob", 1); + assert(QAAllowed("alice") && QAAllowed("bob") && !QAAllowed("ali") && !QAAllowed("eve")); + unsetenv("PORT_MATERIAL_STACK_QA_LOGIN"); + assert(QAAllowed("eve")); + setenv("PORT_MATERIAL_STACK_LEGACY_MODE", "1", 1); + assert(LegacyGrowthMode()); + assert(Limit(ITEM_USE, true, false) == 2000); // Reading old wide rows remains safe. + unsetenv("PORT_MATERIAL_STACK_LEGACY_MODE"); + assert(!LegacyGrowthMode()); + RefineIngredients().insert(999001); + assert(Limit(ITEM_QUEST, true, false, 999001) == 2000); + assert(Limit(ITEM_QUEST, true, false, 999002) == 200); +} +'''.replace('#include ', '#include \n#include ') +with tempfile.TemporaryDirectory() as td: + path = pathlib.Path(td) / 'policy.cpp' + path.write_text(source) + exe = pathlib.Path(td) / 'policy' + subprocess.run(['c++', '-std=c++11', '-I', str(root), str(path), '-o', str(exe)], check=True) + subprocess.run([str(exe)], check=True) +print('PASS: material stack policy') diff --git a/tests/features/test_material_stack_refine.py b/tests/features/test_material_stack_refine.py new file mode 100644 index 00000000..fbea42ec --- /dev/null +++ b/tests/features/test_material_stack_refine.py @@ -0,0 +1,41 @@ +"""Actual refinement debit planner with explicit inventory primitives; no RNG or wallet substitutes.""" +import subprocess,tempfile,unittest +from pathlib import Path +ROOT=Path(__file__).resolve().parents[2] +class Refine(unittest.TestCase): + def test_atomic_aggregate_debits_across_storage_and_invalid_sources(self): + code=r''' +#include +#include +#include +#include +#include +#define ENABLE_SPECIAL_STORAGE +using DWORD=uint32_t;using BYTE=uint8_t; +enum{INVENTORY=1,UPGRADE_INVENTORY=8,BOOK_INVENTORY,STONE_INVENTORY,CHANGE_INVENTORY,COSTUME_INVENTORY}; +constexpr unsigned INVENTORY_MAX_NUM=225,SPECIAL_INVENTORY_MAX_NUM=180; +struct Material{DWORD vnum,count;};struct TRefineTable{unsigned material_count=0;Material materials[5]={};}; +struct TItemPos{unsigned window,cell;TItemPos(unsigned w,unsigned c):window(w),cell(c){}}; +struct Character; +struct Item{unsigned id,cell,vnum,count;Character* owner=nullptr;bool equipped=false,exchanging=false,locked=false,skip=false; + unsigned GetID(){return id;}unsigned GetCell(){return cell;}unsigned GetVnum(){return vnum;}unsigned GetCount(){return count;} + Character* GetOwner(){return owner;}bool IsEquipped(){return equipped;}bool IsExchanging(){return exchanging;}bool isLocked(){return locked;}bool GetSkipSave(){return skip;}void SetCount(unsigned n){assert(n<=count);count=n;}}; +using LPITEM=Item*;struct Shop{unsigned selling=0;bool IsSellingItem(unsigned id){return id==selling;}}; +struct Character{std::map,Item*> items;Shop shop;Item* GetItem(TItemPos p){auto it=items.find({p.window,p.cell});return it==items.end()?nullptr:it->second;}Shop* GetMyShop(){return &shop;}}; +using LPCHARACTER=Character*; +#include "src/server/game/src/port_refine_materials.h" +int main(){Character ch;Item a{1,0,30053,2000,&ch},b{2,1,30006,1000,&ch};ch.items[{UPGRADE_INVENTORY,0}]=&a;ch.items[{INVENTORY,1}]=&b; + TRefineTable r;r.material_count=1;r.materials[0]={30053,1};assert(PortRefineTakeMaterials(&ch,&r)&&a.count==1999); + r.material_count=2;r.materials[0]={30053,1000};r.materials[1]={30053,1000};assert(!PortRefineTakeMaterials(&ch,&r)&&a.count==1999); + r.materials[1].count=999;assert(PortRefineTakeMaterials(&ch,&r)&&a.count==0); + r.material_count=1;r.materials[0]={30006,256}; + for(unsigned kind=0;kind<5;++kind){b.equipped=kind==0;b.exchanging=kind==1;b.locked=kind==2;b.skip=kind==3;ch.shop.selling=kind==4?b.id:0;assert(!PortRefineTakeMaterials(&ch,&r)&&b.count==1000);} + b.equipped=b.exchanging=b.locked=b.skip=false;ch.shop.selling=0;assert(PortRefineTakeMaterials(&ch,&r)&&b.count==744); + r.material_count=2;r.materials[0]={30006,500};r.materials[1]={30053,1};assert(!PortRefineTakeMaterials(&ch,&r)&&b.count==744); + r.material_count=0;assert(PortRefineTakeMaterials(&ch,&r)); +} +''' + with tempfile.TemporaryDirectory() as td: + p=Path(td)/'probe.cpp';p.write_text(code);exe=Path(td)/'probe' + subprocess.run(['c++','-std=c++17','-fsanitize=address,undefined','-I'+str(ROOT),str(p),'-o',str(exe)],check=True);subprocess.run([str(exe)],check=True) +if __name__=='__main__':unittest.main() diff --git a/tests/features/test_point_drop.py b/tests/features/test_point_drop.py index 1248cba9..f7342843 100644 --- a/tests/features/test_point_drop.py +++ b/tests/features/test_point_drop.py @@ -20,8 +20,9 @@ int main() { std::map flags={ENTRIES}; auto lookup=[&](const std::string& key){return flags[key];}; auto mob=PortPointRule(lookup,false),stone=PortPointRule(lookup,true); - assert(mob.chance==500 && mob.minimum==1 && mob.maximum==1); - assert(stone.chance==10000 && stone.minimum==3 && stone.maximum==8); + assert(mob.chance==5000 && mob.minimum==3 && mob.maximum==5); + assert(stone.chance==10000 && stone.minimum==15 && stone.maximum==30); + assert(mob.dailyCap==0 && stone.dailyCap==0); assert(mob.eligible(105,120));assert(!mob.eligible(104,120)); assert(stone.eligible(120,1));assert(!stone.eligible(0,1)); assert(!stone.eligible(120,0)); @@ -29,6 +30,8 @@ int main() { assert(PortPointDropAmount(8,500,500)==0); assert(PortPointDropAmount(8,UINT64_MAX,500)==0); assert(PortPointDropAmount(8,UINT64_MAX,0)==8); + assert(PortPointDropAmount(30,500,stone.dailyCap)==30); + assert(PortPointDropAmount(30,1000000,stone.dailyCap)==30); flags["points_mob_chance"]=0;assert(!PortPointRule(lookup,false).eligible(105,120)); flags["points_stone_chance"]=10001;assert(!PortPointRule(lookup,true).valid()); flags["points_stone_chance"]=10000;flags["points_stone_min"]=-1; diff --git a/tests/features/test_point_rollout.py b/tests/features/test_point_rollout.py new file mode 100644 index 00000000..076ab49b --- /dev/null +++ b/tests/features/test_point_rollout.py @@ -0,0 +1,79 @@ +"""Operational point rollout must target the intended DB and enable chances last.""" +import importlib.util +import json +from pathlib import Path +import tempfile +import unittest +from unittest.mock import Mock, patch + +ROOT = Path(__file__).resolve().parents[2] +spec = importlib.util.spec_from_file_location( + 'point_rollout', ROOT / 'tools/ava2-itemshop/configure_point_drops.py') +rollout = importlib.util.module_from_spec(spec) +spec.loader.exec_module(rollout) + + +class PointRollout(unittest.TestCase): + def test_only_reviewed_rules_are_enabled_after_caps_and_eligibility(self): + approved = json.loads((ROOT / 'tools/ava2-itemshop/points-wide.json').read_text()) + self.assertEqual(rollout.APPROVED, approved) + commands = rollout.rollout({}, approved) + self.assertEqual(commands[:2], [('points_mob_chance', 0), ('points_stone_chance', 0)]) + self.assertEqual(commands[-2:], [('points_mob_chance', 5000), ('points_stone_chance', 10000)]) + self.assertIn(('points_daily_cap', 0), commands[2:-2]) + self.assertIn(('points_mob_min', 3), commands[2:-2]) + self.assertIn(('points_mob_max', 5), commands[2:-2]) + self.assertIn(('points_stone_min', 15), commands[2:-2]) + self.assertIn(('points_stone_max', 30), commands[2:-2]) + self.assertIn(('points_max_overlevel', 15), commands[2:-2]) + self.assertEqual(dict(commands), approved) + self.assertEqual(rollout.rollout(approved, approved), []) + + def test_restoring_absent_flags_disables_rewards(self): + disabled = {key: 0 for key in rollout.APPROVED} + commands = rollout.rollout(rollout.APPROVED, disabled) + self.assertTrue(commands) + self.assertEqual(dict(commands), disabled) + self.assertFalse(any(value for key, value in commands if key in rollout.CHANCES)) + + def test_schema_and_db_port_mismatches_fail_closed(self): + with tempfile.TemporaryDirectory() as directory: + config = Path(directory) / 'CONFIG' + database = Path(directory) / 'conf.txt' + config.write_text('PORT: 13040\nDB_PORT: 15040\nADMINPAGE_IP: 127.0.0.1\n' + 'ADMINPAGE_PASSWORD: local-test-only\n') + database.write_text('SQL_PLAYER = "localhost player_sb root test"\n' + 'SQL_ACCOUNT = "localhost account_sb root test"\n') + rollout.validate_target(config, database, 'player_sb', 'account_sb', 15040) + with self.assertRaisesRegex(RuntimeError, 'schemas'): + rollout.validate_target(config, database, 'player', 'account', 15040) + with self.assertRaisesRegex(RuntimeError, 'DB_PORT'): + rollout.validate_target(config, database, 'player_sb', 'account_sb', 15000) + with self.assertRaisesRegex(RuntimeError, 'schema name'): + rollout.validate_target(config, database, 'player; DROP DATABASE player', 'account', 15040) + + def test_lan_listener_uses_allowlisted_loopback_source_and_checks_event_ack(self): + connection = Mock() + connection.recv.side_effect = [b'\xff' * 15, rollout.socket.timeout(), + b'UNKNOWN\n', b'EVENT FLAG CHANGE points_mob_chance\n'] + with patch.object(rollout.socket, 'create_connection', return_value=connection) as connect: + admin = rollout.Admin({'port': '13040', 'adminpage_password': 'test-only'}, + '192.168.21.203') + admin.event('points_mob_chance', 500) + connect.assert_called_once_with(('192.168.21.203', 13040), timeout=3, + source_address=('127.0.0.1', 0)) + self.assertEqual(connection.sendall.call_args_list[-1].args, + (b'@EVENT points_mob_chance 500\n',)) + + def test_unaccepted_event_does_not_count_as_applied(self): + connection = Mock() + connection.recv.side_effect = [rollout.socket.timeout(), b'UNKNOWN\n', b'UNKNOWN\n'] + with patch.object(rollout.socket, 'create_connection', return_value=connection): + admin = rollout.Admin({'port': '13040', 'adminpage_password': 'test-only'}, + '192.168.21.203') + with self.assertRaisesRegex(RuntimeError, 'rejected'): + admin.event('points_mob_chance', 500) + + +if __name__ == '__main__': + unittest.main() diff --git a/tests/features/test_point_settlement_runtime.py b/tests/features/test_point_settlement_runtime.py index 9c6dfbf8..64c0b4d7 100644 --- a/tests/features/test_point_settlement_runtime.py +++ b/tests/features/test_point_settlement_runtime.py @@ -108,6 +108,18 @@ int main(){ // Zero grants are durable results; later replay does not recalculate the cap. handler.m_map_lEventFlag["points_daily_cap"]=16;assert(settle(handler,r)==0 && granted()==0 && durable.coins==116); handler.m_map_lEventFlag["points_daily_cap"]=500;assert(settle(handler,r)==0 && granted()==0 && durable.coins==116); + // Removing the daily cap permits new rewards even after exceeding the old + // allowance. Committed tokens, including old zero grants, still replay once. + durable.rewards["old_daily_total"]={1,3,8021,1000,1000}; + handler.m_map_lEventFlag["points_daily_cap"]=0; + assert(settle(handler,r)==0 && granted()==0 && durable.coins==116); + handler.m_map_lEventFlag["points_stone_min"]=15; + handler.m_map_lEventFlag["points_stone_max"]=30;r.count=30; + strcpy(r.token,"4123456789abcdef0123456789abcdef"); + assert(settle(handler,r)==0 && granted()==30 && durable.coins==146); + assert(settle(handler,r)==0 && granted()==30 && durable.coins==146); + strcpy(r.token,"5123456789abcdef0123456789abcdef"); + assert(settle(handler,r)==0 && granted()==30 && durable.coins==176); } ''' with tempfile.TemporaryDirectory() as tmp: diff --git a/tests/features/test_shop_economy_runtime.py b/tests/features/test_shop_economy_runtime.py index 79779d96..3f53d44b 100644 --- a/tests/features/test_shop_economy_runtime.py +++ b/tests/features/test_shop_economy_runtime.py @@ -27,8 +27,8 @@ enum {POINT_GOLD,PORT_BP_NPC_SPEND,QUICKSLOT_TYPE_ITEM,DRAGON_SOUL_INVENTORY,INV bool LC_IsYMIR(){return false;}bool LC_IsKorea(){return false;} struct Character;using LPCHARACTER=Character*; struct TItemPos{TItemPos(int,int){}}; -struct Item {DWORD vnum=19,id=1;BYTE count=1;Character* owner=nullptr; - DWORD GetVnum(){return vnum;}DWORD GetID(){return id;}BYTE GetCount(){return count;} +struct Item {DWORD vnum=19,id=1;uint16_t count=1;Character* owner=nullptr; + DWORD GetVnum(){return vnum;}DWORD GetID(){return id;}uint16_t GetCount(){return count;} Character* GetOwner(){return owner;}int GetSize(){return 1;}bool IsDragonSoul(){return false;} const char* GetName(){return "item";}int GetCell(){return 0;} void RemoveFromCharacter(){owner=nullptr;}void AddToCharacter(Character* c,TItemPos){owner=c;} @@ -43,21 +43,25 @@ struct Character {int64_t gold=0;bool full=false;int writes=0,saves=0; struct ITEM_MANAGER {std::map items;int created=0,destroyed=0; static ITEM_MANAGER& instance(){static ITEM_MANAGER m;return m;} Item* Find(int id){return items.count(id)?items[id]:nullptr;} - Item* CreateItem(DWORD vnum,BYTE count){auto* item=new Item;item->vnum=vnum;item->count=count;items[++created+10]=item;return item;} + Item* CreateItem(DWORD vnum,uint16_t count){auto* item=new Item;item->vnum=vnum;item->count=count;items[++created+10]=item;return item;} void Destroy(Item* item){++destroyed;for(auto it=items.begin();it!=items.end();)if(it->second==item)it=items.erase(it);else ++it;delete item;} void FlushDelayedSave(Item*){} ~ITEM_MANAGER(){for(auto& it:items)if(it.first!=1)delete it.second;} }; #define M2_DESTROY_ITEM(i) ITEM_MANAGER::instance().Destroy(i) -struct LogManager {static LogManager& instance(){static LogManager m;return m;}templatevoid HackLog(T...){}templatevoid GoldBarLog(T...){}templatevoid ItemLog(T...){} }; +struct LogManager {static LogManager& instance(){static LogManager m;return m;}templatevoid HackLog(T...){}templatevoid CharLog(T...){}templatevoid GoldBarLog(T...){}templatevoid ItemLog(T...){} }; namespace quest {struct CQuestManager {int tax=3;static CQuestManager& instance(){static CQuestManager q;return q;}int GetEventFlag(const char* key){return std::string(key)=="personal_shop"?tax:1;} };} struct CMonarch {int64_t total=0;static CMonarch& instance(){static CMonarch m;return m;}void SendtoDBAddMoney(int64_t money,int,Character*){total+=money;} }; struct DBManager {int64_t logged=0;static DBManager& instance(){static DBManager m;return m;}void SendMoneyLog(int,DWORD,int64_t gold){logged+=gold;} }; void PortBpCount(Character*,int,int,int64_t){}void VCardUse(Character*,Character*,Item*){} -struct CShop {struct SHOP_ITEM{DWORD vnum=19;int64_t price=0;BYTE count=1;Item* pkItem=nullptr;int itemid=1;}; +struct CShop {struct SHOP_ITEM{int cheque=0;DWORD vnum=19;int64_t price=0;uint16_t count=1;Item* pkItem=nullptr;int itemid=1;}; using GuestMapType=std::map;GuestMapType m_map_guest;std::vector m_itemVector; Character* m_pkPC=nullptr;bool IsPCShop(){return m_pkPC!=nullptr;}void BroadcastUpdateItem(BYTE){}int Buy(Character*,BYTE); }; +''' + harness += r''' +constexpr int CHEQUE_MAX=999999,SHOP_SUBHEADER_GC_NOT_ENOUGH_CHEQUE=13; +bool PortChequeClientSupported(Character*){return true;}int PortChequeGet(Character*){return 0;}bool PortChequeCanChange(Character*,int){return true;}void PortChequeChange(Character*,int){} ''' extra_source=(ROOT/'src/server/game/src/shopEx.cpp').read_bytes().decode('latin1') extra_body=extra_source[extra_source.index('int CShopEx::Buy('):] @@ -75,7 +79,7 @@ struct CShopEx:CShop {std::vector m_vec_shopTabs;int GetTabCount() main = r''' int main(){ Character buyer,seller;Item item;item.owner=&seller;ITEM_MANAGER::instance().items[1]=&item; - CShop shop;shop.m_pkPC=&seller;shop.m_itemVector.resize(1);auto& row=shop.m_itemVector[0];row.price=300000000000LL;row.pkItem=&item; + item.count=2000;CShop shop;shop.m_pkPC=&seller;shop.m_itemVector.resize(1);auto& row=shop.m_itemVector[0];row.price=300000000000LL;row.pkItem=&item; shop.m_map_guest[&buyer]=true; // PC shop never charges an empire multiplier. buyer.gold=400000000000LL;seller.gold=GOLD_MAX_64-291000000000LL+1; assert(shop.Buy(&buyer,0)==SHOP_SUBHEADER_GC_NOT_ENOUGH_MONEY); diff --git a/tools/ava2-itemshop/README.md b/tools/ava2-itemshop/README.md index 9bc9008c..9571c567 100644 --- a/tools/ava2-itemshop/README.md +++ b/tools/ava2-itemshop/README.md @@ -82,4 +82,69 @@ Offline shop mutation and startup expiry cleanup are explicitly closed in game/d Keep the `.lock` sidecar in place for the writer's lifetime. Stop old binaries before upgrading a process that uses the same journal path; mixed old/new concurrent writers are unsupported. An I/O error pauses issuance, retaining a complete recovery source; fix the storage problem and preserve journal evidence before restarting. A corrupt log is not automatically truncated or compacted. These changes have standalone fault tests, including ELF32 probes, and do not replace real database/process-crash acceptance. +## 2026-10-26: increased rewards, no daily cap + +Current production/sbtest rules, explicitly selected by the user: +monsters and bosses have a 50% chance to award 3–5 points; stones always award +15–30 points. `points_daily_cap=0` means unlimited daily earnings, not zero +earnings. The minimum target level of 1 and maximum overlevel gap of 15 remain. +The profile in `points-wide.json` and the rollout tool defaults both use these +values. The 2026-10-25 profile below is historical and has been superseded. + +Applied through authenticated EVENT commands to production's 13 cores and +isolated channel5 without restarting or replacing any process. SQL and every +core's event log match all nine settings. Backups of the prior states are under +`/root/deploy-features/20261026-point-drops-increase/`: production uses +`production-before.json`, and the selected sbtest rollout uses +`sbtest-selected-before.json`. The initial `sbtest-before.json` preserves the +older 5%/1, 3–8, cap-500 profile before a temporary suggested profile; production +was updated directly from that older profile to the selected 50% profile. + +Ten point-related tests passed, including actual DB-handler code with a prior +daily total above 500, repeated 30-point awards with cap zero, and same-token +deduplication. This is a configuration/settlement test record, not a claim of a +controlled live kill after the change. Details and runtime evidence: +`metin2-client/docs/POINT-DROPS-INCREASE-20261026.md`. + +## 2026-10-25: restore missing point-drop flags (historical) + +The current production/sbtest game and db already include point rewards, but both +quest tables had no `points_*` event flags. Missing chance flags mean zero chance, +so neither monsters/bosses nor stones could award shop points. The then-approved rules +were enabled on production's 13 cores and isolated channel5 on 2026-10-25: +5% for monsters/bosses (1 point), 100% for stones (3–8), target at most 15 levels +below the character, and 500 points per account/day. Points credit the account +wallet; they are not ground items. No restart or binary replacement was needed. + +`configure_point_drops.py` defaults to a read-only plan. It verifies DB_PORT, +explicit player/account schemas and transactional tables, then uses the existing +authenticated admin EVENT channel so db persists and broadcasts the flags to all +connected cores. It first sets both chances to zero, applies limits/eligibility, +and enables the approved chances last. An exact match is a no-op. Credentials are +read locally from CONFIG and excluded from output/backups. For a core bound to +its LAN address, use `--host` while retaining the loopback source allowlist. + +```sh +# On 203; omit --apply/--backup to inspect only. +python3.9 configure_point_drops.py \ + --config /usr/metin2/server/channel1/first/CONFIG \ + --db-config /usr/metin2/server/db/conf.txt \ + --player player --account account --db-port 15000 --host 192.168.21.203 \ + --apply --backup /root/deploy-features/20261025-point-drops/NEW-before.json +``` + +Production backup: `/root/deploy-features/20261025-point-drops/production-before.json`. +Isolated backup: `sbtest-before-r2.json` in the same directory. To restore the +previous disabled state, add `--restore BACKUP` with the same explicit target and +a new `--backup` output. Absent flags restore as zero-valued disabled flags; +wallet balances and reward history are preserved. The first sbtest attempt +against a loopback-only destination was refused before any flags changed. + +Verification: five rollout guard tests plus seven existing eligibility, +settlement, completion and journal tests passed. SQL contains all nine expected +flags, and each of the 13 production cores plus channel5 logged the same values +without changing PIDs. No controlled post-change kill is claimed by this rollout; +reward ledgers were still empty at the observation checkpoint. Evidence and +client-facing notes: `metin2-client/docs/POINT-DROPS-ENABLE-20261025.md`. + Strict builds also promote `-Wshorten-64-to-32` to an error. The broader strict warning gate is still failing on legacy code; see the maintenance evidence for the exact blockers. diff --git a/tools/ava2-itemshop/configure_point_drops.py b/tools/ava2-itemshop/configure_point_drops.py new file mode 100644 index 00000000..e243e944 --- /dev/null +++ b/tools/ava2-itemshop/configure_point_drops.py @@ -0,0 +1,172 @@ +#!/usr/bin/env python3 +"""Review/apply approved point flags through a running core, without restarting it. + +Reads admin credentials only from CONFIG; never includes them in output/backups. +EVENT goes through game -> db -> all cores and persists flags in the quest table. +""" +import argparse +import datetime +import json +from pathlib import Path +import re +import socket +import subprocess +import time + +CHANCES = ('points_mob_chance', 'points_stone_chance') +APPROVED = {'points_mob_chance': 5000, 'points_mob_min': 3, 'points_mob_max': 5, + 'points_stone_chance': 10000, 'points_stone_min': 15, 'points_stone_max': 30, + 'points_min_level': 1, 'points_max_overlevel': 15, 'points_daily_cap': 0} + + +def config_values(path): + result = {} + for line in path.read_text().splitlines(): + words = line.split(None, 1) + if len(words) == 2: + result[words[0].rstrip(':').lower()] = words[1].strip() + return result + + +def db_schemas(path): + result = {} + for line in path.read_text().splitlines(): + match = re.match(r'^\s*(SQL_PLAYER|SQL_ACCOUNT)\s*=\s*"([^"]*)"', line) + if match: + result[match[1]] = match[2].split()[1] + return result + + +def validate_target(config, db_config, player, account, db_port): + for schema in (player, account): + if not re.fullmatch(r'[A-Za-z0-9_]+', schema): + raise RuntimeError('Invalid schema name') + values = config_values(config) + if int(values.get('db_port', '0')) != db_port: + raise RuntimeError('Core DB_PORT does not match the requested target') + if db_schemas(db_config) != {'SQL_PLAYER': player, 'SQL_ACCOUNT': account}: + raise RuntimeError('DB config does not match the requested schemas') + ips = ' '.join(v for k, v in values.items() if k.startswith('adminpage_ip')).split() + if '127.0.0.1' not in ips or not values.get('adminpage_password'): + raise RuntimeError('A configured loopback admin endpoint is required') + if '\n' in values['adminpage_password'] or '\r' in values['adminpage_password']: + raise RuntimeError('Invalid admin credential format') + return values + + +def mysql(sql): + return subprocess.check_output(['mysql', '--batch', '--skip-column-names'], + input=sql.encode()).decode().strip() + + +def snapshot(player, account): + names = ','.join("'%s'" % k for k in sorted(APPROVED)) + rows = mysql('SELECT szName,szState,lValue FROM `%s`.quest ' + 'WHERE dwPID=0 AND szName IN (%s) ORDER BY szName,szState' % (player, names)) + before = {} + for line in rows.splitlines(): + name, state, value = line.split('\t') + if state or name in before: + raise RuntimeError('Ambiguous event flag rows: ' + name) + before[name] = int(value) + engines = mysql("SELECT COUNT(*) FROM information_schema.tables WHERE ENGINE='InnoDB' AND " + "((TABLE_SCHEMA='%s' AND TABLE_NAME='port_point_rewards') OR " + "(TABLE_SCHEMA='%s' AND TABLE_NAME='account'))" % (player, account)) + if engines != '2': + raise RuntimeError('Transactional reward ledger/wallet prerequisites are missing') + return before + + +def rollout(before, desired): + if all(before.get(k, 0) == v for k, v in desired.items()): + return [] + # Quotas and eligibility must be active before any nonzero award probability. + return ([(k, 0) for k in CHANCES] + + [(k, desired[k]) for k in sorted(desired) if k not in CHANCES] + + [(k, desired[k]) for k in CHANCES]) + + +class Admin: + def __init__(self, values, host): + # Some cores bind only the machine's LAN address. Keep the connection's + # source on loopback so its existing admin IP allowlist still applies. + self.sock = socket.create_connection((host, int(values['port'])), timeout=3, + source_address=('127.0.0.1', 0)) + # Drain the normal binary phase/handshake before using text admin commands. + self.sock.settimeout(.2) + try: + while self.sock.recv(4096): + pass + except socket.timeout: + pass + self.sock.settimeout(3) + self.command(values['adminpage_password'], 'UNKNOWN') + + def command(self, command, expected): + self.sock.sendall(b'@' + command.encode() + b'\n') + result = b'' + while not result.endswith(b'\n'): + part = self.sock.recv(4096) + if not part or len(result) + len(part) > 4096: + raise RuntimeError('Admin response missing or oversized') + result += part + if result.strip() != expected.encode(): + raise RuntimeError('Admin command rejected; no credential/response is logged') + + def event(self, name, value): + self.command('EVENT %s %d' % (name, value), 'EVENT FLAG CHANGE ' + name) + + def close(self): + self.sock.close() + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--config', required=True, type=Path) + parser.add_argument('--db-config', required=True, type=Path) + parser.add_argument('--player', required=True) + parser.add_argument('--account', required=True) + parser.add_argument('--db-port', required=True, type=int) + parser.add_argument('--host', default='127.0.0.1', help='local listening address of the core') + parser.add_argument('--apply', action='store_true') + parser.add_argument('--backup', type=Path) + parser.add_argument('--restore', type=Path, help='restore flag values from this backup') + args = parser.parse_args() + values = validate_target(args.config, args.db_config, args.player, args.account, args.db_port) + before = snapshot(args.player, args.account) + desired = dict(APPROVED) + if args.restore: + saved = json.loads(args.restore.read_text()) + if (saved['player'], saved['account'], saved['db_port'], saved['config']) != ( + args.player, args.account, args.db_port, str(args.config.resolve())): + raise RuntimeError('Backup belongs to a different target') + desired = {k: int(saved['before'].get(k, 0)) for k in APPROVED} + commands = rollout(before, desired) + report = {'config': str(args.config.resolve()), 'player': args.player, + 'account': args.account, 'db_port': args.db_port, 'host': args.host, + 'created_utc': datetime.datetime.now(datetime.timezone.utc).isoformat(), + 'before': before, 'desired': desired, 'commands': commands, 'applied': False} + if args.apply and commands: + if not args.backup: + raise RuntimeError('--apply requires a new --backup path') + args.backup.parent.mkdir(parents=True, exist_ok=True) + with args.backup.open('x') as file: + json.dump(report, file, indent=2) + admin = Admin(values, args.host) + try: + for name, value in commands: + admin.event(name, value) + deadline = time.monotonic() + 5 + while snapshot(args.player, args.account) != desired: + if time.monotonic() >= deadline: + raise RuntimeError('Flags not persisted; inspect backup and runtime before retry') + time.sleep(.1) + finally: + admin.close() + report['applied'] = True + args.backup.with_suffix('.result.json').write_text(json.dumps(report, indent=2) + '\n') + print(json.dumps(report, sort_keys=True)) + + +if __name__ == '__main__': + main() diff --git a/tools/ava2-itemshop/points-wide.json b/tools/ava2-itemshop/points-wide.json index d64cda72..f40c8c34 100644 --- a/tools/ava2-itemshop/points-wide.json +++ b/tools/ava2-itemshop/points-wide.json @@ -1,11 +1,11 @@ { - "points_mob_chance": 500, - "points_mob_min": 1, - "points_mob_max": 1, + "points_mob_chance": 5000, + "points_mob_min": 3, + "points_mob_max": 5, "points_stone_chance": 10000, - "points_stone_min": 3, - "points_stone_max": 8, + "points_stone_min": 15, + "points_stone_max": 30, "points_min_level": 1, "points_max_overlevel": 15, - "points_daily_cap": 500 + "points_daily_cap": 0 } diff --git a/tools/material-stack/README.md b/tools/material-stack/README.md new file mode 100644 index 00000000..822d6976 --- /dev/null +++ b/tools/material-stack/README.md @@ -0,0 +1,16 @@ +# 材料与消耗品 2000 叠放工具 + +协议修订为 mt20261030,旧客户端必须升级。材料分类与正式清单由 catalogue.py 生成,所有不可合堆标记继续生效。实际数量协议为 uint16,内部及存档为32位。 + +- migrate.py --schema NAME 默认检查;--apply 扩展数量列并对比行数、数量总和,不支持缩窄。 +- cluster.py inventory --scope test|production 按实际 DB_PORT 分组;CH5 当前使用隔离库。deploy 需要候选路径、备份目录和 QA 登录白名单(逗号分隔),执行正常停服、备份、迁移、双端替换和健康检查;open 正常重启并取消白名单。 +- fallback 保留宽协议和宽存档,以环境变量停止超过200的新增长;已有大堆叠可整组移动和扣除,不能换回旧二进制。 +- provision_fixture.py 只创建全新的验收账号和角色;warehouse_fixture.py 仅用于 CH5 临时验收入口,验收后 remove 清理。私密文件只存于 build 或远端受限目录,不提交Git。 + +构建候选必须同时重建配套 libsql,再链接 game 与 db。仓库内预编译 libsql.a 可能与当前 AsyncSQL.h 不一致,不能直接链接后上线。使用候选目录并显式覆盖 Makefile 的 GAMEDIR/DBDIR;原始 Makefile 默认会将构建产物移动到正式服务目录。 + +上线前必须验证候选SHA、包长断言、真实客户端数量往返、普通仓库、洗练扣除、重启存档和旧版拒绝。部署失败期间保留维护状态与备份,不盲目恢复旧版读取大堆叠。 + +2026-10-27 已完成203正式上线:14个正式game/auth+db,CH5独立db与两个活动核心;19个配置二进制路径SHA一致,旧协议被拒绝。详见 docs/FEATURE-MATERIAL-STACK-2000.md。新增 port_refine_materials.h 保证强化能使用专用背包材料且全量预检后扣除。stress_fixture.py 仅在停止隔离集群后安装/清理满背包和确定性宝箱测试数据;warehouse_fixture.py 的 production scope 只允许新验收角色的普通仓库入口,禁止扩展发奖菜单,必须验收后移除并重启。所有临时夹具均已清理。 + +迁移报告额外保存数据完整指纹,比较物品身份和所有存档字段。源码工作区的原有未提交内容已保留,发布二进制以SHA256标识,不能仅用有dirty修改的Git HEAD判断版本。 diff --git a/tools/material-stack/catalogue.py b/tools/material-stack/catalogue.py new file mode 100644 index 00000000..6d17c269 --- /dev/null +++ b/tools/material-stack/catalogue.py @@ -0,0 +1,30 @@ +#!/usr/bin/env python3 +"""Export the active item-proto and recipe-derived 2000-stack coverage.""" +import argparse,json,re,subprocess +from pathlib import Path +TYPES={'ITEM_USE','ITEM_AUTOUSE','ITEM_MATERIAL','ITEM_METIN','ITEM_RESOURCE','ITEM_BLEND','ITEM_EXTRACT'} + +def catalogue(proto,cube,schema): + if not re.fullmatch('[A-Za-z0-9_]+',schema):raise ValueError('schema') + ingredients=set() + if cube.exists(): + for line in cube.read_text(errors='replace').splitlines(): + parts=line.split() + if len(parts)>=3 and parts[0]=='item' and parts[1].isdigit():ingredients.add(int(parts[1])) + query=' UNION '.join('SELECT vnum%d FROM `%s`.refine_proto WHERE vnum%d>0'%(i,schema,i) for i in range(5)) + result=subprocess.run(['mysql','-N','-e',query],check=True,capture_output=True,text=True) + ingredients.update(int(n) for n in result.stdout.split()) + records=[] + for line in proto.read_bytes().splitlines()[1:]: + f=[s.decode('latin1') for s in line.split(b'\t')] + if len(f)<7 or not re.fullmatch(r'\d+(?:~\d+)?',f[0]):continue + span=[int(n) for n in f[0].split('~')];lo=span[0];hi=span[-1] + stackable='ITEM_STACKABLE' in f[6] or 'STACKABLE' in f[6] + anti='ANTI_STACK' in f[5] + for vnum in range(lo,hi+1): + eligible=stackable and not anti and (f[2] in TYPES or vnum in ingredients) + if eligible:records.append(dict(vnum=vnum,type=f[2],old_limit=200,new_limit=2000,recipe_material=vnum in ingredients)) + return dict(schema=schema,proto=str(proto),cube=str(cube),covered_items=len(records),items=records) +if __name__=='__main__': + p=argparse.ArgumentParser();p.add_argument('--proto',type=Path,required=True);p.add_argument('--cube',type=Path,required=True);p.add_argument('--schema',required=True);p.add_argument('--output',type=Path,required=True);a=p.parse_args() + report=catalogue(a.proto,a.cube,a.schema);a.output.write_text(json.dumps(report,indent=2));print(json.dumps({'covered_items':report['covered_items'],'output':str(a.output)})) diff --git a/tools/material-stack/cluster.py b/tools/material-stack/cluster.py new file mode 100644 index 00000000..fed7e3cb --- /dev/null +++ b/tools/material-stack/cluster.py @@ -0,0 +1,131 @@ +#!/usr/bin/env python3 +"""Coordinated mt20261030 deployment. Run on 203; candidates must already be tested. + +Inventory uses CONFIG DB_PORT, not channel numbers: CH5 currently belongs to sbtest. +""" +import argparse,hashlib,json,os,pathlib,shutil,signal,subprocess,time +from migrate import run as migrate +ROOT=pathlib.Path('/usr/metin2/server') + +def digest(path):return hashlib.sha256(pathlib.Path(path).read_bytes()).hexdigest() +def alive(pid): + try:os.kill(pid,0);return True + except ProcessLookupError:return False + +def pid(core): + try:value=int((core/'pid').read_text().strip()) + except (ValueError,OSError):return 0 + if not alive(value):return 0 + output=subprocess.check_output(['procstat','-f',str(value)]).decode() + if not any(' cwd ' in line and str(core) in line for line in output.splitlines()): + raise RuntimeError('PID does not belong to '+str(core)) + return value + +def config(path): + result={} + for line in path.read_text(errors='replace').splitlines(): + key,sep,value=line.partition(':') + if sep:result[key.strip()]=value.strip() + return result + +def inventory(scope): + dbport='15040' if scope=='test' else '15000' + configs=list(ROOT.glob('channel*/**/CONFIG'))+[ROOT/'auth/CONFIG',ROOT/'game99/CONFIG']+list((ROOT/'sbtest').glob('*/CONFIG')) + cores=[] + for path in sorted(set(configs)): + if not path.is_file():continue + cfg=config(path) + if cfg.get('DB_PORT')!=dbport:continue + directory=path.parent + exe='auth' if directory.name=='auth' else 'game' + cores.append(dict(path=str(directory),executable=exe,port=int(cfg['PORT']),pid=pid(directory))) + db=ROOT/('sbtest/db' if scope=='test' else 'db') + return dict(scope=scope,cores=cores,db=dict(path=str(db),executable='db',port=int(dbport),pid=pid(db))) + +def stop(entries): + running=[] + for entry in entries: + value=pid(pathlib.Path(entry['path'])) + if value:os.kill(value,signal.SIGHUP);running.append(value) + deadline=time.time()+180 + while any(alive(value) for value in running): + if time.time()>deadline:raise RuntimeError('graceful stop timed out') + time.sleep(.5) + +def replace(source,target): + target=pathlib.Path(target);tmp=target.with_name(target.name+'.stack2000-new') + shutil.copy2(source,tmp);tmp.chmod(0o755);tmp.replace(target) + +def start(entries,qa_login='',legacy=False): + env=dict(os.environ) + if qa_login:env['PORT_MATERIAL_STACK_QA_LOGIN']=qa_login + else:env.pop('PORT_MATERIAL_STACK_QA_LOGIN',None) + if legacy:env['PORT_MATERIAL_STACK_LEGACY_MODE']='1' + else:env.pop('PORT_MATERIAL_STACK_LEGACY_MODE',None) + for entry in entries: + directory=pathlib.Path(entry['path']) + if pid(directory):raise RuntimeError('process still running before startup') + subprocess.run(['daemon','-f','-o',str(directory/'stack2000.stdout'),'./'+entry['executable']],cwd=directory,env=env,check=True) + time.sleep(.25) + deadline=time.time()+90 + while True: + sockets=subprocess.check_output(['sockstat','-4','-l','-P','tcp']).decode() + missing=[e['path'] for e in entries if not pid(pathlib.Path(e['path'])) or (':'+str(e['port'])+' ') not in sockets] + if not missing:return + if time.time()>deadline:raise RuntimeError('startup failed: '+','.join(missing)) + time.sleep(1) + +def deploy(scope,candidate,backup,qa_login): + state=inventory(scope) + state['configured_cores']=list(state['cores']) + state['cores']=[entry for entry in state['cores'] if entry['pid']] + if not state['cores'] or not state['db']['pid']:raise RuntimeError('no running cluster to deploy') + candidate=pathlib.Path(candidate);backup=pathlib.Path(backup) + if backup.exists():raise RuntimeError('backup path already exists') + for name in ['game','db']: + if not (candidate/name).is_file():raise RuntimeError('candidate missing '+name) + backup.mkdir(parents=True,mode=0o700) + state['candidates']={name:digest(candidate/name) for name in ['game','db']} + for entry in state['configured_cores']+[state['db']]: + directory=pathlib.Path(entry['path']);exe=directory/entry['executable'] + entry['original_target']=str(exe.resolve());entry['was_symlink']=exe.is_symlink() + entry['original_sha256']=digest(exe) + if scope=='production': + expected=ROOT/'share/bin'/('db' if entry['executable']=='db' else 'game') + if exe.resolve()!=expected.resolve():raise RuntimeError('unhandled production binary path: '+str(exe)) + label=directory.relative_to(ROOT).as_posix().replace('/','_') + shutil.copy2(exe,backup/(label+'.binary')) + for filename in ['CONFIG','conf.txt']: + path=directory/filename + if path.exists():shutil.copy2(path,backup/(label+'.'+filename)) + error=directory/'syserr';entry['error_offset']=error.stat().st_size if error.exists() else 0 + (backup/'metadata.json').write_text(json.dumps(state,indent=2));(backup/'metadata.json').chmod(0o600) + stop(state['cores']);stop([state['db']]) + schemas=['player_sb','account_sb','common_sb'] if scope=='test' else ['player','account','common'] + for schema in schemas: + path=backup/(schema+'.sql') + with path.open('wb') as out:subprocess.run(['mysqldump','--default-character-set=binary','--single-transaction','--routines','--triggers',schema],stdout=out,stderr=subprocess.PIPE,check=True) + path.chmod(0o600) + report=migrate(schemas[0],True) + (backup/'migration.json').write_text(json.dumps(report,indent=2)) + if scope=='production': + replace(candidate/'game',ROOT/'share/bin/game');replace(candidate/'db',ROOT/'share/bin/db') + else: + for name in ['game','db']:replace(candidate/name,ROOT/('sbtest/'+name+'.stack2000')) + for entry in state['configured_cores']+[state['db']]: + exe=pathlib.Path(entry['path'])/entry['executable'];source=ROOT/('sbtest/'+('db' if entry['executable']=='db' else 'game')+'.stack2000') + temp=exe.with_name(exe.name+'.stack2000-link');temp.symlink_to(source);temp.replace(exe) + start([state['db']],qa_login);start(state['cores'],qa_login) + (backup/'DEPLOYED_QA').write_text(json.dumps(state['candidates'])) + print(json.dumps({'backup':str(backup),'inventory':inventory(scope),'qa_only':bool(qa_login)})) + +if __name__=='__main__': + p=argparse.ArgumentParser();p.add_argument('action',choices=['inventory','deploy','open','fallback']);p.add_argument('--scope',choices=['test','production'],required=True);p.add_argument('--candidate');p.add_argument('--backup');p.add_argument('--qa-login',default='');a=p.parse_args() + if a.action=='inventory':print(json.dumps(inventory(a.scope),indent=2)) + elif a.action=='deploy': + if not a.candidate or not a.backup or not a.qa_login:p.error('deploy requires candidate, backup and QA login') + deploy(a.scope,a.candidate,a.backup,a.qa_login) + else: + state=inventory(a.scope);cores=[e for e in state['cores'] if e['pid']] + stop(cores);stop([state['db']]);start([state['db']],a.qa_login,legacy=a.action=='fallback');start(cores,a.qa_login,legacy=a.action=='fallback') + print(json.dumps({'inventory':inventory(a.scope),'legacy_growth':a.action=='fallback'})) diff --git a/tools/material-stack/migrate.py b/tools/material-stack/migrate.py new file mode 100644 index 00000000..f594ed61 --- /dev/null +++ b/tools/material-stack/migrate.py @@ -0,0 +1,62 @@ +#!/usr/bin/env python3 +"""Inspect/expand item quantity columns; never narrows columns or rewrites item rows.""" +import argparse +import hashlib +import json +import re +import subprocess + + +def sql(query): + result = subprocess.run(['mysql', '--batch', '--skip-column-names', '-e', query], + check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True) + return [line.split('\t') for line in result.stdout.splitlines()] + + +def identifier(value): + if not re.fullmatch(r'[A-Za-z0-9_]+', value): + raise ValueError('invalid database identifier') + return '`' + value + '`' + + +def run(schema, apply=False): + identifier(schema) + rows = sql("SELECT TABLE_NAME,COLUMN_NAME,COLUMN_TYPE,IS_NULLABLE,COLUMN_DEFAULT " + "FROM information_schema.COLUMNS WHERE TABLE_SCHEMA='%s' " + "AND COLUMN_NAME IN ('count','item_count')" % schema) + report = [] + for table, column, kind, nullable, default in rows: + if not (table in ('item','item_orphan_quarantine','shop_item','item_award') or + 'item' in table or 'custody' in table): + continue + target = identifier(schema) + '.' + identifier(table) + field = identifier(column) + before = sql('SELECT COUNT(*),COALESCE(SUM(%s),0) FROM %s' % (field,target)) + def fingerprint(): + # Data-only canonical dump includes item identities and every saved + # field; column widening must preserve more than aggregate totals. + data=subprocess.check_output(['mysqldump','--no-create-info','--skip-extended-insert', + '--skip-comments','--compact','--order-by-primary','--hex-blob',schema,table],stderr=subprocess.PIPE) + return hashlib.sha256(data).hexdigest() + old_fingerprint=fingerprint() + change = kind.lower().startswith(('tinyint','smallint','mediumint')) + entry = dict(table=table,column=column,old_type=kind,needs_expansion=change,before=before,data_sha256=old_fingerprint) + if change and apply: + if default != 'NULL' and not re.fullmatch(r'\d+',default): + raise RuntimeError('unexpected quantity default for '+table) + declaration = 'INT UNSIGNED ' + ('NULL' if nullable=='YES' else 'NOT NULL') + if default != 'NULL': declaration += ' DEFAULT ' + default + sql('ALTER TABLE %s MODIFY COLUMN %s %s' % (target,field,declaration)) + after=sql('SELECT COUNT(*),COALESCE(SUM(%s),0) FROM %s' % (field,target)) + if before != after: raise RuntimeError('quantity totals changed: '+table) + after_fingerprint=fingerprint() + if after_fingerprint!=old_fingerprint:raise RuntimeError('item identities/data changed: '+table) + entry.update(after=after,new_type='int unsigned',after_data_sha256=after_fingerprint) + report.append(entry) + if not any(row['table']=='item' for row in report): + raise RuntimeError('item table was not found') + return dict(schema=schema,applied=apply,columns=report) + +if __name__=='__main__': + parser=argparse.ArgumentParser();parser.add_argument('--schema',required=True);parser.add_argument('--apply',action='store_true') + args=parser.parse_args();print(json.dumps(run(args.schema,args.apply),indent=2)) diff --git a/tools/material-stack/provision_fixture.py b/tools/material-stack/provision_fixture.py new file mode 100644 index 00000000..598c4842 --- /dev/null +++ b/tools/material-stack/provision_fixture.py @@ -0,0 +1,39 @@ +#!/usr/bin/env python3 +"""Create a fresh, isolated QA character. Does not edit any existing account or item.""" +import argparse,json,re,subprocess +from pathlib import Path + +def sql(q): + r=subprocess.run(['mysql','-N','-e',q],check=True,capture_output=True,text=True) + return [row.split('\t') for row in r.stdout.splitlines()] +def ident(s): + if not re.fullmatch(r'[a-zA-Z0-9_]+',s):raise ValueError('identifier') + return '`'+s+'`' +def value(s):return '0x'+s.encode().hex() +def clone(table,overrides,where): + cols=[x[0] for x in sql('SHOW COLUMNS FROM '+table) if x[0]!='id'] + fields=','.join(ident(c) for c in cols) + expressions=','.join(overrides.get(c,ident(c)) for c in cols) + sql('INSERT INTO '+table+' ('+fields+') SELECT '+expressions+' FROM '+table+' WHERE '+where+' LIMIT 1') + +if __name__=='__main__': + p=argparse.ArgumentParser();p.add_argument('--player-schema',required=True);p.add_argument('--account-schema',required=True);p.add_argument('--private-file',required=True);a=p.parse_args() + private=Path(a.private_file);secrets=json.loads(private.read_text());login=secrets['login'];name=secrets['name'] + if len(secrets['password'])>16:raise ValueError('login UI password limit is 16') + acc=ident(a.account_schema)+'.account';player=ident(a.player_schema)+'.player';index=ident(a.player_schema)+'.player_index' + if sql('SELECT id FROM '+acc+' WHERE login='+value(login)):raise RuntimeError('fixture account already exists') + if sql('SELECT id FROM '+player+' WHERE name='+value(name)):raise RuntimeError('fixture character already exists') + clone(acc,{'login':value(login),'password':'PASSWORD('+value(secrets['password'])+')','status':"'OK'",'create_time':'NOW()'},'1 ORDER BY id') + aid=int(sql('SELECT id FROM '+acc+' WHERE login='+value(login))[0][0]) + replacements={'account_id':str(aid),'name':value(name),'job':'0','level':'10','gold':'1000000','exp':'0','map_index':'1','x':'477100','y':'956700','z':'0','exit_map_index':'1','exit_x':'477100','exit_y':'956700','hp':'10000','sp':'10000'} + clone(player,replacements,'job=0 ORDER BY id') + pid=int(sql('SELECT id FROM '+player+' WHERE name='+value(name))[0][0]) + sql('INSERT INTO '+index+' (id,pid1,pid2,pid3,pid4,pid5,empire) VALUES (%d,%d,0,0,0,0,1)'%(aid,pid)) + item=ident(a.player_schema)+'.item' + for i,count in enumerate([199,200,201,255,256,1999,2000]): + sql("INSERT INTO "+item+" (owner_id,window,pos,count,vnum,port_extra) VALUES (%d,'INVENTORY',%d,%d,30006,%s)"%(pid,180+i,count,'0x'+'00'*69)) + for cell,vnum,count in [(192,71085,2000),(193,71084,2000),(194,19,1)]: + sql("INSERT INTO "+item+" (owner_id,window,pos,count,vnum,port_extra) VALUES (%d,'INVENTORY',%d,%d,%d,%s)"%(pid,cell,count,vnum,'0x'+'00'*69)) + secrets.update(account_id=aid,player_id=pid,player_schema=a.player_schema,account_schema=a.account_schema) + private.write_text(json.dumps(secrets));private.chmod(0o600) + print(json.dumps({'account_id':aid,'player_id':pid,'schema':a.player_schema,'seeded_count':sql('SELECT SUM(count) FROM '+item+' WHERE owner_id='+str(pid))[0][0]})) diff --git a/tools/material-stack/stress_fixture.py b/tools/material-stack/stress_fixture.py new file mode 100644 index 00000000..c584e455 --- /dev/null +++ b/tools/material-stack/stress_fixture.py @@ -0,0 +1,39 @@ +#!/usr/bin/env python3 +"""CH5 QA-only full inventory / deterministic chest fixture. Run with isolated cores/db stopped.""" +import argparse,json,re,subprocess +from pathlib import Path +from cluster import inventory +BASE=Path('/root/deploy-features/20261026-stack2000') +def sql(q):return subprocess.check_output(['mysql','-N','-e',q],text=True).strip() +p=argparse.ArgumentParser();p.add_argument('action',choices=['install','remove']);p.add_argument('--private-file',required=True);a=p.parse_args() +s=inventory('test') +if s['db']['pid'] or any(e['pid'] for e in s['cores']):raise RuntimeError('stop isolated cluster before fixture mutation') +secret=json.loads(Path(a.private_file).read_text());assert secret['player_schema']=='player_sb' +pid=int(secret['player_id']);manifest=BASE/'stress-fixture.json' +if a.action=='remove': + data=json.loads(manifest.read_text()) + ids=','.join(map(str,data['fillers'])) + if ids:sql('DELETE FROM player_sb.item WHERE owner_id=%d AND vnum=11000 AND id IN (%s)'%(pid,ids)) + path=Path(data['group_path']);assert not path.is_symlink();path.unlink();path.symlink_to(data['group_target']) + manifest.unlink();print('QA fillers and isolated chest override removed') +else: + if manifest.exists():raise RuntimeError('fixture already installed') + rows=sql("SELECT i.pos,p.size FROM player_sb.item i JOIN player_sb.item_proto p ON i.vnum=p.vnum WHERE i.owner_id=%d AND i.window='INVENTORY' AND i.pos<225"%pid) + occupied=set() + for row in rows.splitlines(): + cell,size=map(int,row.split());occupied.update(cell+5*j for j in range(size)) + for cell,vnum,count,size in [(197,16,1,2),(198,50037,2,1)]: + cells={cell+5*j for j in range(size)} + if cells&occupied:raise RuntimeError('QA seed cells occupied') + sql("INSERT INTO player_sb.item(owner_id,window,pos,count,vnum,port_extra) VALUES(%d,'INVENTORY',%d,%d,%d,UNHEX(REPEAT('00',69)))"%(pid,cell,count,vnum));occupied.update(cells) + ids=[] + for cell in range(225): + if cell in occupied:continue + ids.append(int(sql("INSERT INTO player_sb.item(owner_id,window,pos,count,vnum,port_extra) VALUES(%d,'INVENTORY',%d,1,11000,UNHEX(REPEAT('00',69)));SELECT LAST_INSERT_ID()"%(pid,cell)))) + path=Path('/usr/metin2/server/sbtest/share/locale/newcibn/special_item_group.txt');assert path.is_symlink();target=str(path.readlink());blob=path.read_bytes() + pattern=rb'(?m)^Group[^\r\n]*\r?\n\{.*?^\}' + def keep(m):return b'' if re.search(rb'\bVnum\s+50037\b',m[0],re.I) else m[0] + blob=re.sub(pattern,keep,blob,flags=re.S)+b'\nGroup STACK2000_QA\n{\n Vnum 50037\n 1 27002 2000 100\n}\n' + data=dict(fillers=ids,group_path=str(path),group_target=target) + manifest.write_text(json.dumps(data));manifest.chmod(0o600);path.unlink();path.write_bytes(blob) + print('QA-only full inventory prepared; filler count',len(ids)) diff --git a/tools/material-stack/warehouse_fixture.py b/tools/material-stack/warehouse_fixture.py new file mode 100644 index 00000000..28f87c9a --- /dev/null +++ b/tools/material-stack/warehouse_fixture.py @@ -0,0 +1,37 @@ +#!/usr/bin/env python3 +"""Temporary CH5-only NPC click fixture for a named QA character; remove after acceptance.""" +import argparse,json,pathlib,re,shutil,subprocess +BASE=pathlib.Path('/root/deploy-features/20261026-stack2000') +QUEST=pathlib.Path('/usr/metin2/server/sbtest/share/locale/newcibn/quest') +if __name__=='__main__': + p=argparse.ArgumentParser();p.add_argument('action',choices=['install','remove']);p.add_argument('--private-file',required=True);p.add_argument('--extended',action='store_true');p.add_argument('--scope',choices=['test','production'],default='test');a=p.parse_args() + if a.scope=='production': + if a.extended:raise RuntimeError('extended fixtures are isolated-only') + QUEST=pathlib.Path('/usr/metin2/server/share/locale/newcibn/quest') + manifest=BASE/('warehouse-fixture-files.json' if a.scope=='test' else 'warehouse-fixture-production-files.json') + if a.action=='remove': + if manifest.exists(): + for name in json.loads(manifest.read_text()): + path=pathlib.Path(name) + if not path.is_relative_to(QUEST/'object'):raise RuntimeError('unexpected fixture path') + path.unlink(missing_ok=True) + manifest.unlink() + else: + s=json.loads(pathlib.Path(a.private_file).read_text());name=s['name'] + if not re.fullmatch('[A-Za-z0-9]+',name):raise ValueError('name') + work=BASE/('warehouse-quest' if a.scope=='test' else 'warehouse-quest-production');work.mkdir(exist_ok=True) + shutil.copy2(QUEST/'quest_functions',work/'quest_functions') + source=work/'stack2000_acceptance.quest' + actions={'STACK2000_QA':'game.open_safebox()'} + if a.extended:actions.update(STACK2000_SHOP='npc.open_shop(65001)',STACK2000_MALL='game.open_mall()',STACK2000_GRANT='pc.give_item2(30007,4001)',STACK2000_CUBE='command("cube open")',STACK2000_CUBE_MATERIAL='pc.give_item2(30008,2000)',STACK2000_FULL='pc.give_item2(27003,2001)',STACK2000_REFINE='pc.give_item2(30053,2000) mob.spawn(20016,pc.get_local_x()+1,pc.get_local_y()+1,0,false,1)') + clauses=['when 9005.chat."'+label+'" with pc.get_name()=="'+name+'" begin\n setskin(NOWINDOW)\n '+action+'\n end' for label,action in actions.items()] + source.write_text('quest stack2000_acceptance begin\n state start begin\n'+'\n'.join(clauses)+'\n end\nend\n') + shutil.rmtree(work/'object',ignore_errors=True) + subprocess.run([str(QUEST/'qc'),str(source)],cwd=work,check=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE) + files=[] + for path in (work/'object').rglob('*'): + if not path.is_file():continue + target=QUEST/'object'/path.relative_to(work/'object') + if target.exists():raise RuntimeError('fixture path already exists') + target.parent.mkdir(parents=True,exist_ok=True);shutil.copy2(path,target);files.append(str(target)) + manifest.write_text(json.dumps(files));print('fixture files',len(files))