Author SHA1 Message Date
shenleiandClaude Opus 5.5 a22c064587 Add attribute lock buttons to the switchbot window
Five per-slot toggles next to start/stop, shown only when the server
sends the MTSB1 lock line; locked attributes are marked in the current
attribute line. Server side: metin2-server docs/FEATURE-ATTR-LOCK.md.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-15 23:06:00 +09:00
shenleiandClaude Opus 5.5 ffe097ec57 Add world boss window (AVA2 uitrack world-boss tab, read-only)
mt_boss lists the server's timed boss regens from the MTF1 "bosses"
query: alive/max, countdown, map-local position and period, paged by 8,
with per-boss spawn reminders that only fire on a fresh alive snapshot.
Teleport is left out.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-15 22:36:04 +09:00
shenleiandClaude Opus 5.5 13a462b6fc Add client-only channel switch (AVA2 ENABLE_CHANNEL_CHANGE)
mt_channel lists the serverInfo channels of the current server and switches by
running the original paths: /logout, then the login window connects to the
chosen channel with the account kept by MainStream, and the original
stream.isAutoSelect starts the same character. No server change.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-15 21:37:02 +09:00
shenleiandClaude Opus 5.5 aeb67f3c9c Hide near trees drawn as PC blockers when trees are switched off
A tree close to the camera is drawn by RenderPCBlocker, not RenderTree,
so background.SetVisiblePart(PART_TREE, 0) left it on screen. Skip tree
blockers while PART_TREE is hidden. Live screenshots on the 203 test
core confirm the tree, the GM mark and the weapon glow now disappear.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-15 21:24:53 +09:00
shenleiandClaude Opus 5.5 e546f91e03 Add AVA2-style display options (effect level, trees, clouds)
Client-only port of ENABLE_GRAPHIC_ON_OFF / HIDE_OBJECTS: five effect
levels toggle attached actor effects via Active/Deactive, tree and cloud
parts use background.SetVisiblePart, plus shortcuts for the original
name and damage options. mt_display window, mt_display.cfg, port.display
test, docs/AVA2-DISPLAY.md.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-15 21:11:25 +09:00
shenleiandClaude Opus 5.5 e22d7ba6fd Add batch pickup on the pickup key for the server mt_pickup command
Embedded module mt_pickup wraps GameWindow.PickUpItem (Z / `): with batch
pickup on it sends /mt_pickup 1 MASK (0.5 s gap, one in flight, presses
swallowed while waiting); after 3 s without a reply it notes once in chat
and falls back to the original single pickup. Settings window (on/off and
8 categories, persisted in mt_pickup.cfg) behind a "拾取" button under the
switchbot entry by the minimap.

Live tested against 203 (channel-5 test core, port 13040) with the macOS
native client.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-15 20:45:37 +09:00
shenleiandClaude Opus 5.5 514eae6745 Record live switchbot busy/no_scroll/rejected results
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-15 19:49:21 +09:00
shenleiandClaude Opus 5.5 6b1d21a2c5 Add switchbot (自动洗练) window for the server mt_switchbot command
Embedded module mt_switchbot: a paced request queue (0.3 s gap, one in
flight, 4 s timeout -> unsupported), atomic attrs lists from the server,
two alternatives of up to 5 targets, 10-1000 roll limits, live state and
stop reasons. Entry button under the wiki button by the minimap. The
selection follows the server-reported cell when the item moves mid-run
and falls back to the same vnum when it moves while idle.

Live tested against 203 (channel-5 test core, port 13040) with the macOS
native client.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-15 19:45:14 +09:00
30 changed files with 2339 additions and 9 deletions
+4
View File
@@ -35,6 +35,10 @@ __pycache__/
# Written by 40250 uitaskbar.py at runtime. # Written by 40250 uitaskbar.py at runtime.
/mouse.cfg /mouse.cfg
# Written at runtime by the mt_* option windows (mt_pickup, mt_display, ...).
/mt_*.cfg
/Client/mt_*.cfg
# native Android client (./android/build.sh): SDL3 download, NDK builds, Gradle output # native Android client (./android/build.sh): SDL3 download, NDK builds, Gradle output
/android/.gradle/ /android/.gradle/
/android/app/build/ /android/app/build/
+64
View File
@@ -0,0 +1,64 @@
# AVA2 世界 Boss 追踪进度(v1)
2026-10-15。参考 AVA2 `uitrack` 的世界 Boss 页,只读。服务端见 metin2-server `docs/FEATURE-BOSS-TRACK.md`。没有移植 AVA2 的传送按钮(它会改变游戏进程);副本页已经由 `mt_dungeons` 实现。
## 与 AVA2 的差异
| 项目 | AVA2 | 本实现 |
| --- | --- | --- |
| 数据来源 | 专用封包 | 原有 `/mt_features` 查询,种类 `bosses`(能力位 256) |
| 跨核心 | 不明(AVA2 服务端源码不在本机) | 每个核心用原 `HEADER_GG_RELAY` 广播自己的 Boss 刷新点,旧核心会忽略 |
| 传送 | 有 | 无 |
| 提醒 | 有 | 有:刷新后在聊天框提示,以服务器快照为准 |
## 窗口
- 入口:小地图左侧按钮列中的“Boss”(换线按钮下方)。
- 标题“世界Boss”,有“刷新”“上一页/下一页”按钮,每页 8 行。
- 每行显示:
- `[CHn]` 或 `[共享]`(频道 99)、Boss 名、地图名;
- 状态(存活 a/m、刷新倒计时、即将刷新、不再刷新)、坐标(地图内坐标 /100,`ANYWHERE` 显示“随机位置”)、刷新周期;
- “提醒:开/关”按钮,只能对未存活、有计时的 Boss 打开。
- 窗口打开时每 30 秒刷新一次。倒计时按服务器时间和本地经过时间计算。
- 名称:
- Boss 名取自 `nonplayer.GetMonsterName`;
- 地图名用服务端地图编号 → 地图目录(`MAPS`,取自服务端 `map/index`)在 `localeInfo.MINIMAP_ZONE_NAME_DICT` 中查找;
- 找不到时显示“地图N”。
## 提醒
- 提醒的键是 (vnum, 地图, 频道, x, y)。
- 窗口关闭时,提醒过的 Boss 计时到期 2 秒后,客户端会主动查询一次。
- 只有新快照显示它存活时,聊天框才提示“X 已在 Y 刷新”,然后清除这条提醒;只到计时不提示。
- 服务器不再列出的 Boss 会被移出提醒。
- 离开游戏(换线、换角色)时,清空快照和提醒。
## 客户端
- 模块 `mt_boss`(`src/platform/ScriptLib/BossScript.inc`),在 `PythonBoot.cpp` 中安装,挂接 `game.GameWindow.Open/Close`。
- `FeatureServiceScript.inc`:
- 新增 `bosses` 种类和 `boss` 行解析(13 项,X/Y 有符号);
- 校验 vnum/地图/周期非 0、频道 ≤ 255、alive ≤ max ≤ 255;
- 一次最多 128 行。
## 证据
- `tests/wiki/test_boss.py`(CTest:`port.boss`)共 5 项通过,覆盖:
- 入口位置、各状态文字、坐标、分页;
- 只在确认刷新后提示;
- 未启用和空列表的提示;
- 关闭时复位;
- 地图表。
- `tests/wiki/test_service.py` 新增 `boss` 行和旧服务端(cap 255)返回 unsupported 的测试。
- 2026-10-15 联机测试(203,macOS 原生客户端,账号 admin):
- 临时开了两个 channel5 核心:13040 放地图 1/21/41/68,13041 放地图 72/5。
- 从任一核心进入游戏,窗口都列出两个核心的 5 个 Boss(海盗 5001 ×2、2307、1192、5161),倒计时一致。
- 截图确认布局正常。测试后 channel5 已恢复原配置。
## 限制和未完成
- 只列出有定时刷新的 Boss 刷新点(regen 文件里 `time > 0`);由任务或事件刷出的 Boss 不在列表中。
- 共享频道(game99)的 Boss 要等 game99 换上新服务端才会出现。
- 副本内地图(如 5、72)在 `MINIMAP_ZONE_NAME_DICT` 中没有名称,显示“地图N”。
- macOS 桌面客户端没有中文字体,窗口文字显示为 `?`。
- Android 真机测试未做。
+54
View File
@@ -0,0 +1,54 @@
# AVA2 换线适配进度(v1)
2026-10-15。只改了 metin2-client,服务端不需要改动。参考了 AVA2 的 `ENABLE_CHANNEL_CHANGE`(`Locale_inc.h`)。AVA2 客户端只接收 `HEADER_GC_CHANNEL`(121)来显示当前频道,真正的换线由服务端完成;AVA2 服务端源码不在本机,所以这里没有照搬它的做法。
## 与 AVA2 的差异
| 项目 | AVA2 | 本实现 |
| --- | --- | --- |
| 换线方式 | 服务端把角色传送到目标频道的核心 | 客户端依次走原有流程:`/logout` → 登录界面 → 用保存的账号登录目标频道 → 自动选择同一角色进入游戏 |
| 服务端改动 | 需要(频道到端口的对应关系,或 DB/P2P 协议) | 不需要;本服务端的核心之间不知道其他频道的监听端口 |
| 频道列表 | 服务端提供 | 客户端 `serverInfo.REGION_DICT`,与登录界面的频道列表相同 |
| 等待时间 | 传送 | 原 `/logout` 倒计时(3 秒,战斗中 10 秒)加一次登录和读图 |
## 流程
1. 游戏内点“换线”,窗口列出当前服务器的频道。当前频道用 `【】` 标出且不能点。当前频道按 `MainStream` 的连接地址在 `serverInfo` 中查找;找不到时(例如测试端口 13040)显示“未知”,服务器取 `channel.inf` 中上次选择的服务器。
2. 选择频道后发送原 `/logout`。服务端倒计时,结束后关闭连接;`OnRemoteDisconnect` 调用 `SetLoginPhase`。
3. `introLogin.LoginWindow.Open` 之后,脚本把连接信息设为目标频道(认证服务器取 `REGION_AUTH_SERVER_DICT`),写入 `channel.inf` 和 `net.SetServerInfo`,打开 `stream.isAutoSelect` 并恢复原来的角色槽位,然后调用原 `LoginWindow.Connect`,账号密码取自 `MainStream.id/pwd`。
4. `introSelect.SelectCharacterWindow.Open` 中原有的 `isAutoSelect` 分支选择同一槽位并 `StartGame`。
5. 进入游戏后关闭 `isAutoSelect`,聊天框提示“已换到 CHx”。
换线进行中所有频道按钮都不能点:再次发送 `/logout` 会取消服务端倒计时。
## 失败处理
- 20 秒内服务端没有断开连接(例如刚战斗过,`IsHack` 拒绝退出),取消换线并提示。
- 登录失败或连接失败时,取消换线、关闭 `isAutoSelect`,并显示原登录失败提示,之后可以手动登录。
- 没有保存的账号密码时(例如自动登录信息不完整)不发送 `/logout`。
## 客户端
- 模块 `mt_channel`(`src/platform/ScriptLib/ChannelScript.inc`),在 `PythonBoot.cpp` 中安装:
- 入口是小地图旁“显示”下方的“换线”按钮。
- 挂接 `game.GameWindow.Open/Close/OnUpdate` 和 `introLogin.LoginWindow.Open/OnUpdate/OnLoginFailure/OnConnectFailure`。
## 证据
- `tests/wiki/test_channel.py`(CTest:`port.channel`)共 6 项通过,覆盖:
- 当前频道定位(`serverInfo` 匹配、`channel.inf` 回退);
- 完整换线:只发一次 `/logout`,登录窗口连接到目标频道和认证服务器,`isAutoSelect`、槽位、`channel.inf`、`SetServerInfo`,进入游戏后复位;
- 退出超时、登录失败、同频道和无账号时拒绝;
- 服务端 `do_cmd` 的 10 秒倒计时小于超时,且重复 `/logout` 会取消。
- 2026-10-15 联机测试(203 正式频道,macOS 原生客户端,账号 admin,角色 `[SA]Admin`):
- CH1(13000)→ CH2(13010)→ CH1,每次约 20 秒(倒计时 3 秒、登录约 2 秒、读图约 6 秒)。
- 换线后角色在同一位置(64600, 79800),连接端口分别为 13010 和 13000,选人界面由原 `isAutoSelect` 自动进入。
- 截图确认窗口布局、当前频道标记和换线中状态正常。
## 限制和未完成
- 换线经过登录界面,比服务端传送慢,期间会看到登录和读图画面。
- 只支持 `serverInfo` 里有的频道;测试核心 channel5(13040)不在列表中,从它出发时当前频道显示“未知”。
- 副本等地图没有做客户端限制:退出后重新登录由服务端按原规则决定角色位置。
- macOS 桌面客户端没有中文字体,窗口文字显示为 `?`。
- Android 真机测试未做。
+56
View File
@@ -0,0 +1,56 @@
# AVA2 显示开关适配进度(v1)
2026-10-15。只改了 metin2-client,服务端不需要改动。参考了 AVA2 的 `ENABLE_GRAPHIC_ON_OFF`(`InstanceBase.cpp` 中 `__CanRender` 的 effect_level 0–4)和 `HIDE_OBJECTS`(`background.SetVisiblePart`)。
## 与 AVA2 的差异
| 项目 | AVA2 | 本实现 |
| --- | --- | --- |
| 特效等级 | 0–4,在渲染判断里跳过 | 相同的 5 档;在 `CInstanceBase::Update` 中对角色挂载的特效调用 Active/Deactive,不改渲染路径 |
| 摆摊、宠物、坐骑的显示范围 | 有 | 不移植:经典版没有离线摆摊和宠物 |
| 树木、云 | `background.SetVisiblePart` | 相同,使用原有接口 |
| 名字、伤害数字 | 原有选项 | 窗口内加了快捷开关,仍然写原来的 systemSetting,退出时由原配置保存 |
## 特效等级
| 等级 | 显示的特效 |
| --- | --- |
| 0 全部特效 | 全部 |
| 1 只看怪物特效 | 自己、怪物、灵石 |
| 2 只看玩家特效 | 自己、其他玩家 |
| 3 只看自己特效 | 只有自己 |
| 4 关闭全部特效 | 无,包括自己 |
## 客户端
- C++:
- `CEffectManager::ActiveEffectInstance`。
- `CActorInstance::SetAttachingEffectShown`:对已挂载的特效调用 Active/Deactive;关闭期间新挂载的特效也会立即 Deactive。使用 Deactive 而不是 Hide,避免和刺客隐身的 Show/Hide 冲突。
- `CPythonSystem::Get/SetEffectLevel`,越界值按 0 处理;不写入 metin2.cfg。
- `systemSetting.SetEffectLevel/GetEffectLevel`。
- `CInstanceBase::__UpdateEffectShown`,每帧在 `Update` 开头按上表判断。
- `CMapOutdoor::RenderPCBlocker`:离镜头近、挡住角色的树会作为遮挡物(PC blocker)单独绘制,不经过 `RenderTree`,所以原来关闭树木后这类树仍然显示。现在隐藏树木时跳过遮挡物中的树。AVA2 有同样的问题。
- 模块 `mt_display`(`src/platform/ScriptLib/DisplayScript.inc`),在 `PythonBoot.cpp` 中安装:
- 入口是小地图旁“拾取”下方的“显示”按钮。
- 窗口“显示设置”包含 5 个特效等级、显示树木、显示云、总是显示名字、显示伤害数字,`【】` 表示当前选中。
- 设置保存在客户端目录的 `mt_display.cfg`,格式为“特效等级 树木 云”,默认 `0 1 1`,损坏时回到默认值。
- 特效等级在启动时生效;树木和云在进入游戏(`GameWindow.Open`)时生效。
## 证据
- `tests/wiki/test_display.py`(CTest:`port.display`)共 3 项通过,覆盖:
- 默认值、配置文件读写、损坏的配置;
- 进入游戏时生效,窗口按钮、配置保存、名字和伤害开关;
- 5 档和 C++ 规则一致。
- `test_pickup.py`(7 项)和 `test_switchbot.py`(6 项)仍然通过。
- 2026-10-15 联机测试(203 测试核心 channel5,macOS 原生客户端,账号 admin):
- 切到等级 4 并关闭树木后,配置为 `4 0 1`;恢复后为 `0 1 1`。
- 截图确认窗口布局正常。
- 用 `/goto 646 798` 走到离树约 7 米的位置截图对比:等级 4 时 GM 标志和武器光效消失;关闭树木后树消失(修复遮挡物问题之前,这棵树仍然显示);恢复后都回来。
## 限制和未完成
- 只控制挂载在角色上的特效(装备光效、buff、种族特效)。单独播放的特效和飞行特效(技能弹道、命中特效)不受影响。
- macOS 桌面客户端没有中文字体,窗口文字显示为 `?`(原版界面同样乱码);Android 使用 CFF FreeType,不受影响。
- 树的影子烘焙在地形阴影图里,关闭树木后地面上仍有树影(与 AVA2 相同)。
- Android 真机测试未做。
+10
View File
@@ -116,3 +116,13 @@
2026-10-15 后续批次:阶段 0 的只读能力协商、阶段 2/3 的掉落/来源/宝箱查询、阶段 4 属性面板已实现并在隔离环境测试;未部署 203,待联机与真机验收。范围和缺口见 AVA2-READONLY-FEATURES.md。 2026-10-15 后续批次:阶段 0 的只读能力协商、阶段 2/3 的掉落/来源/宝箱查询、阶段 4 属性面板已实现并在隔离环境测试;未部署 203,待联机与真机验收。范围和缺口见 AVA2-READONLY-FEATURES.md。
2026-10-15 再续:龙穴/周任务信息与提醒、共享真实掉落开关的活动日历已实现并在隔离环境验证。副本仅首批龙穴;活动仅月光宝箱/圣诞袜,生产未部署,无生产排期。自动洗练/锁定、战令、模型预览、批量开箱仍待实现。见 AVA2-DUNGEON-CALENDAR.md。 2026-10-15 再续:龙穴/周任务信息与提醒、共享真实掉落开关的活动日历已实现并在隔离环境验证。副本仅首批龙穴;活动仅月光宝箱/圣诞袜,生产未部署,无生产排期。自动洗练/锁定、战令、模型预览、批量开箱仍待实现。见 AVA2-DUNGEON-CALENDAR.md。
2026-10-15 自动洗练 v1(阶段 6,不含属性锁定):服务端 mt_switchbot 逐次调用原 UseItem 洗练路径,客户端 mt_switchbot 窗口;隔离环境编译与桩测试通过,macOS 客户端已在 203 测试核心联机验收;未部署 203 正式环境、未做 Android 真机测试。属性锁定仍待存储设计。见 AVA2-SWITCHBOT.md。
2026-10-15 批量拾取(计划外追加,参考 AVA2 do_pickup_all):服务端 mt_pickup 对范围内自己的物品按分类逐件调用原 PickupItem,客户端在拾取键(Z)上接入并提供分类设置窗口;macOS 客户端已在 203 测试核心联机验收,未部署 203 正式环境、未做 Android 真机测试和触屏按钮。见 AVA2-PICKUP.md。
2026-10-15 显示开关(计划外追加,参考 AVA2 ENABLE_GRAPHIC_ON_OFF / HIDE_OBJECTS):仅客户端,5 档特效等级(挂载特效 Active/Deactive)、树木和云开关、名字和伤害数字快捷开关;macOS 客户端已在 203 测试核心联机验收,未做 Android 真机测试。不移植摆摊/宠物/坐骑显示范围。见 AVA2-DISPLAY.md。
2026-10-15 换线(计划外追加,参考 AVA2 ENABLE_CHANNEL_CHANGE):仅客户端,按原流程 /logout → 登录目标频道(serverInfo 频道表 + 保存的账号)→ isAutoSelect 进入同一角色,不做服务端传送;macOS 客户端已在 203 正式频道 CH1↔CH2 联机验收,未做 Android 真机测试。见 AVA2-CHANNEL.md。
2026-10-15 世界 Boss 追踪(AVA2 uitrack 世界 Boss 页,只读,不含传送):服务端各核心用原 HEADER_GG_RELAY(名字 #mt_boss)共享定时 Boss 刷新点,旧核心忽略;客户端 mt_boss 窗口 + 刷新提醒,查询种类 bosses(能力位 256);已在 203 两个 channel5 测试核心上做跨核心联机验收,正式核心尚未部署。见 AVA2-BOSS.md。
2026-10-15 属性锁定(阶段 6 后半,参考 AVA2 ENABLE_LOCK_ATTR):服务端新表 mt_item_attr_lock(按物品 ID 存锁定掩码,各核心启动时自动建表;不改动物品结构、db 缓存和客户端封包),CItem::ChangeAttribute 保留锁定槽位,手动、自动、GM 洗练全部生效;精炼时锁定随属性复制;最多 2 组,加成武器的 0/1 槽算一组;锁定免费。客户端在自动洗练窗口里加 5 个锁定按钮。已在 203 channel5 测试核心联机验收(洗 10 次锁定的 2 条不变,重新登录后仍在),未部署正式环境,未做 Android 真机测试。见 AVA2-SWITCHBOT.md 和服务端 FEATURE-ATTR-LOCK.md。
+46
View File
@@ -0,0 +1,46 @@
# AVA2 批量拾取适配进度(v1)
2026-10-15。修改了 metin2-client 和 metin2-server,AVA2 代码只作参考(`do_pickup_all`、`ENABLE_AUTOMATIC_PICK_UP_SYSTEM`)。服务端规则和协议见 `metin2-server/docs/FEATURE-PICKUP.md`。
## 与 AVA2 的差异
| 项目 | AVA2 | 本实现 |
| --- | --- | --- |
| 触发 | 新包头 `HEADER_CG_ITEMS_PICKUP`,以及付费状态 70002(AFFECT_AUTO_PICK_UP)下的自动拾取 | 聊天命令 `/mt_pickup`,不新增包头;只在按拾取键时触发,不做自动拾取和付费状态 |
| 范围 | 自己的物品 | 相同:只拾取自己的或无主的物品;队伍分配的物品不批量拾取 |
| 拾取过程 | 自己实现 | 每件物品都调用原 `PickupItem`,距离、堆叠、背包空间、GET 日志、任务触发都不变 |
| 分类 | CheckItemCanGet 模式掩码 | 8 个分类位:金币、武器、防具/首饰、技能书、灵石、材料、时装、其他 |
## 客户端
- 模块 `mt_pickup`(`src/platform/ScriptLib/PickupScript.inc`),在 `PythonBoot.cpp` 中安装。替换了 `GameWindow.PickUpItem`(Z 键和 ` 键)。
- 开启时,按拾取键会发送 `/mt_pickup 1 掩码`。等待回复时,以及两次发送间隔不足 0.5 秒时,按键会被吞掉(防止按住 Z 连发)。关闭时走原来的单个拾取。
- 3 秒没有回复:在聊天框提示一次“服务器尚未启用批量拾取”,之后改用单个拾取;再收到回复会自动恢复。
- 设置窗口:入口是小地图旁“洗练”下方的“拾取”按钮。窗口内可开关批量拾取、选择 8 个分类(`【】` 表示已选,至少保留一个),并显示上次结果(附近 N 件、拾取 N 件、失败 N 件)。设置保存在客户端目录的 `mt_pickup.cfg`,格式为“开关 掩码”。
- 单件物品的提示仍由服务端发送;失败提示(例如背包已满)只发一次。
## 证据
- `tests/wiki/test_pickup.py`(CTest:`port.pickup`)共 7 项通过,覆盖:
- 发送节流和等待回复;
- done/error 解析,畸形行和其他前缀;
- 超时后改用单个拾取,迟到的回复会恢复批量拾取;
- 关闭开关、分类掩码、至少保留一个分类;
- 配置文件读写和损坏的配置;
- GameWindow 钩子:入口位置、拾取键、命令拦截、窗口开关;
- 和服务端的分类位、错误码、0.5 秒间隔一致。
- `tests/wiki/test_switchbot.py` 仍然通过。
- 2026-10-15 联机测试(203 测试核心 channel5/first,端口 13040,使用隔离编译的 game;macOS 原生客户端,账号 admin)。先用 `/item` 生成并逐件丢下武器 19、铠甲 11209、材料 30003、灵石 28030、技能书 50300 和 1000 金币:
- 掩码 2(武器):`done 1 1 0`,只拾回武器。
- 掩码 48(灵石+材料):`done 2 2 0`。
- 掩码 255:`done 3 3 0`,拾回铠甲、技能书和金币(金币数恢复)。
- 地上已没有物品:`done 0 0 0`;紧接着再发一次:`error rate`。
- log.log 有 5 行 GET,每件物品一行,和 DROP 一一对应。原路径拾取金币不写 GET 日志。
- 测试核心 syserr 没有新错误。丢金币时出现的 LOCALE_ERROR 来自原有的丢金币提示。
## 未完成
- Android 真机测试和触屏拾取按钮(`touch_controller.h` 的按钮发送 DIK 键码,需要再加布局)。
- 背包已满时的联机测试(服务端桩测试已覆盖)。
- 服务端还没有部署到 203 正式环境。
- 自动狩猎自带的客户端拾取(`PICKUP_TEXTS`)没有改动。
+74
View File
@@ -0,0 +1,74 @@
# AVA2 自动洗练适配进度(v1 + 属性锁定)
2026-10-15。修改了 metin2-client 和 metin2-server,AVA2 代码只作参考。服务端规则和协议见 `metin2-server/docs/FEATURE-SWITCHBOT.md`。
## 与 AVA2 的差异
| 项目 | AVA2 | 本实现 |
| --- | --- | --- |
| 窗口 | 新增 SWITCHBOT 物品窗口,5 个物品槽加 1 个道具槽 | 不新增窗口类型,物品留在背包,按物品 ID 绑定;每个角色同一时间只洗 1 件 |
| 洗练执行 | 自己实现消耗和 ChangeAttribute,绕过手动检查和 ItemLog | 每次都调用原 `UseItem`,检查、概率、日志、扣道具都和手动洗练一样;71151/76023 仍只能洗等级上限 ≤40 的武器和衣服 |
| 速度 | 0.1 秒一次 | 0.25 秒一次(约 4 次/秒) |
| 物品被移动 | 拦截移动、交易、出售等路径 | 每次洗练前重新检查:物品不在背包、已装备、易主时停止(item_gone);交易、商店、仓库、合成界面打开时停止(busy) |
| 换线 / 下线 | 通过 P2P 转移,继续洗 | 直接停止,不离线洗练 |
匹配规则和 AVA2 相同:最多 2 套方案,每套 1–5 条“属性 ≥ 阈值”;任意一套全部达标就停止,只看前 5 条普通属性。
## 客户端
- 模块 `mt_switchbot`(`src/platform/ScriptLib/SwitchbotScript.inc`),在 `PythonBoot.cpp` 中安装。入口是小地图旁“百科”按钮下方的“洗练”按钮。
- 物品:扫描背包里至少有一条属性的武器和防具,用 `<` `>` 切换。洗练道具:扫描子类型为 USE_CHANGE_ATTRIBUTE 的道具,显示数量。次数上限可选 10、50、100、200、500、1000。
- 可选属性和最大值由服务端 `attrs` 下发,客户端不自己推算。添加属性时分页点选;阈值用 -/+ 调整,步长为最大值的 1/5,默认取最大值。
- 运行时锁定所有设置,实时显示次数、剩余道具、停止原因和当前 5 条属性。停止时在聊天框提示;达标时如果窗口已关闭,会自动打开。
- 命令间隔至少 0.3 秒,同一时间只有一个请求在等待回复。4 秒没有回复就显示“服务器尚未启用自动洗练”。`attrs` 只接受完整、连续的回复,不完整的整批丢弃。
- 文字都用 GBK 可编码的字符(不用 ◀/▶/⚠)。
## 属性锁定(2026-10-15)
- 服务端规则、存储和协议见 `metin2-server/docs/FEATURE-ATTR-LOCK.md`。锁定的槽位在所有洗练方式下都保持不变:手动用道具、自动洗练、GM 命令。
- 窗口底部“开始/停止”右边有 5 个按钮,每条有属性的普通槽一个:`锁N` 表示未锁,`【锁N】` 表示已锁。点击切换。选属性时和洗练中不能点。
- 当前属性行里,已锁的属性前面加 `[锁]`。状态行提示“已锁定的属性在每次洗练中保持不变”。
- 服务端在 `attrs_end` 之后下发 `MTSB1 lock CELL VNUM MASK`。旧服务端不发这一行,所以不显示按钮。
- 错误提示:`slot`(该条属性不能锁定),`max`(最多锁定 2 条,且至少留 1 条可洗),`db`(保存失败)。
- 与 AVA2 的差异:
- 锁定免费。AVA2 每次锁定或解锁消耗 50348/50349,203 的 item_proto 里没有这两个道具。
- 锁定状态存在服务端独立表里,不占属性槽。
- 不要求物品正好有 5 条属性,但至少要留 1 条不锁。
- 联机测试(channel5 13040,盔甲 11209,背包 19 格):
- 锁第 2、4 条后,自动洗 10 次,这两条每次都不变,其余 3 条每次都变;
- 锁第 3 组时提示 max;
- 重新登录后锁定状态仍在;
- 解锁后表里的行被删除。
## 证据
- `tests/wiki/test_switchbot.py`(CTest:`port.switchbot`)共 7 项通过(第 7 项是锁定协议和按钮),覆盖:
- 请求节流和合并;
- 不完整的 attrs 回复被拒绝;
- start 命令的拼装和校验;
- state/error 解析和超时;
- 和服务端的原因码、错误码、上限一致;
- 窗口流程:扫描 → 读取属性 → 选属性 → 开始 → 达标提示。
- 脚本能在 Python 2.7 下编译。`tests/wiki/test_service.py` 仍然通过。
- 2026-10-15 联机测试(203 额外开的测试核心 channel5/first,端口 13040,使用隔离编译的 game;macOS 原生客户端,账号 admin,物品为背包 33 格的剑 279,道具 71084):
- 上限 10 次:洗满 10 次后停止(limit),约 4 次/秒。
- 两套方案、阈值 1:第 18 次达标(matched)。
- 已经达标的物品:0 次就停止,不扣道具。
- 洗练中把物品从 33 格移到 90 格:继续洗,窗口跟到 90 格;点停止后显示 stopped。
- 洗练中退出客户端:服务端立即停止。
- log.log 中 CHANGE_ATTRIBUTE 共 72 行,和总次数一致。
- busy:洗练中摆摊(先给 50200 摊位包袱;没有它 `OpenMyShop` 会提前返回、摊位不会开,第一次测试就是这样误判的),摊位开出约 1 秒后停止(busy),共洗 6 次。
- no_scroll:用 76014(共 6 张)、上限 10,洗 6 次后停止(no_scroll),道具剩 0。
- rejected:对 90 级剑用 71151(原路径只允许等级 <= 40):0 次就停止(rejected),道具未扣。
- 截图里窗口布局正常。仓库自带的 `Client` 是英文 cp1252 locale,所以中文显示为 `????`;需要 zh locale 客户端才能看到中文。
- 联机测试发现并修复了两个窗口问题,`test_switchbot.py` 已加回归用例:
- 洗练中移动物品后,选中项会跳到别的物品:现在按服务端报告的格子跟随。
- 空闲时移动物品后选中项丢失:现在退而按相同 vnum 匹配。
- 服务端 `tests/features/test_switchbot.py` 和 `test_queries.py` 通过。203 的隔离目录 `/root/metin2-features-dev` 完整编译通过。
## 未完成
- Android 真机测试。
- macOS 构建需要 `-DMT_40250_SOURCE=<含 EterPack/EterPack.cpp 的源码目录>` 来生成 pack 密钥,否则 system.py 读不出来(RunMain Error)。本机没有 40250 源码,这次用的是 AVA2 的 `TEST/3. Source BIN/Client`,两者密钥相同。
- 服务端还没有部署到 203 正式环境。
- 属性锁定已完成(见上),尚未部署到正式环境。
+247
View File
@@ -0,0 +1,247 @@
// PORT: AVA2 uitrack world-boss tab, read-only. The server's boss regens (own channel plus the shared core) come
// from the MTF1 'bosses' query; the original regen timers stay authoritative. AVA2's teleport button is left out.
// See docs/AVA2-BOSS.md.
static const char c_szBossScript[] = R"PY(# -*- coding: utf-8 -*-
import app
import chat
import game
import grp
import nonplayer
import ui
import weakref
import wndMgr
import mt_feature_service
from mt_biolog import Action, Text, L
try:
import localeInfo
except ImportError:
localeInfo=None
g_window=None
g_entry=None
g_tick=None
PAGE=8
REFRESH=30.
SHARED_CHANNEL=99
# Server map index -> map directory (share/locale/<locale>/map/index), for localeInfo.MINIMAP_ZONE_NAME_DICT.
MAPS={1:'metin2_map_a1',3:'metin2_map_a3',4:'metin2_map_guild_01',5:'metin2_map_monkey_dungeon_11',
6:'metin2_guild_village_01',21:'metin2_map_b1',23:'metin2_map_b3',24:'metin2_map_guild_02',
25:'metin2_map_monkey_dungeon_12',26:'metin2_guild_village_02',41:'metin2_map_c1',43:'metin2_map_c3',
44:'metin2_map_guild_03',45:'metin2_map_monkey_dungeon_13',46:'metin2_guild_village_03',61:'map_n_snowm_01',
62:'metin2_map_n_flame_01',63:'metin2_map_n_desert_01',64:'map_n_threeway',65:'metin2_map_milgyo',
66:'metin2_map_deviltower1',67:'metin2_map_trent',68:'metin2_map_trent02',69:'season1/metin2_map_WL_01',
70:'season1/metin2_map_nusluck01',71:'metin2_map_spiderdungeon_02',72:'metin2_map_skipia_dungeon_01',
73:'metin2_map_skipia_dungeon_02',81:'metin2_map_wedding_01',100:'metin2_map_fielddungeon',
101:'metin2_map_resources_zon',103:'metin2_map_t1',104:'metin2_map_spiderdungeon',105:'metin2_map_t2',
107:'metin2_map_monkey_dungeon',108:'metin2_map_monkey_dungeon2',109:'metin2_map_monkey_dungeon3',
110:'metin2_map_t3',111:'metin2_map_t4',112:'metin2_map_duel',113:'metin2_map_oxevent',
114:'metin2_map_sungzi',118:'metin2_map_sungzi_flame_hill_01',119:'metin2_map_sungzi_flame_hill_02',
120:'metin2_map_sungzi_flame_hill_03',121:'metin2_map_sungzi_snow',122:'metin2_map_sungzi_snow_pass01',
123:'metin2_map_sungzi_snow_pass02',124:'metin2_map_sungzi_snow_pass03',125:'metin2_map_sungzi_desert_01',
126:'metin2_map_sungzi_desert_hill_01',127:'metin2_map_sungzi_desert_hill_02',
128:'metin2_map_sungzi_desert_hill_03',181:'metin2_map_empirewar01',182:'metin2_map_empirewar02',
183:'metin2_map_empirewar03',200:'gm_guild_build',208:'metin2_map_skipia_dungeon_boss',
216:'metin2_map_devilcatacomb',217:'metin2_map_spiderdungeon_03',301:'Metin2_map_CapeDragonHead',
302:'metin2_map_dawnmistwood',303:'metin2_map_BayBlackSand',304:'metin2_map_Mt_Thunder',
351:'metin2_map_n_flame_dungeon_01'}
def Duration(seconds):
seconds=max(0,int(seconds))
return '%02d:%02d:%02d'%(seconds//3600,(seconds//60)%60,seconds%60)
def MapName(index):
names=getattr(localeInfo,'MINIMAP_ZONE_NAME_DICT',{})
name=names.get(MAPS.get(index,''))
return name if name else L('地图%d'%index)
def BossName(vnum):
try:name=nonplayer.GetMonsterName(vnum)
except Exception:name=''
return name if name else L('Boss %d'%vnum)
def Key(row):return (row['vnum'],row['map'],row['channel'],row['x'],row['y'])
def Rows(data):
rows=[]
for v in data['rows']:
vnum,map_index,x,y,channel,alive,most,next_time,period=v
rows.append(dict(vnum=vnum,map=map_index,x=x,y=y,channel=channel,alive=alive,max=most,next=next_time,period=period))
return rows
class Tracker(object):
# Server snapshot plus the per-boss spawn reminders; a reminder only fires on a fresh snapshot.
def __init__(self,now,notify):
self.now=now;self.notify=notify;self.rows=None;self.serverTime=0;self.received=0;self.error=None
self.reminders=set()
def Apply(self,data,error):
if error:self.error=error;self.rows=None;return
self.error=None;self.serverTime=data['time'];self.received=self.now();rows=Rows(data)
alive=set(Key(r) for r in rows if r['alive'])
for key in sorted(self.reminders&alive):self.notify(key);self.reminders.discard(key)
self.reminders&=set(Key(r) for r in rows) # a boss the server no longer lists cannot be announced
self.rows=rows
def Now(self):return self.serverTime+max(0,self.now()-self.received)
def Left(self,row):return max(0,row['next']-self.Now()) if row['next'] else None
def Toggle(self,row):
key=Key(row)
if key in self.reminders:self.reminders.discard(key)
elif not row['alive']:self.reminders.add(key)
def Due(self):
# A reminded boss whose regen timer has passed: ask the server whether it really spawned.
if not self.rows:return False
return any(Key(r) in self.reminders and r['next'] and self.Now()>=r['next']+2 for r in self.rows)
class BossWindow(ui.Window):
def __init__(self,tracker):
ui.Window.__init__(self);self.SetWindowName('BossTrackWindow');self.AddFlag('float');self.AddFlag('movable')
self.tracker=tracker;self.pending=False;self.generation=0;self.nextQuery=0;self.page=0;self.dimensions=None
self.heading=Text(self,18,18,'世界Boss',0xffffd68b)
self.closeButton=Action(self,0,6,60,'关闭',self.Hide)
self.refreshButton=Action(self,18,48,80,'刷新',self.Query)
self.prevButton=Action(self,110,48,72,'上一页',lambda:self.Turn(-1))
self.nextButton=Action(self,194,48,72,'下一页',lambda:self.Turn(1))
self.status=Text(self,280,54,'',0xffc3b7a1)
self.lines=[Text(self,18,0,'',0xffefdfc3) for i in range(PAGE)]
self.details=[Text(self,30,0,'',0xffb2aa9a) for i in range(PAGE)]
self.remindButtons=[Action(self,0,0,92,'',lambda i=i:self.Remind(i)) for i in range(PAGE)]
self.note=Text(self,18,0,'提醒:Boss 刷新后在聊天框提示;以服务器刷新为准。',0xffb2aa9a)
self.Reflow();self.Hide()
def Buttons(self):return [self.closeButton,self.refreshButton,self.prevButton,self.nextButton]+self.remindButtons
def Open(self):
self.Reflow();self.SetCenterPosition();self.Show();self.SetTop();self.Query()
def Query(self):
if self.pending:return
self.pending=True;self.generation+=1;generation=self.generation
self.refreshButton.SetEnabled(False);self.status.SetText(L('正在同步…'))
def received(data,error):
if generation!=self.generation:return
self.pending=False;self.refreshButton.SetEnabled(True);self.nextQuery=app.GetTime()+REFRESH
self.tracker.Apply(data,error);self.Render()
if mt_feature_service.g_service:mt_feature_service.g_service.Request('bosses',0,0,received)
else:received(None,'unsupported')
def Turn(self,step):
self.page=max(0,min(self.Pages()-1,self.page+step));self.Render()
def Pages(self):
rows=self.tracker.rows or []
return max(1,(len(rows)+PAGE-1)//PAGE)
def Remind(self,i):
rows=self.tracker.rows or [];index=self.page*PAGE+i
if index<len(rows):self.tracker.Toggle(rows[index]);self.Render()
def Render(self):
t=self.tracker;rows=t.rows or [];self.page=min(self.page,self.Pages()-1)
if t.error:self.status.SetText(L('服务端未启用 Boss 追踪' if t.error=='unsupported' else '未同步,请稍后刷新'))
elif t.rows is None:self.status.SetText(L('正在同步…'))
elif not rows:self.status.SetText(L('本频道没有定时刷新的 Boss'))
else:self.status.SetText(L('第 %d/%d 页,共 %d 个'%(self.page+1,self.Pages(),len(rows))))
self.prevButton.SetEnabled(self.page>0);self.nextButton.SetEnabled(self.page+1<self.Pages())
for i in range(PAGE):
index=self.page*PAGE+i;line=self.lines[i];detail=self.details[i];button=self.remindButtons[i]
if index>=len(rows):line.Hide();detail.Hide();button.Hide();continue
r=rows[index];left=t.Left(r)
channel='共享' if r['channel']==SHARED_CHANNEL else 'CH%d'%r['channel']
line.SetText(L('[%s] '%channel)+BossName(r['vnum'])+L(' ')+MapName(r['map']))
if r['alive']:state='存活 %d/%d'%(r['alive'],r['max'])
elif left is None:state='不再刷新'
elif left:state='刷新倒计时 '+Duration(left)
else:state='即将刷新'
where='随机位置' if not r['x'] and not r['y'] else '坐标 (%d, %d)'%(r['x']//100,r['y']//100)
detail.SetText(L('%s · %s · 周期 %s'%(state,where,Duration(r['period']))))
button.SetText(L('提醒:'+('开' if Key(r) in t.reminders else '关')))
button.SetEnabled(bool(r['alive']==0 and r['next']) or Key(r) in t.reminders)
line.Show();detail.Show();button.Show()
def Reflow(self):
dims=(wndMgr.GetScreenWidth(),wndMgr.GetScreenHeight())
if dims==self.dimensions:return
self.dimensions=dims;width=min(620,max(460,dims[0]-16));height=min(560,max(360,dims[1]-16));self.SetSize(width,height)
self.closeButton.SetPosition(width-76,6)
spacing=max(36,min(56,(height-140)//PAGE))
for i in range(PAGE):
y=88+i*spacing
self.lines[i].SetPosition(18,y);self.details[i].SetPosition(30,y+18);self.remindButtons[i].SetPosition(width-110,y)
self.note.SetPosition(18,height-22);self.SetCenterPosition()
def OnUpdate(self):
self.Reflow();self.Render()
def OnRender(self):
x,y=self.GetGlobalPosition();grp.SetColor(0xf51b1916);grp.RenderBar(x,y,self.GetWidth(),self.GetHeight());grp.SetColor(0xff9b7b48);grp.RenderBox(x,y,self.GetWidth(),self.GetHeight())
def OnPressEscapeKey(self):self.Hide();return True
def Destroy(self):
self.generation+=1;self.Hide()
for b in self.Buttons():b.event=None
class ReminderTick(ui.Window):
# Keeps the snapshot fresh while the window is open, and checks due reminders while it is closed.
def __init__(self):
ui.Window.__init__(self);self.AddFlag('not_pick');self.SetSize(0,0);self.Show()
def OnUpdate(self):
w=g_window
if not w or w.pending or app.GetTime()<w.nextQuery:return
if w.IsShow() or g_tracker.Due():w.Query()
class Entry(Action):
def __init__(self,window):
Action.__init__(self,None,0,0,64,'Boss',Toggle)
self.minimap=weakref.proxy(window.interface.wndMiniMap);self.SetWindowName('BossEntry');self.OnUpdate()
def OnUpdate(self):
x,y=self.minimap.GetGlobalPosition();self.SetPosition(max(4,x-68),y+356)
def Announce(key):
vnum,map_index,channel,x,y=key
chat.AppendChat(chat.CHAT_TYPE_INFO,BossName(vnum)+L(' 已在 ')+MapName(map_index)+L(' 刷新'))
g_tracker=Tracker(app.GetTime,Announce)
def Toggle():
if g_window:
if g_window.IsShow():g_window.Hide()
else:g_window.Open()
_open=game.GameWindow.Open
_close=game.GameWindow.Close
def Open(self):
global g_window,g_entry,g_tick
_open(self);g_window=BossWindow(g_tracker);g_entry=Entry(self);g_tick=ReminderTick()
def Close(self):
global g_window,g_entry,g_tick
if g_tick:g_tick.Hide();g_tick=None
if g_entry:g_entry.Hide();g_entry.event=None;g_entry=None
if g_window:g_window.Destroy();g_window=None
g_tracker.rows=None;g_tracker.reminders=set() # another channel/character lists other bosses
_close(self)
game.GameWindow.Open=Open
game.GameWindow.Close=Close
)PY";
+240
View File
@@ -0,0 +1,240 @@
// PORT: AVA2-style channel switch (ENABLE_CHANNEL_CHANGE), client-only. Instead of a server-side warp it runs
// the original paths in order: /logout (the server's 3 s / 10 s countdown, which also refuses while fighting),
// the disconnect brings back introLogin.LoginWindow, which then connects to the chosen channel of serverInfo
// with the account kept by networkModule.MainStream, and stream.isAutoSelect makes introSelect start the same
// character. See docs/AVA2-CHANNEL.md.
static const char c_szChannelScript[] = R"PY(# -*- coding: utf-8 -*-
import app
import chat
import game
import grp
import introLogin
import net
import ui
import weakref
from mt_biolog import Action, Text, L
from mt_wiki import B
try:
import serverInfo
except ImportError:
serverInfo=None
g_window=None
g_entry=None
CHANNEL_FILE='channel.inf' # the file introLogin's server board reads
LOGOUT_TIMEOUT=20. # countdown is 3 s, 10 s while fighting; nothing back means the server refused
LOGIN_TIMEOUT=30.
def Locate(addr,port):
# (region, server, channel) of serverInfo whose game address is addr:port; channel 0 when none matches.
regions=getattr(serverInfo,'REGION_DICT',{})
for region in sorted(regions):
for server in sorted(regions[region]):
for channel,data in sorted(regions[region][server].get('channel',{}).items()):
if data.get('ip')==addr and data.get('tcp_port')==port:return region,server,channel
try:
f=open(CHANNEL_FILE,'r');words=f.read().split();f.close()
server=int(words[0]);region=int(words[2]) if len(words)>2 else 0
if server in regions.get(region,{}):return region,server,0
except (IOError,OSError,ValueError,IndexError):pass
for region in sorted(regions):
for server in sorted(regions[region]):return region,server,0
return None
def Channels(place):
if not place:return []
region,server,current=place
data=serverInfo.REGION_DICT[region][server]
return [(channel,info) for channel,info in sorted(data.get('channel',{}).items())]
class Switcher(object):
# stage: None, 'logout' (waiting for the server to close the session), 'login' (connecting to the target).
def __init__(self,send,now,listener=None):
self.send=send;self.now=now;self.listener=listener
self.stage=None;self.deadline=0;self.target=None;self.account=None;self.error=None;self.stream=None
def Busy(self):return self.stage is not None
def Start(self,stream,place,channel):
if self.Busy():return False
region,server,current=place
info=serverInfo.REGION_DICT[region][server]['channel'].get(channel)
if not info or channel==current:self.error='channel';self.Notify('error');return False
if not getattr(stream,'id','') or not getattr(stream,'pwd',''):self.error='account';self.Notify('error');return False
auth=getattr(serverInfo,'REGION_AUTH_SERVER_DICT',{}).get(region,{}).get(server)
account=(auth['ip'],auth['port']) if auth else (stream.account_addr,stream.account_port)
self.target=dict(region=region,server=server,channel=channel,ip=info['ip'],port=info['tcp_port'],
account=account,label='%s, %s'%(serverInfo.REGION_DICT[region][server].get('name',''),info.get('name','')))
self.account=(stream.id,stream.pwd,stream.GetCharacterSlot());self.stream=stream
self.error=None;self.stage='logout';self.deadline=self.now()+LOGOUT_TIMEOUT
self.send('/logout');self.Notify('start')
return True
def Tick(self):
if self.stage and self.now()>=self.deadline:
self.error='timeout' if self.stage=='logout' else 'login';self.Clear();self.Notify('error')
def Clear(self):
if self.stream:self.stream.isAutoSelect=0 # never leave the original auto-select on for a manual login
self.stage=None;self.target=None;self.account=None;self.stream=None
def Notify(self,kind):
if self.listener:self.listener(kind)
def OnLoginWindow(self,window):
# LoginWindow.Open has just reset the connect info from loginInfo.xml; point it at the target channel.
if self.stage!='logout':return False
t=self.target;user,pwd,slot=self.account;stream=window.stream
stream.SetConnectInfo(t['ip'],t['port'],t['account'][0],t['account'][1])
stream.SetCharacterSlot(slot);stream.isAutoSelect=1
net.SetServerInfo(t['label'].strip())
try:
f=open(CHANNEL_FILE,'w');f.write('%d %d %d'%(t['server'],t['channel'],t['region']));f.close()
except (IOError,OSError):pass
self.stage='login';self.deadline=self.now()+LOGIN_TIMEOUT
window.Connect(user,pwd)
return True
def OnLoginFailure(self,error):
if self.stage=='login':self.error='login';self.Clear();self.Notify('error')
def OnGame(self,stream):
if self.stage=='login':
channel=self.target['channel'];self.Clear();self.Notify('done')
return channel
return 0
ERRORS={'channel':'无法换到该频道','account':'没有保存的登录信息,请重新登录后再换线',
'timeout':'服务器没有退出(战斗中或不允许退出),换线已取消','login':'登录目标频道失败'}
class ChannelWindow(ui.Window):
def __init__(self,switcher,stream):
ui.Window.__init__(self);self.SetWindowName('ChannelWindow');self.AddFlag('float');self.AddFlag('movable')
self.switcher=switcher;self.stream=stream;self.place=None;self.channelButtons=[]
self.SetSize(332,260)
self.heading=Text(self,18,18,'换线',0xffffd68b)
self.closeButton=Action(self,256,6,60,'关闭',self.Hide)
self.current=Text(self,18,52,'',0xffc3b7a1)
self.status=Text(self,18,232,'',0xffc3b7a1)
self.Hide()
def Buttons(self):return [self.closeButton]+self.channelButtons
def Build(self):
for b in self.channelButtons:b.Hide();b.event=None
self.place=Locate(self.stream.addr,self.stream.port)
channels=Channels(self.place)
self.channelButtons=[Action(self,18+(i%2)*152,82+(i//2)*52,144,'',lambda channel=channel:self.Switch(channel))
for i,(channel,info) in enumerate(channels)]
self.SetSize(332,max(160,82+(len(channels)+1)//2*52+40));self.status.SetPosition(18,self.GetHeight()-28)
def Open(self):self.Build();self.Refresh();self.SetCenterPosition();self.Show();self.SetTop()
def Switch(self,channel):
if self.place:self.switcher.Start(self.stream,self.place,channel)
self.Refresh()
def Refresh(self):
current=self.place[2] if self.place else 0
channels=Channels(self.place);busy=self.switcher.Busy()
name=dict(channels).get(current,{}).get('name')
self.current.SetText(L('当前频道:'+(name if name else '未知')))
for button,(channel,info) in zip(self.channelButtons,channels):
button.SetText(L(B(u'【%s】'%info.get('name','') if channel==current else info.get('name',''))))
button.SetEnabled(not busy and channel!=current)
self.status.SetText(L(self.StatusText()))
def StatusText(self):
s=self.switcher
if s.stage=='logout':return '正在退出,稍后自动登录 %s'%s.target['label'].split(', ')[-1]
if s.stage=='login':return '正在登录 %s'%s.target['label'].split(', ')[-1]
if s.error:return '!'+ERRORS[s.error]
if not self.place:return '!没有可用的频道列表'
return '退出后自动登录所选频道,并进入同一角色'
def OnRender(self):
x,y=self.GetGlobalPosition();grp.SetColor(0xf51b1916);grp.RenderBar(x,y,self.GetWidth(),self.GetHeight());grp.SetColor(0xff9b7b48);grp.RenderBox(x,y,self.GetWidth(),self.GetHeight())
def OnPressEscapeKey(self):self.Hide();return True
def Destroy(self):
self.Hide()
for b in self.Buttons():b.event=None
class Entry(Action):
def __init__(self,window):
Action.__init__(self,None,0,0,64,'换线',Toggle)
self.minimap=weakref.proxy(window.interface.wndMiniMap);self.SetWindowName('ChannelEntry');self.OnUpdate()
def OnUpdate(self):
x,y=self.minimap.GetGlobalPosition();self.SetPosition(max(4,x-68),y+304)
def OnSwitch(kind):
if kind=='error':chat.AppendChat(chat.CHAT_TYPE_INFO,L(ERRORS[g_switcher.error]))
if g_window:g_window.Refresh()
g_switcher=Switcher(net.SendChatPacket,app.GetTime,OnSwitch)
def Toggle():
if g_window:
if g_window.IsShow():g_window.Hide()
else:g_window.Open()
_open=game.GameWindow.Open
_close=game.GameWindow.Close
_update=game.GameWindow.OnUpdate
_login_open=introLogin.LoginWindow.Open
_login_update=introLogin.LoginWindow.OnUpdate
_login_failure=introLogin.LoginWindow.OnLoginFailure
_connect_failure=introLogin.LoginWindow.OnConnectFailure
def Open(self):
global g_window,g_entry
_open(self)
channel=g_switcher.OnGame(self.stream)
g_window=ChannelWindow(g_switcher,self.stream);g_entry=Entry(self)
if channel:
name=dict(Channels(Locate(self.stream.addr,self.stream.port))).get(channel,{}).get('name','')
chat.AppendChat(chat.CHAT_TYPE_INFO,L('已换到 %s'%name))
def Close(self):
global g_window,g_entry
if g_entry:g_entry.Hide();g_entry.event=None;g_entry=None
if g_window:g_window.Destroy();g_window=None
_close(self)
def OnUpdate(self):
_update(self)
if g_switcher.stage=='logout':g_switcher.Tick()
def LoginOpen(self):
_login_open(self);g_switcher.OnLoginWindow(self)
def LoginUpdate(self):
_login_update(self);g_switcher.Tick()
def LoginFailure(self,error):
g_switcher.OnLoginFailure(error);_login_failure(self,error)
def ConnectFailure(self):
g_switcher.OnLoginFailure('connect');_connect_failure(self)
game.GameWindow.Open=Open
game.GameWindow.Close=Close
game.GameWindow.OnUpdate=OnUpdate
introLogin.LoginWindow.Open=LoginOpen
introLogin.LoginWindow.OnUpdate=LoginUpdate
introLogin.LoginWindow.OnLoginFailure=LoginFailure
introLogin.LoginWindow.OnConnectFailure=ConnectFailure
)PY";
+141
View File
@@ -0,0 +1,141 @@
// PORT: AVA2-style display options (ENABLE_GRAPHIC_ON_OFF effect level, HIDE_OBJECTS tree/cloud parts),
// client-only. The effect level is systemSetting.SetEffectLevel (CInstanceBase::__UpdateEffectShown deactivates
// attached effects); trees and clouds use the original background.SetVisiblePart; names and damage numbers
// are shortcuts to the original game options. See docs/AVA2-DISPLAY.md.
static const char c_szDisplayScript[] = R"PY(# -*- coding: utf-8 -*-
import background
import game
import grp
import systemSetting
import ui
import weakref
from mt_biolog import Action, Text, L
from mt_wiki import B
g_window=None
g_entry=None
CONFIG='mt_display.cfg'
LEVELS=(u'全部特效',u'只看怪物特效',u'只看玩家特效',u'只看自己特效',u'关闭全部特效')
LEVEL_HINTS=('显示所有角色的特效','隐藏其他玩家和NPC的特效,保留自己和怪物的','隐藏怪物和NPC的特效,保留玩家的',
'只保留自己的特效','连自己的特效也隐藏')
class Options(object):
def __init__(self):self.effect=0;self.tree=True;self.cloud=True
def Load(self,text):
words=text.split()
if len(words)!=3 or not all(w.isdigit() and len(w)==1 for w in words):return
effect,tree,cloud=[int(w) for w in words]
if effect<len(LEVELS) and tree in (0,1) and cloud in (0,1):self.effect=effect;self.tree=tree==1;self.cloud=cloud==1
def Dump(self):return '%d %d %d'%(self.effect,int(self.tree),int(self.cloud))
def Apply(self):
systemSetting.SetEffectLevel(self.effect)
background.SetVisiblePart(background.PART_TREE,int(self.tree))
background.SetVisiblePart(background.PART_CLOUD,int(self.cloud))
def LoadConfig(options):
try:
f=open(CONFIG,'r');text=f.read();f.close();options.Load(text)
except (IOError,OSError):pass
def SaveConfig(options):
try:
f=open(CONFIG,'w');f.write(options.Dump());f.close()
except (IOError,OSError):pass
def Mark(text,on):return L(B(u'【%s】'%text if on else text))
class DisplayWindow(ui.Window):
def __init__(self,options):
ui.Window.__init__(self);self.SetWindowName('DisplayWindow');self.AddFlag('float');self.AddFlag('movable')
self.options=options;self.SetSize(332,404)
self.heading=Text(self,18,18,'显示设置',0xffffd68b)
self.closeButton=Action(self,256,6,60,'关闭',self.Hide)
self.effectText=Text(self,18,54,'特效',0xffc3b7a1)
self.levelButtons=[Action(self,18+(i%2)*152,76+(i//2)*52,144,'',lambda level=i:self.SetLevel(level)) for i in range(len(LEVELS))]
self.sceneText=Text(self,18,238,'场景和文字',0xffc3b7a1)
self.treeButton=Action(self,18,260,144,'',self.ToggleTree)
self.cloudButton=Action(self,170,260,144,'',self.ToggleCloud)
self.nameButton=Action(self,18,312,144,'',self.ToggleName)
self.damageButton=Action(self,170,312,144,'',self.ToggleDamage)
self.status=Text(self,18,376,'',0xffc3b7a1)
self.Refresh();self.Hide()
def Buttons(self):return [self.closeButton,self.treeButton,self.cloudButton,self.nameButton,self.damageButton]+self.levelButtons
def Open(self):self.Refresh();self.SetCenterPosition();self.Show();self.SetTop()
def Changed(self):self.options.Apply();SaveConfig(self.options);self.Refresh()
def SetLevel(self,level):self.options.effect=level;self.Changed()
def ToggleTree(self):self.options.tree=not self.options.tree;self.Changed()
def ToggleCloud(self):self.options.cloud=not self.options.cloud;self.Changed()
# Names and damage numbers are the original game options (saved by the client config on exit).
def ToggleName(self):systemSetting.SetAlwaysShowNameFlag(not systemSetting.IsAlwaysShowName());self.Refresh()
def ToggleDamage(self):systemSetting.SetShowDamageFlag(not systemSetting.IsShowDamage());self.Refresh()
def Refresh(self):
o=self.options
for i,button in enumerate(self.levelButtons):button.SetText(Mark(LEVELS[i],i==o.effect))
self.treeButton.SetText(Mark(u'显示树木',o.tree));self.cloudButton.SetText(Mark(u'显示云',o.cloud))
self.nameButton.SetText(Mark(u'总是显示名字',systemSetting.IsAlwaysShowName()))
self.damageButton.SetText(Mark(u'显示伤害数字',systemSetting.IsShowDamage()))
self.status.SetText(L(LEVEL_HINTS[o.effect]))
def OnRender(self):
x,y=self.GetGlobalPosition();grp.SetColor(0xf51b1916);grp.RenderBar(x,y,self.GetWidth(),self.GetHeight());grp.SetColor(0xff9b7b48);grp.RenderBox(x,y,self.GetWidth(),self.GetHeight())
def OnPressEscapeKey(self):self.Hide();return True
def Destroy(self):
self.Hide()
for b in self.Buttons():b.event=None
class Entry(Action):
def __init__(self,window):
Action.__init__(self,None,0,0,64,'显示',Toggle)
self.minimap=weakref.proxy(window.interface.wndMiniMap);self.SetWindowName('DisplayEntry');self.OnUpdate()
def OnUpdate(self):
x,y=self.minimap.GetGlobalPosition();self.SetPosition(max(4,x-68),y+252)
g_options=Options()
LoadConfig(g_options)
systemSetting.SetEffectLevel(g_options.effect)
def Toggle():
if g_window:
if g_window.IsShow():g_window.Hide()
else:g_window.Open()
_open=game.GameWindow.Open
_close=game.GameWindow.Close
def Open(self):
global g_window,g_entry
_open(self);g_options.Apply();g_window=DisplayWindow(g_options);g_entry=Entry(self)
def Close(self):
global g_window,g_entry
if g_entry:g_entry.Hide();g_entry.event=None;g_entry=None
if g_window:g_window.Destroy();g_window=None
_close(self)
game.GameWindow.Open=Open
game.GameWindow.Close=Close
)PY";
@@ -6,7 +6,8 @@ import net
import ui import ui
from mt_wiki_data import Number from mt_wiki_data import Number
BITS={'mob':1,'chest':2,'stats':4,'sources':8,'dungeons':16,'calendar':32} BITS={'mob':1,'chest':2,'stats':4,'sources':8,'dungeons':16,'calendar':32,'bosses':256}
WHOLE=('stats','dungeons','bosses') # one reply with every row; no subject or page
g_service=None g_service=None
g_tick=None g_tick=None
_serial=0 _serial=0
@@ -27,7 +28,7 @@ class Service(object):
global _serial global _serial
if kind not in BITS or not 0<=subject<=4294967295 or not 0<=offset<=4096 or len(self.queue)>=8: if kind not in BITS or not 0<=subject<=4294967295 or not 0<=offset<=4096 or len(self.queue)>=8:
callback(None,'invalid');return 0 callback(None,'invalid');return 0
if (kind in ('stats','dungeons') and (subject or offset)) or (kind=='calendar' and subject!=1): if (kind in WHOLE and (subject or offset)) or (kind=='calendar' and subject!=1):
callback(None,'invalid');return 0 callback(None,'invalid');return 0
_serial=(_serial%2147483647)+1 _serial=(_serial%2147483647)+1
self.queue.append(dict(id=_serial,kind=kind,subject=subject,offset=offset,callback=callback,retries=0)) self.queue.append(dict(id=_serial,kind=kind,subject=subject,offset=offset,callback=callback,retries=0))
@@ -53,7 +54,7 @@ class Service(object):
if not self.mask&BITS[p['kind']]: if not self.mask&BITS[p['kind']]:
self.Finish(None,'unsupported');return self.Finish(None,'unsupported');return
text='/mt_features 1 %d %s'%(p['id'],p['kind']) text='/mt_features 1 %d %s'%(p['id'],p['kind'])
if p['kind'] not in ('stats','dungeons'):text+=' %d %d'%(p['subject'],p['offset']) if p['kind'] not in WHOLE:text+=' %d %d'%(p['subject'],p['offset'])
net.SendChatPacket(text) net.SendChatPacket(text)
self.deadline=now+4.0;self.nextSend=now+0.3 self.deadline=now+4.0;self.nextSend=now+0.3
@@ -80,15 +81,15 @@ class Service(object):
elif op=='begin' and len(w)==9 and p['kind']!='cap': elif op=='begin' and len(w)==9 and p['kind']!='cap':
if 'result' in p or w[3]!=p['kind'] or Number(w[4])!=p['subject'] or Number(w[5])!=p['offset']: if 'result' in p or w[3]!=p['kind'] or Number(w[4])!=p['subject'] or Number(w[5])!=p['offset']:
raise ValueError('mismatched response') raise ValueError('mismatched response')
total=Number(w[6],128 if p['kind'] in ('stats','dungeons') else 256 if p['kind']=='calendar' else 4096) total=Number(w[6],128 if p['kind'] in WHOLE else 256 if p['kind']=='calendar' else 4096)
if total<p['offset']:raise ValueError('invalid page') if total<p['offset']:raise ValueError('invalid page')
p['result']=dict(kind=w[3],subject=p['subject'],offset=p['offset'],total=total,mode=Number(w[7],11), p['result']=dict(kind=w[3],subject=p['subject'],offset=p['offset'],total=total,mode=Number(w[7],11),
time=Number(w[8]),rows=[]) time=Number(w[8]),rows=[])
elif op in ('row','stat','event') and 'result' in p: elif op in ('row','stat','event','boss') and 'result' in p:
result=p['result'];rows=result['rows'] result=p['result'];rows=result['rows']
limit=result['total'] if p['kind'] in ('stats','dungeons') else min(8,result['total']-p['offset']) limit=result['total'] if p['kind'] in WHOLE else min(8,result['total']-p['offset'])
if len(rows)>=limit or Number(w[3])!=p['offset']+len(rows):raise ValueError('invalid row order') if len(rows)>=limit or Number(w[3])!=p['offset']+len(rows):raise ValueError('invalid row order')
if op=='row' and len(w)==12 and p['kind'] not in ('stats','dungeons','calendar'): if op=='row' and len(w)==12 and p['kind'] not in WHOLE+('calendar',):
values=[Number(v) for v in w[4:]] values=[Number(v) for v in w[4:]]
if values[2] not in (0,1,2,3,4,5,10,11,20,21) or not values[0]:raise ValueError('invalid row') if values[2] not in (0,1,2,3,4,5,10,11,20,21) or not values[0]:raise ValueError('invalid row')
rows.append(values) rows.append(values)
@@ -97,12 +98,17 @@ class Service(object):
if not values[0] or values[1] not in (1,2) or values[2]>=values[3] or values[4]>255 or values[5]>3 or values[6]>1:raise ValueError('invalid calendar event') if not values[0] or values[1] not in (1,2) or values[2]>=values[3] or values[4]>255 or values[5]>3 or values[6]>1:raise ValueError('invalid calendar event')
if any(r[0]==values[0] for r in rows):raise ValueError('duplicate event') if any(r[0]==values[0] for r in rows):raise ValueError('duplicate event')
rows.append(values) rows.append(values)
elif op=='boss' and len(w)==13 and p['kind']=='bosses':
# VNUM MAP X Y CHANNEL ALIVE MAX NEXT PERIOD; X/Y are map-local and may be negative.
values=[Number(w[4]),Number(w[5]),Signed(w[6]),Signed(w[7])]+[Number(v) for v in w[8:]]
if not values[0] or not values[1] or values[4]>255 or values[6]>255 or values[5]>values[6] or not values[8]:raise ValueError('invalid boss')
rows.append(values)
elif op=='stat' and len(w)==6 and p['kind'] in ('stats','dungeons'): elif op=='stat' and len(w)==6 and p['kind'] in ('stats','dungeons'):
if not w[4].replace('_','').isalpha() or len(w[4])>32 or any(r[0]==w[4] for r in rows):raise ValueError('invalid stat') if not w[4].replace('_','').isalpha() or len(w[4])>32 or any(r[0]==w[4] for r in rows):raise ValueError('invalid stat')
rows.append((w[4],Signed(w[5]))) rows.append((w[4],Signed(w[5])))
else:raise ValueError('invalid row format') else:raise ValueError('invalid row format')
elif op=='end' and len(w)==4 and 'result' in p: elif op=='end' and len(w)==4 and 'result' in p:
result=p['result'];expected=result['total'] if p['kind'] in ('stats','dungeons') else min(8,result['total']-p['offset']) result=p['result'];expected=result['total'] if p['kind'] in WHOLE else min(8,result['total']-p['offset'])
if Number(w[3])!=expected or len(result['rows'])!=expected:raise ValueError('incomplete reply') if Number(w[3])!=expected or len(result['rows'])!=expected:raise ValueError('incomplete reply')
if p['kind']=='dungeons': if p['kind']=='dungeons':
values=dict(result['rows']) values=dict(result['rows'])
+194
View File
@@ -0,0 +1,194 @@
// PORT: AVA2-style batch pickup (do_pickup_all), driven by the server's /mt_pickup command. With batch
// pickup on, the pickup key (GameWindow.PickUpItem, Z / `) asks the server to pick up every own item in
// range of the chosen categories; each item still goes through the original pickup path. Against a server
// without the command it falls back to the original single pickup. Protocol: metin2-server docs/FEATURE-PICKUP.md.
static const char c_szPickupScript[] = R"PY(# -*- coding: utf-8 -*-
import app
import chat
import game
import grp
import net
import ui
import weakref
from mt_biolog import Action, Text, L
from mt_wiki import B
g_window=None
g_entry=None
CONFIG='mt_pickup.cfg'
ALL=255
CATEGORIES=((1,u'金币'),(2,u'武器'),(4,u'防具/首饰'),(8,u'技能书'),(16,u'灵石'),(32,u'材料'),(64,u'时装'),(128,u'其他'))
SEND_GAP=.5
TIMEOUT=3.
ERRORS={'rate':'操作过快','invalid':'参数无效','busy':'当前状态不能拾取'}
def Number(text,low=0,high=4294967295):
if not text.isdigit() or len(text)>10:raise ValueError(text)
value=int(text)
if not low<=value<=high:raise ValueError(text)
return value
class Picker(object):
# Protocol state only. send(text) posts a chat command, now() is seconds.
def __init__(self,send,now,listener=None):
self.send=send;self.now=now;self.listener=listener
self.enabled=True;self.mask=ALL;self.waiting=None;self.nextSend=0
self.unsupported=False;self.result=None;self.error=None
def Press(self):
# True when the press was handled here; False means use the original single pickup.
self.Tick()
if not self.enabled or self.unsupported:return False
now=self.now()
if self.waiting is None and now>=self.nextSend:
self.send('/mt_pickup 1 %d'%self.mask);self.waiting=now+TIMEOUT;self.nextSend=now+SEND_GAP
return True
def Tick(self):
if self.waiting is not None and self.now()>=self.waiting:
self.waiting=None;self.unsupported=True;self.Notify('unsupported')
def Notify(self,kind):
if self.listener:self.listener(kind)
def Receive(self,line):
if not line.startswith('MTPU1 '):return False
words=line.split()
try:
if words[1]=='done' and len(words)==5:
found,picked,failed=[Number(w,0,1000) for w in words[2:]]
self.result=dict(found=found,picked=picked,failed=failed);self.error=None;kind='done'
elif words[1]=='error' and len(words)==3 and words[2] in ERRORS:self.error=words[2];kind='error'
else:return True
except ValueError:return True
self.waiting=None;self.unsupported=False;self.Notify(kind)
return True
def Load(self,text):
try:
enabled,mask=[Number(w) for w in text.split()]
if enabled in (0,1) and 1<=mask<=ALL:self.enabled=enabled==1;self.mask=mask
except ValueError:pass
def Dump(self):return '%d %d'%(int(self.enabled),self.mask)
def Toggle(self,bit):
mask=self.mask^bit
if mask:self.mask=mask # at least one category stays on
def LoadConfig(picker):
try:
f=open(CONFIG,'r');text=f.read();f.close();picker.Load(text)
except (IOError,OSError):pass
def SaveConfig(picker):
try:
f=open(CONFIG,'w');f.write(picker.Dump());f.close()
except (IOError,OSError):pass
class PickupWindow(ui.Window):
def __init__(self,picker):
ui.Window.__init__(self);self.SetWindowName('PickupWindow');self.AddFlag('float');self.AddFlag('movable')
self.picker=picker;self.SetSize(332,346)
self.heading=Text(self,18,18,'批量拾取',0xffffd68b)
self.closeButton=Action(self,256,6,60,'关闭',self.Hide)
self.enableButton=Action(self,18,52,296,'',self.ToggleEnabled)
self.categoryButtons=[Action(self,18+(i%2)*152,108+(i//2)*52,144,'',lambda bit=bit:self.ToggleCategory(bit))
for i,(bit,name) in enumerate(CATEGORIES)]
self.status=Text(self,18,322,'',0xffc3b7a1)
self.Refresh();self.Hide()
def Buttons(self):return [self.closeButton,self.enableButton]+self.categoryButtons
def Open(self):self.Refresh();self.SetCenterPosition();self.Show();self.SetTop()
def ToggleEnabled(self):
self.picker.enabled=not self.picker.enabled;self.picker.unsupported=False;SaveConfig(self.picker);self.Refresh()
def ToggleCategory(self,bit):self.picker.Toggle(bit);SaveConfig(self.picker);self.Refresh()
def Refresh(self):
p=self.picker
self.enableButton.SetText(L('拾取键(Z):批量拾取 已开启' if p.enabled else '拾取键(Z):批量拾取 已关闭(单个拾取)'))
for button,(bit,name) in zip(self.categoryButtons,CATEGORIES):
button.SetText(L(B(u'【%s】'%name if p.mask&bit else name)))
button.SetEnabled(p.enabled)
self.status.SetText(L(self.StatusText()))
def StatusText(self):
p=self.picker
if p.unsupported:return '!服务器尚未启用批量拾取,已改用单个拾取'
if p.error:return '!'+ERRORS[p.error]
if p.result:
r=p.result;text='上次:附近 %d 件,拾取 %d 件'%(r['found'],r['picked'])
return text+(',%d 件未能拾取'%r['failed'] if r['failed'] else '')
return '只拾取自己的物品,范围与单个拾取相同'
def OnRender(self):
x,y=self.GetGlobalPosition();grp.SetColor(0xf51b1916);grp.RenderBar(x,y,self.GetWidth(),self.GetHeight());grp.SetColor(0xff9b7b48);grp.RenderBox(x,y,self.GetWidth(),self.GetHeight())
def OnUpdate(self):self.picker.Tick()
def OnPressEscapeKey(self):self.Hide();return True
def Destroy(self):
self.Hide()
for b in self.Buttons():b.event=None
class Entry(Action):
def __init__(self,window):
Action.__init__(self,None,0,0,64,'拾取',Toggle)
self.minimap=weakref.proxy(window.interface.wndMiniMap);self.SetWindowName('PickupEntry');self.OnUpdate()
def OnUpdate(self):
x,y=self.minimap.GetGlobalPosition();self.SetPosition(max(4,x-68),y+200)
def OnPicker(kind):
if kind=='unsupported':chat.AppendChat(chat.CHAT_TYPE_INFO,L('服务器尚未启用批量拾取,已改用单个拾取'))
if g_window:g_window.Refresh()
g_picker=Picker(net.SendChatPacket,app.GetTime,OnPicker)
LoadConfig(g_picker)
def Toggle():
if g_window:
if g_window.IsShow():g_window.Hide()
else:g_window.Open()
_open=game.GameWindow.Open
_close=game.GameWindow.Close
_command=game.GameWindow.BINARY_ServerCommand_Run
_pick=game.GameWindow.PickUpItem
def Open(self):
global g_window,g_entry
_open(self);g_picker.waiting=None;g_window=PickupWindow(g_picker);g_entry=Entry(self)
def Close(self):
global g_window,g_entry
if g_entry:g_entry.Hide();g_entry.event=None;g_entry=None
if g_window:g_window.Destroy();g_window=None
_close(self)
def Command(self,line):
if g_picker.Receive(line):return 1
return _command(self,line)
def PickUpItem(self):
if not g_picker.Press():_pick(self)
game.GameWindow.Open=Open
game.GameWindow.Close=Close
game.GameWindow.BINARY_ServerCommand_Run=Command
game.GameWindow.PickUpItem=PickUpItem
)PY";
+10
View File
@@ -999,6 +999,11 @@ namespace PythonBoot
#include "DungeonScript.inc" #include "DungeonScript.inc"
#include "CalendarScript.inc" #include "CalendarScript.inc"
#include "WikiEntryScript.inc" #include "WikiEntryScript.inc"
#include "SwitchbotScript.inc"
#include "PickupScript.inc"
#include "DisplayScript.inc"
#include "ChannelScript.inc"
#include "BossScript.inc"
static void install_script_module(const char* c_szModule, const char* c_szScript) static void install_script_module(const char* c_szModule, const char* c_szScript)
{ {
@@ -1072,6 +1077,11 @@ bool RunMainScript(const char* lpCmdLine, std::string* error)
install_script_module("mt_dungeons", c_szDungeonScript); install_script_module("mt_dungeons", c_szDungeonScript);
install_script_module("mt_calendar", c_szCalendarScript); install_script_module("mt_calendar", c_szCalendarScript);
install_script_module("mt_wiki_entries", c_szWikiEntryScript); install_script_module("mt_wiki_entries", c_szWikiEntryScript);
install_script_module("mt_switchbot", c_szSwitchbotScript);
install_script_module("mt_pickup", c_szPickupScript);
install_script_module("mt_display", c_szDisplayScript);
install_script_module("mt_channel", c_szChannelScript);
install_script_module("mt_boss", c_szBossScript);
if (g_touch_input) if (g_touch_input)
install_script_module("mt_mobile_hud", c_szMobileHUDScript); install_script_module("mt_mobile_hud", c_szMobileHUDScript);
} }
+404
View File
@@ -0,0 +1,404 @@
// PORT: AVA2-style automatic attribute change (uiswitchbot.py), driven by the server's /mt_switchbot
// command. Every roll runs on the server through the original change-attribute scroll path; this window
// only picks the item, scroll and targets and shows progress. The lock buttons toggle the server-side attribute
// lock that every reroll keeps. Protocol: metin2-server docs/FEATURE-SWITCHBOT.md, FEATURE-ATTR-LOCK.md.
static const char c_szSwitchbotScript[] = R"PY(# -*- coding: utf-8 -*-
import app
import chat
import game
import grp
import item
import net
import player
import ui
import uiToolTip
import wndMgr
import weakref
from mt_biolog import Action, Text, L
from mt_wiki import B, U
g_window=None
g_entry=None
USE_CHANGE_ATTRIBUTE=18 # CItemData::EUseSubTypes; the server re-checks the scroll subtype.
LIMITS=(10,50,100,200,500,1000)
MAX_TARGETS=5
LOCK_GROUPS=2
SEND_GAP=.3
TIMEOUT=4.
REASONS={'running':'洗练中','matched':'已获得目标属性','limit':'已达到次数上限','no_scroll':'洗练道具已用完',
'item_gone':'物品已移动、装备或交易,已停止','rejected':'服务器拒绝了本次洗练','busy':'交易/商店/仓库/合成界面打开,已停止',
'stopped':'已手动停止','idle':'未运行'}
ERRORS={'rate':'操作过快,请稍后','invalid':'参数无效','item':'物品不存在','equipped':'请先卸下装备或结束交易','no_attr':'该物品不能洗练',
'scroll':'没有可用的洗练道具','target':'目标属性超出可洗范围','running':'已有洗练在进行','busy':'当前状态不能洗练',
'unsupported':'服务器尚未启用自动洗练','slot':'该条属性不能锁定','max':'最多锁定 2 条,且至少留 1 条可洗',
'db':'锁定保存失败,请稍后再试'}
def Number(text,low=0,high=4294967295):
if not text.isdigit() or len(text)>10:raise ValueError(text)
value=int(text)
if not low<=value<=high:raise ValueError(text)
return value
class Bot(object):
# Protocol state only; the window renders it. send(text) posts a chat command, now() is seconds.
def __init__(self,send,now,listener=None):
self.send=send;self.now=now;self.listener=listener
self.queue=[];self.nextSend=0;self.waiting=None
self.allowed={};self.locks={};self.loading=None;self.state=None;self.error=None;self.unsupported=False
def Enqueue(self,verb,text):
if verb=='attrs' and self.waiting and self.waiting[2]==text:return
self.queue=[q for q in self.queue if not (verb=='attrs' and q[0]=='attrs')]
if len(self.queue)<4:self.queue.append((verb,text))
self.Tick()
def RequestAttrs(self,cell):
self.Enqueue('attrs','/mt_switchbot 1 attrs %d'%cell)
def Start(self,cell,scroll,limit,alternatives):
groups=[a for a in alternatives if a]
if not groups or len(groups)>2 or not 1<=limit<=1000:return 'invalid'
allowed=dict(self.allowed.get(cell,{}).get('rows',()))
parts=['/mt_switchbot 1 start %d %d %d'%(cell,scroll,limit)]
for targets in groups:
if len(targets)>MAX_TARGETS or len(set(a for a,v in targets))!=len(targets):return 'invalid'
parts.append(str(len(targets)))
for apply,value in targets:
if apply not in allowed or not 1<=value<=allowed[apply]:return 'target'
parts.append('%d %d'%(apply,value))
self.error=None;self.Enqueue('start',' '.join(parts));return None
def Lock(self,cell,slot):
if not 0<=slot<5 or cell not in self.locks:return
self.error=None;self.Enqueue('lock','/mt_switchbot 1 lock %d %d'%(cell,slot))
def LockMask(self,cell,vnum):
lock=self.locks.get(cell)
return lock[1] if lock and lock[0]==vnum else None
def Stop(self):self.Enqueue('stop','/mt_switchbot 1 stop')
def Status(self):self.Enqueue('status','/mt_switchbot 1 status')
def Running(self):return bool(self.state and self.state['active'])
def Tick(self):
now=self.now()
if self.waiting and now>=self.waiting[1]:
self.waiting=None;self.queue=[];self.loading=None;self.unsupported=True;self.error='unsupported';self.Notify('error')
if self.queue and not self.waiting and now>=self.nextSend:
verb,text=self.queue.pop(0);self.send(text);self.nextSend=now+SEND_GAP
self.waiting=(verb,now+TIMEOUT,text)
def Answered(self,verb):
if self.waiting and (self.waiting[0]==verb or verb in ('state','error')):self.waiting=None
self.unsupported=False
def Notify(self,kind):
if self.listener:self.listener(kind)
def Receive(self,line):
if not line.startswith('MTSB1 '):return False
words=line.split()
try:self.Parse(words[1:])
except (ValueError,IndexError,KeyError):self.loading=None
return True
def Parse(self,words):
kind=words[0]
if kind=='attrs':
self.loading=dict(cell=Number(words[1]),vnum=Number(words[2]),count=Number(words[3],0,255),rows=[])
elif kind=='attr':
row=self.loading;index=Number(words[1])
if not row or index!=len(row['rows']) or index>=row['count']:raise ValueError('order')
row['rows'].append((Number(words[2],0,255),Number(words[3],1,2147483647)))
elif kind=='attrs_end':
row=self.loading;self.loading=None
if not row or Number(words[1])!=row['cell'] or Number(words[2])!=row['count'] or len(row['rows'])!=row['count']:
raise ValueError('partial')
self.allowed[row['cell']]=row;self.Answered('attrs');self.Notify('attrs')
elif kind=='lock':
# Follows attrs_end (and answers lock). Servers without the lock never send it, so no buttons show.
if len(words)!=4:raise ValueError('lock')
self.locks[Number(words[1])]=(Number(words[2]),Number(words[3],0,31));self.Answered('lock');self.Notify('lock')
elif kind=='state':
if len(words)!=9 or words[8] not in REASONS:raise ValueError('state')
self.state=dict(active=Number(words[1],0,1)==1,cell=Number(words[2]),vnum=Number(words[3]),rolls=Number(words[4]),
limit=Number(words[5]),scroll=Number(words[6]),scrolls=Number(words[7]),reason=words[8])
self.Answered('state');self.Notify('state')
elif kind=='error':
if len(words)!=3 or words[2] not in ERRORS:raise ValueError('error')
if words[1]=='attrs':self.loading=None
self.error=words[2];self.Answered('error');self.Notify('error')
def ItemName(vnum):
item.SelectItem(vnum);return item.GetItemName()
def AffectText(apply,value):
affect=getattr(uiToolTip.ItemToolTip,'AFFECT_DICT',{}).get(apply)
try:
if affect:return affect(value)
except (TypeError,ValueError):pass
return L(B(u'属性#%d +%d'%(apply,value)))
def Step(maximum):return max(1,maximum//5)
class SwitchbotWindow(ui.Window):
def __init__(self):
ui.Window.__init__(self);self.SetWindowName('SwitchbotWindow');self.AddFlag('float');self.AddFlag('movable')
self.bot=Bot(net.SendChatPacket,app.GetTime,self.OnBot)
self.items=[];self.itemIndex=0;self.scrolls=[];self.scrollIndex=0;self.limitIndex=2
self.alternatives=[[],[]];self.alt=0;self.picking=False;self.pickPage=0;self.dimensions=None;self.nextScan=0
self.heading=Text(self,18,18,'自动洗练',0xffffd68b)
self.closeButton=Action(self,0,6,60,'关闭',self.Hide)
self.itemPrev=Action(self,18,58,48,'<',lambda:self.Cycle('item',-1));self.itemNext=Action(self,0,58,48,'>',lambda:self.Cycle('item',1))
self.itemText=Text(self,80,82,'')
self.scrollPrev=Action(self,18,110,48,'<',lambda:self.Cycle('scroll',-1));self.scrollNext=Action(self,0,110,48,'>',lambda:self.Cycle('scroll',1))
self.scrollText=Text(self,80,134,'')
self.limitButton=Action(self,0,110,110,'',self.NextLimit)
self.altButtons=[Action(self,18+i*104,162,96,'方案一' if i==0 else '方案二',lambda i=i:self.SelectAlt(i)) for i in range(2)]
self.addButton=Action(self,0,162,110,'添加属性',self.TogglePick)
self.rows=[]
for i in range(MAX_TARGETS):
y=214+i*46
self.rows.append(dict(text=Text(self,24,y+22,''),minus=Action(self,0,y,44,'-',lambda i=i:self.Adjust(i,-1)),
plus=Action(self,0,y,44,'+',lambda i=i:self.Adjust(i,1)),remove=Action(self,0,y,44,'×',lambda i=i:self.Remove(i)),
pick=Action(self,18,y,100,'',lambda i=i:self.Pick(i))))
self.pickPrev=Action(self,18,0,80,'上一页',lambda:self.PickPage(-1));self.pickNext=Action(self,0,0,80,'下一页',lambda:self.PickPage(1))
self.startButton=Action(self,18,0,120,'开始洗练',self.Start);self.stopButton=Action(self,146,0,120,'停止',self.bot.Stop)
self.lockButtons=[Action(self,0,0,40,'',lambda i=i:self.ToggleLock(i)) for i in range(5)]
self.status=Text(self,18,0,'',0xffc3b7a1);self.current=Text(self,18,0,'',0xffefdfc3)
self.Reflow();self.Hide()
def Buttons(self):
rows=[b for r in self.rows for b in (r['minus'],r['plus'],r['remove'],r['pick'])]
return [self.closeButton,self.itemPrev,self.itemNext,self.scrollPrev,self.scrollNext,self.limitButton,self.addButton,
self.pickPrev,self.pickNext,self.startButton,self.stopButton]+self.altButtons+self.lockButtons+rows
def Open(self):
self.Reflow();self.Scan();self.SetCenterPosition();self.Show();self.SetTop();self.bot.Status();self.RequestAttrs()
def Scan(self):
items=[];scrolls={}
for cell in range(player.INVENTORY_PAGE_SIZE*player.INVENTORY_PAGE_COUNT):
vnum=player.GetItemIndex(player.INVENTORY,cell)
if not vnum:continue
item.SelectItem(vnum);kind=item.GetItemType()
if kind==item.ITEM_TYPE_USE and item.GetItemSubType()==USE_CHANGE_ATTRIBUTE:
scrolls[vnum]=scrolls.get(vnum,0)+player.GetItemCount(player.INVENTORY,cell)
elif kind in (item.ITEM_TYPE_WEAPON,item.ITEM_TYPE_ARMOR) and any(player.GetItemAttribute(player.INVENTORY,cell,i)[0] for i in range(5)):
items.append((cell,vnum))
selected=self.Selected();scroll=self.Scroll();state=self.bot.state
if state and state['active'] and (state['cell'],state['vnum']) in items:
# The server binds the bot to the item ID and reports its current cell; follow it after a move.
if selected and selected[0] in self.bot.allowed and selected[1]==state['vnum']:
self.bot.allowed[state['cell']]=dict(self.bot.allowed[selected[0]],cell=state['cell'])
if selected[0] in self.bot.locks:self.bot.locks[state['cell']]=self.bot.locks[selected[0]]
selected=(state['cell'],state['vnum'])
self.items=items;self.scrolls=sorted(scrolls.items())
self.itemIndex=next((i for i,v in enumerate(items) if v==selected),
next((i for i,v in enumerate(items) if selected and v[1]==selected[1]),min(self.itemIndex,max(0,len(items)-1))))
self.scrollIndex=next((i for i,v in enumerate(self.scrolls) if v[0]==scroll),min(self.scrollIndex,max(0,len(self.scrolls)-1)))
self.nextScan=app.GetTime()+1
if self.Selected()!=selected:self.alternatives=[[],[]];self.RequestAttrs()
def Selected(self):return self.items[self.itemIndex] if self.items else None
def Scroll(self):return self.scrolls[self.scrollIndex][0] if self.scrolls else 0
def RequestAttrs(self):
selected=self.Selected()
if selected and (self.bot.allowed.get(selected[0],{}).get('vnum')!=selected[1]):self.bot.RequestAttrs(selected[0])
def Allowed(self):
selected=self.Selected()
data=self.bot.allowed.get(selected[0]) if selected else None
return data['rows'] if data and data['vnum']==selected[1] else None
def Cycle(self,kind,step):
if self.bot.Running():return
if kind=='item' and self.items:
self.itemIndex=(self.itemIndex+step)%len(self.items);self.alternatives=[[],[]];self.picking=False;self.RequestAttrs()
elif kind=='scroll' and self.scrolls:self.scrollIndex=(self.scrollIndex+step)%len(self.scrolls)
self.Refresh()
def NextLimit(self):
if not self.bot.Running():self.limitIndex=(self.limitIndex+1)%len(LIMITS);self.Refresh()
def SelectAlt(self,index):self.alt=index;self.picking=False;self.Refresh()
def TogglePick(self):
if self.bot.Running() or self.Allowed() is None:return
self.picking=not self.picking;self.pickPage=0;self.Refresh()
def Candidates(self):
used=set(a for a,v in self.alternatives[self.alt])
return [r for r in self.Allowed() or () if r[0] not in used]
def PickPage(self,step):self.pickPage+=step;self.Refresh()
def Pick(self,index):
rows=self.Candidates()[self.pickPage*MAX_TARGETS:]
if index<len(rows) and len(self.alternatives[self.alt])<MAX_TARGETS:
self.alternatives[self.alt].append(list(rows[index]));self.picking=False
self.Refresh()
def Maximum(self,apply):return dict(self.Allowed() or ()).get(apply,1)
def Adjust(self,index,direction):
target=self.alternatives[self.alt][index];maximum=self.Maximum(target[0])
target[1]=max(1,min(maximum,target[1]+direction*Step(maximum)));self.Refresh()
def Locks(self):
selected=self.Selected()
return self.bot.LockMask(*selected) if selected else None
def ToggleLock(self,slot):
selected=self.Selected()
if selected and not self.bot.Running():self.bot.Lock(selected[0],slot);self.Refresh()
def Remove(self,index):del self.alternatives[self.alt][index];self.Refresh()
def Start(self):
selected=self.Selected()
if not selected or self.bot.Running():return
if not self.Scroll():self.bot.error='scroll';self.Refresh();return
error=self.bot.Start(selected[0],self.Scroll(),LIMITS[self.limitIndex],[[tuple(t) for t in a] for a in self.alternatives])
if error:self.bot.error='target' if error=='target' else 'invalid'
self.Refresh()
def OnBot(self,kind):
state=self.bot.state
if kind=='state' and state and not state['active'] and state['reason'] not in ('idle',):
message=u'自动洗练:'+U(REASONS[state['reason']])+u'(%d 次)'%state['rolls']
chat.AppendChat(chat.CHAT_TYPE_INFO,L(B(message)))
if state['reason']=='matched' and not self.IsShow():self.Open()
if kind=='state':self.nextScan=0
self.Refresh()
def Refresh(self):
running=self.bot.Running();allowed=self.Allowed();selected=self.Selected()
if selected:self.itemText.SetText(ItemName(selected[1])+L(B(u' (%d / %d)'%(self.itemIndex+1,len(self.items)))))
else:self.itemText.SetText(L('背包中没有可洗练的武器或防具'))
if self.scrolls:
vnum,count=self.scrolls[self.scrollIndex];self.scrollText.SetText(ItemName(vnum)+L(B(u' ×%d'%count)))
else:self.scrollText.SetText(L('背包中没有洗练道具'))
self.limitButton.SetText(L(B(u'上限 %d 次'%LIMITS[self.limitIndex])))
for i,b in enumerate(self.altButtons):b.SetText(L(B((u'【%s %d】' if i==self.alt else u'%s %d')%(u'方案一' if i==0 else u'方案二',len(self.alternatives[i])))))
self.addButton.SetText(L('返回' if self.picking else '添加属性'))
for b in (self.itemPrev,self.itemNext,self.scrollPrev,self.scrollNext,self.limitButton):b.SetEnabled(not running)
self.addButton.SetEnabled(not running and allowed is not None and (self.picking or len(self.alternatives[self.alt])<MAX_TARGETS))
targets=self.alternatives[self.alt];candidates=self.Candidates() if self.picking else []
pages=max(1,(len(candidates)+MAX_TARGETS-1)//MAX_TARGETS);self.pickPage=max(0,min(self.pickPage,pages-1))
for i,row in enumerate(self.rows):
for key in ('text','minus','plus','remove','pick'):row[key].Hide()
if self.picking:
index=self.pickPage*MAX_TARGETS+i
if index<len(candidates):
row['pick'].SetText(AffectText(*candidates[index]));row['pick'].Show()
elif i<len(targets):
apply,value=targets[i];row['text'].SetText(L('≥ ')+AffectText(apply,value));row['text'].Show()
for key in ('minus','plus','remove'):row[key].SetEnabled(not running);row[key].Show()
for b in (self.pickPrev,self.pickNext):
if self.picking and pages>1:b.Show()
else:b.Hide()
locks=self.Locks()
for i,b in enumerate(self.lockButtons):
filled=selected and player.GetItemAttribute(player.INVENTORY,selected[0],i)[0]
if locks is None or self.picking or not filled:b.Hide();continue
b.SetText(L(B(u'【锁%d】'%(i+1) if locks>>i&1 else u'锁%d'%(i+1))));b.SetEnabled(not running);b.Show()
self.pickPrev.SetEnabled(self.pickPage>0);self.pickNext.SetEnabled(self.pickPage+1<pages)
self.startButton.SetEnabled(not running and bool(selected) and any(self.alternatives));self.stopButton.SetEnabled(running)
self.status.SetText(L(B(self.StatusText(allowed))));self.current.SetText(self.CurrentText(selected))
def StatusText(self,allowed):
state=self.bot.state
if self.bot.error:return u'!'+U(ERRORS[self.bot.error])
if self.Selected() and allowed is None:return u'正在读取可洗属性…'
if state and (state['active'] or state['reason']!='idle'):
return u'%s · %d / %d 次 · 剩余道具 %d'%(U(REASONS[state['reason']]),state['rolls'],state['limit'],state['scrolls'])
if self.Locks():return u'已锁定的属性在每次洗练中保持不变'
return u'任一方案的属性全部达标即停止;只看前 5 条普通属性'
def CurrentText(self,selected):
if not selected:return ''
parts=[];locks=self.Locks() or 0
for i in range(5):
apply,value=player.GetItemAttribute(player.INVENTORY,selected[0],i)
if apply:parts.append((L('[锁]') if locks>>i&1 else '')+AffectText(apply,value))
return ' / '.join(parts)
def Reflow(self):
dims=(wndMgr.GetScreenWidth(),wndMgr.GetScreenHeight())
if dims==self.dimensions:return
self.dimensions=dims;width=min(600,max(480,dims[0]-16));height=min(560,max(400,dims[1]-8));self.SetSize(width,height)
self.closeButton.SetPosition(width-76,6);self.itemNext.SetPosition(width-66,58);self.limitButton.SetPosition(width-128,110)
self.scrollNext.SetPosition(width-184,110);self.addButton.SetPosition(width-128,162)
for row in self.rows:
x,y=row['minus'].GetLocalPosition()
row['minus'].SetPosition(width-166,y);row['plus'].SetPosition(width-116,y);row['remove'].SetPosition(width-66,y)
row['pick'].SetSize(width-36,44);row['pick'].label.SetPosition((width-36)//2,22)
bottom=height-104
self.pickPrev.SetPosition(18,bottom);self.pickNext.SetPosition(width-98,bottom)
self.startButton.SetPosition(18,bottom);self.stopButton.SetPosition(146,bottom)
step=(width-292)//5
for i,b in enumerate(self.lockButtons):b.SetPosition(274+i*step,bottom);b.SetSize(step-4,48);b.label.SetPosition((step-4)//2,24)
self.status.SetPosition(18,height-46);self.current.SetPosition(18,height-22)
self.SetCenterPosition();self.Refresh()
def OnUpdate(self):
self.Reflow();self.bot.Tick()
if self.IsShow() and app.GetTime()>=self.nextScan:self.Scan();self.Refresh()
def OnRender(self):
x,y=self.GetGlobalPosition();grp.SetColor(0xf51b1916);grp.RenderBar(x,y,self.GetWidth(),self.GetHeight());grp.SetColor(0xff9b7b48);grp.RenderBox(x,y,self.GetWidth(),self.GetHeight())
def OnPressEscapeKey(self):self.Hide();return True
def Destroy(self):
self.Hide();self.bot.listener=None
for b in self.Buttons():b.event=None
class Entry(Action):
def __init__(self,window):
Action.__init__(self,None,0,0,64,'洗练',Toggle)
self.minimap=weakref.proxy(window.interface.wndMiniMap);self.SetWindowName('SwitchbotEntry');self.OnUpdate()
def OnUpdate(self):
x,y=self.minimap.GetGlobalPosition();self.SetPosition(max(4,x-68),y+148)
def Toggle():
if g_window:
if g_window.IsShow():g_window.Hide()
else:g_window.Open()
_open=game.GameWindow.Open
_close=game.GameWindow.Close
_command=game.GameWindow.BINARY_ServerCommand_Run
def Open(self):
global g_window,g_entry
_open(self);g_window=SwitchbotWindow();g_entry=Entry(self)
def Close(self):
global g_window,g_entry
if g_entry:g_entry.Hide();g_entry.event=None;g_entry=None
if g_window:g_window.Destroy();g_window=None
_close(self)
def Command(self,line):
if line.startswith('MTSB1 '):
if g_window:g_window.bot.Receive(line)
return 1
return _command(self,line)
game.GameWindow.Open=Open
game.GameWindow.Close=Close
game.GameWindow.BINARY_ServerCommand_Run=Command
)PY";
+10
View File
@@ -316,6 +316,16 @@ if(BUILD_TESTING AND CMAKE_SYSTEM_NAME STREQUAL CMAKE_HOST_SYSTEM_NAME)
COMMAND ${MT_WIKI_PYTHON3} ${PROJECT_SOURCE_DIR}/tests/wiki/test_timers.py) COMMAND ${MT_WIKI_PYTHON3} ${PROJECT_SOURCE_DIR}/tests/wiki/test_timers.py)
add_test(NAME port.feature_service add_test(NAME port.feature_service
COMMAND ${MT_WIKI_PYTHON3} ${PROJECT_SOURCE_DIR}/tests/wiki/test_service.py) COMMAND ${MT_WIKI_PYTHON3} ${PROJECT_SOURCE_DIR}/tests/wiki/test_service.py)
add_test(NAME port.switchbot
COMMAND ${MT_WIKI_PYTHON3} ${PROJECT_SOURCE_DIR}/tests/wiki/test_switchbot.py)
add_test(NAME port.pickup
COMMAND ${MT_WIKI_PYTHON3} ${PROJECT_SOURCE_DIR}/tests/wiki/test_pickup.py)
add_test(NAME port.display
COMMAND ${MT_WIKI_PYTHON3} ${PROJECT_SOURCE_DIR}/tests/wiki/test_display.py)
add_test(NAME port.channel
COMMAND ${MT_WIKI_PYTHON3} ${PROJECT_SOURCE_DIR}/tests/wiki/test_channel.py)
add_test(NAME port.boss
COMMAND ${MT_WIKI_PYTHON3} ${PROJECT_SOURCE_DIR}/tests/wiki/test_boss.py)
endif() endif()
# Offline locale data builder: retains 40250 proto layout and gameplay fields. # Offline locale data builder: retains 40250 proto layout and gameplay fields.
add_executable(locale_proto_patch ${PROJECT_SOURCE_DIR}/tests/port/locale_proto_patch.cpp) add_executable(locale_proto_patch ${PROJECT_SOURCE_DIR}/tests/port/locale_proto_patch.cpp)
+11
View File
@@ -252,6 +252,17 @@ void CEffectManager::DeactiveEffectInstance(DWORD dwInstanceIndex)
pEffectInstance->SetDeactive(); pEffectInstance->SetDeactive();
} }
// PORT: AVA2 ENABLE_GRAPHIC_ON_OFF (display options effect level).
void CEffectManager::ActiveEffectInstance(DWORD dwInstanceIndex)
{
TEffectInstanceMap::iterator itor = m_kEftInstMap.find(dwInstanceIndex);
if (itor == m_kEftInstMap.end())
return;
itor->second->SetActive();
}
void CEffectManager::CreateUnsafeEffectInstance(DWORD dwEffectDataID, CEffectInstance ** ppEffectInstance) void CEffectManager::CreateUnsafeEffectInstance(DWORD dwEffectDataID, CEffectInstance ** ppEffectInstance)
{ {
CEffectData * pEffect; CEffectData * pEffect;
+1
View File
@@ -47,6 +47,7 @@ class CEffectManager : public CScreen, public CSingleton<CEffectManager>
BOOL SelectEffectInstance(DWORD dwInstanceIndex); BOOL SelectEffectInstance(DWORD dwInstanceIndex);
bool DestroyEffectInstance(DWORD dwInstanceIndex); bool DestroyEffectInstance(DWORD dwInstanceIndex);
void DeactiveEffectInstance(DWORD dwInstanceIndex); void DeactiveEffectInstance(DWORD dwInstanceIndex);
void ActiveEffectInstance(DWORD dwInstanceIndex); // PORT: AVA2 ENABLE_GRAPHIC_ON_OFF
void SetEffectTextures(DWORD dwID, std::vector<std::string> textures); void SetEffectTextures(DWORD dwID, std::vector<std::string> textures);
void SetEffectInstancePosition(const D3DXVECTOR3 & c_rv3Position); void SetEffectInstancePosition(const D3DXVECTOR3 & c_rv3Position);
+4
View File
@@ -496,6 +496,9 @@ class CActorInstance : public IActorInstance, public IFlyTargetableObject
float GetHeight(); float GetHeight();
void ShowAllAttachingEffect(); void ShowAllAttachingEffect();
void HideAllAttachingEffect(); void HideAllAttachingEffect();
// PORT: AVA2 ENABLE_GRAPHIC_ON_OFF. Deactivates (not hides) attached effects, so it does not fight
// the assassin invisibility Show/Hide; effects attached while off start deactivated.
void SetAttachingEffectShown(bool bShown);
void ClearAttachingEffect(); void ClearAttachingEffect();
// Fishing // Fishing
@@ -793,6 +796,7 @@ class CActorInstance : public IActorInstance, public IFlyTargetableObject
// Attached Effect // Attached Effect
std::list<TAttachingEffect> m_AttachingEffectList; std::list<TAttachingEffect> m_AttachingEffectList;
bool m_bEffectInitialized; bool m_bEffectInitialized;
bool m_bAttachingEffectShown = true;
// material color // material color
DWORD m_dwMtrlColor; DWORD m_dwMtrlColor;
+20
View File
@@ -294,6 +294,8 @@ DWORD CActorInstance::AttachEffectByID(DWORD dwParentPartIndex, const char * c_p
ae.iBoneIndex = -1; ae.iBoneIndex = -1;
} }
if (!m_bAttachingEffectShown)
rkEftMgr.DeactiveEffectInstance(ae.dwEffectIndex);
m_AttachingEffectList.push_back(ae); m_AttachingEffectList.push_back(ae);
return ae.dwEffectIndex; return ae.dwEffectIndex;
@@ -472,6 +474,8 @@ void CActorInstance::RefreshActorInstance()
ae.iBoneIndex = iBoneIndex; ae.iBoneIndex = iBoneIndex;
if (!m_bAttachingEffectShown)
CEffectManager::Instance().DeactiveEffectInstance(ae.dwEffectIndex);
m_AttachingEffectList.push_back(ae); m_AttachingEffectList.push_back(ae);
} }
break; break;
@@ -593,6 +597,22 @@ void CActorInstance::HideAllAttachingEffect()
} }
} }
void CActorInstance::SetAttachingEffectShown(bool bShown)
{
if (m_bAttachingEffectShown == bShown)
return;
m_bAttachingEffectShown = bShown;
CEffectManager& rkEftMgr = CEffectManager::Instance();
for (const TAttachingEffect& ae : m_AttachingEffectList)
{
if (bShown)
rkEftMgr.ActiveEffectInstance(ae.dwEffectIndex);
else
rkEftMgr.DeactiveEffectInstance(ae.dwEffectIndex);
}
}
void CActorInstance::__ClearAttachingEffect() void CActorInstance::__ClearAttachingEffect()
{ {
m_bEffectInitialized = false; m_bEffectInitialized = false;
+7 -1
View File
@@ -640,7 +640,13 @@ void CMapOutdoor::RenderPCBlocker()
STATEMANAGER.SaveTransform(D3DTS_TEXTURE1, &m_matBuildingTransparent); STATEMANAGER.SaveTransform(D3DTS_TEXTURE1, &m_matBuildingTransparent);
STATEMANAGER.SetTexture(1, m_BuildingTransparentImageInstance.GetTexturePointer()->GetD3DTexture()); STATEMANAGER.SetTexture(1, m_BuildingTransparentImageInstance.GetTexturePointer()->GetD3DTexture());
std::for_each(m_PCBlockerVector.begin(), m_PCBlockerVector.end(), FRenderPCBlocker()); // PORT: a tree near the camera is drawn here as a PC blocker, outside RenderTree, so hiding
// PART_TREE (mt_display) left it on screen. Skip it the same way RenderTree does.
const bool bTreeVisible = IsVisiblePart(PART_TREE);
FRenderPCBlocker kRenderPCBlocker;
for (CGraphicObjectInstance * pInstance : m_PCBlockerVector)
if (bTreeVisible || TREE_OBJECT != pInstance->GetType())
kRenderPCBlocker(pInstance);
STATEMANAGER.SetTexture(1, NULL); STATEMANAGER.SetTexture(1, NULL);
STATEMANAGER.RestoreTransform(D3DTS_TEXTURE1); STATEMANAGER.RestoreTransform(D3DTS_TEXTURE1);
+21
View File
@@ -4,6 +4,7 @@
#include "PythonNonPlayer.h" #include "PythonNonPlayer.h"
#include "PythonPlayer.h" #include "PythonPlayer.h"
#include "PythonCharacterManager.h" #include "PythonCharacterManager.h"
#include "PythonSystem.h"
#include "AbstractPlayer.h" #include "AbstractPlayer.h"
#include "AbstractApplication.h" #include "AbstractApplication.h"
#include "Packet.h" #include "Packet.h"
@@ -1868,6 +1869,7 @@ void CInstanceBase::Update()
{ {
++ms_dwUpdateCounter; ++ms_dwUpdateCounter;
__UpdateEffectShown();
StateProcess(); StateProcess();
m_GraphicThingInstance.PhysicsProcess(); m_GraphicThingInstance.PhysicsProcess();
m_GraphicThingInstance.RotationProcess(); m_GraphicThingInstance.RotationProcess();
@@ -2454,6 +2456,25 @@ bool CInstanceBase::__IsInViewFrustum()
return m_GraphicThingInstance.isShow(); return m_GraphicThingInstance.isShow();
} }
// PORT: AVA2 ENABLE_GRAPHIC_ON_OFF effect level, applied to attached effects (skills, buffs, refine glow).
void CInstanceBase::__UpdateEffectShown()
{
const int iLevel = CPythonSystem::Instance().GetEffectLevel();
bool isShown = true;
if (iLevel == 4)
isShown = false;
else if (iLevel != 0 && !__IsMainInstance())
{
if (iLevel == 1)
isShown = IsEnemy() || IsStone();
else if (iLevel == 2)
isShown = IsPC();
else
isShown = false;
}
m_GraphicThingInstance.SetAttachingEffectShown(isShown);
}
bool CInstanceBase::__CanRender() bool CInstanceBase::__CanRender()
{ {
if (!__IsInViewFrustum()) if (!__IsInViewFrustum())
+1
View File
@@ -407,6 +407,7 @@ class CInstanceBase
protected: protected:
bool __IsExistMainInstance(); bool __IsExistMainInstance();
bool __IsMainInstance(); bool __IsMainInstance();
void __UpdateEffectShown();
bool __MainCanSeeHiddenThing(); bool __MainCanSeeHiddenThing();
float __GetBowRange(); float __GetBowRange();
+4
View File
@@ -110,6 +110,9 @@ class CPythonSystem : public CSingleton<CPythonSystem>
bool IsAlwaysShowName(); bool IsAlwaysShowName();
bool IsShowDamage(); bool IsShowDamage();
bool IsShowSalesText(); bool IsShowSalesText();
// PORT: AVA2 effect_level (0 all, 1 hide players/NPCs, 2 hide monsters/NPCs, 3 hide others, 4 hide all).
int GetEffectLevel() { return m_iPortEffectLevel; }
void SetEffectLevel(int iLevel) { m_iPortEffectLevel = iLevel < 0 || iLevel > 4 ? 0 : iLevel; }
bool IsUseDefaultIME(); bool IsUseDefaultIME();
bool IsNoSoundCard(); bool IsNoSoundCard();
bool IsAutoTiling(); bool IsAutoTiling();
@@ -159,4 +162,5 @@ class CPythonSystem : public CSingleton<CPythonSystem>
bool m_isInterfaceConfig; bool m_isInterfaceConfig;
PyObject * m_poInterfaceHandler; PyObject * m_poInterfaceHandler;
TWindowStatus m_WindowStatus[WINDOW_MAX_NUM]; TWindowStatus m_WindowStatus[WINDOW_MAX_NUM];
int m_iPortEffectLevel = 0;
}; };
@@ -211,6 +211,22 @@ PyObject * systemSetShowSalesTextFlag(PyObject * poSelf, PyObject * poArgs)
return Py_BuildNone(); return Py_BuildNone();
} }
PyObject * systemSetEffectLevel(PyObject * poSelf, PyObject * poArgs)
{
int iLevel;
if (!PyTuple_GetInteger(poArgs, 0, &iLevel))
return Py_BuildException();
CPythonSystem::Instance().SetEffectLevel(iLevel);
return Py_BuildNone();
}
PyObject * systemGetEffectLevel(PyObject * poSelf, PyObject * poArgs)
{
return Py_BuildValue("i", CPythonSystem::Instance().GetEffectLevel());
}
PyObject * systemIsAlwaysShowName(PyObject * poSelf, PyObject * poArgs) PyObject * systemIsAlwaysShowName(PyObject * poSelf, PyObject * poArgs)
{ {
return Py_BuildValue("i", CPythonSystem::Instance().IsAlwaysShowName()); return Py_BuildValue("i", CPythonSystem::Instance().IsAlwaysShowName());
@@ -422,6 +438,8 @@ void initsystem()
{ "SetShowSalesTextFlag", systemSetShowSalesTextFlag, METH_VARARGS }, { "SetShowSalesTextFlag", systemSetShowSalesTextFlag, METH_VARARGS },
{ "IsShowSalesText", systemIsShowSalesText, METH_VARARGS }, { "IsShowSalesText", systemIsShowSalesText, METH_VARARGS },
{ "SetEffectLevel", systemSetEffectLevel, METH_VARARGS }, // PORT: AVA2
{ "GetEffectLevel", systemGetEffectLevel, METH_VARARGS },
{ "GetShadowLevel", systemGetShadowLevel, METH_VARARGS }, { "GetShadowLevel", systemGetShadowLevel, METH_VARARGS },
{ "SetShadowLevel", systemSetShadowLevel, METH_VARARGS }, { "SetShadowLevel", systemSetShadowLevel, METH_VARARGS },
+117
View File
@@ -0,0 +1,117 @@
import sys
import types
import unittest
from pathlib import Path
ROOT=Path(__file__).resolve().parents[2]
def script(name):return (ROOT/'src/platform/ScriptLib'/name).read_text().split('R"PY(',1)[1].rsplit(')PY";',1)[0]
class Widget(object):
def __init__(self,*a,**k):self.shown=False;self.text='';self.pos=(0,0);self.size=(0,0)
def __getattr__(self,name):return lambda *a,**k:None
def Show(self):self.shown=True
def Hide(self):self.shown=False
def IsShow(self):return self.shown
def SetText(self,text):self.text=text
def SetPosition(self,x,y):self.pos=(x,y)
def GetGlobalPosition(self):return self.pos
def SetSize(self,w,h):self.size=(w,h)
def GetWidth(self):return self.size[0]
def GetHeight(self):return self.size[1]
class Action(Widget):
def __init__(self,parent,x,y,width,text,event):
Widget.__init__(self);self.pos=(x,y);self.event=event;self.enabled=True;self.text=text;self.shown=True
def SetEnabled(self,enabled):self.enabled=enabled
class Service(object):
def __init__(self):self.requests=[]
def Request(self,kind,subject,offset,callback):self.requests.append((kind,subject,offset,callback));return len(self.requests)
def Reply(self,rows,time=1700000000,error=None):
callback=self.requests[-1][3]
callback(None if error else dict(kind='bosses',subject=0,offset=0,total=len(rows),mode=0,time=time,rows=rows),error)
TRENT=[2307,68,51200,-300,1,0,1,1700000100,9000]
SKIPIA=[1192,72,0,0,1,1,1,1700028800,28800]
DESERT=[2191,999,10000,20000,99,0,1,0,1800]
class BossTests(unittest.TestCase):
def setUp(self):
self.time=100.;self.chat=[]
mods={n:types.ModuleType(n) for n in ('app','chat','game','grp','nonplayer','ui','wndMgr','localeInfo','mt_feature_service','mt_biolog')}
mods['app'].GetTime=lambda:self.time
mods['chat'].CHAT_TYPE_INFO=1;mods['chat'].AppendChat=lambda t,m:self.chat.append(m)
mods['game'].GameWindow=type('GameWindow',(),dict(Open=lambda s:None,Close=lambda s:None))
grp=mods['grp'];grp.SetColor=grp.RenderBar=grp.RenderBox=lambda *a:None
mods['nonplayer'].GetMonsterName=lambda vnum:{2307:'TreeKing',1192:'Skipia',2191:'Turtle'}.get(vnum,'')
mods['ui'].Window=Widget
mods['wndMgr'].GetScreenWidth=lambda:1280;mods['wndMgr'].GetScreenHeight=lambda:800
mods['localeInfo'].MINIMAP_ZONE_NAME_DICT={'metin2_map_trent02':'RedWood'}
self.service=Service();mods['mt_feature_service'].g_service=self.service
mods['mt_biolog'].Action=Action;mods['mt_biolog'].Text=lambda p,x,y,t='',c=0:Widget();mods['mt_biolog'].L=lambda t:t
self.previous={n:sys.modules.get(n) for n in mods}
sys.modules.update(mods)
self.ns={'__name__':'mt_boss'};exec(script('BossScript.inc'),self.ns)
self.game=sys.modules['game'];self.gw=self.game.GameWindow()
self.gw.interface=types.SimpleNamespace(wndMiniMap=Widget())
def tearDown(self):
for name,value in self.previous.items():
if value is None:sys.modules.pop(name,None)
else:sys.modules[name]=value
def open(self):
self.game.GameWindow.Open(self.gw);w=self.ns['g_window'];w.Open();return w
def test_window_lists_server_rows(self):
w=self.open();self.assertEqual(self.ns['g_entry'].pos,(4,356))
self.assertEqual(self.service.requests[-1][:3],('bosses',0,0));self.assertFalse(w.refreshButton.enabled)
self.service.Reply([TRENT,SKIPIA,DESERT]);self.assertTrue(w.refreshButton.enabled)
self.assertEqual(w.lines[0].text,'[CH1] TreeKing RedWood')
self.assertEqual(w.details[0].text,'刷新倒计时 00:01:40 · 坐标 (512, -3) · 周期 02:30:00')
self.assertIn('存活 1/1',w.details[1].text);self.assertIn('随机位置',w.details[1].text)
self.assertEqual(w.lines[2].text,'[共享] Turtle 地图999');self.assertIn('不再刷新',w.details[2].text)
self.assertFalse(w.remindButtons[1].enabled) # alive
self.assertFalse(w.remindButtons[2].enabled) # no timer
self.assertFalse(w.lines[3].shown);self.assertIn('共 3 个',w.status.text)
self.time+=40;w.Render();self.assertIn('00:01:00',w.details[0].text) # counts down from the server time
def test_pages(self):
rows=[[2000+i,68,0,0,1,0,1,1700000100,600] for i in range(11)]
w=self.open();self.service.Reply(rows)
self.assertFalse(w.prevButton.enabled);self.assertTrue(w.nextButton.enabled)
w.nextButton.event();self.assertTrue(w.lines[2].shown);self.assertFalse(w.lines[3].shown);self.assertIn('第 2/2 页',w.status.text)
self.assertFalse(w.nextButton.enabled)
def test_reminder_fires_only_on_confirmed_spawn(self):
w=self.open();self.service.Reply([TRENT,SKIPIA]);w.remindButtons[0].event()
self.assertIn('开',w.remindButtons[0].text);w.Hide()
tick=self.ns['g_tick'];count=len(self.service.requests)
self.time+=50;tick.OnUpdate();self.assertEqual(len(self.service.requests),count) # not due yet
self.time+=60;tick.OnUpdate();self.assertEqual(len(self.service.requests),count+1)
self.service.Reply([TRENT,SKIPIA],time=1700000110);self.assertEqual(self.chat,[]) # timer passed, not spawned
self.assertIn(('2307',),[(str(k[0]),) for k in self.ns['g_tracker'].reminders])
spawned=list(TRENT);spawned[5]=1;spawned[7]=1700009110
self.time+=40;tick.OnUpdate();self.service.Reply([spawned,SKIPIA],time=1700000150)
self.assertEqual(self.chat,['TreeKing 已在 RedWood 刷新']);self.assertEqual(self.ns['g_tracker'].reminders,set())
def test_errors_and_close(self):
w=self.open();self.service.Reply([],error='unsupported');self.assertIn('未启用',w.status.text)
w.Query();self.service.Reply([]);self.assertIn('没有定时刷新',w.status.text)
w.Query();self.service.Reply([TRENT]);w.remindButtons[0].event()
self.game.GameWindow.Close(self.gw)
self.assertIsNone(self.ns['g_window']);self.assertIsNone(self.ns['g_entry'])
self.assertEqual(self.ns['g_tracker'].reminders,set());self.assertIsNone(self.ns['g_tracker'].rows)
def test_maps_match_server_index(self):
maps=self.ns['MAPS']
self.assertEqual((maps[68],maps[72],maps[302]),('metin2_map_trent02','metin2_map_skipia_dungeon_01','metin2_map_dawnmistwood'))
if __name__=='__main__':unittest.main()
+142
View File
@@ -0,0 +1,142 @@
import os
import sys
import tempfile
import types
import unittest
from pathlib import Path
ROOT=Path(__file__).resolve().parents[2]
def script(name):return (ROOT/'src/platform/ScriptLib'/name).read_text().split('R"PY(',1)[1].rsplit(')PY";',1)[0]
class Widget(object):
def __init__(self,*a,**k):self.shown=False;self.text='';self.pos=(0,0);self.size=(0,0)
def __getattr__(self,name):return lambda *a,**k:None
def Show(self):self.shown=True
def Hide(self):self.shown=False
def IsShow(self):return self.shown
def SetText(self,text):self.text=text
def SetPosition(self,x,y):self.pos=(x,y)
def GetGlobalPosition(self):return self.pos
def SetSize(self,w,h):self.size=(w,h)
def GetWidth(self):return self.size[0]
def GetHeight(self):return self.size[1]
class Action(Widget):
def __init__(self,parent,x,y,width,text,event):
Widget.__init__(self);self.pos=(x,y);self.event=event;self.enabled=True;self.text=text;self.shown=True
def SetEnabled(self,enabled):self.enabled=enabled
class Stream(object):
def __init__(self):
self.id='admin';self.pwd='secret';self.addr='10.0.0.1';self.port=13000;self.account_addr='10.0.0.1';self.account_port=11000
self.slot=2;self.isAutoSelect=0
def SetConnectInfo(self,addr,port,account_addr=0,account_port=0):
self.addr=addr;self.port=port;self.account_addr=account_addr;self.account_port=account_port
def SetCharacterSlot(self,slot):self.slot=slot
def GetCharacterSlot(self):return self.slot
class Login(object):
# introLogin.LoginWindow.Open resets the connect info and the slot from loginInfo.xml.
def __init__(self,stream,log):self.stream=stream;self.log=log
def Open(self):self.stream.SetConnectInfo('',0,'',0);self.stream.SetCharacterSlot(0);self.stream.isAutoSelect=0
def OnUpdate(self):pass
def OnLoginFailure(self,error):self.log.append(('failure',error))
def OnConnectFailure(self):self.log.append(('connect',))
def Connect(self,id,pwd):self.log.append(('connect_to',self.stream.addr,self.stream.port,id,pwd))
class ChannelTests(unittest.TestCase):
def setUp(self):
self.time=1.;self.sent=[];self.chat=[];self.log=[];self.serverinfo=[]
self.cwd=os.getcwd();self.tmp=tempfile.TemporaryDirectory();os.chdir(self.tmp.name)
mods={n:types.ModuleType(n) for n in ('app','chat','game','grp','introLogin','net','serverInfo','ui','mt_biolog','mt_wiki')}
mods['app'].GetTime=lambda:self.time
mods['chat'].CHAT_TYPE_INFO=1;mods['chat'].AppendChat=lambda t,m:self.chat.append(m)
mods['net'].SendChatPacket=self.sent.append;mods['net'].SetServerInfo=self.serverinfo.append
mods['game'].GameWindow=type('GameWindow',(),dict(Open=lambda s:None,Close=lambda s:None,OnUpdate=lambda s:None))
mods['introLogin'].LoginWindow=Login
si=mods['serverInfo']
si.REGION_DICT={0:{1:{'name':'Metin2','channel':{
1:{'name':'CH1','ip':'10.0.0.1','tcp_port':13000},2:{'name':'CH2','ip':'10.0.0.1','tcp_port':13010},
3:{'name':'CH3','ip':'10.0.0.1','tcp_port':13020}}},
2:{'name':'Test','channel':{1:{'name':'CH1','ip':'127.0.0.1','tcp_port':13000}}}}}
si.REGION_AUTH_SERVER_DICT={0:{1:{'ip':'10.0.0.1','port':11000},2:{'ip':'127.0.0.1','port':11000}}}
grp=mods['grp'];grp.SetColor=grp.RenderBar=grp.RenderBox=lambda *a:None
mods['ui'].Window=Widget
mods['mt_biolog'].Action=Action;mods['mt_biolog'].Text=lambda p,x,y,t='',c=0:Widget();mods['mt_biolog'].L=lambda t:t if isinstance(t,str) else t.decode('utf-8')
mods['mt_wiki'].B=lambda t,limit=0:t
self.previous={n:sys.modules.get(n) for n in mods}
sys.modules.update(mods)
self.ns={'__name__':'mt_channel'};exec(script('ChannelScript.inc'),self.ns)
self.stream=Stream();self.game=sys.modules['game'];self.gw=self.game.GameWindow()
self.gw.stream=self.stream;self.gw.interface=types.SimpleNamespace(wndMiniMap=Widget())
def tearDown(self):
os.chdir(self.cwd);self.tmp.cleanup()
for name,value in self.previous.items():
if value is None:sys.modules.pop(name,None)
else:sys.modules[name]=value
def test_locate(self):
Locate=self.ns['Locate']
self.assertEqual(Locate('10.0.0.1',13010),(0,1,2))
self.assertEqual(Locate('127.0.0.1',13000),(0,2,1))
self.assertEqual(Locate('10.0.0.1',13040),(0,1,0)) # unknown port: first server, current unknown
Path('channel.inf').write_text('2 1 0')
self.assertEqual(Locate('10.0.0.1',13040),(0,2,0)) # the server last picked on the login board
Path('channel.inf').write_text('9 1 0');self.assertEqual(Locate('x',1),(0,1,0))
def test_full_switch(self):
game=self.game;gw=self.gw
game.GameWindow.Open(gw);w=self.ns['g_window'];self.assertEqual(self.ns['g_entry'].pos,(4,304))
w.Open();self.assertEqual(len(w.channelButtons),3);self.assertIn('CH1',w.current.text)
self.assertFalse(w.channelButtons[0].enabled);self.assertIn('【',w.channelButtons[0].text)
w.channelButtons[1].event();self.assertEqual(self.sent,['/logout'])
self.assertTrue(all(not b.enabled for b in w.channelButtons));self.assertIn('正在退出',w.status.text)
w.channelButtons[2].event();self.assertEqual(self.sent,['/logout']) # busy: a second /logout would cancel it
game.GameWindow.Close(gw) # server closed the session -> SetLoginPhase
login=sys.modules['introLogin'].LoginWindow(self.stream,self.log);login.Open()
self.assertEqual(self.log,[('connect_to','10.0.0.1',13010,'admin','secret')])
self.assertEqual((self.stream.account_addr,self.stream.account_port,self.stream.slot,self.stream.isAutoSelect),('10.0.0.1',11000,2,1))
self.assertEqual(self.serverinfo,['Metin2, CH2']);self.assertEqual(Path('channel.inf').read_text(),'1 2 0')
game.GameWindow.Open(gw) # introSelect auto-selected slot 2 and the game started
self.assertEqual(self.stream.isAutoSelect,0);self.assertIsNone(self.ns['g_switcher'].stage)
self.assertIn('已换到 CH2',self.chat[-1])
w=self.ns['g_window'];w.Open();self.assertIn('CH2',w.current.text);self.assertTrue(w.channelButtons[0].enabled)
login.Open();self.assertEqual(len(self.log),1) # a later login window is left alone
def test_logout_refused_times_out(self):
self.game.GameWindow.Open(self.gw);w=self.ns['g_window'];w.Open();w.channelButtons[2].event()
self.time+=19;self.game.GameWindow.OnUpdate(self.gw);self.assertEqual(self.ns['g_switcher'].stage,'logout')
self.time+=1;self.game.GameWindow.OnUpdate(self.gw);self.assertIsNone(self.ns['g_switcher'].stage)
self.assertIn('换线已取消',self.chat[-1]);self.assertTrue(w.channelButtons[2].enabled)
def test_login_failure_clears_auto_select(self):
self.game.GameWindow.Open(self.gw);w=self.ns['g_window'];w.Open();w.channelButtons[1].event()
login=sys.modules['introLogin'].LoginWindow(self.stream,self.log);login.Open()
self.assertEqual(self.stream.isAutoSelect,1)
login.OnLoginFailure('ALREADY');self.assertEqual(self.stream.isAutoSelect,0)
self.assertEqual(self.log[-1],('failure','ALREADY'));self.assertIn('登录目标频道失败',self.chat[-1])
self.assertIsNone(self.ns['g_switcher'].stage)
def test_refuses_without_account_or_same_channel(self):
s=self.ns['g_switcher'];place=(0,1,1)
self.assertFalse(s.Start(self.stream,place,1));self.assertEqual(s.error,'channel')
self.assertFalse(s.Start(self.stream,place,7));self.assertEqual(s.error,'channel')
self.stream.pwd='';self.assertFalse(s.Start(self.stream,place,2));self.assertEqual(s.error,'account')
self.assertEqual(self.sent,[])
def test_server_logout_countdown_fits_timeout(self):
server=ROOT.parent/'metin2-server/src/server/game/src/cmd_general.cpp'
if not server.exists():self.skipTest('server checkout not installed')
text=server.read_text(encoding='latin1');body=text.split('ACMD(do_cmd)',1)[1].split('\n}\n',1)[0]
self.assertIn('info->left_second = 10;',body);self.assertLess(10+2,self.ns['LOGOUT_TIMEOUT'])
self.assertIn('event_cancel(&ch->m_pkTimedEvent)',body) # why the switcher never sends /logout twice
if __name__=='__main__':unittest.main()
+94
View File
@@ -0,0 +1,94 @@
import os
import re
import sys
import tempfile
import types
import unittest
from pathlib import Path
ROOT=Path(__file__).resolve().parents[2]
def script(name):return (ROOT/'src/platform/ScriptLib'/name).read_text().split('R"PY(',1)[1].rsplit(')PY";',1)[0]
class Widget(object):
def __init__(self,*a,**k):self.shown=False;self.text='';self.pos=(0,0);self.size=(0,0)
def __getattr__(self,name):return lambda *a,**k:None
def Show(self):self.shown=True
def Hide(self):self.shown=False
def IsShow(self):return self.shown
def SetText(self,text):self.text=text
def SetPosition(self,x,y):self.pos=(x,y)
def GetGlobalPosition(self):return self.pos
def SetSize(self,w,h):self.size=(w,h)
def GetWidth(self):return self.size[0]
def GetHeight(self):return self.size[1]
class Action(Widget):
def __init__(self,parent,x,y,width,text,event):
Widget.__init__(self);self.pos=(x,y);self.event=event;self.text=text;self.shown=True
class DisplayTests(unittest.TestCase):
def setUp(self):
self.cwd=os.getcwd();self.tmp=tempfile.TemporaryDirectory();os.chdir(self.tmp.name)
self.state=dict(effect=None,name=True,damage=True,parts={});self.opened=[]
mods={n:types.ModuleType(n) for n in ('background','game','grp','systemSetting','ui','mt_biolog','mt_wiki')}
bg=mods['background'];bg.PART_TREE=3;bg.PART_CLOUD=2;bg.SetVisiblePart=lambda part,on:self.state['parts'].__setitem__(part,on)
ss=mods['systemSetting'];ss.SetEffectLevel=lambda v:self.state.__setitem__('effect',v)
ss.IsAlwaysShowName=lambda:self.state['name'];ss.SetAlwaysShowNameFlag=lambda v:self.state.__setitem__('name',bool(v))
ss.IsShowDamage=lambda:self.state['damage'];ss.SetShowDamageFlag=lambda v:self.state.__setitem__('damage',bool(v))
mods['game'].GameWindow=type('GameWindow',(),dict(Open=lambda s:self.opened.append(1),Close=lambda s:None))
grp=mods['grp'];grp.SetColor=grp.RenderBar=grp.RenderBox=lambda *a:None
mods['ui'].Window=Widget
mods['mt_biolog'].Action=Action;mods['mt_biolog'].Text=lambda p,x,y,t='',c=0:Widget();mods['mt_biolog'].L=lambda t:t if isinstance(t,str) else t.decode('utf-8')
mods['mt_wiki'].B=lambda t,limit=0:t
self.previous={n:sys.modules.get(n) for n in mods}
sys.modules.update(mods)
def load(self):
self.ns={'__name__':'mt_display'};exec(script('DisplayScript.inc'),self.ns);return self.ns
def tearDown(self):
os.chdir(self.cwd);self.tmp.cleanup()
for name,value in self.previous.items():
if value is None:sys.modules.pop(name,None)
else:sys.modules[name]=value
def test_defaults_and_config(self):
ns=self.load();self.assertEqual(self.state['effect'],0)
o=ns['Options']();self.assertEqual(o.Dump(),'0 1 1')
for bad in ('5 1 1','1 2 1','a 1 1','1 1','10 1 1','-1 1 1'):
o=ns['Options']();o.Load(bad);self.assertEqual(o.Dump(),'0 1 1')
Path('mt_display.cfg').write_text('3 0 1')
self.load();self.assertEqual(self.state['effect'],3) # applied at boot, before any map
def test_game_window_applies_and_saves(self):
Path('mt_display.cfg').write_text('2 0 1')
ns=self.load();game=sys.modules['game'];gw=game.GameWindow();gw.interface=types.SimpleNamespace(wndMiniMap=Widget())
game.GameWindow.Open(gw);self.assertEqual(self.opened,[1])
self.assertEqual(self.state['parts'],{3:0,2:1});self.assertEqual(ns['g_entry'].pos,(4,252))
w=ns['g_window'];w.Open()
self.assertIn('【',w.levelButtons[2].text);self.assertNotIn('【',w.levelButtons[0].text)
self.assertNotIn('【',w.treeButton.text);self.assertIn('【',w.cloudButton.text)
w.levelButtons[4].event();self.assertEqual(self.state['effect'],4)
w.ToggleTree();w.ToggleCloud();self.assertEqual(self.state['parts'],{3:1,2:0})
self.assertEqual(Path('mt_display.cfg').read_text(),'4 1 0')
w.ToggleName();w.ToggleDamage();self.assertEqual((self.state['name'],self.state['damage']),(False,False))
self.assertNotIn('【',w.nameButton.text)
game.GameWindow.Close(gw);self.assertIsNone(ns['g_window']);self.assertIsNone(ns['g_entry'])
def test_levels_match_native_rule(self):
ns=self.load();text=(ROOT/'src/port/UserInterface/InstanceBase.cpp').read_text(encoding='latin1')
body=text.split('void CInstanceBase::__UpdateEffectShown()',1)[1].split('\n}\n',1)[0]
self.assertEqual(len(ns['LEVELS']),5);self.assertIn('iLevel == 4',body)
self.assertIn('IsEnemy() || IsStone()',body);self.assertIn('IsPC()',body)
system=(ROOT/'src/port/UserInterface/PythonSystem.h').read_text(encoding='latin1')
self.assertIn('iLevel > 4',system)
render=(ROOT/'src/port/GameLib/MapOutdoorRender.cpp').read_text(encoding='latin1')
blocker=render.split('void CMapOutdoor::RenderPCBlocker()',1)[1].split('\n}\n',1)[0]
self.assertIn('TREE_OBJECT != pInstance->GetType()',blocker) # near trees are drawn as PC blockers
if __name__=='__main__':unittest.main()
+127
View File
@@ -0,0 +1,127 @@
import os
import re
import sys
import tempfile
import types
import unittest
from pathlib import Path
ROOT=Path(__file__).resolve().parents[2]
def script(name):return (ROOT/'src/platform/ScriptLib'/name).read_text().split('R"PY(',1)[1].rsplit(')PY";',1)[0]
class Widget(object):
def __init__(self,*a,**k):self.shown=False;self.text='';self.pos=(0,0);self.size=(0,0)
def __getattr__(self,name):return lambda *a,**k:None
def Show(self):self.shown=True
def Hide(self):self.shown=False
def IsShow(self):return self.shown
def SetText(self,text):self.text=text
def SetPosition(self,x,y):self.pos=(x,y)
def GetGlobalPosition(self):return self.pos
def SetSize(self,w,h):self.size=(w,h)
def GetWidth(self):return self.size[0]
def GetHeight(self):return self.size[1]
class Action(Widget):
def __init__(self,parent,x,y,width,text,event):
Widget.__init__(self);self.pos=(x,y);self.event=event;self.enabled=True;self.text=text;self.shown=True
def SetEnabled(self,enabled):self.enabled=enabled
class PickupTests(unittest.TestCase):
def setUp(self):
self.time=1.;self.sent=[];self.chat=[];self.events=[];self.single=[]
self.cwd=os.getcwd();self.tmp=tempfile.TemporaryDirectory();os.chdir(self.tmp.name)
mods={n:types.ModuleType(n) for n in ('app','chat','game','grp','net','ui','mt_biolog','mt_wiki')}
mods['app'].GetTime=lambda:self.time
mods['chat'].CHAT_TYPE_INFO=1;mods['chat'].AppendChat=lambda t,m:self.chat.append(m)
mods['net'].SendChatPacket=self.sent.append
mods['game'].GameWindow=type('GameWindow',(),dict(Open=lambda s:None,Close=lambda s:None,
BINARY_ServerCommand_Run=lambda s,line:7,PickUpItem=lambda s:self.single.append(1)))
grp=mods['grp'];grp.SetColor=grp.RenderBar=grp.RenderBox=lambda *a:None
mods['ui'].Window=Widget
mods['mt_biolog'].Action=Action;mods['mt_biolog'].Text=lambda p,x,y,t='',c=0:Widget();mods['mt_biolog'].L=lambda t:t if isinstance(t,str) else t.decode('utf-8')
mods['mt_wiki'].B=lambda t,limit=0:t
self.previous={n:sys.modules.get(n) for n in mods}
sys.modules.update(mods)
self.load()
def load(self):
self.ns={'__name__':'mt_pickup'};exec(script('PickupScript.inc'),self.ns)
self.picker=self.ns['Picker'](self.sent.append,lambda:self.time,self.events.append)
def tearDown(self):
os.chdir(self.cwd);self.tmp.cleanup()
for name,value in self.previous.items():
if value is None:sys.modules.pop(name,None)
else:sys.modules[name]=value
def test_press_sends_once_per_gap_and_waits_for_reply(self):
self.assertTrue(self.picker.Press());self.assertTrue(self.picker.Press())
self.assertEqual(self.sent,['/mt_pickup 1 255'])
self.time+=.6;self.picker.Press();self.assertEqual(len(self.sent),1) # still waiting for the reply
self.assertTrue(self.picker.Receive('MTPU1 done 5 4 1'))
self.assertEqual(self.picker.result,dict(found=5,picked=4,failed=1))
self.picker.Press();self.assertEqual(len(self.sent),2)
self.picker.Receive('MTPU1 done 0 0 0');self.time+=.1;self.picker.Press()
self.assertEqual(len(self.sent),2) # inside the 0.5 s gap: swallowed (key repeat)
def test_errors_malformed_and_foreign_lines(self):
self.picker.Press();self.picker.Receive('MTPU1 error busy')
self.assertEqual(self.picker.error,'busy');self.assertIsNone(self.picker.waiting)
for bad in ('MTPU1 done 1 2','MTPU1 done a 1 1','MTPU1 error boom','MTPU1 done 1 1 1 1'):
self.assertTrue(self.picker.Receive(bad))
self.assertEqual(self.picker.error,'busy')
self.assertFalse(self.picker.Receive('MTSB1 state 0 0 0 0 0 0 0 idle'))
def test_timeout_falls_back_to_single_pickup(self):
self.picker.Press();self.time+=3.1
self.assertFalse(self.picker.Press());self.assertTrue(self.picker.unsupported)
self.assertEqual(self.events,['unsupported']);self.assertEqual(len(self.sent),1)
self.picker.Receive('MTPU1 done 0 0 0');self.assertFalse(self.picker.unsupported) # a late reply re-enables
def test_disabled_and_category_mask(self):
self.picker.enabled=False;self.assertFalse(self.picker.Press());self.assertEqual(self.sent,[])
self.picker.enabled=True;self.picker.mask=1
self.picker.Toggle(1);self.assertEqual(self.picker.mask,1) # the last category stays on
self.picker.Toggle(32);self.picker.Press();self.assertEqual(self.sent,['/mt_pickup 1 33'])
def test_config_round_trip_and_bad_files(self):
self.picker.enabled=False;self.picker.mask=6;self.ns['SaveConfig'](self.picker)
other=self.ns['Picker'](None,None);self.ns['LoadConfig'](other)
self.assertEqual((other.enabled,other.mask),(False,6))
for text in ('1 0','1 256','2 5','x 5','1','1 -3'):
p=self.ns['Picker'](None,None);p.Load(text);self.assertEqual((p.enabled,p.mask),(True,255))
def test_game_window_hooks(self):
game=sys.modules['game'];gw=game.GameWindow();gw.interface=types.SimpleNamespace(wndMiniMap=Widget())
game.GameWindow.Open(gw);w=self.ns['g_window'];picker=self.ns['g_picker']
self.assertEqual(self.ns['g_entry'].pos,(4,200))
game.GameWindow.PickUpItem(gw);self.assertEqual(self.sent,['/mt_pickup 1 255']);self.assertEqual(self.single,[])
self.assertEqual(game.GameWindow.BINARY_ServerCommand_Run(gw,'MTPU1 done 3 3 0'),1)
self.assertEqual(game.GameWindow.BINARY_ServerCommand_Run(gw,'other'),7)
self.assertIn('拾取 3 件',w.status.text if hasattr(w.status,'text') else '')
w.Open();w.ToggleCategory(128);self.assertNotIn('【',w.categoryButtons[7].text);self.assertIn('【',w.categoryButtons[0].text)
w.ToggleEnabled();self.assertFalse(picker.enabled);self.assertFalse(w.categoryButtons[0].enabled)
game.GameWindow.PickUpItem(gw);self.assertEqual(self.single,[1])
self.assertEqual(Path('mt_pickup.cfg').read_text(),'0 127')
self.time+=1;w.ToggleEnabled();game.GameWindow.PickUpItem(gw);self.time+=3.1;w.OnUpdate()
self.assertTrue(picker.unsupported);self.assertIn('单个拾取',self.chat[-1])
game.GameWindow.PickUpItem(gw);self.assertEqual(self.single,[1,1])
game.GameWindow.Close(gw);self.assertIsNone(self.ns['g_window']);self.assertIsNone(self.ns['g_entry'])
def test_server_constants_match(self):
server=ROOT.parent/'metin2-server/src/server/game/src/port_pickup.h'
if not server.exists():self.skipTest('server checkout not installed')
text=server.read_text(encoding='latin1')
bits=dict((name,int(v)) for name,v in re.findall(r'PORT_PICKUP_([A-Z]+)=(\d+)',text))
self.assertEqual(bits.pop('ALL'),self.ns['ALL'])
self.assertEqual(sorted(bits.values()),[bit for bit,name in self.ns['CATEGORIES']])
self.assertTrue(set(re.findall(r'MTPU1 error ([a-z_]+)"',text))<=set(self.ns['ERRORS']))
self.assertIn('kPortPickupGapMs=500',text);self.assertEqual(self.ns['SEND_GAP'],.5)
if __name__=='__main__':unittest.main()
+21
View File
@@ -110,6 +110,27 @@ class ServiceTests(unittest.TestCase):
self.assertEqual(self.replies[-1][1],expected) self.assertEqual(self.replies[-1][1],expected)
if expected is None:self.assertEqual(self.replies[-1][0]['rows'][0][1],1) if expected is None:self.assertEqual(self.replies[-1][0]['rows'][0][1],1)
def test_boss_rows_signed_positions_and_unsupported_on_old_cap(self):
self.s.mask=511
rid=self.request('bosses',0)
self.assertEqual(self.sent[-1],'/mt_features 1 %d bosses'%rid)
self.s.Receive('MTF1 begin %d bosses 0 0 2 0 1700000000'%rid)
self.s.Receive('MTF1 boss %d 0 2307 68 51200 -300 1 1 1 1700000900 9000'%rid)
self.s.Receive('MTF1 boss %d 1 2191 125 0 0 99 0 1 0 1800'%rid)
self.s.Receive('MTF1 end %d 2'%rid)
self.assertIsNone(self.replies[-1][1])
self.assertEqual(self.replies[-1][0]['rows'],[[2307,68,51200,-300,1,1,1,1700000900,9000],[2191,125,0,0,99,0,1,0,1800]])
for bad in ('2307 68 0 0 1 2 1 0 9000','0 68 0 0 1 0 1 0 9000','2307 68 0 0 1 0 1 0 0','2307 68 0 0 256 0 1 0 9000','2307 68 0 0 1 0 1 0'):
rid=self.request('bosses',0)
self.s.Receive('MTF1 begin %d bosses 0 0 1 0 1700000000'%rid)
self.s.Receive('MTF1 boss %d 0 %s'%(rid,bad));self.s.Receive('MTF1 end %d 1'%rid)
self.assertEqual(self.replies[-1],(None,'bad_reply'),bad)
self.assertEqual(self.s.Request('bosses',1,0,lambda d,e:self.replies.append((d,e))),0)
self.assertEqual(self.replies[-1],(None,'invalid'))
self.s.mask=255 # a server deployed before boss tracking
self.s.Request('bosses',0,0,lambda d,e:self.replies.append((d,e)));self.time+=1;self.s.Tick()
self.assertEqual(self.replies[-1],(None,'unsupported'))
def test_future_capability_bits_do_not_disable_known_features(self): def test_future_capability_bits_do_not_disable_known_features(self):
self.s.Request('stats',0,0,lambda d,e:None) self.s.Request('stats',0,0,lambda d,e:None)
self.time+=1;self.s.Tick();rid=self.s.pending['id'] self.time+=1;self.s.Tick();rid=self.s.pending['id']
+183
View File
@@ -0,0 +1,183 @@
import re
import sys
import types
import unittest
from pathlib import Path
ROOT=Path(__file__).resolve().parents[2]
def script(name):return (ROOT/'src/platform/ScriptLib'/name).read_text().split('R"PY(',1)[1].rsplit(')PY";',1)[0]
class Widget(object):
def __init__(self,*a,**k):self.shown=False;self.text='';self.pos=(0,0);self.size=(0,0)
def __getattr__(self,name):return lambda *a,**k:None
def Show(self):self.shown=True
def Hide(self):self.shown=False
def IsShow(self):return self.shown
def SetText(self,text):self.text=text
def SetPosition(self,x,y):self.pos=(x,y)
def GetLocalPosition(self):return self.pos
def GetGlobalPosition(self):return self.pos
def SetSize(self,w,h):self.size=(w,h)
def GetWidth(self):return self.size[0]
def GetHeight(self):return self.size[1]
class Action(Widget):
def __init__(self,parent,x,y,width,text,event):
Widget.__init__(self);self.pos=(x,y);self.event=event;self.enabled=True;self.label=Widget();self.text=text;self.shown=True
def SetEnabled(self,enabled):self.enabled=enabled
class SwitchbotTests(unittest.TestCase):
def setUp(self):
self.time=1.;self.sent=[];self.chat=[];self.events=[]
self.inventory={10:(11209,1,[(3,2),(15,1)]),20:(71084,7,[]),21:(71084,3,[]),30:(27001,5,[])}
protos={11209:(2,0),71084:(3,18),27001:(3,0)}
mods={n:types.ModuleType(n) for n in ('app','chat','game','grp','item','net','player','ui','uiToolTip','wndMgr','mt_biolog','mt_wiki')}
mods['app'].GetTime=lambda:self.time
mods['chat'].CHAT_TYPE_INFO=1;mods['chat'].AppendChat=lambda t,m:self.chat.append(m)
mods['net'].SendChatPacket=self.sent.append
mods['game'].GameWindow=type('GameWindow',(),dict(Open=lambda s:None,Close=lambda s:None,BINARY_ServerCommand_Run=lambda s,line:7))
grp=mods['grp'];grp.SetColor=grp.RenderBar=grp.RenderBox=lambda *a:None
it=mods['item'];it.ITEM_TYPE_WEAPON=1;it.ITEM_TYPE_ARMOR=2;it.ITEM_TYPE_USE=3;self.selected=None
it.SelectItem=lambda v:setattr(self,'selected',v);it.GetItemType=lambda:protos[self.selected][0];it.GetItemSubType=lambda:protos[self.selected][1]
it.GetItemName=lambda:'N%d'%self.selected
pl=mods['player'];pl.INVENTORY=1;pl.INVENTORY_PAGE_SIZE=45;pl.INVENTORY_PAGE_COUNT=5
pl.GetItemIndex=lambda w,c:self.inventory.get(c,(0,))[0];pl.GetItemCount=lambda w,c:self.inventory[c][1]
pl.GetItemAttribute=lambda w,c,i:(self.inventory[c][2]+[(0,0)]*5)[i]
mods['ui'].Window=Widget
mods['uiToolTip'].ItemToolTip=type('ItemToolTip',(),dict(AFFECT_DICT={3:lambda v:'STR+%d'%v}))
mods['wndMgr'].GetScreenWidth=lambda:800;mods['wndMgr'].GetScreenHeight=lambda:600
mods['mt_biolog'].Action=Action;mods['mt_biolog'].Text=lambda p,x,y,t='',c=0:Widget();mods['mt_biolog'].L=lambda t:t if isinstance(t,str) else t.decode('utf-8')
mods['mt_wiki'].U=lambda t:t if isinstance(t,str) else t.decode('utf-8');mods['mt_wiki'].B=lambda t,limit=0:t
self.previous={n:sys.modules.get(n) for n in mods}
sys.modules.update(mods)
self.ns={'__name__':'mt_switchbot'};exec(script('SwitchbotScript.inc'),self.ns)
self.bot=self.ns['Bot'](self.sent.append,lambda:self.time,self.events.append)
def tearDown(self):
for name,value in self.previous.items():
if value is None:sys.modules.pop(name,None)
else:sys.modules[name]=value
def advance(self,seconds=.4):self.time+=seconds;self.bot.Tick()
def load(self,bot,cell=10):
for line in ('MTSB1 attrs %d 11209 3'%cell,'MTSB1 attr 0 3 12','MTSB1 attr 1 63 6','MTSB1 attr 2 71 30','MTSB1 attrs_end %d 3'%cell):bot.Receive(line)
def test_commands_are_paced_and_attrs_requests_collapse(self):
self.bot.RequestAttrs(10);self.bot.RequestAttrs(11);self.bot.RequestAttrs(12);self.bot.Status()
self.assertEqual(self.sent,['/mt_switchbot 1 attrs 10'])
self.load(self.bot);self.advance()
self.assertEqual(self.sent[-1],'/mt_switchbot 1 attrs 12')
self.bot.Receive('MTSB1 error attrs no_attr');self.advance()
self.assertEqual(self.sent[-1],'/mt_switchbot 1 status')
self.assertEqual(len(self.sent),3)
def test_atomic_attr_list_and_rejected_partials(self):
self.load(self.bot)
self.assertEqual(self.bot.allowed[10]['rows'],[(3,12),(63,6),(71,30)])
for bad in (['MTSB1 attrs 11 1 2','MTSB1 attr 0 3 12','MTSB1 attrs_end 11 2'],
['MTSB1 attrs 11 1 1','MTSB1 attr 1 3 12','MTSB1 attrs_end 11 1'],
['MTSB1 attrs 11 1 1','MTSB1 attr 0 3 -1','MTSB1 attrs_end 11 1'],
['MTSB1 attrs_end 11 0']):
for line in bad:self.assertTrue(self.bot.Receive(line))
self.assertNotIn(11,self.bot.allowed)
self.assertFalse(self.bot.Receive('MTF1 cap 1 1 127 0'))
def test_start_validates_against_server_list_and_builds_command(self):
self.load(self.bot)
self.assertEqual(self.bot.Start(10,71084,100,[[(3,13)],[]]),'target')
self.assertEqual(self.bot.Start(10,71084,100,[[(1,1)],[]]),'target')
self.assertEqual(self.bot.Start(10,71084,100,[[(3,1),(3,2)],[]]),'invalid')
self.assertEqual(self.bot.Start(10,71084,1001,[[(3,1)],[]]),'invalid')
self.assertEqual(self.bot.Start(10,71084,100,[[],[]]),'invalid')
self.assertIsNone(self.bot.Start(10,71084,100,[[(3,8),(63,6)],[(71,30)]]))
self.advance()
self.assertEqual(self.sent[-1],'/mt_switchbot 1 start 10 71084 100 2 3 8 63 6 1 71 30')
self.bot.Receive('MTSB1 error start running')
self.assertIsNone(self.bot.Start(10,71084,5,[[],[(71,1)]]));self.advance()
self.assertEqual(self.sent[-1],'/mt_switchbot 1 start 10 71084 5 1 71 1') # empty first alternative skipped
def test_state_errors_and_timeout(self):
self.bot.Receive('MTSB1 state 1 10 11209 3 100 71084 4 running')
self.assertTrue(self.bot.Running());self.assertEqual(self.bot.state['scrolls'],4)
self.bot.Receive('MTSB1 state 0 10 11209 4 100 71084 3 matched')
self.assertFalse(self.bot.Running());self.assertEqual(self.bot.state['reason'],'matched')
self.bot.Receive('MTSB1 state 0 10 11209 4 100 71084 3 exploded')
self.assertEqual(self.bot.state['reason'],'matched') # unknown reason ignored
self.bot.Receive('MTSB1 error start busy');self.assertEqual(self.bot.error,'busy')
self.bot.Status();self.advance(4.1);self.advance()
self.assertEqual(self.bot.error,'unsupported');self.assertTrue(self.bot.unsupported)
def test_server_constants_match(self):
server=ROOT.parent/'metin2-server/src/server/game/src/port_switchbot.h'
if not server.exists():self.skipTest('server checkout not installed')
text=server.read_text(encoding='latin1')
reasons=set(re.findall(r'return "([a-z_]+)"',text))|{'running','stopped','idle'}
errors=set(re.findall(r'error [a-z%]+ ([a-z_]+)"',text))|{'invalid','rate'}
lock_errors={'slot','max','db'}
self.assertTrue(reasons-{'invalid','running','item','equipped','no_attr','scroll','target','busy'}-lock_errors<=set(self.ns['REASONS']))
self.assertTrue(lock_errors<=set(self.ns['ERRORS']))
self.assertTrue(errors<=set(self.ns['ERRORS']))
self.assertIn('kPortSwitchLimit=1000',text);self.assertEqual(max(self.ns['LIMITS']),1000)
self.assertEqual(self.ns['MAX_TARGETS'],5)
def test_lock_protocol_and_buttons(self):
self.bot.Lock(10,0);self.assertEqual(self.sent,[]) # no lock line yet: old server, no request
self.load(self.bot);self.bot.Receive('MTSB1 lock 10 11209 2')
self.assertEqual(self.bot.LockMask(10,11209),2);self.assertIsNone(self.bot.LockMask(10,11210))
self.bot.Lock(10,5);self.bot.Lock(10,0);self.advance()
self.assertEqual(self.sent[-1],'/mt_switchbot 1 lock 10 0')
self.bot.Receive('MTSB1 lock 10 11209 3');self.assertIsNone(self.bot.waiting);self.assertEqual(self.bot.LockMask(10,11209),3)
self.bot.Lock(10,1);self.advance();self.bot.Receive('MTSB1 error lock max');self.assertEqual(self.bot.error,'max')
for bad in ('MTSB1 lock 10 11209','MTSB1 lock 10 11209 32'):self.bot.Receive(bad)
self.assertEqual(self.bot.LockMask(10,11209),3)
# Window: one button per filled slot, hidden while picking, locked attributes marked.
game=sys.modules['game'];gw=game.GameWindow();gw.interface=types.SimpleNamespace(wndMiniMap=Widget())
game.GameWindow.Open(gw);w=self.ns['g_window'];w.Open()
self.assertFalse(any(b.shown for b in w.lockButtons))
self.load(w.bot);w.bot.Receive('MTSB1 lock 10 11209 2')
self.assertEqual([b.shown for b in w.lockButtons],[True,True,False,False,False])
self.assertEqual([b.text for b in w.lockButtons[:2]],['锁1','【锁2】']);self.assertIn('[锁]',w.current.text.split(' / ')[1])
self.assertIn('保持不变',w.status.text)
self.time+=.5;w.OnUpdate();w.bot.Receive('MTSB1 state 0 0 0 0 0 0 0 idle') # answers the status request
sent=len(self.sent);w.lockButtons[0].event();self.time+=.5;w.OnUpdate()
self.assertEqual(self.sent[sent:],['/mt_switchbot 1 lock 10 0'])
w.TogglePick();self.assertFalse(any(b.shown for b in w.lockButtons));w.TogglePick()
w.bot.Receive('MTSB1 state 1 10 11209 0 100 71084 9 running');self.assertFalse(w.lockButtons[0].enabled)
sent=len(self.sent);w.lockButtons[0].event();self.time+=.5;w.OnUpdate()
self.assertNotIn('/mt_switchbot 1 lock 10 0',self.sent[sent:])
game.GameWindow.Close(gw)
def test_window_scan_pick_start_and_notify(self):
game=sys.modules['game'];window_type=game.GameWindow
gw=window_type();gw.interface=types.SimpleNamespace(wndMiniMap=Widget())
game.GameWindow.Open(gw);w=self.ns['g_window'];w.Open()
self.assertEqual(w.items,[(10,11209)]);self.assertEqual(w.scrolls,[(71084,10)])
self.assertEqual(self.sent,['/mt_switchbot 1 attrs 10']) # the status request waits for this reply
self.load(w.bot);self.time+=.5;w.OnUpdate()
self.assertEqual(self.sent[-1],'/mt_switchbot 1 status')
self.assertEqual(game.GameWindow.BINARY_ServerCommand_Run(gw,'MTSB1 state 0 0 0 0 0 0 0 idle'),1)
self.assertEqual(game.GameWindow.BINARY_ServerCommand_Run(gw,'other'),7)
w.TogglePick();w.Pick(0)
self.assertEqual(w.alternatives[0],[[3,12]])
w.Adjust(0,-1);self.assertEqual(w.alternatives[0][0][1],10);w.Adjust(0,1);w.Adjust(0,1);self.assertEqual(w.alternatives[0][0][1],12)
w.Start();self.time+=.5;w.OnUpdate()
self.assertEqual(self.sent[-1],'/mt_switchbot 1 start 10 71084 100 1 3 12')
w.bot.Receive('MTSB1 state 1 10 11209 1 100 71084 9 running');self.assertFalse(w.startButton.enabled)
self.inventory[40]=self.inventory.pop(10);sent=len(self.sent) # moved while running: follow the server's cell
w.bot.Receive('MTSB1 state 1 40 11209 2 100 71084 8 running');w.Scan()
self.assertEqual(w.Selected(),(40,11209));self.assertEqual(w.alternatives[0],[[3,12]])
self.assertEqual(w.Allowed(),[(3,12),(63,6),(71,30)]);self.time+=.5;w.OnUpdate();self.assertEqual(len(self.sent),sent)
w.bot.Receive('MTSB1 state 0 40 11209 2 100 71084 8 stopped')
self.inventory[5]=self.inventory.pop(40);w.Scan();self.assertEqual(w.Selected(),(5,11209)) # moved while idle: same vnum
self.inventory[10]=self.inventory.pop(5);w.Scan()
w.Hide();w.bot.Receive('MTSB1 state 0 10 11209 2 100 71084 8 matched')
self.assertTrue(w.IsShow());self.assertIn('已获得目标属性',self.chat[-1])
game.GameWindow.Close(gw);self.assertIsNone(self.ns['g_window'])
if __name__=='__main__':unittest.main()