From a28393b16b4471c7e3d73ae6fb9bb6488f5a37b5 Mon Sep 17 00:00:00 2001 From: shenlei Date: Fri, 16 Oct 2026 20:26:06 +0900 Subject: [PATCH] =?UTF-8?q?Port=20the=20AVA2=20switchbot=20(=E8=87=AA?= =?UTF-8?q?=E5=8A=A8=E6=B4=97=E7=BB=83)=201:1?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit AVA2 new_switchbot ported as port_switchbot.{h,cpp}: SWITCHBOT item window (7), CG/GC 171 and GG 31 with AVA2 subheaders and field order, pack(1) structs pinned by static_assert, 0.1 s roll, P2P hand-over on warp, boot ALTER of player.item.window. Switchers come from the inventory; current checks and ItemLog are kept. Clients sending "mt20261016" or newer as the version timestamp get the switchbot; older clients are left alone. The v1 /mt_switchbot chat command, its lock verb and query capability bit 64 are removed (cap mask 1023 -> 959). Co-Authored-By: Claude Opus 5.5 --- docs/FEATURE-ATTR-LOCK.md | 15 +- docs/FEATURE-AVA2-UNLOCK.md | 6 +- docs/FEATURE-CHEST.md | 2 +- docs/FEATURE-PICKUP.md | 2 +- docs/FEATURE-QUERY-PROTOCOL.md | 2 +- docs/FEATURE-SWITCHBOT.md | 126 ++-- src/server/common/length.h | 23 + src/server/common/tables.h | 46 ++ src/server/db/src/ClientManagerPlayer.cpp | 10 +- src/server/game/src/Makefile | 2 +- src/server/game/src/char.cpp | 7 + src/server/game/src/char.h | 7 +- src/server/game/src/char_item.cpp | 114 +++ src/server/game/src/cmd.cpp | 2 - src/server/game/src/cmd_general.cpp | 1 - src/server/game/src/exchange.cpp | 3 + src/server/game/src/input.h | 2 + src/server/game/src/input_db.cpp | 9 + src/server/game/src/input_login.cpp | 2 + src/server/game/src/input_main.cpp | 55 ++ src/server/game/src/input_p2p.cpp | 16 + src/server/game/src/item.cpp | 19 + src/server/game/src/item.h | 3 + src/server/game/src/item_attribute.cpp | 7 + src/server/game/src/main.cpp | 6 + src/server/game/src/packet.h | 55 ++ src/server/game/src/packet_info.cpp | 2 + src/server/game/src/port_features.h | 2 +- src/server/game/src/port_pendant.cpp | 50 +- src/server/game/src/port_rings.cpp | 12 +- src/server/game/src/port_switchbot.cpp | 807 ++++++++++++++++++++++ src/server/game/src/port_switchbot.h | 295 ++------ tests/features/test_attr_lock.py | 2 +- tests/features/test_bosses.py | 2 +- tests/features/test_cmd_prefix.py | 2 +- tests/features/test_costume_attr.py | 4 +- tests/features/test_pendant.py | 7 +- tests/features/test_queries.py | 2 +- tests/features/test_switchbot.py | 311 +++------ 39 files changed, 1485 insertions(+), 555 deletions(-) create mode 100644 src/server/game/src/port_switchbot.cpp diff --git a/docs/FEATURE-ATTR-LOCK.md b/docs/FEATURE-ATTR-LOCK.md index 46bcd663..e8a615ec 100644 --- a/docs/FEATURE-ATTR-LOCK.md +++ b/docs/FEATURE-ATTR-LOCK.md @@ -1,6 +1,6 @@ # PORT attribute lock -AVA2 `ENABLE_LOCK_ATTR`, rebuilt for this server's item layout. Up to two of the five normal attribute slots keep their type and value when the item is rerolled. Source: `src/server/game/src/port_attr_lock.{h,cpp}`, `CItem::ChangeAttribute` / `CopyAttributeTo` (item_attribute.cpp), the cache fields in item.h/item.cpp, the boot hook in main.cpp, and the `lock` verb of `mt_switchbot` (port_switchbot.h). +AVA2 `ENABLE_LOCK_ATTR`, rebuilt for this server's item layout. Up to two of the five normal attribute slots keep their type and value when the item is rerolled. Source: `src/server/game/src/port_attr_lock.{h,cpp}`, `CItem::ChangeAttribute` / `CopyAttributeTo` (item_attribute.cpp), the cache fields in item.h/item.cpp, and the boot hook in main.cpp. The `lock` verb of the v1 `mt_switchbot` command was removed with the AVA2 switchbot port (FEATURE-SWITCHBOT.md). Locks are now set only by using 50348 (lock) / 50349 (unlock) on the item. `UseItemEx` passes the material to `PortAttrLockUse`, which reads the 1-based slot from the material's socket 0 and consumes one material on success. ## Storage @@ -24,7 +24,6 @@ CREATE TABLE IF NOT EXISTS mt_item_attr_lock (item_id INT UNSIGNED NOT NULL PRIM - Only the five normal slots can be locked; the rare slots 5/6 are not affected. The item must sit in the inventory, not be equipped or in an exchange, not be a costume, and have an attribute set. The slot must hold an attribute. - At most 2 lock groups, and at least one filled slot must stay unlocked. On items with an addon type (`sAddonType`, weapons whose slots 0/1 are the skill / normal hit bonus pair), slots 0 and 1 lock and unlock together and count as one group. -- The bot's own item cannot be locked or unlocked while the bot is rolling it (`running`). - Locking is free. AVA2 consumes 50348/50349 per lock or unlock; those vnums do not exist in 203 `item_proto`. - `CItem::ChangeAttribute` (scroll rerolls, the switchbot, the GM command): 1. take the effective mask: stored mask ∩ filled slots, with the addon pair kept whole; @@ -36,15 +35,9 @@ CREATE TABLE IF NOT EXISTS mt_item_attr_lock (item_id INT UNSIGNED NOT NULL PRIM With no lock, the effective mask is 0 and the sequence equals the original. The attribute count is kept, and the rare slots are untouched. - Adding an attribute (71085) and rare-attribute scrolls do not look at the lock. -## Protocol (part of mt_switchbot v1) +## Protocol -``` -/mt_switchbot 1 lock CELL SLOT toggle the lock on normal slot SLOT (0..4) -MTSB1 lock CELL VNUM MASK effective mask; also sent after every attrs_end -MTSB1 error lock CODE item equipped no_attr busy running slot max db rate invalid -``` - -`slot` means out of range or empty. `max` means a third group, or every filled slot locked. `db` means the write failed. Older servers never send a `lock` line, so the client shows no lock buttons there. +No dedicated packet. The v1 `/mt_switchbot 1 lock CELL SLOT` / `MTSB1 lock` lines were removed together with that command. What remains is the item-use path above. AVA2's UI for picking the slot and showing the lock in the tooltip is still open (metin2-client docs/AVA2-PARITY-PLAN.md). ## Verification @@ -58,7 +51,7 @@ MTSB1 error lock CODE item equipped no_attr busy running slot max - there is no DB lookup when there are no attributes; - every toggle, effective-mask and group-count rule holds. - It also checks the boot hook, the Makefile, the cache initialisation and that `CopyAttributeTo` copies the lock. -- `tests/features/test_switchbot.py` covers the `lock` verb (toggle, `slot`, `max`, `db`, `running`, `no_attr`, `item`, `invalid`, the addon pair) and the lock line after `attrs_end`. +- `tests/features/test_switchbot.py` checks that the v1 command (and with it the `lock` verb) is gone. - FreeBSD: full rebuild of game in `/root/metin2-features-dev` (log `attrlock-build.log`; `item.h` changed, so every .cpp was touched). - Live on 2026-10-15, channel-5 test core (13040) with the isolated binary, macOS client, [SA]Admin, armour 11209 (item 20000178, 5 attributes), scroll 71084: - the first boot created the table; diff --git a/docs/FEATURE-AVA2-UNLOCK.md b/docs/FEATURE-AVA2-UNLOCK.md index 47e6d844..a166a475 100644 --- a/docs/FEATURE-AVA2-UNLOCK.md +++ b/docs/FEATURE-AVA2-UNLOCK.md @@ -94,7 +94,7 @@ AVA2's `ENABLE_SPECIAL_COSTUME_ATTR`, in `game/src/port_costume_attr.cpp`. The i - at most 3 attributes (`full`); - no duplicate apply (`has`). - Then `AddAttribute`, consume one, `ItemLog COSTUME_ENCHANT`, `done`. -- The switchbot does not accept enchants as scrolls, on either the server (`PortSwitchScroll`) or the client. +- The switchbot never uses enchants: it only looks up the switcher vnums in FEATURE-SWITCHBOT.md. - Client `mt_costume_attr` (`CostumeAttrScript.inc`): - marks matching costumes as usable drop targets (the 40250 inventory already sends every `USE_CHANGE_ATTRIBUTE` drop); - adds the attribute and targets to the enchant tooltip; @@ -113,7 +113,7 @@ AVA2's `ITEM_TALISMAN_EQUIPMENT` + `ELEMENT_NEW_BONUSES`, in `game/src/port_pend - Damage (battle.cpp `CalcAttBonus`): against a monster with `RACE_FLAG_ATT_`, attack +point %, so a +200 talisman triples the attack on those monsters (×(1+200/100)), which is AVA2's own balance. Each flag is its own `if`, as on AVA2. AVA2 leaves out ICE; we include it, since 203 has 83 ice monsters and an ice talisman chain. - Attributes: - The pool is AVA2's item_attr pendant column (20 rows, levels 1–5), kept in a table in `port_pendant.cpp` instead of a new item_attr column (that would change the db boot packet). - - `GetAttributeSetIndex` stays −1. So talismans drop without attributes, and the 40250 switchers, the switchbot and the attribute lock refuse them. + - `GetAttributeSetIndex` stays −1. So talismans drop without attributes, and the 40250 switchers and the attribute lock refuse them. The switchbot rolls them with 71302 only (pseudo attribute set 9). - 71302 rerolls all attributes (needs at least one; levels 0/10/40/35/15 %). 71301 adds one up to 5, always succeeding (levels 40/50/10 %). No duplicates. - **Deviation:** AVA2's 53996 / 53997 are generic switcher / adder items, a free 40250 gear reroll. Here they work like 71302 / 71301, as their zh names (护符附魔é�“å…· / 护符加æŒ�é�“å…·) say. - Not while worn (`equipped`), like the 40250 switcher. Any other attribute item dropped on a talisman, or a talisman item dropped on anything else, gets `target`. @@ -133,7 +133,7 @@ AVA2's `ENABLE_NEW_RINGS`, in `game/src/port_rings.cpp`. - Attributes: - The pool is AVA2's `item_attr_rings` (20 rows, levels 1–5), kept as a table in `port_rings.cpp`. `GetAttributeSetIndex` stays −1, and `PutAttributeWithLevel` branches to the ring pool. - The 40250 switchers and adders (`USE_CHANGE_ATTRIBUTE`, `USE_ADD_ATTRIBUTE`, `USE_ADD_ATTRIBUTE2`) accept rings, with the usual not-while-worn rule. 71151 / 71152 (weapon / armor only) refuse them, by design. - - The switchbot and the rare (6th / 7th) attributes skip rings. AVA2's `item_attr_rare_rings` is not ported. + - The switchbot rolls rings from this pool (pseudo attribute set 8). The rare (6th / 7th) attributes skip rings. AVA2's `item_attr_rare_rings` is not ported. - Rings drop without attributes: `AlterToMagicItem` only handles weapons and armor. - Client: `ITEM_TYPE_RINGS`, `c_Equipment_Rings1/2` (253 / 254), and `mt_rings` (`RingsScript.inc`). That module adds the two slots beside the shoes, the accessory tooltip (applies, attributes, jewel sockets) and the drop targets for drills, jewels, switchers and adders. diff --git a/docs/FEATURE-CHEST.md b/docs/FEATURE-CHEST.md index 8ebcf2fe..2f4af025 100644 --- a/docs/FEATURE-CHEST.md +++ b/docs/FEATURE-CHEST.md @@ -1,6 +1,6 @@ # PORT batch chest opening, v1 -Date: 2026-10-15. AVA2-style batch opening of gift boxes (reference: AVA2 `ENABLE_MULTI_CHEST`, `/chest_drop`, `CHARACTER::OpenChest`). Source: `src/server/game/src/port_chest.h` (header-only, included from `cmd_general.cpp`), command `mt_chest` (cmd.cpp). It reuses the quiet-INFO hook (`m_portQuietInfo` / `m_portLastInfo`) added for the switchbot. No packet header, no DB schema, no char.h/item.h change. +Date: 2026-10-15. AVA2-style batch opening of gift boxes (reference: AVA2 `ENABLE_MULTI_CHEST`, `/chest_drop`, `CHARACTER::OpenChest`). Source: `src/server/game/src/port_chest.h` (header-only, included from `cmd_general.cpp`), command `mt_chest` (cmd.cpp). It reuses the quiet-INFO hook (`m_portQuietInfo` / `m_portLastInfo`) (char.cpp; first added for the v1 switchbot, which no longer uses it). No packet header, no DB schema, no char.h/item.h change. AVA2 rewrote the drop loop (`GiveItemFromSpecialItemGroupNew`, `AutoGiveItemChest`, cap 1000). That rewrite is not ported. Here every box goes through the original `CHARACTER::UseItem` → `UseItemEx` `ITEM_GIFTBOX` path, one box at a time, so the original checks, the `special_item_group` roll, gold/exp, `ItemLog` and consumption stay exactly as they are. diff --git a/docs/FEATURE-PICKUP.md b/docs/FEATURE-PICKUP.md index 58c835c9..79d81327 100644 --- a/docs/FEATURE-PICKUP.md +++ b/docs/FEATURE-PICKUP.md @@ -1,6 +1,6 @@ # PORT batch pickup, v1 -AVA2-style batch pickup (reference: AVA2 `do_pickup_all`). One command picks up every ground item the character owns within the normal pickup distance, filtered by category. Source: `src/server/game/src/port_pickup.h`, command `mt_pickup` (cmd.cpp), throttle field `m_portPickupLastCommand` in char.h. It reuses the quiet-INFO hook (`m_portQuietInfo`) added for the switchbot. No packet header, no DB schema, no affect. AVA2's `HEADER_CG_ITEMS_PICKUP` packet and its premium automatic pickup (`AFFECT_AUTO_PICK_UP`, item 70002) are not ported. +AVA2-style batch pickup (reference: AVA2 `do_pickup_all`). One command picks up every ground item the character owns within the normal pickup distance, filtered by category. Source: `src/server/game/src/port_pickup.h`, command `mt_pickup` (cmd.cpp), throttle field `m_portPickupLastCommand` in char.h. It reuses the quiet-INFO hook (`m_portQuietInfo`) (char.cpp; first added for the v1 switchbot, which no longer uses it). No packet header, no DB schema, no affect. AVA2's `HEADER_CG_ITEMS_PICKUP` packet and its premium automatic pickup (`AFFECT_AUTO_PICK_UP`, item 70002) are not ported. ## Rules diff --git a/docs/FEATURE-QUERY-PROTOCOL.md b/docs/FEATURE-QUERY-PROTOCOL.md index d53deafd..5507df78 100644 --- a/docs/FEATURE-QUERY-PROTOCOL.md +++ b/docs/FEATURE-QUERY-PROTOCOL.md @@ -31,7 +31,7 @@ MTF1 end REQUEST ROW_COUNT MTF1 error REQUEST ERROR ``` -MASK: 1 mob drops, 2 chest preview, 4 own stats, 8 item sources, 16 dungeon snapshots, 32 scheduled calendar, 64 switchbot (separate `/mt_switchbot` / `MTSB1` protocol, see FEATURE-SWITCHBOT.md), 256 world bosses (see FEATURE-BOSS-TRACK.md). The current mask is 511. Unknown capability bits are ignored; unknown versions are rejected. Capability advertises the query implementation; missing quest/config can still return unsupported/schedule_unavailable. The client negotiates before business queries; old servers time out to unsupported, not an empty result. +MASK: 1 mob drops, 2 chest preview, 4 own stats, 8 item sources, 16 dungeon snapshots, 32 scheduled calendar, 64 was the v1 switchbot (`/mt_switchbot` / `MTSB1`) and is no longer advertised, because the AVA2 switchbot uses its own packets (FEATURE-SWITCHBOT.md), 256 world bosses (see FEATURE-BOSS-TRACK.md). The current mask is 959. Unknown capability bits are ignored; unknown versions are rejected. Capability advertises the query implementation; missing quest/config can still return unsupported/schedule_unavailable. The client negotiates before business queries; old servers time out to unsupported, not an empty result. Each drop/chest/source page contains at most 8 rows, with consecutive absolute indices. TOTAL is capped at 4096; stats are one complete bounded snapshot (currently the named keys in kPortStats, less than 128). Client commits only a complete, matching begin/rows/end sequence. Unknown/stale request IDs cannot overwrite the current selection. Each line is bounded below 512 bytes; rows contain IDs and values, not server-provided script/names/markup. diff --git a/docs/FEATURE-SWITCHBOT.md b/docs/FEATURE-SWITCHBOT.md index b4a1be20..67036114 100644 --- a/docs/FEATURE-SWITCHBOT.md +++ b/docs/FEATURE-SWITCHBOT.md @@ -1,93 +1,63 @@ -# PORT switchbot (automatic attribute change), v1 +# PORT switchbot (自动洗练), AVA2 port -AVA2-style automatic rerolling (reference: AVA2 `new_switchbot.cpp` / `uiswitchbot.py`), rebuilt so that the server stays authoritative and the existing reroll path is unchanged. Source: `src/server/game/src/port_switchbot.h`, command `mt_switchbot` (cmd.cpp), quiet-INFO hook in `CHARACTER::ChatPacket` (char.cpp), fields in char.h. No attribute lock, no DB schema, no packet header, no P2P transfer. +AVA2 `ENABLE_SWITCHBOT` ported 1:1 (reference: AVA2 `game/src/new_switchbot.{h,cpp}`, client `PythonSwitchbot.cpp` and `root/uiswitchbot.py`). Classes, API, packets, the window and the 0.1 s roll speed are AVA2's. It replaces the v1 `/mt_switchbot` chat protocol (`MTSB1`, query capability bit 64). That command and its lock verb are gone. -## Rules +Source: +- `src/server/game/src/port_switchbot.{h,cpp}`: `SwitchbotHelper`, `CSwitchbot`, `CSwitchbotManager`, `PortSwitchbotBoot`. +- `common/length.h`: `SWITCHBOT = 7` in `EWindows` (GROUND is now 8), `SWITCHBOT_SLOT_COUNT 6 / _REAL 5 / ALTERNATIVE_COUNT 2 / NORM_ATTR_NUM 5`, `TItemPos::IsSwitchbotPosition`. +- `common/tables.h`: the switchbot tables. -- Each roll calls the original `CHARACTER::UseItem(scroll cell, target cell)`. All checks, probabilities, the addon handling, `ItemLog CHANGE_ATTRIBUTE` and scroll consumption are the manual path's. That includes the 71151/76023 restriction (weapon/body, level limit <= 40) and the GM quest flag. A roll counts only when exactly one scroll of the chosen vnum was consumed. Otherwise the bot stops with `rejected` and resends the original INFO line once. -- The per-roll INFO lines (`属性已å�˜æ›´`) are held back while the bot calls UseItem (`m_portQuietInfo`); all other chat types pass through. -- Only `ITEM_USE / USE_CHANGE_ATTRIBUTE` scrolls are accepted. `USE_CHANGE_ATTRIBUTE2` has no handler in this server's UseItemEx. -- Target item: inventory cell, not costume, attribute set != -1, at least one attribute, not equipped or in an exchange. It is bound by item ID. -- One bot per character. One roll every 250 ms (`PASSES_PER_SEC(1)/4`). Limit 1..1000 rolls. -- Targets: up to 2 alternatives, each 1..5 distinct (apply, minimum). An alternative matches when every target is found among the 5 normal attribute slots with value >= minimum. Any matching alternative stops the bot (AVA2 CheckItem semantics). The bot also checks before it starts, so an item that already matches consumes nothing. -- Allowed targets are the applies the attribute table can roll for this item's set, excluding the item's base proto applies. The maximum is `lValues[min(maxLevelBySet,5)-1]`. Items with an addon type also allow skill damage 30 / normal hit 65, the item_addon bounds. -- Every tick re-checks the state and stops with a reason. This replaces AVA2's hooks into every move/trade path. - - Character gone, VID changed (logout or warp) or descriptor lost: the bot is erased silently. - - `busy`: dead, warping, `!CanHandleItem()`, exchange, own shop, shop, safebox or cube open. - - `item_gone`: the item is missing, has another owner, has left the inventory window or is equipped. - - `no_scroll`, `limit`, `matched`, `rejected`, `stopped`. -- No offline rolling. Rolls stop when the player leaves, and every completed roll has already been saved and logged by the original path. +## Window and items -## Protocol (CHAT_TYPE_COMMAND, version 1) +- Items placed in the `SWITCHBOT` window (cells 0..4) are kept in `m_pointsInstant.pSwitchbotItems` and saved with `window = 'SWITCHBOT'`. The db loads, saves and deletes that window with SAFEBOX and DRAGON_SOUL_INVENTORY (three queries in `ClientManagerPlayer.cpp`). +- At boot (game cores only), `PortSwitchbotBoot` adds `'SWITCHBOT'` to the `player.item.window` enum if it is missing. The deploy SQL carries the same ALTER. +- `MoveItem` only accepts `SwitchbotHelper::IsValidItem` items into the window. That is AVA2's list: weapons, rings, and armour (body, head, shield, wrist, shoes, necklace, earrings, talisman). Cell 5 is rejected. The move hooks send: + - `switchbot_error active` when the item is moved out of a running slot; + - `switchbot_error invalid` when the item is not valid for the switchbot. +- Drop, give, exchange and safebox refuse switchbot cells: the item has to go back to the inventory first. Shops sell only from the inventory. -Requests (250 ms per-character throttle; tokens <= 10 chars, <= 30 tokens): +## Rolling -``` -/mt_switchbot 1 attrs CELL -/mt_switchbot 1 start CELL SCROLL_VNUM LIMIT N1 (APPLY MIN)*N1 [N2 (APPLY MIN)*N2] -/mt_switchbot 1 stop -/mt_switchbot 1 status -/mt_switchbot 1 lock CELL SLOT (attribute lock, see FEATURE-ATTR-LOCK.md) -``` +- `CSwitchbot::SwitchItems` runs every 0.1 s (`c_fSpeed`). Each active slot takes one switcher per pass. +- A slot finishes when one configured alternative fully matches within the first 5 attributes (AVA2 `CheckItem`). An alternative that isn't configured counts as a match. +- Deviations from AVA2 (also listed at the top of `port_switchbot.cpp`): + - Cell 5 (AVA2's hidden switcher cell) is never used. Switchers come from the inventory, skipping stacks that are being exchanged, locked or sold in the player's shop. + - Which switcher is used follows the manual path: + - a talisman takes only 71302; + - a weapon or body armour with no level limit above 40 takes 71151 / 76023 first; + - everything else takes 71084, then 39028. + - A slot whose item has no attributes stops instead of rolling. + - Every roll is written to ItemLog as `SWITCHBOT`, with the item id as the hint. + - End and stop messages are server commands, which the client turns into localized text: + - `switchbot_end ` + - `switchbot_stop noattr ` + - `switchbot_stop nochanger ` -Replies: + The slot is 0-based. AVA2 sent the locale ids `864` / `865` with slot+1. + - Leaving the core deletes the table once it has been sent on. A logout that unregisters the last active slot also stops the event. + - The attribute list has two pseudo sets after `ATTRIBUTE_SET_MAX_NUM`: 8 = rings (`port_rings.cpp`) and 9 = talismans (`port_pendant.cpp`). +- Warp: `CHARACTER::WarpSet` sends the table over P2P (`HEADER_GG_SWITCHBOT 31`, `TPacketGGSwitchbot`) before `GC_WARP`. The target core keeps it, and `EnterGame` re-registers the slots whose item is still there and restarts the event. -``` -MTSB1 attrs CELL VNUM COUNT -MTSB1 attr INDEX APPLY MAX (COUNT rows, INDEX 0..COUNT-1) -MTSB1 attrs_end CELL COUNT -MTSB1 state ACTIVE CELL VNUM ROLLS LIMIT SCROLL SCROLLS REASON -MTSB1 lock CELL VNUM MASK (after every attrs_end, and as the reply to lock) -MTSB1 error VERB CODE -``` +## Protocol -`REASON` is one of `running matched limit no_scroll item_gone rejected busy stopped idle`. Error codes: +Header numbers, subheaders and field order are AVA2's. The structs are `pack(1)`, and their sizes are pinned with `static_assert` in `port_switchbot.cpp` and in the client (`Packet.h`, `PythonSwitchbot.h`). -| Code | Meaning | -| --- | --- | -| `rate` | throttled | -| `invalid` | malformed | -| `item` | no item in that cell | -| `equipped` | equipped or in an exchange | -| `no_attr` | the item cannot be rerolled | -| `scroll` | the scroll is missing or the wrong type | -| `target` | the apply is not allowed, above the maximum or a duplicate | -| `running` | this character already has a bot | -| `busy` | see the busy states above | +| Packet | Header | Layout | +| --- | --- | --- | +| CG | 171, dynamic | `BYTE header, int size, BYTE subheader, BYTE slot` (7) + `START`: `TSwitchbotAttributeAlternativeTable[2]` (15 each) / `STOP` | +| GC | 171, dynamic | same 7-byte head + `UPDATE`: `TSwitchbotTable` (220) / `UPDATE_ITEM`: `TSwitchbotUpdateItem` (40: slot, vnum, count, 3 sockets, 7 attributes) / `SEND_ATTRIBUTE_INFORMATION`: `TSwitchbottAttributeTable[n]` (9) | +| GG | 31 | `TPacketGGSwitchbot` (223) | -A state line is pushed after every roll and when the bot stops. When the reason is `item_gone`, CELL and VNUM are 0. +CG is registered in `packet_info.cpp` with `Set(..., true)` and GG with `Set(..., false)`. The 40250 base packets are unchanged. -Capability: the MTF1 cap mask advertises bit 64 (63 -> 127). Clients that don't know it ignore it, and the client also times out to "unsupported" against old servers. +**Version gate.** The new client sends `mt20261016` as the `CG_CLIENT_VERSION` timestamp, in place of `__TIMESTAMP__`. Before `EnterGame` sends anything, it checks `SwitchbotHelper::IsClientSupported`, which requires `mt` with date >= `PORT_SWITCHBOT_CLIENT_VERSION`. An older client gets no GC_SWITCHBOT packet. It can't fill the window either. The EU-branch client timestamp (`1215955205`) doesn't pass the gate. ## Verification -- `tests/features/test_switchbot.py` compiles the production header against stubs of the UseItem/ChatPacket contract. It covers the allowed list (proto exclusion, set filter, level cap, addon), validation, two alternatives, the already-matched start, quiet INFO, limit, `no_scroll`, `rejected` (INFO resent once), `item_gone`, `busy`, stop/status/idle and silent erase on a VID change. -- `tests/features/test_queries.py` was updated for cap mask 127. -- FreeBSD build of the whole game target on 203 in `/root/metin2-features-dev` (BINDIR=GAMEDIR=`/root/metin2-features-dev/bin`), log `/root/metin2-features-dev/switchbot-build.log`, with no warnings from the new code. The live `/usr/metin2` binary was not replaced and no service was restarted. -- Live test on 2026-10-15. 203 ran an extra core (`/usr/metin2/server/channel5/first`: CHANNEL 5, PORT 13040, P2P 14040, MAP_ALLOW 1 21 41) with its `game` symlinked to the isolated binary. The macOS native client (`--live-server 192.168.21.203:11000:13040`) drove [SA]Admin, sword 279, scroll 71084: - - `attrs` returned 14 rows for the sword (18 for armor 12019), received complete. - - limit 10 → `limit` after 10 rolls. State lines arrived about every 0.24 s (about 4 rolls/s); the scroll count fell 200 → 190. - - Two alternatives with minimum 1 → `matched` after 18 rolls. - - Start on an item that already matches → `matched` with 0 rolls and no scroll used. - - Moving the item 33 → 90 mid-run → the run continued, the state line reported cell 90, and `stop` → `stopped`. - - Client exit mid-run (8 rolls) → `log.log` stopped at the exit second. The CHANGE_ATTRIBUTE row count (72 = 10+18+12+12+12+8) stayed the same 20 s later. - - Opening a private shop mid-run → `busy` about 1 s after the shop opened (6 rolls). The character needs a shop bundle (50200 or 71049); without one `OpenMyShop` returns before setting `m_pkMyShop`, so no shop opens and the bot correctly keeps rolling. - - 76014 with 6 scrolls and limit 10 → `no_scroll` after 6 rolls. - - 71151 on the level-90 sword (the original path allows limit level <= 40) → `rejected` with 0 rolls and the scroll kept. - - Every roll wrote one `CHANGE_ATTRIBUTE` row. The core's syserr shows no new errors; the `new_quest_lv52` LUA_ERROR also appears on the live cores. -- Live acceptance on CH1 (13000) after the deploy, sword 279 and scroll 71084: - - two alternatives with minimum 1 → `matched` after 2 rolls; - - three attributes at the maximum with limit 10 → `limit` after 10 rolls, scrolls 157 → 147; - - `stop` after 1 s → `stopped` after 4 rolls. -- Not done yet: Android device validation. - -## Production deployment - -- 2026-10-15 14:51, approved by the user. The 203 live cores now run main `3b7e158` (`game` sha256 `0d798ec0…`, the binary the channel-5 core was tested with). The db binary is unchanged. Live `/usr/metin2/src` was at `4577d86`, so the deploy also shipped `1a36719` (query protocol and calendar drop gates; the gates stay inert without `port_events.tsv`). -- Package `/root/deploy-features/20261015-features` (`deploy.sh check|go|rollback`, `SHA256SUMS`). The previous `game`/`db` are in `/root/backup-bin/20261015-145122` (recorded in `LAST_BACKUP`), and the replaced `/usr/metin2/src` files are in `src-before/`. `sh deploy.sh rollback` restores both. -- The first `go` stopped at `rebuild.sh stop_server` ("server still running" after about 38 s, cores still exiting) before any backup or copy; the second `go` succeeded. `start.sh` was answered with `1`, which starts only CH1 and game99, so CH2–CH4 were started afterwards with each `run.sh` in the `start.sh` order. The channel-5 test core was restarted too, giving the pre-deploy layout of 14 cores plus db and auth. The new syserr entries contain only the existing `new_quest_lv52` LUA_ERROR (present since 2026-09-21). - -## Open items - -- Attribute lock: done separately in `FEATURE-ATTR-LOCK.md` (table `mt_item_attr_lock`, applied inside `CItem::ChangeAttribute`, so every bot roll keeps the locked slots). The bot's own item cannot be locked or unlocked while it rolls. -- In 203 `player.item_proto`, 71084, 71151, 76014, 76023 and 39028 are USE/USE_CHANGE_ATTRIBUTE (subtype 18); 71302 (the AVA2 talisman scroll) does not exist. The bot accepts any `USE_CHANGE_ATTRIBUTE` scroll and leaves item rules to the original path. +- `tests/features/test_switchbot.py` checks: + - the window enum, headers, subheaders, struct fields and sizes, on both the server and the client; + - the window hooks, the P2P hand-over, the boot ALTER and the switcher choice; + - the version gate; + - that `/mt_switchbot` is gone. +- Client: `metin2-client/tests/wiki/test_switchbot.py` checks that the window script is AVA2 `uiswitchbot.py` verbatim, plus its glue. +- Not yet compiled on 203 and not deployed. The live 203 still runs v1, so the server and client must be deployed together. diff --git a/src/server/common/length.h b/src/server/common/length.h index 2f41aaec..e7d82979 100755 --- a/src/server/common/length.h +++ b/src/server/common/length.h @@ -474,6 +474,21 @@ enum EOnIdleEvents ON_IDLE_MAX_NUM }; +// PORT: AVA2 ENABLE_SWITCHBOT (port_switchbot.cpp). Slot 5 is AVA2's hidden scroll cell; this port keeps +// the table width but never stores an item there. +enum SwitchbotValues +{ + SWITCHBOT_SLOT_COUNT = 6, + SWITCHBOT_SLOT_COUNT_REAL = 5, + SWITCHBOT_ALTERNATIVE_COUNT = 2, + SWITCHBOT_NORM_ATTR_NUM = 5, // AVA2 MAX_NORM_ATTR_NUM + //1 = Switching Item + //2 = Yang + SWITCHBOT_PRICE_TYPE = 1, + //Amount Swtichting Items the Yang-Price + SWITCHBOT_PRICE_AMOUNT = 1, +}; + enum EWindows { RESERVED_WINDOW, @@ -483,6 +498,7 @@ enum EWindows MALL, DRAGON_SOUL_INVENTORY, BELT_INVENTORY, + SWITCHBOT, // PORT: 7 = player.item.window enum 'SWITCHBOT' (appended after BELT_INVENTORY) #ifdef __AUCTION__ AUCTION, #endif @@ -757,6 +773,8 @@ typedef struct SItemPos return cell < INVENTORY_AND_EQUIP_SLOT_MAX; case DRAGON_SOUL_INVENTORY: return cell < (DRAGON_SOUL_INVENTORY_MAX_NUM); + case SWITCHBOT: + return cell < SWITCHBOT_SLOT_COUNT; // µ¿ÀûÀ¸·Î Å©±â°¡ Á¤ÇØÁö´Â window´Â valid üũ¸¦ ÇÒ ¼ö°¡ ¾ø´Ù. case SAFEBOX: case MALL: @@ -796,6 +814,11 @@ typedef struct SItemPos return INVENTORY == window_type && cell < INVENTORY_MAX_NUM; } + bool IsSwitchbotPosition() const + { + return SWITCHBOT == window_type && cell < SWITCHBOT_SLOT_COUNT; + } + bool operator==(const struct SItemPos& rhs) const { return (window_type == rhs.window_type) && (cell == rhs.cell); diff --git a/src/server/common/tables.h b/src/server/common/tables.h index 8767f3d1..6085990c 100755 --- a/src/server/common/tables.h +++ b/src/server/common/tables.h @@ -1484,5 +1484,51 @@ typedef struct SChannelStatus BYTE bStatus; } TChannelStatus; +// PORT: AVA2 ENABLE_SWITCHBOT tables (port_switchbot.cpp). TSwitchbotTable goes to the client as is +// (SUBHEADER_GC_SWITCHBOT_UPDATE) and between cores (HEADER_GG_SWITCHBOT): 220 bytes. +struct TSwitchbotAttributeAlternativeTable +{ + TPlayerItemAttribute attributes[SWITCHBOT_NORM_ATTR_NUM]; + + bool IsConfigured() const + { + + for (BYTE i = 0; i < SWITCHBOT_NORM_ATTR_NUM; ++i) + { + if (attributes[i].bType && attributes[i].sValue) + { + return true; + } + } + + return false; + } +}; + +struct TSwitchbotTable +{ + DWORD player_id; + bool active[SWITCHBOT_SLOT_COUNT]; + bool finished[SWITCHBOT_SLOT_COUNT]; + DWORD items[SWITCHBOT_SLOT_COUNT]; + TSwitchbotAttributeAlternativeTable alternatives[SWITCHBOT_SLOT_COUNT][SWITCHBOT_ALTERNATIVE_COUNT]; + + TSwitchbotTable() : player_id(0) + { + memset(&items, 0, sizeof(items)); + memset(&alternatives, 0, sizeof(alternatives)); + memset(&active, false, sizeof(active)); + memset(&finished, false, sizeof(finished)); + } +}; + +// PORT: AVA2 declares max_value as long; int keeps the 4-byte wire width the client mirrors with LONG. +struct TSwitchbottAttributeTable +{ + BYTE attribute_set; + int apply_num; + int max_value; +}; + #pragma pack() #endif diff --git a/src/server/db/src/ClientManagerPlayer.cpp b/src/server/db/src/ClientManagerPlayer.cpp index 73cd1c01..c99951ae 100755 --- a/src/server/db/src/ClientManagerPlayer.cpp +++ b/src/server/db/src/ClientManagerPlayer.cpp @@ -322,8 +322,8 @@ void CClientManager::QUERY_PLAYER_LOAD(CPeer * peer, DWORD dwHandle, TPlayerLoad { snprintf(szQuery, sizeof(szQuery), "SELECT id,window+0,pos,count,vnum,socket0,socket1,socket2,attrtype0,attrvalue0,attrtype1,attrvalue1,attrtype2,attrvalue2,attrtype3,attrvalue3,attrtype4,attrvalue4,attrtype5,attrvalue5,attrtype6,attrvalue6 " - "FROM item%s WHERE owner_id=%d AND (window < %d or window = %d)", - GetTablePostfix(), pTab->id, SAFEBOX, DRAGON_SOUL_INVENTORY); + "FROM item%s WHERE owner_id=%d AND (window < %d or window = %d or window = %d)", + GetTablePostfix(), pTab->id, SAFEBOX, DRAGON_SOUL_INVENTORY, SWITCHBOT); CDBManager::instance().ReturnQuery(szQuery, QID_ITEM, @@ -379,8 +379,8 @@ void CClientManager::QUERY_PLAYER_LOAD(CPeer * peer, DWORD dwHandle, TPlayerLoad //-------------------------------------------------------------- snprintf(queryStr, sizeof(queryStr), "SELECT id,window+0,pos,count,vnum,socket0,socket1,socket2,attrtype0,attrvalue0,attrtype1,attrvalue1,attrtype2,attrvalue2,attrtype3,attrvalue3,attrtype4,attrvalue4,attrtype5,attrvalue5,attrtype6,attrvalue6 " - "FROM item%s WHERE owner_id=%d AND (window < %d or window = %d)", - GetTablePostfix(), packet->player_id, SAFEBOX, DRAGON_SOUL_INVENTORY); + "FROM item%s WHERE owner_id=%d AND (window < %d or window = %d or window = %d)", + GetTablePostfix(), packet->player_id, SAFEBOX, DRAGON_SOUL_INVENTORY, SWITCHBOT); CDBManager::instance().ReturnQuery(queryStr, QID_ITEM, peer->GetHandle(), new ClientHandleInfo(dwHandle, packet->player_id)); //-------------------------------------------------------------- @@ -1132,7 +1132,7 @@ void CClientManager::__RESULT_PLAYER_DELETE(CPeer *peer, SQLMsg* msg) snprintf(queryStr, sizeof(queryStr), "DELETE FROM player%s WHERE id=%d", GetTablePostfix(), pi->player_id); delete CDBManager::instance().DirectQuery(queryStr); - snprintf(queryStr, sizeof(queryStr), "DELETE FROM item%s WHERE owner_id=%d AND (window < %d or window = %d)", GetTablePostfix(), pi->player_id, SAFEBOX, DRAGON_SOUL_INVENTORY); + snprintf(queryStr, sizeof(queryStr), "DELETE FROM item%s WHERE owner_id=%d AND (window < %d or window = %d or window = %d)", GetTablePostfix(), pi->player_id, SAFEBOX, DRAGON_SOUL_INVENTORY, SWITCHBOT); delete CDBManager::instance().DirectQuery(queryStr); snprintf(queryStr, sizeof(queryStr), "DELETE FROM quest%s WHERE dwPID=%d", GetTablePostfix(), pi->player_id); diff --git a/src/server/game/src/Makefile b/src/server/game/src/Makefile index 6c94b1a4..447f27c9 100755 --- a/src/server/game/src/Makefile +++ b/src/server/game/src/Makefile @@ -61,7 +61,7 @@ CPPFILE = BattleArena.cpp FSM.cpp MarkConvert.cpp MarkImage.cpp MarkManager.cpp desc_client.cpp desc_manager.cpp desc_p2p.cpp dev_log.cpp dungeon.cpp empire_text_convert.cpp entity.cpp\ entity_view.cpp event.cpp event_queue.cpp exchange.cpp file_loader.cpp fishing.cpp gm.cpp guild.cpp\ guild_manager.cpp guild_war.cpp horse_rider.cpp horsename_manager.cpp input.cpp input_auth.cpp input_db.cpp\ - input_login.cpp input_main.cpp input_p2p.cpp port_boss_track.cpp port_attr_lock.cpp port_sash.cpp port_mount.cpp port_costume_attr.cpp port_pendant.cpp port_rings.cpp input_teen.cpp input_udp.cpp ip_ban.cpp\ + input_login.cpp input_main.cpp input_p2p.cpp port_boss_track.cpp port_attr_lock.cpp port_sash.cpp port_mount.cpp port_costume_attr.cpp port_pendant.cpp port_rings.cpp port_switchbot.cpp input_teen.cpp input_udp.cpp ip_ban.cpp\ item.cpp item_addon.cpp item_attribute.cpp item_manager.cpp item_manager_idrange.cpp locale.cpp\ locale_service.cpp log.cpp login_data.cpp lzo_manager.cpp marriage.cpp matrix_card.cpp\ messenger_manager.cpp mining.cpp mob_manager.cpp monarch.cpp motion.cpp over9refine.cpp p2p.cpp packet_info.cpp\ diff --git a/src/server/game/src/char.cpp b/src/server/game/src/char.cpp index 27f28a24..d31d2149 100755 --- a/src/server/game/src/char.cpp +++ b/src/server/game/src/char.cpp @@ -58,6 +58,7 @@ #include "skill_power.h" #include "buff_on_attributes.h" #include "port_battlepass_hooks.h" +#include "port_switchbot.h" #ifdef __PET_SYSTEM__ #include "PetSystem.h" @@ -5351,6 +5352,12 @@ bool CHARACTER::WarpSet(long x, long y, long lPrivateMapIndex) p.wPort = wPort; + // PORT: AVA2 switchbot: the table follows the player to the target core (port_switchbot.cpp). + CSwitchbotManager::Instance().SetIsWarping(GetPlayerID(), true); + + if (p.wPort != mother_port) + CSwitchbotManager::Instance().P2PSendSwitchbot(GetPlayerID(), p.wPort); + GetDesc()->Packet(&p, sizeof(TPacketGCWarp)); //if (!LC_IsNewCIBN()) diff --git a/src/server/game/src/char.h b/src/server/game/src/char.h index b2c2e093..3281e444 100755 --- a/src/server/game/src/char.h +++ b/src/server/game/src/char.h @@ -412,6 +412,8 @@ typedef struct character_point_instant LPITEM pDSItems[DRAGON_SOUL_INVENTORY_MAX_NUM]; WORD wDSItemGrid[DRAGON_SOUL_INVENTORY_MAX_NUM]; + LPITEM pSwitchbotItems[SWITCHBOT_SLOT_COUNT]; // PORT: AVA2 switchbot window (port_switchbot.cpp) + // by mhh LPITEM pCubeItems[CUBE_MAX_NUM]; LPCHARACTER pCubeNpc; @@ -526,9 +528,8 @@ class CHARACTER : public CEntity, public CFSM, public CHorseRider public: DWORD m_portFeatureLastQuery = 0; // PORT: read-only query throttle, not persisted. - DWORD m_portSwitchbotLastCommand = 0; // PORT: switchbot command throttle. - bool m_portQuietInfo = false; // PORT: switchbot rolls hold back per-roll INFO lines... - std::string m_portLastInfo; // ...keeping the last one to report a rejected roll. + bool m_portQuietInfo = false; // PORT: batch actions hold back per-item INFO lines... + std::string m_portLastInfo; // ...keeping the last one to report a rejected item. DWORD m_portPickupLastCommand = 0; // PORT: batch pickup throttle. LPCHARACTER FindCharacterInView(const char * name, bool bFindPCOnly); diff --git a/src/server/game/src/char_item.cpp b/src/server/game/src/char_item.cpp index a967af71..3d768f41 100755 --- a/src/server/game/src/char_item.cpp +++ b/src/server/game/src/char_item.cpp @@ -44,6 +44,7 @@ #include "../../common/VnumHelper.h" #include "DragonSoul.h" #include "port_attr_lock.h" +#include "port_switchbot.h" #include "buff_on_attributes.h" #include "belt_inventory_helper.h" @@ -263,6 +264,14 @@ LPITEM CHARACTER::GetItem(TItemPos Cell) const return NULL; } return m_pointsInstant.pDSItems[wCell]; + // PORT: AVA2 ENABLE_SWITCHBOT window (port_switchbot.cpp). + case SWITCHBOT: + if (wCell >= SWITCHBOT_SLOT_COUNT) + { + sys_err("CHARACTER::GetInventoryItem: invalid switchbot item cell %d", wCell); + return NULL; + } + return m_pointsInstant.pSwitchbotItems[wCell]; default: return NULL; @@ -399,6 +408,32 @@ void CHARACTER::SetItem(TItemPos Cell, LPITEM pItem) m_pointsInstant.pDSItems[wCell] = pItem; } break; + case SWITCHBOT: + { + if (wCell >= SWITCHBOT_SLOT_COUNT) + { + sys_err("CHARACTER::SetItem: invalid switchbot item cell %d", wCell); + return; + } + + LPITEM pOld = m_pointsInstant.pSwitchbotItems[wCell]; + if (pItem && pOld) + { + return; + } + + if (pItem) + { + CSwitchbotManager::Instance().RegisterItem(GetPlayerID(), pItem->GetID(), wCell); + } + else + { + CSwitchbotManager::Instance().UnregisterItem(GetPlayerID(), wCell); + } + + m_pointsInstant.pSwitchbotItems[wCell] = pItem; + } + break; default: sys_err ("Invalid Inventory type %d", window_type); return; @@ -454,6 +489,9 @@ void CHARACTER::SetItem(TItemPos Cell, LPITEM pItem) case DRAGON_SOUL_INVENTORY: pItem->SetWindow(DRAGON_SOUL_INVENTORY); break; + case SWITCHBOT: + pItem->SetWindow(SWITCHBOT); + break; } } } @@ -517,6 +555,17 @@ void CHARACTER::ClearItem() item->SetSkipSave(true); ITEM_MANAGER::instance().FlushDelayedSave(item); + item->RemoveFromCharacter(); + M2_DESTROY_ITEM(item); + } + } + for (i = 0; i < SWITCHBOT_SLOT_COUNT; ++i) + { + if ((item = GetItem(TItemPos(SWITCHBOT, i)))) + { + item->SetSkipSave(true); + ITEM_MANAGER::instance().FlushDelayedSave(item); + item->RemoveFromCharacter(); M2_DESTROY_ITEM(item); } @@ -681,6 +730,18 @@ bool CHARACTER::IsEmptyItemGrid(TItemPos Cell, BYTE bSize, int iExceptionCell) c return true; } } + // PORT: AVA2 switchbot window; cell 5 (AVA2's hidden switcher cell) never takes an item here. + case SWITCHBOT: + { + WORD wCell = Cell.cell; + if (wCell >= SWITCHBOT_SLOT_COUNT_REAL) + return false; + + if (m_pointsInstant.pSwitchbotItems[wCell]) + return false; + + return true; + } } } @@ -5216,6 +5277,28 @@ bool CHARACTER::UseItem(TItemPos Cell, TItemPos DestCell) if (item->IsExchanging()) return false; + // PORT: AVA2 switchbot: using an idle switchbot item takes it back to the inventory. + if (Cell.IsSwitchbotPosition()) + { + if (CSwitchbotManager::Instance().IsActive(GetPlayerID(), Cell.cell)) + return false; + + int iEmptyCell = GetEmptyInventory(item->GetSize()); + + if (iEmptyCell == -1) + { + ChatPacket(CHAT_TYPE_INFO, LC_TEXT("¼ÒÁöÇϰí ÀÖ´Â ¾ÆÀÌÅÛÀÌ ³Ê¹« ¸¹½À´Ï´Ù.")); + return false; + } + + MoveItem(Cell, TItemPos(INVENTORY, iEmptyCell), item->GetCount()); + return true; + } + + // Switchbot items change only through the switchbot (CItem::UpdatePacket skips that window). + if (DestCell.IsSwitchbotPosition()) + return false; + if (!item->CanUsedBy(this)) { ChatPacket(CHAT_TYPE_INFO, LC_TEXT("±ºÁ÷ÀÌ ¸ÂÁö¾Ê¾Æ ÀÌ ¾ÆÀÌÅÛÀ» »ç¿ëÇÒ ¼ö ¾ø½À´Ï´Ù.")); @@ -5405,6 +5488,9 @@ bool CHARACTER::DropItem(TItemPos Cell, BYTE bCount) if (IsDead()) return false; + if (Cell.IsSwitchbotPosition()) // PORT: switchbot items go back to the inventory first + return false; + if (!IsValidItemPosition(Cell) || !(item = GetItem(Cell))) return false; @@ -5613,6 +5699,28 @@ bool CHARACTER::MoveItem(TItemPos Cell, TItemPos DestCell, BYTE count) return false; } + // PORT: AVA2 switchbot: a running slot keeps its item; only switchbot items go in, and only between the + // switchbot window and the main inventory (cell 5 is refused by IsEmptyItemGrid). + if (Cell.IsSwitchbotPosition() || DestCell.IsSwitchbotPosition()) + { + if (Cell.IsSwitchbotPosition() && CSwitchbotManager::Instance().IsActive(GetPlayerID(), Cell.cell)) + { + ChatPacket(CHAT_TYPE_COMMAND, "switchbot_error active"); + return false; + } + + if (DestCell.IsSwitchbotPosition() && !SwitchbotHelper::IsValidItem(item)) + { + ChatPacket(CHAT_TYPE_COMMAND, "switchbot_error invalid"); + return false; + } + + const TItemPos& other = Cell.IsSwitchbotPosition() ? DestCell : Cell; + + if (!other.IsSwitchbotPosition() && !other.IsDefaultInventoryPosition()) + return false; + } + // ÀÌ¹Ì Âø¿ëÁßÀÎ ¾ÆÀÌÅÛÀ» ´Ù¸¥ °÷À¸·Î ¿Å±â´Â °æ¿ì, 'ÀåÃ¥ ÇØÁ¦' °¡´ÉÇÑ Áö È®ÀÎÇÏ°í ¿Å±è if (Cell.IsEquipPosition() && !CanUnequipNow(item)) return false; @@ -6727,6 +6835,9 @@ bool CHARACTER::GiveItem(LPCHARACTER victim, TItemPos Cell) if (!CanHandleItem()) return false; + if (Cell.IsSwitchbotPosition()) // PORT: switchbot items go back to the inventory first + return false; + LPITEM item = GetItem(Cell); if (item && !item->IsExchanging()) @@ -7472,6 +7583,9 @@ bool CHARACTER::IsValidItemPosition(TItemPos Pos) const case DRAGON_SOUL_INVENTORY: return cell < (DRAGON_SOUL_INVENTORY_MAX_NUM); + case SWITCHBOT: + return cell < SWITCHBOT_SLOT_COUNT; + case SAFEBOX: if (NULL != m_pkSafebox) return m_pkSafebox->IsValidPosition(cell); diff --git a/src/server/game/src/cmd.cpp b/src/server/game/src/cmd.cpp index 99c4fad1..e5084c94 100755 --- a/src/server/game/src/cmd.cpp +++ b/src/server/game/src/cmd.cpp @@ -10,7 +10,6 @@ ACMD(do_autohunt_pull); ACMD(do_server_bonuses); ACMD(do_port_biolog); ACMD(do_port_features); -ACMD(do_port_switchbot); ACMD(do_port_pickup); ACMD(do_port_chest); ACMD(do_port_vip); @@ -604,7 +603,6 @@ struct command_info cmd_info[] = // PORT: feature commands stay at the end: commands are prefix matched in table order, so an entry placed // earlier would take over abbreviations of original commands (/m -> mob, /mt -> mto). { "mt_features", do_port_features, 0, POS_DEAD, GM_PLAYER }, - { "mt_switchbot", do_port_switchbot, 0, POS_DEAD, GM_PLAYER }, { "mt_pickup", do_port_pickup, 0, POS_DEAD, GM_PLAYER }, { "mt_chest", do_port_chest, 0, POS_DEAD, GM_PLAYER }, { "mt_vip", do_port_vip, 0, POS_DEAD, GM_PLAYER }, diff --git a/src/server/game/src/cmd_general.cpp b/src/server/game/src/cmd_general.cpp index ab3fff6b..be7f302f 100755 --- a/src/server/game/src/cmd_general.cpp +++ b/src/server/game/src/cmd_general.cpp @@ -44,7 +44,6 @@ #include "port_calendar_runtime.h" #include "port_ava2_travel.h" #include "port_features.h" -#include "port_switchbot.h" #include "port_pickup.h" #include "port_chest.h" #include "port_premium.h" diff --git a/src/server/game/src/exchange.cpp b/src/server/game/src/exchange.cpp index c3229f00..efc82580 100755 --- a/src/server/game/src/exchange.cpp +++ b/src/server/game/src/exchange.cpp @@ -147,6 +147,9 @@ bool CExchange::AddItem(TItemPos item_pos, BYTE display_pos) if (item_pos.IsEquipPosition()) return false; + if (item_pos.IsSwitchbotPosition()) // PORT: switchbot items go back to the inventory first + return false; + LPITEM item; if (!(item = m_pOwner->GetItem(item_pos))) diff --git a/src/server/game/src/input.h b/src/server/game/src/input.h index c9365e04..4e42d0d0 100755 --- a/src/server/game/src/input.h +++ b/src/server/game/src/input.h @@ -157,6 +157,7 @@ class CInputMain : public CInputProcessor void Refine(LPCHARACTER ch, const char* c_pData); void Sash(LPCHARACTER ch, const char* c_pData); + int Switchbot(LPCHARACTER ch, const char* data, size_t uiBytes); // AVA2 switchbot (port_switchbot.cpp) void Roulette(LPCHARACTER ch, const char* c_pData); }; @@ -354,6 +355,7 @@ class CInputP2P : public CInputProcessor void BlockChat(const char * c_pData); void PCBangUpdate(const char* c_pData); void IamAwake(LPDESC d, const char * c_pData); + void Switchbot(LPDESC d, const char * c_pData); // AVA2 switchbot (port_switchbot.cpp) protected: CPacketInfoGG m_packetInfoGG; diff --git a/src/server/game/src/input_db.cpp b/src/server/game/src/input_db.cpp index 32688f90..b0c6f88c 100755 --- a/src/server/game/src/input_db.cpp +++ b/src/server/game/src/input_db.cpp @@ -47,6 +47,7 @@ // #include "HackShield.h" #include "DragonSoul.h" +#include "port_switchbot.h" #ifdef __AUCTION__ #include "auction_manager.h" @@ -1578,6 +1579,14 @@ void CInputDB::ItemLoad(LPDESC d, const char * c_pData) item->AddToCharacter(ch, TItemPos(p->window, p->pos)); break; + // PORT: AVA2 switchbot window; an item that cannot go back there is restored like the others. + case SWITCHBOT: + if (ch->IsEmptyItemGrid(TItemPos(SWITCHBOT, p->pos), item->GetSize()) && SwitchbotHelper::IsValidItem(item)) + item->AddToCharacter(ch, TItemPos(SWITCHBOT, p->pos)); + else + v.push_back(item); + break; + case EQUIPMENT: if (item->CheckItemUseLevel(ch->GetLevel()) == true ) { diff --git a/src/server/game/src/input_login.cpp b/src/server/game/src/input_login.cpp index fc6b9fb0..cff66bba 100755 --- a/src/server/game/src/input_login.cpp +++ b/src/server/game/src/input_login.cpp @@ -31,6 +31,7 @@ #include "db.h" #include "item.h" #include "port_premium.h" +#include "port_switchbot.h" #include "horsename_manager.h" #include "MarkManager.h" // #include "HackShield.h" @@ -649,6 +650,7 @@ void CInputLogin::Entergame(LPDESC d, const char * data) } // PORT: the db core keeps the login-time premium ends; a VIP card used since then is in the account table. PortVipRefresh(ch, false); + CSwitchbotManager::Instance().EnterGame(ch); // PORT: AVA2 switchbot (port_switchbot.cpp) if (LC_IsEurope()) { diff --git a/src/server/game/src/input_main.cpp b/src/server/game/src/input_main.cpp index 41fccb11..71c16814 100755 --- a/src/server/game/src/input_main.cpp +++ b/src/server/game/src/input_main.cpp @@ -41,6 +41,7 @@ // #include "HackShield.h" // #include "XTrapManager.h" #include "DragonSoul.h" +#include "port_switchbot.h" extern void SendShout(const char * szText, BYTE bEmpire); extern int g_nPortalLimitTime; @@ -2065,6 +2066,9 @@ void CInputMain::SafeboxCheckin(LPCHARACTER ch, const char * c_pData) if (!ch->CanHandleItem()) return; + if (p->ItemPos.IsSwitchbotPosition()) // PORT: switchbot items go back to the inventory first + return; + CSafebox * pkSafebox = ch->GetSafebox(); LPITEM pkItem = ch->GetItem(p->ItemPos); @@ -2136,6 +2140,9 @@ void CInputMain::SafeboxCheckout(LPCHARACTER ch, const char * c_pData, bool bMal if (!pkItem) return; + if (p->ItemPos.IsSwitchbotPosition()) // PORT: only MoveItem fills the switchbot window + return; + if (!ch->IsEmptyItemGrid(p->ItemPos, pkItem->GetSize())) return; @@ -3043,6 +3050,49 @@ void CInputMain::Refine(LPCHARACTER ch, const char* c_pData) ch->ClearRefineMode(); } +// AVA2 CInputMain::Switchbot: START carries SWITCHBOT_ALTERNATIVE_COUNT alternative tables, STOP nothing. +int CInputMain::Switchbot(LPCHARACTER ch, const char* data, size_t uiBytes) +{ + const TPacketCGSwitchbot* p = reinterpret_cast(data); + + if (uiBytes < sizeof(TPacketCGSwitchbot)) + return -1; + + const char* c_pData = data + sizeof(TPacketCGSwitchbot); + uiBytes -= sizeof(TPacketCGSwitchbot); + + switch (p->subheader) + { + case SUBHEADER_CG_SWITCHBOT_START: + { + const size_t extraLen = sizeof(TSwitchbotAttributeAlternativeTable) * SWITCHBOT_ALTERNATIVE_COUNT; + + if (uiBytes < extraLen) + return -1; + + std::vector vec_alternatives; + + for (BYTE alternative = 0; alternative < SWITCHBOT_ALTERNATIVE_COUNT; ++alternative) + { + TSwitchbotAttributeAlternativeTable attr; + memcpy(&attr, c_pData, sizeof(attr)); + c_pData += sizeof(TSwitchbotAttributeAlternativeTable); + + vec_alternatives.push_back(attr); + } + + CSwitchbotManager::Instance().Start(ch->GetPlayerID(), p->slot, vec_alternatives); + return extraLen; + } + + case SUBHEADER_CG_SWITCHBOT_STOP: + CSwitchbotManager::Instance().Stop(ch->GetPlayerID(), p->slot); + return 0; + } + + return 0; +} + void CInputMain::Sash(LPCHARACTER ch, const char* c_pData) { quest::PC * pPC = quest::CQuestManager::instance().GetPCForce(ch->GetPlayerID()); @@ -3352,6 +3402,11 @@ int CInputMain::Analyze(LPDESC d, BYTE bHeader, const char * c_pData) Sash(ch, c_pData); break; + case HEADER_CG_SWITCHBOT: + if ((iExtraLen = Switchbot(ch, c_pData, m_iBufferLeft)) < 0) + return -1; + break; + case HEADER_CG_DRAGON_SOUL_REFINE: { TPacketCGDragonSoulRefine* p = reinterpret_cast ((void*)c_pData); diff --git a/src/server/game/src/input_p2p.cpp b/src/server/game/src/input_p2p.cpp index 1b7b917f..8d9747c4 100755 --- a/src/server/game/src/input_p2p.cpp +++ b/src/server/game/src/input_p2p.cpp @@ -21,6 +21,7 @@ #include "pcbang.h" #include "skill.h" #include "threeway_war.h" +#include "port_switchbot.h" //////////////////////////////////////////////////////////////////////////////// @@ -416,6 +417,17 @@ void CInputP2P::IamAwake(LPDESC d, const char * c_pData) sys_log(0, "P2P Awakeness check from %s. My P2P connection number is %d. and details...\n%s", d->GetHostName(), P2P_MANAGER::instance().GetDescCount(), hostNames.c_str()); } +// AVA2: every core gets the table; only the warp target keeps it. +void CInputP2P::Switchbot(LPDESC d, const char * c_pData) +{ + const TPacketGGSwitchbot* p = reinterpret_cast(c_pData); + + if (p->wPort != mother_port) + return; + + CSwitchbotManager::Instance().P2PReceiveSwitchbot(p->table); +} + int CInputP2P::Analyze(LPDESC d, BYTE bHeader, const char * c_pData) { if (test_server) @@ -536,6 +548,10 @@ int CInputP2P::Analyze(LPDESC d, BYTE bHeader, const char * c_pData) case HEADER_GG_CHECK_AWAKENESS: IamAwake(d, c_pData); break; + + case HEADER_GG_SWITCHBOT: + Switchbot(d, c_pData); + break; } return (iExtraLen); diff --git a/src/server/game/src/item.cpp b/src/server/game/src/item.cpp index 991b84c9..62a7a32c 100755 --- a/src/server/game/src/item.cpp +++ b/src/server/game/src/item.cpp @@ -209,6 +209,10 @@ void CItem::UpdatePacket() if (!m_pOwner || !m_pOwner->GetDesc()) return; + // PORT: AVA2 switchbot: rolls in that window reach the client as SUBHEADER_GC_SWITCHBOT_UPDATE_ITEM. + if (m_bWindow == SWITCHBOT) + return; + TPacketGCItemUpdate pack; pack.header = HEADER_GC_ITEM_UPDATE; @@ -317,6 +321,13 @@ LPITEM CItem::RemoveFromCharacter() else pOwner->SetItem(TItemPos(m_bWindow, m_wCell), NULL); } + else if (m_bWindow == SWITCHBOT) // PORT: AVA2 switchbot window + { + if (m_wCell >= SWITCHBOT_SLOT_COUNT) + sys_err("CItem::RemoveFromCharacter: pos >= SWITCHBOT_SLOT_COUNT"); + else + pOwner->SetItem(TItemPos(SWITCHBOT, m_wCell), NULL); + } else { TItemPos cell(INVENTORY, m_wCell); @@ -362,6 +373,14 @@ bool CItem::AddToCharacter(LPCHARACTER ch, TItemPos Cell) return false; } } + else if (SWITCHBOT == window_type) // PORT: AVA2 switchbot window + { + if (pos >= SWITCHBOT_SLOT_COUNT_REAL) + { + sys_err("CItem::AddToCharacter: switchbot cell overflow: %s to %s cell %d", m_pProto->szName, ch->GetName(), pos); + return false; + } + } if (ch->GetDesc()) m_dwLastOwnerPID = ch->GetPlayerID(); diff --git a/src/server/game/src/item.h b/src/server/game/src/item.h index d13d9597..ae184d81 100755 --- a/src/server/game/src/item.h +++ b/src/server/game/src/item.h @@ -241,6 +241,7 @@ class CItem : public CEntity int GetPendantScrollKind(); bool IsNewRing(); // AVA2 new rings (port_rings.cpp) void PutNewRingAttributeWithLevel(BYTE bLevel); + void PutPendantAttributeWithLevel(BYTE bLevel); // port_pendant.cpp bool IsRamadanRing(); void ClearMountAttributeAndAffect(); @@ -339,5 +340,7 @@ EVENTINFO(item_vid_event_info) }; DWORD GetNewRingJewelVnum(DWORD dwRingVnum); // port_rings.cpp, 0 = none +int GetNewRingAttrMaxValue(BYTE bApply); // port_rings.cpp, 0 = not in the ring pool +int GetPendantAttrMaxValue(BYTE bApply); // port_pendant.cpp, 0 = not in the talisman pool #endif diff --git a/src/server/game/src/item_attribute.cpp b/src/server/game/src/item_attribute.cpp index 61b8f2f4..f1175327 100755 --- a/src/server/game/src/item_attribute.cpp +++ b/src/server/game/src/item_attribute.cpp @@ -124,6 +124,13 @@ void CItem::PutAttributeWithLevel(BYTE bLevel) return; } + // PORT: talismans reroll from their own pool (port_pendant.cpp), as the switchbot's 71302 rolls need. + if (IsTalisman()) + { + PutPendantAttributeWithLevel(bLevel); + return; + } + int iAttributeSet = GetAttributeSetIndex(); if (iAttributeSet < 0) diff --git a/src/server/game/src/main.cpp b/src/server/game/src/main.cpp index 5be6e3a8..c3f46dce 100755 --- a/src/server/game/src/main.cpp +++ b/src/server/game/src/main.cpp @@ -63,6 +63,7 @@ #include "SpeedServer.h" // #include "XTrapManager.h" #include "DragonSoul.h" +#include "port_switchbot.h" #include #ifndef __WIN32__ #include "limit_time.h" @@ -239,6 +240,7 @@ unsigned int save_idx = 0; void PortBossTick(); void PortAttrLockBoot(); +void PortSwitchbotBoot(); void heartbeat(LPHEART ht, int pulse) { @@ -521,6 +523,7 @@ int main(int argc, char **argv) CSpeedServerManager SSManager; DSManager dsManager; + CSwitchbotManager switchbotManager; // PORT: AVA2 switchbot #ifdef __AUCTION__ AuctionManager auctionManager; @@ -794,7 +797,10 @@ int start(int argc, char **argv) // END_OF_LOCALE_SERVICE if (!g_bAuthServer) + { PortAttrLockBoot(); + PortSwitchbotBoot(); + } #ifdef __WIN32__ // In Windows dev mode, "verbose" option is [on] by default. diff --git a/src/server/game/src/packet.h b/src/server/game/src/packet.h index d554e6d7..0636924f 100755 --- a/src/server/game/src/packet.h +++ b/src/server/game/src/packet.h @@ -110,6 +110,7 @@ enum HEADER_CG_DRAGON_SOUL_REFINE = 205, HEADER_CG_STATE_CHECKER = 206, HEADER_CG_SASH = 211, // AVA2 sash + HEADER_CG_SWITCHBOT = 171, // AVA2 switchbot (port_switchbot.cpp) HEADER_CG_CLIENT_VERSION = 0xfd, HEADER_CG_CLIENT_VERSION2 = 0xf1, @@ -297,6 +298,7 @@ enum HEADER_GC_DRAGON_SOUL_REFINE = 209, HEADER_GC_RESPOND_CHANNELSTATUS = 210, HEADER_GC_SASH = 215, // AVA2 sash + HEADER_GC_SWITCHBOT = 171, // AVA2 switchbot (port_switchbot.cpp) ///////////////////////////////////////////////////////////////////////////// @@ -331,6 +333,7 @@ enum HEADER_GG_PCBANG_UPDATE = 28, HEADER_GG_CHECK_AWAKENESS = 29, + HEADER_GG_SWITCHBOT = 31, // AVA2 switchbot: table follows the player to another core }; #pragma pack(1) @@ -1174,6 +1177,58 @@ typedef struct SPacketSash DWORD dwMaxAbs; } TPacketSash; +// AVA2 switchbot (port_switchbot.cpp). CG/GC: header, size, subheader, slot, then the subheader's payload. +struct TPacketGGSwitchbot +{ + BYTE bHeader; + WORD wPort; + TSwitchbotTable table; + + TPacketGGSwitchbot() : bHeader(HEADER_GG_SWITCHBOT), wPort(0) + { + //table = {}; + } +}; + +enum ECGSwitchbotSubheader +{ + SUBHEADER_CG_SWITCHBOT_START, // + TSwitchbotAttributeAlternativeTable[SWITCHBOT_ALTERNATIVE_COUNT] + SUBHEADER_CG_SWITCHBOT_STOP, +}; + +struct TPacketCGSwitchbot +{ + BYTE header; + int size; + BYTE subheader; + BYTE slot; +}; + +enum EGCSwitchbotSubheader +{ + SUBHEADER_GC_SWITCHBOT_UPDATE, // + TSwitchbotTable + SUBHEADER_GC_SWITCHBOT_UPDATE_ITEM, // + TSwitchbotUpdateItem + SUBHEADER_GC_SWITCHBOT_SEND_ATTRIBUTE_INFORMATION, // + TSwitchbottAttributeTable[n] +}; + +struct TPacketGCSwitchbot +{ + BYTE header; + int size; + BYTE subheader; + BYTE slot; +}; + +// Our item layout (3 sockets, 7 attributes), as in TPacketGCItemSet. +struct TSwitchbotUpdateItem +{ + BYTE slot; + DWORD vnum; + WORD count; + long alSockets[ITEM_SOCKET_MAX_NUM]; + TPlayerItemAttribute aAttr[ITEM_ATTRIBUTE_MAX_NUM]; +}; + typedef struct packet_item_del { BYTE header; diff --git a/src/server/game/src/packet_info.cpp b/src/server/game/src/packet_info.cpp index 588f917e..7f0e2743 100755 --- a/src/server/game/src/packet_info.cpp +++ b/src/server/game/src/packet_info.cpp @@ -229,6 +229,7 @@ CPacketInfoCG::CPacketInfoCG() Set(HEADER_CG_DRAGON_SOUL_REFINE, sizeof(TPacketCGDragonSoulRefine), "DragonSoulRefine", false); Set(HEADER_CG_STATE_CHECKER, sizeof(BYTE), "ServerStateCheck", false); Set(HEADER_CG_SASH, sizeof(TPacketSash), "Sash", true); + Set(HEADER_CG_SWITCHBOT, sizeof(TPacketCGSwitchbot), "Switchbot", true); } @@ -271,6 +272,7 @@ CPacketInfoGG::CPacketInfoGG() Set(HEADER_GG_MONARCH_TRANSFER, sizeof(TPacketMonarchGGTransfer), "MonarchTransfer", false); Set(HEADER_GG_PCBANG_UPDATE, sizeof(TPacketPCBangUpdate), "PCBangUpdate", false); Set(HEADER_GG_CHECK_AWAKENESS, sizeof(TPacketGGCheckAwakeness), "CheckAwakeness", false); + Set(HEADER_GG_SWITCHBOT, sizeof(TPacketGGSwitchbot), "Switchbot", false); } CPacketInfoGG::~CPacketInfoGG() diff --git a/src/server/game/src/port_features.h b/src/server/game/src/port_features.h index 778b76a7..08aec4ad 100644 --- a/src/server/game/src/port_features.h +++ b/src/server/game/src/port_features.h @@ -45,7 +45,7 @@ ACMD(do_port_features) { ch->ChatPacket(CHAT_TYPE_COMMAND,"MTF1 error %u rate",request);return; } ch->m_portFeatureLastQuery=get_dword_time(); - if(kind=="cap" && args.size()==3) {ch->ChatPacket(CHAT_TYPE_COMMAND,"MTF1 cap %u 1 1023 %lld",request,(long long)get_global_time());return;} + if(kind=="cap" && args.size()==3) {ch->ChatPacket(CHAT_TYPE_COMMAND,"MTF1 cap %u 1 959 %lld",request,(long long)get_global_time());return;} if(kind=="dungeons" && args.size()==3) {PortDungeonQuery(ch,request);return;} if(kind=="bosses" && args.size()==3) {PortBossQuery(ch,request);return;} if(kind=="stats" && args.size()==3) { diff --git a/src/server/game/src/port_pendant.cpp b/src/server/game/src/port_pendant.cpp index f199a772..e15245a0 100644 --- a/src/server/game/src/port_pendant.cpp +++ b/src/server/game/src/port_pendant.cpp @@ -3,8 +3,9 @@ // matching RACE_FLAG_ATT_* (battle.cpp). // Its random attributes come from AVA2's item_attr "pendant" column. That column is not added to 203's item_attr // table and ATTRIBUTE_SET_*, which would change the db -> game boot packet. Instead the pool lives here and -// GetAttributeSetIndex() stays -1, so the 40250 switchers, the switchbot and the attribute lock never touch a -// talisman, and drops carry no magic attributes. +// GetAttributeSetIndex() stays -1, so the 40250 switchers and the attribute lock never touch a talisman, and drops +// carry no magic attributes. The switchbot (port_switchbot.cpp) rerolls it with 71302 through ChangeAttribute, +// which PutAttributeWithLevel routes to PutPendantAttributeWithLevel. // Only the talisman items change its attributes; AVA2 uses 71302 (reroll) and 71301 (add, up to 5). The // imported 53996 / 53997 (AVA2 generic switcher / adder, which would be free 40250 gear rerolls) act as the same // talisman reroll / add here, as their zh names say. Messages go to the client as "MTPENDANT " @@ -106,6 +107,51 @@ namespace } } +// Highest value of a talisman attribute, for the switchbot attribute list (port_switchbot.cpp). +int GetPendantAttrMaxValue(BYTE bApply) +{ + for (size_t i = 0; i < sizeof(s_aPendantAttr) / sizeof(s_aPendantAttr[0]); ++i) + if (s_aPendantAttr[i].bApply == bApply) + return s_aPendantAttr[i].asValues[ITEM_ATTRIBUTE_MAX_LEVEL - 1]; + + return 0; +} + +// CItem::PutAttributeWithLevel over the talisman pool (bLevel 1..5): CItem::ChangeAttribute, so the switchbot +// rerolls a talisman with 71302 like a 40250 item with a switcher. +void CItem::PutPendantAttributeWithLevel(BYTE bLevel) +{ + if (bLevel < 1 || bLevel > ITEM_ATTRIBUTE_MAX_LEVEL) + return; + + DWORD dwTotal = 0; + + for (size_t i = 0; i < sizeof(s_aPendantAttr) / sizeof(s_aPendantAttr[0]); ++i) + if (!HasAttr(s_aPendantAttr[i].bApply)) + dwTotal += s_aPendantAttr[i].dwProb; + + if (!dwTotal) + return; + + DWORD dwProb = number(1, dwTotal); + + for (size_t i = 0; i < sizeof(s_aPendantAttr) / sizeof(s_aPendantAttr[0]); ++i) + { + const PendantAttr & r = s_aPendantAttr[i]; + + if (HasAttr(r.bApply)) + continue; + + if (dwProb <= r.dwProb) + { + AddAttribute(r.bApply, r.asValues[bLevel - 1]); + return; + } + + dwProb -= r.dwProb; + } +} + bool CItem::IsTalisman() { return GetType() == ITEM_ARMOR && GetSubType() == ARMOR_PENDANT; diff --git a/src/server/game/src/port_rings.cpp b/src/server/game/src/port_rings.cpp index 0beda935..ff04190a 100644 --- a/src/server/game/src/port_rings.cpp +++ b/src/server/game/src/port_rings.cpp @@ -4,7 +4,7 @@ // Their random attributes come from AVA2's item_attr_rings table. As with the talismans (port_pendant.cpp), that // table is not added to 203's item_attr / ATTRIBUTE_SET_*, which would change the db -> game boot packet: the pool // lives here, GetAttributeSetIndex() stays -1 and PutAttributeWithLevel() branches to it, and the 40250 switchers / -// adders accept rings (char_item.cpp). The switchbot and the rare (6th / 7th) attributes skip rings; AVA2's +// adders accept rings (char_item.cpp). The rare (6th / 7th) attributes skip rings; AVA2's // item_attr_rare_rings is not ported. Rings drop without attributes (AlterToMagicItem only handles weapons / armor). #include "stdafx.h" #include "constants.h" @@ -71,6 +71,16 @@ DWORD GetNewRingJewelVnum(DWORD dwRingVnum) return 0; } +// Highest value of a ring attribute, for the switchbot attribute list (port_switchbot.cpp). +int GetNewRingAttrMaxValue(BYTE bApply) +{ + for (size_t i = 0; i < sizeof(s_aRingAttr) / sizeof(s_aRingAttr[0]); ++i) + if (s_aRingAttr[i].bApply == bApply) + return s_aRingAttr[i].asValues[ITEM_ATTRIBUTE_MAX_LEVEL - 1]; + + return 0; +} + // CItem::PutAttributeWithLevel over the ring pool (bLevel 1..5). void CItem::PutNewRingAttributeWithLevel(BYTE bLevel) { diff --git a/src/server/game/src/port_switchbot.cpp b/src/server/game/src/port_switchbot.cpp new file mode 100644 index 00000000..d360af1c --- /dev/null +++ b/src/server/game/src/port_switchbot.cpp @@ -0,0 +1,807 @@ +// PORT: AVA2 ENABLE_SWITCHBOT, from AVA2 game/src/new_switchbot.cpp. Classes, API, packets, the 0.1 s roll +// speed and the CheckItem rule (one configured alternative fully matched within the first 5 attributes; no +// configured alternative counts as a match) are AVA2's. Deviations: +// - Cell 5 (AVA2's hidden 71084 cell) is never used; MoveItem rejects it. Switchers stay in the inventory and +// are taken one per roll, skipping stacks that are being exchanged, locked or sold in the player's shop. +// - Switcher choice follows the manual path (char_item.cpp USE_CHANGE_ATTRIBUTE): a talisman takes only 71302; +// a weapon or body armour without a level limit above 40 takes 71151 / 76023 first; everything else takes +// 71084, then 39028. AVA2 could pick 71151 / 76023 for high-level items and never consumed 39028. +// - A slot stops instead of rolling when its item has no attributes (the manual path refuses that too). +// - Every roll is in ItemLog as SWITCHBOT, with the item id as hint, like CHANGE_ATTRIBUTE. +// - The end / stop messages go to the client as server commands ("switchbot_end ", +// "switchbot_stop ") for localeInfo text, instead of AVA2's numeric locale ids 864 / 865. +// - Leaving the core deletes the table after it is sent (AVA2 leaked it), and a logout that unregisters the last +// active slot stops the roll event. +// - Version gate: EnterGame sends nothing unless the CG_CLIENT_VERSION timestamp is "mt" with +// date >= PORT_SWITCHBOT_CLIENT_VERSION (older clients send __TIMESTAMP__ or "1215955205"). +// - The attribute list has two pseudo sets after ATTRIBUTE_SET_MAX_NUM: 8 = rings (port_rings.cpp) and +// 9 = talismans (port_pendant.cpp), whose pools are not in item_attr. +#include "stdafx.h" +#include "constants.h" +#include "port_switchbot.h" +#include "desc.h" +#include "item.h" +#include "item_manager.h" +#include "char_manager.h" +#include "buffer_manager.h" +#include "char.h" +#include "config.h" +#include "p2p.h" +#include "packet.h" +#include "shop.h" +#include "log.h" +#include "db.h" + +// Wire sizes the client (UserInterface/Packet.h) mirrors byte for byte. +static_assert(sizeof(TSwitchbotTable) == 220, "TSwitchbotTable"); +static_assert(sizeof(TSwitchbotAttributeAlternativeTable) == 15, "TSwitchbotAttributeAlternativeTable"); +static_assert(sizeof(TSwitchbottAttributeTable) == 9, "TSwitchbottAttributeTable"); +static_assert(sizeof(TSwitchbotUpdateItem) == 40, "TSwitchbotUpdateItem"); +static_assert(sizeof(TPacketCGSwitchbot) == 7 && sizeof(TPacketGCSwitchbot) == 7, "switchbot packet header"); +static_assert(sizeof(TPacketGGSwitchbot) == 223, "TPacketGGSwitchbot"); + +namespace +{ + const float c_fSpeed = 0.1f; + + enum + { + SWITCHBOT_ATTRIBUTE_SET_NEW_RINGS = ATTRIBUTE_SET_MAX_NUM, // 8 + SWITCHBOT_ATTRIBUTE_SET_PENDANT, // 9 + }; + + bool ValidPosition(DWORD wCell) + { + return wCell < SWITCHBOT_SLOT_COUNT_REAL; + } + + long SwitchbotPasses() + { + const long lPasses = long(PASSES_PER_SEC(c_fSpeed)); + return lPasses > 0 ? lPasses : 1; + } + + bool IsLowLevelSwitchTarget(LPITEM pkItem) + { + if (!(pkItem->GetType() == ITEM_WEAPON || (pkItem->GetType() == ITEM_ARMOR && pkItem->GetSubType() == ARMOR_BODY))) + return false; + + for (int i = 0; i < ITEM_LIMIT_MAX_NUM; ++i) + if (pkItem->GetLimitType(i) == LIMIT_LEVEL && pkItem->GetLimitValue(i) > 40) + return false; + + return true; + } + + // CHARACTER::FindSpecifyItem over stacks the player can spend right now. + LPITEM FindUsableSwitcher(LPCHARACTER ch, DWORD dwVnum) + { + LPSHOP pkShop = ch->GetMyShop(); + + for (int i = 0; i < INVENTORY_MAX_NUM; ++i) + { + LPITEM item = ch->GetInventoryItem(i); + + if (!item || item->GetVnum() != dwVnum || item->GetCount() < SWITCHBOT_PRICE_AMOUNT) + continue; + + if (item->IsExchanging() || item->isLocked()) + continue; + + if (pkShop && pkShop->IsSellingItem(item->GetID())) + continue; + + return item; + } + + return NULL; + } + + LPITEM SelectSwitcher(LPCHARACTER ch, LPITEM pkItem) + { + if (pkItem->IsTalisman()) + return FindUsableSwitcher(ch, 71302); + + static const DWORD s_adwLow[] = { 71151, 76023 }; + static const DWORD s_adwNormal[] = { 71084, 39028 }; + + if (IsLowLevelSwitchTarget(pkItem)) + for (size_t i = 0; i < sizeof(s_adwLow) / sizeof(s_adwLow[0]); ++i) + if (LPITEM scroll = FindUsableSwitcher(ch, s_adwLow[i])) + return scroll; + + for (size_t i = 0; i < sizeof(s_adwNormal) / sizeof(s_adwNormal[0]); ++i) + if (LPITEM scroll = FindUsableSwitcher(ch, s_adwNormal[i])) + return scroll; + + return NULL; + } + + void WriteAttribute(TEMP_BUFFER& buf, BYTE bSet, int iApply, int iMax) + { + TSwitchbottAttributeTable table = {}; + table.attribute_set = bSet; + table.apply_num = iApply; + table.max_value = iMax; + buf.write(&table, sizeof(table)); + } +} + +bool SwitchbotHelper::IsValidItem(LPITEM pkItem) +{ + if (!pkItem) + return false; + + switch (pkItem->GetType()) + { + case ITEM_NEW_RINGS: + case ITEM_WEAPON: + return true; + + case ITEM_ARMOR: + switch (pkItem->GetSubType()) + { + case ARMOR_BODY: + case ARMOR_HEAD: + case ARMOR_SHIELD: + case ARMOR_WRIST: + case ARMOR_FOOTS: + case ARMOR_NECK: + case ARMOR_EAR: + case ARMOR_PENDANT: + return true; + } + return false; + + default: + return false; + } +} + +CSwitchbot::CSwitchbot() : m_pkSwitchEvent(NULL), m_isWarping(false) +{ +} + +CSwitchbot::~CSwitchbot() +{ + if (m_pkSwitchEvent) + event_cancel(&m_pkSwitchEvent); + + m_pkSwitchEvent = NULL; +} + +void CSwitchbot::RegisterItem(WORD wCell, DWORD item_id) +{ + if (!ValidPosition(wCell)) + return; + + m_table.items[wCell] = item_id; +} + +void CSwitchbot::UnregisterItem(WORD wCell) +{ + if (!ValidPosition(wCell)) + return; + + m_table.items[wCell] = 0; + m_table.active[wCell] = false; + m_table.finished[wCell] = false; + memset(&m_table.alternatives[wCell], 0, sizeof(m_table.alternatives[wCell])); +} + +void CSwitchbot::SetAttributes(BYTE slot, const std::vector& vec_alternatives) +{ + if (!ValidPosition(slot) || vec_alternatives.size() < SWITCHBOT_ALTERNATIVE_COUNT) + return; + + for (BYTE alternative = 0; alternative < SWITCHBOT_ALTERNATIVE_COUNT; ++alternative) + { + for (BYTE attrIdx = 0; attrIdx < SWITCHBOT_NORM_ATTR_NUM; ++attrIdx) + { + m_table.alternatives[slot][alternative].attributes[attrIdx].bType = vec_alternatives[alternative].attributes[attrIdx].bType; + m_table.alternatives[slot][alternative].attributes[attrIdx].sValue = vec_alternatives[alternative].attributes[attrIdx].sValue; + } + } +} + +void CSwitchbot::SetActive(BYTE slot, bool active) +{ + if (!ValidPosition(slot)) + return; + + m_table.active[slot] = active; + m_table.finished[slot] = false; +} + +EVENTINFO(TSwitchbotEventInfo) +{ + CSwitchbot* pkSwitchbot; + + TSwitchbotEventInfo() : pkSwitchbot(NULL) + { + } +}; + +EVENTFUNC(switchbot_event) +{ + TSwitchbotEventInfo* info = dynamic_cast(event->info); + + if (info == NULL) + { + sys_err("switchbot_event> Info Null pointer"); + return 0; + } + + if (!info->pkSwitchbot) + { + sys_err("switchbot_event> Switchbot Null pointer"); + return 0; + } + + info->pkSwitchbot->SwitchItems(); + + return SwitchbotPasses(); +} + +void CSwitchbot::Start() +{ + TSwitchbotEventInfo* info = AllocEventInfo(); + info->pkSwitchbot = this; + + m_pkSwitchEvent = event_create(switchbot_event, info, SwitchbotPasses()); + + CSwitchbotManager::Instance().SendSwitchbotUpdate(m_table.player_id); +} + +void CSwitchbot::Stop() +{ + if (m_pkSwitchEvent) + { + event_cancel(&m_pkSwitchEvent); + m_pkSwitchEvent = NULL; + } + + memset(&m_table.active, 0, sizeof(m_table.active)); + + CSwitchbotManager::Instance().SendSwitchbotUpdate(m_table.player_id); + + for (BYTE bSlot = 0; bSlot < SWITCHBOT_SLOT_COUNT_REAL; ++bSlot) + { + LPITEM pkItem = ITEM_MANAGER::Instance().Find(m_table.items[bSlot]); + + if (!pkItem) + continue; + + LPCHARACTER pkOwner = pkItem->GetOwner(); + + if (!pkOwner) + return; + + SendItemUpdate(pkOwner, bSlot, pkItem); + } +} + +void CSwitchbot::Pause() +{ + if (m_pkSwitchEvent) + { + event_cancel(&m_pkSwitchEvent); + m_pkSwitchEvent = NULL; + } + + for (BYTE bSlot = 0; bSlot < SWITCHBOT_SLOT_COUNT_REAL; ++bSlot) + { + LPITEM pkItem = ITEM_MANAGER::Instance().Find(m_table.items[bSlot]); + + if (!pkItem) + continue; + + LPCHARACTER pkOwner = pkItem->GetOwner(); + + if (!pkOwner) + return; + + SendItemUpdate(pkOwner, bSlot, pkItem); + } +} + +bool CSwitchbot::IsActive(BYTE slot) +{ + if (!ValidPosition(slot)) + return false; + + return m_table.active[slot]; +} + +bool CSwitchbot::HasActiveSlots() +{ + for (int i = 0; i < SWITCHBOT_SLOT_COUNT_REAL; ++i) + if (m_table.active[i]) + return true; + + return false; +} + +bool CSwitchbot::IsSwitching() +{ + return m_pkSwitchEvent != NULL; +} + +// AVA2's success / out-of-switchers tail: deactivate the slot, stop when it was the last one, refresh the client. +void CSwitchbot::FinishSlot(LPCHARACTER ch, BYTE slot, LPITEM item, bool finished) +{ + SetActive(slot, false); + m_table.finished[slot] = finished; + + if (!HasActiveSlots()) + Stop(); + else + CSwitchbotManager::Instance().SendSwitchbotUpdate(m_table.player_id); + + SendItemUpdate(ch, slot, item); +} + +void CSwitchbot::SwitchItems() +{ + for (BYTE bSlot = 0; bSlot < SWITCHBOT_SLOT_COUNT_REAL; ++bSlot) + { + if (!m_table.active[bSlot]) + continue; + + m_table.finished[bSlot] = false; + + LPITEM pkItem = ITEM_MANAGER::Instance().Find(m_table.items[bSlot]); + + if (!pkItem) + continue; + + LPCHARACTER pkOwner = pkItem->GetOwner(); + + if (!pkOwner) + return; + + if (pkOwner->GetPlayerID() != m_table.player_id || pkItem->GetWindow() != SWITCHBOT || pkItem->GetCell() != bSlot) + { + sys_err("switchbot: item %u is no longer in slot %d of player %u", m_table.items[bSlot], bSlot, m_table.player_id); + UnregisterItem(bSlot); + continue; + } + + if (CheckItem(pkItem, bSlot)) + { + pkOwner->ChatPacket(CHAT_TYPE_COMMAND, "switchbot_end %d", bSlot); + FinishSlot(pkOwner, bSlot, pkItem, true); + continue; + } + + if (!pkItem->GetAttributeCount() || (pkItem->GetAttributeSetIndex() < 0 && !pkItem->IsNewRing() && !pkItem->IsTalisman())) + { + pkOwner->ChatPacket(CHAT_TYPE_COMMAND, "switchbot_stop noattr %d", bSlot); + FinishSlot(pkOwner, bSlot, pkItem, false); + continue; + } + + LPITEM pkScroll = SelectSwitcher(pkOwner, pkItem); + + if (!pkScroll) + { + pkOwner->ChatPacket(CHAT_TYPE_COMMAND, "switchbot_stop nochanger %d", bSlot); + FinishSlot(pkOwner, bSlot, pkItem, false); + return; + } + + char szHint[21]; + snprintf(szHint, sizeof(szHint), "%u", pkItem->GetID()); + LogManager::instance().ItemLog(pkOwner, pkScroll, "SWITCHBOT", szHint); + + pkScroll->SetCount(pkScroll->GetCount() - SWITCHBOT_PRICE_AMOUNT); + pkItem->ChangeAttribute(); + } +} + +bool CSwitchbot::CheckItem(LPITEM pkItem, BYTE slot) +{ + if (!ValidPosition(slot) || !pkItem) + return false; + + bool checked = false; + + for (int i = 0; i < SWITCHBOT_ALTERNATIVE_COUNT; ++i) + { + const TSwitchbotAttributeAlternativeTable& alternative = m_table.alternatives[slot][i]; + + if (!alternative.IsConfigured()) + continue; + + BYTE configuredAttrCount = 0; + BYTE correctAttrCount = 0; + + for (int j = 0; j < SWITCHBOT_NORM_ATTR_NUM; ++j) + { + const TPlayerItemAttribute& destAttr = alternative.attributes[j]; + + if (!destAttr.bType || !destAttr.sValue) + continue; + + ++configuredAttrCount; + + for (BYTE attrIdx = 0; attrIdx < SWITCHBOT_NORM_ATTR_NUM; ++attrIdx) + { + const TPlayerItemAttribute& curAttr = pkItem->GetAttribute(attrIdx); + + if (curAttr.bType != destAttr.bType || curAttr.sValue < destAttr.sValue) + continue; + + ++correctAttrCount; + break; + } + } + + checked = true; + + if (configuredAttrCount == correctAttrCount) + return true; + } + + if (!checked) + return true; + + return false; +} + +void CSwitchbot::SendItemUpdate(LPCHARACTER ch, BYTE slot, LPITEM item) +{ + LPDESC desc = ch->GetDesc(); + + if (!desc) + return; + + TPacketGCSwitchbot pack; + pack.header = HEADER_GC_SWITCHBOT; + pack.subheader = SUBHEADER_GC_SWITCHBOT_UPDATE_ITEM; + pack.size = sizeof(TPacketGCSwitchbot) + sizeof(TSwitchbotUpdateItem); + pack.slot = slot; + + TSwitchbotUpdateItem update = {}; + update.slot = slot; + update.vnum = item->GetVnum(); + update.count = item->GetCount(); + thecore_memcpy(update.alSockets, item->GetSockets(), sizeof(update.alSockets)); + thecore_memcpy(update.aAttr, item->GetAttributes(), sizeof(update.aAttr)); + + TEMP_BUFFER tmp_buf; + tmp_buf.write(&pack, sizeof(pack)); + tmp_buf.write(&update, sizeof(update)); + desc->Packet(tmp_buf.read_peek(), tmp_buf.size()); +} + +CSwitchbotManager::~CSwitchbotManager() +{ + for (std::map::iterator it = m_map_Switchbots.begin(); it != m_map_Switchbots.end(); ++it) + delete it->second; + + m_map_Switchbots.clear(); +} + +void CSwitchbotManager::RegisterItem(DWORD player_id, DWORD item_id, WORD wCell) +{ + if (!ValidPosition(wCell)) + return; + + CSwitchbot* pkSwitchbot = FindSwitchbot(player_id); + + if (!pkSwitchbot) + { + pkSwitchbot = new CSwitchbot(); + pkSwitchbot->SetPlayerId(player_id); + m_map_Switchbots.insert(std::make_pair(player_id, pkSwitchbot)); + } + + if (pkSwitchbot->IsWarping()) + return; + + pkSwitchbot->RegisterItem(wCell, item_id); + SendSwitchbotUpdate(player_id); +} + +void CSwitchbotManager::UnregisterItem(DWORD player_id, WORD wCell) +{ + if (!ValidPosition(wCell)) + return; + + CSwitchbot* pkSwitchbot = FindSwitchbot(player_id); + + if (!pkSwitchbot) + return; + + if (pkSwitchbot->IsWarping()) + return; + + pkSwitchbot->UnregisterItem(wCell); + + if (!pkSwitchbot->HasActiveSlots() && pkSwitchbot->IsSwitching()) + pkSwitchbot->Stop(); + else + SendSwitchbotUpdate(player_id); +} + +void CSwitchbotManager::Start(DWORD player_id, BYTE slot, const std::vector& vec_alternatives) +{ + if (!ValidPosition(slot)) + return; + + CSwitchbot* pkSwitchbot = FindSwitchbot(player_id); + + if (!pkSwitchbot) + { + sys_err("No Switchbot found for player_id %u slot %d", player_id, slot); + return; + } + + if (pkSwitchbot->IsActive(slot)) + { + sys_err("Switchbot slot %d already running for player_id %u", slot, player_id); + return; + } + + if (!pkSwitchbot->GetTable().items[slot]) + return; + + pkSwitchbot->SetActive(slot, true); + pkSwitchbot->SetAttributes(slot, vec_alternatives); + + if (pkSwitchbot->HasActiveSlots() && !pkSwitchbot->IsSwitching()) + pkSwitchbot->Start(); + else + SendSwitchbotUpdate(player_id); +} + +void CSwitchbotManager::Stop(DWORD player_id, BYTE slot) +{ + if (!ValidPosition(slot)) + return; + + CSwitchbot* pkSwitchbot = FindSwitchbot(player_id); + + if (!pkSwitchbot) + { + sys_err("No Switchbot found for player_id %u slot %d", player_id, slot); + return; + } + + if (!pkSwitchbot->IsActive(slot)) + { + sys_err("Switchbot slot %d is not running for player_id %u", slot, player_id); + return; + } + + pkSwitchbot->SetActive(slot, false); + + if (!pkSwitchbot->HasActiveSlots() && pkSwitchbot->IsSwitching()) + pkSwitchbot->Stop(); + else + SendSwitchbotUpdate(player_id); +} + +bool CSwitchbotManager::IsActive(DWORD player_id, BYTE slot) +{ + if (!ValidPosition(slot)) + return false; + + CSwitchbot* pkSwitchbot = FindSwitchbot(player_id); + + if (!pkSwitchbot) + return false; + + return pkSwitchbot->IsActive(slot); +} + +bool CSwitchbotManager::IsWarping(DWORD player_id) +{ + CSwitchbot* pkSwitchbot = FindSwitchbot(player_id); + + if (!pkSwitchbot) + return false; + + return pkSwitchbot->IsWarping(); +} + +void CSwitchbotManager::SetIsWarping(DWORD player_id, bool warping) +{ + CSwitchbot* pkSwitchbot = FindSwitchbot(player_id); + + if (!pkSwitchbot) + return; + + // PORT: the warp logout destroys the items; EnterGame starts the event again. + if (warping) + pkSwitchbot->Pause(); + + pkSwitchbot->SetIsWarping(warping); +} + +CSwitchbot* CSwitchbotManager::FindSwitchbot(DWORD player_id) +{ + std::map::iterator it = m_map_Switchbots.find(player_id); + + if (it == m_map_Switchbots.end()) + return NULL; + + return it->second; +} + +void CSwitchbotManager::P2PSendSwitchbot(DWORD player_id, WORD wTargetPort) +{ + CSwitchbot* pkSwitchbot = FindSwitchbot(player_id); + + if (!pkSwitchbot) + return; + + pkSwitchbot->Pause(); + m_map_Switchbots.erase(player_id); + + TPacketGGSwitchbot pack; + pack.wPort = wTargetPort; + pack.table = pkSwitchbot->GetTable(); + P2P_MANAGER::Instance().Send(&pack, sizeof(pack)); + + delete pkSwitchbot; +} + +void CSwitchbotManager::P2PReceiveSwitchbot(const TSwitchbotTable& table) +{ + CSwitchbot* pkSwitchbot = FindSwitchbot(table.player_id); + + if (!pkSwitchbot) + { + pkSwitchbot = new CSwitchbot(); + m_map_Switchbots.insert(std::make_pair(table.player_id, pkSwitchbot)); + } + + pkSwitchbot->SetTable(table); + // The items arrive with the login before EnterGame clears this; RegisterItem keeps the received table. + pkSwitchbot->SetIsWarping(true); +} + +void CSwitchbotManager::SendItemAttributeInformations(LPCHARACTER ch) +{ + if (!ch) + return; + + LPDESC desc = ch->GetDesc(); + + if (!desc) + return; + + TPacketGCSwitchbot pack; + pack.header = HEADER_GC_SWITCHBOT; + pack.subheader = SUBHEADER_GC_SWITCHBOT_SEND_ATTRIBUTE_INFORMATION; + pack.size = sizeof(TPacketGCSwitchbot); + pack.slot = 0; + + TEMP_BUFFER buf; + + for (BYTE bAttributeSet = 0; bAttributeSet < ATTRIBUTE_SET_MAX_NUM; ++bAttributeSet) + { + for (int iApplyNum = 0; iApplyNum < MAX_APPLY_NUM; ++iApplyNum) + { + const TItemAttrTable& r = g_map_itemAttr[iApplyNum]; + const BYTE max = r.bMaxLevelBySet[bAttributeSet]; + + if (max > 0) + WriteAttribute(buf, bAttributeSet, iApplyNum, r.lValues[MIN(max, ITEM_ATTRIBUTE_MAX_LEVEL) - 1]); + } + } + + for (int iApplyNum = 0; iApplyNum < MAX_APPLY_NUM; ++iApplyNum) + if (const int iMax = GetNewRingAttrMaxValue(BYTE(iApplyNum))) + WriteAttribute(buf, SWITCHBOT_ATTRIBUTE_SET_NEW_RINGS, iApplyNum, iMax); + + for (int iApplyNum = 0; iApplyNum < MAX_APPLY_NUM; ++iApplyNum) + if (const int iMax = GetPendantAttrMaxValue(BYTE(iApplyNum))) + WriteAttribute(buf, SWITCHBOT_ATTRIBUTE_SET_PENDANT, iApplyNum, iMax); + + if (buf.size()) + { + pack.size += buf.size(); + desc->BufferedPacket(&pack, sizeof(pack)); + desc->Packet(buf.read_peek(), buf.size()); + } + else + desc->Packet(&pack, sizeof(pack)); +} + +void CSwitchbotManager::SendSwitchbotUpdate(DWORD player_id) +{ + CSwitchbot* pkSwitchbot = FindSwitchbot(player_id); + + if (!pkSwitchbot) + return; + + LPCHARACTER ch = CHARACTER_MANAGER::Instance().FindByPID(player_id); + + if (!ch) + return; + + LPDESC d = ch->GetDesc(); + + if (!d) + return; + + const TSwitchbotTable& table = pkSwitchbot->GetTable(); + + TPacketGCSwitchbot pack; + pack.header = HEADER_GC_SWITCHBOT; + pack.subheader = SUBHEADER_GC_SWITCHBOT_UPDATE; + pack.size = sizeof(TPacketGCSwitchbot) + sizeof(TSwitchbotTable); + pack.slot = 0; + d->BufferedPacket(&pack, sizeof(pack)); + d->Packet(&table, sizeof(table)); +} + +bool SwitchbotHelper::IsClientSupported(LPCHARACTER ch) +{ + LPDESC d = ch ? ch->GetDesc() : NULL; + const char* c_pszVersion = d ? d->GetClientVersion() : ""; + return c_pszVersion[0] == 'm' && c_pszVersion[1] == 't' && atoi(c_pszVersion + 2) >= PORT_SWITCHBOT_CLIENT_VERSION; +} + +void CSwitchbotManager::EnterGame(LPCHARACTER ch) +{ + SetIsWarping(ch->GetPlayerID(), false); + + // PORT: version gate. An older client has no GC_SWITCHBOT handler; it never fills the window either. + if (!SwitchbotHelper::IsClientSupported(ch)) + return; + + SendItemAttributeInformations(ch); + + // A table kept over a warp (or received from another core) only keeps slots whose item is still there. + if (CSwitchbot* pkSwitchbot = FindSwitchbot(ch->GetPlayerID())) + { + for (BYTE bSlot = 0; bSlot < SWITCHBOT_SLOT_COUNT_REAL; ++bSlot) + { + LPITEM pkItem = ch->GetItem(TItemPos(SWITCHBOT, bSlot)); + + if (!pkItem) + pkSwitchbot->UnregisterItem(bSlot); + else if (pkSwitchbot->GetTable().items[bSlot] != pkItem->GetID()) + { + pkSwitchbot->UnregisterItem(bSlot); + pkSwitchbot->RegisterItem(bSlot, pkItem->GetID()); + } + } + } + + SendSwitchbotUpdate(ch->GetPlayerID()); + + CSwitchbot* pkSwitchbot = FindSwitchbot(ch->GetPlayerID()); + + if (pkSwitchbot && pkSwitchbot->HasActiveSlots() && !pkSwitchbot->IsSwitching()) + pkSwitchbot->Start(); +} + +void PortSwitchbotBoot() +{ + std::unique_ptr msg(DBManager::instance().DirectQuery("SHOW COLUMNS FROM item LIKE 'window'")); + + if (msg->uiSQLErrno || !msg->Get()->uiNumRows) + { + sys_err("PortSwitchbotBoot: cannot read item.window (errno %u)", msg->uiSQLErrno); + return; + } + + MYSQL_ROW row = mysql_fetch_row(msg->Get()->pSQLResult); + + if (row[1] && strstr(row[1], "'SWITCHBOT'")) + return; + + std::unique_ptr alter(DBManager::instance().DirectQuery( + "ALTER TABLE item MODIFY window enum('INVENTORY','EQUIPMENT','SAFEBOX','MALL','DRAGON_SOUL_INVENTORY'," + "'BELT_INVENTORY','SWITCHBOT') NOT NULL DEFAULT 'INVENTORY'")); + + if (alter->uiSQLErrno) + sys_err("PortSwitchbotBoot: cannot add SWITCHBOT to item.window (errno %u)", alter->uiSQLErrno); + else + sys_log(0, "PortSwitchbotBoot: added SWITCHBOT to item.window"); +} diff --git a/src/server/game/src/port_switchbot.h b/src/server/game/src/port_switchbot.h index e11ba2b8..6be3f421 100644 --- a/src/server/game/src/port_switchbot.h +++ b/src/server/game/src/port_switchbot.h @@ -1,248 +1,91 @@ #ifndef METIN2_PORT_SWITCHBOT_H #define METIN2_PORT_SWITCHBOT_H -// PORT: AVA2-style automatic attribute change. Every roll goes through the original -// CHARACTER::UseItem change-attribute path, so its checks, probabilities, log and consumption apply unchanged. -// One bound item per character; not persisted; stops on logout, warp, busy windows or any rejected roll. -// The lock verb toggles the attribute lock (port_attr_lock.h) that ChangeAttribute applies to every reroll. -#include -#include -#include -#include -#include -#include "port_attr_lock.h" +// PORT: AVA2 ENABLE_SWITCHBOT (new_switchbot.{h,cpp}): items placed in the SWITCHBOT window (cells 0..4) are +// rerolled with switchers from the inventory until one configured alternative matches. Same classes, API, +// packets and speed as AVA2; the deviations are listed at the top of port_switchbot.cpp. +#include "../../common/tables.h" -static const unsigned kPortSwitchAlternatives=2, kPortSwitchTargets=5, kPortSwitchLimit=1000; -static const unsigned kPortSwitchAddonSkillMax=30, kPortSwitchAddonNormalMax=65; // CItemAddonManager::ApplyAddonTo bounds. +// PORT: clients from this protocol date on send "mt" as their CG_CLIENT_VERSION timestamp +// (metin2-client PythonNetworkStreamPhaseGame.cpp SendClientVersionPacket). +enum { PORT_SWITCHBOT_CLIENT_VERSION = 20261016 }; -struct PortSwitchTarget {unsigned apply;int value;}; -struct PortSwitchbot { - DWORD pid=0,item=0,scroll=0;unsigned limit=0,rolls=0;VID vid; - std::vector alternatives[kPortSwitchAlternatives]; - LPEVENT event; +class SwitchbotHelper +{ +public: + static bool IsValidItem(LPITEM pkItem); + static bool IsClientSupported(LPCHARACTER ch); // PORT: CG_CLIENT_VERSION timestamp gate }; -static std::map g_portSwitchbots; -static bool PortSwitchNumber(const std::string& text,unsigned& value) { - if(text.empty() || text.size()>10)return false; - unsigned long long result=0; - for(char c:text){if(c<'0'||c>'9')return false;result=result*10+(c-'0');} - if(result>0xffffffffull)return false; - value=unsigned(result);return true; -} +class CSwitchbot +{ +public: + CSwitchbot(); + ~CSwitchbot(); -// Attribute types a reroll of this item can produce, with the highest value each can reach. -static std::vector > PortSwitchAllowed(LPITEM item) { - std::vector > allowed; - const int set=item->GetAttributeSetIndex(); - if(set<0)return allowed; - const TItemTable* proto=item->GetProto(); - for(unsigned apply=0;applysecond.bMaxLevelBySet[set]; - if(!level)continue; - bool base=false; - for(int i=0;iaApplies[i].bType==apply; - const long value=it->second.lValues[(level>5?5:level)-1]; - if(!base && value>0)allowed.push_back(std::make_pair(apply,int(value))); - } - if(proto && proto->sAddonType) { - allowed.push_back(std::make_pair(unsigned(APPLY_SKILL_DAMAGE_BONUS),int(kPortSwitchAddonSkillMax))); - allowed.push_back(std::make_pair(unsigned(APPLY_NORMAL_HIT_DAMAGE_BONUS),int(kPortSwitchAddonNormalMax))); - } - return allowed; -} + void SetTable(const TSwitchbotTable& table) { m_table = table; } + const TSwitchbotTable& GetTable() const { return m_table; } -// AVA2 CheckItem semantics over the five normal slots: any one configured alternative fully satisfied. -static bool PortSwitchMatches(LPITEM item,const PortSwitchbot& bot) { - for(const auto& alternative:bot.alternatives) { - if(alternative.empty())continue; - bool all=true; - for(const auto& target:alternative) { - bool found=false; - for(int i=0;iGetAttribute(i); - found=attr.bType==target.apply && attr.sValue>=target.value; - } - all&=found; - } - if(all)return true; - } - return false; -} + void SetPlayerId(DWORD player_id) { m_table.player_id = player_id; } + DWORD GetPlayerId() const { return m_table.player_id; } -static bool PortSwitchBusy(LPCHARACTER ch) { - return ch->IsDead() || ch->IsWarping() || !ch->CanHandleItem() || ch->GetExchange() || ch->GetMyShop() || - ch->GetShopOwner() || ch->IsOpenSafebox() || ch->IsCubeOpen(); -} + void RegisterItem(WORD wCell, DWORD item_id); + void UnregisterItem(WORD wCell); + void SetAttributes(BYTE slot, const std::vector& vec_alternatives); -static LPITEM PortSwitchItem(LPCHARACTER ch,const PortSwitchbot& bot) { - LPITEM item=ITEM_MANAGER::instance().Find(bot.item); - if(!item || item->GetOwner()!=ch || item->GetWindow()!=INVENTORY || item->GetCell()>=INVENTORY_MAX_NUM || item->IsEquipped())return NULL; - return item; -} + void SetActive(BYTE slot, bool active); + bool IsActive(BYTE slot); + bool HasActiveSlots(); + bool IsSwitching(); + bool IsWarping() { return m_isWarping; } + void SetIsWarping(bool warping) { m_isWarping = warping; } -static bool PortSwitchScroll(LPITEM scroll) { - return scroll && scroll->GetVnum()!=50348 && scroll->GetVnum()!=50349 && - scroll->GetType()==ITEM_USE && scroll->GetSubType()==USE_CHANGE_ATTRIBUTE && - !scroll->IsCostumeEnchant() && !scroll->GetPendantScrollKind(); -} + void Start(); + void Stop(); + void Pause(); -static void PortSwitchState(LPCHARACTER ch,const PortSwitchbot* bot,bool active,const char* reason) { - LPITEM item=bot?PortSwitchItem(ch,*bot):NULL; - ch->ChatPacket(CHAT_TYPE_COMMAND,"MTSB1 state %u %u %u %u %u %u %d %s",unsigned(active),item?unsigned(item->GetCell()):0u, - item?unsigned(item->GetVnum()):0u,bot?bot->rolls:0u,bot?bot->limit:0u,bot?unsigned(bot->scroll):0u, - bot?ch->CountSpecifyItem(bot->scroll):0,reason); -} + void SwitchItems(); + bool CheckItem(LPITEM pkItem, BYTE slot); -// One roll. Returns NULL to keep running, otherwise the stop reason. -static const char* PortSwitchStep(LPCHARACTER ch,PortSwitchbot& bot) { - if(PortSwitchBusy(ch))return "busy"; - LPITEM item=PortSwitchItem(ch,bot); - if(!item)return "item_gone"; - if(PortSwitchMatches(item,bot))return "matched"; - if(bot.rolls>=bot.limit)return "limit"; - LPITEM scroll=ch->FindSpecifyItem(bot.scroll); - if(!PortSwitchScroll(scroll))return "no_scroll"; - const int before=ch->CountSpecifyItem(bot.scroll); - ch->m_portQuietInfo=true;ch->m_portLastInfo.clear(); - ch->UseItem(TItemPos(INVENTORY,scroll->GetCell()),TItemPos(INVENTORY,item->GetCell())); - ch->m_portQuietInfo=false; - // Success is judged by the original path consuming exactly one scroll, not by its return value. - if(ch->CountSpecifyItem(bot.scroll)!=before-1) { - if(!ch->m_portLastInfo.empty())ch->ChatPacket(CHAT_TYPE_INFO,"%s",ch->m_portLastInfo.c_str()); - return "rejected"; - } - ++bot.rolls; - item=PortSwitchItem(ch,bot); - if(!item)return "item_gone"; - return PortSwitchMatches(item,bot)?"matched":bot.rolls>=bot.limit?"limit":NULL; -} + void SendItemUpdate(LPCHARACTER ch, BYTE slot, LPITEM item); -EVENTINFO(PortSwitchbotInfo){DWORD pid;PortSwitchbotInfo():pid(0){}}; +protected: + void FinishSlot(LPCHARACTER ch, BYTE slot, LPITEM item, bool finished); -EVENTFUNC(port_switchbot_event) { - PortSwitchbotInfo* info=dynamic_cast(event->info); - if(!info)return 0; - auto it=g_portSwitchbots.find(info->pid); - if(it==g_portSwitchbots.end())return 0; - PortSwitchbot& bot=it->second; - LPCHARACTER ch=CHARACTER_MANAGER::instance().Find(bot.vid); - // A new instance after logout or warp carries a new VID; the bot does not follow it. - if(!ch || ch->GetPlayerID()!=bot.pid || !ch->GetDesc()) {bot.event=NULL;g_portSwitchbots.erase(it);return 0;} - const char* reason=PortSwitchStep(ch,bot); - if(!reason) {PortSwitchState(ch,&bot,true,"running");return PASSES_PER_SEC(1)/4;} - PortSwitchState(ch,&bot,false,reason); - bot.event=NULL;g_portSwitchbots.erase(it); - return 0; -} + TSwitchbotTable m_table; + LPEVENT m_pkSwitchEvent; + bool m_isWarping; +}; -static void PortSwitchStop(LPCHARACTER ch,const char* reason) { - auto it=g_portSwitchbots.find(ch->GetPlayerID()); - if(it==g_portSwitchbots.end()) {PortSwitchState(ch,NULL,false,"idle");return;} - if(it->second.event)event_cancel(&it->second.event); - PortSwitchState(ch,&it->second,false,reason); - g_portSwitchbots.erase(it); -} +class CSwitchbotManager : public singleton +{ +public: + CSwitchbotManager() { Initialize(); } + virtual ~CSwitchbotManager(); -static void PortSwitchLockLine(LPCHARACTER ch,LPITEM item) { - const bool addon=item->GetProto() && item->GetProto()->sAddonType; - ch->ChatPacket(CHAT_TYPE_COMMAND,"MTSB1 lock %u %u %u",unsigned(item->GetCell()),unsigned(item->GetVnum()), - PortAttrLockEffective(PortAttrLockGet(item),PortAttrFilled(item),addon)); -} + void Initialize() { m_map_Switchbots.clear(); } + void RegisterItem(DWORD player_id, DWORD item_id, WORD wCell); + void UnregisterItem(DWORD player_id, WORD wCell); + void Start(DWORD player_id, BYTE slot, const std::vector& vec_alternatives); + void Stop(DWORD player_id, BYTE slot); -// lock CELL SLOT: toggle the lock on one normal slot; not while the bot rolls this item. -static const char* PortSwitchLock(LPCHARACTER ch,unsigned cell,unsigned slot) { - if(PortSwitchBusy(ch))return "busy"; - LPITEM item=cellGetItem(TItemPos(INVENTORY,cell)):NULL; - if(!item)return "item"; - if(item->IsEquipped() || item->IsExchanging())return "equipped"; - if(item->GetType()==ITEM_COSTUME || item->GetAttributeSetIndex()<0)return "no_attr"; - auto it=g_portSwitchbots.find(ch->GetPlayerID()); - if(it!=g_portSwitchbots.end() && it->second.item==item->GetID())return "running"; - const bool addon=item->GetProto() && item->GetProto()->sAddonType; - const unsigned old=PortAttrLockEffective(PortAttrLockGet(item),PortAttrFilled(item),addon); - const bool removing=slot<5 && (old>>slot&1); - if(const char* error=PortAttrLockUse(ch,item,slot,ch->FindSpecifyItem(removing?50349:50348)))return error; - PortSwitchLockLine(ch,item); - return NULL; -} + bool IsActive(DWORD player_id, BYTE slot); + bool IsWarping(DWORD player_id); + void SetIsWarping(DWORD player_id, bool warping); -static void PortSwitchAttrs(LPCHARACTER ch,unsigned cell) { - LPITEM item=cellGetItem(TItemPos(INVENTORY,cell)):NULL; - if(!item){ch->ChatPacket(CHAT_TYPE_COMMAND,"MTSB1 error attrs item");return;} - if(item->GetType()==ITEM_COSTUME || item->GetAttributeSetIndex()<0){ch->ChatPacket(CHAT_TYPE_COMMAND,"MTSB1 error attrs no_attr");return;} - auto allowed=PortSwitchAllowed(item); - ch->ChatPacket(CHAT_TYPE_COMMAND,"MTSB1 attrs %u %u %u",cell,unsigned(item->GetVnum()),unsigned(allowed.size())); - for(unsigned i=0;iChatPacket(CHAT_TYPE_COMMAND,"MTSB1 attr %u %u %d",i,allowed[i].first,allowed[i].second); - ch->ChatPacket(CHAT_TYPE_COMMAND,"MTSB1 attrs_end %u %u",cell,unsigned(allowed.size())); - PortSwitchLockLine(ch,item); -} + CSwitchbot* FindSwitchbot(DWORD player_id); -// start CELL SCROLL LIMIT N1 (APPLY VALUE)*N1 [N2 (APPLY VALUE)*N2] -static const char* PortSwitchStart(LPCHARACTER ch,const std::vector& args) { - unsigned cell=0,scrollVnum=0,limit=0; - if(args.size()<6 || !PortSwitchNumber(args[2],cell) || !PortSwitchNumber(args[3],scrollVnum) || - !PortSwitchNumber(args[4],limit) || !limit || limit>kPortSwitchLimit)return "invalid"; - if(g_portSwitchbots.count(ch->GetPlayerID()))return "running"; - if(PortSwitchBusy(ch))return "busy"; - LPITEM item=cellGetItem(TItemPos(INVENTORY,cell)):NULL; - if(!item)return "item"; - if(item->IsEquipped() || item->IsExchanging())return "equipped"; - if(item->GetType()==ITEM_COSTUME || item->GetAttributeSetIndex()<0 || !item->GetAttributeCount())return "no_attr"; - if(!PortSwitchScroll(ch->FindSpecifyItem(scrollVnum)))return "scroll"; - PortSwitchbot bot;bot.pid=ch->GetPlayerID();bot.vid=ch->GetVID();bot.item=item->GetID();bot.scroll=scrollVnum;bot.limit=limit; - const auto allowed=PortSwitchAllowed(item); - size_t at=5; - for(unsigned alt=0;altkPortSwitchTargets || at+count*2>args.size())return "invalid"; - for(unsigned i=0;iunsigned(max))return "target"; - for(const auto& t:bot.alternatives[alt])if(t.apply==apply)return "target"; - bot.alternatives[alt].push_back(PortSwitchTarget{apply,int(value)}); - } - } - if(at!=args.size())return "invalid"; - if(PortSwitchMatches(item,bot)) {PortSwitchState(ch,&bot,false,"matched");return NULL;} - PortSwitchbot& stored=g_portSwitchbots[bot.pid];stored=bot; - PortSwitchbotInfo* info=AllocEventInfo();info->pid=bot.pid; - stored.event=event_create(port_switchbot_event,info,PASSES_PER_SEC(1)/4); - PortSwitchState(ch,&stored,true,"running"); - return NULL; -} + void P2PSendSwitchbot(DWORD player_id, WORD wTargetPort); + void P2PReceiveSwitchbot(const TSwitchbotTable& table); + + void SendItemAttributeInformations(LPCHARACTER ch); + void SendSwitchbotUpdate(DWORD player_id); + + void EnterGame(LPCHARACTER ch); + +protected: + std::map m_map_Switchbots; +}; + +void PortSwitchbotBoot(); // adds 'SWITCHBOT' to player.item.window when it is missing -ACMD(do_port_switchbot) { - if(!ch || !ch->IsPC() || !ch->GetDesc())return; - std::istringstream input(argument);std::vector args;std::string token; - while(input>>token){if(token.size()>10 || args.size()>=30)return;args.push_back(token);} - if(args.size()<2 || args[0]!="1")return; - const std::string& verb=args[1]; - if(get_dword_time()-ch->m_portSwitchbotLastCommand<250 && ch->m_portSwitchbotLastCommand) { - ch->ChatPacket(CHAT_TYPE_COMMAND,"MTSB1 error %s rate",verb.c_str());return; - } - ch->m_portSwitchbotLastCommand=get_dword_time(); - unsigned cell=0,slot=0; - if(verb=="attrs" && args.size()==3 && PortSwitchNumber(args[2],cell)) PortSwitchAttrs(ch,cell); - else if(verb=="lock" && args.size()==4 && PortSwitchNumber(args[2],cell) && PortSwitchNumber(args[3],slot)) { - const char* error=PortSwitchLock(ch,cell,slot); - if(error)ch->ChatPacket(CHAT_TYPE_COMMAND,"MTSB1 error lock %s",error); - } - else if(verb=="stop" && args.size()==2) PortSwitchStop(ch,"stopped"); - else if(verb=="status" && args.size()==2) { - auto it=g_portSwitchbots.find(ch->GetPlayerID()); - if(it==g_portSwitchbots.end())PortSwitchState(ch,NULL,false,"idle"); - else PortSwitchState(ch,&it->second,true,"running"); - } - else if(verb=="start") { - const char* error=PortSwitchStart(ch,args); - if(error)ch->ChatPacket(CHAT_TYPE_COMMAND,"MTSB1 error start %s",error); - } - else ch->ChatPacket(CHAT_TYPE_COMMAND,"MTSB1 error %s invalid",verb.size()<=10?verb.c_str():"unknown"); -} #endif diff --git a/tests/features/test_attr_lock.py b/tests/features/test_attr_lock.py index fcdca61d..043003d9 100644 --- a/tests/features/test_attr_lock.py +++ b/tests/features/test_attr_lock.py @@ -12,7 +12,7 @@ body=re.search(r'void CItem::ChangeAttribute\(const int\* aiChangeProb\)\n\{.*?\ copy=re.search(r'void CItem::CopyAttributeTo\(LPITEM pItem\)\n\{.*?\n\}\n',attribute,re.S).group(0) assert 'PortAttrLockSet(GetOwner(), pItem, lock)' in copy # refine / replacement keeps the lock assert 'port_attr_lock.cpp' in text('Makefile') and '#include "port_attr_lock.h"' in attribute -assert 'if (!g_bAuthServer)\n\t\tPortAttrLockBoot();' in main.split('config_init(st_localeServiceName);',1)[1][:120] +assert 'if (!g_bAuthServer)\n\t{\n\t\tPortAttrLockBoot();' in main.split('config_init(st_localeServiceName);',1)[1][:120] assert 'CREATE TABLE IF NOT EXISTS mt_item_attr_lock' in glue and 'item->m_portAttrLockLoaded=true' in glue assert 'm_portAttrLockLoaded = false;' in text('item.cpp') code=r''' diff --git a/tests/features/test_bosses.py b/tests/features/test_bosses.py index 202a8914..c744e398 100644 --- a/tests/features/test_bosses.py +++ b/tests/features/test_bosses.py @@ -8,7 +8,7 @@ SRC=ROOT/'src/server/game/src' def text(name):return (SRC/name).read_bytes().decode('latin1') features=text('port_features.h');glue=text('port_boss_track.cpp');p2p=text('input_p2p.cpp');main=text('main.cpp') assert 'if(kind=="bosses" && args.size()==3) {PortBossQuery(ch,request);return;}' in features -assert '"MTF1 cap %u 1 1023 %lld"' in features +assert '"MTF1 cap %u 1 959 %lld"' in features assert 'port_boss_track.cpp' in text('Makefile') assert 'PortBossTick();' in main.split('if (!g_bAuthServer)',1)[1].split('}',1)[0] # 1 s block, game cores only # Relay hook runs after the size checks and before the player lookup; old cores just miss the name. diff --git a/tests/features/test_cmd_prefix.py b/tests/features/test_cmd_prefix.py index 965263fb..606f41cf 100644 --- a/tests/features/test_cmd_prefix.py +++ b/tests/features/test_cmd_prefix.py @@ -17,7 +17,7 @@ assert end,'table sentinel not found' entries=entries[1:end[0]] PORT=lambda name:name.startswith('mt_') port=[name for name,_ in entries if PORT(name)] -assert {'mt_features','mt_switchbot','mt_pickup','mt_chest'}<=set(port),port +assert {'mt_features','mt_pickup','mt_chest'}<=set(port),port def resolve(rows,cmd): for name,fn in rows: diff --git a/tests/features/test_costume_attr.py b/tests/features/test_costume_attr.py index 8693136f..e0912e07 100644 --- a/tests/features/test_costume_attr.py +++ b/tests/features/test_costume_attr.py @@ -1,6 +1,6 @@ #!/usr/bin/env python3 """AVA2 costume enchants (docs/FEATURE-AVA2-UNLOCK.md P6): 54001-54267 add one fixed attribute to a -body/hair/mount-skin costume, are routed before the 40250 switcher path and are no switchbot scroll.""" +body/hair/mount-skin costume, are routed before the 40250 switcher path and are never taken by the switchbot.""" from pathlib import Path ROOT=Path(__file__).resolve().parents[2] SRC=ROOT/'src/server/game/src' @@ -10,7 +10,7 @@ items=source('char_item.cpp') case=items[items.index('case USE_CHANGE_ATTRIBUTE2 :'):] hook=case.index('if (item->IsCostumeEnchant())\n\t\t\t\t\t\t\t\treturn CostumeEnchantUse(item, item2);') assert hookGetType()'),'hook must run before the costume refusal' -assert '!scroll->IsCostumeEnchant()' in source('port_switchbot.h') +assert 'IsCostumeEnchant' not in source('port_switchbot.cpp') and 's_adwNormal[] = { 71084, 39028 };' in source('port_switchbot.cpp') assert 'port_costume_attr.cpp' in source('Makefile') port=source('port_costume_attr.cpp') for text in ('COSTUME_ENCHANT_VNUM_MIN = 54001','COSTUME_ENCHANT_VNUM_MAX = 54267','COSTUME_ENCHANT_MAX_ATTR = 3', diff --git a/tests/features/test_pendant.py b/tests/features/test_pendant.py index 7b2ee2e9..2a962e55 100755 --- a/tests/features/test_pendant.py +++ b/tests/features/test_pendant.py @@ -1,6 +1,6 @@ #!/usr/bin/env python3 """AVA2 talisman (docs/FEATURE-AVA2-UNLOCK.md P7): ARMOR_PENDANT worn in WEAR_PENDANT, element enchant applies, -its own attribute pool changed only by 71301/71302/53996/53997, which are no switchbot scrolls.""" +its own attribute pool changed only by 71301/71302/53996/53997; the switchbot rolls talismans with 71302 only.""" from pathlib import Path ROOT=Path(__file__).resolve().parents[2] SRC=ROOT/'src/server' @@ -17,7 +17,8 @@ assert fec.index('if (IsTalisman())\n\t\treturn WEAR_PENDANT;')GetPendantScrollKind() || item2->IsTalisman())\n\t\t\t\t\t\t\t\treturn PendantScrollUse(item, item2);')GetPendantScrollKind()' in source('game/src/port_switchbot.h') +sb=source('game/src/port_switchbot.cpp') +assert 'if (pkItem->IsTalisman())\n\t\t\treturn FindUsableSwitcher(ch, 71302);' in sb and 'GetPendantAttrMaxValue(' in sb assert 'port_pendant.cpp' in source('game/src/Makefile') port=source('game/src/port_pendant.cpp') pool=port[port.index('s_aPendantAttr[] ='):];pool=pool[:pool.index('};')] @@ -33,4 +34,4 @@ script=ROOT.parent/'metin2-client/src/platform/ScriptLib/PendantScript.inc' if script.is_file(): s=script.read_text() for code in codes:assert "'%s':"%code in s,code -print('PASS: talisman slot/equip, enchant switch routing before the switcher path, 20-row pool, max 5, switchbot excluded, MTPENDANT codes') +print('PASS: talisman slot/equip, enchant switch routing before the switcher path, 20-row pool, max 5, switchbot 71302 only, MTPENDANT codes') diff --git a/tests/features/test_queries.py b/tests/features/test_queries.py index bf0cabb0..2b904557 100644 --- a/tests/features/test_queries.py +++ b/tests/features/test_queries.py @@ -117,7 +117,7 @@ int main(){ assert(rewards[0].total==100 && rewards[0].rule==WIKI_SINGLE); rewards=items.PortWikiChest(50012);assert(rewards[1].rule==WIKI_INDEPENDENT && rewards[1].weight==150 && rewards[1].total==100); assert(items.PortWikiChest(50013).empty() && items.PortWikiChest(19).empty()); - Character ch;query(ch,"1 99 travel 2493 0");assert(travelBoss==2493);query(ch,"1 1 cap");assert(ch.messages.back()=="MTF1 cap 1 1 1023 1700000000"); + Character ch;query(ch,"1 99 travel 2493 0");assert(travelBoss==2493);query(ch,"1 1 cap");assert(ch.messages.back()=="MTF1 cap 1 1 959 1700000000"); ch.messages.clear();query(ch,"1 2 mob 101 0");assert(ch.messages.size()==10 && ch.messages.back()=="MTF1 end 2 8"); query(ch,"1 3 mob 101 999");assert(ch.messages.back()=="MTF1 error 3 offset"); query(ch,"1 4 mob 9001 0");assert(ch.messages.back()=="MTF1 error 4 missing"); diff --git a/tests/features/test_switchbot.py b/tests/features/test_switchbot.py index 2ea57bb1..d578f6ae 100644 --- a/tests/features/test_switchbot.py +++ b/tests/features/test_switchbot.py @@ -1,218 +1,111 @@ #!/usr/bin/env python3 -"""Compile the production switchbot header against stubs of the original UseItem/ChatPacket contract.""" +"""AVA2 switchbot (docs/FEATURE-SWITCHBOT.md): the SWITCHBOT window (7), AVA2's headers 171 / GG 31 with the +same subheaders and field order, wire sizes pinned by static_assert and mirrored by the client, the window +hooks, the P2P hand-over, the boot ALTER and the switcher choice. The old /mt_switchbot command is gone.""" from pathlib import Path -import subprocess -import tempfile +import re ROOT=Path(__file__).resolve().parents[2] -SRC=ROOT/'src/server/game/src' -# The quiet-INFO branch must stay in the real ChatPacket; the stub below mirrors it. -assert 'if (m_portQuietInfo && type == CHAT_TYPE_INFO)' in (SRC/'char.cpp').read_bytes().decode('latin1') -assert '"mt_switchbot", do_port_switchbot' in (SRC/'cmd.cpp').read_bytes().decode('latin1') -lock_use=(SRC/'port_attr_lock.cpp').read_text().split('const char* PortAttrLockUse(',1)[1] -code=r''' -#include -#include -#include -#include -#include -#include -#include -#include -#include -using DWORD=unsigned;using BYTE=unsigned char; -enum {MAX_APPLY_NUM=100,ITEM_APPLY_MAX_NUM=3,ATTRIBUTE_SET_MAX_NUM=11,INVENTORY_MAX_NUM=225,INVENTORY=1,EQUIPMENT=2}; -enum {ITEM_USE=3,ITEM_COSTUME=28,USE_CHANGE_ATTRIBUTE=10,USE_ADD_ATTRIBUTE=11,APPLY_MAX_HP=1,APPLY_STR=3,APPLY_CRITICAL=15, - APPLY_ATTBONUS_MONSTER=63,APPLY_NORMAL_HIT_DAMAGE_BONUS=72,APPLY_SKILL_DAMAGE_BONUS=71}; -enum {CHAT_TYPE_INFO=1,CHAT_TYPE_COMMAND=5}; -struct TItemAttrTable{long lValues[5];BYTE bMaxLevelBySet[ATTRIBUTE_SET_MAX_NUM];}; -std::map g_map_itemAttr; -struct TItemApply{BYTE bType;long lValue;}; -struct TItemTable{TItemApply aApplies[ITEM_APPLY_MAX_NUM];short sAddonType=0;}; -struct TPlayerItemAttribute{BYTE bType=0;short sValue=0;}; -struct TItemPos{BYTE window_type;unsigned cell;TItemPos(BYTE w,unsigned c):window_type(w),cell(c){}}; -struct VID{DWORD id=0;bool operator==(const VID& o)const{return id==o.id;}}; -struct event_info_data{virtual ~event_info_data(){}}; -struct EVENT{event_info_data* info;long (*func)(EVENT*,long);bool cancelled=false;}; -using LPEVENT=EVENT*; -std::vector> events; -template T* AllocEventInfo(){return new T;} -LPEVENT event_create(long (*f)(LPEVENT,long),event_info_data* info,long){events.emplace_back(new EVENT{info,f});return events.back().get();} -void event_cancel(LPEVENT* e){if(*e)(*e)->cancelled=true;*e=nullptr;} -#define EVENTFUNC(name) long (name) (LPEVENT event, long processing_time) -#define EVENTINFO(name) struct name : public event_info_data -#define PASSES_PER_SEC(s) ((s)*4) -static DWORD clockms=1000;DWORD get_dword_time(){return clockms;} -class CHARACTER; -class CItem {public: - DWORD id,vnum;BYTE type,subtype;int set=0;unsigned cell;BYTE window=INVENTORY;bool equipped=false,exchanging=false;int count=1; - CHARACTER* owner=nullptr;TItemTable proto{};TPlayerItemAttribute attrs[7]; - long value2=0;bool IsCostumeEnchant(){return vnum>=54001 && vnum<=54267 && value2;}int GetPendantScrollKind(){return vnum==71302||vnum==53996;} - DWORD GetID(){return id;}DWORD GetVnum(){return vnum;}BYTE GetType(){return type;}BYTE GetSubType(){return subtype;} - int GetAttributeSetIndex(){return set;}const TItemTable* GetProto(){return &proto;} - const TPlayerItemAttribute& GetAttribute(int i){return attrs[i];}BYTE GetAttributeType(int i){return attrs[i].bType;} - int GetAttributeCount(){int n=0;for(int i=0;i<5;++i)n+=attrs[i].bType!=0;return n;} - CHARACTER* GetOwner(){return owner;}BYTE GetWindow(){return window;}unsigned GetCell(){return cell;} - bool isLocked(){return false;}int GetCount(){return count;}void SetCount(int n){count=n;} - bool IsEquipped(){return equipped;}bool IsExchanging(){return exchanging;} -}; -using LPITEM=CItem*; -struct ITEM_MANAGER{ - static const int MAX_NORM_ATTR_NUM=5;std::vector items; - static ITEM_MANAGER& instance(){static ITEM_MANAGER m;return m;} - LPITEM Find(DWORD id){for(auto* i:items)if(i->id==id)return i;return nullptr;} -}; -class CHARACTER {public: - DWORD m_portSwitchbotLastCommand=0;bool m_portQuietInfo=false;std::string m_portLastInfo; - DWORD pid=7;VID vid;bool desc=true,busy=false,dead=false,reject=false;int uses=0; - std::vector messages,info;std::vector inventory; - std::deque>> rolls; - bool IsPC(){return true;}void* GetDesc(){return desc?this:nullptr;}DWORD GetPlayerID(){return pid;}const VID& GetVID(){return vid;} - bool IsDead(){return dead;}bool IsWarping(){return false;}bool CanHandleItem(){return !busy;} - void* GetExchange(){return nullptr;}void* GetMyShop(){return nullptr;}void* GetShopOwner(){return nullptr;} - bool IsOpenSafebox(){return false;}bool IsCubeOpen(){return false;} - LPITEM GetItem(TItemPos p){for(auto* i:inventory)if(i->window==p.window_type&&i->cell==p.cell)return i;return nullptr;} - LPITEM FindSpecifyItem(DWORD v){for(auto* i:inventory)if(i->vnum==v&&i->count>0)return i;return nullptr;} - int CountSpecifyItem(DWORD v){int n=0;for(auto* i:inventory)if(i->vnum==v)n+=i->count;return n;} - void ChatPacket(BYTE type,const char* format,...) { - char out[513];va_list args;va_start(args,format);vsnprintf(out,sizeof(out),format,args);va_end(args); - if(m_portQuietInfo && type==CHAT_TYPE_INFO){m_portLastInfo=out;return;} - (type==CHAT_TYPE_INFO?info:messages).emplace_back(out); - } - // Original contract: INFO line on every call, one scroll consumed per successful change. - bool UseItem(TItemPos scroll,TItemPos target) { - ++uses;LPITEM s=GetItem(scroll),t=GetItem(target);assert(s && t && s->subtype==USE_CHANGE_ATTRIBUTE); - if(reject){ChatPacket(CHAT_TYPE_INFO,"cannot change");return false;} - auto roll=rolls.front();rolls.pop_front(); - for(int i=0;i<5;++i)t->attrs[i]=TPlayerItemAttribute{}; - for(size_t i=0;iattrs[i].bType=roll[i].first;t->attrs[i].sValue=roll[i].second;} - --s->count;ChatPacket(CHAT_TYPE_INFO,"changed");return true; - } -}; -using LPCHARACTER=CHARACTER*; -struct CHARACTER_MANAGER{ - std::vector chars;static CHARACTER_MANAGER& instance(){static CHARACTER_MANAGER m;return m;} - LPCHARACTER Find(const VID& v){for(auto* c:chars)if(c->vid==v)return c;return nullptr;} -}; -#define ACMD(name) void name(LPCHARACTER ch,const char* argument) -#include "port_switchbot.h" -// Lock storage stub: the real one is a player.mt_item_attr_lock row (port_attr_lock.cpp). -static std::map locks;static bool lockFail=false; -unsigned PortAttrLockGet(CItem* item){return locks[item->id];} -bool PortAttrLockSet(CHARACTER*,CItem* item,unsigned mask){if(lockFail)return false;locks[item->id]=mask;return true;} -const char* PortAttrLockUse(@LOCK_USE@ -static CHARACTER ch; -static void cmd(const char* text){clockms+=300;ch.messages.clear();do_port_switchbot(&ch,text);} -static long tick(){for(auto& e:events)if(!e->cancelled&&e->func){long r=e->func(e.get(),0);if(!r)e->func=nullptr;return r;}return -1;} -static const std::string& last(){return ch.messages.back();} -int main(){ - g_map_itemAttr[APPLY_MAX_HP]={{500,1000,1500,2000,2500},{5,5}}; - g_map_itemAttr[APPLY_STR]={{2,4,6,8,12},{5,0}}; // body only (set 0) - g_map_itemAttr[APPLY_CRITICAL]={{1,2,3,5,10},{0,5}}; // not on set 0 - g_map_itemAttr[APPLY_ATTBONUS_MONSTER]={{2,4,6,8,10},{3,5}}; // level-capped at 3 on set 0 - ch.vid.id=99;CHARACTER_MANAGER::instance().chars.push_back(&ch); - CItem armor{1001,11209,2,0,0,10};armor.owner=&ch;armor.proto.aApplies[0]={APPLY_MAX_HP,100};armor.attrs[0]={APPLY_STR,2};armor.attrs[1]={APPLY_CRITICAL,1}; - CItem scroll{2001,71084,ITEM_USE,USE_CHANGE_ATTRIBUTE,-1,20};scroll.owner=&ch;scroll.count=3; - CItem adder{2002,71085,ITEM_USE,USE_ADD_ATTRIBUTE,-1,21};adder.owner=&ch; - CItem plain{1002,50001,ITEM_USE,0,-1,30};plain.owner=&ch; - for(auto* i:{&armor,&scroll,&adder,&plain}){ch.inventory.push_back(i);ITEM_MANAGER::instance().items.push_back(i);} +SRC=ROOT/'src/server' +CLIENT=ROOT.parent/'metin2-client/src/port/UserInterface' +def source(name):return (SRC/name).read_bytes().decode('latin1') +def enum_after(text,start,end): + body=text[text.index(start):];body=body[:body.index(end)] + return re.findall(r'^\s*([A-Z_0-9]+)\s*[,=]',body,re.M) +def struct(text,name): + body=text[text.index('struct %s\n'%name):];body=body[:body.index('};')] + return re.findall(r'^\s*([A-Za-z_][A-Za-z_0-9]*)\s+(\w+)(\[[^;]*\])?;',body,re.M) - // Allowed list: proto applies excluded, set filter, level cap picks lValues[level-1]. - cmd("1 attrs 10"); - assert(ch.messages.size()==5 && ch.messages[0]=="MTSB1 attrs 10 11209 2"); - assert(ch.messages[1]=="MTSB1 attr 0 3 12" && ch.messages[2]=="MTSB1 attr 1 63 6" && ch.messages[3]=="MTSB1 attrs_end 10 2"); - assert(last()=="MTSB1 lock 10 11209 0"); - armor.proto.sAddonType=1;cmd("1 attrs 10");assert(ch.messages[3]=="MTSB1 attr 2 71 30" && ch.messages[4]=="MTSB1 attr 3 72 65");armor.proto.sAddonType=0; - cmd("1 attrs 30");assert(last()=="MTSB1 error attrs no_attr"); - cmd("1 attrs 99");assert(last()=="MTSB1 error attrs item"); - do_port_switchbot(&ch,"1 attrs 10");assert(last()=="MTSB1 error attrs rate"); +length=source('common/length.h') +windows=enum_after(length,'enum EWindows','};') +assert windows.index('SWITCHBOT')==7 and windows[6]=='BELT_INVENTORY',windows +for k,v in (('SWITCHBOT_SLOT_COUNT',6),('SWITCHBOT_SLOT_COUNT_REAL',5),('SWITCHBOT_ALTERNATIVE_COUNT',2),('SWITCHBOT_NORM_ATTR_NUM',5)): + assert re.search(r'\b%s = %d,'%(k,v),length),k +assert 'bool IsSwitchbotPosition() const' in length - // Validation. - for(auto bad:{"1 start 10 71084 0 1 3 1","1 start 10 71084 1001 1 3 1","1 start 10 71084 5 1 3","1 start 10 71084 5 1 3 0", - "1 start 10 71084 5 6 3 1 3 1 3 1 3 1 3 1 3 1","1 start 10 71084 5 1 3 1 1","1 start 10 71084 5 1 3 -1","1 start 10 71084 5 0"}) - {cmd(bad);assert(last()=="MTSB1 error start invalid");} - cmd("1 start 10 71084 5 1 1 100");assert(last()=="MTSB1 error start target"); // base proto apply - cmd("1 start 10 71084 5 1 3 13");assert(last()=="MTSB1 error start target"); // above max - cmd("1 start 10 71084 5 2 3 1 3 2");assert(last()=="MTSB1 error start target"); // duplicate - cmd("1 start 10 71085 5 1 3 4");assert(last()=="MTSB1 error start scroll"); - cmd("1 start 10 50001 5 1 3 4");assert(last()=="MTSB1 error start scroll"); - // AVA2 costume enchants share USE_CHANGE_ATTRIBUTE but are no switchers (port_costume_attr.cpp). - CItem enchant{2004,54001,ITEM_USE,USE_CHANGE_ATTRIBUTE,-1,23};enchant.owner=&ch;enchant.value2=2;ch.inventory.push_back(&enchant); - cmd("1 start 10 54001 5 1 3 4");assert(last()=="MTSB1 error start scroll"); - cmd("1 start 30 71084 5 1 3 4");assert(last()=="MTSB1 error start no_attr"); - armor.equipped=true;cmd("1 start 10 71084 5 1 3 4");assert(last()=="MTSB1 error start equipped");armor.equipped=false; - cmd("1 start 10 71084 5 1 3 2");assert(last()=="MTSB1 state 0 10 11209 0 5 71084 3 matched" && events.empty()); // already satisfied - assert(ch.uses==0); +packet=source('game/src/packet.h') +for name,v in (('HEADER_CG_SWITCHBOT',171),('HEADER_GC_SWITCHBOT',171),('HEADER_GG_SWITCHBOT',31)): + assert re.search(r'\b%s\s*= %d,'%(name,v),packet),name +cg=enum_after(packet,'enum ECGSwitchbotSubheader','};');gc=enum_after(packet,'enum EGCSwitchbotSubheader','};') +assert cg==['SUBHEADER_CG_SWITCHBOT_START','SUBHEADER_CG_SWITCHBOT_STOP'],cg +assert gc==['SUBHEADER_GC_SWITCHBOT_UPDATE','SUBHEADER_GC_SWITCHBOT_UPDATE_ITEM','SUBHEADER_GC_SWITCHBOT_SEND_ATTRIBUTE_INFORMATION'],gc +head=[('BYTE','header'),('int','size'),('BYTE','subheader'),('BYTE','slot')] +for name in ('TPacketCGSwitchbot','TPacketGCSwitchbot'): + assert [(t,n) for t,n,_ in struct(packet,name)]==head,name +upd=struct(packet,'TSwitchbotUpdateItem') +assert upd==[('BYTE','slot',''),('DWORD','vnum',''),('WORD','count',''),('long','alSockets','[ITEM_SOCKET_MAX_NUM]'), + ('TPlayerItemAttribute','aAttr','[ITEM_ATTRIBUTE_MAX_NUM]')],upd +tables=source('common/tables.h') +assert tables.index('#pragma pack(1)')GetID(), wCell);', + 'CSwitchbotManager::Instance().UnregisterItem(GetPlayerID(), wCell);','pItem->SetWindow(SWITCHBOT);', + 'if (wCell >= SWITCHBOT_SLOT_COUNT_REAL)\n\t\t\t\treturn false;','"switchbot_error active"','"switchbot_error invalid"', + 'if (!other.IsSwitchbotPosition() && !other.IsDefaultInventoryPosition())'): + assert text in items,text +assert items.count('if (Cell.IsSwitchbotPosition())\t// PORT: switchbot items go back to the inventory first')==2 # drop + give +char_h=source('game/src/char.h') +assert re.search(r'LPITEM\s+pSwitchbotItems\[SWITCHBOT_SLOT_COUNT\];',char_h) and 'm_portSwitchbotLastCommand' not in char_h +assert 'if (m_bWindow == SWITCHBOT)' in source('game/src/item.cpp') +assert 'if (item_pos.IsSwitchbotPosition())' in source('game/src/exchange.cpp') +inputs=source('game/src/input_main.cpp') +assert inputs.count('p->ItemPos.IsSwitchbotPosition()')==2 # safebox checkin + checkout +assert 'case HEADER_CG_SWITCHBOT:\n\t\t\tif ((iExtraLen = Switchbot(ch, c_pData, m_iBufferLeft)) < 0)' in inputs +info=source('game/src/packet_info.cpp') +assert 'Set(HEADER_CG_SWITCHBOT, sizeof(TPacketCGSwitchbot), "Switchbot", true);' in info +assert re.search(r'Set\(HEADER_GG_SWITCHBOT,\s*sizeof\(TPacketGGSwitchbot\),\s*"Switchbot",\s*false\);',info) +assert 'case HEADER_GG_SWITCHBOT:' in source('game/src/input_p2p.cpp') +char=source('game/src/char.cpp') +warp=char[char.index('CSwitchbotManager::Instance().SetIsWarping(GetPlayerID(), true);'):] +assert warp.index('P2PSendSwitchbot(GetPlayerID(), p.wPort)')Packet(&p, sizeof(TPacketGCWarp))') +assert 'CSwitchbotManager::Instance().EnterGame(ch);' in source('game/src/input_login.cpp') +# version gate: only "mt" clients from PORT_SWITCHBOT_CLIENT_VERSION on get GC_SWITCHBOT at EnterGame +assert 'enum { PORT_SWITCHBOT_CLIENT_VERSION = 20261016 };' in source('game/src/port_switchbot.h') +enter=port[port.index('void CSwitchbotManager::EnterGame'):];enter=enter[:enter.index('\n}\n')] +assert enter.index('if (!SwitchbotHelper::IsClientSupported(ch))\n\t\treturn;')= PORT_SWITCHBOT_CLIENT_VERSION" in port +assert 'case SWITCHBOT:' in source('game/src/input_db.cpp') +main=source('game/src/main.cpp') +assert 'CSwitchbotManager switchbotManager;' in main and 'PortSwitchbotBoot();' in main +assert source('db/src/ClientManagerPlayer.cpp').count('SAFEBOX, DRAGON_SOUL_INVENTORY, SWITCHBOT')==3 +assert 'port_switchbot.cpp' in source('game/src/Makefile') +assert '"mt_switchbot"' not in source('game/src/cmd.cpp') and 'port_switchbot.h' not in source('game/src/cmd_general.cpp') - // Item moved to equipment, busy character, manual stop, logout/warp (VID change) erases silently. - ch.rolls={{{APPLY_STR,2}}};cmd("1 start 10 71084 5 1 3 12");armor.window=EQUIPMENT;tick(); - assert(last()=="MTSB1 state 0 0 0 0 5 71084 2 item_gone");armor.window=INVENTORY; - cmd("1 start 10 71084 5 1 3 12");ch.busy=true;tick();assert(last()=="MTSB1 state 0 10 11209 0 5 71084 2 busy");ch.busy=false; - cmd("1 start 10 71084 5 1 3 12");cmd("1 stop");assert(last()=="MTSB1 state 0 10 11209 0 5 71084 2 stopped" && tick()==-1); - cmd("1 stop");assert(last()=="MTSB1 state 0 0 0 0 0 0 0 idle"); - cmd("1 start 10 71084 5 1 3 12");cmd("1 status");assert(last()=="MTSB1 state 1 10 11209 0 5 71084 2 running"); - ch.vid.id=100;ch.messages.clear();assert(tick()==0 && ch.messages.empty() && g_portSwitchbots.empty()); - assert(ch.uses==6); - - // AVA2 lock costs: no material, partial attributes, persistence failure never consume. - CItem lockMaterial{2100,50348,ITEM_USE,USE_CHANGE_ATTRIBUTE,-1,40};lockMaterial.owner=&ch;lockMaterial.count=20; - CItem unlockMaterial{2101,50349,ITEM_USE,USE_CHANGE_ATTRIBUTE,-1,41};unlockMaterial.owner=&ch;unlockMaterial.count=20; - cmd("1 lock 10 0");assert(last()=="MTSB1 error lock material"); - ch.inventory.push_back(&lockMaterial);ch.inventory.push_back(&unlockMaterial); - cmd("1 lock 10 0");assert(last()=="MTSB1 error lock five_attr" && lockMaterial.count==20); - armor.attrs[3]={APPLY_MAX_HP,500};armor.attrs[4]={APPLY_STR,1}; - // Lock toggle: five slots filled, max two groups, not on the rolling item. - armor.attrs[0]={APPLY_STR,2};armor.attrs[1]={APPLY_CRITICAL,1};armor.attrs[2]={APPLY_ATTBONUS_MONSTER,2}; - cmd("1 lock 10 0");assert(last()=="MTSB1 lock 10 11209 1"); - cmd("1 lock 10 2");assert(last()=="MTSB1 lock 10 11209 5"); - cmd("1 lock 10 1");assert(last()=="MTSB1 error lock max"); - cmd("1 lock 10 3");assert(last()=="MTSB1 error lock max"); - cmd("1 lock 10 5");assert(last()=="MTSB1 error lock slot"); - cmd("1 lock 10 0");assert(last()=="MTSB1 lock 10 11209 4" && locks[1001]==4); - cmd("1 lock 10 1");assert(last()=="MTSB1 lock 10 11209 6"); - cmd("1 attrs 10");assert(last()=="MTSB1 lock 10 11209 6"); - cmd("1 lock 30 0");assert(last()=="MTSB1 error lock no_attr"); - cmd("1 lock 99 0");assert(last()=="MTSB1 error lock item"); - cmd("1 lock 10");assert(last()=="MTSB1 error lock invalid"); - assert(lockMaterial.count==17 && unlockMaterial.count==19); - lockFail=true;cmd("1 lock 10 1");assert(last()=="MTSB1 error lock db" && locks[1001]==6);lockFail=false;assert(unlockMaterial.count==19); - ch.rolls={{{APPLY_STR,2}}};cmd("1 start 10 71084 5 1 3 12");cmd("1 lock 10 1");assert(last()=="MTSB1 error lock running"); - cmd("1 stop"); - // Addon weapon: slots 0 and 1 lock together and count as one group. - armor.proto.sAddonType=1;locks[1001]=0;armor.attrs[3]={APPLY_MAX_HP,500}; - cmd("1 lock 10 1");assert(last()=="MTSB1 lock 10 11209 3"); - cmd("1 lock 10 3");assert(last()=="MTSB1 lock 10 11209 11"); - cmd("1 lock 10 2");assert(last()=="MTSB1 error lock max"); - cmd("1 lock 10 0");assert(last()=="MTSB1 lock 10 11209 8"); - armor.proto.sAddonType=0;armor.attrs[2]=armor.attrs[3]=TPlayerItemAttribute{};locks.clear(); - - // Malformed or foreign input is ignored or rejected without side effects. - cmd("2 status");assert(ch.messages.empty()); - cmd("1 explode");assert(last()=="MTSB1 error explode invalid"); - cmd("1 start 99999999999 71084 5 1 3 12");assert(ch.messages.empty()); // overlong token - puts("PASS: allowed targets, validation, alternatives, original UseItem path, quiet INFO, stop reasons, VID drop"); -} -'''.replace('@LOCK_USE@',lock_use) -with tempfile.TemporaryDirectory(prefix='mt-switchbot-') as folder: - path=Path(folder);(path/'test.cpp').write_text(code) - subprocess.run(['c++','-std=c++17','-Wall','-I'+str(SRC),str(path/'test.cpp'),'-o',str(path/'test')],check=True) - subprocess.run([str(path/'test')],check=True) +# the client mirrors headers, subheaders, structs and sizes (packets in Packet.h, the table in PythonSwitchbot.h) +cpacket=CLIENT/'Packet.h' +if cpacket.is_file(): + client=cpacket.read_bytes().decode('latin1') + for name in ('HEADER_CG_SWITCHBOT','HEADER_GC_SWITCHBOT'): + assert re.search(r'\b%s\s*= 171,'%name,client),name + assert enum_after(client,'enum ECGSwitchbotSubheader','};')==cg + assert enum_after(client,'enum EGCSwitchbotSubheader','};')==gc + assert [n for _,n,_ in struct(client,'TSwitchbotUpdateItem')]==[n for _,n,_ in upd] + assert 'static_assert(sizeof(TSwitchbotUpdateItem) == 40,' in client + assert 'static_assert(sizeof(TPacketCGSwitchbot) == 7 && sizeof(TPacketGCSwitchbot) == 7,' in client + stream=(CLIENT/'PythonNetworkStreamPhaseGame.cpp').read_bytes().decode('latin1') + assert 'strncpy(kVersionPacket.timestamp, "mt20261016", sizeof(kVersionPacket.timestamp)-1);' in stream + pyswitch=(CLIENT/'PythonSwitchbot.h').read_bytes().decode('latin1') + ctable=pyswitch[pyswitch.index('struct TSwitchbotTable'):];ctable=ctable[:ctable.index('};')] + assert re.findall(r'^\s*[A-Za-z_][\w:]*\s+(\w+)(?:\[[^;]*\])?;',ctable,re.M)==table,ctable + for name in ('TSwitchbotTable','TSwitchbotAttributeAlternativeTable','TSwitchbottAttributeTable'): + assert 'static_assert(sizeof(CPythonSwitchbot::%s) == %d,'%(name,sizes[name]) in pyswitch,name +print('PASS: SWITCHBOT window 7, version gate mt20261016, CG/GC 171 + GG 31, AVA2 subheaders/fields, sizes 220/15/9/40/7/223, window hooks, P2P, boot ALTER, switchers 71302/71151/76023/71084/39028')